mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Cloud starter-inference OpenCode runs in remote Daytona sandboxes reuse warm OpenCode sessions across consecutive chat turns. > - Inside the warm sandbox, `startOpenCodeProviderProxy` stays alive bound to the first run's `PAPERCLIP_OPENROUTER_PROXY_TOKEN`. > - Because `cloud-trial-proxy.ts` generated a random per-run token and deleted it in `cleanup()`, every reused-session turn failed on attempt #1 with HTTP 401 (`Trial proxy token is no longer active on this server instance`) and posted `"The OpenCode run failed before it completed."` into the chat before auto-retry recovered. > - This pull request replaces single-run random tokens with deterministic HMAC-SHA256 signed per-`(companyId, agentId, allowedModel)` tokens (`pctrial_v1.<payload>.<sig>`) that remain valid across warm turns and stack restarts/sleep-wake, while still failing closed on tampering, `work_requires_model`, `$1` exhaustion, disallowed models, and provider migration. > - The benefit is zero spurious 401 failure messages on consecutive chat turns in warm starter-inference sessions. ## Linked Issues or Issue Description Refs #23401, #23559, #23571 **Summary** Use stable HMAC-signed proxy tokens for Cloud starter-inference OpenCode sessions so reused warm sessions succeed on attempt #1. **Steps to Reproduce** 1. Start a Cloud starter-inference (`free_inference_1`) chat with an OpenCode agent in a warm Daytona sandbox. 2. Send a first message and wait for the reply. 3. Send a second message in the same chat (`sessionReused: true`). 4. Observe HTTP 401 (`Trial proxy token is no longer active on this server instance`) and `"The OpenCode run failed before it completed."` before auto-retry starts a fresh process. **Expected Behavior** Consecutive messages on a reused warm OpenCode session authenticate cleanly on attempt #1 with zero 401 failures, while tokens still fail closed on tampering, `work_requires_model`, `$1` exhaustion, disallowed models, or migration to a user provider. ## What Changed - `server/src/services/cloud-trial-proxy.ts`: Replaced single-run random `pctrial_` tokens with deterministic HMAC-SHA256 signed `pctrial_v1.<payload>.<sig>` tokens derived from the stack's stable secret (`PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY` / `PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` / `PAPERCLIP_AGENT_JWT_SECRET` / `BETTER_AUTH_SECRET`, with a per-process random fallback). Kept `cleanup()` probing OpenRouter usage without deleting the token on normal run exit, and added `revokeCompanyTokens(companyId)`. - `server/src/services/cloud-trial-inference.ts`: Called `proxy.revokeCompanyTokens(companyId)` upon `migrateTrialAgents` completion and exposed `revokeCompanyTokens`. - `server/src/__tests__/cloud-trial-inference.test.ts`: Added regression test verifying warm session token reuse after `cleanup()`, survival across a fresh controller restart, HTTP 401 on tampered tokens, and HTTP 401 after `revokeCompanyTokens`. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/cloud-trial-inference.test.ts src/__tests__/cloud-trial-proxy-middleware-order.test.ts` — passed (8/8 tests). - `pnpm --filter @paperclipai/server typecheck` — passed (0 errors). ## Risks - Low risk. Tokens are HMAC-SHA256 verified with `timingSafeEqual`, strictly scoped to `(companyId, agentId, allowedModel)`, never contain the raw OpenRouter key, and fail closed on `work_requires_model`, `$1` budget exhaustion, disallowed models, and company migration. ## Model Used - Google Gemini (Antigravity agentic runtime, thinking mode with tool use and local code execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge
722 lines
26 KiB
TypeScript
722 lines
26 KiB
TypeScript
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import { Readable } from "node:stream";
|
|
import { pipeline } from "node:stream/promises";
|
|
import type { ReadableStream as NodeReadableStream } from "node:stream/web";
|
|
import { and, eq, ne } from "drizzle-orm";
|
|
import { agents, type Db } from "@paperclipai/db";
|
|
import {
|
|
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
|
CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
|
isAgentUsingCloudTrialInference,
|
|
type AiConnectionMetadata,
|
|
} from "@paperclipai/shared";
|
|
import { OPENROUTER_ATTRIBUTION_HEADERS } from "@paperclipai/shared/openrouter-attribution";
|
|
import { unprocessable } from "../errors.js";
|
|
import {
|
|
CloudTrialExhaustedError,
|
|
CloudTrialWorkRequiresModelError,
|
|
readJsonRecord,
|
|
stripOpenRouterPrefix,
|
|
type CloudTrialKeyStore,
|
|
} from "./cloud-trial-key-store.js";
|
|
import {
|
|
isCompanyOnTrialOnlyInference,
|
|
resolveEffectiveOnboardingConfig,
|
|
resolveHeldTrialIssues,
|
|
} from "./cloud-trial-status.js";
|
|
|
|
const PROXY_REQUEST_TIMEOUT_MS = 180_000;
|
|
const MAX_PROXY_REQUEST_BYTES = 16 * 1024 * 1024;
|
|
const RUN_TOKEN_PREFIX = "pctrial_";
|
|
const SIGNED_TOKEN_PREFIX = "pctrial_v1.";
|
|
|
|
interface RunProxyTokenRecord {
|
|
token: string;
|
|
companyId: string;
|
|
agentId: string;
|
|
runId: string;
|
|
allowedModel: string;
|
|
}
|
|
|
|
export interface PreparedCloudTrialRuntime {
|
|
env: Record<string, string>;
|
|
secretValues: string[];
|
|
defaultModel: string;
|
|
cleanup: () => Promise<void>;
|
|
}
|
|
|
|
export interface PreparedCloudTrialFastResponse {
|
|
metadata: AiConnectionMetadata;
|
|
credential: string;
|
|
model: string;
|
|
fetch: typeof fetch;
|
|
cleanup: () => Promise<void>;
|
|
}
|
|
|
|
function looksLikeOpenRouterLimitExhausted(status: number, bodyText: string): boolean {
|
|
if (status === 402) return true;
|
|
if (status === 403 || status === 429) {
|
|
return /key\s+limit\s+exceeded|insufficient\s+credits|credit\s+limit|budget\s+exhausted|cloud_trial_exhausted/i.test(
|
|
bodyText,
|
|
);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function deriveProxyTokenSigningKey(env: CloudTrialKeyStore["env"]): Buffer {
|
|
const seed =
|
|
env.PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY?.trim() ||
|
|
env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN?.trim() ||
|
|
env.PAPERCLIP_AGENT_JWT_SECRET?.trim() ||
|
|
env.BETTER_AUTH_SECRET?.trim();
|
|
if (seed) {
|
|
return createHash("sha256")
|
|
.update("paperclip-cloud-trial-proxy-token-v1:")
|
|
.update(seed)
|
|
.digest();
|
|
}
|
|
return randomBytes(32);
|
|
}
|
|
|
|
/**
|
|
* OpenRouter reverse proxy for starter-trial runs.
|
|
*
|
|
* Issues a stable, HMAC-signed per-(companyId, agentId, allowedModel) proxy
|
|
* token so warm OpenCode sessions reused across consecutive turns (or across
|
|
* stack restarts / sleep-wake) keep authenticating through `/api/internal/cloud-inference/v1`
|
|
* without failing on a deleted single-run token. Tokens fail closed immediately
|
|
* on `work_requires_model`, `$1` budget exhaustion, wrong model, or migration.
|
|
*/
|
|
export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
|
|
const { env, fetchImpl } = keyStore;
|
|
const signingKey = deriveProxyTokenSigningKey(env);
|
|
const activeRunTokens = new Map<string, RunProxyTokenRecord>();
|
|
const revokedAgents = new Set<string>();
|
|
|
|
const agentRevocationKey = (companyId: string, agentId: string) => `${companyId}:${agentId}`;
|
|
|
|
keyStore.setOnExhausted(() => {
|
|
activeRunTokens.clear();
|
|
});
|
|
|
|
function signProxyToken(companyId: string, agentId: string, allowedModel: string): string {
|
|
const payloadB64 = Buffer.from(
|
|
JSON.stringify({ c: companyId, a: agentId, m: allowedModel }),
|
|
"utf8",
|
|
).toString("base64url");
|
|
const sigB64 = createHmac("sha256", signingKey).update(payloadB64).digest("base64url");
|
|
return `${SIGNED_TOKEN_PREFIX}${payloadB64}.${sigB64}`;
|
|
}
|
|
|
|
function verifySignedProxyToken(presented: string): RunProxyTokenRecord | null {
|
|
if (!presented.startsWith(SIGNED_TOKEN_PREFIX)) return null;
|
|
const rest = presented.slice(SIGNED_TOKEN_PREFIX.length);
|
|
const dotIndex = rest.indexOf(".");
|
|
if (dotIndex <= 0 || dotIndex === rest.length - 1 || rest.indexOf(".", dotIndex + 1) !== -1) {
|
|
return null;
|
|
}
|
|
const payloadB64 = rest.slice(0, dotIndex);
|
|
const sigB64 = rest.slice(dotIndex + 1);
|
|
const expectedSigB64 = createHmac("sha256", signingKey).update(payloadB64).digest("base64url");
|
|
const actualBuf = Buffer.from(sigB64, "utf8");
|
|
const expectedBuf = Buffer.from(expectedSigB64, "utf8");
|
|
if (actualBuf.length !== expectedBuf.length || !timingSafeEqual(actualBuf, expectedBuf)) {
|
|
return null;
|
|
}
|
|
try {
|
|
const parsed = readJsonRecord(JSON.parse(Buffer.from(payloadB64, "base64url").toString("utf8")));
|
|
const companyId = typeof parsed.c === "string" ? parsed.c.trim() : "";
|
|
const agentId = typeof parsed.a === "string" ? parsed.a.trim() : "";
|
|
const allowedModel = typeof parsed.m === "string" ? parsed.m.trim() : "";
|
|
if (!companyId || !agentId || !allowedModel) return null;
|
|
if (revokedAgents.has(agentRevocationKey(companyId, agentId))) return null;
|
|
return {
|
|
token: presented,
|
|
companyId,
|
|
agentId,
|
|
runId: activeRunTokens.get(presented)?.runId ?? "warm-session",
|
|
allowedModel,
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function findActiveRunToken(presented: string): RunProxyTokenRecord | null {
|
|
const presentedBuf = Buffer.from(presented, "utf8");
|
|
for (const [stored, record] of activeRunTokens) {
|
|
const storedBuf = Buffer.from(stored, "utf8");
|
|
if (storedBuf.length === presentedBuf.length && timingSafeEqual(storedBuf, presentedBuf)) {
|
|
return revokedAgents.has(agentRevocationKey(record.companyId, record.agentId)) ? null : record;
|
|
}
|
|
}
|
|
return verifySignedProxyToken(presented);
|
|
}
|
|
|
|
function revokeAgentTokens(companyId: string, agentIds: readonly string[]): void {
|
|
const targets = new Set(agentIds);
|
|
for (const agentId of targets) {
|
|
revokedAgents.add(agentRevocationKey(companyId, agentId));
|
|
}
|
|
for (const [stored, record] of activeRunTokens) {
|
|
if (record.companyId === companyId && targets.has(record.agentId)) {
|
|
activeRunTokens.delete(stored);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Prepares an isolated, proxy-backed runtime environment for a single run of a
|
|
* Cloud-trial agent. The raw `sk-or-v1-...` key NEVER leaves this server process,
|
|
* and the allowed model is strictly bound to the Cloud-approved starter model.
|
|
*/
|
|
async function prepareCloudTrialRuntime(
|
|
db: Db,
|
|
input: {
|
|
companyId: string;
|
|
agentId: string;
|
|
runId: string;
|
|
model?: string;
|
|
probeOnly?: boolean;
|
|
},
|
|
): Promise<PreparedCloudTrialRuntime> {
|
|
const effective = await resolveEffectiveOnboardingConfig(db, keyStore);
|
|
if (!effective.trialInferenceEnabled) {
|
|
throw unprocessable("Cloud starter inference is not enabled on this instance.", {
|
|
code: "cloud_trial_disabled",
|
|
});
|
|
}
|
|
|
|
const heldIssues =
|
|
keyStore.getGateReason(input.companyId) === "work_requires_model"
|
|
? keyStore.getHeldIssues(input.companyId)
|
|
: await resolveHeldTrialIssues(db, input.companyId, keyStore, true);
|
|
if (heldIssues.length > 0) {
|
|
throw new CloudTrialWorkRequiresModelError(undefined, {
|
|
companyId: input.companyId,
|
|
agentId: input.agentId,
|
|
runId: input.runId,
|
|
heldIssueIds: heldIssues.map((h) => h.id),
|
|
});
|
|
}
|
|
|
|
const state = await keyStore.fetchKeyFromCloudOrLocal(false);
|
|
if (state.status === "exhausted" || (state.status === "active" && state.remainingUsdCents <= 0)) {
|
|
await keyStore.markExhausted({
|
|
companyId: input.companyId,
|
|
agentId: input.agentId,
|
|
runId: input.runId,
|
|
spentUsdCents: state.spentUsdCents || state.limitUsdCents,
|
|
reason: "budget_exhausted",
|
|
});
|
|
throw new CloudTrialExhaustedError(undefined, {
|
|
companyId: input.companyId,
|
|
agentId: input.agentId,
|
|
runId: input.runId,
|
|
});
|
|
}
|
|
if (state.status !== "active" || !state.apiKey) {
|
|
throw unprocessable("You need to connect a model provider to continue.", {
|
|
code: state.status === "disabled" ? "cloud_trial_disabled" : CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
|
trialStatus: state.status,
|
|
reason: state.reason,
|
|
});
|
|
}
|
|
|
|
const allowedModel = stripOpenRouterPrefix(state.defaultModel);
|
|
if (input.model?.trim() && stripOpenRouterPrefix(input.model) !== allowedModel) {
|
|
throw unprocessable(
|
|
`Starter inference is limited to ${state.defaultModel}. Connect a model provider to use other models.`,
|
|
{
|
|
code: "cloud_trial_model_not_allowed",
|
|
allowedModel: state.defaultModel,
|
|
requestedModel: input.model.trim(),
|
|
},
|
|
);
|
|
}
|
|
|
|
const serverOrigin = (env.PAPERCLIP_API_URL?.trim() || "http://127.0.0.1:3100").replace(/\/+$/, "");
|
|
const proxyUrl = `${serverOrigin}/api/internal/cloud-inference/v1`;
|
|
const token = signProxyToken(input.companyId, input.agentId, allowedModel);
|
|
if (!input.probeOnly) {
|
|
revokedAgents.delete(agentRevocationKey(input.companyId, input.agentId));
|
|
keyStore.recordRunPrepared();
|
|
activeRunTokens.set(token, {
|
|
token,
|
|
companyId: input.companyId,
|
|
agentId: input.agentId,
|
|
runId: input.runId,
|
|
allowedModel,
|
|
});
|
|
}
|
|
|
|
return {
|
|
env: {
|
|
OPENROUTER_API_KEY: "",
|
|
PAPERCLIP_OPENROUTER_PROXY_URL: proxyUrl,
|
|
PAPERCLIP_OPENROUTER_PROXY_TOKEN: token,
|
|
},
|
|
secretValues: [token, state.apiKey],
|
|
defaultModel: state.defaultModel,
|
|
cleanup: async () => {
|
|
// Keep the signed token valid for warm OpenCode session reuse across
|
|
// consecutive turns; revocation happens on exhaustion, work gate, or migration.
|
|
await keyStore.probeOpenRouterUsage(input.companyId, true);
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Transparent OpenRouter reverse proxy for trial runs.
|
|
* Authenticates strictly via the active per-run token and injects the
|
|
* server-held OpenRouter key upstream. Never exposes the raw key to the caller.
|
|
*/
|
|
async function proxyOpenRouterRequest(
|
|
req: IncomingMessage & { originalUrl?: string; url?: string; body?: unknown },
|
|
res: ServerResponse,
|
|
subpath: string,
|
|
db?: Db,
|
|
): Promise<void> {
|
|
const authHeader = typeof req.headers.authorization === "string" ? req.headers.authorization : "";
|
|
const bearer = authHeader.startsWith("Bearer ") ? authHeader.slice("Bearer ".length).trim() : "";
|
|
const tokenRecord = bearer ? findActiveRunToken(bearer) : null;
|
|
if (!tokenRecord) {
|
|
const code = bearer.startsWith(RUN_TOKEN_PREFIX)
|
|
? "proxy_token_not_found_on_instance"
|
|
: "unauthorized";
|
|
res.statusCode = 401;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code,
|
|
message:
|
|
code === "proxy_token_not_found_on_instance"
|
|
? "Trial proxy token is no longer active on this server instance"
|
|
: "Invalid or expired trial proxy token",
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (db) {
|
|
// Authoritative DB check so migrated/deleted agents cannot keep using old
|
|
// signed tokens after a server restart or sleep-wake.
|
|
const [agentRow] = await db
|
|
.select({ runtimeConfig: agents.runtimeConfig })
|
|
.from(agents)
|
|
.where(
|
|
and(
|
|
eq(agents.id, tokenRecord.agentId),
|
|
eq(agents.companyId, tokenRecord.companyId),
|
|
ne(agents.status, "terminated"),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (!agentRow || !isAgentUsingCloudTrialInference(agentRow.runtimeConfig)) {
|
|
revokeAgentTokens(tokenRecord.companyId, [tokenRecord.agentId]);
|
|
res.statusCode = 401;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code: "proxy_token_not_found_on_instance",
|
|
message: "Trial proxy token is no longer active for this agent",
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
}
|
|
|
|
const workGateActive =
|
|
keyStore.getGateReason(tokenRecord.companyId) === "work_requires_model" ||
|
|
(db ? (await resolveHeldTrialIssues(db, tokenRecord.companyId, keyStore, true)).length > 0 : false);
|
|
if (workGateActive) {
|
|
activeRunTokens.delete(tokenRecord.token);
|
|
res.statusCode = 402;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code: CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
|
message: "Connect a model provider to run tasks and continue chatting.",
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
|
|
const state = keyStore.getCached() ?? (await keyStore.fetchKeyFromCloudOrLocal(false));
|
|
if (state.status === "exhausted" || !state.apiKey || state.remainingUsdCents <= 0) {
|
|
await keyStore.markExhausted({
|
|
companyId: tokenRecord.companyId,
|
|
agentId: tokenRecord.agentId,
|
|
runId: tokenRecord.runId,
|
|
reason: "budget_exhausted",
|
|
});
|
|
res.statusCode = 402;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code: CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
|
message: "You need to connect a model provider to continue.",
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
|
|
const currentAllowedModel = stripOpenRouterPrefix(state.defaultModel);
|
|
if (tokenRecord.allowedModel !== currentAllowedModel) {
|
|
res.statusCode = 403;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code: "model_not_allowed",
|
|
message: `Trial inference is restricted to ${currentAllowedModel}`,
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
|
|
const normalizedSubpath = subpath.replace(/^\/+/, "");
|
|
if (!["chat/completions", "responses", "models"].includes(normalizedSubpath)) {
|
|
res.statusCode = 404;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(JSON.stringify({ error: { code: "unsupported_endpoint", message: "Unsupported proxy endpoint" } }));
|
|
return;
|
|
}
|
|
|
|
const method = (req.method ?? "POST").toUpperCase();
|
|
let forwardBody: Buffer | undefined;
|
|
if (method !== "GET" && method !== "HEAD") {
|
|
if (req.body !== undefined && req.body !== null) {
|
|
const serialized = typeof req.body === "string" ? req.body : JSON.stringify(req.body);
|
|
forwardBody = Buffer.from(serialized, "utf8");
|
|
} else {
|
|
const chunks: Buffer[] = [];
|
|
let total = 0;
|
|
for await (const chunk of req) {
|
|
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
total += buf.length;
|
|
if (total > MAX_PROXY_REQUEST_BYTES) {
|
|
res.statusCode = 413;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(JSON.stringify({ error: { code: "payload_too_large", message: "Request body too large" } }));
|
|
return;
|
|
}
|
|
chunks.push(buf);
|
|
}
|
|
forwardBody = Buffer.concat(chunks);
|
|
}
|
|
|
|
if (normalizedSubpath === "chat/completions" || normalizedSubpath === "responses") {
|
|
if (forwardBody.length === 0) {
|
|
res.statusCode = 400;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(JSON.stringify({ error: { code: "invalid_json", message: "Request body is required" } }));
|
|
return;
|
|
}
|
|
try {
|
|
const parsed = readJsonRecord(JSON.parse(forwardBody.toString("utf8")));
|
|
const requestedModel =
|
|
typeof parsed.model === "string" && parsed.model.trim()
|
|
? stripOpenRouterPrefix(parsed.model)
|
|
: "";
|
|
const disallowedFallbackRoute = parsed.route !== undefined;
|
|
let disallowedModelsList = false;
|
|
if (parsed.models !== undefined) {
|
|
if (
|
|
!Array.isArray(parsed.models) ||
|
|
parsed.models.length === 0 ||
|
|
parsed.models.some(
|
|
(entry) =>
|
|
typeof entry !== "string" ||
|
|
!entry.trim() ||
|
|
stripOpenRouterPrefix(entry) !== tokenRecord.allowedModel,
|
|
)
|
|
) {
|
|
disallowedModelsList = true;
|
|
}
|
|
}
|
|
if (
|
|
requestedModel !== tokenRecord.allowedModel ||
|
|
disallowedFallbackRoute ||
|
|
disallowedModelsList
|
|
) {
|
|
res.statusCode = 403;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code: "model_not_allowed",
|
|
message: `Trial inference is restricted to ${tokenRecord.allowedModel}`,
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
} catch {
|
|
res.statusCode = 400;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(JSON.stringify({ error: { code: "invalid_json", message: "Invalid JSON payload" } }));
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
const upstreamAbort = new AbortController();
|
|
const onClientClose = () => {
|
|
if (!res.writableEnded) {
|
|
upstreamAbort.abort();
|
|
}
|
|
};
|
|
res.on("close", onClientClose);
|
|
|
|
try {
|
|
const upstreamUrl = `${keyStore.upstreamBaseUrl()}/${normalizedSubpath}`;
|
|
let upstream: Response;
|
|
try {
|
|
upstream = await fetchImpl(upstreamUrl, {
|
|
method,
|
|
headers: {
|
|
...OPENROUTER_ATTRIBUTION_HEADERS,
|
|
accept: typeof req.headers.accept === "string" ? req.headers.accept : "application/json",
|
|
authorization: `Bearer ${state.apiKey}`,
|
|
...(forwardBody ? { "content-type": "application/json" } : {}),
|
|
},
|
|
...(forwardBody ? { body: new Uint8Array(forwardBody) } : {}),
|
|
signal: AbortSignal.any([upstreamAbort.signal, AbortSignal.timeout(PROXY_REQUEST_TIMEOUT_MS)]),
|
|
});
|
|
} catch (err) {
|
|
if (upstreamAbort.signal.aborted || res.writableEnded) return;
|
|
res.statusCode = 502;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code: "upstream_unavailable",
|
|
message: err instanceof Error ? err.message : "Failed to reach inference upstream",
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (upstream.status === 402 || upstream.status === 403 || upstream.status === 429) {
|
|
const text = await upstream.text().catch(() => "");
|
|
if (looksLikeOpenRouterLimitExhausted(upstream.status, text)) {
|
|
await keyStore.markExhausted({
|
|
companyId: tokenRecord.companyId,
|
|
agentId: tokenRecord.agentId,
|
|
runId: tokenRecord.runId,
|
|
reason: `openrouter_http_${upstream.status}`,
|
|
});
|
|
res.statusCode = 402;
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(
|
|
JSON.stringify({
|
|
error: {
|
|
code: CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
|
message: "You need to connect a model provider to continue.",
|
|
},
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
res.statusCode = upstream.status;
|
|
res.setHeader("content-type", upstream.headers.get("content-type") ?? "application/json");
|
|
res.end(text);
|
|
return;
|
|
}
|
|
|
|
res.statusCode = upstream.status;
|
|
const contentType = upstream.headers.get("content-type");
|
|
if (contentType) res.setHeader("content-type", contentType);
|
|
res.setHeader("cache-control", "no-store");
|
|
|
|
if (upstream.body) {
|
|
try {
|
|
const nodeStream = Readable.fromWeb(upstream.body as unknown as NodeReadableStream);
|
|
await pipeline(nodeStream, res);
|
|
} catch (err) {
|
|
if (!upstreamAbort.signal.aborted && !res.writableEnded) {
|
|
throw err;
|
|
}
|
|
}
|
|
} else {
|
|
res.end(await upstream.text());
|
|
}
|
|
|
|
// Background usage probe (throttled) so UI stays current without blocking stream completion.
|
|
void keyStore.probeOpenRouterUsage(tokenRecord.companyId, false);
|
|
} finally {
|
|
res.off("close", onClientClose);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fast check for whether a company is currently eligible to use the Cloud
|
|
* starter inference key for default fast responses (active trial-only
|
|
* company, no llmBlocked gate, starter key not exhausted).
|
|
*
|
|
* Defaults `allowRemoteFetch` to `false` so callers inside chat-save
|
|
* transactions never block on a Cloud onboarding-config HTTP request.
|
|
*/
|
|
async function isCloudTrialFastResponseEligible(
|
|
db: Db,
|
|
companyId: string,
|
|
options: { checkHeldIssues?: boolean; allowRemoteFetch?: boolean } = {},
|
|
): Promise<boolean> {
|
|
const effective = await resolveEffectiveOnboardingConfig(db, keyStore, {
|
|
allowRemoteFetch: options.allowRemoteFetch === true,
|
|
});
|
|
if (!effective.trialInferenceEnabled) return false;
|
|
const { trialOnly } = await isCompanyOnTrialOnlyInference(db, companyId);
|
|
if (!trialOnly) return false;
|
|
if (keyStore.getGateReason(companyId) !== null) return false;
|
|
const cached = keyStore.getCached();
|
|
if (
|
|
cached &&
|
|
(cached.status === "exhausted" ||
|
|
cached.status === "disabled" ||
|
|
cached.remainingUsdCents <= 0)
|
|
) {
|
|
return false;
|
|
}
|
|
if (options.checkHeldIssues) {
|
|
const heldIssues = await resolveHeldTrialIssues(db, companyId, keyStore, true);
|
|
if (heldIssues.length > 0) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Prepares an in-process OpenRouter credential + guarded fetch wrapper for a
|
|
* fast-response acknowledgement using the Cloud starter inference key.
|
|
*
|
|
* The raw `sk-or-v1-...` key stays strictly inside the server process,
|
|
* respects the $1 quota and `work_requires_model` / `exhausted` gates, and
|
|
* flips the company gate to `exhausted` immediately on HTTP 402/limit errors.
|
|
*/
|
|
async function prepareCloudTrialFastResponse(
|
|
db: Db,
|
|
input: {
|
|
companyId: string;
|
|
agentId?: string | null;
|
|
requestId: string;
|
|
},
|
|
): Promise<PreparedCloudTrialFastResponse> {
|
|
const effective = await resolveEffectiveOnboardingConfig(db, keyStore);
|
|
if (!effective.trialInferenceEnabled) {
|
|
throw unprocessable("Cloud starter inference is not enabled on this instance.", {
|
|
code: "cloud_trial_disabled",
|
|
});
|
|
}
|
|
const { trialOnly } = await isCompanyOnTrialOnlyInference(db, input.companyId);
|
|
if (!trialOnly) {
|
|
throw unprocessable("Cloud starter inference is not active for this company.", {
|
|
code: "cloud_trial_disabled",
|
|
});
|
|
}
|
|
|
|
const heldIssues =
|
|
keyStore.getGateReason(input.companyId) === "work_requires_model"
|
|
? keyStore.getHeldIssues(input.companyId)
|
|
: await resolveHeldTrialIssues(db, input.companyId, keyStore, true);
|
|
if (heldIssues.length > 0) {
|
|
throw new CloudTrialWorkRequiresModelError(undefined, {
|
|
companyId: input.companyId,
|
|
agentId: input.agentId ?? undefined,
|
|
runId: `fast-response:${input.requestId}`,
|
|
heldIssueIds: heldIssues.map((h) => h.id),
|
|
});
|
|
}
|
|
|
|
const state = await keyStore.fetchKeyFromCloudOrLocal(false);
|
|
if (state.status === "exhausted" || (state.status === "active" && state.remainingUsdCents <= 0)) {
|
|
await keyStore.markExhausted({
|
|
companyId: input.companyId,
|
|
agentId: input.agentId ?? undefined,
|
|
runId: `fast-response:${input.requestId}`,
|
|
spentUsdCents: state.spentUsdCents || state.limitUsdCents,
|
|
reason: "budget_exhausted",
|
|
});
|
|
throw new CloudTrialExhaustedError(undefined, {
|
|
companyId: input.companyId,
|
|
agentId: input.agentId ?? undefined,
|
|
runId: `fast-response:${input.requestId}`,
|
|
});
|
|
}
|
|
if (state.status !== "active" || !state.apiKey) {
|
|
throw unprocessable("You need to connect a model provider to continue.", {
|
|
code: state.status === "disabled" ? "cloud_trial_disabled" : CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
|
trialStatus: state.status,
|
|
reason: state.reason,
|
|
});
|
|
}
|
|
|
|
const upstreamBase = keyStore.upstreamBaseUrl();
|
|
const defaultOpenRouterBase = "https://openrouter.ai/api/v1";
|
|
const guardedFetch: typeof fetch = async (url, init) => {
|
|
const rawUrl =
|
|
typeof url === "string"
|
|
? url
|
|
: url instanceof URL
|
|
? url.toString()
|
|
: url.url;
|
|
const targetUrl = rawUrl.startsWith(defaultOpenRouterBase)
|
|
? `${upstreamBase}${rawUrl.slice(defaultOpenRouterBase.length)}`
|
|
: url;
|
|
const response = await fetchImpl(targetUrl, init);
|
|
if (
|
|
!response.ok &&
|
|
(response.status === 402 || response.status === 403 || response.status === 429)
|
|
) {
|
|
const clonedText = await response.clone().text().catch(() => "");
|
|
if (looksLikeOpenRouterLimitExhausted(response.status, clonedText)) {
|
|
await keyStore.markExhausted({
|
|
companyId: input.companyId,
|
|
agentId: input.agentId ?? undefined,
|
|
runId: `fast-response:${input.requestId}`,
|
|
reason: `openrouter_http_${response.status}`,
|
|
});
|
|
}
|
|
}
|
|
return response;
|
|
};
|
|
|
|
return {
|
|
metadata: {
|
|
provider: "openrouter",
|
|
method: "api_key",
|
|
},
|
|
credential: state.apiKey,
|
|
model: keyStore.configuredFastResponseModel(),
|
|
fetch: guardedFetch,
|
|
cleanup: async () => {
|
|
void keyStore.probeOpenRouterUsage(input.companyId, false);
|
|
},
|
|
};
|
|
}
|
|
|
|
return {
|
|
prepareCloudTrialRuntime,
|
|
isCloudTrialFastResponseEligible,
|
|
prepareCloudTrialFastResponse,
|
|
getFastResponseModel: keyStore.configuredFastResponseModel,
|
|
proxyOpenRouterRequest,
|
|
revokeAgentTokens,
|
|
clearTokens: () => {
|
|
activeRunTokens.clear();
|
|
revokedAgents.clear();
|
|
},
|
|
};
|
|
}
|