mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
## 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
671 lines
24 KiB
TypeScript
671 lines
24 KiB
TypeScript
import { createPrivateKey, sign } from "node:crypto";
|
|
import {
|
|
CLOUD_TRIAL_DEFAULT_LIMIT_USD_CENTS,
|
|
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
|
CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
|
DEFAULT_ONBOARDING_VARIANT,
|
|
FAST_RESPONSE_DEFAULT_MODEL,
|
|
FREE_INFERENCE_ONBOARDING_VARIANT,
|
|
isFreeInferenceOnboardingVariant,
|
|
normalizeOnboardingVariant,
|
|
parseCloudTrialMigrationTargetsEnv,
|
|
resolveCloudTrialModel,
|
|
type CloudTrialGateReason,
|
|
type CloudTrialHeldIssueSummary,
|
|
type CloudTrialInferenceState,
|
|
type CloudTrialMigrationTargetOverrides,
|
|
type OnboardingVariant,
|
|
} from "@paperclipai/shared";
|
|
import { HttpError } from "../errors.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { getCloudStackContext, type CloudInstanceEnv } from "./cloud-instance.js";
|
|
import { onCloudRuntimeIdentityChange } from "./cloud-runtime-identity.js";
|
|
import {
|
|
setResolvedCloudTrialInferenceEnabled,
|
|
setResolvedOnboardingVariant,
|
|
} from "./cloud-posthog-cohort.js";
|
|
import { resolveOnboardingVariant } from "./cloud-posthog-config.js";
|
|
import { publishLiveEvent } from "./live-events.js";
|
|
import { trackCloudPostHogEvent } from "../telemetry.js";
|
|
|
|
const DEFAULT_OPENROUTER_UPSTREAM_BASE = "https://openrouter.ai/api/v1";
|
|
const USAGE_PROBE_MIN_INTERVAL_MS = 15_000;
|
|
const ONBOARDING_CONFIG_TTL_MS = 60_000;
|
|
|
|
export class CloudTrialExhaustedError extends HttpError {
|
|
constructor(
|
|
message = "You need to connect a model provider to continue.",
|
|
details: Record<string, unknown> = {},
|
|
) {
|
|
super(402, message, {
|
|
code: CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
|
gateReason: "exhausted",
|
|
...details,
|
|
});
|
|
this.name = "CloudTrialExhaustedError";
|
|
}
|
|
}
|
|
|
|
export class CloudTrialWorkRequiresModelError extends HttpError {
|
|
constructor(
|
|
message = "Connect a model provider to run tasks and continue chatting.",
|
|
details: Record<string, unknown> = {},
|
|
) {
|
|
super(402, message, {
|
|
code: CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE,
|
|
gateReason: "work_requires_model",
|
|
...details,
|
|
});
|
|
this.name = "CloudTrialWorkRequiresModelError";
|
|
}
|
|
}
|
|
|
|
export function isCloudTrialExhaustedError(error: unknown): error is CloudTrialExhaustedError {
|
|
if (error instanceof CloudTrialExhaustedError) return true;
|
|
if (error instanceof HttpError) {
|
|
const details = error.details as { code?: unknown } | undefined;
|
|
return details?.code === CLOUD_TRIAL_EXHAUSTED_ERROR_CODE;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
export function isCloudTrialWorkRequiresModelError(
|
|
error: unknown,
|
|
): error is CloudTrialWorkRequiresModelError {
|
|
if (error instanceof CloudTrialWorkRequiresModelError) return true;
|
|
if (error instanceof HttpError) {
|
|
const details = error.details as { code?: unknown } | undefined;
|
|
return details?.code === CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
export function isCloudTrialGateError(
|
|
error: unknown,
|
|
): error is CloudTrialExhaustedError | CloudTrialWorkRequiresModelError {
|
|
return isCloudTrialExhaustedError(error) || isCloudTrialWorkRequiresModelError(error);
|
|
}
|
|
|
|
export interface CachedOnboardingConfig {
|
|
onboardingVariant: OnboardingVariant;
|
|
trialInferenceEnabled: boolean;
|
|
source: "cloud" | "env" | "managed_config" | "default";
|
|
fetchedAtMs: number;
|
|
}
|
|
|
|
export interface CachedCloudKeyState {
|
|
status: CloudTrialInferenceState;
|
|
reason?: string;
|
|
apiKey: string | null;
|
|
limitUsdCents: number;
|
|
spentUsdCents: number;
|
|
remainingUsdCents: number;
|
|
defaultModel: string;
|
|
fetchedAtMs: number;
|
|
lastUsageProbeAtMs: number;
|
|
}
|
|
|
|
export interface CloudTrialKeyStoreOptions {
|
|
env?: CloudInstanceEnv;
|
|
fetchImpl?: typeof fetch;
|
|
now?: () => number;
|
|
onExhausted?: () => void;
|
|
}
|
|
|
|
export function readJsonRecord(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: {};
|
|
}
|
|
|
|
export function stripOpenRouterPrefix(model: string): string {
|
|
const trimmed = model.trim();
|
|
return trimmed.startsWith("openrouter/") ? trimmed.slice("openrouter/".length) : trimmed;
|
|
}
|
|
|
|
function buildCloudStackAuthHeaders(
|
|
env: CloudInstanceEnv,
|
|
method: string,
|
|
pathname: string,
|
|
stackId: string,
|
|
): Record<string, string> {
|
|
const signPrivateKey = env.PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY?.trim();
|
|
if (!signPrivateKey) {
|
|
throw new HttpError(502, "Cloud stack signing key is not configured", {
|
|
code: "cloud_inference_auth_unconfigured",
|
|
});
|
|
}
|
|
const raw = Buffer.from(signPrivateKey, "base64url");
|
|
if (raw.length !== 32) {
|
|
throw new HttpError(502, "Cloud stack signing key is invalid", {
|
|
code: "cloud_inference_auth_unconfigured",
|
|
});
|
|
}
|
|
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), raw]);
|
|
const key = createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
|
|
const payload = Buffer.from(`${method}\n${pathname}\n${stackId}\n${timestamp}`, "utf8");
|
|
return {
|
|
accept: "application/json",
|
|
"x-paperclip-cloud-stack-id": stackId,
|
|
"x-paperclip-cloud-stack-timestamp": timestamp,
|
|
"x-paperclip-cloud-stack-signature": sign(null, payload, key).toString("base64url"),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* In-process custody for the tenant stack's Cloud-issued OpenRouter starter key.
|
|
*
|
|
* Paperclip Cloud tenant stacks run as a single Node instance per stack; the
|
|
* raw OpenRouter key is intentionally held only in server process memory so it
|
|
* never touches Postgres, sandboxes, logs, or UI responses.
|
|
*/
|
|
export function createCloudTrialKeyStore(opts: CloudTrialKeyStoreOptions = {}) {
|
|
const env = opts.env ?? process.env;
|
|
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
const now = opts.now ?? Date.now;
|
|
let onExhaustedHook = opts.onExhausted;
|
|
|
|
let cached: CachedCloudKeyState | null = null;
|
|
let inflightFetch: Promise<CachedCloudKeyState> | null = null;
|
|
let cachedOnboardingConfig: CachedOnboardingConfig | null = null;
|
|
let inflightOnboardingConfigFetch: Promise<CachedOnboardingConfig> | null = null;
|
|
const heldIssuesByCompany = new Map<string, Map<string, CloudTrialHeldIssueSummary>>();
|
|
|
|
// Warm-pool stacks may boot before signup/claim time. Invalidate cached
|
|
// onboarding config when runtime identity changes so the next read fetches
|
|
// the stack's claim-time assigned variant from Cloud control plane.
|
|
if (env === process.env) {
|
|
onCloudRuntimeIdentityChange(() => {
|
|
cachedOnboardingConfig = null;
|
|
});
|
|
}
|
|
|
|
function syncResolvedCohort(onboardingVariant: OnboardingVariant, trialInferenceEnabled: boolean) {
|
|
if (env !== process.env) return;
|
|
setResolvedOnboardingVariant(onboardingVariant);
|
|
setResolvedCloudTrialInferenceEnabled(trialInferenceEnabled);
|
|
}
|
|
|
|
function fallbackOnboardingConfig(): CachedOnboardingConfig {
|
|
const envVariant = env.PAPERCLIP_ONBOARDING_VARIANT?.trim();
|
|
if (envVariant) {
|
|
const normalized = normalizeOnboardingVariant(envVariant);
|
|
const trialInferenceEnabled = isFreeInferenceOnboardingVariant(normalized);
|
|
return {
|
|
onboardingVariant: normalized,
|
|
trialInferenceEnabled,
|
|
source: "env",
|
|
fetchedAtMs: now(),
|
|
};
|
|
}
|
|
const managedRaw = env.PAPERCLIP_MANAGED_CONFIG?.trim();
|
|
if (managedRaw) {
|
|
const resolved = resolveOnboardingVariant(env);
|
|
const trialInferenceEnabled = isFreeInferenceOnboardingVariant(resolved);
|
|
if (resolved !== DEFAULT_ONBOARDING_VARIANT) {
|
|
return {
|
|
onboardingVariant: resolved,
|
|
trialInferenceEnabled,
|
|
source: "managed_config",
|
|
fetchedAtMs: now(),
|
|
};
|
|
}
|
|
}
|
|
return {
|
|
onboardingVariant: DEFAULT_ONBOARDING_VARIANT,
|
|
trialInferenceEnabled: false,
|
|
source: "default",
|
|
fetchedAtMs: now(),
|
|
};
|
|
}
|
|
|
|
async function fetchOnboardingConfig(forceRefresh = false): Promise<CachedOnboardingConfig> {
|
|
if (
|
|
!forceRefresh &&
|
|
cachedOnboardingConfig &&
|
|
now() - cachedOnboardingConfig.fetchedAtMs < ONBOARDING_CONFIG_TTL_MS
|
|
) {
|
|
return cachedOnboardingConfig;
|
|
}
|
|
|
|
const context = getCloudStackContext(env);
|
|
const hasSigningKey = Boolean(env.PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY?.trim());
|
|
if (!context?.cloudOrigin || !context.stackId || !hasSigningKey) {
|
|
const fallback = fallbackOnboardingConfig();
|
|
cachedOnboardingConfig = fallback;
|
|
syncResolvedCohort(fallback.onboardingVariant, fallback.trialInferenceEnabled);
|
|
return fallback;
|
|
}
|
|
|
|
if (inflightOnboardingConfigFetch) return inflightOnboardingConfigFetch;
|
|
inflightOnboardingConfigFetch = (async () => {
|
|
try {
|
|
const pathname = "/v1/tenant/onboarding-config";
|
|
const url = new URL(pathname, context.cloudOrigin!);
|
|
const response = await fetchImpl(url, {
|
|
method: "GET",
|
|
headers: buildCloudStackAuthHeaders(env, "GET", pathname, context.stackId!),
|
|
signal: AbortSignal.timeout(5_000),
|
|
});
|
|
if (!response.ok) {
|
|
logger.warn(
|
|
{ status: response.status, stackId: context.stackId },
|
|
"Cloud onboarding config request returned non-OK status; falling back",
|
|
);
|
|
const fallback = fallbackOnboardingConfig();
|
|
cachedOnboardingConfig = fallback;
|
|
syncResolvedCohort(fallback.onboardingVariant, fallback.trialInferenceEnabled);
|
|
return fallback;
|
|
}
|
|
const payload = readJsonRecord(await response.json());
|
|
const onboardingVariant = normalizeOnboardingVariant(
|
|
typeof payload.onboardingVariant === "string" ? payload.onboardingVariant : undefined,
|
|
);
|
|
const trialInferenceEnabled =
|
|
payload.trialInferenceEnabled === true ||
|
|
isFreeInferenceOnboardingVariant(onboardingVariant);
|
|
cachedOnboardingConfig = {
|
|
onboardingVariant,
|
|
trialInferenceEnabled,
|
|
source: "cloud",
|
|
fetchedAtMs: now(),
|
|
};
|
|
syncResolvedCohort(onboardingVariant, trialInferenceEnabled);
|
|
return cachedOnboardingConfig;
|
|
} catch (err) {
|
|
logger.debug({ err }, "Failed to fetch Cloud onboarding config; falling back");
|
|
const fallback = fallbackOnboardingConfig();
|
|
cachedOnboardingConfig = fallback;
|
|
syncResolvedCohort(fallback.onboardingVariant, fallback.trialInferenceEnabled);
|
|
return fallback;
|
|
}
|
|
})().finally(() => {
|
|
inflightOnboardingConfigFetch = null;
|
|
});
|
|
return inflightOnboardingConfigFetch;
|
|
}
|
|
|
|
function getHeldIssues(companyId: string): CloudTrialHeldIssueSummary[] {
|
|
const map = heldIssuesByCompany.get(companyId);
|
|
return map ? Array.from(map.values()) : [];
|
|
}
|
|
|
|
function holdIssue(
|
|
companyId: string,
|
|
issue: {
|
|
id: string;
|
|
identifier: string | null;
|
|
title: string;
|
|
assigneeAgentId: string | null;
|
|
},
|
|
): { heldIssues: CloudTrialHeldIssueSummary[]; newlyHeld: boolean } {
|
|
let map = heldIssuesByCompany.get(companyId);
|
|
if (!map) {
|
|
map = new Map();
|
|
heldIssuesByCompany.set(companyId, map);
|
|
}
|
|
const newlyHeld = !map.has(issue.id);
|
|
if (newlyHeld) {
|
|
map.set(issue.id, {
|
|
id: issue.id,
|
|
identifier: issue.identifier,
|
|
title: issue.title,
|
|
assigneeAgentId: issue.assigneeAgentId,
|
|
heldAt: new Date(now()).toISOString(),
|
|
});
|
|
}
|
|
return { heldIssues: Array.from(map.values()), newlyHeld };
|
|
}
|
|
|
|
function clearHeldIssues(companyId: string): CloudTrialHeldIssueSummary[] {
|
|
const existing = getHeldIssues(companyId);
|
|
heldIssuesByCompany.delete(companyId);
|
|
return existing;
|
|
}
|
|
|
|
function removeHeldIssue(companyId: string, issueId: string): void {
|
|
const map = heldIssuesByCompany.get(companyId);
|
|
if (!map) return;
|
|
map.delete(issueId);
|
|
if (map.size === 0) {
|
|
heldIssuesByCompany.delete(companyId);
|
|
}
|
|
}
|
|
|
|
function getGateReason(companyId: string): CloudTrialGateReason | null {
|
|
if (cached?.status === "exhausted") return "exhausted";
|
|
if (getHeldIssues(companyId).length > 0) return "work_requires_model";
|
|
return null;
|
|
}
|
|
|
|
// Best-effort PostHog funnel counters for this process (Cloud-only).
|
|
let keyIssuedTracked = false;
|
|
let keyIssuedAtMs: number | null = null;
|
|
let trialRunsCount = 0;
|
|
let exhaustedTracked = false;
|
|
let exhaustedAtMs: number | null = null;
|
|
|
|
function maybeTrackKeyIssued(state: CachedCloudKeyState) {
|
|
if (keyIssuedTracked || state.status !== "active" || !state.apiKey) return;
|
|
keyIssuedTracked = true;
|
|
keyIssuedAtMs = now();
|
|
trackCloudPostHogEvent("cloud_trial.key_issued", {
|
|
model: state.defaultModel,
|
|
limit_usd_cents: state.limitUsdCents,
|
|
});
|
|
}
|
|
|
|
function upstreamBaseUrl(): string {
|
|
return (env.PAPERCLIP_CLOUD_TRIAL_OPENROUTER_BASE_URL?.trim() || DEFAULT_OPENROUTER_UPSTREAM_BASE).replace(
|
|
/\/+$/,
|
|
"",
|
|
);
|
|
}
|
|
|
|
function configuredDefaultModel(): string {
|
|
return resolveCloudTrialModel(env.PAPERCLIP_CLOUD_TRIAL_MODEL);
|
|
}
|
|
|
|
function configuredFastResponseModel(): string {
|
|
const raw = env.PAPERCLIP_CLOUD_TRIAL_FAST_RESPONSE_MODEL?.trim();
|
|
return raw ? stripOpenRouterPrefix(raw) : FAST_RESPONSE_DEFAULT_MODEL;
|
|
}
|
|
|
|
function configuredMigrationTargets(): CloudTrialMigrationTargetOverrides {
|
|
return parseCloudTrialMigrationTargetsEnv(env.PAPERCLIP_CLOUD_TRIAL_MIGRATION_TARGETS);
|
|
}
|
|
|
|
function configuredLocalLimitCents(): number {
|
|
const raw = env.PAPERCLIP_CLOUD_TRIAL_LIMIT_USD_CENTS?.trim();
|
|
if (!raw) return CLOUD_TRIAL_DEFAULT_LIMIT_USD_CENTS;
|
|
const parsed = Number.parseInt(raw, 10);
|
|
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : CLOUD_TRIAL_DEFAULT_LIMIT_USD_CENTS;
|
|
}
|
|
|
|
async function fetchKeyFromCloudOrLocal(forceRefresh = false): Promise<CachedCloudKeyState> {
|
|
if (!forceRefresh && cached) {
|
|
if (cached.status === "exhausted" || cached.status === "disabled" || cached.status === "ineligible") {
|
|
return cached;
|
|
}
|
|
if (cached.status === "active" && cached.apiKey) {
|
|
return cached;
|
|
}
|
|
}
|
|
|
|
// Local/dev override (allows running E2E and live key tests without Cloud Harness).
|
|
const localKey = env.PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY?.trim();
|
|
if (localKey) {
|
|
const limitUsdCents = configuredLocalLimitCents();
|
|
const priorSpent = cached?.spentUsdCents ?? 0;
|
|
const exhausted = cached?.status === "exhausted" || (limitUsdCents > 0 && priorSpent >= limitUsdCents);
|
|
cached = {
|
|
status: exhausted ? "exhausted" : "active",
|
|
apiKey: exhausted ? null : localKey,
|
|
limitUsdCents,
|
|
spentUsdCents: priorSpent,
|
|
remainingUsdCents: exhausted ? 0 : Math.max(0, limitUsdCents - priorSpent),
|
|
defaultModel: configuredDefaultModel(),
|
|
fetchedAtMs: now(),
|
|
lastUsageProbeAtMs: cached?.lastUsageProbeAtMs ?? 0,
|
|
};
|
|
maybeTrackKeyIssued(cached);
|
|
return cached;
|
|
}
|
|
|
|
const context = getCloudStackContext(env);
|
|
if (!context?.cloudOrigin || !context.stackId) {
|
|
return {
|
|
status: "unavailable",
|
|
reason: "cloud_not_configured",
|
|
apiKey: null,
|
|
limitUsdCents: 0,
|
|
spentUsdCents: 0,
|
|
remainingUsdCents: 0,
|
|
defaultModel: configuredDefaultModel(),
|
|
fetchedAtMs: now(),
|
|
lastUsageProbeAtMs: 0,
|
|
};
|
|
}
|
|
|
|
if (inflightFetch) return inflightFetch;
|
|
inflightFetch = (async () => {
|
|
const pathname = "/v1/tenant/inference-key";
|
|
const url = new URL(pathname, context.cloudOrigin!);
|
|
const response = await fetchImpl(url, {
|
|
method: "POST",
|
|
headers: {
|
|
...buildCloudStackAuthHeaders(env, "POST", pathname, context.stackId!),
|
|
"content-type": "application/json",
|
|
},
|
|
body: JSON.stringify({ refreshUsage: forceRefresh }),
|
|
signal: AbortSignal.timeout(10_000),
|
|
});
|
|
if (!response.ok) {
|
|
throw new HttpError(502, `Cloud inference key request failed (HTTP ${response.status})`, {
|
|
code: "cloud_inference_fetch_failed",
|
|
});
|
|
}
|
|
const payload = readJsonRecord(await response.json());
|
|
const status = typeof payload.status === "string" ? (payload.status as CloudTrialInferenceState) : "unavailable";
|
|
const limitUsdCents =
|
|
typeof payload.limitUsdCents === "number" && Number.isFinite(payload.limitUsdCents)
|
|
? Math.max(0, Math.round(payload.limitUsdCents))
|
|
: 0;
|
|
const spentUsdCents =
|
|
typeof payload.spentUsdCents === "number" && Number.isFinite(payload.spentUsdCents)
|
|
? Math.max(0, Math.round(payload.spentUsdCents))
|
|
: 0;
|
|
const remainingUsdCents =
|
|
typeof payload.remainingUsdCents === "number" && Number.isFinite(payload.remainingUsdCents)
|
|
? Math.max(0, Math.round(payload.remainingUsdCents))
|
|
: Math.max(0, limitUsdCents - spentUsdCents);
|
|
const apiKey = status === "active" && typeof payload.apiKey === "string" && payload.apiKey.trim()
|
|
? payload.apiKey.trim()
|
|
: null;
|
|
if (typeof payload.onboardingVariant === "string" && payload.onboardingVariant.trim()) {
|
|
const variant = normalizeOnboardingVariant(payload.onboardingVariant);
|
|
const trialEnabled =
|
|
isFreeInferenceOnboardingVariant(variant) || status === "active" || status === "exhausted";
|
|
cachedOnboardingConfig = {
|
|
onboardingVariant: variant,
|
|
trialInferenceEnabled: trialEnabled,
|
|
source: "cloud",
|
|
fetchedAtMs: now(),
|
|
};
|
|
syncResolvedCohort(variant, trialEnabled);
|
|
}
|
|
cached = {
|
|
status,
|
|
reason: typeof payload.reason === "string" ? payload.reason : undefined,
|
|
apiKey,
|
|
limitUsdCents,
|
|
spentUsdCents,
|
|
remainingUsdCents,
|
|
defaultModel: resolveCloudTrialModel(typeof payload.defaultModel === "string" ? payload.defaultModel : undefined),
|
|
fetchedAtMs: now(),
|
|
lastUsageProbeAtMs: now(),
|
|
};
|
|
maybeTrackKeyIssued(cached);
|
|
return cached;
|
|
})().finally(() => {
|
|
inflightFetch = null;
|
|
});
|
|
return inflightFetch;
|
|
}
|
|
|
|
async function reportExhaustedToCloud(spentUsdCents: number, reason: string): Promise<void> {
|
|
const context = getCloudStackContext(env);
|
|
if (!context?.cloudOrigin || !context.stackId) return;
|
|
try {
|
|
const pathname = "/v1/tenant/inference-key/exhausted";
|
|
const url = new URL(pathname, context.cloudOrigin);
|
|
await fetchImpl(url, {
|
|
method: "POST",
|
|
headers: {
|
|
...buildCloudStackAuthHeaders(env, "POST", pathname, context.stackId),
|
|
"content-type": "application/json",
|
|
},
|
|
body: JSON.stringify({ spentUsdCents, reason }),
|
|
signal: AbortSignal.timeout(8_000),
|
|
});
|
|
} catch (err) {
|
|
logger.warn({ err }, "Failed to report Cloud trial inference exhaustion to Cloud Harness");
|
|
}
|
|
}
|
|
|
|
async function markExhausted(input: {
|
|
companyId?: string;
|
|
agentId?: string;
|
|
runId?: string;
|
|
spentUsdCents?: number;
|
|
reason?: string;
|
|
}): Promise<void> {
|
|
const limitUsdCents = cached?.limitUsdCents ?? configuredLocalLimitCents();
|
|
const spentUsdCents = Math.max(
|
|
cached?.spentUsdCents ?? 0,
|
|
input.spentUsdCents ?? limitUsdCents,
|
|
);
|
|
cached = {
|
|
status: "exhausted",
|
|
reason: input.reason ?? "budget_exhausted",
|
|
apiKey: null,
|
|
limitUsdCents,
|
|
spentUsdCents,
|
|
remainingUsdCents: 0,
|
|
defaultModel: cached?.defaultModel ?? configuredDefaultModel(),
|
|
fetchedAtMs: now(),
|
|
lastUsageProbeAtMs: now(),
|
|
};
|
|
onExhaustedHook?.();
|
|
|
|
if (!exhaustedTracked) {
|
|
exhaustedTracked = true;
|
|
exhaustedAtMs = now();
|
|
const elapsedSeconds =
|
|
keyIssuedAtMs !== null ? Math.max(0, Math.round((exhaustedAtMs - keyIssuedAtMs) / 1000)) : undefined;
|
|
trackCloudPostHogEvent(
|
|
"cloud_trial.exhausted",
|
|
{
|
|
reason: input.reason ?? "budget_exhausted",
|
|
spent_usd_cents: spentUsdCents,
|
|
limit_usd_cents: limitUsdCents,
|
|
runs_count: trialRunsCount,
|
|
...(elapsedSeconds !== undefined ? { elapsed_seconds: elapsedSeconds } : {}),
|
|
},
|
|
input.companyId ? { companyId: input.companyId } : undefined,
|
|
);
|
|
}
|
|
|
|
await reportExhaustedToCloud(spentUsdCents, input.reason ?? "budget_exhausted");
|
|
|
|
if (input.companyId) {
|
|
const heldIssues = getHeldIssues(input.companyId);
|
|
publishLiveEvent({
|
|
companyId: input.companyId,
|
|
type: "cloud_trial.status.updated",
|
|
payload: {
|
|
status: "exhausted",
|
|
gateReason: "exhausted",
|
|
llmBlocked: true,
|
|
heldIssueCount: heldIssues.length,
|
|
limitUsdCents,
|
|
spentUsdCents,
|
|
remainingUsdCents: 0,
|
|
reason: input.reason ?? "budget_exhausted",
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
async function probeOpenRouterUsage(companyId?: string, force = false): Promise<void> {
|
|
if (!cached || cached.status !== "active" || !cached.apiKey) return;
|
|
const current = now();
|
|
if (!force && current - cached.lastUsageProbeAtMs < USAGE_PROBE_MIN_INTERVAL_MS) return;
|
|
cached.lastUsageProbeAtMs = current;
|
|
try {
|
|
const response = await fetchImpl(`${upstreamBaseUrl()}/key`, {
|
|
method: "GET",
|
|
headers: {
|
|
accept: "application/json",
|
|
authorization: `Bearer ${cached.apiKey}`,
|
|
},
|
|
signal: AbortSignal.timeout(8_000),
|
|
});
|
|
if (response.status === 402 || response.status === 403) {
|
|
await markExhausted({ companyId, reason: `openrouter_key_probe_${response.status}` });
|
|
return;
|
|
}
|
|
if (!response.ok) return;
|
|
const body = readJsonRecord(await response.json());
|
|
const data = readJsonRecord(body.data);
|
|
const limitUsd = typeof data.limit === "number" && Number.isFinite(data.limit) ? data.limit : null;
|
|
const usageUsd = typeof data.usage === "number" && Number.isFinite(data.usage) ? data.usage : null;
|
|
const remainingUsd =
|
|
typeof data.limit_remaining === "number" && Number.isFinite(data.limit_remaining)
|
|
? data.limit_remaining
|
|
: limitUsd !== null && usageUsd !== null
|
|
? Math.max(0, limitUsd - usageUsd)
|
|
: null;
|
|
|
|
if (limitUsd !== null) cached.limitUsdCents = Math.max(0, Math.round(limitUsd * 100));
|
|
if (usageUsd !== null) cached.spentUsdCents = Math.max(cached.spentUsdCents, Math.round(usageUsd * 100));
|
|
if (remainingUsd !== null) {
|
|
cached.remainingUsdCents = Math.max(0, Math.round(remainingUsd * 100));
|
|
if (remainingUsd <= 0) {
|
|
await markExhausted({
|
|
companyId,
|
|
spentUsdCents: cached.limitUsdCents,
|
|
reason: "openrouter_limit_remaining_zero",
|
|
});
|
|
}
|
|
}
|
|
} catch (err) {
|
|
logger.debug({ err }, "OpenRouter trial key usage probe failed");
|
|
}
|
|
}
|
|
|
|
return {
|
|
env,
|
|
fetchImpl,
|
|
now,
|
|
getCached: () => cached,
|
|
getExhaustedAtMs: () => exhaustedAtMs,
|
|
setOnExhausted: (hook: (() => void) | undefined) => {
|
|
onExhaustedHook = hook;
|
|
},
|
|
recordRunPrepared: () => {
|
|
trialRunsCount += 1;
|
|
},
|
|
upstreamBaseUrl,
|
|
configuredDefaultModel,
|
|
configuredFastResponseModel,
|
|
configuredMigrationTargets,
|
|
fetchKeyFromCloudOrLocal,
|
|
fetchOnboardingConfig,
|
|
fallbackOnboardingConfig,
|
|
getCachedOnboardingConfig: () => cachedOnboardingConfig,
|
|
getHeldIssues,
|
|
holdIssue,
|
|
clearHeldIssues,
|
|
removeHeldIssue,
|
|
getGateReason,
|
|
markExhausted,
|
|
probeOpenRouterUsage,
|
|
_resetForTests: () => {
|
|
cached = null;
|
|
inflightFetch = null;
|
|
cachedOnboardingConfig = null;
|
|
inflightOnboardingConfigFetch = null;
|
|
heldIssuesByCompany.clear();
|
|
keyIssuedTracked = false;
|
|
keyIssuedAtMs = null;
|
|
trialRunsCount = 0;
|
|
exhaustedTracked = false;
|
|
exhaustedAtMs = null;
|
|
},
|
|
};
|
|
}
|
|
|
|
export type CloudTrialKeyStore = ReturnType<typeof createCloudTrialKeyStore>;
|