fix(cloud-trial): use stable HMAC-signed proxy tokens across warm OpenCode sessions (#23616)

## 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
This commit is contained in:
Dotta authored and GitHub committed 2026-12-03 08:54:03 -06:00
1 parent ce204a223a
commit 8e2381a1d1
6 files changed
+320 -26

No files matched your search

@@ -708,4 +708,132 @@ describe("cloud-trial-inference", () => {
}),
).rejects.toBeInstanceOf(CloudTrialWorkRequiresModelError);
});
it("keeps signed starter proxy tokens valid across warm session reuse and restarts, while failing closed on tampering or revocation", async () => {
const db = fakeDbWithFlag(true);
const sharedEnv = {
PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1",
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "stable-tenant-secret-across-restarts",
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-warm-session-secret",
};
const mockFetch: typeof fetch = async (input) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (url.endsWith("/key")) {
return new Response(JSON.stringify({ data: { usage: 0.02, limit: 1.0 } }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
return new Response(
JSON.stringify({
id: "chatcmpl-warm",
choices: [{ message: { role: "assistant", content: "Warm turn reply!" } }],
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
};
const controller1 = createCloudTrialInferenceController({ env: sharedEnv, fetchImpl: mockFetch });
const app1 = express();
app1.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(controller1));
const proxy1 = await listenExpress(app1);
const controller2 = createCloudTrialInferenceController({ env: sharedEnv, fetchImpl: mockFetch });
const app2 = express();
app2.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(controller2));
const proxy2 = await listenExpress(app2);
try {
// Run 1 prepares runtime and completes cleanup()
const run1 = await controller1.prepareCloudTrialRuntime(db, {
companyId: "comp-warm",
agentId: "agent-warm",
runId: "run-1",
model: "openrouter/openai/gpt-6-luna",
});
const token1 = run1.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN!;
expect(token1.startsWith("pctrial_v1.")).toBe(true);
await run1.cleanup();
// Warm session turn 2 reuses run 1's token AFTER run 1 cleanup() -> succeeds on attempt #1
const warmTurnRes = await fetch(`${proxy1.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token1}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "2+2?" }] }),
});
expect(warmTurnRes.status).toBe(200);
// Consecutive prepareCloudTrialRuntime for the same agent yields the exact same stable token
const run2 = await controller1.prepareCloudTrialRuntime(db, {
companyId: "comp-warm",
agentId: "agent-warm",
runId: "run-2",
model: "openrouter/openai/gpt-6-luna",
});
expect(run2.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN).toBe(token1);
await run2.cleanup();
// Fresh controller (simulating server restart / sleep-wake) still accepts the signed warm token
const afterRestartRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token1}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "still warm?" }] }),
});
expect(afterRestartRes.status).toBe(200);
// Tampered token fails closed with 401
const tamperedRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token1}x`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
});
expect(tamperedRes.status).toBe(401);
// Partial migration revokes ONLY the migrated agent, leaving sibling trial agents working
const siblingRun = await controller2.prepareCloudTrialRuntime(db, {
companyId: "comp-warm",
agentId: "agent-sibling",
runId: "run-sibling",
model: "openrouter/openai/gpt-6-luna",
});
const siblingToken = siblingRun.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN!;
controller2.revokeAgentTokens("comp-warm", ["agent-warm"]);
const revokedRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${token1}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
});
expect(revokedRes.status).toBe(401);
const siblingRes = await fetch(`${proxy2.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: { authorization: `Bearer ${siblingToken}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "sibling ok?" }] }),
});
expect(siblingRes.status).toBe(200);
await siblingRun.cleanup();
// Changing PAPERCLIP_CLOUD_TRIAL_MODEL invalidates tokens signed for the old model (403)
const rotatedController = createCloudTrialInferenceController({
env: { ...sharedEnv, PAPERCLIP_CLOUD_TRIAL_MODEL: "openrouter/openai/gpt-6-new" },
fetchImpl: mockFetch,
});
const rotatedApp = express();
rotatedApp.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(rotatedController));
const rotatedProxy = await listenExpress(rotatedApp);
try {
const staleModelRes = await fetch(
`${rotatedProxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`,
{
method: "POST",
headers: { authorization: `Bearer ${siblingToken}`, "content-type": "application/json" },
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
},
);
expect(staleModelRes.status).toBe(403);
} finally {
await rotatedProxy.close();
}
} finally {
await proxy1.close();
await proxy2.close();
}
});
});
@@ -4,7 +4,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { companies, createDb } from "@paperclipai/db";
import { eq } from "drizzle-orm";
import { agents, companies, createDb } from "@paperclipai/db";
import { createApp } from "../app.js";
import { getDefaultCloudTrialInferenceController } from "../services/cloud-trial-inference.js";
import { instanceSettingsService } from "../services/instance-settings.js";
@@ -83,11 +84,19 @@ describePostgres("cloud inference internal proxy middleware order", () => {
it("mounts /api/internal/cloud-inference before actorMiddleware so pctrial_ Bearer tokens are not rejected as agent tokens", async () => {
await instanceSettingsService(db).updateExperimental({ enableCloudTrialInference: true });
const companyId = randomUUID();
const agentId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Proxy Order Co",
issuePrefix: "PO",
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "Starter Agent",
adapterType: "paperclip_runner",
runtimeConfig: { cloudTrialInference: true },
});
const app: App = await createApp(db, {
uiMode: "none",
@@ -127,7 +136,7 @@ describePostgres("cloud inference internal proxy middleware order", () => {
// 2. Valid active pctrial_ token proxies cleanly to upstream OpenRouter with server-held key
const runtime = await getDefaultCloudTrialInferenceController().prepareCloudTrialRuntime(db, {
companyId,
agentId: randomUUID(),
agentId,
runId: randomUUID(),
model: "openrouter/openai/gpt-6-luna",
});
@@ -149,6 +158,21 @@ describePostgres("cloud inference internal proxy middleware order", () => {
};
expect(okBody.choices[0]?.message.content).toBe("Hello from starter proxy!");
expect(seenUpstreamAuth).toBe("Bearer sk-or-v1-middleware-order-secret");
// 3. Once the agent is migrated off cloudTrialInference in DB, the old signed token fails closed (401)
await db.update(agents).set({ runtimeConfig: {} }).where(eq(agents.id, agentId));
const migratedRes = await fetch(`${baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
method: "POST",
headers: {
authorization: `Bearer ${runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: "openai/gpt-6-luna",
messages: [{ role: "user", content: "After migration" }],
}),
});
expect(migratedRes.status).toBe(401);
} finally {
await runtime.cleanup();
}
+1 -1
View File
@@ -682,7 +682,7 @@ export async function createApp(
void instanceSettingsService(db)
.getExperimental()
.catch(() => {});
app.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(cloudTrialInferenceController));
app.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(cloudTrialInferenceController, db));
app.use(
actorMiddleware(db, {
deploymentMode: opts.deploymentMode,
+2 -1
View File
@@ -20,13 +20,14 @@ import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
*/
export function cloudInferenceInternalProxyRoutes(
controller: CloudTrialInferenceController = getDefaultCloudTrialInferenceController(),
db?: Db,
) {
const router = Router();
router.all("/v1/*subpath", async (req, res) => {
const rawSubpath = (req.params as Record<string, string | string[]>).subpath;
const subpath = Array.isArray(rawSubpath) ? rawSubpath.join("/") : rawSubpath ?? "";
await controller.proxyOpenRouterRequest(req, res, subpath);
await controller.proxyOpenRouterRequest(req, res, subpath, db);
});
return router;
+10 -2
View File
@@ -85,12 +85,20 @@ export function createCloudTrialInferenceController(opts: CloudTrialInferenceOpt
companyId: string,
options: { refreshUsage?: boolean; actor?: AuthorizationActor } = {},
) => getCompanyCloudTrialStatus(db, companyId, keyStore, options),
migrateTrialAgents: (
migrateTrialAgents: async (
db: Db,
companyId: string,
input: MigrateCloudTrialAgentsInput,
actor: CloudTrialMigrationActor,
) => migrateCloudTrialAgents(db, companyId, input, actor, keyStore),
) => {
const result = await migrateCloudTrialAgents(db, companyId, input, actor, keyStore);
const migratedAgentIds = result.agents.map((a) => a.agentId);
if (migratedAgentIds.length > 0) {
proxy.revokeAgentTokens(companyId, migratedAgentIds);
}
return result;
},
revokeAgentTokens: proxy.revokeAgentTokens,
markExhausted: keyStore.markExhausted,
probeOpenRouterUsage: keyStore.probeOpenRouterUsage,
_resetForTests: () => {
+153 -20
View File
@@ -1,12 +1,14 @@
import { randomBytes, timingSafeEqual } from "node:crypto";
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 type { Db } from "@paperclipai/db";
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";
@@ -27,6 +29,7 @@ import {
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;
@@ -61,30 +64,106 @@ function looksLikeOpenRouterLimitExhausted(status: number, bodyText: string): bo
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);
}
/**
* Per-run OpenRouter reverse proxy for starter-trial runs.
* OpenRouter reverse proxy for starter-trial runs.
*
* Ephemeral tokens live in this single-replica stack process for the lifetime
* of the active run (sliding idle TTL refreshed on every proxied request, and
* revoked immediately on run exit or budget exhaustion).
* 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 record;
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);
}
}
return null;
}
/**
@@ -159,19 +238,19 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
const serverOrigin = (env.PAPERCLIP_API_URL?.trim() || "http://127.0.0.1:3100").replace(/\/+$/, "");
const proxyUrl = `${serverOrigin}/api/internal/cloud-inference/v1`;
const token = `${RUN_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
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,
});
}
activeRunTokens.set(token, {
token,
companyId: input.companyId,
agentId: input.agentId,
runId: input.runId,
allowedModel,
});
return {
env: {
OPENROUTER_API_KEY: "",
@@ -181,7 +260,8 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
secretValues: [token, state.apiKey],
defaultModel: state.defaultModel,
cleanup: async () => {
activeRunTokens.delete(token);
// 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);
},
};
@@ -196,6 +276,7 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
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() : "";
@@ -220,7 +301,40 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
return;
}
if (keyStore.getGateReason(tokenRecord.companyId) === "work_requires_model") {
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");
@@ -256,6 +370,21 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
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;
@@ -583,6 +712,10 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
prepareCloudTrialFastResponse,
getFastResponseModel: keyStore.configuredFastResponseModel,
proxyOpenRouterRequest,
clearTokens: () => activeRunTokens.clear(),
revokeAgentTokens,
clearTokens: () => {
activeRunTokens.clear();
revokedAgents.clear();
},
};
}