mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
feat(cloud): add Cloud starter inference proxy, migration modal, and PostHog A/B telemetry (#22966)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Hosted Cloud onboarding currently requires new users to connect a model provider subscription or API key before their first agent can run > - That upfront credential step creates drop-off before a new user sees their first agent do real work > - We need an opt-in, managed Cloud capability that runs the first agent right away through a server-side proxy, keeps the raw provider key out of sandboxes and browsers, prompts the user to connect their own provider when starter inference runs out, and measures treatment vs. control in PostHog > - This pull request adds the default-off `enableCloudTrialInference` managed feature, the server-side OpenRouter reverse proxy with ephemeral per-run tokens, the blocking model-connection and agent-migration modal with Storybook stories, and Cloud-only PostHog A/B cohort and funnel telemetry > - The benefit is zero-friction first-agent onboarding on Cloud stacks enrolled in the experiment, with automatic migration to the user's own model provider and clean A/B observability ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (`packages/shared`, `packages/paperclip-runner`, `server/`, `ui/`) **Problem or motivation** New Cloud users must connect an AI subscription or API key before they can run their first agent. We want to A/B test letting eligible Cloud workspaces start their first agent right away with managed starter inference (OpenCode / GPT-6 Luna in Paperclip Runner) without exposing any raw upstream API key to the sandbox, database, or browser, and then guide the user to connect their own model provider when starter inference runs out. **Proposed solution** Add an experimental managed feature flag (`enableCloudTrialInference`, off by default on both Cloud and self-hosted) that: - Routes starter-inference runs through a server-side OpenRouter reverse proxy (`/api/internal/cloud-inference/v1/*`) authenticated with ephemeral per-run bearer tokens so the raw OpenRouter key never leaves server memory. - Enforces the configured starter model, detects upstream HTTP 402 exhaustion, invalidates active run tokens, reports exhaustion back to the Cloud control plane, and broadcasts `cloud_trial.status.updated` over live events. - Displays a blocking modal (`CloudTrialExhaustedModal`) when starter inference runs out while agents still depend on it, lets the user connect their own model provider, automatically migrates trial agents to that provider's default harness and model, clears incompatible provider sessions, and resumes paused work. - Stamps the `cloud-trial-inference` (`treatment` / `control`) cohort onto Cloud-only server and browser PostHog telemetry and records Cloud-only funnel events (`$feature_flag_called`, `cloud_trial.started`, `cloud_trial.key_issued`, `cloud_trial.exhausted`, `cloud_trial.modal_shown`, `cloud_trial.migrated`, `cloud_trial.migration_failed`) without affecting self-hosted telemetry. **Alternatives considered** - Passing a capped OpenRouter API key directly into the agent sandbox environment: rejected because a sandboxed agent or user could read and reuse the raw key outside Paperclip. - Showing starter dollar amounts or a usage progress bar in the UI: rejected in favor of a simple prompt asking the user to connect a model provider to continue. **Roadmap alignment** Supports hosted onboarding activation experiments while staying strictly gated behind a default-off managed feature flag (`cloudDefault: false`, `selfHostedDefault: false`) so self-hosted installs and unflagged Cloud stacks see zero behavior change. **Additional context** Paired with the private Cloud control plane key-management service PR that provisions per-stack capped OpenRouter child keys and enforces single-trial caps across accounts. ## What Changed - **Shared contracts & feature flag (`packages/shared`)**: - Added `enableCloudTrialInference` (`tier: "managed"`, `cloudDefault: false`, `selfHostedDefault: false`) to `feature-catalog.ts`, `types/instance.ts`, and `validators/instance.ts`. - Added `packages/shared/src/cloud-inference.ts` with trial status types, migration schemas, provider-to-harness migration defaults, and telemetry event validation. - Added `cloud_trial.status.updated` to `LIVE_EVENT_TYPES`, `cloudTrialInference` to `agentRuntimeConfigSchema`, and optional `cloudTrialInferenceEnabled` to `browserAnalyticsConfigSchema`. - **Paperclip Runner (`packages/paperclip-runner`)**: - Updated OpenCode server driver (`opencode-server-driver.ts`) and `configured-environment.ts` to accept `PAPERCLIP_OPENROUTER_PROXY_URL` and `PAPERCLIP_OPENROUTER_PROXY_TOKEN`. - Updated `provider-failure.ts` to classify HTTP 402 as quota exhaustion and redact `sk-or-` key material. - **Server proxy, migration, and onboarding (`server/`)**: - Added `server/src/services/cloud-trial-inference.ts` and `server/src/routes/cloud-inference.ts` for server-memory key custody, ephemeral per-run proxy tokens, model guard, HTTP 402 exhaustion handling, agent migration, blocked-run resume, and company-scoped status/migrate/telemetry routes. - Wired proxy mounting in `server/src/app.ts`, runtime env & cleanup in `heartbeat.ts` / `execution-configuration.ts`, `cloud_trial_exhausted` error code in `run-completion.ts`, and starter-agent seeding in `onboarding-seed.ts`. - **PostHog A/B telemetry (`server/`, `ui/`)**: - Resolved `cloudTrialInferenceEnabled` from `PAPERCLIP_MANAGED_CONFIG` in `cloud-posthog-config.ts` and `cloud-posthog-browser.ts`. - Stamped `cloud_trial_inference_enabled` and `$feature/cloud-trial-inference` on `workspace` groups, `cloud.workspace_started`, direct server PostHog events, and browser PostHog super-properties plus `$set_once.cloud_trial_inference_cohort`. - Added Cloud-only direct PostHog helpers (`trackCloudPostHogEvent`, `trackCloudTrialExposure`) in `server/src/telemetry.ts` and wired exposure + lifecycle funnel events (no-op on self-hosted). - **UI & Storybook (`ui/`)**: - Added `ui/src/api/cloud-inference.ts`, `CloudTrialExhaustedModal.tsx`, `CloudTrialGate.tsx`, and optional `hideCancel` / `hideProviderHeading` props on `AiProviderSetup.tsx`. - Wired `CloudTrialGate` into `Layout.tsx` / `Layout.production.tsx`, live-event invalidation into `LiveUpdatesProvider.tsx`, starter onboarding card into `OnboardingWizard.tsx`, and the experimental card into `InstanceExperimentalSettings.tsx`. - Added Storybook stories in `ui/storybook/stories/onboarding/cloud-trial-exhausted-modal.stories.tsx` covering single agent, multiple agents, migrating, migration succeeded, and migration error states. ## Verification - `pnpm --filter @paperclipai/shared build`: passed. - `pnpm --filter @paperclipai/paperclip-runner build`: passed (TypeScript, protocol manifest, Cargo release build, replay golden parity). - `pnpm --filter @paperclipai/ui typecheck` & `node scripts/storybook-catalog.mjs --check`: passed (372 files, 3484 stories). - `pnpm --filter @paperclipai/server exec tsc --noEmit`: passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/cloud-trial-inference.test.ts src/__tests__/cloud-posthog-config.test.ts src/__tests__/cloud-posthog-browser.test.ts src/__tests__/posthog-direct-event-shape.test.ts src/__tests__/posthog-direct-telemetry.test.ts src/__tests__/auth-routes.test.ts`: 6 files, 144/144 passed. - `pnpm --filter @paperclipai/ui exec vitest run src/lib/analytics/product-analytics.test.ts src/lib/analytics/product-analytics-events.test.ts`: 2 files, 14/14 passed. - Verified Storybook stories interactively in the embedded browser (`ExhaustedSingleAgent`, `ExhaustedMultipleAgents`, `MigrationSucceeded`) with passing `play()` interactions and zero console errors, plus live end-to-end onboarding → exhaustion → blocking modal → provider connect → agent migration flow against a mock OpenRouter server. ## Risks - **Default-off isolation**: `enableCloudTrialInference` defaults to `false` everywhere, and Cloud stacks hide `instance.experimental.*` controls by default, so existing self-hosted and unflagged Cloud stacks have zero behavior change. - **Key custody boundary**: Raw OpenRouter keys stay strictly in server process memory; sandboxes only receive short-lived per-run proxy tokens invalidated on run exit or exhaustion. - **PostHog direct contract**: Existing self-hosted collector envelopes remain unchanged; `posthog-direct-event-shape.test.ts` and `product-analytics-events.test.ts` verify event shape and ownership invariants. - **CI coverage**: Broad workspace suites and E2E lanes were not run locally and will run on PR CI. ## Model Used - Google Gemini (Antigravity agentic assistant) with code editing, terminal execution, browser verification, and test tools. ## 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
9cfc80b340
commit
64bef50be0
63 files changed
+4295
-52
No files matched your search
@@ -0,0 +1,160 @@
|
||||
---
|
||||
title: Cloud Starter Inference
|
||||
summary: Inspect Cloud starter-inference status, migrate trial agents to a connected provider, and record onboarding funnel telemetry
|
||||
---
|
||||
|
||||
These company-scoped endpoints support Paperclip Cloud starter inference when the
|
||||
`enableCloudTrialInference` instance experimental setting is enabled. Every
|
||||
endpoint requires a board session with active membership in `{companyId}`. Agent
|
||||
API keys cannot call them. Responses use `Cache-Control: no-store`.
|
||||
|
||||
## Get Cloud Inference Status
|
||||
|
||||
```
|
||||
GET /api/companies/{companyId}/cloud-inference/status?refresh=true
|
||||
```
|
||||
|
||||
Returns the company's starter-inference state, trial-bound agents, and whether
|
||||
the caller can migrate them.
|
||||
|
||||
### Query Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `refresh` | `"1"` \| `"true"` | — | When set, refreshes key usage from Paperclip Cloud and OpenRouter before responding |
|
||||
|
||||
### Permissions
|
||||
|
||||
- Authenticated board user with access to `{companyId}` (viewers may read status; `canMigrate` is `false` for viewers or users without agent configuration authority).
|
||||
|
||||
### Response (`200 OK`)
|
||||
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"provider": "openrouter",
|
||||
"status": "active",
|
||||
"limitUsdCents": 100,
|
||||
"spentUsdCents": 12,
|
||||
"remainingUsdCents": 88,
|
||||
"defaultModel": "openrouter/openai/gpt-6-luna",
|
||||
"canMigrate": true,
|
||||
"trialAgentIds": ["11111111-1111-4111-8111-111111111111"],
|
||||
"trialAgents": [
|
||||
{
|
||||
"id": "11111111-1111-4111-8111-111111111111",
|
||||
"name": "Nova",
|
||||
"role": "ceo",
|
||||
"title": "Chief of Staff"
|
||||
}
|
||||
],
|
||||
"blockedRun": null
|
||||
}
|
||||
```
|
||||
|
||||
`status` is one of `unavailable`, `not_issued`, `active`, `exhausted`,
|
||||
`disabled`, `ineligible`, or `migrated`. `blockedRun` is either `null` or
|
||||
`{ runId, agentId, issueId, failedAt }` when a trial agent's latest run failed
|
||||
due to starter-inference exhaustion.
|
||||
|
||||
## Migrate Trial Agents
|
||||
|
||||
```
|
||||
POST /api/companies/{companyId}/cloud-inference/migrate
|
||||
```
|
||||
|
||||
Moves non-terminated, non-pending trial agents in `{companyId}` off Cloud
|
||||
starter inference onto a connected user or shared AI connection, clears
|
||||
incompatible task sessions, ensures connection install access, and optionally
|
||||
resumes the latest blocked run.
|
||||
|
||||
### Permissions
|
||||
|
||||
- Authenticated board user with company access (non-viewer, unless instance admin).
|
||||
- Must hold `agent_config:update` (or setup-draft creator authority) for every target trial agent.
|
||||
- Personal grants may only be used by their owner; adding missing agent installs requires `connections:configure` (or self-service ownership of a personal grant).
|
||||
|
||||
### Request Body
|
||||
|
||||
```json
|
||||
{
|
||||
"connectionId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
"grantId": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||
"provider": "anthropic",
|
||||
"method": "subscription",
|
||||
"ownership": "personal",
|
||||
"model": "claude-sonnet-4-6",
|
||||
"agentIds": ["11111111-1111-4111-8111-111111111111"],
|
||||
"resumeBlockedWork": true
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `connectionId` | UUID | Yes | Active company AI `tool_connections` ID |
|
||||
| `grantId` | UUID | Yes | Active `connection_grants` ID belonging to `connectionId` |
|
||||
| `provider` | `"openai"` \| `"anthropic"` \| `"google"` \| `"xai"` \| `"openrouter"` \| `"github"` | Yes | Connected AI provider |
|
||||
| `method` | `"subscription"` \| `"api_key"` | Yes | Authentication method |
|
||||
| `ownership` | `"personal"` \| `"shared"` | No (default `"personal"`) | Personal delegated vs. shared org binding |
|
||||
| `model` | string (1–200 chars) | No | Optional model override (defaults come from deployment config or provider defaults) |
|
||||
| `agentIds` | UUID[] (max 200) | No | Optional subset of trial agent IDs to migrate; omits to migrate all eligible trial agents |
|
||||
| `resumeBlockedWork` | boolean | No (default `true`) | Whether to wake the latest exhaustion-blocked run after migration |
|
||||
|
||||
### Response (`200 OK`)
|
||||
|
||||
```json
|
||||
{
|
||||
"migratedCount": 1,
|
||||
"agents": [
|
||||
{
|
||||
"agentId": "11111111-1111-4111-8111-111111111111",
|
||||
"name": "Nova",
|
||||
"adapterType": "paperclip_runner",
|
||||
"runnerProvider": "claude",
|
||||
"model": "claude-sonnet-4-6"
|
||||
}
|
||||
],
|
||||
"resumedRunIds": ["99999999-9999-4999-8999-999999999999"],
|
||||
"resumedIssueId": "33333333-3333-4333-8333-333333333333"
|
||||
}
|
||||
```
|
||||
|
||||
### Errors
|
||||
|
||||
| Status | Meaning |
|
||||
|--------|---------|
|
||||
| `400` | Validation error or selected AI connection is not active |
|
||||
| `403` | Viewer role, missing `agent_config:update`, another user's personal grant, or unauthorized connection install |
|
||||
| `404` | Selected AI connection grant was not found for `{companyId}` |
|
||||
|
||||
## Record Starter Inference Telemetry
|
||||
|
||||
```
|
||||
POST /api/companies/{companyId}/cloud-inference/telemetry
|
||||
```
|
||||
|
||||
Records Cloud-only PostHog funnel events (no-op on self-hosted instances).
|
||||
|
||||
### Request Body
|
||||
|
||||
Either an onboarding exposure event:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "onboarding_exposure",
|
||||
"surface": "onboarding_wizard"
|
||||
}
|
||||
```
|
||||
|
||||
or a connect-provider modal impression event:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "modal_shown",
|
||||
"trialAgentCount": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Response
|
||||
|
||||
`204 No Content`.
|
||||
@@ -131,6 +131,65 @@ describe("configured environment authority", () => {
|
||||
}
|
||||
} finally { vi.unstubAllEnvs(); }
|
||||
});
|
||||
|
||||
it("forwards explicit OpenRouter starter proxy credentials through runner spawn and OpenCode without ambient bleed", () => {
|
||||
const proxyEnv = {
|
||||
PAPERCLIP_OPENROUTER_PROXY_URL: "http://127.0.0.1:3100/api/internal/cloud-inference/v1",
|
||||
PAPERCLIP_OPENROUTER_PROXY_TOKEN: "pctrial_test_token_value",
|
||||
};
|
||||
const projected = configuredEnvironmentProjection({ ...proxyEnv, CUSTOM_FLAG: "ok" });
|
||||
expect(projected.PAPERCLIP_OPENROUTER_PROXY_URL).toBeUndefined();
|
||||
expect(projected.PAPERCLIP_OPENROUTER_PROXY_TOKEN).toBeUndefined();
|
||||
expect(JSON.parse(projected[CONFIGURED_ENVIRONMENT_KEYS]!)).toEqual(["CUSTOM_FLAG"]);
|
||||
|
||||
let launched: NodeJS.ProcessEnv | undefined;
|
||||
spawnRunner({
|
||||
connection: { mode: "connect", connectUrl: "ws://127.0.0.1:43127" },
|
||||
stateDirectory: "/tmp/runner-env-proof",
|
||||
identity,
|
||||
ticket: "fake-ticket",
|
||||
maxOutboxBytes: 262144,
|
||||
p0ReserveBytes: 65536,
|
||||
runnerVersion: "0.3.0",
|
||||
runnerDigest: `sha256:${"a".repeat(64)}`,
|
||||
environment: { ...projected, ...proxyEnv, PATH: "/bin" },
|
||||
processLauncher: (spec) => {
|
||||
launched = spec.environment;
|
||||
return {
|
||||
child: { pid: 42, exitCode: null, signalCode: null, kill: () => true },
|
||||
completion: Promise.resolve({ code: 0, signal: null, stdout: "", stderr: "" }),
|
||||
};
|
||||
},
|
||||
});
|
||||
expect(launched).toMatchObject(proxyEnv);
|
||||
|
||||
const prepared = createCapabilityRunnerdProviderEnvironment({
|
||||
provider: "opencode",
|
||||
options: { environment: { ...projected, ...proxyEnv, PATH: "/bin" } },
|
||||
identity,
|
||||
codexHome: "/isolated/home",
|
||||
runtimeContextPath: "/isolated/context",
|
||||
hasRuntimeContext: false,
|
||||
});
|
||||
expect(prepared).toMatchObject(proxyEnv);
|
||||
|
||||
vi.stubEnv("PAPERCLIP_OPENROUTER_PROXY_URL", "http://ambient.invalid");
|
||||
vi.stubEnv("PAPERCLIP_OPENROUTER_PROXY_TOKEN", "pctrial_ambient");
|
||||
try {
|
||||
const ambientPrepared = createCapabilityRunnerdProviderEnvironment({
|
||||
provider: "opencode",
|
||||
options: { environment: {} },
|
||||
identity,
|
||||
codexHome: "/isolated/home",
|
||||
runtimeContextPath: "/isolated/context",
|
||||
hasRuntimeContext: false,
|
||||
});
|
||||
expect(ambientPrepared.PAPERCLIP_OPENROUTER_PROXY_URL).toBeUndefined();
|
||||
expect(ambientPrepared.PAPERCLIP_OPENROUTER_PROXY_TOKEN).toBeUndefined();
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("configured secret names", () => {
|
||||
|
||||
@@ -31,6 +31,7 @@ export const GENERATED_RUNTIME_ENVIRONMENT_KEYS: ReadonlySet<string> = new Set([
|
||||
"PAPERCLIP_AGENT_MESSAGE_KEY", "PAPERCLIP_HARNESS_CHECKOUT_KEY", "PAPERCLIP_EXTERNAL_CHAT_EXECUTION_BOUND_KEY",
|
||||
"PAPERCLIP_NATIVE_MCP_STDIO", "PAPERCLIP_NATIVE_MCP_PROXY",
|
||||
"PAPERCLIP_NATIVE_MCP_NAME", "PAPERCLIP_NATIVE_MCP_URL", "PAPERCLIP_NATIVE_MCP_TOKEN", "PAPERCLIP_AI_PROVIDER_KEY",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN",
|
||||
"PAPERCLIP_PROVIDER_TRACE_PATH", "PAPERCLIP_PROVIDER_TRACE_MAX_BYTES", "PAPERCLIP_ACPX_CREDENTIAL_BINDING",
|
||||
"PAPERCLIP_RUNNER_NETWORK_ACCESS", "PAPERCLIP_RUNNER_NETWORK_ROOTS", "PAPERCLIP_RUNNER_EXTERNAL_SANDBOX",
|
||||
"PAPERCLIP_GITHUB_AUTH_MODE", "PAPERCLIP_GITHUB_HOST_HOME", "PAPERCLIP_GIT_METADATA_ROOTS",
|
||||
|
||||
@@ -4945,6 +4945,8 @@ const runnerExplicitProviderEnvironmentKeys = [
|
||||
"PAPERCLIP_OPENCODE_PERMISSION_MODE",
|
||||
"PAPERCLIP_OPENCODE_RUNTIME_DIR",
|
||||
"PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_URL",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_TOKEN",
|
||||
"PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH",
|
||||
"PAPERCLIP_CURSOR_CLOUD_ARTIFACT_ROOT",
|
||||
"PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH",
|
||||
|
||||
@@ -368,6 +368,7 @@ export class OpenCodeServerDriver implements HarnessDriver {
|
||||
reason: redact(String(error), [
|
||||
this.#options.environment?.OPENROUTER_API_KEY,
|
||||
this.#options.environment?.PAPERCLIP_AI_PROVIDER_KEY,
|
||||
this.#options.environment?.PAPERCLIP_OPENROUTER_PROXY_TOKEN,
|
||||
]),
|
||||
};
|
||||
}
|
||||
@@ -2712,6 +2713,7 @@ async function startRuntime(input: {
|
||||
bridge.secret,
|
||||
providerEnvironment.OPENROUTER_API_KEY,
|
||||
providerEnvironment.PAPERCLIP_AI_PROVIDER_KEY,
|
||||
providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN,
|
||||
].filter((value): value is string => Boolean(value));
|
||||
input.trace?.addSensitiveValues(sensitiveValues);
|
||||
// Configured secrets must never reach OpenCode's captured tool output, its
|
||||
@@ -2743,7 +2745,12 @@ async function startRuntime(input: {
|
||||
const [modelProvider, ...modelIdParts] = input.options.model.split("/");
|
||||
const providerModelId = modelIdParts.join("/");
|
||||
const providerRoute = modelProvider === "openrouter"
|
||||
? { baseUrl: "https://openrouter.ai/api/v1", key: providerEnvironment.OPENROUTER_API_KEY ?? "" }
|
||||
? providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL
|
||||
? {
|
||||
baseUrl: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_URL,
|
||||
key: providerEnvironment.PAPERCLIP_OPENROUTER_PROXY_TOKEN ?? "",
|
||||
}
|
||||
: { baseUrl: "https://openrouter.ai/api/v1", key: providerEnvironment.OPENROUTER_API_KEY ?? "" }
|
||||
: modelProvider === "paperclip" && input.options.environment?.PAPERCLIP_AI_PROVIDER_URL
|
||||
? { baseUrl: input.options.environment.PAPERCLIP_AI_PROVIDER_URL, key: input.options.environment.PAPERCLIP_AI_PROVIDER_KEY ?? "" }
|
||||
: null;
|
||||
|
||||
@@ -9,7 +9,7 @@ export function providerFailureMessage(message: string, environment: NodeJS.Proc
|
||||
if (secret) message = message.replaceAll(secret, "[REDACTED]");
|
||||
}
|
||||
return [...redactProviderDiagnostic(message)
|
||||
.replace(/\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9_]+)\b/g, "[REDACTED]")
|
||||
.replace(/\b(?:sk-(?:ant-|proj-|or-(?:v1-)?)?[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9_]+)\b/g, "[REDACTED]")
|
||||
.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "")]
|
||||
.slice(0, 4000).join("").trim();
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export function createProviderFailure(input: {
|
||||
}): ProviderFailure | null {
|
||||
const httpStatus = typeof input.httpStatus === "number" && Number.isInteger(input.httpStatus)
|
||||
&& input.httpStatus >= 400 && input.httpStatus <= 599 ? input.httpStatus : undefined;
|
||||
const category = input.category ?? (httpStatus === 429 ? "rate_limit" : httpStatus === 401 ? "authentication"
|
||||
const category = input.category ?? (httpStatus === 402 ? "quota_exhausted" : httpStatus === 429 ? "rate_limit" : httpStatus === 401 ? "authentication"
|
||||
: httpStatus === 403 ? "permission" : httpStatus === 503 || httpStatus === 529 ? "overloaded"
|
||||
: httpStatus === 408 || httpStatus === 504 ? "timeout" : "unknown");
|
||||
const retryAt = typeof input.retryAt === "string" && Number.isFinite(Date.parse(input.retryAt))
|
||||
|
||||
@@ -4042,13 +4042,21 @@ export const OPEN_CODE_RUNNER_ENVIRONMENT_KEYS = new Set([
|
||||
"WINDIR",
|
||||
"RUST_BACKTRACE",
|
||||
"OPENROUTER_API_KEY",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_URL",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_TOKEN",
|
||||
]);
|
||||
|
||||
function createSanitizedOpenCodeRunnerEnvironment(
|
||||
source: NodeJS.ProcessEnv | undefined,
|
||||
): NodeJS.ProcessEnv {
|
||||
const candidate = { ...process.env, ...source };
|
||||
for (const key of ["PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY"]) {
|
||||
for (const key of [
|
||||
"PAPERCLIP_AGENT_KEY_ID",
|
||||
"PAPERCLIP_AGENT_PUBLIC_KEY",
|
||||
"PAPERCLIP_AGENT_PRIVATE_KEY",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_URL",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_TOKEN",
|
||||
]) {
|
||||
delete candidate[key];
|
||||
if (source?.[key] !== undefined) candidate[key] = source[key];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import { z } from "zod";
|
||||
import { AI_PROVIDERS, type AiAuthMethod, type AiProvider } from "./ai-connections.js";
|
||||
|
||||
const CLOUD_TRIAL_AUTH_METHODS = ["subscription", "api_key"] as const;
|
||||
|
||||
export const CLOUD_TRIAL_EXHAUSTED_ERROR_CODE = "cloud_trial_exhausted" as const;
|
||||
export const CLOUD_TRIAL_DEFAULT_MODEL = "openrouter/openai/gpt-6-luna" as const;
|
||||
export const CLOUD_TRIAL_DEFAULT_LIMIT_USD_CENTS = 100 as const;
|
||||
|
||||
/**
|
||||
* Canonical starter-trial model normalizer used across onboarding seed, UI,
|
||||
* and server proxy/key-store so every layer agrees on the `openrouter/` prefix.
|
||||
*/
|
||||
export function resolveCloudTrialModel(raw?: string | null): string {
|
||||
const trimmed = raw?.trim();
|
||||
if (!trimmed) return CLOUD_TRIAL_DEFAULT_MODEL;
|
||||
return trimmed.startsWith("openrouter/") ? trimmed : `openrouter/${trimmed}`;
|
||||
}
|
||||
|
||||
export const CLOUD_TRIAL_INFERENCE_STATUSES = [
|
||||
"unavailable",
|
||||
"not_issued",
|
||||
"active",
|
||||
"exhausted",
|
||||
"disabled",
|
||||
"ineligible",
|
||||
"migrated",
|
||||
] as const;
|
||||
export type CloudTrialInferenceState = (typeof CLOUD_TRIAL_INFERENCE_STATUSES)[number];
|
||||
|
||||
export interface CloudTrialBlockedRunSummary {
|
||||
runId: string;
|
||||
agentId: string;
|
||||
issueId: string | null;
|
||||
failedAt: string;
|
||||
}
|
||||
|
||||
export interface CloudTrialInferenceStatus {
|
||||
enabled: boolean;
|
||||
provider: "openrouter";
|
||||
status: CloudTrialInferenceState;
|
||||
reason?: string;
|
||||
limitUsdCents: number;
|
||||
spentUsdCents: number;
|
||||
remainingUsdCents: number;
|
||||
defaultModel: string;
|
||||
/** Whether the requesting user has permission to migrate all trial agents in this company. */
|
||||
canMigrate: boolean;
|
||||
/** Non-terminated agents in this company currently configured to use Cloud starter inference. */
|
||||
trialAgentIds: string[];
|
||||
/** Human-readable summaries of trial-bound agents for modal copy. */
|
||||
trialAgents: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
title: string | null;
|
||||
}>;
|
||||
/** Most recent run blocked by trial exhaustion, if any. */
|
||||
blockedRun: CloudTrialBlockedRunSummary | null;
|
||||
}
|
||||
|
||||
export const migrateCloudTrialAgentsSchema = z
|
||||
.object({
|
||||
connectionId: z.string().uuid(),
|
||||
grantId: z.string().uuid(),
|
||||
provider: z.enum(AI_PROVIDERS),
|
||||
method: z.enum(CLOUD_TRIAL_AUTH_METHODS),
|
||||
ownership: z.enum(["personal", "shared"]).default("personal"),
|
||||
model: z.string().trim().min(1).max(200).optional(),
|
||||
agentIds: z.array(z.string().uuid()).max(200).optional(),
|
||||
resumeBlockedWork: z.boolean().default(true),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type MigrateCloudTrialAgentsInput = z.infer<typeof migrateCloudTrialAgentsSchema>;
|
||||
|
||||
export const cloudTrialTelemetryEventSchema = z.discriminatedUnion("event", [
|
||||
z.object({
|
||||
event: z.literal("onboarding_exposure"),
|
||||
surface: z.enum(["onboarding_wizard", "onboarding_seed"]).default("onboarding_wizard"),
|
||||
}).strict(),
|
||||
z.object({
|
||||
event: z.literal("modal_shown"),
|
||||
trialAgentCount: z.number().int().nonnegative().max(1000),
|
||||
}).strict(),
|
||||
]);
|
||||
|
||||
export type CloudTrialTelemetryEventInput = z.infer<typeof cloudTrialTelemetryEventSchema>;
|
||||
|
||||
export interface MigratedCloudTrialAgentSummary {
|
||||
agentId: string;
|
||||
name: string;
|
||||
adapterType: string;
|
||||
runnerProvider?: string;
|
||||
acpxAgent?: string;
|
||||
model: string;
|
||||
}
|
||||
|
||||
export interface MigrateCloudTrialAgentsResult {
|
||||
migratedCount: number;
|
||||
agents: MigratedCloudTrialAgentSummary[];
|
||||
resumedRunIds: string[];
|
||||
resumedIssueId: string | null;
|
||||
}
|
||||
|
||||
export interface CloudTrialMigrationTarget {
|
||||
adapterType: string;
|
||||
runnerProvider?: string;
|
||||
acpxAgent?: string;
|
||||
model: string;
|
||||
}
|
||||
|
||||
export type CloudTrialMigrationTargetOverrides = Partial<
|
||||
Record<AiProvider, Partial<CloudTrialMigrationTarget>>
|
||||
>;
|
||||
|
||||
const cloudTrialMigrationTargetOverrideSchema = z
|
||||
.object({
|
||||
adapterType: z.string().trim().min(1).max(100).optional(),
|
||||
runnerProvider: z.string().trim().min(1).max(100).optional(),
|
||||
acpxAgent: z.string().trim().min(1).max(100).optional(),
|
||||
model: z.string().trim().min(1).max(200).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/**
|
||||
* Parses deployment-owned migration target overrides from a JSON string
|
||||
* (e.g. `PAPERCLIP_CLOUD_TRIAL_MIGRATION_TARGETS`). Fails closed to `{}` on
|
||||
* invalid input so a malformed env value never crashes startup.
|
||||
*/
|
||||
export function parseCloudTrialMigrationTargetsEnv(
|
||||
raw?: string | null,
|
||||
): CloudTrialMigrationTargetOverrides {
|
||||
const trimmed = raw?.trim();
|
||||
if (!trimmed) return {};
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
||||
const result: CloudTrialMigrationTargetOverrides = {};
|
||||
for (const provider of AI_PROVIDERS) {
|
||||
const candidate = (parsed as Record<string, unknown>)[provider];
|
||||
if (!candidate) continue;
|
||||
const validated = cloudTrialMigrationTargetOverrideSchema.safeParse(candidate);
|
||||
if (validated.success) {
|
||||
result[provider] = validated.data;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a newly connected user AI provider to the runner harness + model used
|
||||
* when migrating agents off starter inference. Deployment repositories may
|
||||
* supply `configuredTargets` (via `PAPERCLIP_CLOUD_TRIAL_MIGRATION_TARGETS`)
|
||||
* to override adapter/provider/model defaults without a Core release.
|
||||
*/
|
||||
export function defaultMigrationTargetForProvider(
|
||||
provider: AiProvider,
|
||||
_method: AiAuthMethod,
|
||||
overrideModel?: string,
|
||||
configuredTargets?: CloudTrialMigrationTargetOverrides,
|
||||
): CloudTrialMigrationTarget {
|
||||
const customModel = overrideModel?.trim() || undefined;
|
||||
const configured = configuredTargets?.[provider];
|
||||
let base: CloudTrialMigrationTarget;
|
||||
switch (provider) {
|
||||
case "openai":
|
||||
base = {
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "codex",
|
||||
model: "gpt-6-luna",
|
||||
};
|
||||
break;
|
||||
case "anthropic":
|
||||
base = {
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
};
|
||||
break;
|
||||
case "google":
|
||||
base = {
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "acpx",
|
||||
acpxAgent: "antigravity",
|
||||
model: "gemini-2.5-pro",
|
||||
};
|
||||
break;
|
||||
case "xai":
|
||||
base = {
|
||||
adapterType: "grok_local",
|
||||
model: "grok-4",
|
||||
};
|
||||
break;
|
||||
case "openrouter":
|
||||
base = {
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "opencode",
|
||||
model: CLOUD_TRIAL_DEFAULT_MODEL,
|
||||
};
|
||||
break;
|
||||
case "github":
|
||||
base = {
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "acpx",
|
||||
acpxAgent: "copilot",
|
||||
model: "gpt-5.6-luna",
|
||||
};
|
||||
break;
|
||||
}
|
||||
|
||||
const merged: CloudTrialMigrationTarget = {
|
||||
adapterType: configured?.adapterType ?? base.adapterType,
|
||||
...(configured?.runnerProvider !== undefined
|
||||
? { runnerProvider: configured.runnerProvider }
|
||||
: base.runnerProvider !== undefined
|
||||
? { runnerProvider: base.runnerProvider }
|
||||
: {}),
|
||||
...(configured?.acpxAgent !== undefined
|
||||
? { acpxAgent: configured.acpxAgent }
|
||||
: base.acpxAgent !== undefined
|
||||
? { acpxAgent: base.acpxAgent }
|
||||
: {}),
|
||||
model: customModel ?? configured?.model ?? base.model,
|
||||
};
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function isAgentUsingCloudTrialInference(runtimeConfig: unknown): boolean {
|
||||
if (!runtimeConfig || typeof runtimeConfig !== "object" || Array.isArray(runtimeConfig)) {
|
||||
return false;
|
||||
}
|
||||
return (runtimeConfig as Record<string, unknown>).cloudTrialInference === true;
|
||||
}
|
||||
@@ -1131,6 +1131,7 @@ export const LIVE_EVENT_TYPES = [
|
||||
"plugin.worker.crashed",
|
||||
"plugin.worker.restarted",
|
||||
"agent_setup_progress.updated",
|
||||
"cloud_trial.status.updated",
|
||||
] as const;
|
||||
export type LiveEventType = (typeof LIVE_EVENT_TYPES)[number];
|
||||
|
||||
|
||||
@@ -449,6 +449,14 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalog
|
||||
cloudDefault: false,
|
||||
selfHostedDefault: false,
|
||||
},
|
||||
enableCloudTrialInference: {
|
||||
title: "Cloud starter inference",
|
||||
description:
|
||||
"Lets new Cloud workspaces start their first agent right away (OpenCode / GPT-6 Luna via server proxy) before asking the user to connect a model provider.",
|
||||
tier: "managed",
|
||||
cloudDefault: false,
|
||||
selfHostedDefault: false,
|
||||
},
|
||||
};
|
||||
|
||||
export const INSTANCE_FEATURE_KEYS = Object.keys(INSTANCE_FEATURE_CATALOG).sort() as InstanceFeatureKey[];
|
||||
|
||||
@@ -3157,3 +3157,4 @@ export * from "./mcp-skills.js";
|
||||
export type { TailscaleConnection, TailscaleDeviceLogin } from "./types/tailscale.js";
|
||||
export * from "./agent-setup-progress.js";
|
||||
export { antigravitySwarmAvailable, antigravitySwarmWorkModeAllows, isAntigravityAgent, parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS, type LeadingUserCommand } from "./leading-user-command.js";
|
||||
export * from "./cloud-inference.js";
|
||||
@@ -132,6 +132,13 @@ export interface InstanceExperimentalSettings {
|
||||
* flipping it later does not change an existing first task.
|
||||
*/
|
||||
enableFirstTaskPlanProposal: boolean;
|
||||
/**
|
||||
* Experimental Paperclip Cloud onboarding starter inference: provides a
|
||||
* Cloud-funded $1 OpenRouter allowance (defaulting to OpenCode / Luna) via
|
||||
* the tenant server proxy so the user's first agent works out of the box,
|
||||
* then prompts to connect their own subscription when exhausted.
|
||||
*/
|
||||
enableCloudTrialInference: boolean;
|
||||
autoRestartDevServerWhenIdle: boolean;
|
||||
enableWorkspaceBranchReconcileForward: boolean;
|
||||
enableWorkspaceDirtyQuarantineRepair: boolean;
|
||||
|
||||
@@ -235,6 +235,7 @@ export const browserAnalyticsConfigSchema = z.object({
|
||||
stackId: z.string().min(1),
|
||||
replayEnabled: z.boolean(),
|
||||
consentRequired: z.boolean().nullable().optional(),
|
||||
cloudTrialInferenceEnabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type BrowserAnalyticsConfig = z.infer<typeof browserAnalyticsConfigSchema>;
|
||||
|
||||
@@ -74,6 +74,7 @@ export const createAgentInstructionsBundleSchema = z.object({
|
||||
|
||||
export const agentRuntimeConfigSchema = z.object({
|
||||
aiConnection: aiConnectionBindingSchema.optional(),
|
||||
cloudTrialInference: z.boolean().optional(),
|
||||
debug: z.object({
|
||||
providerTrace: z.literal("raw").optional(),
|
||||
}).strict().optional(),
|
||||
|
||||
@@ -90,6 +90,7 @@ export const instanceExperimentalSettingsSchema = z.object({
|
||||
enablePaperclipDeveloperMode: z.boolean().default(false),
|
||||
enableSimplifiedEnglishInteractions: z.boolean().default(false),
|
||||
enableFirstTaskPlanProposal: z.boolean().default(false),
|
||||
enableCloudTrialInference: z.boolean().default(false),
|
||||
autoRestartDevServerWhenIdle: z.boolean().default(false),
|
||||
enableWorkspaceBranchReconcileForward: z.boolean().default(true),
|
||||
enableWorkspaceDirtyQuarantineRepair: z.boolean().default(true),
|
||||
|
||||
@@ -132,6 +132,7 @@ describe("auth routes", () => {
|
||||
stackId: "stack-1",
|
||||
replayEnabled: true,
|
||||
consentRequired: null,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
});
|
||||
|
||||
vi.stubEnv("PAPERCLIP_POSTHOG_COUNTRY_HEADER", "cf-ipcountry");
|
||||
|
||||
@@ -50,6 +50,7 @@ describe("browser analytics config exposure", () => {
|
||||
stackId: "stack-1",
|
||||
replayEnabled,
|
||||
consentRequired: null,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -30,9 +30,31 @@ describe("resolveCloudPostHogConfig", () => {
|
||||
directEnabled: true,
|
||||
browserEnabled: false,
|
||||
replayEnabled: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves cloudTrialInferenceEnabled from PAPERCLIP_MANAGED_CONFIG and fails closed when invalid", () => {
|
||||
expect(
|
||||
resolveCloudPostHogConfig({
|
||||
...CLOUD,
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ features: { enableCloudTrialInference: true } }),
|
||||
})?.cloudTrialInferenceEnabled,
|
||||
).toBe(true);
|
||||
expect(
|
||||
resolveCloudPostHogConfig({
|
||||
...CLOUD,
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ features: { enableCloudTrialInference: false } }),
|
||||
})?.cloudTrialInferenceEnabled,
|
||||
).toBe(false);
|
||||
expect(
|
||||
resolveCloudPostHogConfig({
|
||||
...CLOUD,
|
||||
PAPERCLIP_MANAGED_CONFIG: "{not-json",
|
||||
})?.cloudTrialInferenceEnabled,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts the legacy managed-config Cloud signal", () => {
|
||||
const { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: _omit, ...rest } = CLOUD;
|
||||
expect(resolveCloudPostHogConfig({ ...rest, PAPERCLIP_MANAGED_CONFIG: "{}" })?.stackId).toBe("stack-123");
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
import { generateKeyPairSync, verify } from "node:crypto";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import express from "express";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
CLOUD_TRIAL_DEFAULT_MODEL,
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
defaultMigrationTargetForProvider,
|
||||
parseCloudTrialMigrationTargetsEnv,
|
||||
resolveCloudTrialModel,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
CloudTrialExhaustedError,
|
||||
createCloudTrialInferenceController,
|
||||
} from "../services/cloud-trial-inference.js";
|
||||
import { cloudInferenceInternalProxyRoutes } from "../routes/cloud-inference.js";
|
||||
import { resolveBrowserAnalyticsConfig } from "../services/cloud-posthog-browser.js";
|
||||
import {
|
||||
resetResolvedCloudTrialInferenceEnabledForTests,
|
||||
setResolvedCloudTrialInferenceEnabled,
|
||||
} from "../services/cloud-posthog-cohort.js";
|
||||
import { createPostHogDirectTransport } from "../services/posthog-direct/transport.js";
|
||||
|
||||
function generateTestEd25519Pair() {
|
||||
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
|
||||
const privDer = privateKey.export({ format: "der", type: "pkcs8" });
|
||||
const rawSeed = privDer.subarray(privDer.length - 32);
|
||||
return {
|
||||
publicKey,
|
||||
privateKeyBase64Url: rawSeed.toString("base64url"),
|
||||
};
|
||||
}
|
||||
|
||||
async function listenExpress(app: express.Express): Promise<{ baseUrl: string; close: () => Promise<void> }> {
|
||||
const server: Server = createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const addr = server.address();
|
||||
if (!addr || typeof addr !== "object") throw new Error("Failed to bind test server");
|
||||
return {
|
||||
baseUrl: `http://127.0.0.1:${addr.port}`,
|
||||
close: () => new Promise<void>((resolve, reject) => server.close((err) => (err ? reject(err) : resolve()))),
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDbWithFlag(enabled: boolean) {
|
||||
const row = {
|
||||
id: "00000000-0000-0000-0000-000000000001",
|
||||
singletonKey: "default",
|
||||
general: {},
|
||||
experimental: { enableCloudTrialInference: enabled },
|
||||
defaultEnvironmentId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
return {
|
||||
select: () => ({
|
||||
from: () => ({
|
||||
where: async () => [row],
|
||||
limit: async () => [row],
|
||||
}),
|
||||
}),
|
||||
} as never;
|
||||
}
|
||||
|
||||
describe("cloud-trial-inference", () => {
|
||||
const closers: Array<() => Promise<void>> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (closers.length > 0) {
|
||||
await closers.pop()!();
|
||||
}
|
||||
resetResolvedCloudTrialInferenceEnabledForTests();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("signs Cloud requests with Ed25519 only, enforces strict starter model, renews active run tokens, and detects HTTP 402 exhaustion", async () => {
|
||||
const keypair = generateTestEd25519Pair();
|
||||
const seenAuthHeaders: string[] = [];
|
||||
const seenAttributionHeaders: Array<string | undefined> = [];
|
||||
let return402 = false;
|
||||
let keyRemainingUsd = 0.75;
|
||||
let fakeNow = 1_700_000_000_000;
|
||||
|
||||
// Mock upstream OpenRouter server
|
||||
const mockOpenRouter = express();
|
||||
mockOpenRouter.use(express.json());
|
||||
mockOpenRouter.post("/api/v1/chat/completions", (req, res) => {
|
||||
seenAuthHeaders.push(String(req.headers.authorization ?? ""));
|
||||
seenAttributionHeaders.push(
|
||||
typeof req.headers["x-openrouter-title"] === "string" ? req.headers["x-openrouter-title"] : undefined,
|
||||
);
|
||||
if (return402) {
|
||||
res.status(402).json({ error: { code: 402, message: "Key limit exceeded" } });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({
|
||||
id: "chatcmpl-test",
|
||||
choices: [{ message: { role: "assistant", content: "Hello from Luna!" } }],
|
||||
});
|
||||
});
|
||||
mockOpenRouter.get("/api/v1/key", (_req, res) => {
|
||||
res.status(200).json({
|
||||
data: { limit: 1.0, usage: 1.0 - keyRemainingUsd, limit_remaining: keyRemainingUsd },
|
||||
});
|
||||
});
|
||||
const upstream = await listenExpress(mockOpenRouter);
|
||||
closers.push(upstream.close);
|
||||
|
||||
// Mock Cloud Harness server verifying Ed25519 signature (no shared bearer token)
|
||||
let exhaustedReportedToCloud = false;
|
||||
const mockCloud = express();
|
||||
mockCloud.use(express.json());
|
||||
const verifySignature = (req: express.Request, pathname: string) => {
|
||||
expect(req.headers.authorization).toBeUndefined();
|
||||
const stackId = String(req.headers["x-paperclip-cloud-stack-id"] ?? "");
|
||||
const ts = String(req.headers["x-paperclip-cloud-stack-timestamp"] ?? "");
|
||||
const sig = String(req.headers["x-paperclip-cloud-stack-signature"] ?? "");
|
||||
expect(stackId).toBe("stack-test-1");
|
||||
const payload = Buffer.from(`POST\n${pathname}\n${stackId}\n${ts}`, "utf8");
|
||||
expect(verify(null, payload, keypair.publicKey, Buffer.from(sig, "base64url"))).toBe(true);
|
||||
};
|
||||
mockCloud.post("/v1/tenant/inference-key", (req, res) => {
|
||||
verifySignature(req, "/v1/tenant/inference-key");
|
||||
res.status(200).json({
|
||||
provider: "openrouter",
|
||||
status: "active",
|
||||
apiKey: "sk-or-v1-real-secret-key-never-sent-to-sandbox",
|
||||
limitUsdCents: 100,
|
||||
spentUsdCents: 0,
|
||||
remainingUsdCents: 100,
|
||||
defaultModel: "openrouter/openai/gpt-6-luna",
|
||||
});
|
||||
});
|
||||
mockCloud.post("/v1/tenant/inference-key/exhausted", (req, res) => {
|
||||
verifySignature(req, "/v1/tenant/inference-key/exhausted");
|
||||
exhaustedReportedToCloud = true;
|
||||
res.status(200).json({
|
||||
provider: "openrouter",
|
||||
status: "exhausted",
|
||||
limitUsdCents: 100,
|
||||
spentUsdCents: 100,
|
||||
remainingUsdCents: 0,
|
||||
});
|
||||
});
|
||||
const cloud = await listenExpress(mockCloud);
|
||||
closers.push(cloud.close);
|
||||
|
||||
const controller = createCloudTrialInferenceController({
|
||||
env: {
|
||||
PAPERCLIP_CLOUD_STACK_ID: "stack-test-1",
|
||||
PAPERCLIP_CLOUD_API_ORIGIN: cloud.baseUrl,
|
||||
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "shared-token-must-not-be-sent",
|
||||
PAPERCLIP_CLOUD_CONNECTOR_SIGN_PRIVATE_KEY: keypair.privateKeyBase64Url,
|
||||
PAPERCLIP_CLOUD_TRIAL_OPENROUTER_BASE_URL: `${upstream.baseUrl}/api/v1`,
|
||||
PAPERCLIP_API_URL: "http://127.0.0.1:3100",
|
||||
},
|
||||
now: () => fakeNow,
|
||||
});
|
||||
|
||||
// Mount internal proxy
|
||||
const proxyApp = express();
|
||||
proxyApp.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(controller));
|
||||
const proxy = await listenExpress(proxyApp);
|
||||
closers.push(proxy.close);
|
||||
|
||||
const db = fakeDbWithFlag(true);
|
||||
|
||||
// 0. Non-starter model is rejected at run preparation (cannot bypass starter model cap)
|
||||
await expect(
|
||||
controller.prepareCloudTrialRuntime(db, {
|
||||
companyId: "comp-1",
|
||||
agentId: "agent-1",
|
||||
runId: "run-bad-model",
|
||||
model: "openrouter/anthropic/claude-opus-4",
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
status: 422,
|
||||
details: expect.objectContaining({ code: "cloud_trial_model_not_allowed" }),
|
||||
});
|
||||
|
||||
const runtime = await controller.prepareCloudTrialRuntime(db, {
|
||||
companyId: "comp-1",
|
||||
agentId: "agent-1",
|
||||
runId: "run-1",
|
||||
model: "openrouter/openai/gpt-6-luna",
|
||||
});
|
||||
|
||||
// Raw key MUST NOT be in sandbox env!
|
||||
expect(runtime.env.OPENROUTER_API_KEY).toBe("");
|
||||
expect(runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN).toMatch(/^pctrial_/);
|
||||
expect(runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN).not.toContain("sk-or-v1-real-secret");
|
||||
expect(runtime.env.PAPERCLIP_OPENROUTER_PROXY_URL).toBe("http://127.0.0.1:3100/api/internal/cloud-inference/v1");
|
||||
|
||||
const token = runtime.env.PAPERCLIP_OPENROUTER_PROXY_TOKEN!;
|
||||
|
||||
// 1. Invalid token fails closed (401), unknown pctrial_ token reports distinct instance error
|
||||
const badAuth = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer bogus", "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
|
||||
});
|
||||
expect(badAuth.status).toBe(401);
|
||||
expect(((await badAuth.json()) as { error: { code: string } }).error.code).toBe("unauthorized");
|
||||
|
||||
const unknownRunToken = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer pctrial_unknown_from_other_instance", "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [] }),
|
||||
});
|
||||
expect(unknownRunToken.status).toBe(401);
|
||||
expect(((await unknownRunToken.json()) as { error: { code: string } }).error.code).toBe(
|
||||
"proxy_token_not_found_on_instance",
|
||||
);
|
||||
|
||||
// 2. Disallowed model, missing model, fallback models array, and fallback route all fail closed (403)
|
||||
const badModel = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: "anthropic/claude-opus-4", messages: [] }),
|
||||
});
|
||||
expect(badModel.status).toBe(403);
|
||||
|
||||
const missingModel = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ models: ["anthropic/claude-opus-4"], messages: [] }),
|
||||
});
|
||||
expect(missingModel.status).toBe(403);
|
||||
|
||||
const fallbackModels = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
model: "openai/gpt-6-luna",
|
||||
models: ["openai/gpt-6-luna", "anthropic/claude-opus-4"],
|
||||
messages: [],
|
||||
}),
|
||||
});
|
||||
expect(fallbackModels.status).toBe(403);
|
||||
|
||||
const fallbackRoute = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
model: "openai/gpt-6-luna",
|
||||
route: "fallback",
|
||||
messages: [],
|
||||
}),
|
||||
});
|
||||
expect(fallbackRoute.status).toBe(403);
|
||||
|
||||
// 3. Allowed model succeeds and active-run token survives multi-hour tool execution gaps until cleanup()
|
||||
fakeNow += 2 * 60 * 60_000;
|
||||
const okRes = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "Hi" }] }),
|
||||
});
|
||||
expect(okRes.status).toBe(200);
|
||||
const okBody = (await okRes.json()) as { choices: Array<{ message: { content: string } }> };
|
||||
expect(okBody.choices[0]!.message.content).toBe("Hello from Luna!");
|
||||
expect(seenAuthHeaders[0]).toBe("Bearer sk-or-v1-real-secret-key-never-sent-to-sandbox");
|
||||
expect(seenAttributionHeaders[0]).toBe("Paperclip");
|
||||
|
||||
// Advance another 3 hours — still valid while the run remains active!
|
||||
fakeNow += 3 * 60 * 60_000;
|
||||
const renewedRes = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "Still running" }] }),
|
||||
});
|
||||
expect(renewedRes.status).toBe(200);
|
||||
|
||||
// 4. Upstream HTTP 402 immediately triggers exhaustion + Cloud notification + 402 response
|
||||
return402 = true;
|
||||
const exhaustedRes = await fetch(`${proxy.baseUrl}/api/internal/cloud-inference/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: "openai/gpt-6-luna", messages: [{ role: "user", content: "More" }] }),
|
||||
});
|
||||
expect(exhaustedRes.status).toBe(402);
|
||||
const exhaustedBody = (await exhaustedRes.json()) as { error: { code: string } };
|
||||
expect(exhaustedBody.error.code).toBe(CLOUD_TRIAL_EXHAUSTED_ERROR_CODE);
|
||||
expect(exhaustedReportedToCloud).toBe(true);
|
||||
|
||||
// 5. Subsequent run preparation fails immediately with CloudTrialExhaustedError
|
||||
await expect(
|
||||
controller.prepareCloudTrialRuntime(db, {
|
||||
companyId: "comp-1",
|
||||
agentId: "agent-1",
|
||||
runId: "run-2",
|
||||
model: "openrouter/openai/gpt-6-luna",
|
||||
}),
|
||||
).rejects.toBeInstanceOf(CloudTrialExhaustedError);
|
||||
|
||||
await runtime.cleanup();
|
||||
});
|
||||
|
||||
it("normalizes starter model slugs consistently and maps providers including acpx Google/GitHub and deployment overrides", () => {
|
||||
expect(resolveCloudTrialModel(undefined)).toBe(CLOUD_TRIAL_DEFAULT_MODEL);
|
||||
expect(resolveCloudTrialModel("openai/gpt-6-luna")).toBe("openrouter/openai/gpt-6-luna");
|
||||
expect(resolveCloudTrialModel("openrouter/openai/gpt-6-luna")).toBe("openrouter/openai/gpt-6-luna");
|
||||
|
||||
expect(defaultMigrationTargetForProvider("openai", "subscription")).toEqual({
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "codex",
|
||||
model: "gpt-6-luna",
|
||||
});
|
||||
expect(defaultMigrationTargetForProvider("anthropic", "subscription")).toEqual({
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
expect(defaultMigrationTargetForProvider("google", "subscription")).toEqual({
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "acpx",
|
||||
acpxAgent: "antigravity",
|
||||
model: "gemini-2.5-pro",
|
||||
});
|
||||
expect(defaultMigrationTargetForProvider("github", "subscription")).toEqual({
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "acpx",
|
||||
acpxAgent: "copilot",
|
||||
model: "gpt-5.6-luna",
|
||||
});
|
||||
expect(defaultMigrationTargetForProvider("xai", "subscription")).toEqual({
|
||||
adapterType: "grok_local",
|
||||
model: "grok-4",
|
||||
});
|
||||
|
||||
const overrides = parseCloudTrialMigrationTargetsEnv(
|
||||
JSON.stringify({
|
||||
openai: { model: "gpt-6.5-pro" },
|
||||
google: { acpxAgent: "antigravity", model: "gemini-3-pro" },
|
||||
}),
|
||||
);
|
||||
expect(defaultMigrationTargetForProvider("openai", "subscription", undefined, overrides)).toEqual({
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "codex",
|
||||
model: "gpt-6.5-pro",
|
||||
});
|
||||
expect(defaultMigrationTargetForProvider("google", "subscription", undefined, overrides)).toEqual({
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "acpx",
|
||||
acpxAgent: "antigravity",
|
||||
model: "gemini-3-pro",
|
||||
});
|
||||
expect(parseCloudTrialMigrationTargetsEnv("not-json")).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps PostHog server and browser experiment cohort synced with resolved staging overrides", async () => {
|
||||
const captured: Array<{ event: string; properties?: Record<string, unknown> }> = [];
|
||||
const transport = createPostHogDirectTransport(
|
||||
{
|
||||
token: "phc_test",
|
||||
host: "https://us.i.posthog.com",
|
||||
environment: "staging",
|
||||
stackId: "stack-staging-1",
|
||||
directEnabled: true,
|
||||
browserEnabled: true,
|
||||
replayEnabled: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
},
|
||||
{
|
||||
factory: async () => ({
|
||||
capture: (msg) => captured.push({ event: msg.event, properties: msg.properties }),
|
||||
groupIdentify: () => {},
|
||||
flush: async () => {},
|
||||
shutdown: async () => {},
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
expect(transport.cloudTrialInferenceEnabled).toBe(false);
|
||||
setResolvedCloudTrialInferenceEnabled(true);
|
||||
expect(transport.cloudTrialInferenceEnabled).toBe(true);
|
||||
await transport.captureCloudEvent({ event: "cloud_trial.started", properties: { source: "test" } });
|
||||
expect(captured[0]?.properties?.cloud_trial_inference_enabled).toBe(true);
|
||||
expect(captured[0]?.properties?.["$feature/cloud-trial-inference"]).toBe("treatment");
|
||||
|
||||
const browserCfg = resolveBrowserAnalyticsConfig(
|
||||
{
|
||||
PAPERCLIP_CLOUD_STACK_ID: "stack-staging-1",
|
||||
PAPERCLIP_CLOUD_HOSTED: "1",
|
||||
PAPERCLIP_POSTHOG_PROJECT_TOKEN: "phc_test",
|
||||
PAPERCLIP_POSTHOG_BROWSER_ENABLED: "1",
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({ features: { enableCloudTrialInference: false } }),
|
||||
},
|
||||
{},
|
||||
{ cloudTrialInferenceEnabled: true },
|
||||
);
|
||||
expect(browserCfg?.cloudTrialInferenceEnabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -147,6 +147,7 @@ describe("instance settings service", () => {
|
||||
enableExternalObjects: false,
|
||||
enableSmokeLab: false,
|
||||
enableCases: false,
|
||||
enableCloudTrialInference: false,
|
||||
enableIssuePlanDecompositions: true,
|
||||
enableExperimentalFileViewer: true,
|
||||
enableBuiltInAgents: true,
|
||||
|
||||
@@ -48,6 +48,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"slack-tools.ts": "/api",
|
||||
"email.ts": "/api",
|
||||
"cloud.ts": "/api/cloud",
|
||||
"cloud-inference.ts": "/api",
|
||||
"customer-success.ts": "/api/customer-success/v1",
|
||||
"companies.ts": "/api/companies",
|
||||
"company-skills.ts": "/api",
|
||||
|
||||
@@ -25,6 +25,8 @@ import {
|
||||
isPostHogDirectTelemetryActive,
|
||||
resetTelemetryForTests,
|
||||
shutdownTelemetry,
|
||||
trackCloudPostHogEvent,
|
||||
trackCloudTrialExposure,
|
||||
} from "../telemetry.js";
|
||||
import type { PostHogNodeClient } from "../services/posthog-direct/index.js";
|
||||
import {
|
||||
@@ -291,7 +293,13 @@ describe("server telemetry sender selection", () => {
|
||||
groupType: "workspace",
|
||||
groupKey: "stack-123",
|
||||
disableGeoip: true,
|
||||
properties: { stack_slug: "acme", primary_host: "acme.paperclip.app", environment: "staging" },
|
||||
properties: {
|
||||
stack_slug: "acme",
|
||||
primary_host: "acme.paperclip.app",
|
||||
environment: "staging",
|
||||
cloud_trial_inference_enabled: false,
|
||||
cloud_trial_inference_cohort: "control",
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(posthog.client.shutdownCalls).toBe(1);
|
||||
@@ -599,4 +607,71 @@ describe("server telemetry sender selection", () => {
|
||||
expect(byState.succeeded!.distinctId).toBe("paperclip-id:creator");
|
||||
expect(byState.succeeded!.properties).toMatchObject({ attributed_via: "task_creator", company_id: "company-1" });
|
||||
});
|
||||
|
||||
it("Cloud: stamps cloud-trial-inference experiment cohort on events and emits deduplicated exposure and funnel events", async () => {
|
||||
const posthog = fakePostHog();
|
||||
const treatmentEnv = {
|
||||
...CLOUD_ENV,
|
||||
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({
|
||||
v: 1,
|
||||
mode: "cloud",
|
||||
catalogVersion: "v1",
|
||||
features: { enableCloudTrialInference: true },
|
||||
plugins: { autoInstall: [] },
|
||||
}),
|
||||
};
|
||||
const client = initTelemetry({ enabled: true }, { env: treatmentEnv, postHogFactory: posthog.factory })!;
|
||||
trackRoutineCreated(client);
|
||||
trackCloudTrialExposure({ surface: "onboarding_wizard", userId: "user-42", companyId: "co-1" });
|
||||
// Second call for the same user/company deduplicates.
|
||||
trackCloudTrialExposure({ surface: "onboarding_wizard", userId: "user-42", companyId: "co-1" });
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.migrated",
|
||||
{ provider: "anthropic", auth_method: "subscription", migrated_agent_count: 1 },
|
||||
{ userId: "user-42", companyId: "co-1" },
|
||||
);
|
||||
await shutdownTelemetry();
|
||||
|
||||
expect(posthog.groups[0]?.properties).toMatchObject({
|
||||
cloud_trial_inference_enabled: true,
|
||||
cloud_trial_inference_cohort: "treatment",
|
||||
});
|
||||
|
||||
const routine = posthog.captured.find((message) => message.event === "routine.created")!;
|
||||
expect(routine.properties).toMatchObject({
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
});
|
||||
|
||||
const exposures = posthog.captured.filter((message) => message.event === "$feature_flag_called");
|
||||
expect(exposures).toHaveLength(1);
|
||||
expect(exposures[0]!.distinctId).toBe("user-42");
|
||||
expect(exposures[0]!.properties).toMatchObject({
|
||||
$feature_flag: "cloud-trial-inference",
|
||||
$feature_flag_response: "treatment",
|
||||
surface: "onboarding_wizard",
|
||||
company_id: "co-1",
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
$set_once: { cloud_trial_inference_cohort: "treatment" },
|
||||
});
|
||||
|
||||
const migrated = posthog.captured.find((message) => message.event === "cloud_trial.migrated")!;
|
||||
expect(migrated.distinctId).toBe("user-42");
|
||||
expect(migrated.properties).toMatchObject({
|
||||
provider: "anthropic",
|
||||
auth_method: "subscription",
|
||||
migrated_agent_count: 1,
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
});
|
||||
});
|
||||
|
||||
it("self-hosted: cloud trial PostHog helpers are no-ops and never load posthog-node", async () => {
|
||||
initTelemetry({ enabled: true }, { env: {} });
|
||||
trackCloudTrialExposure({ surface: "onboarding_wizard", userId: "user-1", companyId: "co-1" });
|
||||
trackCloudPostHogEvent("cloud_trial.started", { source: "onboarding_wizard" }, { userId: "user-1" });
|
||||
await shutdownTelemetry();
|
||||
expect(hoisted.posthogNodeLoads).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ const config: CloudPostHogConfig = {
|
||||
directEnabled: true,
|
||||
browserEnabled: false,
|
||||
replayEnabled: false,
|
||||
cloudTrialInferenceEnabled: false,
|
||||
};
|
||||
|
||||
const startup = {
|
||||
|
||||
@@ -101,6 +101,11 @@ import { cloudRuntimeIdentityMiddleware } from "./middleware/cloud-runtime-ident
|
||||
import { cloudControlMiddleware } from "./middleware/cloud-control.js";
|
||||
import { runnerCallOutcomeMiddleware } from "./middleware/runner-call-outcome.js";
|
||||
import { cloudRoutes } from "./routes/cloud.js";
|
||||
import { cloudInferenceInternalProxyRoutes, cloudInferenceRoutes } from "./routes/cloud-inference.js";
|
||||
import {
|
||||
createCloudTrialInferenceController,
|
||||
setDefaultCloudTrialInferenceController,
|
||||
} from "./services/cloud-trial-inference.js";
|
||||
import { companyRoutes } from "./routes/companies.js";
|
||||
import { companySkillRoutes } from "./routes/company-skills.js";
|
||||
import { companySkillPolicyRoutes } from "./routes/company-skill-policy.js";
|
||||
@@ -752,6 +757,17 @@ export async function createApp(
|
||||
})
|
||||
: undefined;
|
||||
|
||||
// Internal OpenRouter trial inference proxy (authenticated strictly by
|
||||
// ephemeral per-run bearer token; never requires board session cookies).
|
||||
const cloudTrialInferenceController = createCloudTrialInferenceController();
|
||||
setDefaultCloudTrialInferenceController(cloudTrialInferenceController);
|
||||
// Warm resolved experimental settings at startup so staging overrides sync
|
||||
// into PostHog cohort properties before the first request or event.
|
||||
void instanceSettingsService(db)
|
||||
.getExperimental()
|
||||
.catch(() => {});
|
||||
app.use("/api/internal/cloud-inference", cloudInferenceInternalProxyRoutes(cloudTrialInferenceController));
|
||||
|
||||
// Mount API routes
|
||||
const api = Router();
|
||||
const agentAvatars = agentAvatarRoutes();
|
||||
@@ -760,6 +776,7 @@ export async function createApp(
|
||||
api.use("/health", health);
|
||||
api.use(openApiRoutes());
|
||||
api.use("/cloud", cloudRoutes());
|
||||
api.use(cloudInferenceRoutes(db, cloudTrialInferenceController));
|
||||
api.use("/companies", companyRoutes(db, opts.storageService));
|
||||
api.use(llmRoutes(db));
|
||||
api.use(folderRoutes(db));
|
||||
|
||||
@@ -26,6 +26,7 @@ import { agentIdentityService } from "../services/agent-identity.js";
|
||||
import { aiConnectionRouterService, poolMemberRuntimeConfig } from "../services/ai-connection-router.js";
|
||||
import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import { isCloudManagedInstance } from "../services/cloud-instance.js";
|
||||
import { assertCloudTrialInferenceEligible } from "../services/cloud-trial-inference.js";
|
||||
import { dotRunnerBroker } from "../services/dot-runner-broker.js";
|
||||
import { publicMcpConfig } from "../services/public-mcp/oauth.js";
|
||||
import { connectionIntentDeliveryService } from "../services/connection-intent-delivery.js";
|
||||
@@ -293,7 +294,7 @@ import {
|
||||
resolveDefaultAgentInstructionsBundleRole,
|
||||
} from "../services/default-agent-instructions.js";
|
||||
import { buildOnboardingFirstAgentInstructionsBundle } from "../services/onboarding-first-task-assets.js";
|
||||
import { getTelemetryClient } from "../telemetry.js";
|
||||
import { getTelemetryClient, trackCloudPostHogEvent } from "../telemetry.js";
|
||||
import { assertEnvironmentSelectionForCompany } from "./environment-selection.js";
|
||||
import { recoveryService } from "../services/recovery/service.js";
|
||||
import { resolveCoreTrustPreset } from "../services/trust-preset-resolver.js";
|
||||
@@ -4758,6 +4759,9 @@ export function agentRoutes(
|
||||
const requiresApproval = company.requireBoardApprovalForNewAgents;
|
||||
const status = requiresApproval ? "pending_approval" : "idle";
|
||||
const managedHireBinding = normalizedHireInput.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(normalizedHireInput.runtimeConfig.aiConnection) : undefined;
|
||||
if ((normalizedHireInput.runtimeConfig as Record<string, unknown> | undefined)?.cloudTrialInference === true) {
|
||||
await assertCloudTrialInferenceEligible(db, companyId);
|
||||
}
|
||||
const managedHireConnection = managedHireBinding ? await validateManagedAgentBinding(req, companyId, hiredAgentId, normalizedHireInput.adapterType, normalizedHireInput.adapterConfig, managedHireBinding, normalizedHireInput.defaultEnvironmentId, "none", true) : undefined;
|
||||
const createdAgent = await svcLifecycle.requestHire(
|
||||
companyId,
|
||||
@@ -4894,6 +4898,17 @@ export function agentRoutes(
|
||||
if (telemetryClient) {
|
||||
trackAgentCreated(telemetryClient, { agentRole: agent.role, agentId: agent.id });
|
||||
}
|
||||
if ((agent.runtimeConfig as Record<string, unknown> | null)?.cloudTrialInference === true) {
|
||||
const rawModel = (agent.adapterConfig as Record<string, unknown> | null)?.model;
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.started",
|
||||
{
|
||||
source: "onboarding_wizard",
|
||||
...(typeof rawModel === "string" && rawModel.trim() ? { model: rawModel.trim() } : {}),
|
||||
},
|
||||
{ userId: actor.actorType === "user" ? actor.actorId : null, companyId },
|
||||
);
|
||||
}
|
||||
|
||||
await applyDefaultAgentTaskAssignGrant(
|
||||
companyId,
|
||||
@@ -4974,6 +4989,9 @@ export function agentRoutes(
|
||||
} = req.body;
|
||||
const agentId = setupId ?? randomUUID();
|
||||
const requestedCreateConfig = (createInput.adapterConfig ?? {}) as Record<string, unknown>;
|
||||
if ((createInput.runtimeConfig as Record<string, unknown> | undefined)?.cloudTrialInference === true) {
|
||||
await assertCloudTrialInferenceEligible(db, companyId);
|
||||
}
|
||||
assertProviderTraceSettingTransition(req, createInput.runtimeConfig);
|
||||
assertNoAgentAdapterConfigMutation(req, requestedCreateConfig);
|
||||
assertNoAgentLocalAdapterHostCommandMutation(req, createInput.adapterType ?? "process", requestedCreateConfig, await callerUsesAiConnectionPool(req, companyId));
|
||||
@@ -5742,6 +5760,10 @@ export function agentRoutes(
|
||||
existing.runtimeConfig,
|
||||
);
|
||||
requestedRuntimeConfig = req.actor.source === "mcp_oauth" ? { ...existing.runtimeConfig, ...runtimeConfig } : runtimeConfig;
|
||||
const wasCloudTrial = (existing.runtimeConfig as Record<string, unknown> | null)?.cloudTrialInference === true;
|
||||
if (requestedRuntimeConfig.cloudTrialInference === true && !wasCloudTrial) {
|
||||
await assertCloudTrialInferenceEligible(db, existing.companyId);
|
||||
}
|
||||
}
|
||||
const touchesAdapterConfiguration =
|
||||
hasOwn(patchData, "adapterType") ||
|
||||
|
||||
@@ -14,6 +14,8 @@ import { resolveBrowserTracingConfig, warnOnce } from "../browser-tracing-config
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { loadBoardBootstrap } from "../services/board-bootstrap.js";
|
||||
import { resolveBrowserAnalyticsConfig } from "../services/cloud-posthog-browser.js";
|
||||
import { setResolvedCloudTrialInferenceEnabled } from "../services/cloud-posthog-cohort.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
|
||||
async function loadCurrentUserProfile(db: Db, userId: string) {
|
||||
const user = await db
|
||||
@@ -56,7 +58,18 @@ export function authRoutes(db: Db) {
|
||||
return undefined;
|
||||
})
|
||||
: Promise.resolve(undefined);
|
||||
const [user, boardBootstrap] = await Promise.all([loadCurrentUserProfile(db, req.actor.userId), bootstrap]);
|
||||
const [user, boardBootstrap, experimental] = await Promise.all([
|
||||
loadCurrentUserProfile(db, req.actor.userId),
|
||||
bootstrap,
|
||||
instanceSettingsService(db)
|
||||
.getExperimental()
|
||||
.catch(() => null),
|
||||
]);
|
||||
const cloudTrialInferenceEnabled =
|
||||
experimental !== null ? experimental.enableCloudTrialInference === true : undefined;
|
||||
if (typeof cloudTrialInferenceEnabled === "boolean") {
|
||||
setResolvedCloudTrialInferenceEnabled(cloudTrialInferenceEnabled);
|
||||
}
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
const session = authSessionSchema.parse({
|
||||
session: {
|
||||
@@ -76,7 +89,9 @@ export function authRoutes(db: Db) {
|
||||
browserTracing: resolveBrowserTracingConfig(process.env, warnBrowserTracing),
|
||||
// Hosted Paperclip Cloud with PAPERCLIP_POSTHOG_BROWSER_ENABLED=1 only;
|
||||
// null everywhere else. See `server/src/services/cloud-posthog-browser.ts`.
|
||||
browserAnalytics: resolveBrowserAnalyticsConfig(process.env, req.headers),
|
||||
browserAnalytics: resolveBrowserAnalyticsConfig(process.env, req.headers, {
|
||||
...(typeof cloudTrialInferenceEnabled === "boolean" ? { cloudTrialInferenceEnabled } : {}),
|
||||
}),
|
||||
});
|
||||
res.json({ ...session, ...(boardBootstrap ? { boardBootstrap } : {}) });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { Router } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
cloudTrialTelemetryEventSchema,
|
||||
migrateCloudTrialAgentsSchema,
|
||||
} from "@paperclipai/shared";
|
||||
import { forbidden, HttpError } from "../errors.js";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import {
|
||||
getDefaultCloudTrialInferenceController,
|
||||
type CloudTrialInferenceController,
|
||||
} from "../services/cloud-trial-inference.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { trackCloudPostHogEvent, trackCloudTrialExposure } from "../telemetry.js";
|
||||
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
|
||||
/**
|
||||
* Internal OpenRouter reverse proxy mounted at `/api/internal/cloud-inference`.
|
||||
* Authenticated strictly via ephemeral per-run bearer tokens (never board cookies),
|
||||
* keeping the real Cloud-issued OpenRouter API key strictly on the server process.
|
||||
*/
|
||||
export function cloudInferenceInternalProxyRoutes(
|
||||
controller: CloudTrialInferenceController = getDefaultCloudTrialInferenceController(),
|
||||
) {
|
||||
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);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Company-scoped board routes for inspecting Cloud starter inference status
|
||||
* and migrating trial agents onto a newly connected user AI subscription/key.
|
||||
*/
|
||||
export function cloudInferenceRoutes(
|
||||
db: Db,
|
||||
controller: CloudTrialInferenceController = getDefaultCloudTrialInferenceController(),
|
||||
) {
|
||||
const router = Router();
|
||||
|
||||
router.get("/companies/:companyId/cloud-inference/status", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertBoard(req);
|
||||
assertCompanyAccess(req, companyId);
|
||||
const refreshUsage = req.query.refresh === "1" || req.query.refresh === "true";
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.json(
|
||||
await controller.getCompanyStatus(db, companyId, {
|
||||
refreshUsage,
|
||||
actor: req.actor,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
router.post(
|
||||
"/companies/:companyId/cloud-inference/migrate",
|
||||
validate(migrateCloudTrialAgentsSchema),
|
||||
async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertBoard(req);
|
||||
assertCompanyAccess(req, companyId);
|
||||
const membership = req.actor.memberships?.find(
|
||||
(m) => m.companyId === companyId && m.status === "active",
|
||||
);
|
||||
if (membership?.membershipRole === "viewer" && !req.actor.isInstanceAdmin) {
|
||||
throw forbidden("Viewers cannot migrate agent AI connections");
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
try {
|
||||
const result = await controller.migrateTrialAgents(db, companyId, req.body, {
|
||||
userId: actor.actorId,
|
||||
actor: req.actor,
|
||||
});
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
const errorCode =
|
||||
err instanceof HttpError
|
||||
? `http_${err.status}`
|
||||
: "unexpected_error";
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.migration_failed",
|
||||
{
|
||||
provider: req.body?.provider ?? "unknown",
|
||||
auth_method: req.body?.method ?? "unknown",
|
||||
error_code: errorCode,
|
||||
},
|
||||
{ userId: actor.actorId, companyId },
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/companies/:companyId/cloud-inference/telemetry",
|
||||
validate(cloudTrialTelemetryEventSchema),
|
||||
async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertBoard(req);
|
||||
assertCompanyAccess(req, companyId);
|
||||
const actor = getActorInfo(req);
|
||||
const body = req.body as
|
||||
| { event: "onboarding_exposure"; surface: "onboarding_wizard" | "onboarding_seed" }
|
||||
| { event: "modal_shown"; trialAgentCount: number };
|
||||
if (body.event === "onboarding_exposure") {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
trackCloudTrialExposure({
|
||||
surface: body.surface,
|
||||
userId: actor.actorId,
|
||||
companyId,
|
||||
enabledOverride: experimental.enableCloudTrialInference === true,
|
||||
});
|
||||
} else if (body.event === "modal_shown") {
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.modal_shown",
|
||||
{ trial_agent_count: body.trialAgentCount },
|
||||
{ userId: actor.actorId, companyId },
|
||||
);
|
||||
}
|
||||
res.status(204).end();
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
experimentalApiQueries,
|
||||
} from "./experimental-api-paths.js";
|
||||
import { Router } from "express";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema } from "@paperclipai/shared";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema, CLOUD_TRIAL_INFERENCE_STATUSES, cloudTrialTelemetryEventSchema, migrateCloudTrialAgentsSchema } from "@paperclipai/shared";
|
||||
import { z } from "zod";
|
||||
import { getHiddenSettings } from "../services/settings-visibility.js";
|
||||
import {
|
||||
@@ -1549,6 +1549,9 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"DELETE /api/issues/{id}/documents/{key}",
|
||||
"GET /api/companies/{companyId}/decisions",
|
||||
"GET /api/cloud/stacks",
|
||||
"GET /api/companies/{companyId}/cloud-inference/status",
|
||||
"POST /api/companies/{companyId}/cloud-inference/migrate",
|
||||
"POST /api/companies/{companyId}/cloud-inference/telemetry",
|
||||
"GET /api/companies",
|
||||
"POST /api/companies",
|
||||
"GET /api/companies/stats",
|
||||
@@ -2149,6 +2152,107 @@ registry.registerPath({
|
||||
},
|
||||
});
|
||||
|
||||
const cloudTrialInferenceStatusSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
provider: z.literal("openrouter"),
|
||||
status: z.enum(CLOUD_TRIAL_INFERENCE_STATUSES),
|
||||
reason: z.string().optional(),
|
||||
limitUsdCents: z.number().int(),
|
||||
spentUsdCents: z.number().int(),
|
||||
remainingUsdCents: z.number().int(),
|
||||
defaultModel: z.string(),
|
||||
canMigrate: z.boolean(),
|
||||
trialAgentIds: z.array(z.string().uuid()),
|
||||
trialAgents: z.array(
|
||||
z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
role: z.string(),
|
||||
title: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
blockedRun: z
|
||||
.object({
|
||||
runId: z.string().uuid(),
|
||||
agentId: z.string().uuid(),
|
||||
issueId: z.string().uuid().nullable(),
|
||||
failedAt: z.string(),
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
|
||||
const migrateCloudTrialAgentsResultSchema = z.object({
|
||||
migratedCount: z.number().int(),
|
||||
agents: z.array(
|
||||
z.object({
|
||||
agentId: z.string().uuid(),
|
||||
name: z.string(),
|
||||
adapterType: z.string(),
|
||||
runnerProvider: z.string().optional(),
|
||||
acpxAgent: z.string().optional(),
|
||||
model: z.string(),
|
||||
}),
|
||||
),
|
||||
resumedRunIds: z.array(z.string().uuid()),
|
||||
resumedIssueId: z.string().uuid().nullable(),
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies/{companyId}/cloud-inference/status",
|
||||
tags: ["cloud"],
|
||||
summary: "Get Cloud starter inference status for a company",
|
||||
description:
|
||||
"Requires an authenticated board session with access to companyId. Returns starter-inference state, trial-bound agents, and whether the caller can migrate them (canMigrate).",
|
||||
request: {
|
||||
params: z.object({ companyId: z.string().uuid() }),
|
||||
query: z.object({
|
||||
refresh: z.enum(["1", "true"]).optional(),
|
||||
}),
|
||||
},
|
||||
responses: {
|
||||
200: r.ok(cloudTrialInferenceStatusSchema),
|
||||
403: r.forbidden,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/cloud-inference/migrate",
|
||||
tags: ["cloud"],
|
||||
summary: "Migrate Cloud starter trial agents onto a connected model provider",
|
||||
description:
|
||||
"Requires a non-viewer board user with agent_config:update (or setup-draft creator authority) for every target trial agent, plus ownership or connections:configure authority for the selected AI connection.",
|
||||
request: {
|
||||
params: z.object({ companyId: z.string().uuid() }),
|
||||
body: jsonBody(migrateCloudTrialAgentsSchema),
|
||||
},
|
||||
responses: {
|
||||
200: r.ok(migrateCloudTrialAgentsResultSchema),
|
||||
400: r.badRequest,
|
||||
403: r.forbidden,
|
||||
404: r.notFound,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/cloud-inference/telemetry",
|
||||
tags: ["cloud"],
|
||||
summary: "Record Cloud starter inference onboarding exposure or prompt telemetry",
|
||||
description:
|
||||
"Requires an authenticated board session with access to companyId. Emits Cloud-only PostHog funnel events (no-op on self-hosted instances).",
|
||||
request: {
|
||||
params: z.object({ companyId: z.string().uuid() }),
|
||||
body: jsonBody(cloudTrialTelemetryEventSchema),
|
||||
},
|
||||
responses: {
|
||||
204: { description: "Recorded" },
|
||||
400: r.badRequest,
|
||||
403: r.forbidden,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies",
|
||||
|
||||
@@ -53,6 +53,7 @@ function projectAuthConflict(files: string[]) {
|
||||
export const AI_AUTH_ENV_KEYS = [
|
||||
"COPILOT_GITHUB_TOKEN",
|
||||
"PAPERCLIP_AI_PROVIDER_KEY", "PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_CODEX_PROVIDERS",
|
||||
"PAPERCLIP_OPENROUTER_PROXY_URL", "PAPERCLIP_OPENROUTER_PROXY_TOKEN",
|
||||
"GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL", "GOOGLE_GENAI_USE_VERTEXAI",
|
||||
"GEMINI_HOME", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_ACCESS_TOKEN", "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET",
|
||||
"HERMES_HOME", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_BEARER_TOKEN_BEDROCK", "AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_SHARED_CREDENTIALS_FILE", "AWS_CONFIG_FILE", "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
|
||||
@@ -18,6 +18,7 @@ const CLOUD_STAGING_EXPERIMENTAL_KEYS: ReadonlySet<string> = new Set([
|
||||
"enableExternalObjects",
|
||||
"enableFastResponses",
|
||||
"enableFirstTaskPlanProposal",
|
||||
"enableCloudTrialInference",
|
||||
"enableGitHubReviewBots",
|
||||
"enableGoogleWorkspaceConnector",
|
||||
"enableAwsConnector",
|
||||
|
||||
@@ -54,6 +54,7 @@ export function posthogUiHost(ingestHost: string): string | null {
|
||||
export function resolveBrowserAnalyticsConfig(
|
||||
env: CloudInstanceEnv = process.env,
|
||||
headers: RequestHeaders = {},
|
||||
options?: { cloudTrialInferenceEnabled?: boolean },
|
||||
): BrowserAnalyticsConfig | null {
|
||||
const config = resolveBrowserPostHogConfig(env);
|
||||
if (!config) return null;
|
||||
@@ -74,5 +75,9 @@ export function resolveBrowserAnalyticsConfig(
|
||||
stackId: config.stackId,
|
||||
replayEnabled: config.replayEnabled,
|
||||
consentRequired: resolveAnalyticsConsentRequired(env, headers),
|
||||
cloudTrialInferenceEnabled:
|
||||
typeof options?.cloudTrialInferenceEnabled === "boolean"
|
||||
? options.cloudTrialInferenceEnabled
|
||||
: config.cloudTrialInferenceEnabled,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Process-scoped resolved state for the Cloud starter-inference experiment flag.
|
||||
*
|
||||
* `instance-settings.ts` updates this whenever the effective experimental
|
||||
* settings are resolved (including staging database overrides), while PostHog
|
||||
* direct transport and browser analytics read it so runtime behavior,
|
||||
* `$feature/cloud-trial-inference`, browser super-properties, `$groupidentify`,
|
||||
* and server events always agree on the active cohort.
|
||||
*
|
||||
* Kept in its own leaf module (separate from `telemetry.ts`) so existing tests
|
||||
* that mock `../telemetry.js` never break on an unmocked export.
|
||||
*/
|
||||
let resolvedCloudTrialInferenceEnabled: boolean | null = null;
|
||||
const listeners = new Set<(enabled: boolean) => void>();
|
||||
|
||||
export function setResolvedCloudTrialInferenceEnabled(enabled: boolean): void {
|
||||
const changed = resolvedCloudTrialInferenceEnabled !== enabled;
|
||||
resolvedCloudTrialInferenceEnabled = enabled;
|
||||
if (changed) {
|
||||
for (const listener of listeners) {
|
||||
try {
|
||||
listener(enabled);
|
||||
} catch {
|
||||
// Best-effort analytics listeners must never disrupt settings reads.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getResolvedCloudTrialInferenceEnabled(): boolean | null {
|
||||
return resolvedCloudTrialInferenceEnabled;
|
||||
}
|
||||
|
||||
export function onCloudTrialInferenceCohortChange(
|
||||
listener: (enabled: boolean) => void,
|
||||
): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function resetResolvedCloudTrialInferenceEnabledForTests(): void {
|
||||
resolvedCloudTrialInferenceEnabled = null;
|
||||
listeners.clear();
|
||||
}
|
||||
@@ -1,4 +1,38 @@
|
||||
import { isCloudManagedInstance, type CloudInstanceEnv } from "./cloud-instance.js";
|
||||
import { getResolvedCloudTrialInferenceEnabled } from "./cloud-posthog-cohort.js";
|
||||
|
||||
/**
|
||||
* PostHog experiment / feature flag key for the Cloud starter-inference A/B test.
|
||||
* Stamped onto workspace groups, direct server events, browser super-properties,
|
||||
* and `$feature_flag_called` exposure events so every onboarding, activation,
|
||||
* conversion, and retention chart can split treatment vs. control cleanly.
|
||||
*/
|
||||
export const CLOUD_TRIAL_INFERENCE_FLAG_KEY = "cloud-trial-inference";
|
||||
export type CloudTrialInferenceCohort = "treatment" | "control";
|
||||
|
||||
export function cloudTrialInferenceCohort(enabled: boolean): CloudTrialInferenceCohort {
|
||||
return enabled ? "treatment" : "control";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves whether `enableCloudTrialInference` is active in this stack's
|
||||
* `PAPERCLIP_MANAGED_CONFIG` document. Fails closed (`false`) if absent or
|
||||
* malformed so analytics never throw on startup.
|
||||
*/
|
||||
export function resolveCloudTrialInferenceEnabled(env: CloudInstanceEnv = process.env): boolean {
|
||||
if (env === process.env) {
|
||||
const resolved = getResolvedCloudTrialInferenceEnabled();
|
||||
if (resolved !== null) return resolved;
|
||||
}
|
||||
const raw = env.PAPERCLIP_MANAGED_CONFIG?.trim();
|
||||
if (!raw) return false;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as { features?: Record<string, unknown> } | null;
|
||||
return parsed?.features?.enableCloudTrialInference === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PostHog settings for a Paperclip Cloud stack. Present only on a
|
||||
@@ -13,6 +47,7 @@ export type CloudPostHogConfig = {
|
||||
directEnabled: boolean; // PAPERCLIP_POSTHOG_DIRECT !== "0"
|
||||
browserEnabled: boolean; // PAPERCLIP_POSTHOG_BROWSER_ENABLED === "1"
|
||||
replayEnabled: boolean; // browserEnabled && PAPERCLIP_POSTHOG_REPLAY_ENABLED !== "0"
|
||||
cloudTrialInferenceEnabled: boolean; // PAPERCLIP_MANAGED_CONFIG.features.enableCloudTrialInference
|
||||
};
|
||||
|
||||
export const DEFAULT_CLOUD_POSTHOG_HOST = "https://us.i.posthog.com";
|
||||
@@ -39,6 +74,7 @@ export function resolveCloudPostHogConfig(
|
||||
directEnabled: readEnv(env, "PAPERCLIP_POSTHOG_DIRECT") !== "0",
|
||||
browserEnabled,
|
||||
replayEnabled: browserEnabled && readEnv(env, "PAPERCLIP_POSTHOG_REPLAY_ENABLED") !== "0",
|
||||
cloudTrialInferenceEnabled: resolveCloudTrialInferenceEnabled(env),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { MigrateCloudTrialAgentsInput } from "@paperclipai/shared";
|
||||
import type { AuthorizationActor } from "./authorization.js";
|
||||
import type { CloudInstanceEnv } from "./cloud-instance.js";
|
||||
import {
|
||||
CloudTrialExhaustedError,
|
||||
createCloudTrialKeyStore,
|
||||
isCloudTrialExhaustedError,
|
||||
} from "./cloud-trial-key-store.js";
|
||||
import {
|
||||
migrateCloudTrialAgents,
|
||||
type CloudTrialMigrationActor,
|
||||
} from "./cloud-trial-migration.js";
|
||||
import {
|
||||
createCloudTrialProxy,
|
||||
type PreparedCloudTrialRuntime,
|
||||
} from "./cloud-trial-proxy.js";
|
||||
import {
|
||||
assertCloudTrialInferenceEligible,
|
||||
getCompanyCloudTrialStatus,
|
||||
} from "./cloud-trial-status.js";
|
||||
|
||||
export {
|
||||
CloudTrialExhaustedError,
|
||||
isCloudTrialExhaustedError,
|
||||
assertCloudTrialInferenceEligible,
|
||||
type PreparedCloudTrialRuntime,
|
||||
};
|
||||
|
||||
export interface CloudTrialInferenceOptions {
|
||||
env?: CloudInstanceEnv;
|
||||
fetchImpl?: typeof fetch;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export function createCloudTrialInferenceController(opts: CloudTrialInferenceOptions = {}) {
|
||||
const keyStore = createCloudTrialKeyStore(opts);
|
||||
const proxy = createCloudTrialProxy(keyStore);
|
||||
|
||||
return {
|
||||
prepareCloudTrialRuntime: proxy.prepareCloudTrialRuntime,
|
||||
proxyOpenRouterRequest: proxy.proxyOpenRouterRequest,
|
||||
getCompanyStatus: (
|
||||
db: Db,
|
||||
companyId: string,
|
||||
options: { refreshUsage?: boolean; actor?: AuthorizationActor } = {},
|
||||
) => getCompanyCloudTrialStatus(db, companyId, keyStore, options),
|
||||
migrateTrialAgents: (
|
||||
db: Db,
|
||||
companyId: string,
|
||||
input: MigrateCloudTrialAgentsInput,
|
||||
actor: CloudTrialMigrationActor,
|
||||
) => migrateCloudTrialAgents(db, companyId, input, actor, keyStore),
|
||||
markExhausted: keyStore.markExhausted,
|
||||
probeOpenRouterUsage: keyStore.probeOpenRouterUsage,
|
||||
_resetForTests: () => {
|
||||
proxy.clearTokens();
|
||||
keyStore._resetForTests();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type CloudTrialInferenceController = ReturnType<
|
||||
typeof createCloudTrialInferenceController
|
||||
>;
|
||||
|
||||
let defaultController: CloudTrialInferenceController | null = null;
|
||||
|
||||
export function setDefaultCloudTrialInferenceController(
|
||||
controller: CloudTrialInferenceController,
|
||||
): void {
|
||||
defaultController = controller;
|
||||
}
|
||||
|
||||
export function getDefaultCloudTrialInferenceController(): CloudTrialInferenceController {
|
||||
if (!defaultController) {
|
||||
defaultController = createCloudTrialInferenceController();
|
||||
}
|
||||
return defaultController;
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
import { createPrivateKey, sign } from "node:crypto";
|
||||
import {
|
||||
CLOUD_TRIAL_DEFAULT_LIMIT_USD_CENTS,
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
parseCloudTrialMigrationTargetsEnv,
|
||||
resolveCloudTrialModel,
|
||||
type CloudTrialInferenceState,
|
||||
type CloudTrialMigrationTargetOverrides,
|
||||
} from "@paperclipai/shared";
|
||||
import { HttpError } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { getCloudStackContext, type CloudInstanceEnv } from "./cloud-instance.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;
|
||||
|
||||
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,
|
||||
...details,
|
||||
});
|
||||
this.name = "CloudTrialExhaustedError";
|
||||
}
|
||||
}
|
||||
|
||||
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 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;
|
||||
|
||||
// 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;
|
||||
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) {
|
||||
publishLiveEvent({
|
||||
companyId: input.companyId,
|
||||
type: "cloud_trial.status.updated",
|
||||
payload: {
|
||||
status: "exhausted",
|
||||
limitUsdCents,
|
||||
spentUsdCents,
|
||||
remainingUsdCents: 0,
|
||||
agentId: input.agentId ?? null,
|
||||
runId: input.runId ?? null,
|
||||
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,
|
||||
markExhausted,
|
||||
probeOpenRouterUsage,
|
||||
_resetForTests: () => {
|
||||
cached = null;
|
||||
inflightFetch = null;
|
||||
keyIssuedTracked = false;
|
||||
keyIssuedAtMs = null;
|
||||
trialRunsCount = 0;
|
||||
exhaustedTracked = false;
|
||||
exhaustedAtMs = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type CloudTrialKeyStore = ReturnType<typeof createCloudTrialKeyStore>;
|
||||
@@ -0,0 +1,332 @@
|
||||
import { and, eq, inArray, ne } from "drizzle-orm";
|
||||
import {
|
||||
agents,
|
||||
agentTaskSessions,
|
||||
connectionGrants,
|
||||
toolConnections,
|
||||
type Db,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
defaultMigrationTargetForProvider,
|
||||
isAgentUsingCloudTrialInference,
|
||||
type MigrateCloudTrialAgentsInput,
|
||||
type MigrateCloudTrialAgentsResult,
|
||||
type MigratedCloudTrialAgentSummary,
|
||||
} from "@paperclipai/shared";
|
||||
import { badRequest, forbidden, notFound } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import type { AuthorizationActor } from "./authorization.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { createAgentLifecycle } from "./agent-lifecycle.js";
|
||||
import { connectionManagementService } from "./connection-management.js";
|
||||
import { heartbeatService } from "./heartbeat.js";
|
||||
import { publishLiveEvent } from "./live-events.js";
|
||||
import { toolAccessService } from "./tool-access.js";
|
||||
import { trackCloudPostHogEvent } from "../telemetry.js";
|
||||
import { readJsonRecord, type CloudTrialKeyStore } from "./cloud-trial-key-store.js";
|
||||
import {
|
||||
canActorConfigureTrialAgent,
|
||||
findLatestExhaustedTrialRun,
|
||||
} from "./cloud-trial-status.js";
|
||||
|
||||
export interface CloudTrialMigrationActor {
|
||||
userId: string;
|
||||
actor?: AuthorizationActor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrates all (or selected) Cloud-trial agents in a company onto a newly
|
||||
* connected user subscription / API key:
|
||||
* 1. Verifies connection + grant belong to the company, are active, and are permitted.
|
||||
* 2. Verifies the caller has `agent_config:update` (or setup-draft creator) authority
|
||||
* for every target trial agent.
|
||||
* 3. Ensures every target agent has an install for the selected connection via the
|
||||
* existing connection service (creating authorized missing installs before mutating).
|
||||
* 4. Updates agent configuration through `createAgentLifecycle(db).updateConfiguration`,
|
||||
* clears incompatible task sessions, and optionally resumes the latest blocked run.
|
||||
*/
|
||||
export async function migrateCloudTrialAgents(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
input: MigrateCloudTrialAgentsInput,
|
||||
actorCtx: CloudTrialMigrationActor,
|
||||
keyStore: CloudTrialKeyStore,
|
||||
): Promise<MigrateCloudTrialAgentsResult> {
|
||||
// 1. Verify the connection + grant belong to this company and are active.
|
||||
const [grantRow] = await db
|
||||
.select({
|
||||
connection: toolConnections,
|
||||
grant: connectionGrants,
|
||||
})
|
||||
.from(connectionGrants)
|
||||
.innerJoin(
|
||||
toolConnections,
|
||||
and(
|
||||
eq(toolConnections.id, connectionGrants.connectionId),
|
||||
eq(toolConnections.companyId, connectionGrants.companyId),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(connectionGrants.companyId, companyId),
|
||||
eq(connectionGrants.id, input.grantId),
|
||||
eq(toolConnections.id, input.connectionId),
|
||||
eq(toolConnections.connectionPurpose, "ai"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!grantRow) {
|
||||
throw notFound("Selected AI connection grant was not found for this company");
|
||||
}
|
||||
if (grantRow.grant.status !== "active" || !grantRow.connection.enabled) {
|
||||
throw badRequest("Selected AI connection is not active");
|
||||
}
|
||||
if (grantRow.grant.kind === "user" && grantRow.grant.subjectUserId !== actorCtx.userId) {
|
||||
throw forbidden("You cannot migrate agents onto another user's personal AI connection");
|
||||
}
|
||||
|
||||
const companyAgents = await db
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(
|
||||
and(
|
||||
eq(agents.companyId, companyId),
|
||||
ne(agents.status, "terminated"),
|
||||
ne(agents.status, "pending_approval"),
|
||||
),
|
||||
);
|
||||
|
||||
const requestedIds = input.agentIds ? new Set(input.agentIds) : null;
|
||||
const targets = companyAgents.filter((agent) => {
|
||||
if (!isAgentUsingCloudTrialInference(agent.runtimeConfig)) return false;
|
||||
if (requestedIds && !requestedIds.has(agent.id)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
// 2. Check per-agent configuration authority before making any mutation.
|
||||
if (actorCtx.actor) {
|
||||
for (const agent of targets) {
|
||||
const allowed = await canActorConfigureTrialAgent(db, actorCtx.actor, agent);
|
||||
if (!allowed) {
|
||||
throw forbidden("You do not have permission to update this agent's model configuration");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Check & add missing connection install access atomically under the
|
||||
// connection write lock so concurrent access changes are never overwritten.
|
||||
if (targets.length > 0) {
|
||||
const toolAccess = toolAccessService(db);
|
||||
const existingInstalls = await toolAccess.listConnectionInstalls(input.connectionId);
|
||||
const hasCompanyInstall = existingInstalls.some(
|
||||
(install) => install.targetType === "company" && install.targetId === companyId,
|
||||
);
|
||||
if (!hasCompanyInstall) {
|
||||
const installedAgentIds = new Set(
|
||||
existingInstalls
|
||||
.filter((install) => install.targetType === "agent")
|
||||
.map((install) => install.targetId),
|
||||
);
|
||||
const missingAgentIds = targets
|
||||
.map((agent) => agent.id)
|
||||
.filter((agentId) => !installedAgentIds.has(agentId));
|
||||
|
||||
if (missingAgentIds.length > 0) {
|
||||
let managementContext = undefined;
|
||||
if (actorCtx.actor) {
|
||||
managementContext = await connectionManagementService(db).authorize(
|
||||
actorCtx.actor,
|
||||
"connections:configure",
|
||||
{
|
||||
type: "connection_management",
|
||||
companyId,
|
||||
connectionId: input.connectionId,
|
||||
purpose: "ai",
|
||||
operation: "POST /api/companies/:companyId/cloud-inference/migrate",
|
||||
selfServiceUserId:
|
||||
grantRow.grant.kind === "user" ? grantRow.grant.subjectUserId : null,
|
||||
selfServiceAgentInstalls: true,
|
||||
},
|
||||
{ targetAgentIds: missingAgentIds },
|
||||
);
|
||||
}
|
||||
await toolAccess.ensureAgentConnectionInstalls(
|
||||
input.connectionId,
|
||||
missingAgentIds,
|
||||
{
|
||||
actorType: "user",
|
||||
actorId: actorCtx.userId,
|
||||
responsibleUserId: actorCtx.userId,
|
||||
...(managementContext ? { managementContext } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const targetSpec = defaultMigrationTargetForProvider(
|
||||
input.provider,
|
||||
input.method,
|
||||
input.model,
|
||||
keyStore.configuredMigrationTargets(),
|
||||
);
|
||||
const binding = {
|
||||
provider: input.provider,
|
||||
method: input.method,
|
||||
mode: input.ownership === "shared" ? ("shared" as const) : ("delegated" as const),
|
||||
connectionId: input.connectionId,
|
||||
grantId: input.grantId,
|
||||
};
|
||||
|
||||
// 4. Update each target agent through the agent-lifecycle module boundary.
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const migrated: MigratedCloudTrialAgentSummary[] = [];
|
||||
const migratedAgentIds: string[] = [];
|
||||
|
||||
for (const agent of targets) {
|
||||
const currentAdapterConfig = readJsonRecord(agent.adapterConfig);
|
||||
const nextAdapterConfig: Record<string, unknown> = {
|
||||
...currentAdapterConfig,
|
||||
model: targetSpec.model,
|
||||
};
|
||||
if (targetSpec.runnerProvider) {
|
||||
nextAdapterConfig.provider = targetSpec.runnerProvider;
|
||||
} else {
|
||||
delete nextAdapterConfig.provider;
|
||||
}
|
||||
if (targetSpec.acpxAgent) {
|
||||
nextAdapterConfig.acpxAgent = targetSpec.acpxAgent;
|
||||
} else {
|
||||
delete nextAdapterConfig.acpxAgent;
|
||||
}
|
||||
|
||||
const currentRuntimeConfig = readJsonRecord(agent.runtimeConfig);
|
||||
const nextRuntimeConfig: Record<string, unknown> = {
|
||||
...currentRuntimeConfig,
|
||||
aiConnection: binding,
|
||||
};
|
||||
delete nextRuntimeConfig.cloudTrialInference;
|
||||
|
||||
await lifecycle.updateConfiguration(agent.id, {
|
||||
adapterType: targetSpec.adapterType,
|
||||
adapterConfig: nextAdapterConfig,
|
||||
runtimeConfig: nextRuntimeConfig,
|
||||
});
|
||||
|
||||
migratedAgentIds.push(agent.id);
|
||||
migrated.push({
|
||||
agentId: agent.id,
|
||||
name: agent.name,
|
||||
adapterType: targetSpec.adapterType,
|
||||
...(targetSpec.runnerProvider ? { runnerProvider: targetSpec.runnerProvider } : {}),
|
||||
...(targetSpec.acpxAgent ? { acpxAgent: targetSpec.acpxAgent } : {}),
|
||||
model: targetSpec.model,
|
||||
});
|
||||
}
|
||||
|
||||
if (migratedAgentIds.length > 0) {
|
||||
// Reset incompatible provider task sessions so resumed work starts fresh on the new harness.
|
||||
await db
|
||||
.delete(agentTaskSessions)
|
||||
.where(
|
||||
and(
|
||||
eq(agentTaskSessions.companyId, companyId),
|
||||
inArray(agentTaskSessions.agentId, migratedAgentIds),
|
||||
),
|
||||
);
|
||||
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: "user",
|
||||
actorId: actorCtx.userId,
|
||||
action: "cloud_trial.agents_migrated",
|
||||
entityType: "company",
|
||||
entityId: companyId,
|
||||
details: {
|
||||
provider: input.provider,
|
||||
method: input.method,
|
||||
connectionId: input.connectionId,
|
||||
migratedAgentIds,
|
||||
targetAdapterType: targetSpec.adapterType,
|
||||
targetRunnerProvider: targetSpec.runnerProvider ?? null,
|
||||
targetAcpxAgent: targetSpec.acpxAgent ?? null,
|
||||
targetModel: targetSpec.model,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Resume the most recent blocked turn/issue if requested (only when latest run was exhausted).
|
||||
const resumedRunIds: string[] = [];
|
||||
let resumedIssueId: string | null = null;
|
||||
if (input.resumeBlockedWork && migratedAgentIds.length > 0) {
|
||||
const blocked = await findLatestExhaustedTrialRun(db, companyId, migratedAgentIds);
|
||||
if (blocked) {
|
||||
resumedIssueId = blocked.issueId;
|
||||
try {
|
||||
const woke = await heartbeatService(db).wakeup(blocked.agentId, {
|
||||
source: "on_demand",
|
||||
triggerDetail: "manual",
|
||||
reason: "cloud_trial_migrated_resume",
|
||||
requestedByActorType: "user",
|
||||
requestedByActorId: actorCtx.userId,
|
||||
payload: resumedIssueId ? { issueId: resumedIssueId } : undefined,
|
||||
contextSnapshot: {
|
||||
...(resumedIssueId ? { issueId: resumedIssueId, taskId: resumedIssueId } : {}),
|
||||
wakeReason: "cloud_trial_migrated_resume",
|
||||
source: "cloud_trial_migration",
|
||||
},
|
||||
});
|
||||
if (woke?.id) {
|
||||
resumedRunIds.push(woke.id);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, companyId, agentId: blocked.agentId, issueId: resumedIssueId },
|
||||
"Migrated trial agents succeeded, but auto-resuming the blocked run failed",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
publishLiveEvent({
|
||||
companyId,
|
||||
type: "cloud_trial.status.updated",
|
||||
payload: {
|
||||
status: "migrated",
|
||||
migratedCount: migrated.length,
|
||||
provider: input.provider,
|
||||
resumedRunIds,
|
||||
resumedIssueId,
|
||||
},
|
||||
});
|
||||
|
||||
const exhaustedAtMs = keyStore.getExhaustedAtMs();
|
||||
const secondsSinceExhausted =
|
||||
exhaustedAtMs !== null
|
||||
? Math.max(0, Math.round((keyStore.now() - exhaustedAtMs) / 1000))
|
||||
: undefined;
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.migrated",
|
||||
{
|
||||
provider: input.provider,
|
||||
auth_method: input.method,
|
||||
ownership: input.ownership,
|
||||
migrated_agent_count: migrated.length,
|
||||
resumed_run_count: resumedRunIds.length,
|
||||
target_adapter_type: targetSpec.adapterType,
|
||||
target_model: targetSpec.model,
|
||||
...(secondsSinceExhausted !== undefined
|
||||
? { seconds_since_exhausted: secondsSinceExhausted }
|
||||
: {}),
|
||||
},
|
||||
{ userId: actorCtx.userId, companyId },
|
||||
);
|
||||
|
||||
return {
|
||||
migratedCount: migrated.length,
|
||||
agents: migrated,
|
||||
resumedRunIds,
|
||||
resumedIssueId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
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 } from "@paperclipai/shared";
|
||||
import { OPENROUTER_ATTRIBUTION_HEADERS } from "@paperclipai/shared/openrouter-attribution";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import {
|
||||
CloudTrialExhaustedError,
|
||||
readJsonRecord,
|
||||
stripOpenRouterPrefix,
|
||||
type CloudTrialKeyStore,
|
||||
} from "./cloud-trial-key-store.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>;
|
||||
}
|
||||
|
||||
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;
|
||||
},
|
||||
): Promise<PreparedCloudTrialRuntime> {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
if (!experimental.enableCloudTrialInference) {
|
||||
throw unprocessable("Cloud starter inference is not enabled on this instance.", {
|
||||
code: "cloud_trial_disabled",
|
||||
});
|
||||
}
|
||||
|
||||
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")}`;
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
prepareCloudTrialRuntime,
|
||||
proxyOpenRouterRequest,
|
||||
clearTokens: () => activeRunTokens.clear(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
import { and, desc, eq, inArray, ne } from "drizzle-orm";
|
||||
import {
|
||||
agents,
|
||||
heartbeatRuns,
|
||||
toolConnections,
|
||||
type Db,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
isAgentUsingCloudTrialInference,
|
||||
type CloudTrialBlockedRunSummary,
|
||||
type CloudTrialInferenceState,
|
||||
type CloudTrialInferenceStatus,
|
||||
} from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { accessService } from "./access.js";
|
||||
import type { AuthorizationActor } from "./authorization.js";
|
||||
import { isAgentSetupDraft } from "../modules/agent-lifecycle/index.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import type { CloudTrialKeyStore } from "./cloud-trial-key-store.js";
|
||||
|
||||
const EXHAUSTION_ERROR_CODES = new Set([
|
||||
CLOUD_TRIAL_EXHAUSTED_ERROR_CODE,
|
||||
"native_provider_usage_limit",
|
||||
]);
|
||||
|
||||
export interface TrialAgentCandidate {
|
||||
id: string;
|
||||
companyId: string;
|
||||
createdByUserId?: string | null;
|
||||
lifecycleState?: string;
|
||||
pauseReason?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors `assertCanConfigureAgentSetup` in `routes/agents.ts`:
|
||||
* requires `agent_config:update` on the target agent, or setup-draft creator
|
||||
* authority (`agents:create` + `createdByUserId === actor.userId` + draft state).
|
||||
*/
|
||||
export async function canActorConfigureTrialAgent(
|
||||
db: Db,
|
||||
actor: AuthorizationActor,
|
||||
targetAgent: TrialAgentCandidate,
|
||||
): Promise<boolean> {
|
||||
if (actor.type !== "board" || !actor.userId) return false;
|
||||
if (actor.isInstanceAdmin) return true;
|
||||
const access = accessService(db);
|
||||
if (targetAgent.createdByUserId === actor.userId && isAgentSetupDraft(targetAgent)) {
|
||||
const createDecision = await access.decide({
|
||||
actor,
|
||||
action: "agents:create",
|
||||
resource: { type: "company", companyId: targetAgent.companyId },
|
||||
});
|
||||
if (createDecision.allowed) return true;
|
||||
}
|
||||
const updateDecision = await access.decide({
|
||||
actor,
|
||||
action: "agent_config:update",
|
||||
resource: { type: "agent", companyId: targetAgent.companyId, agentId: targetAgent.id },
|
||||
});
|
||||
return updateDecision.allowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforces server-side eligibility before any route permits setting
|
||||
* `runtimeConfig.cloudTrialInference: true`: the instance flag must be
|
||||
* enabled and the company must not already have an active AI connection.
|
||||
*/
|
||||
export async function assertCloudTrialInferenceEligible(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
): Promise<void> {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
if (!experimental.enableCloudTrialInference) {
|
||||
throw unprocessable("Cloud starter inference is not enabled on this instance.", {
|
||||
code: "cloud_trial_disabled",
|
||||
});
|
||||
}
|
||||
const [existingAiConnection] = await db
|
||||
.select({ id: toolConnections.id })
|
||||
.from(toolConnections)
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnections.companyId, companyId),
|
||||
eq(toolConnections.connectionPurpose, "ai"),
|
||||
eq(toolConnections.enabled, true),
|
||||
eq(toolConnections.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (existingAiConnection) {
|
||||
throw unprocessable(
|
||||
"Cloud starter inference is only available before a model provider is connected.",
|
||||
{ code: "cloud_trial_ineligible_existing_connection" },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the most recent blocked trial run ONLY among agents whose *latest* run
|
||||
* ended with a trial exhaustion error. Once credits are restored or a newer
|
||||
* run succeeds, older historical failures no longer pin the blocking modal.
|
||||
*/
|
||||
export async function findLatestExhaustedTrialRun(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
trialAgentIds: string[],
|
||||
): Promise<CloudTrialBlockedRunSummary | null> {
|
||||
if (trialAgentIds.length === 0) return null;
|
||||
|
||||
const recentRuns = await db
|
||||
.select({
|
||||
id: heartbeatRuns.id,
|
||||
agentId: heartbeatRuns.agentId,
|
||||
issueId: heartbeatRuns.issueId,
|
||||
nativeIssueId: heartbeatRuns.nativeIssueId,
|
||||
errorCode: heartbeatRuns.errorCode,
|
||||
finishedAt: heartbeatRuns.finishedAt,
|
||||
createdAt: heartbeatRuns.createdAt,
|
||||
})
|
||||
.from(heartbeatRuns)
|
||||
.where(
|
||||
and(
|
||||
eq(heartbeatRuns.companyId, companyId),
|
||||
inArray(heartbeatRuns.agentId, trialAgentIds),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(heartbeatRuns.createdAt))
|
||||
.limit(Math.max(trialAgentIds.length * 4, 20));
|
||||
|
||||
const seenAgents = new Set<string>();
|
||||
for (const run of recentRuns) {
|
||||
if (seenAgents.has(run.agentId)) continue;
|
||||
seenAgents.add(run.agentId);
|
||||
if (run.errorCode && EXHAUSTION_ERROR_CODES.has(run.errorCode)) {
|
||||
return {
|
||||
runId: run.id,
|
||||
agentId: run.agentId,
|
||||
issueId: run.nativeIssueId ?? run.issueId ?? null,
|
||||
failedAt: (run.finishedAt ?? run.createdAt).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function getCompanyCloudTrialStatus(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
keyStore: CloudTrialKeyStore,
|
||||
options: { refreshUsage?: boolean; actor?: AuthorizationActor } = {},
|
||||
): Promise<CloudTrialInferenceStatus> {
|
||||
const experimental = await instanceSettingsService(db).getExperimental();
|
||||
const enabled = experimental.enableCloudTrialInference === true;
|
||||
|
||||
const companyAgents = await db
|
||||
.select({
|
||||
id: agents.id,
|
||||
companyId: agents.companyId,
|
||||
name: agents.name,
|
||||
role: agents.role,
|
||||
title: agents.title,
|
||||
runtimeConfig: agents.runtimeConfig,
|
||||
createdByUserId: agents.createdByUserId,
|
||||
lifecycleState: agents.lifecycleState,
|
||||
pauseReason: agents.pauseReason,
|
||||
})
|
||||
.from(agents)
|
||||
.where(
|
||||
and(
|
||||
eq(agents.companyId, companyId),
|
||||
ne(agents.status, "terminated"),
|
||||
ne(agents.status, "pending_approval"),
|
||||
),
|
||||
);
|
||||
|
||||
const trialAgentRows = companyAgents.filter((a) => isAgentUsingCloudTrialInference(a.runtimeConfig));
|
||||
const trialAgents = trialAgentRows.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
role: a.role,
|
||||
title: a.title,
|
||||
}));
|
||||
const trialAgentIds = trialAgents.map((a) => a.id);
|
||||
|
||||
let canMigrate = true;
|
||||
if (options.actor) {
|
||||
if (options.actor.type !== "board" || !options.actor.userId) {
|
||||
canMigrate = false;
|
||||
} else if (!options.actor.isInstanceAdmin) {
|
||||
const membership = options.actor.memberships?.find(
|
||||
(m) => m.companyId === companyId && m.status === "active",
|
||||
);
|
||||
if (membership?.membershipRole === "viewer") {
|
||||
canMigrate = false;
|
||||
} else if (trialAgentRows.length > 0) {
|
||||
const checks = await Promise.all(
|
||||
trialAgentRows.map((agent) => canActorConfigureTrialAgent(db, options.actor!, agent)),
|
||||
);
|
||||
canMigrate = checks.every(Boolean);
|
||||
} else {
|
||||
const decision = await accessService(db).decide({
|
||||
actor: options.actor,
|
||||
action: "agent_config:update",
|
||||
resource: { type: "company", companyId },
|
||||
});
|
||||
canMigrate = decision.allowed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const blockedRun = await findLatestExhaustedTrialRun(db, companyId, trialAgentIds);
|
||||
|
||||
if (!enabled) {
|
||||
return {
|
||||
enabled: false,
|
||||
provider: "openrouter",
|
||||
status: "unavailable",
|
||||
reason: "feature_disabled",
|
||||
limitUsdCents: 0,
|
||||
spentUsdCents: 0,
|
||||
remainingUsdCents: 0,
|
||||
defaultModel: keyStore.configuredDefaultModel(),
|
||||
canMigrate,
|
||||
trialAgentIds,
|
||||
trialAgents,
|
||||
blockedRun,
|
||||
};
|
||||
}
|
||||
|
||||
let state = keyStore.getCached();
|
||||
if (!state || options.refreshUsage) {
|
||||
try {
|
||||
state = await keyStore.fetchKeyFromCloudOrLocal(Boolean(options.refreshUsage));
|
||||
if (options.refreshUsage && state.status === "active") {
|
||||
await keyStore.probeOpenRouterUsage(companyId, true);
|
||||
state = keyStore.getCached() ?? state;
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn({ err, companyId }, "Failed to fetch Cloud trial inference status");
|
||||
state = {
|
||||
status: "unavailable",
|
||||
reason: "cloud_unavailable",
|
||||
apiKey: null,
|
||||
limitUsdCents: 0,
|
||||
spentUsdCents: 0,
|
||||
remainingUsdCents: 0,
|
||||
defaultModel: keyStore.configuredDefaultModel(),
|
||||
fetchedAtMs: keyStore.now(),
|
||||
lastUsageProbeAtMs: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// If the user already migrated every trial agent to their own subscription, report migrated.
|
||||
const effectiveStatus: CloudTrialInferenceState =
|
||||
state.status === "exhausted" && trialAgentIds.length === 0 && companyAgents.length > 0
|
||||
? "migrated"
|
||||
: blockedRun && state.status === "active"
|
||||
? "exhausted"
|
||||
: state.status;
|
||||
|
||||
return {
|
||||
enabled: true,
|
||||
provider: "openrouter",
|
||||
status: effectiveStatus,
|
||||
...(state.reason ? { reason: state.reason } : {}),
|
||||
limitUsdCents: state.limitUsdCents,
|
||||
spentUsdCents: state.spentUsdCents,
|
||||
remainingUsdCents: effectiveStatus === "exhausted" ? 0 : state.remainingUsdCents,
|
||||
defaultModel: state.defaultModel,
|
||||
canMigrate,
|
||||
trialAgentIds,
|
||||
trialAgents,
|
||||
blockedRun,
|
||||
};
|
||||
}
|
||||
@@ -2221,6 +2221,7 @@ export function heartbeatService(
|
||||
}
|
||||
| undefined;
|
||||
let managedAiRuntime: Awaited<ReturnType<typeof prepareManagedAiRuntime>> | undefined;
|
||||
let cloudTrialRuntimeCleanup: (() => Promise<void>) | undefined;
|
||||
let providerTraceCapture: Awaited<
|
||||
ReturnType<typeof traceStore.prepare>
|
||||
> | null = null;
|
||||
@@ -2956,6 +2957,7 @@ export function heartbeatService(
|
||||
services: { secretsSvc, companySkills, appendRunEvent, finalizeAiConnectionBusyDeferral },
|
||||
onFailureSecretsResolved: (readSecrets) => { readFailureReportSecrets = () => [...readSecrets(), ...identityRedactor.values]; },
|
||||
onManagedAiRuntimeAcquired: (runtime) => { managedAiRuntime = runtime; },
|
||||
onCloudTrialRuntimeCleanup: (cleanup) => { cloudTrialRuntimeCleanup = cleanup; },
|
||||
onIdentityRedactorPrepared: (redactor) => { identityRedactor = redactor; },
|
||||
}));
|
||||
if (!executionConfiguration.prepared) return;
|
||||
@@ -4155,6 +4157,7 @@ export function heartbeatService(
|
||||
let failedProcessCancellationSeen = failedProcessRunCancellations.has(run.id);
|
||||
await instructionWorkingCopy?.nativeInstructionReservation?.release().catch(error => logger.warn({ runId: run.id, err: error }, "Managed warm session preparation cleanup failed"));
|
||||
if (managedAiRuntime) await managedAiRuntime.cleanup().catch(() => logger.warn({ runId: run.id }, "AI connection refresh or cleanup failed"));
|
||||
if (cloudTrialRuntimeCleanup) await cloudTrialRuntimeCleanup().catch(() => logger.warn({ runId: run.id }, "Cloud trial inference proxy cleanup failed"));
|
||||
let latestRun = await getRun(run.id).catch(() => null);
|
||||
if (preparationHandedOff() && (!latestRun || latestRun.status === "running")) nativeSessionResumeScheduled = true;
|
||||
try {
|
||||
|
||||
@@ -17,6 +17,8 @@ import { createAgentIdentityRedactor, secretEnvironmentValues } from "../agent-i
|
||||
import { agentIdentityService, supportsManagedAgentIdentity } from "../agent-identity.js";
|
||||
import { readAiConnectionConfigurationFailure, readAiCredentialAccessFailure } from "../ai-connection-configuration-failure.js";
|
||||
import { AI_AUTH_ENV_KEYS, isAiConnectionBusy, prepareManagedAiRuntime, stripAiAuthBindings } from "../ai-connection-runtime.js";
|
||||
import { getDefaultCloudTrialInferenceController } from "../cloud-trial-inference.js";
|
||||
import { isAgentUsingCloudTrialInference } from "@paperclipai/shared";
|
||||
import { managedAiSessionIdentityCompatible } from "../ai-connection-session.js";
|
||||
import type { companySkillService } from "../company-skills.js";
|
||||
import { connectionIntentService } from "../connection-intents.js";
|
||||
@@ -93,6 +95,7 @@ export interface HeartbeatExecutionConfigurationInput {
|
||||
// The executor must observe these before a later preparation step can throw.
|
||||
onFailureSecretsResolved: (readSecrets: () => string[]) => void;
|
||||
onManagedAiRuntimeAcquired: (runtime: ManagedAiRuntime) => void;
|
||||
onCloudTrialRuntimeCleanup?: (cleanup: () => Promise<void>) => void;
|
||||
onIdentityRedactorPrepared: (redactor: ReturnType<typeof createAgentIdentityRedactor>) => void;
|
||||
}
|
||||
|
||||
@@ -202,9 +205,11 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
|
||||
selectedEnvironmentForConfig?.driver ?? "local",
|
||||
);
|
||||
|
||||
const isCloudTrial = !aiBinding && isAgentUsingCloudTrialInference(agent.runtimeConfig);
|
||||
const stripAiEnv = Boolean(aiBinding) || isCloudTrial;
|
||||
const { resolvedConfig, configuredTaskEnvironment, secretKeys, secretManifest } =
|
||||
await time("configuration_secrets", () => resolveExecutionRunAdapterConfig({
|
||||
managedAiCredentials: Boolean(aiBinding),
|
||||
managedAiCredentials: stripAiEnv,
|
||||
managedGitHubCredentials: !useHostGitHub,
|
||||
companyId: agent.companyId,
|
||||
agentId: agent.id,
|
||||
@@ -212,14 +217,14 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
|
||||
issueId,
|
||||
heartbeatRunId: run.id,
|
||||
environmentId: selectedEnvironmentForConfig?.id ?? null,
|
||||
environmentEnv: aiBinding ? stripAiAuthBindings(selectedEnvironmentForConfig?.envVars) : selectedEnvironmentForConfig?.envVars ?? null,
|
||||
environmentEnv: stripAiEnv ? stripAiAuthBindings(selectedEnvironmentForConfig?.envVars) : selectedEnvironmentForConfig?.envVars ?? null,
|
||||
environmentDriver: selectedEnvironmentForConfig?.driver ?? null,
|
||||
projectId: taskProjectContext?.id ?? null,
|
||||
routineId: routineEnvContext.routineId,
|
||||
responsibleUserId,
|
||||
executionRunConfig: aiBinding ? { ...executionRunConfig, env: stripAiAuthBindings(executionRunConfig.env) } : executionRunConfig,
|
||||
projectEnv: aiBinding ? stripAiAuthBindings(taskProjectContext?.env) : taskProjectContext?.env ?? null,
|
||||
routineEnv: aiBinding ? stripAiAuthBindings(routineEnvContext.env) : routineEnvContext.env,
|
||||
executionRunConfig: stripAiEnv ? { ...executionRunConfig, env: stripAiAuthBindings(executionRunConfig.env) } : executionRunConfig,
|
||||
projectEnv: stripAiEnv ? stripAiAuthBindings(taskProjectContext?.env) : taskProjectContext?.env ?? null,
|
||||
routineEnv: stripAiEnv ? stripAiAuthBindings(routineEnvContext.env) : routineEnvContext.env,
|
||||
secretsSvc,
|
||||
trustPreset,
|
||||
}));
|
||||
@@ -269,6 +274,24 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
|
||||
for (const key of AI_AUTH_ENV_KEYS) secretKeys.add(key);
|
||||
context.aiConnection = { ...managedAiRuntime.attribution, accountName: managedAiRuntime.accountName, identity: managedAiRuntime.identity, sessionIdentity: managedAiRuntime.sessionIdentity };
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ aiConnection: context.aiConnection, ...(context.aiRouterTaskKey ? { aiRouterTaskKey: context.aiRouterTaskKey } : {}), ...(context.aiRouterSelection ? { aiRouterSelection: context.aiRouterSelection } : {}) })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
|
||||
} else if (isAgentUsingCloudTrialInference(agent.runtimeConfig)) {
|
||||
const cloudTrialRuntime = await time("configuration_ai_runtime", () =>
|
||||
getDefaultCloudTrialInferenceController().prepareCloudTrialRuntime(db, {
|
||||
companyId: agent.companyId,
|
||||
agentId: agent.id,
|
||||
runId: run.id,
|
||||
model: typeof resolvedConfig.model === "string" ? resolvedConfig.model : undefined,
|
||||
}),
|
||||
);
|
||||
input.onCloudTrialRuntimeCleanup?.(cloudTrialRuntime.cleanup);
|
||||
const currentEnv = parseObject(resolvedConfig.env);
|
||||
resolvedConfig.env = {
|
||||
...stripAiAuthBindings(currentEnv),
|
||||
...cloudTrialRuntime.env,
|
||||
};
|
||||
resolvedConfig.model = cloudTrialRuntime.defaultModel;
|
||||
for (const key of AI_AUTH_ENV_KEYS) secretKeys.add(key);
|
||||
identityRedactor.addSecretValues(cloudTrialRuntime.secretValues);
|
||||
}
|
||||
if (secretManifest.length > 0) {
|
||||
context.paperclipSecrets = {
|
||||
|
||||
@@ -8,7 +8,8 @@ import { PREDECESSOR_RETIREMENT_FALLBACK_KEY, readPredecessorRetirementFallback,
|
||||
import { releaseUnchangedFallbackWorkspace } from "./predecessor-retirement-fallback.js";
|
||||
import { hasNativeExecutionStartEvidence } from "../native-runtime/native-restart-recovery.js";
|
||||
import { isSandboxProviderDiskFullError, NATIVE_SANDBOX_DISK_FULL } from "../native-runtime/native-sandbox-disk-full.js";
|
||||
import { withoutSqlStatementText } from "@paperclipai/shared";
|
||||
import { CLOUD_TRIAL_EXHAUSTED_ERROR_CODE, withoutSqlStatementText } from "@paperclipai/shared";
|
||||
import { isCloudTrialExhaustedError } from "../cloud-trial-inference.js";
|
||||
import { nativeTaskSessionPublicationHandled } from "../native-runtime/native-task-session-publication.js";
|
||||
import { boundOriginalMessage, describeRefusedExactResume, interruptedExactResumeCause } from "../native-runtime/native-exact-resume-failure.js";
|
||||
import { settledResponsePublicationSql } from "../native-runtime/native-response-publication-receipt.js";
|
||||
@@ -1696,6 +1697,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
const ownedAiSelectionRejection = isOwnedAiConnectionSelectionRejection(
|
||||
configurationIncompleteSetupFailure?.resultJson.configurationIncomplete);
|
||||
const setupFailureErrorCode =
|
||||
(isCloudTrialExhaustedError(outerErr) ? CLOUD_TRIAL_EXHAUSTED_ERROR_CODE : null) ??
|
||||
(controllerLeaseLost && !ownedAiSelectionRejection ? CONTROLLER_LEASE_LOST_FAILURE_CODE : null) ??
|
||||
(storageUnavailable ? STORAGE_UNAVAILABLE_CODE : null) ??
|
||||
remoteWorkspacePreparationTimeout?.code ??
|
||||
|
||||
@@ -19,6 +19,7 @@ import { notifyVoiceChange } from "./voice/voice-recovery-notifications.js";
|
||||
import { notifyToolConnectionHealth } from "./tool-connection-health-notifications.js";
|
||||
import { notifyExternalObjectRefresh } from "./external-object-refresh-notifications.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import { setResolvedCloudTrialInferenceEnabled } from "./cloud-posthog-cohort.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { companies, instanceSettings } from "@paperclipai/db";
|
||||
|
||||
@@ -292,6 +293,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enablePaperclipDeveloperMode: parsed.data.enablePaperclipDeveloperMode ?? false,
|
||||
enableSimplifiedEnglishInteractions: parsed.data.enableSimplifiedEnglishInteractions ?? false,
|
||||
enableFirstTaskPlanProposal: parsed.data.enableFirstTaskPlanProposal ?? false,
|
||||
enableCloudTrialInference: parsed.data.enableCloudTrialInference ?? false,
|
||||
autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false,
|
||||
enableWorkspaceBranchReconcileForward: parsed.data.enableWorkspaceBranchReconcileForward ?? true,
|
||||
enableWorkspaceDirtyQuarantineRepair: parsed.data.enableWorkspaceDirtyQuarantineRepair ?? true,
|
||||
@@ -355,6 +357,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enablePaperclipDeveloperMode: false,
|
||||
enableSimplifiedEnglishInteractions: false,
|
||||
enableFirstTaskPlanProposal: false,
|
||||
enableCloudTrialInference: false,
|
||||
autoRestartDevServerWhenIdle: false,
|
||||
enableWorkspaceBranchReconcileForward: true,
|
||||
enableWorkspaceDirtyQuarantineRepair: true,
|
||||
@@ -508,6 +511,9 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService
|
||||
applyCloudCatalogDefaults(normalizeExperimentalSettings(defaults), defaults, managedConfig),
|
||||
enforcedManagedConfig,
|
||||
);
|
||||
if (!options.runtimeEnv) {
|
||||
setResolvedCloudTrialInferenceEnabled(experimental.enableCloudTrialInference === true);
|
||||
}
|
||||
// Self-hosted responses stay byte-identical: no managedKeys field at all.
|
||||
return managedConfig ? { ...experimental, managedKeys } : experimental;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { and, eq, ne, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agents, companyOnboardingSeeds, goals } from "@paperclipai/db";
|
||||
import type { ApplyOnboardingSeed } from "@paperclipai/shared";
|
||||
import { agents, companyOnboardingSeeds, goals, toolConnections } from "@paperclipai/db";
|
||||
import { resolveCloudTrialModel, type ApplyOnboardingSeed } from "@paperclipai/shared";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { findActiveServerAdapter } from "../adapters/registry.js";
|
||||
import { agentService } from "./agents.js";
|
||||
@@ -10,6 +11,7 @@ import { withDedicatedDbConnection } from "@paperclipai/db";
|
||||
import { PAPERCLIP_CORE_SKILL_KEYS } from "./company-skills.js";
|
||||
import { goalService } from "./goals.js";
|
||||
import { readBuiltInAgentMarker } from "../lib/built-in-agent-metadata.js";
|
||||
import { trackCloudPostHogEvent, trackCloudTrialExposure } from "../telemetry.js";
|
||||
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
|
||||
|
||||
/**
|
||||
@@ -150,20 +152,52 @@ export function onboardingSeedService(db: Db) {
|
||||
if (agentId) {
|
||||
await agentSvc.update(agentId, { name: agentName, title: agentRole });
|
||||
} else {
|
||||
const adapterType = seededAgentAdapterType();
|
||||
const experimental = await instanceSettingsService(dbx).getExperimental();
|
||||
const actorUserId = audit?.actorType === "user" ? audit.actorId : null;
|
||||
trackCloudTrialExposure({
|
||||
surface: "onboarding_seed",
|
||||
userId: actorUserId,
|
||||
companyId,
|
||||
enabledOverride: experimental.enableCloudTrialInference === true,
|
||||
});
|
||||
const existingAiConnections = experimental.enableCloudTrialInference
|
||||
? await dbx
|
||||
.select({ id: toolConnections.id })
|
||||
.from(toolConnections)
|
||||
.where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.connectionPurpose, "ai")))
|
||||
.limit(1)
|
||||
: [];
|
||||
const useCloudTrial =
|
||||
experimental.enableCloudTrialInference && existingAiConnections.length === 0;
|
||||
const adapterType = useCloudTrial ? "paperclip_runner" : seededAgentAdapterType();
|
||||
const trialModel = resolveCloudTrialModel(process.env.PAPERCLIP_CLOUD_TRIAL_MODEL);
|
||||
const adapterConfig = useCloudTrial
|
||||
? {
|
||||
...seededAgentAdapterConfig("paperclip_runner"),
|
||||
provider: "opencode",
|
||||
model: trialModel,
|
||||
}
|
||||
: seededAgentAdapterConfig(adapterType);
|
||||
const created = await createAgentLifecycle(dbx).requestHire(companyId, {
|
||||
name: agentName,
|
||||
role: SEEDED_AGENT_ROLE,
|
||||
title: agentRole,
|
||||
adapterType,
|
||||
adapterConfig: seededAgentAdapterConfig(adapterType),
|
||||
runtimeConfig: {},
|
||||
adapterConfig,
|
||||
runtimeConfig: useCloudTrial ? { cloudTrialInference: true } : {},
|
||||
permissions: {},
|
||||
status: "idle",
|
||||
spentMonthlyCents: 0,
|
||||
lastHeartbeatAt: null,
|
||||
}, { createdByUserId: audit?.actorType === "user" ? audit.actorId : null });
|
||||
}, { createdByUserId: actorUserId });
|
||||
agentId = created.id;
|
||||
if (useCloudTrial) {
|
||||
trackCloudPostHogEvent(
|
||||
"cloud_trial.started",
|
||||
{ source: "onboarding_seed", model: trialModel },
|
||||
{ userId: actorUserId, companyId },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import {
|
||||
PAPERCLIP_ENUM_DESCRIPTIONS,
|
||||
PAPERCLIP_EVENTS,
|
||||
type TelemetryDimensions,
|
||||
type TelemetryEvent,
|
||||
} from "@paperclipai/shared/telemetry";
|
||||
import type { CloudPostHogConfig } from "../cloud-posthog-config.js";
|
||||
import {
|
||||
CLOUD_TRIAL_INFERENCE_FLAG_KEY,
|
||||
cloudTrialInferenceCohort,
|
||||
type CloudPostHogConfig,
|
||||
} from "../cloud-posthog-config.js";
|
||||
import { UNKNOWN_ENUM_FALLBACKS } from "./enum-fallbacks.generated.js";
|
||||
import type { PostHogEventContext } from "./request-context.js";
|
||||
|
||||
@@ -49,7 +53,19 @@ export type PostHogDirectBatchMeta = {
|
||||
ingestedAt: string;
|
||||
};
|
||||
|
||||
type IdentityConfig = Pick<CloudPostHogConfig, "stackId" | "environment">;
|
||||
type IdentityConfig = Pick<CloudPostHogConfig, "stackId" | "environment"> & {
|
||||
cloudTrialInferenceEnabled?: boolean;
|
||||
};
|
||||
|
||||
export function cloudExperimentProperties(
|
||||
cloudTrialInferenceEnabled: boolean | undefined,
|
||||
): Record<string, unknown> {
|
||||
if (typeof cloudTrialInferenceEnabled !== "boolean") return {};
|
||||
return {
|
||||
cloud_trial_inference_enabled: cloudTrialInferenceEnabled,
|
||||
[`$feature/${CLOUD_TRIAL_INFERENCE_FLAG_KEY}`]: cloudTrialInferenceCohort(cloudTrialInferenceEnabled),
|
||||
};
|
||||
}
|
||||
|
||||
function stableJson(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
||||
@@ -181,6 +197,7 @@ export function buildPostHogDirectEvent(
|
||||
...(context?.userId ? { user_id: context.userId } : {}),
|
||||
attributed_via: context?.userId ? (context.attributedVia ?? "request") : "none",
|
||||
...(config.environment ? { environment: config.environment } : {}),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled),
|
||||
...(context?.sessionId ? { $session_id: context.sessionId } : {}),
|
||||
...(context?.windowId ? { $window_id: context.windowId } : {}),
|
||||
$groups: { [POSTHOG_WORKSPACE_GROUP_TYPE]: config.stackId },
|
||||
@@ -227,9 +244,58 @@ export function buildWorkspaceStartedEvent(
|
||||
install_hash: input.installHash,
|
||||
attributed_via: "none",
|
||||
...(config.environment ? { environment: config.environment } : {}),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled),
|
||||
$groups: { [POSTHOG_WORKSPACE_GROUP_TYPE]: config.stackId },
|
||||
distinct_id: distinctId,
|
||||
$process_person_profile: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloud-only direct PostHog event (not in the self-hosted collector contract).
|
||||
* Used for Cloud experiment exposure (`$feature_flag_called`) and Cloud starter
|
||||
* inference funnel events (`cloud_trial.*`).
|
||||
*/
|
||||
export function buildCloudDirectEvent(
|
||||
input: {
|
||||
event: string;
|
||||
occurredAt: string;
|
||||
properties?: Record<string, unknown>;
|
||||
setOncePersonProperties?: Record<string, unknown>;
|
||||
},
|
||||
context: PostHogEventContext | undefined,
|
||||
config: IdentityConfig,
|
||||
): PostHogDirectEvent {
|
||||
const distinctId = resolveDistinctId(config, context);
|
||||
const hasPerson = Boolean(context?.userId);
|
||||
const setOnce: Record<string, unknown> = {
|
||||
...(typeof config.cloudTrialInferenceEnabled === "boolean"
|
||||
? { cloud_trial_inference_cohort: cloudTrialInferenceCohort(config.cloudTrialInferenceEnabled) }
|
||||
: {}),
|
||||
...(input.setOncePersonProperties ?? {}),
|
||||
};
|
||||
return {
|
||||
event: input.event,
|
||||
distinct_id: distinctId,
|
||||
timestamp: input.occurredAt,
|
||||
uuid: randomUUID(),
|
||||
disableGeoip: true,
|
||||
sendFeatureFlags: false,
|
||||
properties: {
|
||||
deployment_source: "cloud",
|
||||
stack_id: config.stackId,
|
||||
...(context?.companyId ? { company_id: context.companyId } : {}),
|
||||
...(context?.userId ? { user_id: context.userId } : {}),
|
||||
...(config.environment ? { environment: config.environment } : {}),
|
||||
...cloudExperimentProperties(config.cloudTrialInferenceEnabled),
|
||||
...(input.properties ?? {}),
|
||||
...(context?.sessionId ? { $session_id: context.sessionId } : {}),
|
||||
...(context?.windowId ? { $window_id: context.windowId } : {}),
|
||||
$groups: { [POSTHOG_WORKSPACE_GROUP_TYPE]: config.stackId },
|
||||
distinct_id: distinctId,
|
||||
...(hasPerson && Object.keys(setOnce).length > 0 ? { $set_once: setOnce } : {}),
|
||||
...(hasPerson ? {} : { $process_person_profile: false }),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -10,4 +10,9 @@ export {
|
||||
postHogRequestContextMiddleware,
|
||||
type PostHogEventContext,
|
||||
} from "./request-context.js";
|
||||
export { buildPostHogDirectEvent, type PostHogDirectEvent } from "./event-shape.js";
|
||||
export {
|
||||
buildCloudDirectEvent,
|
||||
buildPostHogDirectEvent,
|
||||
cloudExperimentProperties,
|
||||
type PostHogDirectEvent,
|
||||
} from "./event-shape.js";
|
||||
@@ -3,8 +3,16 @@ import type {
|
||||
TelemetrySendResult,
|
||||
TelemetryTransport,
|
||||
} from "@paperclipai/shared/telemetry";
|
||||
import type { CloudPostHogConfig } from "../cloud-posthog-config.js";
|
||||
import {
|
||||
cloudTrialInferenceCohort,
|
||||
type CloudPostHogConfig,
|
||||
} from "../cloud-posthog-config.js";
|
||||
import {
|
||||
getResolvedCloudTrialInferenceEnabled,
|
||||
onCloudTrialInferenceCohortChange,
|
||||
} from "../cloud-posthog-cohort.js";
|
||||
import {
|
||||
buildCloudDirectEvent,
|
||||
buildPostHogDirectEvent,
|
||||
buildWorkspaceStartedEvent,
|
||||
POSTHOG_WORKSPACE_GROUP_TYPE,
|
||||
@@ -70,8 +78,19 @@ export type WorkspaceStartup = {
|
||||
};
|
||||
|
||||
export type PostHogDirectTransport = TelemetryTransport & {
|
||||
/** Whether the stack has the Cloud starter-inference experiment enabled. */
|
||||
readonly cloudTrialInferenceEnabled: boolean;
|
||||
/** Syncs the resolved instance setting (including staging overrides) into all future events. */
|
||||
setCloudTrialInferenceEnabled(enabled: boolean): void;
|
||||
/** Sends `$groupidentify` and `cloud.workspace_started` for this start. */
|
||||
announceWorkspace(startup: WorkspaceStartup): Promise<void>;
|
||||
/** Captures a Cloud-only direct PostHog event (not in the self-hosted collector contract). */
|
||||
captureCloudEvent(input: {
|
||||
event: string;
|
||||
properties?: Record<string, unknown>;
|
||||
contextOverride?: Partial<PostHogEventContext>;
|
||||
setOncePersonProperties?: Record<string, unknown>;
|
||||
}): Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
};
|
||||
|
||||
@@ -83,6 +102,46 @@ export function createPostHogDirectTransport(
|
||||
const now = options.now ?? (() => new Date());
|
||||
let clientPromise: Promise<PostHogNodeClient> | null = null;
|
||||
let pendingAnnouncement: { startup: WorkspaceStartup; occurredAt: string } | null = null;
|
||||
let announcedCohort: boolean | null = null;
|
||||
let explicitCloudTrialInferenceEnabled: boolean | null = null;
|
||||
|
||||
const effectiveCloudTrialInferenceEnabled = (): boolean =>
|
||||
explicitCloudTrialInferenceEnabled ??
|
||||
getResolvedCloudTrialInferenceEnabled() ??
|
||||
config.cloudTrialInferenceEnabled;
|
||||
|
||||
const syncWorkspaceGroupCohort = (enabled: boolean) => {
|
||||
if (announcedCohort === null || announcedCohort === enabled || !clientPromise) return;
|
||||
announcedCohort = enabled;
|
||||
void clientPromise
|
||||
.then((client) => {
|
||||
client.groupIdentify({
|
||||
groupType: POSTHOG_WORKSPACE_GROUP_TYPE,
|
||||
groupKey: config.stackId,
|
||||
disableGeoip: true,
|
||||
properties: {
|
||||
environment: config.environment,
|
||||
cloud_trial_inference_enabled: enabled,
|
||||
cloud_trial_inference_cohort: cloudTrialInferenceCohort(enabled),
|
||||
},
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never interrupt settings reads.
|
||||
});
|
||||
};
|
||||
|
||||
const unsubscribeCohortChange = onCloudTrialInferenceCohortChange((enabled) => {
|
||||
if (explicitCloudTrialInferenceEnabled !== null) return;
|
||||
syncWorkspaceGroupCohort(enabled);
|
||||
});
|
||||
|
||||
const currentConfig = (): CloudPostHogConfig => {
|
||||
const enabled = effectiveCloudTrialInferenceEnabled();
|
||||
return enabled === config.cloudTrialInferenceEnabled
|
||||
? config
|
||||
: { ...config, cloudTrialInferenceEnabled: enabled };
|
||||
};
|
||||
|
||||
const getClient = () => {
|
||||
clientPromise ??= factory(config).catch((error) => {
|
||||
@@ -115,14 +174,18 @@ export function createPostHogDirectTransport(
|
||||
client: PostHogNodeClient,
|
||||
{ startup, occurredAt }: { startup: WorkspaceStartup; occurredAt: string },
|
||||
) {
|
||||
const activeConfig = currentConfig();
|
||||
announcedCohort = activeConfig.cloudTrialInferenceEnabled;
|
||||
client.groupIdentify({
|
||||
groupType: POSTHOG_WORKSPACE_GROUP_TYPE,
|
||||
groupKey: config.stackId,
|
||||
groupKey: activeConfig.stackId,
|
||||
disableGeoip: true,
|
||||
properties: {
|
||||
stack_slug: startup.stackSlug,
|
||||
primary_host: startup.primaryHost,
|
||||
environment: config.environment,
|
||||
environment: activeConfig.environment,
|
||||
cloud_trial_inference_enabled: activeConfig.cloudTrialInferenceEnabled,
|
||||
cloud_trial_inference_cohort: cloudTrialInferenceCohort(activeConfig.cloudTrialInferenceEnabled),
|
||||
},
|
||||
});
|
||||
capture(
|
||||
@@ -136,17 +199,27 @@ export function createPostHogDirectTransport(
|
||||
version: startup.version,
|
||||
ingestedAt: occurredAt,
|
||||
},
|
||||
config,
|
||||
activeConfig,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
get cloudTrialInferenceEnabled() {
|
||||
return effectiveCloudTrialInferenceEnabled();
|
||||
},
|
||||
|
||||
setCloudTrialInferenceEnabled(enabled: boolean) {
|
||||
explicitCloudTrialInferenceEnabled = enabled;
|
||||
syncWorkspaceGroupCohort(enabled);
|
||||
},
|
||||
|
||||
hashesPrivateRefs: false,
|
||||
|
||||
captureEventContext: () => capturePostHogEventContext(),
|
||||
|
||||
async send(batch: TelemetryOutgoingBatch): Promise<TelemetrySendResult> {
|
||||
const activeConfig = currentConfig();
|
||||
const meta = {
|
||||
app: batch.app,
|
||||
schemaVersion: batch.schemaVersion,
|
||||
@@ -156,7 +229,7 @@ export function createPostHogDirectTransport(
|
||||
};
|
||||
const messages = batch.events
|
||||
.map(({ event, context }) =>
|
||||
buildPostHogDirectEvent(event, context as PostHogEventContext | undefined, meta, config),
|
||||
buildPostHogDirectEvent(event, context as PostHogEventContext | undefined, meta, activeConfig),
|
||||
)
|
||||
.filter((message): message is PostHogDirectEvent => message !== null);
|
||||
if (messages.length === 0) return { kind: "ok" };
|
||||
@@ -201,7 +274,44 @@ export function createPostHogDirectTransport(
|
||||
await client.flush();
|
||||
},
|
||||
|
||||
async captureCloudEvent(input): Promise<void> {
|
||||
let client: PostHogNodeClient;
|
||||
try {
|
||||
client = await getClient();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const reqCtx = capturePostHogEventContext();
|
||||
const mergedContext: PostHogEventContext | undefined =
|
||||
reqCtx || input.contextOverride
|
||||
? {
|
||||
...(reqCtx ?? {}),
|
||||
...(input.contextOverride?.userId ? { userId: input.contextOverride.userId } : {}),
|
||||
...(input.contextOverride?.companyId ? { companyId: input.contextOverride.companyId } : {}),
|
||||
...(input.contextOverride?.sessionId ? { sessionId: input.contextOverride.sessionId } : {}),
|
||||
...(input.contextOverride?.windowId ? { windowId: input.contextOverride.windowId } : {}),
|
||||
}
|
||||
: undefined;
|
||||
const message = buildCloudDirectEvent(
|
||||
{
|
||||
event: input.event,
|
||||
occurredAt: now().toISOString(),
|
||||
properties: input.properties,
|
||||
setOncePersonProperties: input.setOncePersonProperties,
|
||||
},
|
||||
mergedContext,
|
||||
currentConfig(),
|
||||
);
|
||||
capture(client, message);
|
||||
try {
|
||||
await client.flush();
|
||||
} catch {
|
||||
console.warn(`[telemetry] PostHog flush failed for cloud event ${input.event}`);
|
||||
}
|
||||
},
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
unsubscribeCohortChange();
|
||||
if (!clientPromise) return;
|
||||
const client = await clientPromise.catch(() => null);
|
||||
if (!client) return;
|
||||
|
||||
@@ -4939,6 +4939,7 @@ export function toolAccessService(
|
||||
|
||||
listConnectionInstalls,
|
||||
putConnectionInstalls: connectionInstalls.putConnectionInstalls,
|
||||
ensureAgentConnectionInstalls: connectionInstalls.ensureAgentConnectionInstalls,
|
||||
|
||||
updateConnection: async (
|
||||
connectionId: string,
|
||||
|
||||
@@ -354,6 +354,99 @@ export function createConnectionInstalls(db: Db, { now, getConnectionRow, assert
|
||||
connection.companyId,
|
||||
),
|
||||
};
|
||||
}
|
||||
},
|
||||
ensureAgentConnectionInstalls: async (
|
||||
connectionId: string,
|
||||
agentIds: readonly string[],
|
||||
actor?: ActorInfo,
|
||||
): Promise<ToolConnectionInstallSnapshot> => {
|
||||
await actor?.managementContext?.reauthorize();
|
||||
const connection = await getConnectionRow(connectionId);
|
||||
const uniqueAgentIds = [...new Set(agentIds)];
|
||||
for (const agentId of uniqueAgentIds) {
|
||||
await assertOptionalAgent(
|
||||
connection.companyId,
|
||||
agentId,
|
||||
"Tool connection install agent",
|
||||
);
|
||||
}
|
||||
if (uniqueAgentIds.length > 0) {
|
||||
await db.transaction(async (tx) => {
|
||||
await lockToolConnectionRuntimeInputs(tx, connection.companyId, connection.id);
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(toolConnectionInstalls)
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnectionInstalls.companyId, connection.companyId),
|
||||
eq(toolConnectionInstalls.connectionId, connection.id),
|
||||
),
|
||||
);
|
||||
const hasCompanyInstall = existing.some(
|
||||
(install) =>
|
||||
install.targetType === "company" && install.targetId === connection.companyId,
|
||||
);
|
||||
if (hasCompanyInstall) return;
|
||||
const existingAgentIds = new Set(
|
||||
existing
|
||||
.filter((install) => install.targetType === "agent")
|
||||
.map((install) => install.targetId),
|
||||
);
|
||||
const additions = uniqueAgentIds
|
||||
.filter((agentId) => !existingAgentIds.has(agentId))
|
||||
.map((agentId) => ({ targetType: "agent" as const, targetId: agentId }));
|
||||
if (additions.length === 0) return;
|
||||
const sourceAgentId =
|
||||
actor?.managementContext?.actor.type === "agent"
|
||||
? actor.managementContext.actor.agentId
|
||||
: actor?.actorType === "agent"
|
||||
? actor.actorId
|
||||
: null;
|
||||
await lockToolAssignmentAgents(
|
||||
tx,
|
||||
connection.companyId,
|
||||
[...existing, ...additions],
|
||||
sourceAgentId,
|
||||
);
|
||||
await assertAgentToolAssignmentInteractions(
|
||||
tx as unknown as Db,
|
||||
sourceAgentId,
|
||||
connection.companyId,
|
||||
additions.map((install) => install.targetId),
|
||||
false,
|
||||
);
|
||||
await tx.insert(toolConnectionInstalls).values(
|
||||
additions.map((install) => ({
|
||||
companyId: connection.companyId,
|
||||
connectionId: connection.id,
|
||||
targetType: install.targetType,
|
||||
targetId: install.targetId,
|
||||
createdByAgentId:
|
||||
actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
|
||||
createdByUserId: connectionActorUserId(actor),
|
||||
})),
|
||||
);
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId: connection.companyId,
|
||||
actorType: actor?.actorType ?? "system",
|
||||
actorId: actor?.actorId ?? "system",
|
||||
action: "tool_connection.installs_updated",
|
||||
entityType: "tool_connection",
|
||||
entityId: connection.id,
|
||||
details: {
|
||||
added: additions,
|
||||
removed: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
return {
|
||||
connectionId: connection.id,
|
||||
installs: await listConnectionInstalls(
|
||||
connection.id,
|
||||
connection.companyId,
|
||||
),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
+95
-1
@@ -11,16 +11,27 @@ import {
|
||||
import { resolvePaperclipInstanceRoot } from "./home-paths.js";
|
||||
import { serverVersion } from "./version.js";
|
||||
import { getCloudStackContext } from "./services/cloud-instance.js";
|
||||
import { isPostHogDirectDeliveryEnabled, resolveCloudPostHogConfig } from "./services/cloud-posthog-config.js";
|
||||
import {
|
||||
resetResolvedCloudTrialInferenceEnabledForTests,
|
||||
setResolvedCloudTrialInferenceEnabled,
|
||||
} from "./services/cloud-posthog-cohort.js";
|
||||
import {
|
||||
CLOUD_TRIAL_INFERENCE_FLAG_KEY,
|
||||
cloudTrialInferenceCohort,
|
||||
isPostHogDirectDeliveryEnabled,
|
||||
resolveCloudPostHogConfig,
|
||||
} from "./services/cloud-posthog-config.js";
|
||||
import {
|
||||
createPostHogDirectTransport,
|
||||
type PostHogDirectTransport,
|
||||
type PostHogEventContext,
|
||||
type PostHogNodeFactory,
|
||||
} from "./services/posthog-direct/index.js";
|
||||
|
||||
let client: TelemetryClient | null = null;
|
||||
let directTransport: PostHogDirectTransport | null = null;
|
||||
let initializationFailed = false;
|
||||
const exposedTrialActors = new Set<string>();
|
||||
|
||||
export type InitTelemetryOptions = {
|
||||
env?: Record<string, string | undefined>;
|
||||
@@ -105,6 +116,87 @@ export function isPostHogDirectTelemetryActive(): boolean {
|
||||
return directTransport !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits a Cloud-only direct PostHog event (never sent through the self-hosted
|
||||
* collector). Fire-and-forget; never throws to callers.
|
||||
*/
|
||||
export function trackCloudPostHogEvent(
|
||||
event: string,
|
||||
properties?: Record<string, unknown>,
|
||||
contextOverride?: {
|
||||
userId?: string | null;
|
||||
companyId?: string | null;
|
||||
sessionId?: string | null;
|
||||
windowId?: string | null;
|
||||
},
|
||||
): void {
|
||||
const transport = directTransport;
|
||||
if (!transport) return;
|
||||
const normalizedContext: Partial<PostHogEventContext> | undefined = contextOverride
|
||||
? {
|
||||
...(contextOverride.userId ? { userId: contextOverride.userId } : {}),
|
||||
...(contextOverride.companyId ? { companyId: contextOverride.companyId } : {}),
|
||||
...(contextOverride.sessionId ? { sessionId: contextOverride.sessionId } : {}),
|
||||
...(contextOverride.windowId ? { windowId: contextOverride.windowId } : {}),
|
||||
}
|
||||
: undefined;
|
||||
void transport
|
||||
.captureCloudEvent({
|
||||
event,
|
||||
properties,
|
||||
contextOverride: normalizedContext,
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never break product flows.
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits PostHog's `$feature_flag_called` exposure event once per actor per
|
||||
* process when a Cloud user enters onboarding (both treatment and control),
|
||||
* establishing an exact denominator for A/B experiment funnels.
|
||||
*/
|
||||
export function trackCloudTrialExposure(input: {
|
||||
surface: "onboarding_wizard" | "onboarding_seed";
|
||||
userId?: string | null;
|
||||
companyId?: string | null;
|
||||
enabledOverride?: boolean;
|
||||
}): void {
|
||||
const transport = directTransport;
|
||||
if (!transport) return;
|
||||
const dedupeKey = `${input.userId ?? "workspace"}:${input.companyId ?? ""}`;
|
||||
if (exposedTrialActors.has(dedupeKey)) return;
|
||||
exposedTrialActors.add(dedupeKey);
|
||||
const enabled =
|
||||
typeof input.enabledOverride === "boolean"
|
||||
? input.enabledOverride
|
||||
: transport.cloudTrialInferenceEnabled;
|
||||
if (typeof input.enabledOverride === "boolean") {
|
||||
setResolvedCloudTrialInferenceEnabled(input.enabledOverride);
|
||||
transport.setCloudTrialInferenceEnabled(input.enabledOverride);
|
||||
}
|
||||
const cohort = cloudTrialInferenceCohort(enabled);
|
||||
void transport
|
||||
.captureCloudEvent({
|
||||
event: "$feature_flag_called",
|
||||
properties: {
|
||||
$feature_flag: CLOUD_TRIAL_INFERENCE_FLAG_KEY,
|
||||
$feature_flag_response: cohort,
|
||||
surface: input.surface,
|
||||
},
|
||||
contextOverride: {
|
||||
...(input.userId ? { userId: input.userId } : {}),
|
||||
...(input.companyId ? { companyId: input.companyId } : {}),
|
||||
},
|
||||
setOncePersonProperties: {
|
||||
cloud_trial_inference_cohort: cohort,
|
||||
},
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never break product flows.
|
||||
});
|
||||
}
|
||||
|
||||
/** Stops timers, sends queued events, then closes the PostHog client if any. */
|
||||
export async function shutdownTelemetry(): Promise<void> {
|
||||
const current = client;
|
||||
@@ -123,4 +215,6 @@ export function resetTelemetryForTests(): void {
|
||||
client = null;
|
||||
directTransport = null;
|
||||
initializationFailed = false;
|
||||
exposedTrialActors.clear();
|
||||
resetResolvedCloudTrialInferenceEnabledForTests();
|
||||
}
|
||||
@@ -217,6 +217,7 @@
|
||||
"packages/shared/src/cliplab/svg-canvas.ts": "2b1bb631749524487d05a61df435da7effb5d607",
|
||||
"packages/shared/src/cliplab/svg-path.ts": "69ab5fc506a0ad9965837ddb41ecc245b2df1916",
|
||||
"packages/shared/src/cliplab/svg-snapshot.ts": "f1ef8e5d8e4d69db0d1cdcf80ba9b54a7ad3d0c7",
|
||||
"packages/shared/src/cloud-inference.ts": "29ccc0135b0d4557daf73ad674aa10faf6eccfd0",
|
||||
"packages/shared/src/company-import-transfer.test.ts": "213169db79a3f4b6788f4107d6a7b49cd0beb6b9",
|
||||
"packages/shared/src/company-import-transfer.ts": "376482a8c28feba53b1e4973db0ba2e158b65b41",
|
||||
"packages/shared/src/composio-app-setup.ts": "75f544f5647f227214b8a9d0f61d0196bcbbab55",
|
||||
@@ -236,7 +237,7 @@
|
||||
"packages/shared/src/connector-availability.ts": "82aec0dfb2e9b8cb04e21c4bcd9aab74b087c76a",
|
||||
"packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a",
|
||||
"packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955",
|
||||
"packages/shared/src/constants.ts": "2cb07762a025c0d678cfd9aeeae6653fe9afb9d6",
|
||||
"packages/shared/src/constants.ts": "b38786d0ab71d31a1745067e6b7a07c90f9c3c01",
|
||||
"packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c",
|
||||
"packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2",
|
||||
"packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe",
|
||||
@@ -260,7 +261,7 @@
|
||||
"packages/shared/src/external-objects.ts": "a9953c4e3f77f2bad03cb7832914ffc0b1a1266a",
|
||||
"packages/shared/src/fast-response.ts": "a81332a2b46b59c1f6953cfc4da659eae2326beb",
|
||||
"packages/shared/src/feature-catalog.test.ts": "d3e000c039492daad1fe0b7302b34e7c3816a8ce",
|
||||
"packages/shared/src/feature-catalog.ts": "d49ac40217e0f4018fe8c1bff904e5b7eb6f171e",
|
||||
"packages/shared/src/feature-catalog.ts": "f30fed662ad1a7dec4c3012b7653af2f777f0a0d",
|
||||
"packages/shared/src/frontmatter-runner-contract.test.ts": "cd121330e10aaa9da36c16293bcd9760561b6b41",
|
||||
"packages/shared/src/frontmatter.test.ts": "56635e331c8abca8868da76f23a08e98f20ff07f",
|
||||
"packages/shared/src/frontmatter.ts": "a86e046ce588d2f92d4996122cc2068ec275e89c",
|
||||
@@ -278,7 +279,7 @@
|
||||
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
|
||||
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
|
||||
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
|
||||
"packages/shared/src/index.ts": "f0c8e72ac411fad0f9c090f68ea9590d15316d94",
|
||||
"packages/shared/src/index.ts": "46b77dd3c9da46aa8fa8fd98e0649dc10a556578",
|
||||
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
|
||||
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
|
||||
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
|
||||
@@ -439,7 +440,7 @@
|
||||
"packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371",
|
||||
"packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d",
|
||||
"packages/shared/src/types/index.ts": "e566109a838995a8b14cb2a4d47394aea0b9a752",
|
||||
"packages/shared/src/types/instance.ts": "ddfef2455723757a5ecffaf3bab56ec47c287267",
|
||||
"packages/shared/src/types/instance.ts": "ba01ade6bf1071ab19419b4c60bc062f05f09212",
|
||||
"packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df",
|
||||
"packages/shared/src/types/issue.ts": "fe78765782a50faf24e91e76e39846a4ace2cfc5",
|
||||
"packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec",
|
||||
@@ -473,14 +474,14 @@
|
||||
"packages/shared/src/types/workspace-runtime.ts": "00ab237577d3ea3a1fa946ce6ab6ef8b389b1739",
|
||||
"packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d",
|
||||
"packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1",
|
||||
"packages/shared/src/validators/access.ts": "987401ab5c3c352c9417071f78b960857d7fe65f",
|
||||
"packages/shared/src/validators/access.ts": "efd12471a885dcdcae575dc73445f8bbbd06b889",
|
||||
"packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81",
|
||||
"packages/shared/src/validators/adapter-registry.test.ts": "567c113e50dd0c0d259b095375f8f8f403ffa893",
|
||||
"packages/shared/src/validators/adapter-registry.ts": "6fb9f655d49f774ef7f082bf842f388f1187e545",
|
||||
"packages/shared/src/validators/adapter-skills.ts": "ae43f7b180f632d5f54dfa821b8dc5ef6c6aa53d",
|
||||
"packages/shared/src/validators/agent-commentary.ts": "8242c5b28a77131aefdc00c873ad84c6c6736e4b",
|
||||
"packages/shared/src/validators/agent.test.ts": "b15ce4e96097e807de7e52ca174139dd51e0d9c9",
|
||||
"packages/shared/src/validators/agent.ts": "c6c4e351e64cc668e67ad7489f93cfcb4506ba6a",
|
||||
"packages/shared/src/validators/agent.ts": "92cbbfb031bd0e592083e2deb6f961bd5f31a574",
|
||||
"packages/shared/src/validators/app-definition.ts": "87a60e50f386c8f836d1c5a1576b75a50bc719a2",
|
||||
"packages/shared/src/validators/approval.test.ts": "051d29b27400fdd1e311466587b276264cf072e4",
|
||||
"packages/shared/src/validators/approval.ts": "b8fd4da39568e3b70b767266196ea5303efeef25",
|
||||
@@ -518,7 +519,7 @@
|
||||
"packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b",
|
||||
"packages/shared/src/validators/index.ts": "c6d21d8635e39e269774d4d893b69bc76192e14a",
|
||||
"packages/shared/src/validators/instance.test.ts": "3faa9593a9a05f74429d9b1d2251906a03e9a903",
|
||||
"packages/shared/src/validators/instance.ts": "3cb2bc003d32a8f4f49f705a18a1c9343c243cee",
|
||||
"packages/shared/src/validators/instance.ts": "edde733b1d1b91023321c6c59b17b65aadf5dfa1",
|
||||
"packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645",
|
||||
"packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438",
|
||||
"packages/shared/src/validators/issue.test.ts": "7584bcce33a933ebcb02695b439767163e5ef61a",
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type {
|
||||
CloudTrialInferenceStatus,
|
||||
CloudTrialTelemetryEventInput,
|
||||
MigrateCloudTrialAgentsInput,
|
||||
MigrateCloudTrialAgentsResult,
|
||||
} from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
|
||||
export const cloudInferenceApi = {
|
||||
getStatus: (companyId: string, opts?: { refresh?: boolean }) =>
|
||||
api.get<CloudTrialInferenceStatus>(
|
||||
`/companies/${encodeURIComponent(companyId)}/cloud-inference/status${opts?.refresh ? "?refresh=1" : ""}`,
|
||||
),
|
||||
migrate: (companyId: string, input: MigrateCloudTrialAgentsInput) =>
|
||||
api.post<MigrateCloudTrialAgentsResult>(
|
||||
`/companies/${encodeURIComponent(companyId)}/cloud-inference/migrate`,
|
||||
input,
|
||||
),
|
||||
trackTelemetry: (companyId: string, input: CloudTrialTelemetryEventInput) =>
|
||||
api.post<void>(
|
||||
`/companies/${encodeURIComponent(companyId)}/cloud-inference/telemetry`,
|
||||
input,
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,315 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ArrowRight,
|
||||
Bot,
|
||||
CheckCircle2,
|
||||
Loader2,
|
||||
RotateCcw,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
import type {
|
||||
AiConnectionBinding,
|
||||
CloudTrialInferenceStatus,
|
||||
MigrateCloudTrialAgentsResult,
|
||||
} from "@paperclipai/shared";
|
||||
import { cloudInferenceApi } from "@/api/cloud-inference";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { AiProviderSetup } from "@/components/ai-connections/AiProviderSetup";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface CloudTrialExhaustedModalProps {
|
||||
open: boolean;
|
||||
companyId: string;
|
||||
status: CloudTrialInferenceStatus;
|
||||
/** When true, blocks closing until the user connects a model provider and migrates agents. */
|
||||
required?: boolean;
|
||||
/** Initial visual phase override (primarily for Storybook & previewing states). */
|
||||
initialPhase?: "connect" | "migrating" | "done" | "error";
|
||||
initialResult?: MigrateCloudTrialAgentsResult | null;
|
||||
initialError?: string | null;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onMigrationStart?: () => void;
|
||||
onMigrated?: (result: MigrateCloudTrialAgentsResult) => void;
|
||||
}
|
||||
|
||||
export function CloudTrialExhaustedModal({
|
||||
open,
|
||||
companyId,
|
||||
status,
|
||||
required = true,
|
||||
initialPhase = "connect",
|
||||
initialResult = null,
|
||||
initialError = null,
|
||||
onOpenChange,
|
||||
onMigrationStart,
|
||||
onMigrated,
|
||||
}: CloudTrialExhaustedModalProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [phase, setPhase] = useState<"connect" | "migrating" | "done" | "error">(initialPhase);
|
||||
const [migrationResult, setMigrationResult] = useState<MigrateCloudTrialAgentsResult | null>(initialResult);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(initialError);
|
||||
const [lastBinding, setLastBinding] = useState<Exclude<AiConnectionBinding, { mode: "responsible_user" }> | null>(
|
||||
null,
|
||||
);
|
||||
const modalShownTrackedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
modalShownTrackedRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (phase !== "connect" || modalShownTrackedRef.current) return;
|
||||
modalShownTrackedRef.current = true;
|
||||
void cloudInferenceApi
|
||||
.trackTelemetry(companyId, {
|
||||
event: "modal_shown",
|
||||
trialAgentCount: status.trialAgents.length,
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never interrupt connecting a provider.
|
||||
});
|
||||
}, [open, phase, companyId, status.trialAgents.length]);
|
||||
|
||||
const migrateMutation = useMutation({
|
||||
mutationFn: (binding: Exclude<AiConnectionBinding, { mode: "responsible_user" }>) =>
|
||||
cloudInferenceApi.migrate(companyId, {
|
||||
connectionId: binding.connectionId,
|
||||
grantId: binding.grantId,
|
||||
provider: binding.provider,
|
||||
method: binding.method,
|
||||
ownership: binding.mode === "shared" ? "shared" : "personal",
|
||||
resumeBlockedWork: true,
|
||||
}),
|
||||
onMutate: (binding) => {
|
||||
onMigrationStart?.();
|
||||
setLastBinding(binding);
|
||||
setErrorMessage(null);
|
||||
setPhase("migrating");
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
setMigrationResult(result);
|
||||
setPhase("done");
|
||||
onMigrated?.(result);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.cloudInference.status(companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: ["ai-connections", companyId] });
|
||||
},
|
||||
onError: (err) => {
|
||||
setErrorMessage(describeError(err).body);
|
||||
setPhase("error");
|
||||
},
|
||||
});
|
||||
|
||||
const canMigrate = status.canMigrate !== false;
|
||||
const canClose = !required || !canMigrate || phase === "done";
|
||||
const agentCount = status.trialAgents.length;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen && !canClose) return;
|
||||
onOpenChange?.(nextOpen);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
showCloseButton={canClose}
|
||||
onEscapeKeyDown={(event) => {
|
||||
if (!canClose) event.preventDefault();
|
||||
}}
|
||||
onPointerDownOutside={(event) => {
|
||||
if (!canClose) event.preventDefault();
|
||||
}}
|
||||
onInteractOutside={(event) => {
|
||||
if (!canClose) event.preventDefault();
|
||||
}}
|
||||
className="max-h-(--sz-85vh) sm:max-w-2xl overflow-y-auto p-0 gap-0"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="border-b border-border bg-card px-6 py-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div
|
||||
className={cn(
|
||||
"mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg border",
|
||||
phase === "done"
|
||||
? "border-(--status-task-icon-done)/30 bg-(--diff-add-bg) text-(--diff-add-fg)"
|
||||
: "border-border bg-muted/50 text-foreground",
|
||||
)}
|
||||
>
|
||||
{phase === "done" ? (
|
||||
<CheckCircle2 className="size-4" />
|
||||
) : (
|
||||
<Sparkles className="size-4" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<DialogHeader className="text-left">
|
||||
<DialogTitle className="text-base font-semibold">
|
||||
{phase === "done"
|
||||
? "Model provider connected"
|
||||
: "Connect a model provider to continue"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription className="text-sm text-muted-foreground">
|
||||
{phase === "done"
|
||||
? "Your agents have been updated to use your connected model provider."
|
||||
: !canMigrate
|
||||
? "A company administrator needs to connect a model provider before these agents can continue running."
|
||||
: `You need to connect a model provider to continue. We’ll automatically update ${
|
||||
agentCount === 1
|
||||
? status.trialAgents[0]?.name || "your agent"
|
||||
: agentCount > 1
|
||||
? `all ${agentCount} agents`
|
||||
: "your agents"
|
||||
} and pick up where you left off.`}
|
||||
</DialogDescription>
|
||||
{phase !== "done" && status.trialAgents.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 pt-2">
|
||||
<span className="text-xs text-muted-foreground mr-1">
|
||||
{canMigrate ? "Will update:" : "Waiting on provider:"}
|
||||
</span>
|
||||
{status.trialAgents.map((agent) => (
|
||||
<span
|
||||
key={agent.id}
|
||||
className="inline-flex items-center gap-1 rounded-full border border-border bg-background px-2 py-0.5 text-xs text-foreground"
|
||||
>
|
||||
<Bot className="size-3 text-muted-foreground" />
|
||||
<span className="font-medium">{agent.name}</span>
|
||||
{agent.title ? (
|
||||
<span className="text-muted-foreground">· {agent.title}</span>
|
||||
) : null}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="px-6 py-4">
|
||||
{phase === "connect" && !canMigrate && (
|
||||
<div className="space-y-4 py-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You have read-only access to agent model settings in this company. Ask an administrator to connect a model provider so paused agent work can resume.
|
||||
</p>
|
||||
<div className="flex justify-end">
|
||||
<Button variant="outline" onClick={() => onOpenChange?.(false)}>
|
||||
Dismiss
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "connect" && canMigrate && (
|
||||
<AiProviderSetup
|
||||
companyId={companyId}
|
||||
hideCancel={!canClose}
|
||||
hideProviderHeading
|
||||
submitLabel="Connect & update agents"
|
||||
onCancel={() => {
|
||||
if (canClose) onOpenChange?.(false);
|
||||
}}
|
||||
onComplete={(binding) => {
|
||||
migrateMutation.mutate(binding);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{phase === "migrating" && (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-10 text-center">
|
||||
<Loader2 className="size-6 animate-spin text-primary" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
Updating your agents to your model provider…
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Switching harnesses and resuming paused work.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "error" && (
|
||||
<div className="space-y-4 py-4">
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm text-destructive"
|
||||
>
|
||||
<p className="font-medium">Could not finish updating your agents</p>
|
||||
<p className="mt-1 text-xs opacity-90">
|
||||
{errorMessage ?? "An unexpected error occurred while updating your agents."}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setErrorMessage(null);
|
||||
setPhase("connect");
|
||||
}}
|
||||
>
|
||||
Choose another provider
|
||||
</Button>
|
||||
{lastBinding && (
|
||||
<Button onClick={() => migrateMutation.mutate(lastBinding)}>
|
||||
<RotateCcw className="size-3.5 mr-1.5" />
|
||||
Retry update
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "done" && (
|
||||
<div className="space-y-5">
|
||||
{migrationResult && migrationResult.agents.length > 0 && (
|
||||
<div className="rounded-lg border border-border bg-muted/20 divide-y divide-border">
|
||||
{migrationResult.agents.map((agent) => (
|
||||
<div
|
||||
key={agent.agentId}
|
||||
className="flex items-center justify-between gap-3 px-3.5 py-2.5 text-sm"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Bot className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate font-medium text-foreground">{agent.name}</span>
|
||||
</div>
|
||||
<span className="shrink-0 font-mono text-xs text-muted-foreground">
|
||||
{agent.runnerProvider ? `${agent.runnerProvider} · ` : ""}
|
||||
{agent.model}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{migrationResult && migrationResult.resumedRunIds.length > 0 && (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-(--status-task-icon-done)/30 bg-(--diff-add-bg) px-3.5 py-2.5 text-xs text-(--diff-add-fg)">
|
||||
<Sparkles className="size-3.5 shrink-0" />
|
||||
<span>Your paused work has been automatically resumed.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={() => onOpenChange?.(false)}>
|
||||
Continue to workspace
|
||||
<ArrowRight className="size-3.5 ml-1.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { CloudTrialInferenceStatus } from "@paperclipai/shared";
|
||||
import { cloudInferenceApi } from "@/api/cloud-inference";
|
||||
import { instanceSettingsApi } from "@/api/instanceSettings";
|
||||
import { CloudTrialExhaustedModal } from "@/components/CloudTrialExhaustedModal";
|
||||
import { useCompany } from "@/context/CompanyContext";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
|
||||
/**
|
||||
* Global shell controller that watches the selected company's Cloud starter
|
||||
* inference status and requires connecting a model provider when needed.
|
||||
*/
|
||||
export function CloudTrialGate() {
|
||||
const { selectedCompanyId } = useCompany();
|
||||
const [dismissedAfterMigration, setDismissedAfterMigration] = useState(false);
|
||||
// Keep the modal mounted on its "Subscription connected" confirmation screen
|
||||
// after migration flips `status` to "migrated" and empties `trialAgentIds`,
|
||||
// until the user explicitly clicks "Continue to workspace".
|
||||
const [holdingMigrationSuccess, setHoldingMigrationSuccess] = useState(false);
|
||||
const [migrationComplete, setMigrationComplete] = useState(false);
|
||||
const [lastExhaustedStatus, setLastExhaustedStatus] = useState<CloudTrialInferenceStatus | null>(null);
|
||||
|
||||
const experimental = useQuery({
|
||||
queryKey: queryKeys.instance.experimentalSettings,
|
||||
queryFn: instanceSettingsApi.getExperimental,
|
||||
});
|
||||
|
||||
const enabled = experimental.data?.enableCloudTrialInference === true;
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: queryKeys.cloudInference.status(selectedCompanyId ?? "__none__"),
|
||||
queryFn: () => cloudInferenceApi.getStatus(selectedCompanyId!),
|
||||
enabled: Boolean(selectedCompanyId) && enabled,
|
||||
staleTime: 15_000,
|
||||
});
|
||||
|
||||
const status = statusQuery.data;
|
||||
const isExhaustedWithTrialAgents =
|
||||
Boolean(selectedCompanyId) &&
|
||||
enabled &&
|
||||
status?.status === "exhausted" &&
|
||||
status.trialAgentIds.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (isExhaustedWithTrialAgents && status) {
|
||||
setLastExhaustedStatus(status);
|
||||
}
|
||||
}, [isExhaustedWithTrialAgents, status]);
|
||||
|
||||
useEffect(() => {
|
||||
setDismissedAfterMigration(false);
|
||||
setHoldingMigrationSuccess(false);
|
||||
setMigrationComplete(false);
|
||||
setLastExhaustedStatus(null);
|
||||
}, [selectedCompanyId]);
|
||||
|
||||
const modalStatus = isExhaustedWithTrialAgents ? status : lastExhaustedStatus;
|
||||
const shouldShowModal =
|
||||
Boolean(selectedCompanyId) &&
|
||||
Boolean(modalStatus) &&
|
||||
!dismissedAfterMigration &&
|
||||
(isExhaustedWithTrialAgents || holdingMigrationSuccess);
|
||||
|
||||
if (!selectedCompanyId || !modalStatus || !shouldShowModal) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<CloudTrialExhaustedModal
|
||||
open={shouldShowModal}
|
||||
companyId={selectedCompanyId}
|
||||
status={modalStatus}
|
||||
required={!migrationComplete && modalStatus.canMigrate !== false}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setHoldingMigrationSuccess(false);
|
||||
setMigrationComplete(false);
|
||||
setDismissedAfterMigration(true);
|
||||
}
|
||||
}}
|
||||
onMigrationStart={() => {
|
||||
// Lock the modal open BEFORE POST /migrate fires so the server's
|
||||
// WebSocket `cloud_trial.status.updated` event cannot unmount the
|
||||
// dialog before the confirmation screen renders.
|
||||
setHoldingMigrationSuccess(true);
|
||||
}}
|
||||
onMigrated={() => {
|
||||
setHoldingMigrationSuccess(true);
|
||||
setMigrationComplete(true);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useDesignSandbox } from "@/context/DesignSandboxContext";
|
||||
import { DesignSandboxSidebar } from "./DesignSandboxSidebar";
|
||||
import { BoardDialogs } from "./BoardDialogs";
|
||||
import { CloudTrialGate } from "./CloudTrialGate";
|
||||
import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
|
||||
import { PluginAppShellOverlays } from "./PluginAppShellOverlays";
|
||||
import {
|
||||
@@ -608,6 +609,7 @@ export function Layout() {
|
||||
{isMobile && <MobileBottomNav visible={mobileNavVisible} />}
|
||||
<CommandPalette />
|
||||
<BoardDialogs />
|
||||
<CloudTrialGate />
|
||||
<KeyboardShortcutsCheatsheet
|
||||
open={shortcutsOpen}
|
||||
onOpenChange={setShortcutsOpen}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useBrowserTimeZoneSync } from "@/hooks/useBrowserTimeZoneSync";
|
||||
import { useDesignSandbox } from "@/context/DesignSandboxContext";
|
||||
import { DesignSandboxSidebar } from "./DesignSandboxSidebar";
|
||||
import { BoardDialogs } from "./BoardDialogs";
|
||||
import { CloudTrialGate } from "./CloudTrialGate";
|
||||
import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
@@ -680,6 +681,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
|
||||
{isMobile && <MobileBottomNav visible={mobileNavVisible} />}
|
||||
<CommandPalette />
|
||||
<BoardDialogs />
|
||||
<CloudTrialGate />
|
||||
<KeyboardShortcutsCheatsheet open={shortcutsOpen} onOpenChange={setShortcutsOpen} />
|
||||
<ToastViewport />
|
||||
{isMobile ? <AnnouncementWell health={health} placement="floating" /> : null}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { describeError } from "@/api/errors";
|
||||
import { LocalProviderLoginInstructions } from "./AdapterLoginChrome";
|
||||
import { useLocalAiLogin } from "./ai-connections/useLocalAiLogin";
|
||||
import { aiConnectionsApi } from "@/api/ai-connections";
|
||||
import { cloudInferenceApi } from "@/api/cloud-inference";
|
||||
import { aiProviderForAdapter } from "./ai-connections/AiConnectionField";
|
||||
import { useConnectionModelsState } from "./ai-connections/useConnectionModels";
|
||||
import type { AiConnectionBinding } from "@paperclipai/shared";
|
||||
@@ -31,7 +32,7 @@ import type {
|
||||
Environment,
|
||||
InstanceSettings,
|
||||
} from "@paperclipai/shared";
|
||||
import { AGENT_ROLES, AGENT_ROLE_LABELS, ADAPTER_AUTH_MISSING_CHECK_CODE } from "@paperclipai/shared";
|
||||
import { AGENT_ROLES, AGENT_ROLE_LABELS, ADAPTER_AUTH_MISSING_CHECK_CODE, resolveCloudTrialModel } from "@paperclipai/shared";
|
||||
import { AdapterLoginPanel, ModelDropdown } from "./AgentConfigForm";
|
||||
import {
|
||||
CONNECT_SOURCE_NAMES,
|
||||
@@ -151,6 +152,7 @@ import {
|
||||
Check,
|
||||
Loader2,
|
||||
ChevronDown,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
|
||||
type Step = 0 | 1 | 2 | 3 | 4 | 5;
|
||||
@@ -954,6 +956,78 @@ function OnboardingWizardInner({
|
||||
queryFn: () => instanceSettingsApi.getExperimental(),
|
||||
enabled: effectiveOnboardingOpen && step >= 3 && step <= 5,
|
||||
});
|
||||
const cloudTrialInferenceEnabled = experimentalSettingsForLogin?.enableCloudTrialInference === true;
|
||||
const { data: cloudTrialStatus } = useQuery({
|
||||
queryKey: queryKeys.cloudInference.status(createdCompanyId ?? "__none__"),
|
||||
queryFn: () => cloudInferenceApi.getStatus(createdCompanyId!),
|
||||
enabled: effectiveOnboardingOpen && step === 4 && Boolean(createdCompanyId) && cloudTrialInferenceEnabled,
|
||||
});
|
||||
const canUseCloudTrialStarter =
|
||||
cloudTrialInferenceEnabled &&
|
||||
Boolean(cloudTrialStatus) &&
|
||||
(cloudTrialStatus?.status === "not_issued" || cloudTrialStatus?.status === "active");
|
||||
const [startingCloudTrial, setStartingCloudTrial] = useState(false);
|
||||
const trackedTrialExposureCompaniesRef = useRef<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
if (!effectiveOnboardingOpen || step !== 4 || !createdCompanyId) return;
|
||||
if (trackedTrialExposureCompaniesRef.current.has(createdCompanyId)) return;
|
||||
trackedTrialExposureCompaniesRef.current.add(createdCompanyId);
|
||||
void cloudInferenceApi
|
||||
.trackTelemetry(createdCompanyId, {
|
||||
event: "onboarding_exposure",
|
||||
surface: "onboarding_wizard",
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never interrupt onboarding.
|
||||
});
|
||||
}, [effectiveOnboardingOpen, step, createdCompanyId]);
|
||||
|
||||
async function handleStartWithCloudTrial() {
|
||||
if (!createdCompanyId || startingCloudTrial || loading) return;
|
||||
setStartingCloudTrial(true);
|
||||
setError(null);
|
||||
try {
|
||||
const hireName = agentName.trim() || AGENT_ROLE_LABELS[agentRole];
|
||||
const trialModel = resolveCloudTrialModel(cloudTrialStatus?.defaultModel);
|
||||
await setupSave.current.catch(() => {});
|
||||
const hire = await agentsApi.hire(createdCompanyId, {
|
||||
...(setupAgentId ? { setupAgentId } : {}),
|
||||
name: hireName,
|
||||
appearance: agentAppearance,
|
||||
role: agentRole,
|
||||
...(restoredSetup?.companyId === createdCompanyId ? { reportsTo: restoredSetup.reportsTo } : {}),
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: {
|
||||
provider: "opencode",
|
||||
model: trialModel,
|
||||
},
|
||||
onboardingFirstAgent: true,
|
||||
...(restoredSetup?.companyId === createdCompanyId && restoredSetup.defaultEnvironmentId
|
||||
? { defaultEnvironmentId: resolvedLoginEnvironmentId }
|
||||
: {}),
|
||||
runtimeConfig: {
|
||||
...buildNewAgentRuntimeConfig({ heartbeatEnabled: false }),
|
||||
cloudTrialInference: true,
|
||||
},
|
||||
});
|
||||
if (hire.approval) {
|
||||
await approvalsApi.approve(
|
||||
hire.approval.id,
|
||||
"Approved during onboarding starter-credit setup.",
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.approvals.list(createdCompanyId) });
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(createdCompanyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.cloudInference.status(createdCompanyId) });
|
||||
setCreatedAgentId(hire.agent.id);
|
||||
setStep(5);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Could not start right away");
|
||||
} finally {
|
||||
setStartingCloudTrial(false);
|
||||
}
|
||||
}
|
||||
const loginEnvironmentResolution = useMemo(() => {
|
||||
try {
|
||||
return { environmentId: resolveAdapterTestEnvironmentId({
|
||||
@@ -3069,6 +3143,44 @@ function OnboardingWizardInner({
|
||||
{/* Step 4: Connect a model — adapter + model + env check (capsule above) */}
|
||||
{step === 4 && (
|
||||
<motion.div key="step-4" {...stepContentMotion} exit={stepHandoff ? stepContentMotion.exit : undefined} className="space-y-8">
|
||||
{canUseCloudTrialStarter && connectPhase === "idle" && (
|
||||
<div className="rounded-xl border border-border bg-card p-4 shadow-xs space-y-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
<span className="text-sm font-semibold text-foreground">
|
||||
Start right away
|
||||
</span>
|
||||
<Badge variant="secondary" className="rounded-full text-xs">
|
||||
{resolveCloudTrialModel(cloudTrialStatus?.defaultModel).split("/").pop() ?? "Starter"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Try Paperclip right away without connecting an account. We’ll ask you to connect a model provider when it’s time to continue.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleStartWithCloudTrial}
|
||||
disabled={startingCloudTrial || loading}
|
||||
className="shrink-0"
|
||||
>
|
||||
{startingCloudTrial ? (
|
||||
<>
|
||||
<Loader2 className="size-3.5 mr-1.5 animate-spin" />
|
||||
Starting…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Start free
|
||||
<ArrowRight className="size-3.5 ml-1.5" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<ModelSourceTiles
|
||||
label="Model source"
|
||||
|
||||
@@ -77,6 +77,8 @@ export function AiProviderSetup({
|
||||
initialProtocol,
|
||||
providerLabel,
|
||||
advancedOnly = false,
|
||||
hideCancel = false,
|
||||
hideProviderHeading = false,
|
||||
submitLabel,
|
||||
reconnect,
|
||||
onCancel,
|
||||
@@ -89,6 +91,8 @@ export function AiProviderSetup({
|
||||
initialProtocol?: AiProviderRouting["protocol"];
|
||||
providerLabel?: string;
|
||||
advancedOnly?: boolean;
|
||||
hideCancel?: boolean;
|
||||
hideProviderHeading?: boolean;
|
||||
submitLabel?: string;
|
||||
reconnect?: AiManagedConnectionSummary;
|
||||
onCancel: () => void;
|
||||
@@ -282,13 +286,15 @@ export function AiProviderSetup({
|
||||
if (!reconnect && accountsView.kind === "error") return <QueryErrorState error={accounts.error} action="load connection permissions" onRetry={accountsView.retry} retrying={accountsView.isFetching} />;
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-2xl space-y-6" onSubmit={(event) => event.stopPropagation()}>
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{step === "provider"
|
||||
? "Connect a model provider"
|
||||
: `${reconnect ? "Reconnect" : "Connect"} ${label}`}
|
||||
</h2>
|
||||
</div>
|
||||
{!(step === "provider" && hideProviderHeading) && (
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{step === "provider"
|
||||
? "Connect a model provider"
|
||||
: `${reconnect ? "Reconnect" : "Connect"} ${label}`}
|
||||
</h2>
|
||||
</div>
|
||||
)}
|
||||
{agentsView.kind === "error" && <QueryErrorState size="inline" error={agents.error} action="load agents" onRetry={agentsView.retry} retrying={agentsView.isFetching} />}
|
||||
{step === "provider" ? (
|
||||
<>
|
||||
@@ -301,9 +307,11 @@ export function AiProviderSetup({
|
||||
<div className="pt-4">{choices(true)}</div>
|
||||
</details>
|
||||
</>}
|
||||
<Button type="button" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
{!hideCancel && (
|
||||
<Button type="button" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : !advanced ? (
|
||||
<AiConnectionCredentialStep
|
||||
|
||||
@@ -2219,6 +2219,16 @@ function handleLiveEvent(
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "cloud_trial.status.updated") {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.cloudInference.status(expectedCompanyId),
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.agents.list(expectedCompanyId),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "agent.status") {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.agents.list(expectedCompanyId),
|
||||
|
||||
@@ -194,4 +194,27 @@ describe("product analytics", () => {
|
||||
expect(out.timestamp).toBe(timestamp);
|
||||
expect(out.properties.$current_url).toBe("https://a.paperclip.app/x");
|
||||
});
|
||||
|
||||
it("registers cloud-trial-inference experiment super properties and $set_once cohort on identify", async () => {
|
||||
const treatmentConfig: BrowserAnalyticsConfig = {
|
||||
...config,
|
||||
cloudTrialInferenceEnabled: true,
|
||||
};
|
||||
setProductAnalyticsUser({ id: "user-9", email: "alex@example.com", name: "Alex" });
|
||||
startProductAnalytics(treatmentConfig, { load, schedule });
|
||||
scheduled!();
|
||||
await flush();
|
||||
|
||||
expect(client.register).toHaveBeenCalledWith({
|
||||
deployment_source: "cloud",
|
||||
environment: "staging",
|
||||
cloud_trial_inference_enabled: true,
|
||||
"$feature/cloud-trial-inference": "treatment",
|
||||
});
|
||||
expect(client.identify).toHaveBeenCalledWith(
|
||||
"user-9",
|
||||
{ email: "alex@example.com", name: "Alex" },
|
||||
{ cloud_trial_inference_cohort: "treatment" },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,11 @@ import {
|
||||
export interface ProductAnalyticsClient {
|
||||
init(token: string, config: PostHogInitOptions): unknown;
|
||||
register(properties: Record<string, unknown>): void;
|
||||
identify(distinctId: string, personProperties?: Record<string, unknown>): void;
|
||||
identify(
|
||||
distinctId: string,
|
||||
personProperties?: Record<string, unknown>,
|
||||
personPropertiesSetOnce?: Record<string, unknown>,
|
||||
): void;
|
||||
group(groupType: string, groupKey: string): void;
|
||||
reset(): void;
|
||||
capture?(event: string, properties?: Record<string, unknown>, options?: { timestamp?: Date }): unknown;
|
||||
@@ -201,6 +205,12 @@ function superProperties(config: BrowserAnalyticsConfig) {
|
||||
return {
|
||||
deployment_source: "cloud",
|
||||
environment: config.environment,
|
||||
...(typeof config.cloudTrialInferenceEnabled === "boolean"
|
||||
? {
|
||||
cloud_trial_inference_enabled: config.cloudTrialInferenceEnabled,
|
||||
"$feature/cloud-trial-inference": config.cloudTrialInferenceEnabled ? "treatment" : "control",
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -233,7 +243,13 @@ function applyIdentity(client: ProductAnalyticsClient, config: BrowserAnalyticsC
|
||||
const personProperties: Record<string, string> = {};
|
||||
if (user.email) personProperties.email = user.email;
|
||||
if (user.name) personProperties.name = user.name;
|
||||
client.identify(user.id, personProperties);
|
||||
if (typeof config.cloudTrialInferenceEnabled === "boolean") {
|
||||
client.identify(user.id, personProperties, {
|
||||
cloud_trial_inference_cohort: config.cloudTrialInferenceEnabled ? "treatment" : "control",
|
||||
});
|
||||
} else {
|
||||
client.identify(user.id, personProperties);
|
||||
}
|
||||
client.group(WORKSPACE_GROUP_TYPE, config.stackId);
|
||||
identifiedUserId = user.id;
|
||||
return;
|
||||
|
||||
@@ -324,6 +324,9 @@ export const queryKeys = {
|
||||
detail: (issueId: string, viewId: string) => ["mcp-app-views", issueId, "detail", viewId] as const,
|
||||
},
|
||||
toolCallProgress: (issueId: string) => ["tool-call-progress", issueId] as const,
|
||||
cloudInference: {
|
||||
status: (companyId: string) => ["cloud-inference", companyId, "status"] as const,
|
||||
},
|
||||
issues: {
|
||||
recoveryActions: (id: string, actionId: string | null, runId: string | null) =>
|
||||
["issues", id, "recovery-actions", actionId, runId] as const,
|
||||
|
||||
@@ -249,6 +249,8 @@ export function InstanceExperimentalSettings() {
|
||||
experimentalQuery.data?.enableSimplifiedEnglishInteractions === true;
|
||||
const enableFirstTaskPlanProposal =
|
||||
experimentalQuery.data?.enableFirstTaskPlanProposal === true;
|
||||
const enableCloudTrialInference =
|
||||
experimentalQuery.data?.enableCloudTrialInference === true;
|
||||
const enableSmokeLab = experimentalQuery.data?.enableSmokeLab === true;
|
||||
const autoRestartDevServerWhenIdle = experimentalQuery.data?.autoRestartDevServerWhenIdle === true;
|
||||
const isVisible = (key: InstanceFeatureKey) => !hiddenSettings.has(experimentalSettingKey(key));
|
||||
@@ -378,6 +380,19 @@ export function InstanceExperimentalSettings() {
|
||||
ariaLabel="Toggle chat connectors experimental setting"
|
||||
/>
|
||||
|
||||
<ExperimentalToggleCard
|
||||
title="Cloud starter inference"
|
||||
description="Lets new Cloud workspaces start their first agent right away (OpenCode / GPT-6 Luna via server proxy) before asking the user to connect a model provider."
|
||||
checked={enableCloudTrialInference}
|
||||
onCheckedChange={(checked) =>
|
||||
toggleMutation.mutate({ enableCloudTrialInference: checked })
|
||||
}
|
||||
disabled={toggleMutation.isPending}
|
||||
settingKey="enableCloudTrialInference"
|
||||
managed={managedKeys.enableCloudTrialInference}
|
||||
ariaLabel="Toggle Cloud starter inference experimental setting"
|
||||
/>
|
||||
|
||||
<ExperimentalToggleCard
|
||||
title="Combined Inbox + Task List"
|
||||
description="In the Classic workspace, fold Inbox into Tasks. One Tasks row carries the unread badge, and a Views menu reaches every personal and organization task view."
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, screen, userEvent, waitFor } from "storybook/test";
|
||||
import type { CloudTrialInferenceStatus } from "@paperclipai/shared";
|
||||
import { CloudTrialExhaustedModal } from "@/components/CloudTrialExhaustedModal";
|
||||
import { prepareFixtureApi } from "../../support/capability-gaps/api";
|
||||
|
||||
const COMPANY_ID = "company-storybook";
|
||||
|
||||
const singleAgentExhaustedStatus: CloudTrialInferenceStatus = {
|
||||
enabled: true,
|
||||
provider: "openrouter",
|
||||
status: "exhausted",
|
||||
reason: "openrouter_http_402",
|
||||
limitUsdCents: 100,
|
||||
spentUsdCents: 100,
|
||||
remainingUsdCents: 0,
|
||||
defaultModel: "openrouter/openai/gpt-6-luna",
|
||||
canMigrate: true,
|
||||
trialAgentIds: ["11111111-1111-4111-8111-111111111111"],
|
||||
trialAgents: [
|
||||
{
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
name: "Nova",
|
||||
role: "ceo",
|
||||
title: "Chief of Staff",
|
||||
},
|
||||
],
|
||||
blockedRun: {
|
||||
runId: "22222222-2222-4222-8222-222222222222",
|
||||
agentId: "11111111-1111-4111-8111-111111111111",
|
||||
issueId: "33333333-3333-4333-8333-333333333333",
|
||||
failedAt: "2026-11-24T19:00:00Z",
|
||||
},
|
||||
};
|
||||
|
||||
const multiAgentExhaustedStatus: CloudTrialInferenceStatus = {
|
||||
...singleAgentExhaustedStatus,
|
||||
trialAgentIds: [
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
"44444444-4444-4444-8444-444444444444",
|
||||
"55555555-5555-4555-8555-555555555555",
|
||||
],
|
||||
trialAgents: [
|
||||
{
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
name: "Nova",
|
||||
role: "ceo",
|
||||
title: "Chief of Staff",
|
||||
},
|
||||
{
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
name: "Atlas",
|
||||
role: "engineer",
|
||||
title: "Founding Engineer",
|
||||
},
|
||||
{
|
||||
id: "55555555-5555-4555-8555-555555555555",
|
||||
name: "Sage",
|
||||
role: "researcher",
|
||||
title: "Market Researcher",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function installCloudTrialFixtures(opts?: { migrateFails?: boolean }) {
|
||||
return prepareFixtureApi([
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/ai-connections`,
|
||||
read: () => ({
|
||||
canManageConnections: true,
|
||||
accounts: [],
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/agents`,
|
||||
read: () =>
|
||||
singleAgentExhaustedStatus.trialAgents.map((a) => ({
|
||||
id: a.id,
|
||||
companyId: COMPANY_ID,
|
||||
name: a.name,
|
||||
role: a.role,
|
||||
title: a.title,
|
||||
status: "idle",
|
||||
adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "opencode", model: "openrouter/openai/gpt-6-luna" },
|
||||
runtimeConfig: { cloudTrialInference: true },
|
||||
})),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/environments`,
|
||||
read: () => [
|
||||
{
|
||||
id: "env-managed-1",
|
||||
companyId: COMPANY_ID,
|
||||
name: "Paperclip Computer",
|
||||
driver: "local",
|
||||
status: "active",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/environments/capabilities`,
|
||||
read: () => ({ drivers: {} }),
|
||||
},
|
||||
{
|
||||
path: "/api/instance/settings",
|
||||
read: () => ({
|
||||
id: "inst-1",
|
||||
defaultEnvironmentId: "env-managed-1",
|
||||
general: { executionMode: "any" },
|
||||
experimental: { enableCloudTrialInference: true, enableManagedSandboxOnly: false },
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: "/api/instance/settings/experimental",
|
||||
read: () => ({
|
||||
enableCloudTrialInference: true,
|
||||
enableManagedSandboxOnly: false,
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: "/api/instance/settings/general",
|
||||
read: () => ({
|
||||
executionMode: "any",
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/ai-connections`,
|
||||
method: "POST",
|
||||
read: () => ({
|
||||
connectionId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
grantId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||
}),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/cloud-inference/telemetry`,
|
||||
method: "POST",
|
||||
read: () => new Response(null, { status: 204 }),
|
||||
},
|
||||
{
|
||||
path: `/api/companies/${COMPANY_ID}/cloud-inference/migrate`,
|
||||
method: "POST",
|
||||
read: () => {
|
||||
if (opts?.migrateFails) {
|
||||
return Response.json(
|
||||
{ error: "Selected AI connection could not be applied to agent Nova." },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
return {
|
||||
migratedCount: 1,
|
||||
agents: [
|
||||
{
|
||||
agentId: "11111111-1111-4111-8111-111111111111",
|
||||
name: "Nova",
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
],
|
||||
resumedRunIds: ["99999999-9999-4999-8999-999999999999"],
|
||||
resumedIssueId: "33333333-3333-4333-8333-333333333333",
|
||||
};
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
const meta = {
|
||||
id: "onboarding-cloud-trial-exhausted",
|
||||
title:
|
||||
"Getting started and access/Onboarding and first work/Onboarding/Connect model required",
|
||||
component: CloudTrialExhaustedModal,
|
||||
parameters: {
|
||||
layout: "centered",
|
||||
paperclip: {
|
||||
capabilities: ["onboarding/adapter"],
|
||||
status: "current",
|
||||
implementation: "production",
|
||||
boundary: "fixtures",
|
||||
notes:
|
||||
"Production CloudTrialExhaustedModal mounted against fixture APIs covering required model-provider connection, multi-agent migration, success confirmation, and error retry.",
|
||||
},
|
||||
},
|
||||
beforeEach: () => installCloudTrialFixtures().cleanup,
|
||||
} satisfies Meta<typeof CloudTrialExhaustedModal>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const ExhaustedSingleAgent: Story = {
|
||||
args: {
|
||||
open: true,
|
||||
companyId: COMPANY_ID,
|
||||
status: singleAgentExhaustedStatus,
|
||||
required: true,
|
||||
},
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Connect a model provider to continue" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("Nova")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/\$1/)).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const ExhaustedMultipleAgents: Story = {
|
||||
args: {
|
||||
open: true,
|
||||
companyId: COMPANY_ID,
|
||||
status: multiAgentExhaustedStatus,
|
||||
required: true,
|
||||
},
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/all 3 agents/i)).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("Atlas")).toBeInTheDocument();
|
||||
expect(screen.getByText("Sage")).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const MigratingAgents: Story = {
|
||||
args: {
|
||||
open: true,
|
||||
companyId: COMPANY_ID,
|
||||
status: singleAgentExhaustedStatus,
|
||||
required: true,
|
||||
initialPhase: "migrating",
|
||||
},
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Updating your agents to your model provider/i)).toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export const MigrationSucceeded: Story = {
|
||||
args: {
|
||||
open: true,
|
||||
companyId: COMPANY_ID,
|
||||
status: multiAgentExhaustedStatus,
|
||||
required: true,
|
||||
initialPhase: "done",
|
||||
initialResult: {
|
||||
migratedCount: 2,
|
||||
agents: [
|
||||
{
|
||||
agentId: "11111111-1111-4111-8111-111111111111",
|
||||
name: "Nova",
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
{
|
||||
agentId: "44444444-4444-4444-8444-444444444444",
|
||||
name: "Atlas",
|
||||
adapterType: "paperclip_runner",
|
||||
runnerProvider: "claude",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
],
|
||||
resumedRunIds: ["99999999-9999-4999-8999-999999999999"],
|
||||
resumedIssueId: "33333333-3333-4333-8333-333333333333",
|
||||
},
|
||||
},
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Model provider connected/i)).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText(/automatically resumed/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /Continue to workspace/i })).toBeEnabled();
|
||||
},
|
||||
};
|
||||
|
||||
export const MigrationError: Story = {
|
||||
args: {
|
||||
open: true,
|
||||
companyId: COMPANY_ID,
|
||||
status: singleAgentExhaustedStatus,
|
||||
required: true,
|
||||
initialPhase: "error",
|
||||
initialError: "Selected AI connection could not be verified on this environment.",
|
||||
},
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(/Could not finish updating your agents/i);
|
||||
});
|
||||
const backBtn = screen.getByRole("button", { name: /Choose another provider/i });
|
||||
await userEvent.click(backBtn);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("OpenAI")).toBeInTheDocument();
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export const ViewerNonBlocking: Story = {
|
||||
args: {
|
||||
open: true,
|
||||
companyId: COMPANY_ID,
|
||||
status: {
|
||||
...singleAgentExhaustedStatus,
|
||||
canMigrate: false,
|
||||
},
|
||||
required: false,
|
||||
},
|
||||
play: async () => {
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/company administrator needs to connect a model provider/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByRole("button", { name: /Dismiss/i })).toBeEnabled();
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user