Files
PaperClipAI/server/src/services/cloud-trial-proxy.ts
T
Dotta 86927d4933 feat(cloud-trial): enable fast responses by default with starter inference key (#23556)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Fast responses send a brief acknowledgement in the agent's voice
while the full agent run starts.
> - During Cloud starter-inference onboarding (`free_inference_1`),
users start chatting immediately before connecting their own model
provider, so no `company_fast_responses` connection exists yet.
> - Without a default fast-response path, the first chat waits silently
while the Runner starts up and thinks.
> - This pull request enables fast responses by default while Cloud
starter inference is active, routing acknowledgements through the
server-held OpenRouter starter key with `$1` quota and `llmBlocked` gate
enforcement.
> - The benefit is immediate, responsive first-chat acknowledgements out
of the box with a clean handoff once the user connects their own model
provider.

## Linked Issues or Issue Description

Refs #23401, #23427

**Summary**
Enable fast-response acknowledgements by default for companies running
on active Cloud starter inference (`free_inference_1`), using the
existing server-side OpenRouter starter inference key.

**Problem Statement**
Fast responses currently require both the experimental
`enableFastResponses` instance flag and an explicit shared API
connection in `company_fast_responses`. New Cloud starter-inference
workspaces have no saved API connection yet, so users do not get fast
acknowledgements during their initial onboarding chat.

**Proposed Solution**
Fall back to the server-side Cloud starter inference OpenRouter key
(`FAST_RESPONSE_DEFAULT_MODEL`, `openai/gpt-oss-120b`) when a company
has no `company_fast_responses` row and is actively on trial-only
inference without a blocked gate. Respect explicit company
configuration/opt-out, enforce `responsibleUserId` and `issue:read`
authorization, disallow sponsored webhooks on the starter key, mark the
trial exhausted on HTTP 402/limit errors, and stop using the starter key
automatically once the user connects their own model provider.

## What Changed

- `server/src/services/cloud-trial-proxy.ts` &
`server/src/services/cloud-trial-inference.ts`: Added
`isCloudTrialFastResponseEligible` and `prepareCloudTrialFastResponse`.
Keeps the raw OpenRouter key strictly in server process memory, enforces
`isCompanyOnTrialOnlyInference`, the `$1` quota, and the
`work_requires_model` / `exhausted` gates, wraps `fetch` to call
`markExhausted` immediately on HTTP 402/limit responses, and probes
usage on cleanup.
- `server/src/services/fast-responses.ts`: Updated
`enqueueFastResponse`, `fastResponseSourceCurrent`, `settings`,
`availability`, `resolve`, `process`, and `history` to use Cloud starter
inference by default when no `company_fast_responses` row exists and
starter inference is active and unblocked. Explicit
`company_fast_responses` rows (including opt-out `enabled: false`)
always take precedence, and connecting a user model provider cleanly
ends starter-key usage.
- `packages/shared/src/fast-response.ts`: Added optional
`usingCloudTrialDefault?: boolean` to `FastResponseSettings`.
- `server/src/__tests__/fast-responses.test.ts`: Added regression tests
covering starter-inference default fast responses (even when
`enableFastResponses` is `false`), raw key non-leakage,
`work_requires_model` gate blocking, HTTP 402 exhaustion, explicit
opt-out, and clean handoff after connecting a user model provider.

## Verification

- `pnpm --filter @paperclipai/shared typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/fast-responses.test.ts
src/__tests__/cloud-trial-inference.test.ts` — passed (44/44 tests).

## Risks

- Low risk. No database schema migration is required
(`fast_response_requests.connection_id` and `grant_id` are already
nullable). Self-hosted instances and `baseline` Cloud stacks are
unaffected because `trialInferenceEnabled` is `false`. Companies that
explicitly configure or disable `company_fast_responses` or connect
their own AI provider never fall back to the starter key.

## 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
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-02 16:29:41 -06:00

589 lines
21 KiB
TypeScript

import { 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 {
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
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_";
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;
}
/**
* Per-run 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).
*/
export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
const { env, fetchImpl } = keyStore;
const activeRunTokens = new Map<string, RunProxyTokenRecord>();
keyStore.setOnExhausted(() => {
activeRunTokens.clear();
});
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 null;
}
/**
* 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 = `${RUN_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
if (!input.probeOnly) {
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 () => {
activeRunTokens.delete(token);
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,
): 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 (keyStore.getGateReason(tokenRecord.companyId) === "work_requires_model") {
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 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,
clearTokens: () => activeRunTokens.clear(),
};
}