Files
PaperClipAI/server/src/services/cloud-trial-key-store.ts
T
DottaandPaperclip 689bfd04ac feat(onboarding): add free_inference_1 onboarding flow, dual-trigger model gate, and multi-variant PostHog attribution (#23401)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - First-time Cloud users currently must connect an external AI
provider during onboarding before they can talk to their first agent.
> - Requiring provider setup up front adds friction before users
experience their first agent chat.
> - Paperclip needs a multi-variant onboarding experiment
(`onboarding-flow`) that defaults to `baseline` while allowing an
alternate `free_inference_1` path that skips the model-connection screen
and starts with capped starter inference.
> - When a trial-only workspace either exhausts its starter credit or
creates its first executable task or subtask, Paperclip must hold the
new task, prompt the user to connect a model provider, keep LLM actions
blocked if the modal is dismissed, and automatically resume held work
once a model is connected.
> - This pull request adds multi-variant onboarding resolution, PostHog
multi-variant attribution, dual-trigger connect-model gating with
restart-safe DB hydration, the `free_inference_1` UI onboarding flow,
and full-flow Storybooks.
> - The benefit is a safe, measurable onboarding experiment that leaves
`baseline` and self-hosted installs unchanged while letting opted-in
Cloud workspaces reach their first chat immediately and upgrade
seamlessly when real work begins.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/shared/`, `server/`, `ui/`)

**Problem or motivation**

New Cloud users currently hit a mandatory "Connect a model" step during
onboarding before they can open their first agent chat. Existing
trial-inference gating only supported a binary flag and only triggered
on starter-credit exhaustion, not on subtask or manual task creation,
and did not track multi-variant onboarding cohorts cleanly in PostHog.

**Proposed solution**

Introduce the extensible `onboarding-flow` experiment (`baseline`
default, `free_inference_1` variant) across shared contracts, server
services, and UI:
- Resolve `onboardingVariant` from the Cloud control plane (`GET
/v1/tenant/onboarding-config`) with safe fallbacks to
`PAPERCLIP_ONBOARDING_VARIANT`, managed config, and `"baseline"`.
- In `free_inference_1`, skip Step 4 ("Connect a model") in
`OnboardingWizard`, hire the first agent on starter inference, and drop
the user straight into the first chat.
- Support a dual-trigger connect-model gate (`exhausted` and
`work_requires_model`) that holds newly created tasks/subtasks on
trial-only workspaces (hydrated from DB across restarts), returns HTTP
402 for blocked LLM chat/runs, keeps the modal dismissible while
blocking chat composers with a "Connect a model" CTA banner, and
automatically resumes held work after provider migration.
- Stamp `$feature/onboarding-flow`, `onboarding_variant`, and immutable
`initial_onboarding_variant` across server PostHog events,
`$groupidentify` (with top-level `$group_set_once`), and browser PostHog
super-properties / `identify()`.

**Alternatives considered**

- Baking per-stack experiment variants into warm-pool container config
was ruled out because warm-pool stacks must remain homogeneous until
claim time.
- Failing agent subtask creation calls on trial-only workspaces was
ruled out because it breaks the agent's first-chat experience; creating
the task in a held state and auto-resuming it after model connection
preserves user intent.

## What Changed

- **`packages/shared`**: Added `onboarding-flow` variant
constants/helpers, `CloudTrialGateReason` (`"exhausted" |
"work_requires_model"`), `CloudTrialHeldIssueSummary`, `gateReason`,
`llmBlocked`, `heldIssueIds`, `heldIssues`, `onboardingVariant`, and
`resumedIssueIds` on cloud-inference and session/browser-analytics
contracts.
- **`server/`**:
- Added Ed25519-signed `GET /v1/tenant/onboarding-config` resolution
with warm-pool claim cache invalidation and safe `"baseline"` default.
- Added dual-trigger trial gating (`exhausted` + `work_requires_model`)
with DB-backed held-issue hydration across restarts, HTTP 402 refusal
for blocked trial runs and chat sends, and automatic wake/resume of held
subtasks upon migration.
- Updated PostHog server telemetry, `$groupidentify` (top-level
`$group_set` and `$group_set_once`), `$feature_flag_called`, and
`BrowserAnalyticsConfig` to stamp `onboarding-flow` multi-variant
properties while preserving backwards-compatible `cloud-trial-inference`
properties.
- Added and updated Vitest suites covering multi-variant resolution,
PostHog attribution, held subtask creation, cold-restart hydration, LLM
run refusal, and auto-resume.
- **`ui/`**:
- Updated `OnboardingWizard` so `free_inference_1` skips Step 4
("Connect a model"), auto-hires with `cloudTrialInference: true`, and
launches straight into the first chat while leaving `baseline`
unchanged.
- Updated `CloudTrialGate` and `CloudTrialExhaustedModal` for
dual-trigger copy (`work_requires_model` vs `exhausted`), waiting
subtask pills, and dismissible modal behavior (`required={false}`).
- Added `CloudTrialBlockedBanner` and wired LLM-blocked composer
disabling + "Connect a model" CTA into `IssueDetail` / `AgentChat` and
`DashboardChatComposer`, plus status refresh on manual task creation in
`NewIssueDialog`.
- Updated `product-analytics.ts` + tests to register
`$feature/onboarding-flow` and `onboarding_variant` super-properties and
`$set_once.initial_onboarding_variant`.
- Added full-flow Storybooks
(`free-inference-onboarding-flow.stories.tsx`) covering all 7 onboarding
and gate states.

## Verification

- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck` (0 errors)
- `pnpm --filter @paperclipai/ui typecheck` (0 errors)
- 9 targeted server Vitest suites (`cloud-trial-inference`,
`cloud-posthog-config`, `cloud-posthog-browser`,
`posthog-direct-telemetry`, `posthog-direct-transport`, `auth-routes`,
`cloud-runtime-identity`, `onboarding-seed-route`,
`issue-onboarding-first-task-routes`): 196/196 passed
- 4 targeted UI Vitest suites (`CloudTrialGate.test.tsx`,
`product-analytics.test.ts`, `onboarding-analytics.test.tsx`,
`Layout.mobile.test.tsx`): 37/37 passed
- `pnpm --filter @paperclipai/ui build` and `pnpm --filter
@paperclipai/ui build-storybook`: passed
- Visually inspected Storybook renders across all 7 `free_inference_1`
states in headless Chromium via Playwright with zero page errors.

## Risks

- Low risk to existing users: `onboardingVariant` defaults to
`"baseline"` everywhere, leaving self-hosted installs and unflagged
Cloud stacks unchanged.
- No database schema migrations are required; held trial subtasks are
hydrated from existing `issues` and `toolConnections` tables on restart.
- Requires the companion `paperclip-cloud` control-plane endpoint (`GET
/v1/tenant/onboarding-config`) to activate non-baseline variants in
Cloud; falls back safely to `"baseline"` if unavailable.

## Model Used

- Google Gemini (Antigravity agentic coding environment with multi-agent
swarm, tool use, code execution, and Playwright Storybook verification)

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 20:54:03 +00:00

663 lines
23 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,
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 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,
configuredMigrationTargets,
fetchKeyFromCloudOrLocal,
fetchOnboardingConfig,
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>;