diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index 3c32f8854f..e151f3863a 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -48,34 +48,62 @@ primary-only, and so is the signed GitHub-trigger audit (staging2 has no GitHub shared deployment engine (`use_shared_engine`) is not supported for staging2. A `staging2` GitHub Environment exists only because lease records are kept per installation; it holds no secrets and must not get any (staging2's jobs run with `staging`). -**Signing in to staging2.** Use workload identity; no separate token exists for staging2. (The -staging smoke token is also registered there, as the admin, so the deploy's smoke tests and pool -seeding can sign in; agents should use workload identity.) Audience -`https://api.sammy2.party/api/auth/workload-identity-login`; targets `staging2-agent-admin` -(superadmin) or `staging2-agent-user` (ordinary user). Add the returned cookie for -`.sammy2.party`. The issuer and allowed source project/user are the same as for `staging`. - -**What a fresh staging2 has.** The deploy bootstraps it on every run -(`scripts/deploy/bootstrap-staging-installation.ts`, secondary installations only): the two users -above, a platform cloud credential copied from `staging` (a platform GCP credential, or a GCP -service-account key owned by one of staging's agent test accounts, otherwise any other enabled -platform cloud credential, today Hetzner; staging's GCP credential today is workload identity, which only trusts -`sammy.party`'s issuer, so staging2 uses Hetzner), the staging smoke token registered for -the admin, and the shared compute pool's machines (the same ones `staging`'s pool has active, or, when the -providers differ, the two cheapest machines per role with at least 2 vCPU and 8 GB). -Both users are opted into the SAM AI proxy for each copied agent key -(`providerMode: sam`), the only way a platform key is used. Today that is Claude Code, so -start sessions with the Claude Code agent (for example set the project's default agent); -the installation default agent has no key. There is no GitHub App: use Artifacts-backed -projects. The shared pool is capped at 2 nodes on first seeding, because the Hetzner account -is shared with staging and production. +**The staging2 account to use.** Since 2026-11-17 the working account is +`test-user@simple-agent-manager.org` (user `staging2-test-user`, superadmin). Raphaël added its +own credentials by hand: a Claude Code OAuth credential, a GCP cloud credential, and a platform +`google-infrastructure` integration. Run sessions and VMs as that user. The two bootstrap users +(`staging2-agent-admin`, `staging2-agent-user`) have no credentials of their own. + +**Signing in to staging2.** Use workload identity; no separate token exists for staging2. +Audience `https://api.sammy2.party/api/auth/workload-identity-login`; target `staging2-test-user` +once the trust names it, otherwise `staging2-agent-admin` (superadmin) or `staging2-agent-user`. +Add the returned cookie for `.sammy2.party`. The issuer and allowed source project/user are the +same as for `staging`. + +The trust comes from the `staging` Environment's GitHub secret `AGENT_SIGN_IN_TRUST_STAGING2`, which +Raphaël sets by hand: staging's issuer and source, with `allowedTargets` +`["staging2-agent-admin","staging2-agent-user","staging2-test-user"]`. Deploys pass it straight to +`configure-secrets.sh` as `SECONDARY_AGENT_SIGN_IN_TRUST`, in the same bulk secret write, and never +derive it from staging's trust. The first staging2 deploy after the secret is set (and PR #2841 is +on the deployed ref) applies it. Before that, the Worker value from earlier deploys names only the +two bootstrap users, so signing in as `staging2-test-user` returns 403. While the secret is unset, +a deploy leaves staging2's Worker secret as it is (`AGENT_SIGN_IN_TRUST_KEEP_WHEN_UNSET`), so +staging2 is never left without a trust; revoking it therefore also means deleting the Worker +secret by hand. + +The staging smoke token works on staging2 only where a registration row already exists (the +one made before 2026-11-17 does). Deploys no longer register it, because that needs staging2's +`ENCRYPTION_KEY` in the runner. When staging2 refuses the token, the deploy's smoke tests are +skipped with a warning. + +**What a fresh staging2 has.** The deploy seeds only what needs no secret value +(`scripts/deploy/bootstrap-staging-installation.ts`, secondary installations only): the two +bootstrap users above, both opted into the SAM AI proxy for Claude Code (`providerMode: sam`). +It never reads a Pulumi secret, decrypts a credential, or copies anything from `staging` (policy +795e72a6, `.claude/rules/83-no-secret-readback-in-ci.md`). A human (Raphaël) sets up the rest by +hand, once per installation: + +1. Sign in as `test-user@simple-agent-manager.org`. On a rebuilt installation, add that user + first, as superadmin, in the D1 console. Then add its credentials (Claude Code, GCP) and the + Google infrastructure integration. +2. Admin → Infrastructure: pick the shared pool's machines, at most 2 nodes. +3. GitHub → Environments → `staging`: the `AGENT_SIGN_IN_TRUST_STAGING2` secret described above. + +Earlier deploys copied some rows into staging2 by the old, now removed path: platform +credentials `staging2-bootstrap-cloud` (Hetzner) and `staging2-bootstrap-agent-claude-code`, the +smoke token `staging2-bootstrap-smoke-token`, and the pool machines. Those rows are still in +place; deleting them is Raphaël's call. A teardown removes everything, and the steps above must +then be repeated: file an inbox item for Raphaël before tearing staging2 down, and do not expect +a rebuilt staging2 to run VMs or agent sessions on its own. There is no GitHub App: use +Artifacts-backed projects. **Querying staging2 directly.** Same account and `$CF_TOKEN` as staging. Look the D1 id up by name (`sam2-staging2`): `GET /accounts/$CF_ACCOUNT_ID/d1/database?name=sam2-staging2`. **Teardown.** Actions → Teardown → `staging2` → `DELETE`. It touches only `sam2-*` resources, the `staging2` Pulumi stack and the `sammy2.party` zone's workspace and node records. Delete test workspaces and -nodes first; teardown does not delete VMs. The next deploy rebuilds staging2 from nothing. +nodes first; teardown does not delete VMs. The next deploy rebuilds staging2 with only its two +users. Credentials, pool and smoke token then need Raphaël's manual setup again (above). **Branches that add a Durable Object migration.** Durable Object migrations only move forward. Once a branch deploys a tag that `origin/main` lacks (a new `[[migrations]]` entry in @@ -87,7 +115,9 @@ include it, and the deploy-time migration preflight stays the backstop). Use `st when you are done on `staging2`, tear it down (Actions → Teardown → `staging2` → `DELETE`, after deleting test workspaces and nodes) and redeploy `main` to it (`gh workflow run deploy-staging.yml --ref main -f environment=staging2 -f sam_task_id=`) before you release. staging2 rebuilds -from nothing, so main-based branches can use it again. Nothing does this automatically. +from nothing, so main-based branches can use it again. Teardown erases the manual setup above +(credentials, pool, sign-in trust Worker value), so file an inbox item asking Raphaël to redo it; +until he does, staging2 cannot run VMs or agent sessions. Nothing does this automatically. Adding a third: one entry in `scripts/deploy/staging-installations.mjs` plus a zone in the staging Cloudflare account that the staging deploy token can edit. diff --git a/.agents/skills/api-reference/SKILL.md b/.agents/skills/api-reference/SKILL.md index 3b49d51f27..d31ca457c4 100644 --- a/.agents/skills/api-reference/SKILL.md +++ b/.agents/skills/api-reference/SKILL.md @@ -12,6 +12,7 @@ The reference covers: - Node Management (`/api/nodes/*`) - Workspace Management (`/api/workspaces/*`) - Project Management (`/api/projects/*`) +- Project Insights (`/api/projects/:projectId/insights/{flow,accounts,people}`) - Default Capacity Pools (`/api/projects/:id/capacity-pools/defaults*`, `/api/capacity-pools/defaults*`, `/api/admin/capacity-pools/defaults*`) - Provider Catalog (`/api/providers/catalog`) - Task Management (`/api/projects/:projectId/tasks/*`) diff --git a/.agents/skills/do/SKILL.md b/.agents/skills/do/SKILL.md index 6d90eddcc7..ff82580c6c 100644 --- a/.agents/skills/do/SKILL.md +++ b/.agents/skills/do/SKILL.md @@ -16,7 +16,7 @@ Read the full workflow from `.claude/commands/do.md` and execute it. Use `.claud 4. **Implement** — follow checklist, push frequently, run quality checks. After the first push open the PR as a draft (`gh pr create --draft`); draft PRs run only quick CI checks. **For UI changes**: run mandatory Playwright visual audit with mock data on mobile + desktop viewports (see `.claude/rules/17-ui-visual-testing.md`) 5. **Validate** — full quality suite: lint, typecheck, test, build. As soon as the candidate is complete, mark the PR ready (`gh pr ready `), which starts the full CI suite, and request CodeRabbit at the same moment; reviews and staging then run in parallel with CI and CodeRabbit 6. **Review** — invoke local specialist skills / local subagents ($go-specialist, $cloudflare-specialist, etc.) -7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call) and use the free or shorter one with `-f environment=` (staging2 sign-in: workload identity). A branch adding a Durable Object migration tag that main lacks must use staging2 and, if unmerged when done, tear staging2 down and redeploy main before releasing. Reserve first: `gh workflow run deploy-staging.yml --ref -f environment= -f lease_action=reserve -f sam_task_id=`; schedule a SAM wake at your turn start (shown in the run summary and `status`) instead of polling or chatting, and never dispatch a deploy while another branch holds the lease or has its turn. On your turn deploy with the same command minus `lease_action` (only the head of the queue may take a freed slot, for a 10-minute grace period by default). After live checks release with `-f lease_action=release`, confirm success, and if you released early message the next task in the queue. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. +7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call) and use the free or shorter one with `-f environment=` (staging2 sign-in: workload identity). A branch adding a Durable Object migration tag that main lacks must use staging2 and, if unmerged when done, tear staging2 down, redeploy main before releasing, and file an inbox item asking Raphaël to redo staging2's manual credential setup (teardown erases it). Reserve first: `gh workflow run deploy-staging.yml --ref -f environment= -f lease_action=reserve -f sam_task_id=`; schedule a SAM wake at your turn start (shown in the run summary and `status`) instead of polling or chatting, and never dispatch a deploy while another branch holds the lease or has its turn. On your turn deploy with the same command minus `lease_action` (only the head of the queue may take a freed slot, for a 10-minute grace period by default). After live checks release with `-f lease_action=release`, confirm success, and if you released early message the next task in the queue. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. 8. **PR** — the PR is already ready from step 5 (create it now if not, not as a draft). Wait for the full CI run on the ready PR (the required `Durable Object Workers` check reports only after every job finished). CodeRabbit is requested when the PR is marked ready, through the trusted GitHub Actions path: apply the `coderabbit-review` label with `gh pr edit --add-label coderabbit-review`; if the label run did not fire (it never fires on a draft PR), run `gh workflow run coderabbit-bot-review.yml --ref main -f pr_number=`. Do not post `@coderabbitai review` directly with an agent token. Then wait about 15 minutes from the request, ending at once on a `Review skipped`, rate-limit or quota reply. A CodeRabbit review is not required, but one that arrives blocks merge: implement or resolve every finding with a reason, and give incremental reviews after pushed fixes the same wait. If no review arrives (silence, `Review skipped`, rate limit), record that in the PR's CodeRabbit Review Evidence and continue. Do not re-trigger in a loop, and never add `needs-human-review` or wait for a waiver because CodeRabbit is silent (see `.claude/rules/25-review-merge-gate.md`). If the user requested draft PR / do-not-merge, do not mark it ready; get the full suite with `gh workflow run ci.yml --ref `, stop at the draft PR and do not merge. 9. **Cleanup** — remove worktree, pull main diff --git a/.claude/commands/do.md b/.claude/commands/do.md index 0e8e5a8a41..a57e17c398 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -227,8 +227,9 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin workload identity only; see "Two Staging Installations" in the full reference. A branch that adds a Durable Object migration tag `origin/main` lacks is refused on primary `staging`: use `staging2`, and if the branch has not merged when you - are done, tear `staging2` down and redeploy `main` before releasing (full - reference, "Branches that add a Durable Object migration"). + are done, tear `staging2` down and redeploy `main` before releasing, then file an + inbox item asking Raphaël to redo its manual credential setup, which teardown + erases (full reference, "Branches that add a Durable Object migration"). 2. **Reserve first, then deploy only on your turn.** Reserving takes seconds and deploys nothing: @@ -303,8 +304,9 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin If the env var is not set, ask the human for credentials. On `staging2` (`sammy2.party`), sign in with your workload identity instead (audience - `https://api.sammy2.party/api/auth/workload-identity-login`, target `staging2-agent-user` or - `staging2-agent-admin`); see "Two Staging Installations" in the full reference. + `https://api.sammy2.party/api/auth/workload-identity-login`, target `staging2-test-user`, the + account that holds staging2's credentials, once the trust names it); see "Two Staging + Installations" in the full reference. 6. **Verify the changed behavior works end-to-end:** - **UI changes**: interact as a real user — click buttons, submit forms, navigate pages diff --git a/.claude/rules/00-rule-routing.md b/.claude/rules/00-rule-routing.md index 7db93d6c80..4dc449e2dd 100644 --- a/.claude/rules/00-rule-routing.md +++ b/.claude/rules/00-rule-routing.md @@ -8,10 +8,12 @@ the files it governs with `paths` frontmatter. - **Claude Code** loads a rule without `paths` at launch. It loads a rule with `paths` when a matching file is read, written or edited (`.claude/hooks/log-instructions-loaded.sh` records every load in `.tmp/instruction-loads/`). -- **Codex and other harnesses** load none of these files by themselves. The root - `AGENTS.md` lists the launch rules by name. The `AGENTS.md` nearest the code lists the - path-scoped rules for that directory. Read both sets before editing. This route is a - convention: nothing delivers these rules to Codex automatically. +- **Codex** loads only the root `AGENTS.md`, which lists the launch rules by name. In SAM + sessions the hook `.codex/hooks/rule-context.mjs` adds the path-scoped rules for the files + a shell command or patch touches (see `scripts/quality/README.md`, "Codex hooks"). +- **Other harnesses** load none of these files by themselves. The `AGENTS.md` nearest the + code lists the path-scoped rules for that directory. Read it and the launch rules before + editing. - A path-scoped rule arrives when you first access a matching file. Claude Code counts the Read, Write and Edit tools and simple shell reads of one file (`cat`, `head`, `sed -n`). It does not arrive before you write a brand-new file, when a script or @@ -128,5 +130,6 @@ work, or planning in one of these areas, open the rule yourself. - `79-new-enum-values-audit-every-denylist.md`: A New Value in a Shared Status Enum Must Audit Every Denylist Over That Enum. Loads for: apps/web; packages/shared - `80-sam-glass.md`: SAM Glass. Loads for: apps/web; packages/ui - `82-typed-cards-every-harness.md`: A Typed Chat Card Must Render for Every Agent Harness. Loads for: apps/web; packages/shared (src/typed-chat-cards.ts) +- `83-no-secret-readback-in-ci.md`: No Secret Readback or Printing in CI. Loads for: .github; scripts; infra diff --git a/.claude/rules/08-architecture.md b/.claude/rules/08-architecture.md index f24ed5e9b3..ad88a52c2c 100644 --- a/.claude/rules/08-architecture.md +++ b/.claude/rules/08-architecture.md @@ -22,7 +22,7 @@ worker module packages: project-data, operations, app-deployment, ai-proxy, agen @simple-agent-manager/web ``` -Build order matters: shared -> providers / worker-core / scheduler-core -> worker module packages -> api/web. +Build order matters: shared -> providers / worker-core / scheduler-core / cron -> worker module packages -> api/web. Of the worker module packages, project-data also depends on scheduler-core and app-deployment on providers. Worker module packages never import from `apps/*`; the worker imports them through public entry points only (`eslint.config.mjs`, `boundaryRules`). diff --git a/.claude/rules/26-project-chat-first.md b/.claude/rules/26-project-chat-first.md index c0b3724856..a7a7f2c0b4 100644 --- a/.claude/rules/26-project-chat-first.md +++ b/.claude/rules/26-project-chat-first.md @@ -10,6 +10,8 @@ paths: The app is chat-first (spec 022). The **project chat** is the primary way users interact with workspaces, agents, files, and tools. The workspace view is secondary — most users access everything through the project chat without ever navigating to a standalone workspace page. +Opening a project lands on its **Overview** (`/projects/:id` redirects to `/projects/:id/overview`, inbox slice F2), with chat one tap away. "Chat first" here is about where features integrate, not which route a project opens on. + When building or modifying any feature that has a user-facing component, the **project chat integration** must be designed and implemented first. The workspace view integration is secondary and can follow. ### What This Means in Practice diff --git a/.claude/rules/83-no-secret-readback-in-ci.md b/.claude/rules/83-no-secret-readback-in-ci.md new file mode 100644 index 0000000000..374224383b --- /dev/null +++ b/.claude/rules/83-no-secret-readback-in-ci.md @@ -0,0 +1,79 @@ +--- +paths: + - '.github/**' + - 'scripts/**' + - 'infra/**' +--- + +# No Secret Readback or Printing in CI + +## When This Applies + +Any change to a workflow, a deploy or CI script, or Pulumi code that touches a secret: a +GitHub secret, a Pulumi secret output, a Worker secret, a stored credential, or any value +derived from one. + +## Why This Rule Exists + +Raphaël, 2026-11-17 (project policy 795e72a6): "Make sure we never do anything ever again that +even has the slightest risk of printing secrets in github actions. Better to just have me do +some manual work configure a new environment if necessary, or ask me to give you a secret in +here that you can add to github action secrets." + +The staging2 bootstrap ("Bootstrap Secondary Installation" in +`.github/workflows/deploy-reusable.yml`) read both installations' `ENCRYPTION_KEY` with +`pulumi stack output --show-secrets` on every deploy. It decrypted staging's platform +credentials (the Claude Code key, the cloud credential, test accounts' GCP keys), re-encrypted +them for staging2, HMACed the smoke token with the target key, and derived staging2's sign-in +trust from staging's secret. `scripts/deploy/configure-secrets.sh` read six Pulumi-generated +keys the same way on every deploy, production included, and masked none of them. A scan of +the logs found no leak. The design was rejected anyway: GitHub masks only values it knows, +line by line, so a value read back, decrypted, JSON-escaped, base64-encoded or derived is not +masked, and one stray `echo`, `set -x` or error message prints it. + +## Hard Requirements + +1. **No readback.** Never read a secret out of Pulumi (`--show-secrets`, `showSecrets: true`, + `pulumi config get` of a secret), out of a Worker, or out of D1 in a runner. +2. **No decryption in CI.** Never decrypt stored credentials (`platform_credentials`, user + credentials) in a workflow or deploy script, and never import a decrypt helper there. +3. **No copying between installations.** An installation never takes another installation's + credentials. Staging installations do not share credentials automatically. +4. **No tracing or dumps.** No `set -x` (in any flag cluster such as `set -euxo`), no `bash -x`. + Never print `env`, `printenv`, or any variable or command output that can hold a secret, + including to `$GITHUB_STEP_SUMMARY`, `$GITHUB_OUTPUT`, step outputs or artifacts. +5. **The only allowed shape:** a secret comes from `${{ secrets.X }}`, which GitHub masks, and + goes straight to the tool that consumes it, through `env:` or stdin. It must never be a + command-line argument, and it must never be transformed first. +6. **When an installation needs a secret or credential:** ask Raphaël to configure it by hand + (Admin → Credentials, the Cloudflare dashboard, GitHub settings), or collect it in chat with + `request_secret` and store it as a GitHub secret. Never print it. Prefer manual setup to + automation that touches secret values. +7. **Legacy reads that cannot go yet** add `::add-mask::` for every line and for the + JSON-escaped form, right after the read and before any other use, and only when + `GITHUB_ACTIONS=true`. Each one carries `# sam:secret-readback-allowed ` + and has a tracked task to remove it (rule 42). + +## Enforcement + +- **Mechanical, blocking in CI:** `pnpm quality:no-secret-readback` + (`scripts/quality/check-no-secret-readback.ts`) reports Pulumi readback (`--show-secrets`, + `showSecrets`, `pulumi config get`), credential decryption and decrypt-helper imports, shell + tracing and environment dumps in `.github/`, `scripts/` and `infra/`. It accepts a marked line + only when the file and task are pinned in its `ALLOWED_LEGACY_READS` and the task is still + open. Coverage and noise measurements are in `scripts/quality/README.md`. +- **The check catches ordinary shapes, not deliberate evasion.** It is a tripwire for the + forms people write by habit; an obfuscated read (indirection, `eval`, encoded commands) is + a review finding, not a gap to chase with more patterns. +- **Judgment, in review:** printing a variable that holds a secret, transformed secrets (base64, + JSON, HMAC or derived keys), secrets in step outputs, summaries or artifacts, and secrets on + command lines. The check cannot tell which variables are secret. + +## Quick Compliance Check + +- [ ] No secret is read back, decrypted, derived or copied in a runner +- [ ] Every secret in a step comes from `secrets.*` and goes straight to its consumer, via env or stdin +- [ ] No `set -x`, environment dump, or echo of a secret-bearing variable or command output +- [ ] Manual setup steps for a new environment are written down for Raphaël rather than automated +- [ ] Any remaining legacy read is masked first and carries a marker naming an open task +- [ ] `pnpm quality:no-secret-readback` passes diff --git a/.claude/skills/api-reference/SKILL.md b/.claude/skills/api-reference/SKILL.md index 1dab452887..20b17ba79d 100644 --- a/.claude/skills/api-reference/SKILL.md +++ b/.claude/skills/api-reference/SKILL.md @@ -67,6 +67,7 @@ The control plane uses the VM-agent capability path `DELETE /workspaces/:id/phys - `PATCH /api/projects/:id/capacity-pools/defaults` — Update only the project-owned default pool policy (workspace strategy, deployment strategy, exhaustion policy, or maximum nodes), candidate statuses, provider-native `catalogAdditions`, or `sourceOrder` (provider order, most preferred source first; `null`/`[]` clears; unknown ids → 400 `missingSourceIds`); requires project `secret:write` and never mutates user or installation fallback pools. - `PATCH /api/projects/:id` — Update project metadata (`name`, `description`, `defaultBranch`) - `DELETE /api/projects/:id` — Delete project (cascades project tasks/dependencies/events) +- Insights (project members; `?range=7d|30d|90d`, default `30d`, else 400; each a thin adapter over its `packages/operations/src/insights-*.ts` op, `routes/project-insights.ts`): `GET /api/projects/:projectId/insights/flow` (`projectFlow`), `.../insights/accounts` (`projectAccounts`, `private, no-store`), `.../insights/people` (`projectPeople`, `private, no-store`: waiting-on by assignee with private items reduced to their age, review pickup median/p90 from `pull_request_review_requests`, first-person answer share; reassign goes through the Inbox `.../inbox/items/:ref/reassign` route). Run receipt: `GET /api/projects/:projectId/tasks/:taskId/receipt` ## Default Capacity Pools @@ -98,7 +99,8 @@ The control plane uses the VM-agent capability path `DELETE /workspaces/:id/phys - `POST /api/projects/:projectId/sessions/:sessionId/attention/:markerId/resolve` — Validate, forward, and record one structured human-input answer (`{ answer }`) - `GET /api/inbox`, `GET /api/inbox/count`, `GET /api/projects/:projectId/inbox[/count]` — inbox list (`filter`, `limit`, `cursor`) and counts across `asks`, attention markers (via `session_summaries.attention_json`), secret requests and approvals (`routes/inbox.ts`) - `GET /api/projects/:projectId/inbox/items/:ref[?context=true]`, `POST .../items/:ref/answer`, `POST .../items/:ref/archive` — one item, answer through its store's existing path, archive (agent told it will not act); writes need the exact app origin + JSON -- MCP `inbox_write` (`ask`, `review`, `update`, `cancel`) and `inbox_read` (`list`, `get`) — the agent's side of the inbox (`routes/mcp/inbox-tools.ts` over `packages/operations/src/inbox-agent-core.ts` / `inbox-agent-reads.ts`): files `asks` rows from the token's chat and task, links checked as the project's, `idempotencyKey` → `dedupe_key agent::`, similar open items returned; update/cancel bind project, chat and kind (`question`/`review`). `request_human_input` is a blocking `ask` alias. Only a blocking question pauses a chat (readers filter `blocking = 1`). +- Human tasks (`ask:`, kind `task`): `POST .../items/:ref/steps/:index` `{done}`, `.../comments` `{body, threadId?, mentions?}`, `.../claim`, `.../reassign` `{assigneeUserId}|{team:true}`, `.../done` `{note?}`, `.../reopen`; `GET .../items/:ref` adds `task` (steps, assignee, claim, activity, discussion). Routes: `apps/api/src/routes/inbox-tasks.ts` +- MCP `inbox_write` (`ask`, `review`, `result`, `assign`, `comment`, `attach`, `update`, `cancel`) and `inbox_read` (`list`, `get`) — the agent's side of the inbox (`routes/mcp/inbox-tools.ts` over `packages/operations/src/inbox-agent-core.ts` / `inbox-agent-reads.ts`): files `asks` rows from the token's chat and task, links checked as the project's, `idempotencyKey` → `dedupe_key agent::`, similar open items returned; update/cancel bind project, chat and kind (`question`/`review`/`result`/`task`). A `result` answered with no text ("Got it") closes with `notified_at` set and wakes no one; a reply wakes the agent. `request_human_input` is a blocking `ask` alias. Only a blocking question pauses a chat (readers filter `blocking = 1`). - `POST /api/projects/:projectId/sessions/:sessionId/stop` — Stop a chat session - `GET /api/projects/:projectId/sessions/:sessionId/access` — Shared-access summary: `viewerAccess` (`owner`/`grantee`/`reader`), owner, active grants (`expiresAt`, `durationMinutes`), `undelivered` (messages cancelled because their sender's access ended, newest first, at most 100, `{ messageId, reason }`) and `serverTime`. The session detail carries the same summary - `POST /api/projects/:projectId/sessions/:sessionId/access/grants` — Share the chat with an active member, or (owner only) renew (`{ userId, durationMinutes: 5|10|30|60, acknowledgeSharedCredentials: true }`; no default duration; `201` new, `200` existing). Its `access` omits `undelivered` @@ -114,6 +116,7 @@ Comment threads are scoped to the ProjectData Durable Object addressed by `proje - `GET /api/projects/:projectId/tasks/:taskId` — Get task detail (includes dependencies + blocked state) - `PATCH /api/projects/:projectId/tasks/:taskId` — Update task fields (`title`, `description`, `priority`, `parentTaskId`) - `DELETE /api/projects/:projectId/tasks/:taskId` — Delete task +- `POST /api/projects/:projectId/tasks/:taskId/provider-limit/start-anyway` — Owner-only `task:write` override of a waiting admission hold (`202 starting`) or saved callback hold (`202 waking`, same account/profile and retained claim). The saved-session notice calls this **Resume anyway**. Snapshot/generation/authority/expiry are rechecked; changed waits return `409`. - `POST /api/projects/:projectId/tasks/:taskId/provider-limit/resume` — Owner approves a blocked provider wait and resumes its retained snapshot or first-dispatch admission. Requires `task:write`; `202` waking, `409` if no longer blocked or snapshot unavailable. - `POST /api/projects/:projectId/tasks/:taskId/status` — Transition task status - `POST /api/projects/:projectId/tasks/:taskId/status/callback` — Trusted callback status update for delegated tasks @@ -166,6 +169,8 @@ Project event pull loop: create a subscription with the narrowest useful filter, ## Administration (Superadmin Only) - `GET|PUT|DELETE /api/admin/ai-allowance/:userId` — Per-user AI allowance: budget ceilings plus `allowedModelTiers` (`null` = every tier, else a subset of `low-cost`/`standard`/`premium`; unknown names are `400`). The AI proxy enforces the tiers on every platform-credential route (`packages/ai-proxy/src/ai-model-tier-gate.ts`): out-of-tier or untiered models get `403 permission_error`, an unreadable allowance fails closed; BYO-key passthrough is not restricted +- `GET /api/admin/health-cost?range=7d|30d|month` — Superadmin Admin Health & cost read (`installationHealth` in `packages/operations`): compute spend per currency, reuse, density, new-machine reasons, lifecycle latency, and `cloudflare` (the Cloudflare account's estimated USD cost this month from the daily snapshot) +- `POST /api/admin/health-cost/cloudflare/refresh` — Superadmin "Refresh now": runs the Cloudflare cost snapshot (`runCloudflareCostSnapshot`); `429` inside `insights.cloudflareCostRefreshMinSeconds`; Cloudflare failures return `200` with a recorded status - `GET /api/admin/tasks/stuck` — List tasks currently in transient states - `GET /api/admin/tasks/:taskId/reconciliation-diagnostics` — Read the TaskRunner probe, task-scoped runtime liveness, eligibility threshold, reconciliation decision, and whether/where the bounded cursor page selects the task, without mutating task state - `GET /api/admin/tasks/recent-failures` — List recent failed tasks with error details diff --git a/.claude/skills/env-reference/SKILL.md b/.claude/skills/env-reference/SKILL.md index b8c341bb8a..539cc1e2f9 100644 --- a/.claude/skills/env-reference/SKILL.md +++ b/.claude/skills/env-reference/SKILL.md @@ -26,7 +26,7 @@ Uses `GH_*` prefix because GitHub Actions secret names cannot start with `GITHUB | Variable | `D1_MIGRATION_CHURNING_TABLE_MAX_DECREASE_PERCENT` | No (default: `50`; range: 0–100) | | Variable | `D1_MIGRATION_READ_ATTEMPTS` | No (default: `3`; range: 1–5; verification reads only) | | Variable | `D1_MIGRATION_READ_RETRY_DELAY_MS` | No (default: `10000`; range: 0–60000) | -| Secret | `CF_API_TOKEN` | Yes (requires Account → SSL and Certificates → Edit for Origin CA) | +| Secret | `CF_API_TOKEN` | Yes (requires Account → SSL and Certificates → Edit for Origin CA; optional Account Analytics → Read for Admin Analytics and the Cloudflare cost snapshot) | | Secret | `CF_ACCOUNT_ID` | Yes | | Secret | `CF_ZONE_ID` | Yes | | Secret | `DEVCONTAINER_CACHE_CLOUDFLARE_API_TOKEN` | No (falls back to `CF_API_TOKEN`) | @@ -103,7 +103,7 @@ Admin setting overrides take precedence over registry defaults. The disabled set Sources: `apps/api/src/services/operator-settings.ts`, `admin-settings-registry.ts`, and `apps/api/src/durable-objects/sam-session/operator/work.ts`. -The assistant reuses existing `SAM_MODEL` (the deployed `wrangler.toml` value is `@cf/zai-org/glm-5.3-flash`, which needs the Workers Paid plan or prepaid AI Gateway credits, like the rest of SAM; code default `claude-sonnet-5`), context/window, tool-result and model-step limits from `resolveSamConfig`, plus `SAM_LLM_TIMEOUT_MS` (operator fallback `120000`). Operator turn admission uses `SAM_MESSAGE_MAX_LENGTH` with a `16000`-character fallback; legacy subtask-message readers can have a different fallback. No new provider API key is required specifically for enabling the assistant: it uses the installation's supported platform AI configuration and usage gate. +The assistant reuses existing `SAM_MODEL` (code default `@cf/deepseek-ai/deepseek-v4.1-flash-1017` in `resolveSamConfig`; omitted from Wrangler bindings unless explicitly overridden through the GitHub Environment variable `SAM_MODEL`; this model requires the Workers Paid plan or prepaid AI Gateway credits, like the rest of SAM), context/window, tool-result and model-step limits from `resolveSamConfig`, plus `SAM_LLM_TIMEOUT_MS` (operator fallback `120000`). Operator turn admission uses `SAM_MESSAGE_MAX_LENGTH` with a `16000`-character fallback; legacy subtask-message readers can have a different fallback. No new provider API key is required specifically for enabling the assistant: it uses the installation's supported platform AI configuration and usage gate. ### How Worker variables are set @@ -271,6 +271,7 @@ Activity coalescing and binding caches are per Worker isolate. Delayed flushes c - `WORKSPACE_IDLE_BACKOFF_MAX_MS` — Maximum workspace-idle retry delay; the delay doubles from the base and resets on new activity or when the session wakes (default: `21600000`) - `DIAGNOSIS_COMPLETED_STEP_MIN_DELAY_MS` — Minimum re-arm delay for completed diagnosis steps (default: `1000`) - `ORCHESTRATOR_ZERO_TASK_GRACE_MS` — Grace before a zero-task mission terminalizes (default: `600000`) +- Mission cancellation bounds use `orchestrator.cancellation*` runtime settings under Admin Settings → Operations; they are not environment variables. - `ORCHESTRATOR_MAX_MISSION_LIFETIME_MS` — Mission lifetime backstop (default: `86400000`) - `ORCHESTRATOR_WAIT_RECONCILE_INTERVAL_MS` — ProjectData D1 reconciliation backstop interval for active parent waits (default: `30000`) - `ORCHESTRATOR_WAIT_MAX_CHILDREN` — Maximum same-project task IDs selected by one durable wait (default: `20`, hard ceiling: `90`) @@ -642,6 +643,7 @@ by the read-only cron-liveness check. - `SESSION_ACTIVITY_STALE_THRESHOLD_MS` — Threshold before stale working activity is checked against authoritative SessionHost inventory (default: 300000) - `NODE_HEARTBEAT_STALE_SECONDS` — Staleness threshold for node health - `TASK_LIVENESS_PROBE_TIMEOUT_MS` — Per-candidate timeout for ACP and Instant lifecycle probes used by ProjectData heartbeat deferral, idle cleanup, and stuck-task reconciliation; timeout is inconclusive (default: 5000) +- `PROMPT_DELIVERY_BACKGROUND_TIMEOUT_MS` — Background prompt target/recovery preparation and owner-approved recovery repair wait budget, also used for VM submit/receipt calls (default: `5000`). Owner repair timeout retains the pending consent/claim; late completion stays fenced and cannot acknowledge the timed-out sweep. - `TASK_LIVENESS_MAX_ACP_SESSIONS` — Maximum task-scoped ACP sessions inspected per liveness probe (default: 5) - `TASK_LIVENESS_NODE_HEALTH_PROBE_TIMEOUT_MS` — Timeout for stale-VM-node health probes used by ProjectData idle cleanup and stuck-task reconciliation; a timeout is inconclusive and preserves the task/workspace (default: 5000) - `NODE_PROVISIONING_REQUEST_TIMEOUT_MS` — Durable direct provisioning per-request budget for Cloudflare calls during allocation/reconciliation, also used for background readiness and workspace dispatch (default: 5000). The attempt's cancellation budget is the admin setting `operations.nodeProvisioningAttemptDeadlineMs` (default 60000, range 5000–180000, never below this value); it cuts pre-create steps and the node DNS record only, not a started create, its publish, readiness or dispatch. diff --git a/.codex/config.toml b/.codex/config.toml index 0c7581374f..525b053802 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -14,13 +14,45 @@ approval_policy = "never" # Hooks (schema: https://developers.openai.com/codex/hooks) # ============================================================================== # Each event holds matcher groups, and each group holds a `hooks` array of handlers. -# `timeout` is in seconds. Project hooks run only when this .codex/ layer is trusted and -# each hook definition has been trusted (Codex records trust against its hash). +# `timeout` is in seconds. Codex runs project hooks only for a trusted project whose hook +# definitions are trusted. codex-acp trusts the session's project; SAM's vm-agent supplies +# the hook trust (bypass_hook_trust in buildCodexACPManagedConfigEnv, +# packages/vm-agent/internal/acp/session_host_agent_config.go). # `pnpm quality:agent-context-budget --check` validates these entries. -# No hooks are configured: SAM-managed Codex sessions do not trust this project, so Codex -# would skip them (probe evidence on SAM idea 01M7H32EK6S4E31EHWVSJSENR5). The rule-delivery -# and Stop hooks wait on that decision, on branch sam/codex-rule-delivery-hook. +# Path-scoped rule delivery: Codex loads only the root AGENTS.md by itself. This hook adds +# the rules (.claude/rules/*.md with `paths`) that govern the files a tool call touches, +# the same rules Claude Code loads on file access. See .codex/hooks/rule-context.mjs. +# additionalContextLimit (tokens) sits above the hook's own byte cap so Codex never spills. +[[hooks.SessionStart]] +matcher = "^(startup|resume|clear|compact|fork)$" + +[[hooks.SessionStart.hooks]] +type = "command" +command = 'node "$(git rev-parse --show-toplevel)/.codex/hooks/rule-context.mjs"' +timeout = 10 +additionalContextLimit = 20000 +statusMessage = "Preparing SAM rule delivery" + +[[hooks.PreToolUse]] +matcher = "^(Bash|apply_patch)$" + +[[hooks.PreToolUse.hooks]] +type = "command" +command = 'node "$(git rev-parse --show-toplevel)/.codex/hooks/rule-context.mjs"' +timeout = 10 +additionalContextLimit = 20000 +statusMessage = "Checking SAM rules for these files" + +# Test-quality Stop gate (rule 35), shared with Claude Code. Delivery per finding class is +# set and measured in .claude/hooks/verify-test-quality.mjs; it never blocks without limit. +[[hooks.Stop]] + +[[hooks.Stop.hooks]] +type = "command" +command = 'node "$(git rev-parse --show-toplevel)/.claude/hooks/verify-test-quality.mjs"' +timeout = 30 +statusMessage = "Checking tests for changed boundary code" [projects."/workspaces/simple-agent-manager"] trust_level = "trusted" diff --git a/.codex/hooks/rule-context.mjs b/.codex/hooks/rule-context.mjs new file mode 100644 index 0000000000..10526360a7 --- /dev/null +++ b/.codex/hooks/rule-context.mjs @@ -0,0 +1,486 @@ +#!/usr/bin/env node +// rule-context.mjs — Codex hook that delivers path-scoped rules. +// +// Codex started at the repository root loads only the root AGENTS.md. Claude Code loads a +// path-scoped rule (.claude/rules/*.md with `paths` frontmatter) when a matching file is +// accessed; this hook gives Codex the same rules at the same moment: +// +// SessionStart (startup, resume, clear, compact, fork) +// Starts a new delivery epoch when the model's context was reset (startup, clear, +// compact), so rules are delivered again, and tells the model how delivery works. +// PreToolUse (apply_patch, Bash) +// Finds the repository paths the call touches, and adds the bodies of the rules +// that govern them and have not been delivered in this epoch as additionalContext. +// The first write to paths whose rules were never delivered is denied once, so the +// rules are in context before anything is written; the retried write is allowed. +// +// Which rules apply to a path comes from .codex/hooks/rule-scopes.json, generated from +// scripts/quality/agent-instructions.ts by `pnpm quality:agent-context-budget --write` +// (--check fails when it is stale). Rule bodies are read from disk when delivered. +// +// Constraints: Node built-ins only (it must run in a workspace without node_modules); it +// never fails a session (every error path prints `{}` and exits 0, which Codex treats as +// "no opinion"); output is bounded by SAM_CODEX_RULE_CONTEXT_MAX_BYTES so Codex never +// spills it to disk. Every delivery is logged to .tmp/instruction-loads/codex-.jsonl. +// +// `node .codex/hooks/rule-context.mjs --show ...` prints the rules for paths, for an +// agent (or a person) who wants them without a hook. + +import { createHash } from 'node:crypto'; +import { + appendFileSync, + mkdirSync, + readFileSync, + renameSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); +const LOOKUP_FILE = join(ROOT, '.codex/hooks/rule-scopes.json'); +const STATE_DIR = join(ROOT, '.tmp/codex-rule-context'); +const LOG_DIR = join(ROOT, '.tmp/instruction-loads'); + +/** + * Rule text per hook output. Must stay below the handler's additionalContextLimit in + * .codex/config.toml (20000 tokens; at a conservative three bytes per token that is 60 KB) so Codex never spills. + */ +const DEFAULT_MAX_BYTES = 40_000; +const MIN_MAX_BYTES = 4_000; +const MAX_MAX_BYTES = 48_000; + +/** Session-start sources after which the model no longer has earlier hook context. */ +const RESET_SOURCES = new Set(['startup', 'clear', 'compact']); + +/** Shell words that write their path arguments. */ +const SHELL_WRITERS = new Set([ + 'cp', + 'install', + 'ln', + 'mkdir', + 'mv', + 'rm', + 'rmdir', + 'tee', + 'touch', + 'truncate', +]); + +const IGNORED_SEGMENTS = new Set(['.git', 'node_modules', '.tmp', 'dist']); + +/** Input bounds: a hook runs before every shell call, so a huge command must stay cheap. */ +const MAX_COMMAND_CHARS = 64_000; +const MAX_WORDS = 4_000; +const MAX_CD_STEPS = 50; +const MAX_PATH_CHARS = 1_024; +const MAX_TARGETS = 200; +const DISPLAY_PATH_CHARS = 200; + +/** Only files in the rules directory may be read into model context. */ +const RULE_PATH = /^\.claude\/rules\/[A-Za-z0-9._-]+\.md$/; + +/** A path as shown to the model or written to the log: bounded and quoted. */ +export function displayPath(path) { + const text = String(path); + return JSON.stringify( + text.length > DISPLAY_PATH_CHARS ? `${text.slice(0, DISPLAY_PATH_CHARS)}…` : text + ); +} + +export function maxBytes(env = process.env) { + const raw = Number.parseInt(env.SAM_CODEX_RULE_CONTEXT_MAX_BYTES ?? '', 10); + if (!Number.isFinite(raw)) return DEFAULT_MAX_BYTES; + return Math.min(MAX_MAX_BYTES, Math.max(MIN_MAX_BYTES, raw)); +} + +export function loadLookup(file = LOOKUP_FILE) { + const data = JSON.parse(readFileSync(file, 'utf8')); + if (!data || !Array.isArray(data.rules)) throw new Error('rule-scopes.json has no rules array'); + return data.rules + .filter((rule) => RULE_PATH.test(String(rule.path)) && Array.isArray(rule.patterns)) + .map((rule) => ({ + path: String(rule.path), + title: String(rule.title).slice(0, DISPLAY_PATH_CHARS), + patterns: rule.patterns.map((p) => ({ + literal: Number(p.literal) || 0, + regex: new RegExp(p.regex), + })), + })); +} + +/** How narrowly a matched pattern names the path: its literal characters. */ +function specificity(rule, path) { + let best = -1; + for (const pattern of rule.patterns) { + if (pattern.regex.test(path)) best = Math.max(best, pattern.literal); + } + return best; +} + +/** Rules governing any of `paths`, most specific first; a directory matches its contents. */ +export function rulesFor(lookup, paths) { + const scored = new Map(); + for (const path of paths) { + const probes = path.isDirectory ? [`${path.path}/x`] : [path.path]; + for (const probe of probes) { + for (const rule of lookup) { + const score = specificity(rule, probe); + if (score < 0) continue; + const entry = scored.get(rule.path); + if (!entry || entry.score < score) scored.set(rule.path, { rule, score }); + } + } + } + return [...scored.values()] + .sort((a, b) => b.score - a.score || a.rule.path.localeCompare(b.rule.path)) + .map((entry) => entry.rule); +} + +/** Repository-relative path for a token, or null when it is outside the repository. */ +export function toRepoPath(token, cwd, root = ROOT) { + if (String(token).length > MAX_PATH_CHARS) return null; + const absolute = isAbsolute(token) ? token : resolve(cwd, token); + const rel = relative(root, absolute); + if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null; + const normalized = rel.split('\\').join('/'); + if (normalized.split('/').some((segment) => IGNORED_SEGMENTS.has(segment))) return null; + return normalized; +} + +/** Target paths of an apply_patch body. */ +export function patchPaths(patch) { + const paths = []; + for (const line of String(patch).split('\n')) { + const match = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/.exec(line.trim()); + if (match) paths.push(match[1].trim()); + if (paths.length >= MAX_TARGETS) break; + } + return paths; +} + +/** Drop heredoc bodies: they are file content or script text, not path arguments. */ +export function withoutHeredocBodies(text) { + const lines = text.split('\n'); + const kept = []; + let delimiter = null; + for (const line of lines) { + if (delimiter !== null) { + if (line.trim() === delimiter) delimiter = null; + continue; + } + kept.push(line); + const match = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/.exec(line); + if (match) delimiter = match[1]; + } + return kept.join('\n'); +} + +function shellWords(command) { + // Good enough to find path arguments; not a shell parser. Quotes are stripped, operators + // split words, and anything with expansion syntax is dropped. + return String(command) + .replaceAll(/\\\n/g, ' ') + .split(/[\s;|&()<>]+/) + .map((word) => word.replaceAll(/^['"]+|['"]+$/g, '')) + .filter((word) => word.length > 0); +} + +/** + * Paths a shell command reads or writes, resolved against `cd` steps inside it. A command + * counts as a write when it redirects output, edits in place, or runs a writing command. + */ +export function shellPaths(command, cwd, root = ROOT, exists = defaultExists) { + const text = withoutHeredocBodies(String(command).slice(0, MAX_COMMAND_CHARS)); + const words = shellWords(text).slice(0, MAX_WORDS); + const known = new Map(); + const kindOf = (path) => { + if (!known.has(path)) known.set(path, exists(path)); + return known.get(path); + }; + let base = cwd; + let cdSteps = 0; + const found = []; + for (let index = 0; index < words.length; index++) { + const word = words[index]; + if (word === 'cd' && words[index + 1]) { + const next = words[index + 1]; + if (!/[$`*]/.test(next) && cdSteps < MAX_CD_STEPS && next.length <= MAX_PATH_CHARS) { + base = resolve(base, next); + cdSteps++; + } + index++; + continue; + } + const candidate = word.includes('=') && word.startsWith('-') ? word.split('=')[1] : word; + if (!candidate || candidate.startsWith('-') || /[$`*?{}[\]]/.test(candidate)) continue; + if (!candidate.includes('/') && !candidate.includes('.')) continue; + const absolute = isAbsolute(candidate) ? candidate : resolve(base, candidate); + const repoPath = toRepoPath(absolute, base, root); + if (!repoPath) continue; + const kind = kindOf(absolute); + if (kind) found.push({ path: repoPath, isDirectory: kind === 'dir', exists: true }); + else if (kindOf(dirname(absolute)) === 'dir') { + found.push({ path: repoPath, isDirectory: false, exists: false }); + } + } + const writes = + />>?\s*[^\s&|]/.test( + text.replaceAll(/[0-9]?>&[0-9]/g, '').replaceAll(/>\s*\/dev\/null/g, '') + ) || + /\b(?:sed|perl)\s+(?:-[a-zA-Z]*\s+)*-[a-zA-Z]*i/.test(text) || + /\bgit\s+(?:mv|rm|apply|checkout|restore)\b/.test(text) || + words.some((word) => SHELL_WRITERS.has(word)); + return { paths: dedupe(found).slice(0, MAX_TARGETS), writes }; +} + +function dedupe(paths) { + const seen = new Map(); + for (const entry of paths) if (!seen.has(entry.path)) seen.set(entry.path, entry); + return [...seen.values()]; +} + +function defaultExists(path) { + try { + return statSync(path).isDirectory() ? 'dir' : 'file'; + } catch { + return null; + } +} + +function readRuleBody(rulePath, root) { + const text = readFileSync(join(root, rulePath), 'utf8'); + // Drop the frontmatter: the scope is stated in the header line instead. + return text.replace(/^---\n[\s\S]*?\n---\n/, '').trim(); +} + +/** + * Build the model-visible text for `rules`, delivering whole bodies in order until the + * byte budget is spent, and naming the rest so the model knows they exist (a capped + * selection must disclose what it dropped). + */ +export function renderDelivery(rules, targets, budget, root = ROOT) { + const header = [ + `SAM rule delivery (.codex/hooks/rule-context.mjs). These repository rules govern ${targets + .slice(0, 5) + .map(displayPath) + .join(', ')}${targets.length > 5 ? `, +${targets.length - 5} more` : ''}.`, + 'Claude Code loads them by itself when these files are accessed; treat them as project instructions for this work.', + ].join('\n'); + const parts = [header]; + let used = Buffer.byteLength(header); + const delivered = []; + const deferred = []; + for (const rule of rules) { + let body; + try { + body = readRuleBody(rule.path, root); + } catch { + continue; + } + const block = `\n\n===== ${rule.path} =====\n${body}`; + const size = Buffer.byteLength(block); + if (used + size > budget - 1500) { + deferred.push(rule); + continue; + } + parts.push(block); + used += size; + delivered.push({ rule, bytes: size }); + } + if (deferred.length > 0) { + const lines = deferred + .slice(0, 40) + .map((rule) => `- ${rule.path}: ${rule.title}`) + .join('\n'); + const more = deferred.length > 40 ? `\n- +${deferred.length - 40} more` : ''; + parts.push( + `\n\nAlso governing these paths, not delivered yet because of the per-call size cap. They arrive with your next tool calls on these paths, or run \`node .codex/hooks/rule-context.mjs --show ${targets[0] ? displayPath(targets[0]) : ''}\`:\n${lines}${more}` + ); + } + return { text: parts.join(''), delivered, deferred }; +} + +/** A file-name-safe key; long or unusual ids are shortened and made unique with a hash. */ +export function sessionKey(sessionId) { + const raw = String(sessionId || 'unknown'); + const safe = raw.replaceAll(/[^A-Za-z0-9._-]/g, '_').slice(0, 80); + if (safe === raw) return safe; + return `${safe}-${createHash('sha256').update(raw).digest('hex').slice(0, 12)}`; +} + +function readState(sessionId) { + try { + const state = JSON.parse( + readFileSync(join(STATE_DIR, `${sessionKey(sessionId)}.json`), 'utf8') + ); + return { + epoch: Number(state.epoch) || 0, + delivered: Array.isArray(state.delivered) ? state.delivered : [], + deniedWrites: Array.isArray(state.deniedWrites) ? state.deniedWrites : [], + }; + } catch { + return { epoch: 0, delivered: [], deniedWrites: [] }; + } +} + +function writeState(sessionId, state) { + mkdirSync(STATE_DIR, { recursive: true }); + const file = join(STATE_DIR, `${sessionKey(sessionId)}.json`); + const temporary = `${file}.${process.pid}.tmp`; + writeFileSync(temporary, JSON.stringify(state)); + renameSync(temporary, file); +} + +function log(sessionId, entries) { + if (entries.length === 0) return; + try { + mkdirSync(LOG_DIR, { recursive: true }); + const at = new Date().toISOString(); + const lines = entries.map((entry) => + JSON.stringify({ at, harness: 'codex', session_id: sessionId, ...entry }) + ); + appendFileSync(join(LOG_DIR, `codex-${sessionKey(sessionId)}.jsonl`), `${lines.join('\n')}\n`); + } catch { + // Logging must never fail the hook. + } +} + +function sessionStart(event) { + const source = String(event.source ?? 'startup'); + const state = readState(event.session_id); + let epoch = state.epoch; + if (RESET_SOURCES.has(source) || epoch === 0) { + epoch += 1; + writeState(event.session_id, { epoch, delivered: [], deniedWrites: [] }); + } + log(event.session_id, [{ event: 'SessionStart', source, load_reason: 'session_start', epoch }]); + return { + hookSpecificOutput: { + hookEventName: 'SessionStart', + additionalContext: + 'SAM rule delivery is active. Before a tool call that reads or writes repository files, a hook adds the path-scoped rules (.claude/rules/*.md) that govern those files, if they are not already in your context. The first write to files whose rules you have not seen is refused once with the rules attached: read them, adjust if needed, and retry. The rules every task follows are listed in AGENTS.md under "Rules"; open the ones that bear on your task.', + }, + }; +} + +function preToolUse(event, lookup, budget) { + const tool = String(event.tool_name ?? ''); + const command = event.tool_input?.command ?? ''; + const cwd = typeof event.cwd === 'string' && event.cwd ? event.cwd : ROOT; + let targets; + let writes; + if (tool === 'apply_patch') { + targets = patchPaths(command) + .map((path) => toRepoPath(path, cwd)) + .filter(Boolean) + .map((path) => ({ path, isDirectory: false })); + writes = true; + } else if (tool === 'Bash') { + ({ paths: targets, writes } = shellPaths(command, cwd)); + } else { + return {}; + } + if (targets.length === 0) return {}; + const state = readState(event.session_id); + const delivered = new Set(state.delivered); + const pending = rulesFor(lookup, targets).filter((rule) => !delivered.has(rule.path)); + if (pending.length === 0) return {}; + + const targetPaths = targets.map((target) => target.path); + const rendered = renderDelivery(pending, targetPaths, budget); + if (rendered.delivered.length === 0 && rendered.deferred.length === 0) return {}; + const writeKey = createHash('sha256') + .update(targetPaths.slice().sort().join('\n')) + .digest('hex') + .slice(0, 16); + // Deny only to deliver: a write is refused once, and only when rule text came with it. + const deny = writes && rendered.delivered.length > 0 && !state.deniedWrites.includes(writeKey); + writeState(event.session_id, { + epoch: state.epoch, + delivered: [...delivered, ...rendered.delivered.map((entry) => entry.rule.path)], + deniedWrites: deny ? [...state.deniedWrites, writeKey] : state.deniedWrites, + }); + log( + event.session_id, + rendered.delivered.map((entry) => ({ + event: 'PreToolUse', + tool, + load_reason: 'path_match', + file: entry.rule.path, + trigger: targetPaths[0].slice(0, DISPLAY_PATH_CHARS), + triggers: targetPaths.slice(0, 10).map((path) => path.slice(0, DISPLAY_PATH_CHARS)), + bytes: entry.bytes, + decision: deny ? 'deny_once' : 'allow', + epoch: state.epoch, + tool_use_id: event.tool_use_id ?? null, + })) + ); + const output = { + hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: rendered.text }, + }; + if (deny) { + output.hookSpecificOutput.permissionDecision = 'deny'; + output.hookSpecificOutput.permissionDecisionReason = `Not run yet: ${rendered.delivered.length} repository rule(s) governing ${displayPath(targetPaths[0])} were not in your context. They are attached as context. Check this change against them, then run it again (the retry is allowed). If you cannot see the rule text, run: node .codex/hooks/rule-context.mjs --show ${displayPath(targetPaths[0])}`; + } + return output; +} + +function show(paths) { + const lookup = loadLookup(); + const targets = paths + .map((path) => toRepoPath(path, process.cwd())) + .filter(Boolean) + .map((path) => ({ path, isDirectory: defaultExists(join(ROOT, path)) === 'dir' })); + const rules = rulesFor(lookup, targets); + if (rules.length === 0) { + process.stdout.write('No path-scoped rules govern these paths.\n'); + return; + } + process.stdout.write( + `${ + renderDelivery( + rules, + targets.map((t) => t.path), + maxBytes() + ).text + }\n` + ); +} + +function main() { + const args = process.argv.slice(2); + if (args[0] === '--show') { + show(args.slice(1)); + return; + } + let output = {}; + let event = {}; + try { + event = JSON.parse(readFileSync(0, 'utf8') || '{}'); + if (event.hook_event_name === 'SessionStart') output = sessionStart(event); + else if (event.hook_event_name === 'PreToolUse') { + output = preToolUse(event, loadLookup(), maxBytes()); + } + } catch (error) { + output = {}; + log(event.session_id, [ + { + event: String(event.hook_event_name ?? 'unknown'), + load_reason: 'error', + error: String(error?.message ?? error).slice(0, 300), + }, + ]); + } + process.stdout.write(`${JSON.stringify(output)}\n`); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + try { + main(); + } catch { + process.stdout.write('{}\n'); + } + process.exitCode = 0; +} diff --git a/.codex/hooks/rule-scopes.json b/.codex/hooks/rule-scopes.json new file mode 100644 index 0000000000..6e257eaa6b --- /dev/null +++ b/.codex/hooks/rule-scopes.json @@ -0,0 +1,1258 @@ +{ + "generatedBy": "pnpm quality:agent-context-budget --write", + "note": "Read by .codex/hooks/rule-context.mjs. Do not edit by hand.", + "rules": [ + { + "path": ".claude/rules/04-ui-standards.md", + "title": "UI Standards", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/www/src/content/docs/docs/**", + "regex": "^apps\\/www\\/src\\/content\\/docs\\/docs\\/.*$", + "literal": 31 + } + ] + }, + { + "path": ".claude/rules/06-api-patterns.md", + "title": "API Technical Patterns", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/06-vm-agent-patterns.md", + "title": "VM Agent Technical Patterns", + "patterns": [ + { + "pattern": "packages/cloud-init/**", + "regex": "^packages\\/cloud-init\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "scripts/vm/**", + "regex": "^scripts\\/vm\\/.*$", + "literal": 11 + } + ] + }, + { + "path": ".claude/rules/15-nav-parity.md", + "title": "Desktop–Mobile Navigation Parity", + "patterns": [ + { + "pattern": "apps/web/src/components/NavSidebar.tsx", + "regex": "^apps\\/web\\/src\\/components\\/NavSidebar\\.tsx(?:\\/.*)?$", + "literal": 38 + }, + { + "pattern": "apps/web/src/components/MobileNavDrawer.tsx", + "regex": "^apps\\/web\\/src\\/components\\/MobileNavDrawer\\.tsx(?:\\/.*)?$", + "literal": 43 + }, + { + "pattern": "apps/web/src/components/AppShell.tsx", + "regex": "^apps\\/web\\/src\\/components\\/AppShell\\.tsx(?:\\/.*)?$", + "literal": 36 + }, + { + "pattern": "apps/web/src/components/chat/SessionLinkedWorkDrawer.tsx", + "regex": "^apps\\/web\\/src\\/components\\/chat\\/SessionLinkedWorkDrawer\\.tsx(?:\\/.*)?$", + "literal": 56 + } + ] + }, + { + "path": ".claude/rules/16-no-page-reload-on-mutation.md", + "title": "No Page Reload on Mutation", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/17-ui-visual-testing.md", + "title": "Mandatory Playwright Visual Testing for UI Changes", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + }, + { + "pattern": "scripts/quality/check-preflight-evidence.ts", + "regex": "^scripts\\/quality\\/check-preflight-evidence\\.ts(?:\\/.*)?$", + "literal": 43 + } + ] + }, + { + "path": ".claude/rules/24-no-duplicate-ui-controls.md", + "title": "No Duplicate Implementations", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/shared/**", + "regex": "^packages\\/shared\\/.*$", + "literal": 16 + } + ] + }, + { + "path": ".claude/rules/26-project-chat-first.md", + "title": "Project Chat First", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/27-vm-agent-staging-refresh.md", + "title": "VM Agent Binary Refresh for Staging Tests", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/31-migration-safety.md", + "title": "Migration Safety (ABSOLUTE RULE — DATA LOSS PREVENTION)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/ai-proxy/src/ai-token-budget-counter.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-token-budget-counter\\.ts(?:\\/.*)?$", + "literal": 48 + }, + { + "pattern": "packages/repo-hosting/src/github-installation-leak-sweep.ts", + "regex": "^packages\\/repo-hosting\\/src\\/github-installation-leak-sweep\\.ts(?:\\/.*)?$", + "literal": 59 + }, + { + "pattern": "infra/resources/database.ts", + "regex": "^infra\\/resources\\/database\\.ts(?:\\/.*)?$", + "literal": 27 + }, + { + "pattern": "scripts/deploy/configure-d1-read-replication.sh", + "regex": "^scripts\\/deploy\\/configure-d1-read-replication\\.sh(?:\\/.*)?$", + "literal": 47 + }, + { + "pattern": "scripts/quality/check-do-migration-safety.ts", + "regex": "^scripts\\/quality\\/check-do-migration-safety\\.ts(?:\\/.*)?$", + "literal": 44 + }, + { + "pattern": "scripts/quality/check-migration-safety.test.ts", + "regex": "^scripts\\/quality\\/check-migration-safety\\.test\\.ts(?:\\/.*)?$", + "literal": 46 + }, + { + "pattern": "scripts/quality/check-migration-safety.ts", + "regex": "^scripts\\/quality\\/check-migration-safety\\.ts(?:\\/.*)?$", + "literal": 41 + }, + { + "pattern": "scripts/quality/d1-read-replication-script.test.ts", + "regex": "^scripts\\/quality\\/d1-read-replication-script\\.test\\.ts(?:\\/.*)?$", + "literal": 50 + } + ] + }, + { + "path": ".claude/rules/32-cf-api-debugging.md", + "title": "Cloudflare API Debugging (Use This Before Guessing)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/34-vm-agent-callback-auth-agent-side.md", + "title": "VM Agent Callback Routes Must Use Callback JWT Auth (ABSOLUTE RULE)", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/api/src/routes/deploy-release-callback.ts", + "regex": "^apps\\/api\\/src\\/routes\\/deploy-release-callback\\.ts(?:\\/.*)?$", + "literal": 46 + }, + { + "pattern": "apps/api/src/routes/projects/agent-activity-callback.ts", + "regex": "^apps\\/api\\/src\\/routes\\/projects\\/agent-activity-callback\\.ts(?:\\/.*)?$", + "literal": 55 + } + ] + }, + { + "path": ".claude/rules/34-vm-agent-callback-auth.md", + "title": "VM Agent Callback Routes Must Use Callback JWT Auth (ABSOLUTE RULE)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ai-proxy/**", + "regex": "^packages\\/ai-proxy\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/36-cli-quality.md", + "title": "CLI Quality Bar", + "patterns": [ + { + "pattern": "packages/cli/**", + "regex": "^packages\\/cli\\/.*$", + "literal": 13 + }, + { + "pattern": ".github/workflows/ci.yml", + "regex": "^\\.github\\/workflows\\/ci\\.yml(?:\\/.*)?$", + "literal": 24 + }, + { + "pattern": "sonar-project.properties", + "regex": "^(?:[^/]+\\/)*sonar-project\\.properties(?:\\/.*)?$", + "literal": 24 + } + ] + }, + { + "path": ".claude/rules/37-prototype-development.md", + "title": "Prototype Development", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ui/src/tokens/theme.css", + "regex": "^packages\\/ui\\/src\\/tokens\\/theme\\.css(?:\\/.*)?$", + "literal": 32 + } + ] + }, + { + "path": ".claude/rules/40-sentinel-rows-excluded-from-counts.md", + "title": "Internal/Sentinel Rows Must Be Excluded From Business-Logic Counts", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/43-long-running-mcp-tools.md", + "title": "Long-Running MCP Tools Must Be Async", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/vm-agent/internal/server/mcp_build.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/mcp_build\\.go(?:\\/.*)?$", + "literal": 46 + } + ] + }, + { + "path": ".claude/rules/44-dual-write-migration-enumerate-writers.md", + "title": "Storage Migrations Must Enumerate Every Writer of the Migrated Data", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + } + ] + }, + { + "path": ".claude/rules/45-durable-object-concurrency-mutex.md", + "title": "Durable Objects Do Not Serialize Across `await` — Use a Real Mutex for Critical Sections", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/ai-proxy/src/ai-token-budget-counter.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-token-budget-counter\\.ts(?:\\/.*)?$", + "literal": 48 + } + ] + }, + { + "path": ".claude/rules/46-vm-agent-diagnostic-getter-sync.md", + "title": "VM Agent Diagnostic Getters Must Synchronize Loop-Mutated Fields", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/47-control-loop-io-budget.md", + "title": "Control Loops Need Explicit I/O Budgets", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/ai-proxy/src/ai-monthly-cost-cron.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-monthly-cost-cron\\.ts(?:\\/.*)?$", + "literal": 45 + }, + { + "pattern": "packages/app-deployment/src/scheduled/**", + "regex": "^packages\\/app-deployment\\/src\\/scheduled\\/.*$", + "literal": 38 + }, + { + "pattern": "packages/repo-hosting/src/github-installation-leak-sweep.ts", + "regex": "^packages\\/repo-hosting\\/src\\/github-installation-leak-sweep\\.ts(?:\\/.*)?$", + "literal": 59 + }, + { + "pattern": "packages/agent-email/src/recovery.ts", + "regex": "^packages\\/agent-email\\/src\\/recovery\\.ts(?:\\/.*)?$", + "literal": 36 + } + ] + }, + { + "path": ".claude/rules/48-stale-while-revalidate-ui.md", + "title": "Stale-While-Revalidate UI (No Hiding, No Refetch Loops)", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + } + ] + }, + { + "path": ".claude/rules/49-capture-prerequisites-before-async-completion.md", + "title": "Capture Handler Prerequisites Before a Long Async Operation", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/vm-agent/internal/acp/session_host_prompt.go", + "regex": "^packages\\/vm-agent\\/internal\\/acp\\/session_host_prompt\\.go(?:\\/.*)?$", + "literal": 53 + } + ] + }, + { + "path": ".claude/rules/50-list-read-row-fault-isolation.md", + "title": "List/Snapshot Reads Must Tolerate a Single Malformed Row", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/worker-core/src/row-parsing.ts", + "regex": "^packages\\/worker-core\\/src\\/row-parsing\\.ts(?:\\/.*)?$", + "literal": 39 + } + ] + }, + { + "path": ".claude/rules/51-runtime-boundary-validation.md", + "title": "Runtime boundary validation", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/scheduler-core/**", + "regex": "^packages\\/scheduler-core\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/app-deployment/**", + "regex": "^packages\\/app-deployment\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/ai-proxy/**", + "regex": "^packages\\/ai-proxy\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/agent-email/**", + "regex": "^packages\\/agent-email\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/repo-hosting/**", + "regex": "^packages\\/repo-hosting\\/.*$", + "literal": 22 + }, + { + "pattern": "scripts/quality/type-boundary-baseline.json", + "regex": "^scripts\\/quality\\/type-boundary-baseline\\.json(?:\\/.*)?$", + "literal": 43 + } + ] + }, + { + "path": ".claude/rules/51-server-side-node-class-gates.md", + "title": "Server-Side Node-Class / Identity Gates — Never Trust a Client-Supplied Identifier or Agent Abstention", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/scheduler-core/**", + "regex": "^packages\\/scheduler-core\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + } + ] + }, + { + "path": ".claude/rules/51-vm-agent-no-host-mime-dependency.md", + "title": "VM Agent Behavior Must Not Depend on Host-Provided MIME/OS Databases", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/shared/src/mime.ts", + "regex": "^packages\\/shared\\/src\\/mime\\.ts(?:\\/.*)?$", + "literal": 27 + } + ] + }, + { + "path": ".claude/rules/52-model-catalog-lifecycle.md", + "title": "Model Catalog Lifecycle (Adding and Retiring Provider Models)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/shared/**", + "regex": "^packages\\/shared\\/.*$", + "literal": 16 + }, + { + "pattern": "packages/ai-proxy/**", + "regex": "^packages\\/ai-proxy\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/53-scheduled-handler-isolation-and-liveness-signals.md", + "title": "Scheduled Handlers: Isolate Every Step, and Never Use a Liveness Timestamp as an Idleness Signal", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/vm-agent/internal/deploy/artifact_client.go", + "regex": "^packages\\/vm-agent\\/internal\\/deploy\\/artifact_client\\.go(?:\\/.*)?$", + "literal": 52 + }, + { + "pattern": "packages/vm-agent/internal/deploy/compose.go", + "regex": "^packages\\/vm-agent\\/internal\\/deploy\\/compose\\.go(?:\\/.*)?$", + "literal": 44 + }, + { + "pattern": "packages/vm-agent/internal/server/health.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/health\\.go(?:\\/.*)?$", + "literal": 43 + }, + { + "pattern": "packages/ai-proxy/src/ai-monthly-cost-cron.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-monthly-cost-cron\\.ts(?:\\/.*)?$", + "literal": 45 + }, + { + "pattern": "packages/app-deployment/src/scheduled/**", + "regex": "^packages\\/app-deployment\\/src\\/scheduled\\/.*$", + "literal": 38 + }, + { + "pattern": "packages/repo-hosting/src/github-installation-leak-sweep.ts", + "regex": "^packages\\/repo-hosting\\/src\\/github-installation-leak-sweep\\.ts(?:\\/.*)?$", + "literal": 59 + }, + { + "pattern": "packages/agent-email/src/recovery.ts", + "regex": "^packages\\/agent-email\\/src\\/recovery\\.ts(?:\\/.*)?$", + "literal": 36 + } + ] + }, + { + "path": ".claude/rules/54-vm-agent-rollout-compatibility.md", + "title": "VM Agent Rollout Compatibility", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "scripts/deploy/resolve-vm-agent-release.sh", + "regex": "^scripts\\/deploy\\/resolve-vm-agent-release\\.sh(?:\\/.*)?$", + "literal": 42 + }, + { + "pattern": "scripts/quality/deploy-reusable-workflow.test.ts", + "regex": "^scripts\\/quality\\/deploy-reusable-workflow\\.test\\.ts(?:\\/.*)?$", + "literal": 48 + } + ] + }, + { + "path": ".claude/rules/55-runaway-cost-emergency-ops.md", + "title": "Runaway-Cost Emergency Operations", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/56-clipped-overflow-is-invisible-to-document-checks.md", + "title": "Horizontal Overflow Inside `overflow-x-hidden` Is Invisible to Document-Level Checks", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + } + ] + }, + { + "path": ".claude/rules/56-destructive-provider-ownership-proof.md", + "title": "Destructive Provider Ownership Proof", + "patterns": [ + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + } + ] + }, + { + "path": ".claude/rules/57-write-only-cross-boundary-state.md", + "title": "Cross-Boundary State With Multiple Consumers Must Be Reconciled, Not Just Reported", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/58-terminal-verdicts-must-match-the-resumer.md", + "title": "A \"Work Is Unrecoverable\" Verdict Must Read The Same Record The Resumer Reads", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/src/do/reconciliation-dead-target.ts", + "regex": "^packages\\/project-data\\/src\\/do\\/reconciliation-dead-target\\.ts(?:\\/.*)?$", + "literal": 58 + } + ] + }, + { + "path": ".claude/rules/61-guards-must-cover-every-runtime.md", + "title": "A Guard Added for One Runtime Must Be Enforced for Every Runtime", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/61-per-cycle-budget-counters.md", + "title": "Per-Cycle Budget Counters Must Reset on Success", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/63-widening-a-table-can-delete-an-auth-check.md", + "title": "Making a Scoping Column Nullable Silently Deletes Every Check That Used It", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + } + ] + }, + { + "path": ".claude/rules/64-unstable-prop-identity-remounts-subtrees.md", + "title": "An Object Literal in a Render Body Can Remount an Entire Subtree", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + }, + { + "pattern": "packages/eslint-plugin-sam/src/rules/no-inline-markdown-components.js", + "regex": "^packages\\/eslint-plugin-sam\\/src\\/rules\\/no-inline-markdown-components\\.js(?:\\/.*)?$", + "literal": 69 + } + ] + }, + { + "path": ".claude/rules/65-capped-selection-must-rank-and-disclose.md", + "title": "A Capped Selection Must Rank By Its Purpose, And Must Disclose What It Dropped", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/shared/src/types/comments.ts", + "regex": "^packages\\/shared\\/src\\/types\\/comments\\.ts(?:\\/.*)?$", + "literal": 37 + } + ] + }, + { + "path": ".claude/rules/66-ownership-handoff-must-record-the-supersession.md", + "title": "An Ownership Handoff Must Record That It Happened", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/67-shared-predicates-that-trigger-actions.md", + "title": "Never Widen a Shared Predicate That Drives an Action", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/vm-agent/internal/server/session_snapshot_coordinator.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/session_snapshot_coordinator\\.go(?:\\/.*)?$", + "literal": 65 + }, + { + "pattern": "packages/operations/src/idea-identity.ts", + "regex": "^packages\\/operations\\/src\\/idea-identity\\.ts(?:\\/.*)?$", + "literal": 40 + }, + { + "pattern": "packages/vm-agent/internal/server/session_snapshot_coordinator_test.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/session_snapshot_coordinator_test\\.go(?:\\/.*)?$", + "literal": 70 + }, + { + "pattern": "packages/vm-agent/internal/server/session_snapshot_errors.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/session_snapshot_errors\\.go(?:\\/.*)?$", + "literal": 60 + }, + { + "pattern": "packages/vm-agent/internal/server/workspace_provisioning.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/workspace_provisioning\\.go(?:\\/.*)?$", + "literal": 59 + } + ] + }, + { + "path": ".claude/rules/68-event-scoped-filter-predicates.md", + "title": "Event-Scoped Filters Must Encode Their Scope", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/69-aggregate-capacity-at-final-reservation.md", + "title": "Enforce Aggregate Capacity at the Final Atomic Reservation", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + }, + { + "pattern": "packages/scheduler-core/**", + "regex": "^packages\\/scheduler-core\\/.*$", + "literal": 24 + } + ] + }, + { + "path": ".claude/rules/69-emergency-config-paths-need-their-own-coverage.md", + "title": "A Code Path That Only Activates Under an Emergency Configuration Needs Tests In That Configuration", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/worker-core/src/d1-limits.ts", + "regex": "^packages\\/worker-core\\/src\\/d1-limits\\.ts(?:\\/.*)?$", + "literal": 37 + } + ] + }, + { + "path": ".claude/rules/70-flag-flips-must-verify-the-deployed-value.md", + "title": "A Config Flip Ships Only When the Deployed Value Says So", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": ".github/workflows/deploy-reusable.yml", + "regex": "^\\.github\\/workflows\\/deploy-reusable\\.yml(?:\\/.*)?$", + "literal": 37 + }, + { + "pattern": "scripts/deploy/environment-var-overrides.ts", + "regex": "^scripts\\/deploy\\/environment-var-overrides\\.ts(?:\\/.*)?$", + "literal": 43 + }, + { + "pattern": "scripts/deploy/sync-wrangler-config.ts", + "regex": "^scripts\\/deploy\\/sync-wrangler-config\\.ts(?:\\/.*)?$", + "literal": 38 + }, + { + "pattern": "scripts/deploy/worker-var-defaults.ts", + "regex": "^scripts\\/deploy\\/worker-var-defaults\\.ts(?:\\/.*)?$", + "literal": 37 + }, + { + "pattern": "packages/project-data/src/do/tool-payload-cleanup-config-refusal.ts", + "regex": "^packages\\/project-data\\/src\\/do\\/tool-payload-cleanup-config-refusal\\.ts(?:\\/.*)?$", + "literal": 67 + }, + { + "pattern": "scripts/deploy/configure-d1-read-replication.sh", + "regex": "^scripts\\/deploy\\/configure-d1-read-replication\\.sh(?:\\/.*)?$", + "literal": 47 + } + ] + }, + { + "path": ".claude/rules/71-request-context-must-not-outlive-its-request.md", + "title": "A Goroutine That Outlives Its Request Must Not Capture That Request's Context", + "patterns": [ + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/71-tightening-a-column-can-delete-a-capability.md", + "title": "A New Required Column Can Silently Delete a Capability for Every Existing Row", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/72-error-categories-must-match-the-recovery-action.md", + "title": "An Error Category Must Name the Recovery Action, Not the Provider's Vocabulary", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + } + ] + }, + { + "path": ".claude/rules/73-optional-struct-fields-must-not-overwrite-on-absence.md", + "title": "A Zero-Valued Optional Field Must Not Overwrite Existing State", + "patterns": [ + { + "pattern": "**/*.go", + "regex": "^(?:[^/]+\\/)*[^/]*\\.go$", + "literal": 4 + }, + { + "pattern": "**/*.ts", + "regex": "^(?:[^/]+\\/)*[^/]*\\.ts$", + "literal": 4 + }, + { + "pattern": "**/*.tsx", + "regex": "^(?:[^/]+\\/)*[^/]*\\.tsx$", + "literal": 5 + }, + { + "pattern": "**/*.sql", + "regex": "^(?:[^/]+\\/)*[^/]*\\.sql$", + "literal": 5 + } + ] + }, + { + "path": ".claude/rules/75-external-api-check-then-act.md", + "title": "A Conflict From a Remote Uniqueness Constraint Is a Signal, Not a Failure", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/repo-hosting/**", + "regex": "^packages\\/repo-hosting\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/app-deployment/**", + "regex": "^packages\\/app-deployment\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/vm-agent/internal/server/vm_jobs.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/vm_jobs\\.go(?:\\/.*)?$", + "literal": 44 + } + ] + }, + { + "path": ".claude/rules/77-library-extension-points-typed-and-exercised.md", + "title": "Implement a Library Extension Point Against the Library's Types, and Test It Through the Library", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/78-snapshot-capture-must-scale-with-the-session.md", + "title": "Snapshot Capture Cost Must Scale With the Session, Not the Repository", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/api/src/services/session-snapshot-capture-cleanup.ts", + "regex": "^apps\\/api\\/src\\/services\\/session-snapshot-capture-cleanup\\.ts(?:\\/.*)?$", + "literal": 57 + } + ] + }, + { + "path": ".claude/rules/79-new-enum-values-audit-every-denylist.md", + "title": "A New Value in a Shared Status Enum Must Audit Every Denylist Over That Enum", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/shared/**", + "regex": "^packages\\/shared\\/.*$", + "literal": 16 + } + ] + }, + { + "path": ".claude/rules/80-sam-glass.md", + "title": "SAM Glass", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + } + ] + }, + { + "path": ".claude/rules/82-typed-cards-every-harness.md", + "title": "A Typed Chat Card Must Render for Every Agent Harness", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/shared/src/typed-chat-cards.ts", + "regex": "^packages\\/shared\\/src\\/typed-chat-cards\\.ts(?:\\/.*)?$", + "literal": 39 + } + ] + }, + { + "path": ".claude/rules/83-no-secret-readback-in-ci.md", + "title": "No Secret Readback or Printing in CI", + "patterns": [ + { + "pattern": ".github/**", + "regex": "^\\.github\\/.*$", + "literal": 8 + }, + { + "pattern": "scripts/**", + "regex": "^scripts\\/.*$", + "literal": 8 + }, + { + "pattern": "infra/**", + "regex": "^infra\\/.*$", + "literal": 6 + } + ] + } + ] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ed710a90cc..93412b9dca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -92,6 +92,7 @@ jobs: - 'packages/ai-proxy/**' - 'packages/app-deployment/**' - 'packages/cloud-init/**' + - 'packages/cron/**' - 'packages/operations/**' - 'packages/project-data/**' - 'packages/providers/**' @@ -134,11 +135,13 @@ jobs: - 'scripts/deploy/deploy-signing-keys.ts' - 'scripts/deploy/types.ts' - 'scripts/deploy/vapid-keys.ts' + - 'scripts/selfhost/reverse-tunnel-migrations.ts' - 'scripts/quality/node-pool-boundary.ts' - 'scripts/quality/node-pool-boundary/**' - 'tests/fixtures/acp-activity-report-v1.json' - 'tests/fixtures/deploy-release/**' - 'tests/fixtures/durable-execution-protocol-v1.json' + - 'tests/fixtures/session-snapshot-restore-transcript-only-v1.json' # The conformance suite also builds the self-host entry/configuration. hosted-git: - *api @@ -174,6 +177,7 @@ jobs: - 'packages/ai-proxy/**' - 'packages/app-deployment/**' - 'packages/cloud-init/**' + - 'packages/cron/**' - 'packages/eslint-plugin-sam/**' - 'packages/operations/**' - 'packages/project-data/**' @@ -190,6 +194,8 @@ jobs: - 'apps/web/src/components/AgentSettingsCard.tsx' vm-agent: - 'packages/vm-agent/**' + # Shared with the Worker tests; a fixture-only edit must run the Go half too. + - 'tests/fixtures/session-snapshot-restore-transcript-only-v1.json' - 'apps/api/Dockerfile.vm-agent-container' - 'scripts/ci/verify-codex-runtime-image.sh' - 'scripts/deploy/prepare-codex-runtime-artifact.sh' @@ -206,6 +212,7 @@ jobs: - 'packages/agent-email/src/**' - 'packages/operations/src/**' - 'packages/ai-proxy/src/**' + - 'packages/cron/src/**' - 'sonar-project.properties' - '.claude/rules/36-cli-quality.md' devcontainer: @@ -422,6 +429,14 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile --ignore-scripts + # Policy 795e72a6 / rule 83: no Pulumi secret readback, credential decryption, shell + # tracing or environment dumps in workflow, deploy, infra or CI-script code. Here, not in a + # path-filtered job, so every PR runs it whatever it touches. Blocking from the start: zero + # findings outside real instances in 25 sampled commits since June 2026 + # (scripts/quality/README.md). + - name: No secret readback in CI code (policy 795e72a6) + run: pnpm quality:no-secret-readback + - name: Install verified Gitleaks release env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 237e61bf20..01fb457630 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -34,7 +34,7 @@ jobs: - name: Run Claude Code id: claude - uses: anthropics/claude-code-action@4d75e5f390ee76b2e09c1980ecc99ff3a2e088c8 # v1 + uses: anthropics/claude-code-action@f3b070c88125d33dbae5653df5f143101d4ea9dc # v1 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} allowed_bots: 'simple-agent-manager' diff --git a/.github/workflows/deploy-reusable.yml b/.github/workflows/deploy-reusable.yml index fc73378c2e..27cb8f7c1b 100644 --- a/.github/workflows/deploy-reusable.yml +++ b/.github/workflows/deploy-reusable.yml @@ -896,6 +896,7 @@ jobs: OBSERVABILITY_ERROR_MESSAGE_MAX_LENGTH: ${{ vars.OBSERVABILITY_ERROR_MESSAGE_MAX_LENGTH }} OBSERVABILITY_ERROR_STACK_MAX_LENGTH: ${{ vars.OBSERVABILITY_ERROR_STACK_MAX_LENGTH }} OBSERVABILITY_ERROR_USER_AGENT_MAX_LENGTH: ${{ vars.OBSERVABILITY_ERROR_USER_AGENT_MAX_LENGTH }} + SAM_MODEL: ${{ vars.SAM_MODEL }} DEBUG_AGENT_MODEL: ${{ vars.DEBUG_AGENT_MODEL }} DEBUG_AGENT_MAX_TURNS: ${{ vars.DEBUG_AGENT_MAX_TURNS }} DEBUG_AGENT_RUN_TOKEN_LIMIT: ${{ vars.DEBUG_AGENT_RUN_TOKEN_LIMIT }} @@ -1766,6 +1767,7 @@ jobs: OBSERVABILITY_ERROR_MESSAGE_MAX_LENGTH: ${{ vars.OBSERVABILITY_ERROR_MESSAGE_MAX_LENGTH }} OBSERVABILITY_ERROR_STACK_MAX_LENGTH: ${{ vars.OBSERVABILITY_ERROR_STACK_MAX_LENGTH }} OBSERVABILITY_ERROR_USER_AGENT_MAX_LENGTH: ${{ vars.OBSERVABILITY_ERROR_USER_AGENT_MAX_LENGTH }} + SAM_MODEL: ${{ vars.SAM_MODEL }} DEBUG_AGENT_MODEL: ${{ vars.DEBUG_AGENT_MODEL }} DEBUG_AGENT_MAX_TURNS: ${{ vars.DEBUG_AGENT_MAX_TURNS }} DEBUG_AGENT_RUN_TOKEN_LIMIT: ${{ vars.DEBUG_AGENT_RUN_TOKEN_LIMIT }} @@ -1978,32 +1980,17 @@ jobs: # A secondary installation shares this environment's account-level credentials but not # its identity: OAuth/App callbacks, signing, encryption and analytics overrides belong to - # the primary installation, so they are not passed and Pulumi generates the keys. Its - # agent sign-in trust is the primary's, retargeted at its bootstrap users. - - name: Derive Installation Agent Sign-In Trust - if: ${{ !inputs.use_shared_engine && (inputs.dry_run != true) && steps.deploy_resources.outputs.secondary == 'true' }} - run: pnpm tsx scripts/deploy/bootstrap-staging-installation.ts derive-trust - env: - AGENT_SIGN_IN_TRUST_FILE: ${{ runner.temp }}/agent-sign-in-trust.json - INSTALLATION: ${{ steps.deploy_resources.outputs.installation }} - DEPLOY_ENVIRONMENT: ${{ steps.deploy_resources.outputs.credential_environment }} - BASE_DOMAIN: ${{ steps.deploy_resources.outputs.base_domain }} - SOURCE_AGENT_SIGN_IN_TRUST: ${{ secrets.AGENT_SIGN_IN_TRUST }} - + # the primary installation, so they are not passed and Pulumi generates the keys. Its agent + # sign-in trust is its own GitHub secret (AGENT_SIGN_IN_TRUST_STAGING2), passed straight to + # configure-secrets.sh as SECONDARY_AGENT_SIGN_IN_TRUST and written in the same bulk secret + # deployment; unset, the Worker value is left as it is. A new secondary installation needs + # its own secret name in that expression. + # Nothing here reads, derives or copies a secret (.claude/rules/83-no-secret-readback-in-ci.md). - name: Configure Worker Secrets if: ${{ !inputs.use_shared_engine && (inputs.dry_run != true) }} - run: | - # A secondary installation's trust was derived into a file (never a step output). - if [ -n "$AGENT_SIGN_IN_TRUST_FILE" ]; then - AGENT_SIGN_IN_TRUST="" - if [ -f "$AGENT_SIGN_IN_TRUST_FILE" ]; then - AGENT_SIGN_IN_TRUST="$(cat "$AGENT_SIGN_IN_TRUST_FILE")" - fi - export AGENT_SIGN_IN_TRUST - fi - bash scripts/deploy/configure-secrets.sh "$DEPLOY_ENV" + run: bash scripts/deploy/configure-secrets.sh "$DEPLOY_ENV" env: - AGENT_SIGN_IN_TRUST_FILE: ${{ steps.deploy_resources.outputs.secondary == 'true' && format('{0}/agent-sign-in-trust.json', runner.temp) || '' }} + AGENT_SIGN_IN_TRUST_KEEP_WHEN_UNSET: ${{ steps.deploy_resources.outputs.secondary == 'true' && 'true' || '' }} CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }} CF_ZONE_ID: ${{ steps.deploy_resources.outputs.secondary == 'true' && (steps.installation_zone.outputs.zone_id || 'unresolved-zone') || secrets.CF_ZONE_ID }} @@ -2037,7 +2024,9 @@ jobs: R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} SMOKE_TEST_AUTH_ENABLED: ${{ secrets.SMOKE_TEST_AUTH_ENABLED }} + # The primary's trust never reaches a secondary, and a secondary's never reaches the primary. AGENT_SIGN_IN_TRUST: ${{ steps.deploy_resources.outputs.secondary != 'true' && secrets.AGENT_SIGN_IN_TRUST || '' }} + SECONDARY_AGENT_SIGN_IN_TRUST: ${{ steps.deploy_resources.outputs.secondary == 'true' && steps.deploy_resources.outputs.installation == 'staging2' && secrets.AGENT_SIGN_IN_TRUST_STAGING2 || '' }} DEPLOY_SIGNING_PRIVATE_KEY: ${{ steps.deploy_resources.outputs.secondary != 'true' && secrets.DEPLOY_SIGNING_PRIVATE_KEY || '' }} DEPLOY_SIGNING_PUBLIC_KEY: ${{ steps.deploy_resources.outputs.secondary != 'true' && secrets.DEPLOY_SIGNING_PUBLIC_KEY || '' }} SEGMENT_WRITE_KEY: ${{ steps.deploy_resources.outputs.secondary != 'true' && secrets.SEGMENT_WRITE_KEY || '' }} @@ -2146,56 +2135,17 @@ jobs: API_URL: ${{ steps.deploy_resources.outputs.api_url }} # Secondary installations only (never production; the script re-checks the allowlist): - # seed the agent test users, copy a portable cloud credential from the primary - # installation, register the smoke token, then pick the shared pool's machines through - # the admin API (so it runs after the health check). Idempotent; see the script header. + # seed the two agent test users. No secret value is read, decrypted or copied here; an admin + # adds credentials, pool machines and the sign-in trust by hand (see the script header). - name: Bootstrap Secondary Installation if: ${{ !inputs.use_shared_engine && (inputs.dry_run != true) && steps.deploy_resources.outputs.secondary == 'true' && inputs.environment != 'production' }} - working-directory: infra - run: | - read_output() { - local value - value="$(pulumi stack output --stack "$1" "$2" --show-secrets)" - if [ -z "$value" ]; then - echo "::error::Pulumi output $2 is empty on stack $1" >&2 - return 1 - fi - printf '%s' "$value" - } - TARGET_D1_ID="$(read_output "$TARGET_STACK" d1DatabaseId)" - SOURCE_D1_ID="$(read_output "$PRIMARY_STACK" d1DatabaseId)" - TARGET_ENCRYPTION_KEY="$(read_output "$TARGET_STACK" encryptionKey)" - echo "::add-mask::$TARGET_ENCRYPTION_KEY" - if [ -n "$PRIMARY_ENCRYPTION_KEY_OVERRIDE" ]; then - SOURCE_ENCRYPTION_KEY="$PRIMARY_ENCRYPTION_KEY_OVERRIDE" - else - SOURCE_ENCRYPTION_KEY="$(read_output "$PRIMARY_STACK" encryptionKey)" - echo "::add-mask::$SOURCE_ENCRYPTION_KEY" - fi - if [ "$TARGET_D1_ID" = "$SOURCE_D1_ID" ] || [ "$TARGET_STACK" = "$PRIMARY_STACK" ]; then - echo "::error::Target and primary installation resolve to the same stack or database." - exit 1 - fi - export TARGET_D1_ID SOURCE_D1_ID TARGET_ENCRYPTION_KEY SOURCE_ENCRYPTION_KEY - cd .. && pnpm tsx scripts/deploy/bootstrap-staging-installation.ts bootstrap + run: pnpm tsx scripts/deploy/bootstrap-staging-installation.ts env: - AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} - PULUMI_CONFIG_PASSPHRASE: ${{ secrets.PULUMI_CONFIG_PASSPHRASE }} CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }} CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} INSTALLATION: ${{ steps.deploy_resources.outputs.installation }} DEPLOY_ENVIRONMENT: ${{ steps.deploy_resources.outputs.credential_environment }} BASE_DOMAIN: ${{ steps.deploy_resources.outputs.base_domain }} - TARGET_STACK: ${{ steps.pulumi-select.outputs.stack_name }} - PRIMARY_STACK: ${{ steps.deploy_resources.outputs.primary_stack }} - # The primary Worker's keys: an Environment override wins over Pulumi, as in - # configure-secrets.sh. The secondary never receives these overrides. - PRIMARY_ENCRYPTION_KEY_OVERRIDE: ${{ secrets.ENCRYPTION_KEY }} - SOURCE_CREDENTIAL_ENCRYPTION_KEY: ${{ secrets.CREDENTIAL_ENCRYPTION_KEY }} - SMOKE_TEST_TOKEN: ${{ secrets.SMOKE_TEST_TOKEN }} - # Only the primary's designated test accounts' own credentials may be copied. - SOURCE_AGENT_SIGN_IN_TRUST: ${{ secrets.AGENT_SIGN_IN_TRUST }} - name: Output Deployment URLs id: output diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml index 0a23227dff..bdf07cf868 100644 --- a/.github/workflows/deploy-staging.yml +++ b/.github/workflows/deploy-staging.yml @@ -116,9 +116,10 @@ jobs: base_domain: ${{ steps.target.outputs.base_domain }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - # The lease is keyed by installation. A secondary installation (staging2) has no secrets of - # its own: its jobs run with the environment the allowlist names (scripts/deploy/ - # staging-installations.mjs) and it is deployed to its own domain, stack and prefix. + # The lease is keyed by installation. A secondary installation (staging2) has no GitHub + # Environment secrets of its own: its jobs run with the environment the allowlist names + # (scripts/deploy/staging-installations.mjs), whose AGENT_SIGN_IN_TRUST_STAGING2 secret is its + # sign-in trust, and it is deployed to its own domain, stack and prefix. - name: Resolve installation target id: target env: @@ -246,16 +247,40 @@ jobs: echo '::error::SMOKE_TEST_TOKEN is required for the requested staging performance audit' exit 1 + # Deploys never register the smoke token on a secondary installation: that needs the + # installation's ENCRYPTION_KEY in the runner (policy 795e72a6). Where it was registered by + # earlier deploys or by hand it works; where the installation refuses it, skip with a warning. + # The token goes from the GitHub secret straight to the request body on stdin. + - name: Check smoke token on a secondary installation + id: smoke_token + # `installation` is empty for the primary installation (workflowTargetFor), so this never + # runs there: on the primary a refused token must fail the smoke tests, not skip them. + if: ${{ needs.lease.outputs.installation != '' && !inputs.github_trigger_audit_send_only && env.SMOKE_TEST_TOKEN != '' }} + run: | + status="$(node -e 'process.stdout.write(JSON.stringify({ token: process.env.SMOKE_TEST_TOKEN }))' | + curl -sS -o /dev/null -w '%{http_code}' -X POST -H 'content-type: application/json' \ + --data-binary @- "$SMOKE_TEST_API_URL/api/auth/token-login")" || status="request failed" + # Only a refusal skips: any other failure (5xx, network) still runs the tests, which then + # report the broken installation. + if [ "$status" = "401" ]; then + echo "::warning::The smoke token is not registered on $INSTALLATION; smoke tests skipped (see 'Two Staging Installations')." + echo "skip=true" >> "$GITHUB_OUTPUT" + else + echo "Smoke token check on $INSTALLATION: HTTP $status" + fi + env: + INSTALLATION: ${{ needs.lease.outputs.installation }} + - name: Run smoke tests - if: ${{ !inputs.github_trigger_audit_send_only && !inputs.performance_audit_only && env.SMOKE_TEST_TOKEN != '' }} + if: ${{ !inputs.github_trigger_audit_send_only && !inputs.performance_audit_only && env.SMOKE_TEST_TOKEN != '' && steps.smoke_token.outputs.skip != 'true' }} run: node node_modules/@playwright/test/cli.js test --config=tests/smoke/playwright.config.ts - name: Run current-deployment performance audit only - if: ${{ inputs.performance_audit && inputs.performance_audit_only && env.SMOKE_TEST_TOKEN != '' }} + if: ${{ inputs.performance_audit && inputs.performance_audit_only && env.SMOKE_TEST_TOKEN != '' && steps.smoke_token.outputs.skip != 'true' }} run: node node_modules/@playwright/test/cli.js test --config=tests/smoke/playwright.config.ts admin-runtime-performance.spec.ts - name: Upload bounded performance audit - if: ${{ always() && inputs.performance_audit }} + if: ${{ always() && inputs.performance_audit && steps.smoke_token.outputs.skip != 'true' }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: admin-runtime-performance-${{ github.run_id }} diff --git a/.github/workflows/devcontainer-cache-experiments.yml b/.github/workflows/devcontainer-cache-experiments.yml index dfa876af94..7d869fdd43 100644 --- a/.github/workflows/devcontainer-cache-experiments.yml +++ b/.github/workflows/devcontainer-cache-experiments.yml @@ -89,7 +89,7 @@ jobs: - name: Plain Docker push/pull against registry.cloudflare.com run: | - set -euxo pipefail + set -euo pipefail REF="registry.cloudflare.com/${CLOUDFLARE_ACCOUNT_ID}/${IMAGE_NAME}:docker-${GITHUB_RUN_ID}" docker tag "$IMAGE_NAME:${GITHUB_RUN_ID}" "$REF" docker push "$REF" @@ -147,7 +147,7 @@ jobs: - name: Test R2 tarball upload/download run: | - set -euxo pipefail + set -euo pipefail KEY="docker-save/sam-r2-cache-exp-${GITHUB_RUN_ID}.tar" pnpm --filter @simple-agent-manager/api exec wrangler r2 object put "$BUCKET/$KEY" --file /tmp/sam-cache-exp-image.tar pnpm --filter @simple-agent-manager/api exec wrangler r2 object get "$BUCKET/$KEY" --file /tmp/sam-cache-exp-image-downloaded.tar @@ -226,7 +226,7 @@ jobs: - name: Build SAM devcontainer image run: | - set -euxo pipefail + set -euo pipefail LOCAL_REF="${IMAGE_NAME}:local-${GITHUB_RUN_ID}" devcontainer build --workspace-folder . --image-name "$LOCAL_REF" IMAGE_ID="$(docker image inspect "$LOCAL_REF" --format '{{.Id}}')" @@ -269,8 +269,8 @@ jobs: const raw = fs.readFileSync('registry-credentials.raw', 'utf8'); const start = raw.lastIndexOf('{'); if (start < 0) { - console.error(raw); - throw new Error('No JSON object found in Wrangler credentials output'); + // Never print the raw output: it can hold the minted registry password. + throw new Error('No JSON object found in Wrangler credentials output (' + raw.length + ' bytes withheld)'); } fs.writeFileSync('registry-credentials.json', raw.slice(start)); " diff --git a/.github/workflows/e2e-smoke.yml b/.github/workflows/e2e-smoke.yml index 5399fbcb52..29bad7fb0e 100644 --- a/.github/workflows/e2e-smoke.yml +++ b/.github/workflows/e2e-smoke.yml @@ -10,6 +10,7 @@ on: - 'packages/task-runner/**' - 'packages/scheduler-core/**' - 'packages/agent-email/**' + - 'packages/cron/**' - 'packages/operations/**' - 'packages/ai-proxy/**' - 'scripts/e2e/**' diff --git a/.gitignore b/.gitignore index 5604864c71..532d586ebf 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,8 @@ pnpm-debug.log* # committed. Ignore ALL of .codex/ and track ONLY the config we author by hand. .codex/* !.codex/config.toml +# Repository hook scripts named by config.toml (see scripts/quality/README.md, "Codex hooks"). +!.codex/hooks/ # Playwright audit screenshots write under apps/web cwd, not the repo root **/.codex/tmp/ # Throwaway Playwright specs, e.g. blog UI captures (apps/www/src/content/CLAUDE.md) diff --git a/.sonarcloud.properties b/.sonarcloud.properties index c203ce82e0..b395b4b468 100644 --- a/.sonarcloud.properties +++ b/.sonarcloud.properties @@ -5,4 +5,4 @@ # test-only CPD policy in sonar-project.properties; CI and issue analysis continue # to execute them. Production allocation code remains included in CPD analysis. # 0188 retains two explicit, audited production-row corrections; do not refactor applied migration SQL for duplication metrics. -sonar.cpd.exclusions=apps/api/tests/workers/node-lifecycle-do.test.ts,apps/api/tests/unit/durable-objects/task-runner-provider-tiers.test.ts,apps/api/tests/unit/routes/workspace-restart-deletion-race-real-sql.test.ts,apps/api/tests/workers/instant-runtime-recovery-persistence.test.ts,apps/api/tests/unit/services/nodes-delete.test.ts,apps/api/tests/unit/routes/mcp-dispatch-resource-requirements.test.ts,apps/api/tests/unit/routes/task-submit-capacity-pools.test.ts,apps/api/tests/unit/services/trigger-submit-capacity-pools.test.ts,apps/api/tests/unit/durable-objects/sam-session-dispatch-authority.test.ts,apps/api/tests/unit/routes/project-capacity-pools.test.ts,apps/api/tests/unit/routes/capacity-pools-defaults.test.ts,apps/api/tests/unit/routes/task-run-inherited-resource-layers.test.ts,apps/api/tests/unit/services/default-capacity-pools.test.ts,apps/api/tests/unit/services/offboarding-trigger-execution-principal.test.ts,apps/api/tests/unit/services/workspace-placement.test.ts,apps/api/tests/workers/workspace-resource-capacity-races.test.ts,apps/api/tests/unit/services/node-pool-legacy-boundary.test.ts,packages/providers/tests/unit/provider-native-vm-contract.test.ts,apps/web/tests/playwright/resource-form-browser-proof.spec.ts,apps/web/tests/playwright/resource-requirements-ui-audit.spec.ts,apps/web/tests/playwright/session-expiry-audit.spec.ts,apps/api/tests/helpers/incompatible-agent-capacity-fixture.ts,apps/api/src/db/migrations/0188_expiry_review_window_backfill.sql +sonar.cpd.exclusions=apps/api/tests/workers/node-lifecycle-do.test.ts,apps/api/tests/unit/durable-objects/task-runner-provider-tiers.test.ts,apps/api/tests/unit/routes/workspace-restart-deletion-race-real-sql.test.ts,apps/api/tests/workers/instant-runtime-recovery-persistence.test.ts,apps/api/tests/unit/services/nodes-delete.test.ts,apps/api/tests/unit/routes/mcp-dispatch-resource-requirements.test.ts,apps/api/tests/unit/routes/task-submit-capacity-pools.test.ts,apps/api/tests/unit/services/trigger-submit-capacity-pools.test.ts,apps/api/tests/unit/durable-objects/sam-session-dispatch-authority.test.ts,apps/api/tests/unit/routes/project-capacity-pools.test.ts,apps/api/tests/unit/routes/capacity-pools-defaults.test.ts,apps/api/tests/unit/routes/task-run-inherited-resource-layers.test.ts,apps/api/tests/unit/services/default-capacity-pools.test.ts,apps/api/tests/unit/services/offboarding-trigger-execution-principal.test.ts,apps/api/tests/unit/services/workspace-placement.test.ts,apps/api/tests/workers/workspace-resource-capacity-races.test.ts,apps/api/tests/unit/services/node-pool-legacy-boundary.test.ts,packages/providers/tests/unit/provider-native-vm-contract.test.ts,apps/web/tests/playwright/resource-form-browser-proof.spec.ts,apps/web/tests/playwright/resource-requirements-ui-audit.spec.ts,apps/web/tests/playwright/session-expiry-audit.spec.ts,apps/api/tests/helpers/incompatible-agent-capacity-fixture.ts,apps/api/tests/unit/durable-objects/task-runner-transcript-only-wake.test.ts,apps/api/src/db/migrations/0188_expiry_review_window_backfill.sql,packages/cron/tests/unit/cron-utils.test.ts diff --git a/AGENTS.md b/AGENTS.md index 9157c76e20..709a7f0005 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -143,9 +143,10 @@ Per-project data (chat sessions, messages, activity events, and canonical `proje Codex does not load `.claude/rules/` by itself. Two steps before you edit: -1. Open the `AGENTS.md` nearest the files you will change and read the rules its - "Rules for this directory" section lists. `.claude/rules/00-rule-routing.md` indexes - every path-scoped rule. +1. Path-scoped rules: in a SAM session the hook `.codex/hooks/rule-context.mjs` adds the + rules for the files a command or patch touches. Elsewhere, or if none arrive, open the + `AGENTS.md` nearest the files you will change and read the rules its "Rules for this + directory" section lists. `.claude/rules/00-rule-routing.md` indexes every one. 2. The rules below apply to all work. Claude Code has them in context at launch. Read the ones that bear on your task. diff --git a/CLAUDE.md b/CLAUDE.md index 4fa014f755..b037bc0b81 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,6 +52,7 @@ packages/ ├── repo-hosting/ # GitHub App and OAuth, GitLab, repository browsing ├── terminal/ # Shared terminal component ├── cloud-init/ # Cloud-init template generator +├── cron/ # Cron parsing for triggers ├── acp-client/ # Shared ACP React components (MessageBubble, MessageActions, AudioPlayer) ├── eslint-plugin-sam/ # Unpublished repository-specific ESLint boundary rules ├── ui/ # Design system tokens and shared UI components @@ -78,7 +79,7 @@ ratchet. Scanner and quality-policy commands are documented in `scripts/quality/ ## Build Order -Build packages in dependency order: `shared` -> `providers` / `worker-core` / `scheduler-core` -> the worker module packages (`project-data`, `operations`, `app-deployment`, `ai-proxy`, `agent-email`, `repo-hosting`) -> `cloud-init` -> `api` / `web` +Build packages in dependency order: `shared` -> `providers` / `worker-core` / `scheduler-core` / `cron` -> the worker module packages (`project-data`, `operations`, `app-deployment`, `ai-proxy`, `agent-email`, `repo-hosting`) -> `cloud-init` -> `api` / `web` ```bash pnpm exec turbo run build --filter=@simple-agent-manager/api^... # every package the API worker needs, in order diff --git a/apps/api/.env.example b/apps/api/.env.example index a1328fad9a..7ff6e1a060 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -560,6 +560,9 @@ DEBUG_AGENT_MODEL_OUTPUT_TOKENS=4096 # VULTR_IP_POLL_INTERVAL_MS=3000 # Infomaniak OpenStack provider (optional defaults) +# New Infomaniak VMs boot from a Cinder volume sized by the admin setting +# infomaniak.bootVolumeGb (default 80 GB), not the flavor's 20 GB local disk. +# INFOMANIAK_VOLUME_TYPE applies to separately managed data volumes only. INFOMANIAK_AUTH_URL=https://api.pub1.infomaniak.cloud/identity/v3 INFOMANIAK_REGION=dc4-a INFOMANIAK_ENDPOINT_INTERFACE=public @@ -1208,8 +1211,8 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000 # ANALYTICS_DEFAULT_PERIOD_DAYS=30 # Default DAU query period # ANALYTICS_DATASET=sa379a6_analytics # Analytics Engine dataset name # ANALYTICS_TOP_EVENTS_LIMIT=50 # Max rows returned by top-events query -# ANALYTICS_GEO_LIMIT=50 # Max countries in geo distribution query -# ANALYTICS_RETENTION_WEEKS=12 # Retention cohort lookback weeks +# ANALYTICS_WEBSITE_TRAFFIC_TOP_PAGES_LIMIT=20 # Max top pages per section in website traffic +# ANALYTICS_INGEST_ENABLED=true # Set to "false" to accept browser events without writing them # Analytics forwarding — external event export (Phase 4) # ANALYTICS_FORWARD_ENABLED=false # Set to "true" to enable daily batch forwarding @@ -1386,7 +1389,7 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000 # PROMPT_DELIVERY_RETRY_MAX_MS=300000 # Maximum exponential retry delay # PROMPT_DELIVERY_TTL_MS=3600000 # Maximum queued-delivery lifetime # PROMPT_DELIVERY_RECEIPT_TIMEOUT_MS=30000 # Reconcile a stale claim instead of replaying it -# PROMPT_DELIVERY_BACKGROUND_TIMEOUT_MS=5000 # Pre-send target/recovery preparation deadline and VM submit/receipt call timeout +# PROMPT_DELIVERY_BACKGROUND_TIMEOUT_MS=5000 # Pre-send target/recovery preparation, owner-approved recovery repair, and VM submit/receipt call timeout # PROMPT_DELIVERY_MIN_ALARM_DELAY_MS=1000 # Prevent immediate alarm hot loops # ACP_LONG_TURN_SUPERVISOR_ENABLED=false # Candidate selection/preemption is intentionally disabled # ACP_LONG_TURN_CHECKPOINT_MS=18000000 # Reserved five-hour checkpoint threshold @@ -1488,3 +1491,5 @@ CONNECTOR_INBOX_SESSION_LIMIT=5 # Private account SAM assistant: user opt-in remains OFF by default. # Use typed Operations admin settings (operations.samOperator*) for runtime controls. + +# Mission cancellation bounds use typed orchestrator.cancellation* admin runtime settings. diff --git a/apps/api/Dockerfile.compose-builder b/apps/api/Dockerfile.compose-builder index 5cd6bc3276..699b4aa6d9 100644 --- a/apps/api/Dockerfile.compose-builder +++ b/apps/api/Dockerfile.compose-builder @@ -2,7 +2,7 @@ # Keep the reviewed digest: root DinD with overlayfs, not rootless or vfs. # Rootful DinD is required by the measured recipe. The isolated, one-job # Cloudflare microVM is the trust boundary; no broad credential is delivered. -FROM docker.io/library/docker@sha256:08a98015fce594af7c382883bea080ea206de74402a95da9dc52b6428c8cd121 +FROM docker.io/library/docker@sha256:7bf70dcb85c822e3fa6f2d332143e474b99147b9d7b39102b0cfe8b04a7dd61b COPY container-artifacts/sam-builder-linux-amd64 /usr/local/bin/sam-builder COPY container-entrypoints/compose-builder.sh /usr/local/bin/compose-builder RUN chmod 0755 /usr/local/bin/sam-builder /usr/local/bin/compose-builder diff --git a/apps/api/package.json b/apps/api/package.json index b0920e451c..57e6cdd800 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -36,6 +36,7 @@ "@simple-agent-manager/ai-proxy": "workspace:*", "@simple-agent-manager/app-deployment": "workspace:*", "@simple-agent-manager/cloud-init": "workspace:*", + "@simple-agent-manager/cron": "workspace:*", "@simple-agent-manager/operations": "workspace:*", "@simple-agent-manager/project-data": "workspace:*", "@simple-agent-manager/providers": "workspace:*", diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index 586c38d5e4..76f6e80c37 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -11,6 +11,7 @@ import { betterAuthSecretOptions } from './lib/better-auth-secrets'; import { CLIENT_IP_HEADER } from './lib/client-ip'; import { createModuleLogger } from './lib/logger'; import { readResponseJson } from './lib/runtime-validation'; +import { accountLinkingPlugin, validateLinkUserInfo } from './services/account-linking'; import { clampSessionRefresh, HARD_EXPIRES_AT_FIELD } from './services/agent-sign-in/session-cap'; import { bootstrapOwnerEmail, @@ -151,6 +152,8 @@ export function selectPrimaryGitHubEmail( * Create BetterAuth instance with Cloudflare D1 + KV configuration. */ export interface CreateAuthOptions { + /** Preserve refresh failure category across BetterAuth's generic token-error wrapper. */ + onGitHubRefreshError?: (error: unknown) => void; /** * Keeps work BetterAuth runs in the background alive after the response (the request's * `executionCtx.waitUntil`). Email sign-in codes are sent this way, so the response time does @@ -180,7 +183,10 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { clientId: githubOAuth.clientId, clientSecret: githubOAuth.clientSecret, scope: ['read:user', 'user:email', 'read:org'], - refreshAccessToken: (refreshToken: string) => refreshGitHubAccessToken(env, refreshToken), + refreshAccessToken: async (refreshToken: string) => { + try { return await refreshGitHubAccessToken(env, refreshToken); } + catch (error) { options.onGitHubRefreshError?.(error); throw error; } + }, // Ensure existing linked users are refreshed with latest provider profile data on sign-in. overrideUserInfoOnSignIn: true, // Custom getUserInfo to ensure we persist the account's primary email when available. @@ -249,12 +255,7 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { return null; } - // A linked account keeps its own verified SAM email (see the helper). - const identity = await keepLinkedAccountEmail(env, 'github', user.id, { - email, - emailVerified, - }); - + const identity = await keepLinkedAccountEmail(env, 'github', user.id, { email, emailVerified }); return { user: { email: identity.email ?? email, @@ -284,14 +285,12 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { }; } - // Not registered when the admin's GitLab host may not be called (gitlab-login-provider.ts). - const gitlabProvider = gitlabOAuth ? gitLabLoginProvider(env, gitlabOAuth) : null; - if (gitlabOAuth && gitlabProvider) { - // better-auth links a sign-in to the existing user with that email when the provider is - // trusted OR the provider says the email is verified, so an untrusted host must lose both - // (its `getUserInfo` reports emails unverified and host-scopes its account ids). - if (gitlabOAuth.identityTrusted) trustedProviders.push('gitlab'); - socialProviders.gitlab = gitlabProvider; + if (gitlabOAuth) { + const provider = gitLabLoginProvider(env, gitlabOAuth); + if (provider) { + if (gitlabOAuth.identityTrusted) trustedProviders.push('gitlab'); + socialProviders.gitlab = provider; + } } return betterAuth({ @@ -340,15 +339,14 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { }, }, socialProviders, - plugins: emailSignInPlugins(env), + plugins: [...emailSignInPlugins(env), accountLinkingPlugin(env)], advanced: { - // One client-IP rule for the whole API (`lib/client-ip.ts`): only the ingress-set - // CF-Connecting-IP is trusted for BetterAuth's session IPs and rate limits. Its default, - // X-Forwarded-For, carries whatever a client prepends. + // Ingress owns this header. BetterAuth's X-Forwarded-For default is client-controlled. ipAddress: { ipAddressHeaders: [CLIENT_IP_HEADER] }, ...(options.waitUntil ? { backgroundTasks: { handler: options.waitUntil } } : {}), }, user: { + validateUserInfo: validateLinkUserInfo, additionalFields: { githubId: { type: 'string', @@ -373,7 +371,7 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { }, }, databaseHooks: { - // Owner alert when a social sign-in is linked to an admin or superadmin (best-effort). + // Notify the affected account owner when a social sign-in is linked (best-effort). account: { create: { after: (account) => { @@ -487,16 +485,9 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { accountLinking: { enabled: true, trustedProviders, - // "Connect GitHub" / "Connect GitLab" in Settings: an account that signed in by email - // links a provider through BetterAuth's own `/link-social` flow. The provider account's - // email usually differs from the SAM one (a GitHub-created account may only expose its - // noreply address). better-auth 1.7 reads this flag only on the explicit, signed-in link - // paths (`linkOAuthAccount` in `oauth2/link-account.mjs` for the redirect callback, and - // the `/link-social` idToken branch); implicit linking at sign-in still requires the - // email to match. `routes/auth.ts` limits linking to GitHub and GitLab, whose - // `getUserInfo` keeps the linked account's own email (`keepLinkedAccountEmail`), and - // refuses every BetterAuth write for agent sign-in sessions. allowDifferentEmails: true, + // The plugin permits removing the last provider only with usable verified email login. + allowUnlinkingAll: true, }, }, }); diff --git a/apps/api/src/db/migrations/0248_asks_system_errors.sql b/apps/api/src/db/migrations/0248_asks_system_errors.sql new file mode 100644 index 0000000000..1e82bb30f6 --- /dev/null +++ b/apps/api/src/db/migrations/0248_asks_system_errors.sql @@ -0,0 +1,38 @@ +-- Inbox slice E (idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9): SAM files system error items as `asks` rows +-- of kind 'error', one per failing thing (dedupe_key error::), updated in place on a +-- repeat failure (`packages/operations/src/inbox-error-core.ts`). +-- +-- failure_count times the thing failed while its item was open. Default 1: the filing +-- failure. Read only for kind 'error'; every other row keeps the default and +-- the API reports null for it. +-- +-- Failed tasks are found by a cron step that scans recently failed tasks +-- (`apps/api/src/services/inbox/system-errors.ts`, `automation-errors.ts`); the partial index keeps that scan to the +-- failed rows of the lookback window. +-- +-- Two partial indexes on asks keep that step off the rest of the table: error items by task +-- (has this failure been filed?) and error items still holding a dedupe key (which ones can +-- still be closed by recovery). +-- +-- Failing automations are found the same way, from recently failed runs; an automation item +-- closes when its newest finished run (one seek on (trigger_id, sequence_number) over finished +-- runs) is no longer a failure. +-- +-- A failed chat wake is an open error item (dedupe key error:wake:) instead of a +-- ProjectData wake_failed attention marker; the chat list reads it by its exact dedupe key on the +-- existing unique (project_id, dedupe_key) index (`packages/worker-core/src/question-asks.ts`). +-- +-- Additive only: one column with a default and five partial indexes. Existing rows are unaffected. +ALTER TABLE asks ADD COLUMN failure_count INTEGER NOT NULL DEFAULT 1; + +CREATE INDEX idx_tasks_failed_updated ON tasks (updated_at) WHERE status = 'failed'; + +CREATE INDEX idx_asks_error_task ON asks (source_task_id, created_at) WHERE kind = 'error'; + +CREATE INDEX idx_asks_error_key ON asks (dedupe_key) WHERE kind = 'error' AND dedupe_key IS NOT NULL; + +CREATE INDEX idx_trigger_executions_failed_completed ON trigger_executions (completed_at) + WHERE status = 'failed'; + +CREATE INDEX idx_trigger_executions_trigger_finished ON trigger_executions (trigger_id, sequence_number) + WHERE status IN ('completed', 'failed'); diff --git a/apps/api/src/db/migrations/0253_agent_run_usage.sql b/apps/api/src/db/migrations/0253_agent_run_usage.sql new file mode 100644 index 0000000000..9b54266db6 --- /dev/null +++ b/apps/api/src/db/migrations/0253_agent_run_usage.sql @@ -0,0 +1,46 @@ +-- Insights slice U (idea 01M7HTS38KX2G78JD0ESAGMKKH): measured token usage per run. +-- One row per (project, chat session, source, usage epoch, model, credential key). +-- Writers: recordHarnessRunUsage() (VM agent usage callback, apps/api/src/services/agent-run-usage.ts) +-- and recordProxyRunUsage() (AI proxy, same file). +-- Reads: packages/operations/src/insights-run-usage.ts (run receipt, Accounts). +-- +-- Counters are cumulative. Harness rows hold the VM agent's running totals for one usage epoch and +-- are upserted with a per-column MAX, so a repeated or reordered report never counts twice. AI proxy +-- rows are additive, one increment per measured upstream response. reasoning_tokens is NULL when +-- the harness does not report reasoning separately (it is then part of output_tokens). +-- +-- credential_key is credentialLimitReferenceKey() of the server-attributed credential reference +-- (the key credential_limit_windows uses); '' means the run had no attributed credential. It is an +-- identifier, never a secret. +-- +-- No foreign keys: rows are telemetry about a run and must never block or cascade a project, +-- workspace or session delete. Times are epoch milliseconds. +-- +-- Additive only (rule 31): a new table and its indexes. +CREATE TABLE IF NOT EXISTS agent_run_usage ( + id INTEGER PRIMARY KEY, + project_id TEXT NOT NULL, + chat_session_id TEXT NOT NULL, + workspace_id TEXT, + agent_session_id TEXT, + source TEXT NOT NULL CHECK (source IN ('harness', 'ai_proxy')), + usage_epoch TEXT NOT NULL, + model TEXT NOT NULL DEFAULT '', + credential_key TEXT NOT NULL DEFAULT '', + credential_source TEXT, + agent_type TEXT, + input_tokens INTEGER NOT NULL DEFAULT 0, + output_tokens INTEGER NOT NULL DEFAULT 0, + cache_read_tokens INTEGER NOT NULL DEFAULT 0, + cache_write_tokens INTEGER NOT NULL DEFAULT 0, + reasoning_tokens INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); + +-- The upsert key, and the per-run read (project + chat session). +CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_run_usage_key + ON agent_run_usage (project_id, chat_session_id, source, usage_epoch, model, credential_key); +-- Usage per account over a window, always within one project (Accounts): seek the window. +CREATE INDEX IF NOT EXISTS idx_agent_run_usage_project_updated + ON agent_run_usage (project_id, updated_at); diff --git a/apps/api/src/db/migrations/0254_ask_activity_human_tasks.sql b/apps/api/src/db/migrations/0254_ask_activity_human_tasks.sql new file mode 100644 index 0000000000..3af69b6c4d --- /dev/null +++ b/apps/api/src/db/migrations/0254_ask_activity_human_tasks.sql @@ -0,0 +1,28 @@ +-- Inbox slice H1 (ideas 01M7G03ZCQ6TM6CMEYDRKQ8ST9, 01M6MFVAJF20DZK8NJ97VAXC7A): human tasks. +-- +-- A human task is one `asks` row of kind 'task'. Two additions: +-- asks.steps_checked_json JSON array of the indexes of steps the person ticked. steps_json +-- keeps the agent's step texts unchanged; NULL means none ticked. +-- ask_activity one lifecycle row per change (created, step ticked, claimed, +-- reassigned, done, reopened, archived, cancelled, commented). It +-- holds no discussion text: discussion is the anchored comment core +-- in the project's Durable Object (anchor kind inbox_item). +-- +-- Additive only: one nullable column and one new table whose parent is asks (ON DELETE +-- CASCADE: activity has no meaning without its ask, and asks itself cascades from projects). +-- Existing rows keep NULL and read as "no step ticked"; nothing else changes for them. +ALTER TABLE asks ADD COLUMN steps_checked_json TEXT; + +CREATE TABLE ask_activity ( + id TEXT PRIMARY KEY, + ask_id TEXT NOT NULL REFERENCES asks(id) ON DELETE CASCADE, + project_id TEXT NOT NULL, + actor_kind TEXT NOT NULL, + actor_id TEXT, + kind TEXT NOT NULL, + detail_json TEXT, + created_at INTEGER NOT NULL +); + +-- A task's activity in order (the task view and inbox_read get). +CREATE INDEX idx_ask_activity_ask_created ON ask_activity (ask_id, created_at, id); diff --git a/apps/api/src/db/migrations/0255_project_briefs.sql b/apps/api/src/db/migrations/0255_project_briefs.sql new file mode 100644 index 0000000000..42693562b9 --- /dev/null +++ b/apps/api/src/db/migrations/0255_project_briefs.sql @@ -0,0 +1,42 @@ +-- Inbox slice I (idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9, section 4.3): the generated brief on the +-- Project Overview. One row per project, the only home of the brief (no copies). +-- Writer: refreshProjectBriefIfDue() (apps/api/src/services/project-brief/refresh.ts). +-- Reader: readProjectBrief() (packages/operations/src/project-brief-read.ts), one statement in +-- the Overview's aggregated read. +-- It lives in D1 beside the Overview's other reads because it is read per project with them, and +-- every fact it is built from is in D1. +-- +-- brief_json is NULL when the project was quiet at the last check (nothing to say). The ref_* +-- columns list the asks, running chats, automations and accounts the brief names, so the read can +-- drop a claim that is no longer true (or no longer visible to every member). Times are epoch milliseconds. generation_day/count is the +-- per-UTC-day generation budget (a daily cap by design: it resets on a new day, not on success). +-- +-- Additive only (rule 31): a new table and two indexes. Deleting a project deletes its brief (it +-- has no meaning without the project and nothing references it). +CREATE TABLE IF NOT EXISTS project_briefs ( + project_id TEXT PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE, + brief_json TEXT, + ref_asks_json TEXT NOT NULL DEFAULT '[]', + ref_chats_json TEXT NOT NULL DEFAULT '[]', + ref_automations_json TEXT NOT NULL DEFAULT '[]', + ref_accounts_json TEXT NOT NULL DEFAULT '[]', + fingerprint TEXT, + generated_at INTEGER, + checked_at INTEGER, + stale INTEGER NOT NULL DEFAULT 0, + pending_since INTEGER, + generation_day TEXT, + generation_count INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + last_error_at INTEGER, + updated_at INTEGER NOT NULL +); + +-- The brief's facts read each trigger's newest finished runs and a project's failed tasks' chats +-- on every check (readBriefFacts, packages/operations/src/project-brief-facts.ts). Without these, +-- the first walks and sorts every execution of every trigger (90 days of history), and the second +-- walks the project's whole chat history. +CREATE INDEX IF NOT EXISTS idx_trigger_executions_trigger_sequence + ON trigger_executions(trigger_id, sequence_number, created_at); +CREATE INDEX IF NOT EXISTS idx_session_summaries_task + ON session_summaries(task_id); diff --git a/apps/api/src/db/migrations/0256_installation_cost_daily.sql b/apps/api/src/db/migrations/0256_installation_cost_daily.sql new file mode 100644 index 0000000000..10a84cdaeb --- /dev/null +++ b/apps/api/src/db/migrations/0256_installation_cost_daily.sql @@ -0,0 +1,36 @@ +-- Insights slice CF (idea 01M7HTS38KX2G78JD0ESAGMKKH): a daily, usage-derived estimate of what +-- the Cloudflare account costs, for the Cloudflare card on Admin › Health & cost. +-- Writer: runCloudflareCostSnapshot() (apps/api/src/services/cloudflare-cost-snapshot.ts), run +-- by the daily 03:00 UTC cron and by the superadmin "Refresh now" button. +-- Reader: readCloudflareCost() (packages/operations/src/insights-installation-cloudflare.ts). +-- +-- One row per UTC day per product line (a billed metric key such as `workersRequests` or +-- `doDurationGbSeconds`, see CLOUDFLARE_COST_METRIC_KEYS in packages/shared). The snapshot job +-- re-fetches its whole window on every run and upserts, so a day is idempotent. Costs are +-- estimates at Cloudflare's list prices, in USD. fetched_at is epoch milliseconds. +-- +-- Additive only (rule 31): two new tables. Numbered 0256 to stay clear of 0253-0255 (open PRs +-- #2811, #2818, #2821). +CREATE TABLE IF NOT EXISTS installation_cost_daily ( + source TEXT NOT NULL, + day TEXT NOT NULL, + product_line TEXT NOT NULL, + usage_quantity REAL NOT NULL, + usage_unit TEXT NOT NULL, + estimated_cost_usd REAL NOT NULL, + fetched_at INTEGER NOT NULL, + PRIMARY KEY (source, day, product_line) +); + +-- The latest snapshot attempt per source, so the card can say why it has no data +-- (not configured, token lacks permission, last fetch failed) without reading logs. +CREATE TABLE IF NOT EXISTS installation_cost_sync ( + source TEXT PRIMARY KEY, + status TEXT NOT NULL, + last_attempt_at INTEGER NOT NULL, + last_success_at INTEGER, + error_message TEXT, + first_day TEXT, + last_day TEXT, + rows_written INTEGER NOT NULL DEFAULT 0 +); diff --git a/apps/api/src/db/migrations/0257_provider_limit_recovery_scan_index.sql b/apps/api/src/db/migrations/0257_provider_limit_recovery_scan_index.sql new file mode 100644 index 0000000000..3208c4d067 --- /dev/null +++ b/apps/api/src/db/migrations/0257_provider_limit_recovery_scan_index.sql @@ -0,0 +1,6 @@ +-- Preserve the active-only index for its existing callers. The stuck-task sweep +-- also consumes owner-approved sleeping recovery intents in the same keyset order. +CREATE INDEX IF NOT EXISTS idx_tasks_recovery_scan_updated_id + ON tasks(updated_at, id) + WHERE status IN ('queued', 'delegated', 'in_progress') + OR (status='sleeping' AND admission_state='provider_limit_recovery_pending'); diff --git a/apps/api/src/db/migrations/0258_pull_request_review_requests.sql b/apps/api/src/db/migrations/0258_pull_request_review_requests.sql new file mode 100644 index 0000000000..53c56fda80 --- /dev/null +++ b/apps/api/src/db/migrations/0258_pull_request_review_requests.sql @@ -0,0 +1,47 @@ +-- Insights slice P (idea 01M7HTS38KX2G78JD0ESAGMKKH): "review pickup time" on Insights · People, +-- the time from a review being requested to the first review, per project (`projectPeople`, +-- packages/operations/src/insights-people.ts). Nothing stored it: `pull_requests` is one row per +-- pull request and `pull_request_heads` one row per head commit, and a pull request can ask several +-- reviewers, more than once. +-- +-- Additive only (rule 31): one new table. It is a CASCADE child of projects (its rows mean nothing +-- without the project, like pull_request_heads) and nothing references it, so it is not a parent. +-- +-- pull_request_review_requests: one row per request cycle, written by the GitHub webhook ingest +-- (`apps/api/src/services/github-pull-request-reviews.ts`): +-- - `pull_request.review_requested` opens a cycle for that reviewer unless one is already open. +-- `requested_at` is GitHub's `pull_request.updated_at` from that delivery, so a redelivery +-- cannot move it. +-- - `pull_request.review_request_removed` stamps `removed_at` on the open cycle (not a pickup). +-- - `pull_request_review.submitted` stamps `first_review_at` on the reviewer's open user cycle and +-- on the pull request's open team cycles. +-- `reviewer_kind` is 'user' (a GitHub login) or 'team' (a team slug); `reviewer_key` is lowercase. +-- The key exists only to match a review to its request. Insights reports per project, never per +-- reviewer. +-- `pull_request.closed` closes the pull request's open cycles as removed: a request the PR closed +-- on was never picked up, and must not wait forever. +-- Existing rows: none. Requests made before this deploy were never recorded, and Insights says so +-- ("not recorded") rather than estimating them. +-- Growth: one small row per review request, deleted with the project, like pull_request_heads. +-- +-- Also one index on asks, for "answered by the first person asked": the read seeks a project's +-- answered and done asks by when they were resolved, so asks closed before the range are never +-- read (idx_asks_project_status orders by created_at and cannot bound resolved_at). +CREATE TABLE IF NOT EXISTS pull_request_review_requests ( + project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + repository TEXT NOT NULL, + pr_number INTEGER NOT NULL, + reviewer_kind TEXT NOT NULL CHECK (reviewer_kind IN ('user', 'team')), + reviewer_key TEXT NOT NULL, + requested_at TEXT NOT NULL, + first_review_at TEXT, + removed_at TEXT, + PRIMARY KEY (project_id, repository, pr_number, reviewer_kind, reviewer_key, requested_at) +); + +-- Insights reads a project's cycles requested in a range, newest first. +CREATE INDEX IF NOT EXISTS idx_pull_request_review_requests_project_requested + ON pull_request_review_requests (project_id, requested_at); + +CREATE INDEX IF NOT EXISTS idx_asks_project_status_resolved + ON asks (project_id, status, resolved_at); diff --git a/apps/api/src/db/migrations/0259_speech_synthesis_rate_limits.sql b/apps/api/src/db/migrations/0259_speech_synthesis_rate_limits.sql new file mode 100644 index 0000000000..019c53d451 --- /dev/null +++ b/apps/api/src/db/migrations/0259_speech_synthesis_rate_limits.sql @@ -0,0 +1,10 @@ +-- Independent atomic counters for paid speech endpoints. Keep the existing AI +-- counters and their CHECK constraint intact; no table rebuild or data movement. +-- One row per user is reused at each clock-hour rollover. +CREATE TABLE speech_synthesis_rate_limits ( + bucket TEXT NOT NULL CHECK (bucket = 'speech-synthesis'), + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + window_start INTEGER NOT NULL CHECK (window_start >= 0), + count INTEGER NOT NULL CHECK (count >= 0), + PRIMARY KEY (bucket, user_id) +); diff --git a/apps/api/src/db/migrations/0260_lifecycle_phase_timings_pair_indexes.sql b/apps/api/src/db/migrations/0260_lifecycle_phase_timings_pair_indexes.sql new file mode 100644 index 0000000000..06013922df --- /dev/null +++ b/apps/api/src/db/migrations/0260_lifecycle_phase_timings_pair_indexes.sql @@ -0,0 +1,21 @@ +-- Insights slice I (`project_insights` method `phases`, idea 01M7HTS38KX2G78JD0ESAGMKKH): phase +-- durations are sampled per (operation, phase), from successful rows only, newest first +-- (`phaseDurationStats` in packages/operations/src/insights-phase-timings.ts): +-- WHERE project_id = ? AND skill_id = ? AND operation = ? AND phase = ? AND outcome = 'success' +-- AND created_at >= ? ORDER BY created_at DESC LIMIT ? +-- With every filter in the key, each pair's sample is one index range that stops at its LIMIT, so +-- a read examines about (pairs x sample) entries however much history is retained. The +-- (operation, phase) pairs themselves are listed by seeking this index pair by pair. +-- +-- These replace the 0250 (project_id, skill|profile, phase, created_at) indexes, whose only reader +-- was that query: they lacked operation and outcome, so a rare operation or a run of failed +-- phases made the read walk a phase's whole history. Indexes only; no table is changed (rule 31). +-- Numbered 0260 to stay clear of open PRs using 0257 and 0259. +CREATE INDEX IF NOT EXISTS idx_lifecycle_phase_timings_skill_pair + ON lifecycle_phase_timings (project_id, skill_id, operation, phase, outcome, created_at) + WHERE skill_id IS NOT NULL; +CREATE INDEX IF NOT EXISTS idx_lifecycle_phase_timings_profile_pair + ON lifecycle_phase_timings (project_id, agent_profile_id, operation, phase, outcome, created_at) + WHERE agent_profile_id IS NOT NULL; +DROP INDEX IF EXISTS idx_lifecycle_phase_timings_skill_phase; +DROP INDEX IF EXISTS idx_lifecycle_phase_timings_profile_phase; diff --git a/apps/api/src/db/migrations/0261_agent_run_usage_admission_hits.sql b/apps/api/src/db/migrations/0261_agent_run_usage_admission_hits.sql new file mode 100644 index 0000000000..107ad5368f --- /dev/null +++ b/apps/api/src/db/migrations/0261_agent_run_usage_admission_hits.sql @@ -0,0 +1,13 @@ +-- A rejected usage report leaves one sticky disclosure row per project/chat. +-- No token counters, credential material, history deletion or retention change. +-- Like agent_run_usage, telemetry has no resource foreign keys. +-- Writer: recordHarnessRunUsage, marker BEFORE usage in the same atomic D1 batch. +-- Readers: shared run receipt and Insights Accounts operations. +CREATE TABLE IF NOT EXISTS agent_run_usage_admission_hits ( + project_id TEXT NOT NULL, + chat_session_id TEXT NOT NULL, + last_rejected_at INTEGER NOT NULL, + PRIMARY KEY (project_id, chat_session_id) +) WITHOUT ROWID; +CREATE INDEX IF NOT EXISTS idx_agent_run_usage_hits_project_rejected + ON agent_run_usage_admission_hits (project_id, last_rejected_at); diff --git a/apps/api/src/durable-objects/credential-setup-session/cleanup-recovery.ts b/apps/api/src/durable-objects/credential-setup-session/cleanup-recovery.ts new file mode 100644 index 0000000000..fd315fe8a9 --- /dev/null +++ b/apps/api/src/durable-objects/credential-setup-session/cleanup-recovery.ts @@ -0,0 +1,239 @@ +/** Pending SDK work has a watchdog, not a failed-network-attempt budget. */ +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { + DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS, + getSetupSessionCleanupRecoveryConfig, + getSetupSessionCleanupRecoveryStepTimeoutMs, +} from '../../services/credential-setup-config'; +import { persistError } from '../../services/observability-errors'; +import { getSandboxConfig, withTimeout } from '../../services/sandbox'; +import type { SetupSessionRow } from './schema'; + +/** Snapshot prevents later setting changes from reviving a quarantined episode. */ +export function cleanupAttemptLimit(row: SetupSessionRow): number { + return row.cleanup_recovery_max_attempts ?? DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS; +} + +export function readCleanupRow(sql: SqlStorage, sessionId: string): SetupSessionRow | undefined { + return sql + .exec('SELECT * FROM setup_session WHERE id = ?', sessionId) + .toArray()[0]; +} + +/** Resolve once per episode; already-started legacy recovery keeps its old policy. */ +export async function snapshotCleanupPolicy( + env: Env, + sql: SqlStorage, + row: SetupSessionRow +): Promise { + if (row.cleanup_recovery_max_attempts != null) return row; + const policy = await getSetupSessionCleanupRecoveryConfig(env); + sql.exec( + `UPDATE setup_session SET cleanup_recovery_max_attempts = ? WHERE id = ? AND cleanup_recovery_max_attempts IS NULL`, + (row.cleanup_attempts ?? 0) > 0 + ? DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS + : policy.maxAttempts, + row.id + ); + return readCleanupRow(sql, row.id) ?? row; +} + +function pendingDeadline(env: Env, row: SetupSessionRow): number | null { + const timeout = getSandboxConfig(env).execTimeoutMs; + const completedAt = row.completed_at; + if (typeof completedAt !== 'number') return null; + const clocks = [row.expires_at, completedAt, timeout, row.capture_poll_ms]; + if (!clocks.every((value) => typeof value === 'number' && Number.isFinite(value) && value > 0)) + return null; + const deadline = Math.max(row.expires_at, completedAt + timeout + row.capture_poll_ms); + return Number.isFinite(new Date(deadline).getTime()) ? deadline : null; +} + +/** Join the existing owner briefly; a stalled inline D1/pool RPC must not pin an alarm. + * The original flight keeps ownership until settlement, with the same immutable + * uncertainty watchdog as SDK work rather than a hot polling/retry loop. + */ +export async function joinCleanupFlight( + ctx: DurableObjectState, + env: Env, + sql: SqlStorage, + row: SetupSessionRow, + flight: Promise +): Promise { + if ((row.cleanup_attempts ?? 0) > cleanupAttemptLimit(row)) return; + const deadline = pendingDeadline(env, row); + if (deadline === null || Date.now() >= deadline) { + await quarantineCleanup(ctx, env, sql, row, 'inline_cleanup_watchdog'); + return; + } + const timeout = Math.min( + getSandboxConfig(env).execTimeoutMs, + await getSetupSessionCleanupRecoveryStepTimeoutMs(env), + Math.max(1, deadline - Date.now()) + ); + try { + await withTimeout(flight, timeout, 'Setup inline cleanup join timed out'); + return; + } catch { + // A failure or timeout retains the original owner and durable obligation. + } + const current = readCleanupRow(sql, row.id); + if ( + current?.cleanup_pending !== 1 || + (current.cleanup_attempts ?? 0) > cleanupAttemptLimit(current) + ) + return; + try { + await ctx.storage.setAlarm(deadline); + } catch { + // alarm()'s final ensureCleanupWake refuses to acknowledge without a wake. + log.error('credential_setup.cleanup_alarm_failed', { sessionId: row.id }); + } + // Attach after scheduling: settlement during setAlarm must win with an earlier wake. + const settled = async () => { + const latest = readCleanupRow(sql, row.id); + if ( + latest?.cleanup_pending === 1 && + (latest.cleanup_attempts ?? 0) <= cleanupAttemptLimit(latest) + ) { + try { + await ctx.storage.setAlarm(Date.now() + latest.capture_poll_ms); + } catch { + log.error('credential_setup.cleanup_alarm_failed', { sessionId: row.id }); + } + } + }; + ctx.waitUntil(flight.then(settled, settled)); +} + +async function deleteRecoveryAlarm(ctx: DurableObjectState): Promise { + try { + await ctx.storage.deleteAlarm(); + } catch { + /* Already disarmed. */ + } +} + +export async function quarantineCleanup( + ctx: DurableObjectState, + env: Env, + sql: SqlStorage, + row: SetupSessionRow, + reason = 'attempts_exhausted' +): Promise { + if ((row.cleanup_attempts ?? 0) > cleanupAttemptLimit(row)) { + await deleteRecoveryAlarm(ctx); + return; + } + const attempts = cleanupAttemptLimit(row) + 1; + sql.exec(`UPDATE setup_session SET cleanup_attempts = ? WHERE id = ?`, attempts, row.id); + const context = { + status: row.status, + cleanupFromStatus: row.cleanup_from_status, + attempts: row.cleanup_attempts, + reason, + }; + log.error('credential_setup.cleanup_abandoned', { sessionId: row.id, ...context }); + await deleteRecoveryAlarm(ctx); + if (env.OBSERVABILITY_DATABASE) { + ctx.waitUntil( + persistError( + env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: 'credential_setup.cleanup_abandoned', + sessionId: row.id, + context, + }, + env + ).catch(() => log.error('credential_setup.cleanup_alert_failed', { sessionId: row.id })) + ); + } +} + +/** Read after awaits; setAlarm is issued before yielding so a later settlement wins. */ +export async function deferPendingCleanup( + ctx: DurableObjectState, + env: Env, + sql: SqlStorage, + row: SetupSessionRow +): Promise { + row = readCleanupRow(sql, row.id) ?? row; + if (row.cleanup_pending !== 1) return true; + if ((row.cleanup_attempts ?? 0) > cleanupAttemptLimit(row)) { + await deleteRecoveryAlarm(ctx); + return true; + } + if ((row.cleanup_sandbox_io_pending ?? 0) <= 0 && row.cleanup_scrub_state !== 1) return false; + if (row.cleanup_from_status === 'provisioning') + log.info('credential_setup.scrub_skipped', { + sessionId: row.id, + reason: 'provisioning_still_in_flight', + }); + const deadline = pendingDeadline(env, row); + if (deadline === null || Date.now() >= deadline) { + await quarantineCleanup(ctx, env, sql, row, 'sdk_uncertainty_watchdog'); + return true; + } + try { + await ctx.storage.setAlarm(deadline); + } catch { + log.error('credential_setup.cleanup_alarm_failed', { sessionId: row.id }); + } + return true; +} + +/** Count work only after terminal D1 repair and pending-flight deferral. */ +export async function claimCleanupAttempt( + ctx: DurableObjectState, + env: Env, + sql: SqlStorage, + row: SetupSessionRow +): Promise { + row = readCleanupRow(sql, row.id) ?? row; + // Quarantine is final even if an original SDK promise succeeds afterwards. + if ((row.cleanup_attempts ?? 0) > cleanupAttemptLimit(row)) return false; + if (row.cleanup_settlement_credit === 1) { + sql.exec('UPDATE setup_session SET cleanup_settlement_credit = 0 WHERE id = ?', row.id); + return true; + } + const attempts = (row.cleanup_attempts ?? 0) + 1; + if (attempts > cleanupAttemptLimit(row)) { + await quarantineCleanup(ctx, env, sql, row); + return false; + } + sql.exec(`UPDATE setup_session SET cleanup_attempts = ? WHERE id = ?`, attempts, row.id); + log.warn('credential_setup.cleanup_resumed', { + sessionId: row.id, + status: row.status, + cleanupFromStatus: row.cleanup_from_status, + attempt: attempts, + }); + return true; +} + +/** An alarm must not acknowledge unresolved cleanup without a durable next wake. + * Cloudflare retries uncaught alarm failures (including isolate termination). + * https://developers.cloudflare.com/durable-objects/api/alarms/ + */ +export async function ensureCleanupWake( + ctx: DurableObjectState, + sql: SqlStorage, + row: SetupSessionRow +): Promise { + const needsWake = (current: SetupSessionRow | undefined) => + current?.cleanup_pending === 1 && + (current.cleanup_attempts ?? 0) <= cleanupAttemptLimit(current); + if (!needsWake(readCleanupRow(sql, row.id))) return; + let alarm: number | null = null; + try { + alarm = await ctx.storage.getAlarm(); + } catch { + // An unknown wake cannot acknowledge the alarm delivery as complete. + } + if (alarm !== null && Number.isFinite(alarm)) return; + if (needsWake(readCleanupRow(sql, row.id))) + throw new Error('Credential setup cleanup has no durable recovery alarm'); +} diff --git a/apps/api/src/durable-objects/credential-setup-session/cleanup.ts b/apps/api/src/durable-objects/credential-setup-session/cleanup.ts new file mode 100644 index 0000000000..7a82605a90 --- /dev/null +++ b/apps/api/src/durable-objects/credential-setup-session/cleanup.ts @@ -0,0 +1,292 @@ +/** + * Sandbox and pool cleanup for a setup session whose terminal status teardown has + * already claimed (CredentialSetupSession.teardown in ./index.ts). + * + * Every step is best-effort (logged, never thrown) and safe to repeat, because the + * recovery alarm re-runs interrupted or failed cleanup up to its recovery cap. + */ +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { + getSetupSessionCleanupRecoveryStepTimeoutMs, + type SetupSessionStatus, +} from '../../services/credential-setup-config'; +import { + destroySandboxInstance, + getSandboxConfig, + getSandboxInstance, + shellQuote, + withTimeout, +} from '../../services/sandbox'; +import { releaseSetupSlot } from '../../services/setup-session-pool'; +import { readCleanupRow } from './cleanup-recovery'; +import { updateSetupSessionD1Status } from './d1-status'; +import { beginSandboxFlight } from './lifecycle-io'; +import type { SetupSessionRow } from './schema'; + +export interface SetupSessionCleanupContext { + env: Env; + sql: SqlStorage; + deferPending(row: SetupSessionRow): Promise; + claimAttempt(row: SetupSessionRow): Promise; + /** Schedule recovery after a failed attempt, even if the old alarm already fired. */ + rearmAlarm(): Promise; + /** Disarm the recovery alarm once the cleanup has finished. */ + deleteAlarm(): Promise; + waitUntil(work: Promise): void; +} + +/** + * The initial scrub is skipped when teardown started from `provisioning`: an exec + * could start a container that never started and wait out the SDK's start retries + * before the destroy. + * A resumed cleanup scrubs unless scrubbing or destruction durably succeeded: + * the Sandbox container outlives the dead DO isolate, so the captured credential + * may still be on it, and the destroy after the scrub is best-effort. (The integration branch also skipped it on resume, + * because on celld the exec starts a fresh container; that is self-host only.) + */ +function skipsScrub(row: SetupSessionRow, resumed: boolean): boolean { + return ( + row.cleanup_scrub_state === 2 || + row.cleanup_sandbox_destroyed === 1 || + (row.cleanup_from_status === 'provisioning' && !resumed) + ); +} + +export async function runSetupSessionCleanup( + context: SetupSessionCleanupContext, + row: SetupSessionRow, + resumed: boolean +): Promise { + const { env, sql } = context; + const interactiveTimeoutMs = getSandboxConfig(env).execTimeoutMs; + // Recovery has its snapshotted attempt cap and four bounded remote steps (20s + // per attempt by default), plus the settings read. Inline keeps its existing budget. + const execTimeoutMs = resumed + ? Math.min(interactiveTimeoutMs, await getSetupSessionCleanupRecoveryStepTimeoutMs(env)) + : interactiveTimeoutMs; + // Repair first, including while SDK uncertainty prevents destructive cleanup. + const d1Repaired = await repairTerminalD1(env, row, resumed, execTimeoutMs); + row = readCleanupRow(sql, row.id) ?? row; + if (await context.deferPending(row)) return; + const metadataOnly = row.cleanup_sandbox_destroyed === 1; + if (resumed && !metadataOnly && !(await context.claimAttempt(row))) return; + if (skipsScrub(row, resumed)) { + log.info('credential_setup.scrub_skipped', { sessionId: row.id, reason: scrubSkipReason(row) }); + } else { + await scrubSetupDirectory(context, row, execTimeoutMs); + } + if (await context.deferPending(row)) return; + const destroyed = await destroySetupSandbox(context, row, execTimeoutMs); + if (await context.deferPending(row)) return; + const released = await releaseSetupPool(env, row, resumed, execTimeoutMs); + // Failed/unfinished steps preserve both the obligation and a future recovery alarm. + if (!destroyed || !released || !d1Repaired) { + // A successful final D1/pool reconciliation completes before the budget gate. + // Failed metadata-only passes still spend the bounded recovery budget. + if (resumed && metadataOnly && !(await context.claimAttempt(row))) return; + await context.rearmAlarm(); + return; + } + sql.exec(`UPDATE setup_session SET cleanup_pending = 0 WHERE id = ?`, row.id); + await context.deleteAlarm(); + log.info('credential_setup.torn_down', { + sessionId: row.id, + finalStatus: row.status, + errorCode: row.error_code, + cleanupFromStatus: row.cleanup_from_status, + resumed, + }); +} + +function scrubSkipReason(row: SetupSessionRow): string { + if (row.cleanup_scrub_state === 2) return 'scrub_already_succeeded'; + if (row.cleanup_sandbox_destroyed === 1) return 'sandbox_already_destroyed'; + return 'never_left_provisioning'; +} + +async function repairTerminalD1( + env: Env, + row: SetupSessionRow, + resumed: boolean, + execTimeoutMs: number +): Promise { + try { + const repair = updateSetupSessionD1Status(env, row.id, row.status as SetupSessionStatus, { + errorCode: row.error_code ?? undefined, + errorMessage: row.error_message ?? undefined, + completed: true, + onlyIfActive: true, + }); + return resumed + ? await withTimeout(repair, execTimeoutMs, 'Setup D1 repair timed out') + : await repair; + } catch { + log.warn('credential_setup.d1_repair_timeout', { sessionId: row.id }); + return false; + } +} + +async function scrubSetupDirectory( + context: SetupSessionCleanupContext, + row: SetupSessionRow, + execTimeoutMs: number +): Promise { + const { env, sql } = context; + let scrubAllowed = true; + try { + // Variable (not inline): avoids the SQL-injection AST check's false positive. + const scrubCmd = `rm -rf ${shellQuote(row.codex_home)}`; + // Bounded here too: the exec's own timeout covers the command, not the container + // start the SDK may perform before it. + await withTimeout( + (async () => { + const sandbox = await getSandboxInstance(env, row.id); + // A timed-out acquisition can resolve after destruction. Do not begin + // a new exec then: it would restart the sandbox we just removed. + if (!scrubAllowed) return; + const settled = beginSandboxFlight(sql, row.id, () => context.rearmAlarm()); + sql.exec(`UPDATE setup_session SET cleanup_scrub_state = 1 WHERE id = ?`, row.id); + // Mark uncertainty BEFORE invocation, including a synchronous SDK throw. + const execution = Promise.resolve().then(() => + sandbox.exec(scrubCmd, { timeout: execTimeoutMs }) + ); + const observed = execution.then( + async (result) => { + const succeeded = result.success === true && result.exitCode === 0; + await recordScrubSettled(context, row.id, succeeded, !scrubAllowed, () => + settled(!scrubAllowed) + ); + if (!succeeded) + log.warn('credential_setup.scrub_failed', { + sessionId: row.id, + reason: 'command_unsuccessful', + }); + return result; + }, + async (error: unknown) => { + await recordScrubSettled(context, row.id, false, !scrubAllowed, () => + settled(!scrubAllowed) + ); + throw error; + } + ); + context.waitUntil( + observed.then( + () => undefined, + () => undefined + ) + ); + return observed; + })(), + execTimeoutMs, + `Setup dir scrub timed out after ${execTimeoutMs}ms` + ); + } catch (err) { + log.warn('credential_setup.scrub_failed', { + sessionId: row.id, + error: err instanceof Error ? err.message : String(err), + }); + } finally { + scrubAllowed = false; + } +} + +async function destroySetupSandbox( + context: SetupSessionCleanupContext, + row: SetupSessionRow, + execTimeoutMs: number +): Promise { + if (row.cleanup_sandbox_destroyed === 1) return true; + const { env, sql } = context; + let awaitingDestruction = true; + try { + const settled = beginSandboxFlight(sql, row.id, () => context.rearmAlarm()); + const destruction = Promise.resolve() + .then(() => destroySandboxInstance(env, row.id, { sandboxId: row.id }, { timeoutMs: null })) + .then( + async () => { + // Commit before settlement/rearm so recovery never recreates this sandbox. + // If proof cannot persist, retain uncertainty instead of permitting exec. + try { + sql.exec( + `UPDATE setup_session SET cleanup_sandbox_destroyed = 1, + cleanup_settlement_credit = CASE WHEN ? = 1 THEN 1 ELSE cleanup_settlement_credit END + WHERE id = ?`, + // The one destruction proof also permits final D1/pool bookkeeping. + 1, + row.id + ); + } catch { + log.error('credential_setup.destroy_proof_failed', { sessionId: row.id }); + throw new Error('Setup destruction proof could not be persisted'); + } + await settled(!awaitingDestruction); + }, + async (error: unknown) => { + await settled(!awaitingDestruction); + throw error; + } + ); + context.waitUntil( + destruction.then( + () => undefined, + () => undefined + ) + ); + await withTimeout( + destruction, + execTimeoutMs, + `Setup sandbox destroy timed out after ${execTimeoutMs}ms` + ); + return true; + } catch { + log.warn('credential_setup.sandbox_destroy_failed', { sessionId: row.id }); + return false; + } finally { + awaitingDestruction = false; + } +} + +async function releaseSetupPool( + env: Env, + row: SetupSessionRow, + resumed: boolean, + execTimeoutMs: number +): Promise { + try { + const release = releaseSetupSlot(env, row.pool_lease_id); + if (resumed) await withTimeout(release, execTimeoutMs, 'Setup pool release timed out'); + else await release; + return true; + } catch (err) { + log.warn('credential_setup.pool_release_failed', { + sessionId: row.id, + error: err instanceof Error ? err.message : String(err), + }); + return false; + } +} + +/** Only a successful command proves scrubbing; settlement alone clears uncertainty. */ +async function recordScrubSettled( + context: SetupSessionCleanupContext, + sessionId: string, + succeeded: boolean, + afterTimeout: boolean, + settleFlight: () => Promise +): Promise { + try { + context.sql.exec( + `UPDATE setup_session SET cleanup_scrub_state = ?, + cleanup_settlement_credit = CASE WHEN ? = 1 THEN 1 ELSE cleanup_settlement_credit END + WHERE id = ? AND cleanup_scrub_state = 1`, + succeeded ? 2 : null, + succeeded && afterTimeout ? 1 : 0, + sessionId + ); + await settleFlight(); + } catch { + log.error('credential_setup.scrub_settlement_failed', { sessionId }); + } +} diff --git a/apps/api/src/durable-objects/credential-setup-session/d1-status.ts b/apps/api/src/durable-objects/credential-setup-session/d1-status.ts new file mode 100644 index 0000000000..7c4e6ca842 --- /dev/null +++ b/apps/api/src/durable-objects/credential-setup-session/d1-status.ts @@ -0,0 +1,71 @@ +/** + * The D1 mirror of a setup session's status (`agent_credential_setup_sessions`). + * The create route's one-active lookup and the status route read it, so every + * lifecycle transition the DO makes is written here too. Failures are logged and + * swallowed: the DO's own SQLite stays authoritative, and teardown repairs D1. + */ +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { + ACTIVE_SETUP_STATUSES, + type SetupSessionStatus, +} from '../../services/credential-setup-config'; + +export interface SetupSessionD1Extra { + errorCode?: string; + errorMessage?: string; + completed?: boolean; + started?: boolean; + /** Only write while the D1 row is still active: a repair, never an overwrite. */ + onlyIfActive?: boolean; +} + +export async function updateSetupSessionD1Status( + env: Env, + id: string, + status: SetupSessionStatus, + extra?: SetupSessionD1Extra +): Promise { + const now = new Date().toISOString(); + const set = ['status = ?', 'updated_at = ?']; + const binds: unknown[] = [status, now]; + if (extra?.started) { + set.push('started_at = COALESCE(started_at, ?)'); + binds.push(now); + } + if (extra?.completed) { + set.push('completed_at = ?'); + binds.push(now); + } + if (extra?.errorCode !== undefined) { + set.push('error_code = ?'); + binds.push(extra.errorCode); + } + if (extra?.errorMessage !== undefined) { + set.push('error_message = ?'); + binds.push(extra.errorMessage); + } + binds.push(id); + let where = 'id = ?'; + // A late active-phase write must never resurrect a cancellation/terminal row. + const activeStatuses: readonly SetupSessionStatus[] = ACTIVE_SETUP_STATUSES; + if (extra?.onlyIfActive || activeStatuses.includes(status)) { + where += ` AND status IN (${ACTIVE_SETUP_STATUSES.map(() => '?').join(', ')})`; + binds.push(...ACTIVE_SETUP_STATUSES); + } + try { + await env.DATABASE.prepare( + `UPDATE agent_credential_setup_sessions SET ${set.join(', ')} WHERE ${where}` + ) + .bind(...binds) + .run(); + return true; + } catch (err) { + log.warn('credential_setup.d1_update_failed', { + sessionId: id, + status, + error: err instanceof Error ? err.message : String(err), + }); + return false; + } +} diff --git a/apps/api/src/durable-objects/credential-setup-session/index.ts b/apps/api/src/durable-objects/credential-setup-session/index.ts index 2dc3a15b67..c3a71a3263 100644 --- a/apps/api/src/durable-objects/credential-setup-session/index.ts +++ b/apps/api/src/durable-objects/credential-setup-session/index.ts @@ -19,58 +19,67 @@ * SECURITY: the captured credential is read server-side and never transits this * DO's SQLite, the D1 row, logs, or the browser. Only non-secret lifecycle * metadata is persisted. Every terminal state runs teardown so a vanished browser - * leaves no orphan (rules 43/47). + * leaves no orphan (rules 43/47): + * 1. Arm a recovery alarm, then synchronously claim the terminal status in DO + * SQLite and mark cleanup pending with its pre-claim status. + * 2. Mark the D1 row terminal BEFORE any sandbox I/O, so an isolate that dies + * mid-teardown never leaves D1 active for the create route's one-active lookup. + * 3. `./cleanup.ts`: scrub the setup dir (skipped when teardown starts from + * `provisioning`), destroy the sandbox, release the pool slot, repair D1, then + * clear the marker and the alarm. The alarm joins a cleanup already running in + * this isolate instead of starting a second one. + * If the isolate dies during step 3, `alarm()` finds a terminal row with + * `cleanup_pending = 1` and resumes the cleanup with at most + * its snapshotted recovery work cap, plus at most two success continuations. SDK + * flights wait for settlement or an immutable watchdog without spending attempts. * - * Teardown order (`teardown()` then `runCleanup()`): - * 1. Synchronously claim the terminal status in DO SQLite, mark cleanup pending - * (with the pre-claim status), and arm a recovery alarm. - * 2. Mark the D1 row terminal BEFORE any sandbox I/O, so a process that dies - * mid-teardown never leaves D1 active (the create route's one-active lookup - * would otherwise keep returning the dead session until the cron sweep). - * 3. Scrub the setup dir (skipped when teardown starts from `provisioning`: no - * driver ran, and an exec would restart a never-started container), destroy - * the sandbox, release the pool slot, re-check D1, then clear the pending - * marker and the alarm. - * If the isolate dies during step 3, `alarm()` sees a terminal row with - * `cleanup_pending = 1` and resumes the cleanup, at most - * MAX_CLEANUP_RECOVERY_ATTEMPTS times. - * - * Storage: embedded SQLite (wrangler `new_sqlite_classes`). DDL is inlined in - * the constructor (CREATE TABLE IF NOT EXISTS plus guarded additive - * ALTER TABLE ADD COLUMN for existing objects) — no separate DO migration file. + * Storage: embedded SQLite (wrangler `new_sqlite_classes`). The constructor runs + * the additive DDL in `./schema.ts`, which the DO migration safety check scans. */ import type { AgentType, CredentialKind } from '@simple-agent-manager/shared'; import { DurableObject } from 'cloudflare:workers'; import { drizzle } from 'drizzle-orm/d1'; -import * as v from 'valibot'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; -import { settleSharedFlight } from '../../lib/shared-flight'; import { OWN_AGENT_ACCOUNT_PROJECT_CAPABILITY, requireProjectCapability, } from '../../middleware/project-auth'; import { saveAgentCredentialForUser } from '../../services/agent-credential-save'; import { - ACTIVE_SETUP_STATUSES, getClaudeOauthTokenMaxLength, getClaudeVerificationCodeMaxLength, isTerminalSetupStatus, + SANDBOX_PERMANENT_STARTUP_MESSAGE, type SetupSessionStatus, } from '../../services/credential-setup-config'; import { deferAlarmWhenDisabled } from '../../services/operational-kill-switch'; -import { - destroySandboxInstance, - getSandboxConfig, - getSandboxInstance, - shellQuote, - withTimeout, -} from '../../services/sandbox'; -import { PERMANENT_STARTUP_MESSAGE } from '../../services/sandbox-startup-errors'; -import { releaseSetupSlot } from '../../services/setup-session-pool'; +import { getSandboxInstance, shellQuote } from '../../services/sandbox'; import { CredentialValidator } from '../../services/validation'; -import { type DeviceAuthState, DeviceAuthStateSchema, driverFailure } from './driver-state'; +import { runSetupSessionCleanup } from './cleanup'; +import { + claimCleanupAttempt, + cleanupAttemptLimit, + deferPendingCleanup, + ensureCleanupWake, + joinCleanupFlight, + snapshotCleanupPolicy, +} from './cleanup-recovery'; +import { type SetupSessionD1Extra, updateSetupSessionD1Status } from './d1-status'; +import { type DeviceAuthState, driverFailure } from './driver-state'; +import { + armCleanupAlarmBestEffort, + beginSandboxFlight, + readDeviceAuthState, + runProvisioningSandboxSteps, + trackSandboxFlight, +} from './lifecycle-io'; +import { + type DeviceAuthDetailsRow, + ensureSetupSessionSchema, + type SetupSessionRow, +} from './schema'; export interface CreateSetupSessionParams { id: string; @@ -97,65 +106,6 @@ export interface SetupSessionStateResult { userCode: string | null; } -// `type` (not `interface`) so it carries an implicit index signature and -// satisfies the `Record` constraint on sql.exec(). -type SetupSessionRow = { - id: string; - user_id: string; - project_id: string | null; - scope: string; - agent_type: string; - credential_kind: string; - provider: string; - agent_name: string; - status: string; - pool_lease_id: string | null; - codex_home: string; - expires_at: number; - capture_poll_ms: number; - error_code: string | null; - error_message: string | null; - completed_at: number | null; - /** 1 while teardown's sandbox cleanup has not finished; NULL/0 otherwise. */ - cleanup_pending: number | null; - /** Status the session had when teardown claimed it (decides whether to scrub). */ - cleanup_from_status: string | null; - /** Number of alarm-driven recoveries of an interrupted cleanup. */ - cleanup_attempts: number | null; -}; - -/** - * Additive columns for teardown recovery. Objects created before these existed - * get them through a guarded ALTER TABLE ADD COLUMN (no table recreation). - */ -const CLEANUP_COLUMNS: ReadonlyArray = [ - ['cleanup_pending', 'ALTER TABLE setup_session ADD COLUMN cleanup_pending INTEGER'], - ['cleanup_from_status', 'ALTER TABLE setup_session ADD COLUMN cleanup_from_status TEXT'], - ['cleanup_attempts', 'ALTER TABLE setup_session ADD COLUMN cleanup_attempts INTEGER'], -]; - -/** - * Alarm-driven re-runs of an interrupted cleanup before giving up. Every cleanup - * step is best-effort and catches its own errors, so a run only fails to finish - * when the isolate dies; three consecutive deaths means retrying is not helping. - */ -const MAX_CLEANUP_RECOVERY_ATTEMPTS = 3; - -/** - * How long the recovery alarm waits on an inline cleanup before resuming it itself: the scrub - * and the destroy are each bounded by the exec timeout, plus a margin for the slot release and - * the D1 repair. Internal safety margin, not an operator setting. - */ -const CLEANUP_JOIN_MARGIN_MS = 30_000; -function cleanupJoinBoundMs(env: Env): number { - return 2 * getSandboxConfig(env).execTimeoutMs + CLEANUP_JOIN_MARGIN_MS; -} - -type DeviceAuthDetailsRow = { - verification_url: string; - user_code: string | null; -}; - /** Relative paths of captured credential files inside the per-session setup home. */ const CODEX_AUTH_FILE = 'auth.json'; const CLAUDE_OAUTH_TOKEN_FILE = 'claude-oauth-token.txt'; @@ -178,53 +128,16 @@ function credentialFileName(agentType: string): string { export class CredentialSetupSession extends DurableObject { private readonly sql: SqlStorage; /** - * The cleanup this isolate is running, if any. A recovery alarm that fires - * while the inline cleanup is still awaiting sandbox I/O joins it instead of - * starting a second one. It is in memory on purpose: after an isolate death it - * is gone, and the alarm then runs the cleanup itself. + * The cleanup this isolate is running, if any. In memory on purpose: after an + * isolate death it is gone, and the recovery alarm then runs the cleanup itself. */ - private cleanupInFlight: { startedAt: number; promise: Promise } | null = null; + private cleanupInFlight: Promise | null = null; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.sql = ctx.storage.sql; ctx.blockConcurrencyWhile(async () => { - this.sql.exec( - `CREATE TABLE IF NOT EXISTS setup_session ( - id TEXT PRIMARY KEY NOT NULL, - user_id TEXT NOT NULL, - project_id TEXT, - scope TEXT NOT NULL, - agent_type TEXT NOT NULL, - credential_kind TEXT NOT NULL, - provider TEXT NOT NULL, - agent_name TEXT NOT NULL, - status TEXT NOT NULL, - pool_lease_id TEXT, - codex_home TEXT NOT NULL, - expires_at INTEGER NOT NULL, - capture_poll_ms INTEGER NOT NULL, - error_code TEXT, - error_message TEXT, - completed_at INTEGER - )` - ); - const existingColumns = new Set( - this.sql - .exec<{ name: string }>('PRAGMA table_info(setup_session)') - .toArray() - .map((column) => column.name) - ); - for (const [name, ddl] of CLEANUP_COLUMNS) { - if (!existingColumns.has(name)) this.sql.exec(ddl); - } - this.sql.exec( - `CREATE TABLE IF NOT EXISTS device_auth_details ( - singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1), - verification_url TEXT NOT NULL, - user_code TEXT - )` - ); + ensureSetupSessionSchema(this.sql); }); } @@ -242,8 +155,8 @@ export class CredentialSetupSession extends DurableObject { `INSERT OR REPLACE INTO setup_session ( id, user_id, project_id, scope, agent_type, credential_kind, provider, agent_name, status, pool_lease_id, codex_home, expires_at, capture_poll_ms, - error_code, error_message, completed_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?, ?, NULL, NULL, NULL)`, + error_code, error_message, completed_at, cleanup_sandbox_io_pending + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?, ?, NULL, NULL, NULL, 0)`, params.id, params.userId, params.projectId, @@ -351,14 +264,18 @@ export class CredentialSetupSession extends DurableObject { throw new Error('Invalid Claude verification code'); } - const sandbox = await getSandboxInstance(this.env, row.id); - await sandbox.writeFile(`${row.codex_home}/${CLAUDE_VERIFICATION_CODE_FILE}`, normalizedCode); - const current = this.readRow(); - if (!current || current.status !== 'waiting_for_user') { + await this.withSandboxFlight(row, async () => { + const sandbox = await getSandboxInstance(this.env, row.id); + if (this.readRow()?.status !== 'waiting_for_user') + throw new Error('Claude Code setup is no longer waiting for a verification code'); + await sandbox.writeFile(`${row.codex_home}/${CLAUDE_VERIFICATION_CODE_FILE}`, normalizedCode); + }); + if (this.readRow()?.status !== 'waiting_for_user') throw new Error('Claude Code setup is no longer waiting for a verification code'); - } this.setStatus(row.id, 'exchanging'); await this.updateD1Status(row.id, 'exchanging'); + if (this.readRow()?.status !== 'exchanging') + return this.getState() ?? this.terminalState(row, 'cancelled'); await this.ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); return this.getState() ?? this.terminalState(row, 'exchanging'); } @@ -369,13 +286,22 @@ export class CredentialSetupSession extends DurableObject { * or reaches a terminal teardown, so a session cannot get stuck armed. */ async alarm(): Promise { + try { + await this.alarmTick(); + } finally { + const row = this.readRow(); + if (row) await ensureCleanupWake(this.ctx, this.sql, row); + } + } + + private async alarmTick(): Promise { if (await deferAlarmWhenDisabled(this.env, this.ctx.storage, 'CredentialSetupSession')) return; const row = this.readRow(); if (!row) return; // torn down / never created — nothing to do if (isTerminalSetupStatus(row.status)) { - // A terminal row only needs work when its teardown cleanup never finished - // (the isolate died mid-teardown). Otherwise terminal is a fixed point. + // A terminal row only needs work when its teardown cleanup never finished (the + // isolate died mid-teardown). Otherwise terminal is a fixed point. if (row.cleanup_pending === 1) await this.resumeCleanup(row); return; } @@ -405,6 +331,7 @@ export class CredentialSetupSession extends DurableObject { } // waiting_for_user | exchanging | capturing — observe driver failure and capture output. const driverState = await this.readDeviceAuthState(row); + if (isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled')) return; if (driverState?.status === 'failed') { const failure = driverFailure(driverState, setupDisplayName(row.agent_type)); log.warn('credential_setup.driver_failed', { @@ -429,39 +356,33 @@ export class CredentialSetupSession extends DurableObject { } } - // --------------------------------------------------------------------------- - // State-machine steps - // --------------------------------------------------------------------------- - private async provision(row: SetupSessionRow): Promise { const displayName = setupDisplayName(row.agent_type); + const settle = beginSandboxFlight(this.sql, row.id, () => + armCleanupAlarmBestEffort(this.ctx, row) + ); try { - const sandbox = await getSandboxInstance(this.env, row.id); - // Per-session setup home. For Codex this is CODEX_HOME; for Claude Code it - // is CLAUDE_CONFIG_DIR. mkdir first so provider CLIs can write there. - // Built in a variable (not inline in .exec) so the SQL-injection AST rule - // doesn't false-match this SHELL command — the path is already shellQuote()d. - const mkdirCmd = `mkdir -p ${shellQuote(row.codex_home)}`; - await sandbox.exec(mkdirCmd, { - timeout: getSandboxConfig(this.env).execTimeoutMs, - }); - if (row.agent_type === 'openai-codex') { - await sandbox.writeFile( - `${row.codex_home}/config.toml`, - 'cli_auth_credentials_store = "file"\n' - ); - } - const statePath = `${row.codex_home}/${DEVICE_AUTH_STATE_FILE}`; - const startCommand = this.startSetupDriverCommand(row, statePath); - await sandbox.exec(startCommand, { - timeout: getSandboxConfig(this.env).execTimeoutMs, - }); + const currentFlight = await runProvisioningSandboxSteps( + this.env, + row, + () => this.readRow()?.status === 'provisioning', + this.startSetupDriverCommand(row, `${row.codex_home}/${DEVICE_AUTH_STATE_FILE}`) + ); + await settle(); // D1 bookkeeping cannot restart sandbox work. + if (!currentFlight) return; + const current = this.readRow(); + if (!current || current.status !== 'provisioning') return; + this.setStatus(current.id, 'admitting'); + await this.updateD1Status(current.id, 'admitting', { started: true }); + if (this.readRow()?.status !== 'admitting') return; + await this.ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); } catch (err) { + await settle(); const message = err instanceof Error ? err.message : String(err); - // SandboxDO reports a container engine that can never start the sandbox (runtime not - // installed, socket proxy refusal, image gone) as the SDK's permanent startup error, so it - // arrives here in seconds instead of after the SDK's start retries (durable-objects/sandbox-do.ts). - const runtimeUnavailable = message.includes(PERMANENT_STARTUP_MESSAGE); + // The Sandbox SDK answers a container start that can never succeed (no such image, + // no matching container application, out of memory) with its permanent-startup + // error instead of retrying, so it arrives here within seconds. + const runtimeUnavailable = message.includes(SANDBOX_PERMANENT_STARTUP_MESSAGE); log.error('credential_setup.provision_failed', { sessionId: row.id, agentType: row.agent_type, @@ -472,16 +393,13 @@ export class CredentialSetupSession extends DurableObject { 'failed', runtimeUnavailable ? 'sandbox_runtime_unavailable' : 'sandbox_provision_failed', runtimeUnavailable - ? `${displayName} sign-in is unavailable on this server: the sign-in sandbox could not start` + ? `${displayName} sign-in is unavailable right now: the sign-in sandbox could not start` : `Failed to prepare ${displayName} sign-in` ); return; + } finally { + await settle(); } - const current = this.readRow(); - if (!current || current.status !== 'provisioning') return; - this.setStatus(current.id, 'admitting'); - await this.updateD1Status(current.id, 'admitting', { started: true }); - await this.ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); } private startSetupDriverCommand(row: SetupSessionRow, statePath: string): string { @@ -575,22 +493,25 @@ export class CredentialSetupSession extends DurableObject { await this.ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); } - private async readDeviceAuthState(row: SetupSessionRow): Promise { - try { - const sandbox = await getSandboxInstance(this.env, row.id); - const path = `${row.codex_home}/${DEVICE_AUTH_STATE_FILE}`; - const existence = await sandbox.exists(path); - if (!existence.exists) return null; - const file = await sandbox.readFile(path); - const parsedRaw = JSON.parse(file.content ?? '') as unknown; - const result = v.safeParse(DeviceAuthStateSchema, parsedRaw); - // A partial/mid-flush write or an unrecognized status parses invalid — - // degrade to null (caller keeps polling), matching the pre-validation - // blind-cast behavior for any state that didn't drive a status branch. - return result.success ? result.output : null; - } catch { - return null; - } + private readDeviceAuthState(row: SetupSessionRow): Promise { + return this.withSandboxFlight(row, () => + readDeviceAuthState( + this.env, + row, + () => !isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled'), + `${row.codex_home}/${DEVICE_AUTH_STATE_FILE}` + ) + ); + } + + private withSandboxFlight(row: SetupSessionRow, run: () => Promise): Promise { + return trackSandboxFlight( + this.sql, + this.ctx, + row.id, + () => armCleanupAlarmBestEffort(this.ctx, row), + run + ); } private readDeviceAuthDetails(): DeviceAuthDetailsRow | null { @@ -605,23 +526,33 @@ export class CredentialSetupSession extends DurableObject { } private async attemptCapture(row: SetupSessionRow): Promise { - const sandbox = await getSandboxInstance(this.env, row.id); - const credentialPath = `${row.codex_home}/${credentialFileName(row.agent_type)}`; + const capture = await this.withSandboxFlight(row, async () => { + if (isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled')) return null; + const sandbox = await getSandboxInstance(this.env, row.id); + if (isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled')) return null; + const credentialPath = `${row.codex_home}/${credentialFileName(row.agent_type)}`; - const existence = await sandbox.exists(credentialPath); - if (!existence.exists) { - await this.ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); + const existence = await sandbox.exists(credentialPath); + if (isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled')) return null; + return existence.exists ? { sandbox, credentialPath } : null; + }); + if (!capture) { + if (!isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled')) + await this.ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); return; } - - let current = this.readRow(); - if (!current || isTerminalSetupStatus(current.status)) return; - if (current.status !== 'capturing') { - this.setStatus(current.id, 'capturing'); - await this.updateD1Status(current.id, 'capturing'); + const currentCapture = this.readRow(); + if (!currentCapture || isTerminalSetupStatus(currentCapture.status)) return; + if (currentCapture.status !== 'capturing') { + this.setStatus(row.id, 'capturing'); + await this.updateD1Status(row.id, 'capturing'); } - - const file = await sandbox.readFile(credentialPath); + const file = await this.withSandboxFlight(row, () => + isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled') + ? Promise.resolve(null) + : capture.sandbox.readFile(capture.credentialPath) + ); + if (!file || isTerminalSetupStatus(this.readRow()?.status ?? 'cancelled')) return; let content = file.content ?? ''; if (row.agent_type === 'claude-code') content = content.trim(); @@ -642,7 +573,7 @@ export class CredentialSetupSession extends DurableObject { return; } - current = this.readRow(); + let current = this.readRow(); if (!current || isTerminalSetupStatus(current.status)) return; this.setStatus(current.id, 'saving'); await this.updateD1Status(current.id, 'saving'); @@ -686,7 +617,7 @@ export class CredentialSetupSession extends DurableObject { } // --------------------------------------------------------------------------- - // Teardown — always completes every step (best-effort), never throws. + // Teardown — establish a durable wake before committing a terminal claim. // --------------------------------------------------------------------------- private async teardown( @@ -694,15 +625,33 @@ export class CredentialSetupSession extends DurableObject { errorCode?: string, errorMessage?: string ): Promise { - // Atomically claim teardown (rule 45): if a concurrent cancel()/sweep already - // terminalized this session while this call awaits sandbox I/O, no-op — the - // read + setStatus below are synchronous (no await between), so the claim is - // atomic within this DO instance and cleanup + the final write happen once. + if (this.cleanupInFlight) { + await this.cleanupInFlight; + return this.teardown(finalStatus, errorCode, errorMessage); + } + await this.trackCleanup(this.claimAndFinishTeardown(finalStatus, errorCode, errorMessage)); + } + + private async claimAndFinishTeardown( + finalStatus: 'completed' | 'failed' | 'cancelled' | 'expired', + errorCode?: string, + errorMessage?: string + ): Promise { + const before = this.readRow(); + if (!before || isTerminalSetupStatus(before.status)) return; + // Failure leaves D1 active for the existing sweep; no terminal orphan is created. + await armCleanupAlarmBestEffort(this.ctx, before, true); + // Recheck after arming: cancellation cannot cross the saving commit point. const current = this.readRow(); - if (!current || isTerminalSetupStatus(current.status)) return; + if ( + !current || + isTerminalSetupStatus(current.status) || + (finalStatus === 'cancelled' && current.status === 'saving') + ) + return; this.setStatus(current.id, finalStatus, { errorCode, errorMessage, completed: true }); - // Same synchronous step as the claim: record that cleanup is owed, and from - // which status, so a dead isolate's cleanup can be resumed by the alarm. + // Record that cleanup is owed, and from which status (it decides whether to scrub), + // so the recovery alarm can resume a cleanup that a dead isolate never finished. this.sql.exec( `UPDATE setup_session SET cleanup_pending = 1, cleanup_from_status = ?, cleanup_attempts = 0 @@ -713,150 +662,75 @@ export class CredentialSetupSession extends DurableObject { this.sql.exec(`DELETE FROM device_auth_details WHERE singleton = 1`); const claimed = this.readRow(); if (!claimed) return; + // The registered flight also covers D1, so a firing alarm joins this run. + await this.finishTeardown(claimed, finalStatus, errorCode, errorMessage); + } - // Arm the recovery alarm before any I/O (replaces any pending poll alarm). - // runCleanup deletes it on completion. - await this.ctx.storage.setAlarm(Date.now() + claimed.capture_poll_ms); - // D1 terminal FIRST: the create route's one-active lookup reads D1, so a - // process death during sandbox I/O must not leave this row active. + private async finishTeardown( + claimed: SetupSessionRow, + finalStatus: SetupSessionStatus, + errorCode?: string, + errorMessage?: string + ): Promise { + // D1 terminal FIRST: the create route's one-active lookup reads D1, so an isolate + // death during the sandbox I/O must not leave this row active. await this.updateD1Status(claimed.id, finalStatus, { errorCode, errorMessage, completed: true, }); - await this.startCleanup(claimed); + await this.runCleanup(claimed, false); } - /** Alarm path: resume a cleanup an earlier isolate claimed but never finished. */ + /** Alarm path: resume a cleanup that an earlier isolate claimed but never finished. */ private async resumeCleanup(row: SetupSessionRow): Promise { const inline = this.cleanupInFlight; if (inline) { - // The inline cleanup in this isolate is still running: join it, under the alarm's own - // timer. On celld the request that started it can lose its client, and its sandbox calls - // and timeouts are dropped with it, so it may never settle (lib/shared-flight.ts). The - // bound is the cleanup's own worst case plus a margin, so a live cleanup always settles - // first (Cloudflare unchanged); past it, resume the cleanup here (every step is safe to - // repeat). - const joined = await settleSharedFlight( - inline.promise, - inline.startedAt + cleanupJoinBoundMs(this.env) - ); - if (!joined.abandoned) return; - if (this.cleanupInFlight === inline) this.cleanupInFlight = null; + // The recovery alarm fires one poll interval after the claim, usually while this + // isolate's own cleanup is still awaiting sandbox I/O. Join it rather than run a + // second destroy and release (rule 45), but inline D1/pool I/O can stall. + await joinCleanupFlight(this.ctx, this.env, this.sql, row, inline); + return; } - const attempts = (row.cleanup_attempts ?? 0) + 1; - if (attempts > MAX_CLEANUP_RECOVERY_ATTEMPTS) { - log.error('credential_setup.cleanup_abandoned', { - sessionId: row.id, - status: row.status, - cleanupFromStatus: row.cleanup_from_status, - attempts: row.cleanup_attempts, - }); - this.sql.exec(`UPDATE setup_session SET cleanup_pending = 0 WHERE id = ?`, row.id); + // cap + 1 is a durable quarantine marker. Keep cleanup_pending=1 as evidence + // that teardown is unresolved, but never restart work or repeat the alert. + if ((row.cleanup_attempts ?? 0) > cleanupAttemptLimit(row)) { await this.deleteAlarmBestEffort(); return; } - this.sql.exec(`UPDATE setup_session SET cleanup_attempts = ? WHERE id = ?`, attempts, row.id); - log.warn('credential_setup.cleanup_resumed', { - sessionId: row.id, - status: row.status, - cleanupFromStatus: row.cleanup_from_status, - attempt: attempts, - }); - // Re-arm before I/O so a death during this run is retried as well. - await this.ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); - await this.startCleanup(row, true); + await this.trackCleanup(this.resumeClaimedCleanup(row)); } - private startCleanup(row: SetupSessionRow, resumed = false): Promise { - const flight = { - startedAt: Date.now(), - promise: this.runCleanup(row, resumed).finally(() => { - if (this.cleanupInFlight === flight) this.cleanupInFlight = null; - }), - }; - this.cleanupInFlight = flight; - return flight.promise; + private async resumeClaimedCleanup(row: SetupSessionRow): Promise { + // Re-arm before I/O so a death during this run is retried as well. + await armCleanupAlarmBestEffort(this.ctx, row); + await this.runCleanup(row, true); } - /** - * Sandbox + pool cleanup for a row whose terminal status is already claimed. - * Every step is best-effort (logged, never thrown), and every step is safe to - * repeat, because an alarm may re-run it after an isolate death. - */ private async runCleanup(row: SetupSessionRow, resumed: boolean): Promise { - const execTimeoutMs = getSandboxConfig(this.env).execTimeoutMs; - const skipScrub = - row.cleanup_from_status === 'provisioning' - ? 'never_left_provisioning' - : // A resumed cleanup runs after the isolate (on a box, possibly the whole runtime) died: - // whether the container survived is unknown, and an exec would start a fresh, empty - // one only to scrub it (observed on celld). Destroy (step 2) still removes the - // container's filesystem if it did survive. - resumed - ? 'resumed_after_interruption' - : null; - // 1. Delete captured credential file + scrub the setup dir. Skipped when the - // session never left `provisioning`: no driver ran and no sign-in URL was - // shown, so no credential can exist, and an exec would (re)start a - // container that never started — waiting out the SDK's start retries. - // Destroy (step 2) removes the container's filesystem either way. - if (skipScrub) { - log.info('credential_setup.scrub_skipped', { sessionId: row.id, reason: skipScrub }); - } else { - try { - const sandbox = await getSandboxInstance(this.env, row.id); - // Variable (not inline) — same SQL-injection-AST-false-positive avoidance. - const scrubCmd = `rm -rf ${shellQuote(row.codex_home)}`; - // Bounded here too: the exec's own timeout covers the command, not the - // container start the SDK may perform before it. - await withTimeout( - sandbox.exec(scrubCmd, { timeout: execTimeoutMs }), - execTimeoutMs, - `Setup dir scrub timed out after ${execTimeoutMs}ms` - ); - } catch (err) { - log.warn('credential_setup.scrub_failed', { - sessionId: row.id, - error: err instanceof Error ? err.message : String(err), - }); - } - } - // 2. Destroy the sandbox container (bounded inside destroySandboxInstance). - try { - await destroySandboxInstance(this.env, row.id, { sandboxId: row.id }); - } catch (err) { - log.warn('credential_setup.sandbox_destroy_failed', { - sessionId: row.id, - error: err instanceof Error ? err.message : String(err), - }); - } - // 3. Release the concurrency slot. - try { - await releaseSetupSlot(this.env, row.pool_lease_id); - } catch (err) { - log.warn('credential_setup.pool_release_failed', { - sessionId: row.id, - error: err instanceof Error ? err.message : String(err), - }); - } - // 4. Repair D1 only if the terminal write in teardown() did not land (it - // logs and continues on failure). A no-op when D1 is already terminal. - await this.updateD1Status(row.id, row.status as SetupSessionStatus, { - errorCode: row.error_code ?? undefined, - errorMessage: row.error_message ?? undefined, - completed: true, - onlyIfActive: true, - }); - // 5. Cleanup is done: clear the marker and the recovery alarm. - this.sql.exec(`UPDATE setup_session SET cleanup_pending = 0 WHERE id = ?`, row.id); - await this.deleteAlarmBestEffort(); - log.info('credential_setup.torn_down', { - sessionId: row.id, - finalStatus: row.status, - errorCode: row.error_code, - cleanupFromStatus: row.cleanup_from_status, + if (resumed) row = await snapshotCleanupPolicy(this.env, this.sql, row); + return runSetupSessionCleanup( + { + env: this.env, + sql: this.sql, + deferPending: (current) => deferPendingCleanup(this.ctx, this.env, this.sql, current), + claimAttempt: (current) => claimCleanupAttempt(this.ctx, this.env, this.sql, current), + deleteAlarm: () => this.deleteAlarmBestEffort(), + waitUntil: (work) => this.ctx.waitUntil(work), + rearmAlarm: () => armCleanupAlarmBestEffort(this.ctx, row), + }, + row, + resumed + ); + } + + /** Record `run` as this isolate's cleanup. Call it before `run`'s caller awaits anything. */ + private trackCleanup(run: Promise): Promise { + const flight = run.finally(() => { + if (this.cleanupInFlight === flight) this.cleanupInFlight = null; }); + this.cleanupInFlight = flight; + return flight; } private async deleteAlarmBestEffort(): Promise { @@ -910,55 +784,11 @@ export class CredentialSetupSession extends DurableObject { ); } - private async updateD1Status( + private updateD1Status( id: string, status: SetupSessionStatus, - extra?: { - errorCode?: string; - errorMessage?: string; - completed?: boolean; - started?: boolean; - /** Only write while the D1 row is still active (repair, never overwrite). */ - onlyIfActive?: boolean; - } - ): Promise { - const now = new Date().toISOString(); - const set = ['status = ?', 'updated_at = ?']; - const binds: unknown[] = [status, now]; - if (extra?.started) { - set.push('started_at = COALESCE(started_at, ?)'); - binds.push(now); - } - if (extra?.completed) { - set.push('completed_at = ?'); - binds.push(now); - } - if (extra?.errorCode !== undefined) { - set.push('error_code = ?'); - binds.push(extra.errorCode); - } - if (extra?.errorMessage !== undefined) { - set.push('error_message = ?'); - binds.push(extra.errorMessage); - } - binds.push(id); - let where = 'id = ?'; - if (extra?.onlyIfActive) { - where += ` AND status IN (${ACTIVE_SETUP_STATUSES.map(() => '?').join(', ')})`; - binds.push(...ACTIVE_SETUP_STATUSES); - } - try { - await this.env.DATABASE.prepare( - `UPDATE agent_credential_setup_sessions SET ${set.join(', ')} WHERE ${where}` - ) - .bind(...binds) - .run(); - } catch (err) { - log.warn('credential_setup.d1_update_failed', { - sessionId: id, - status, - error: err instanceof Error ? err.message : String(err), - }); - } + extra?: SetupSessionD1Extra + ): Promise { + return updateSetupSessionD1Status(this.env, id, status, extra); } } diff --git a/apps/api/src/durable-objects/credential-setup-session/lifecycle-io.ts b/apps/api/src/durable-objects/credential-setup-session/lifecycle-io.ts new file mode 100644 index 0000000000..292585129a --- /dev/null +++ b/apps/api/src/durable-objects/credential-setup-session/lifecycle-io.ts @@ -0,0 +1,134 @@ +/** Shared flight settlement: elapsed time and isolate eviction never prove SDK work stopped. */ +import * as v from 'valibot'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { getSandboxConfig, getSandboxInstance, shellQuote } from '../../services/sandbox'; +import { cleanupAttemptLimit } from './cleanup-recovery'; +import { type DeviceAuthState, DeviceAuthStateSchema } from './driver-state'; +import type { SetupSessionRow } from './schema'; + +export async function rearmPendingCleanup( + sql: SqlStorage, + sessionId: string, + rearm: () => Promise +): Promise { + const current = sql + .exec('SELECT * FROM setup_session WHERE id = ?', sessionId) + .toArray()[0]; + if ( + current?.cleanup_pending === 1 && + (current.cleanup_attempts ?? 0) <= cleanupAttemptLimit(current) + ) + await rearm(); +} + +/** One counter unit belongs to one original promise chain, never to a later alarm. */ +export function beginSandboxFlight( + sql: SqlStorage, + sessionId: string, + rearm: () => Promise +): (needsRearm?: boolean) => Promise { + sql.exec( + `UPDATE setup_session SET cleanup_sandbox_io_pending = COALESCE(cleanup_sandbox_io_pending, 0) + 1 WHERE id = ?`, + sessionId + ); + let settled = false; + return async (needsRearm = true) => { + if (settled) return; + settled = true; + try { + sql.exec( + `UPDATE setup_session SET cleanup_sandbox_io_pending = MAX(0, COALESCE(cleanup_sandbox_io_pending, 0) - 1) WHERE id = ?`, + sessionId + ); + if (needsRearm) await rearmPendingCleanup(sql, sessionId, rearm); + } catch { + log.error('credential_setup.sdk_settlement_failed', { sessionId }); + } + }; +} + +export function trackSandboxFlight( + sql: SqlStorage, + ctx: DurableObjectState, + sessionId: string, + rearm: () => Promise, + run: () => Promise +): Promise { + const settled = beginSandboxFlight(sql, sessionId, rearm); + const flight = (async () => { + try { + return await run(); + } finally { + await settled(); + } + })(); + ctx.waitUntil( + flight.then( + () => undefined, + () => undefined + ) + ); + return flight; +} + +/** Reads are SDK producers too: a late readFile can restart a destroyed sandbox. */ +export async function readDeviceAuthState( + env: Env, + row: SetupSessionRow, + isActive: () => boolean, + path: string +): Promise { + try { + if (!isActive()) return null; + const sandbox = await getSandboxInstance(env, row.id); + if (!isActive()) return null; + const existence = await sandbox.exists(path); + if (!isActive() || !existence.exists) return null; + const file = await sandbox.readFile(path); + if (!isActive()) return null; + const raw = JSON.parse(file.content ?? '') as unknown; + const result = v.safeParse(DeviceAuthStateSchema, raw); + return result.success ? result.output : null; + } catch { + return null; + } +} + +/** Check authoritative cancellation after every awaited SDK call, before issuing another. */ +export async function runProvisioningSandboxSteps( + env: Env, + row: SetupSessionRow, + isCurrent: () => boolean, + startCommand: string +): Promise { + const sandbox = await getSandboxInstance(env, row.id); + if (!isCurrent()) return false; + const mkdirCmd = `mkdir -p ${shellQuote(row.codex_home)}`; + await sandbox.exec(mkdirCmd, { timeout: getSandboxConfig(env).execTimeoutMs }); + if (!isCurrent()) return false; + if (row.agent_type === 'openai-codex') { + await sandbox.writeFile( + `${row.codex_home}/config.toml`, + 'cli_auth_credentials_store = "file"\n' + ); + if (!isCurrent()) return false; + } + await sandbox.exec(startCommand, { timeout: getSandboxConfig(env).execTimeoutMs }); + return isCurrent(); +} + +/** Failure to schedule recovery must not block D1 terminalization or inline cleanup. */ +export async function armCleanupAlarmBestEffort( + ctx: DurableObjectState, + row: SetupSessionRow, + required = false +): Promise { + try { + await ctx.storage.setAlarm(Date.now() + row.capture_poll_ms); + } catch { + log.error('credential_setup.cleanup_alarm_failed', { sessionId: row.id }); + if (required) throw new Error('Credential setup cleanup alarm could not be scheduled'); + } +} diff --git a/apps/api/src/durable-objects/credential-setup-session/schema.ts b/apps/api/src/durable-objects/credential-setup-session/schema.ts new file mode 100644 index 0000000000..8d4d284908 --- /dev/null +++ b/apps/api/src/durable-objects/credential-setup-session/schema.ts @@ -0,0 +1,125 @@ +/** + * DO-SQLite schema for CredentialSetupSession: the row types and every DDL + * statement the object runs. Kept apart from the DO (which also writes D1 through + * a dynamic SET) so `pnpm quality:do-migration-safety` can scan all of it + * (scripts/quality/check-do-migration-safety.ts). + * + * Changes here must stay additive: CREATE TABLE IF NOT EXISTS, or a guarded + * ALTER TABLE ADD COLUMN for objects created before a column existed. Never + * drop or recreate a table: DO SQLite has no recovery (rule 31). + */ + +// `type` (not `interface`) so it carries an implicit index signature and +// satisfies the `Record` constraint on sql.exec(). +export type SetupSessionRow = { + id: string; + user_id: string; + project_id: string | null; + scope: string; + agent_type: string; + credential_kind: string; + provider: string; + agent_name: string; + status: string; + pool_lease_id: string | null; + codex_home: string; + expires_at: number; + capture_poll_ms: number; + error_code: string | null; + error_message: string | null; + completed_at: number | null; + /** 1 while teardown's sandbox cleanup has not finished; NULL/0 otherwise. */ + cleanup_pending: number | null; + /** Status the session had when teardown claimed it (decides whether to scrub). */ + cleanup_from_status: string | null; + /** Number of recovery work attempts; pending SDK watchdog wakes do not count. */ + cleanup_attempts: number | null; + /** Immutable per-cleanup retry policy; NULL legacy retains the original cap. */ + cleanup_recovery_max_attempts: number | null; + /** One late scrub or successful destroy may continue its existing work attempt. */ + cleanup_settlement_credit: number | null; + /** 1 only after sandbox.destroy() succeeds; recovery must not restart that sandbox. */ + cleanup_sandbox_destroyed: number | null; + /** NULL: scrub needed; 1: SDK exec may still start work; 2: scrub succeeded. */ + cleanup_scrub_state: number | null; + /** NULL legacy; positive count of original SDK flights; 0 all observed settled. */ + cleanup_sandbox_io_pending: number | null; +}; + +export type DeviceAuthDetailsRow = { + verification_url: string; + user_code: string | null; +}; + +/** + * Teardown-recovery columns, added after the table first shipped. Each carries its full + * literal statement (DDL cannot take placeholders, and a literal is what the safety check + * scans). Nullable with no default: legacy rows owe no cleanup unless marked pending, and + * NULL sandbox-destroyed means no destruction proof, so interrupted legacy cleanup + * still scrubs and destroys before releasing its obligation. + */ +const CLEANUP_COLUMNS: ReadonlyArray = [ + ['cleanup_pending', 'ALTER TABLE setup_session ADD COLUMN cleanup_pending INTEGER'], + ['cleanup_from_status', 'ALTER TABLE setup_session ADD COLUMN cleanup_from_status TEXT'], + ['cleanup_attempts', 'ALTER TABLE setup_session ADD COLUMN cleanup_attempts INTEGER'], + [ + 'cleanup_recovery_max_attempts', + 'ALTER TABLE setup_session ADD COLUMN cleanup_recovery_max_attempts INTEGER', + ], + [ + 'cleanup_settlement_credit', + 'ALTER TABLE setup_session ADD COLUMN cleanup_settlement_credit INTEGER', + ], + ['cleanup_scrub_state', 'ALTER TABLE setup_session ADD COLUMN cleanup_scrub_state INTEGER'], + [ + 'cleanup_sandbox_io_pending', + 'ALTER TABLE setup_session ADD COLUMN cleanup_sandbox_io_pending INTEGER', + ], + [ + 'cleanup_sandbox_destroyed', + 'ALTER TABLE setup_session ADD COLUMN cleanup_sandbox_destroyed INTEGER', + ], +]; + +/** + * Create the tables if absent and add any missing additive column. Runs in the DO + * constructor; idempotent. The PRAGMA is one local SQLite read per constructor run. + */ +export function ensureSetupSessionSchema(sql: SqlStorage): void { + sql.exec( + `CREATE TABLE IF NOT EXISTS setup_session ( + id TEXT PRIMARY KEY NOT NULL, + user_id TEXT NOT NULL, + project_id TEXT, + scope TEXT NOT NULL, + agent_type TEXT NOT NULL, + credential_kind TEXT NOT NULL, + provider TEXT NOT NULL, + agent_name TEXT NOT NULL, + status TEXT NOT NULL, + pool_lease_id TEXT, + codex_home TEXT NOT NULL, + expires_at INTEGER NOT NULL, + capture_poll_ms INTEGER NOT NULL, + error_code TEXT, + error_message TEXT, + completed_at INTEGER + )` + ); + sql.exec( + `CREATE TABLE IF NOT EXISTS device_auth_details ( + singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1), + verification_url TEXT NOT NULL, + user_code TEXT + )` + ); + const existingColumns = new Set( + sql + .exec<{ name: string }>('PRAGMA table_info(setup_session)') + .toArray() + .map((column) => column.name) + ); + for (const [name, ddl] of CLEANUP_COLUMNS) { + if (!existingColumns.has(name)) sql.exec(ddl); + } +} diff --git a/apps/api/src/durable-objects/interaction-store-attention.ts b/apps/api/src/durable-objects/interaction-store-attention.ts index 384fd69821..0ee65abccc 100644 --- a/apps/api/src/durable-objects/interaction-store-attention.ts +++ b/apps/api/src/durable-objects/interaction-store-attention.ts @@ -1,8 +1,10 @@ import type { ProjectData } from '@simple-agent-manager/project-data/durable-object'; -import { ACP_INTERACTION_ATTENTION_SOURCE } from '@simple-agent-manager/shared'; +import { ACP_INTERACTION_ATTENTION_SOURCE, formatInboxRef } from '@simple-agent-manager/shared'; import type { Env } from '../env'; import { canonicalJson } from '../lib/canonical-json'; +import { log, serializeError } from '../lib/logger'; +import * as notificationService from '../services/notification'; import { nowMs, parseSummary, terminalState } from './interaction-store-model'; import { readInteractionRow } from './interaction-store-read'; @@ -39,6 +41,49 @@ export async function projectInteractionAttention( nowMs(), interactionId ); + // Tell the person, once per request (slice E). This job runs only while the marker is unset. + await notifyInteractionOwner(env, row, marker.id); +} + +/** The chat's creator answers its permission requests; never throws. */ +async function notifyInteractionOwner( + env: Env, + row: { project_id: string; chat_session_id: string; interaction_id: string; kind: string }, + markerId: string +): Promise { + if (!env.NOTIFICATION) return; + try { + const { loadChatForError } = await import('../services/inbox/system-errors'); + const chat = await loadChatForError(env, row.project_id, row.chat_session_id); + if (!chat?.createdBy) return; + // Only a current member hears about the project's chats (a removed creator does not). + const member = await env.DATABASE.prepare( + `SELECT 1 AS ok FROM project_members WHERE project_id = ? AND user_id = ? AND status = 'active'` + ) + .bind(row.project_id, chat.createdBy) + .first(); + if (!member) return; + await notificationService.notifyInteractionRequested(env, chat.createdBy, { + projectId: row.project_id, + projectName: await notificationService.getProjectName(env, row.project_id), + interactionId: row.interaction_id, + interactionKind: row.kind, + sessionId: row.chat_session_id, + taskId: chat.taskId, + topic: chat.topic, + inboxRef: formatInboxRef({ + store: 'attention', + sessionId: row.chat_session_id, + markerId, + }), + }); + } catch (error) { + log.warn('interaction_store.notify_failed', { + interactionId: row.interaction_id, + projectId: row.project_id, + ...serializeError(error), + }); + } } export async function resolveInteractionAttention( @@ -54,10 +99,22 @@ export async function resolveInteractionAttention( 'system', `${ACP_INTERACTION_ATTENTION_SOURCE}:${row.state}` ); + // The person answered but the agent never confirmed it (`recordDelivery`, outcome + // `unconfirmed`): their inbox says so (slice E). Filed before the projection is marked resolved, + // so a failed write throws and this outbox job retries it, and once the projection is resolved + // it is never filed again. Loaded on use: the filing service builds a large worker graph. + if (row.state === 'delivery_unconfirmed' && row.attention_projection_state !== 'resolved') { + const { fileUndeliveredAnswerError } = await import('../services/inbox/system-errors'); + const outcome = await fileUndeliveredAnswerError(env, { + projectId: row.project_id, + sessionId: row.chat_session_id, + }); + if (outcome === 'failed') throw new Error('undelivered answer item not filed'); + } sql.exec( `UPDATE interactions SET attention_projection_state = 'resolved', updated_at = ? - WHERE interaction_id = ?`, + WHERE interaction_id = ? AND attention_projection_state IS NOT 'resolved'`, nowMs(), interactionId ); diff --git a/apps/api/src/durable-objects/notification.ts b/apps/api/src/durable-objects/notification.ts index f1f5694a42..6e012f5d3a 100644 --- a/apps/api/src/durable-objects/notification.ts +++ b/apps/api/src/durable-objects/notification.ts @@ -167,33 +167,38 @@ export class NotificationService extends DurableObject { } } - // Suppression: deduplicate needs_input notifications for the same task (prevent notification spam) + // Suppression: deduplicate needs_input notifications for the same task (prevent notification spam). + // Only within one inbox kind, so a non-blocking result never rewrites an open question's. if (request.type === 'needs_input' && request.taskId) { + const inboxKind = request.metadata?.inboxKind; const dedupWindow = parseInt(this.env.NOTIFICATION_DEDUP_WINDOW_MS || '') || DEFAULT_NOTIFICATION_DEDUP_WINDOW_MS; const cutoff = now - dedupWindow; const existing = this.sql .exec( - `SELECT id FROM notifications WHERE user_id = ? AND type = 'needs_input' AND task_id = ? AND created_at > ? AND read_at IS NULL AND dismissed_at IS NULL`, + `SELECT id FROM notifications WHERE user_id = ? AND type = 'needs_input' AND task_id = ? AND created_at > ? AND read_at IS NULL AND dismissed_at IS NULL + AND COALESCE(json_extract(metadata, '$.inboxKind'), '') = ?`, userId, request.taskId, - cutoff + cutoff, + typeof inboxKind === 'string' ? inboxKind : '' ) .toArray(); if (existing.length > 0) { // Update the existing unread needs_input notification instead of creating a new one. - // The metadata moves with the text: its attentionMarkerId and options must name the - // newest question, or answering from the notification would target the old one. + // The metadata and link move with the text: they must name the newest ask, or answering + // or opening from the notification would target the old one. const existingId = parseIdRow(existing[0], 'notification.needs_input_dedup'); this.sql.exec( `UPDATE notifications - SET body = ?, title = ?, metadata = ?, read_at = NULL, - in_app_visible = MAX(in_app_visible, ?) + SET body = ?, title = ?, metadata = ?, action_url = COALESCE(?, action_url), + read_at = NULL, in_app_visible = MAX(in_app_visible, ?) WHERE id = ?`, request.body ?? null, request.title, request.metadata ? JSON.stringify(request.metadata) : null, + request.actionUrl ?? null, inAppEnabled ? 1 : 0, existingId ); diff --git a/apps/api/src/durable-objects/project-data/ports.ts b/apps/api/src/durable-objects/project-data/ports.ts index ae89528d99..002f5518e3 100644 --- a/apps/api/src/durable-objects/project-data/ports.ts +++ b/apps/api/src/durable-objects/project-data/ports.ts @@ -4,6 +4,7 @@ export { configureProjectDataPort, configureProjectDataPorts, type CredentialsPort, + type InboxErrorsPort, type NoticesPort, type NotificationsPort, type ObservabilityPort, diff --git a/apps/api/src/durable-objects/project-orchestrator/auto-dispatch.ts b/apps/api/src/durable-objects/project-orchestrator/auto-dispatch.ts new file mode 100644 index 0000000000..cee02ace59 --- /dev/null +++ b/apps/api/src/durable-objects/project-orchestrator/auto-dispatch.ts @@ -0,0 +1,380 @@ +import type { OrchestratorConfig, VMSize } from '@simple-agent-manager/shared'; +import { drizzle } from 'drizzle-orm/d1'; + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { expectJsonRecord } from '../../lib/runtime-validation'; +import { ulid } from '../../lib/ulid'; +import { + CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS, + capacityPlacementSnapshotSqlValues, +} from '../../services/capacity-placement-snapshot'; +import { resolveTaskStartPlacementCredentialAttribution } from '../../services/placement-resolver'; +import * as projectDataService from '../../services/project-data'; +import { startTaskRunnerDO } from '../../services/task-runner-do'; +import { logDecision } from './decision-log'; + +interface DispatchableTaskRow { + id: string; + title: string; + description: string | null; + user_id: string; + project_id: string; + output_branch: string | null; + agent_profile_hint: string | null; + dispatch_depth: number; + priority: number; +} + +/** + * Find schedulable tasks and auto-dispatch them via startTaskRunnerDO. + * Respects concurrency limits from mission budget_config and per-cycle max. + */ +export async function autoDispatchSchedulableTasks( + sql: SqlStorage, + env: Env, + projectId: string, + missionId: string, + config: OrchestratorConfig, + now: number +): Promise { + // Re-read task states from D1 (fresh after recompute) + const schedulableResult = await env.DATABASE.prepare( + `SELECT id, title, description, user_id, project_id, output_branch, agent_profile_hint, dispatch_depth, priority + FROM tasks + WHERE mission_id = ? + AND scheduler_state = 'schedulable' + AND status = 'queued' + AND chat_session_id IS NULL + AND NOT EXISTS ( + SELECT 1 + FROM vm_task_admissions + WHERE vm_task_admissions.task_id = tasks.id + AND vm_task_admissions.state IN ( + 'queued', 'waiting', 'provisioning_granted', 'provisioning', 'node_ready' + ) + ) + ORDER BY priority DESC, created_at ASC + LIMIT ?` + ) + .bind(missionId, config.maxDispatchesPerCycle) + .all(); + + const schedulable = schedulableResult.results ?? []; + if (schedulable.length === 0) return; + + // Check concurrency limit: count currently active tasks in this mission + const activeCountResult = await env.DATABASE.prepare( + `SELECT COUNT(*) as cnt FROM tasks + WHERE mission_id = ? + AND ( + status IN ('in_progress', 'delegated') + OR (status = 'queued' AND chat_session_id IS NOT NULL) + OR EXISTS ( + SELECT 1 + FROM vm_task_admissions + WHERE vm_task_admissions.task_id = tasks.id + AND vm_task_admissions.state IN ( + 'queued', 'waiting', 'provisioning_granted', 'provisioning', 'node_ready' + ) + ) + )` + ) + .bind(missionId) + .first<{ cnt: number }>(); + + const activeCount = activeCountResult?.cnt ?? 0; + + // Resolve max active tasks from mission budget_config + const missionRow = await env.DATABASE.prepare('SELECT budget_config FROM missions WHERE id = ?') + .bind(missionId) + .first<{ budget_config: string | null }>(); + + let maxActive = config.maxActiveTasksPerMission; + if (missionRow?.budget_config) { + try { + const budget = expectJsonRecord( + JSON.parse(missionRow.budget_config), + 'mission.budget_config' + ); + if (typeof budget.maxActiveTasks === 'number' && budget.maxActiveTasks > 0) { + maxActive = budget.maxActiveTasks; + } + } catch { + // Invalid JSON — use default + } + } + + const slotsAvailable = Math.max(0, maxActive - activeCount); + if (slotsAvailable === 0) { + logDecision( + sql, + missionId, + null, + 'skip', + `${schedulable.length} schedulable task(s) held: concurrency limit reached (${activeCount}/${maxActive} active)`, + now + ); + return; + } + + // Fetch project info (needed for startTaskRunnerDO) + const projectRow = await env.DATABASE.prepare( + `SELECT repository, installation_id, default_branch, default_vm_size, + default_agent_type, default_workspace_profile, default_devcontainer_config_name, + task_execution_timeout_ms, node_cpu_threshold_percent, + node_memory_threshold_percent, warm_node_timeout_ms + FROM projects WHERE id = ?` + ) + .bind(projectId) + .first<{ + repository: string; + installation_id: string; + default_branch: string; + default_vm_size: string | null; + default_agent_type: string | null; + default_workspace_profile: string | null; + default_devcontainer_config_name: string | null; + task_execution_timeout_ms: number | null; + node_cpu_threshold_percent: number | null; + node_memory_threshold_percent: number | null; + warm_node_timeout_ms: number | null; + }>(); + + if (!projectRow) { + logDecision(sql, missionId, null, 'skip', 'Project not found — cannot dispatch', now); + return; + } + + const db = drizzle(env.DATABASE, { schema }); + const toDispatch = schedulable.slice(0, Math.min(slotsAvailable, config.maxDispatchesPerCycle)); + let dispatched = 0; + + for (const task of toDispatch) { + try { + // Resolve user info for git config + const userRow = await env.DATABASE.prepare( + 'SELECT name, email, github_id FROM users WHERE id = ?' + ) + .bind(task.user_id) + .first<{ name: string | null; email: string | null; github_id: string | null }>(); + + const placementResolution = await resolveTaskStartPlacementCredentialAttribution( + db, + { + entryPoint: 'orchestrator-dispatch', + taskId: task.id, + projectId, + userId: task.user_id, + project: { + id: projectId, + defaultVmSize: projectRow.default_vm_size, + defaultWorkspaceProfile: projectRow.default_workspace_profile, + defaultDevcontainerConfigName: projectRow.default_devcontainer_config_name, + defaultAgentType: projectRow.default_agent_type, + }, + profile: null, + credentialProjectPolicy: 'current-project', + taskModeDefault: 'task', + resourceRequirements: {}, + }, + { env } + ); + if ('error' in placementResolution) { + logDecision(sql, missionId, task.id, 'skip', placementResolution.error, now); + continue; + } + const { + placement, + effectiveProvider, + credentialAttributionUserId, + credentialAttributionProjectId, + credentialAttributionSource, + capacityPoolSelection, + capacityPlacementSnapshot, + } = placementResolution; + const { + vmSize: resolvedVmSize, + vmSizeSource, + vmLocation: resolvedVmLocation, + workspaceProfile: resolvedWorkspaceProfile, + devcontainerConfigName: resolvedDevcontainerConfig, + agentType: resolvedAgentType, + resolvedReservation, + } = placement; + + // Create chat session for the task + const sessionId = await projectDataService.createSession( + env, + projectId, + null, + task.title, + task.id, + task.user_id + ); + + if (task.description) { + await projectDataService.persistMessage( + env, + projectId, + sessionId, + 'user', + task.description, + null + ); + } + + if ( + !sql + .exec( + "SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status='active'", + missionId + ) + .toArray().length + ) + return; + // Transition task to queued → provisioning via status update + const dispatchTransition = await env.DATABASE.prepare( + `UPDATE tasks + SET status = 'queued', + chat_session_id = ?, + execution_step = 'node_selection', + requested_vm_size = ?, + requested_vm_size_source = ?, + resource_requirements_source = ?, + resolved_reservation_json = ?, + credential_attribution_user_id = ?, + credential_attribution_project_id = ?, + credential_attribution_source = ?, + ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS}, + updated_at = ? + WHERE id = ? AND status='queued' AND (chat_session_id IS NULL OR chat_session_id = ?) + AND EXISTS (SELECT 1 FROM missions WHERE missions.id=tasks.mission_id AND missions.status IN ('planning','active'))` + ) + .bind( + sessionId, + resolvedVmSize, + vmSizeSource, + resolvedReservation.source, + JSON.stringify(resolvedReservation), + credentialAttributionUserId, + credentialAttributionProjectId, + credentialAttributionSource, + ...capacityPlacementSnapshotSqlValues(capacityPlacementSnapshot), + new Date().toISOString(), + task.id, + sessionId + ) + .run(); + if (!dispatchTransition.meta.changes) { + throw new Error('Task was already bound to a different chat session'); + } + + // The cancellation marker can appear while the placement CAS is awaited. + if ( + !sql + .exec( + "SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status='active'", + missionId + ) + .toArray().length + ) + return; + // Start the TaskRunner DO + await startTaskRunnerDO(env, { + taskId: task.id, + projectId, + userId: task.user_id, + vmSize: resolvedVmSize, + vmLocation: resolvedVmLocation, + branch: projectRow.default_branch, + defaultBranch: projectRow.default_branch, + userName: userRow?.name ?? null, + userEmail: userRow?.email ?? null, + githubId: userRow?.github_id ?? null, + taskTitle: task.title, + taskDescription: task.description ?? null, + repository: projectRow.repository, + installationId: projectRow.installation_id, + outputBranch: task.output_branch ?? null, + projectDefaultVmSize: projectRow.default_vm_size as VMSize | null, + chatSessionId: sessionId, + agentType: resolvedAgentType, + workspaceProfile: resolvedWorkspaceProfile, + devcontainerConfigName: resolvedDevcontainerConfig, + cloudProvider: placement.provider ?? effectiveProvider, + explicitVmLocation: placement.explicitVmLocation === true, + credentialAttributionUserId, + credentialAttributionProjectId, + credentialAttributionSource, + agentProfileHint: task.agent_profile_hint ?? null, + effort: null, + projectScaling: { + taskExecutionTimeoutMs: projectRow.task_execution_timeout_ms ?? null, + nodeCpuThresholdPercent: projectRow.node_cpu_threshold_percent ?? null, + nodeMemoryThresholdPercent: projectRow.node_memory_threshold_percent ?? null, + warmNodeTimeoutMs: projectRow.warm_node_timeout_ms ?? null, + }, + resolvedReservation, + capacityPoolSelection, + vmSizeSource, + }); + + // Record in scheduling_queue + sql.exec( + `INSERT INTO scheduling_queue (id, mission_id, task_id, scheduled_at, dispatched_at, reason) + VALUES (?, ?, ?, ?, ?, ?)`, + ulid(), + missionId, + task.id, + now, + now, + 'auto-dispatch: task became schedulable' + ); + + logDecision( + sql, + missionId, + task.id, + 'dispatch', + `Auto-dispatched schedulable task (slot ${dispatched + 1}/${slotsAvailable})`, + now + ); + + dispatched++; + + log.info('orchestrator.task_dispatched', { + projectId, + missionId, + taskId: task.id, + slot: dispatched, + slotsAvailable, + }); + } catch (err) { + log.error('orchestrator.auto_dispatch_failed', { + projectId, + missionId, + taskId: task.id, + error: err instanceof Error ? err.message : String(err), + }); + logDecision( + sql, + missionId, + task.id, + 'skip', + `Auto-dispatch failed: ${err instanceof Error ? err.message : String(err)}`, + now + ); + } + } + + if (dispatched > 0) { + // Update last_dispatch_at + sql.exec( + 'UPDATE orchestrator_missions SET last_dispatch_at = ? WHERE mission_id = ?', + now, + missionId + ); + } +} diff --git a/apps/api/src/durable-objects/project-orchestrator/cancel-mission.ts b/apps/api/src/durable-objects/project-orchestrator/cancel-mission.ts new file mode 100644 index 0000000000..1692fe1c12 --- /dev/null +++ b/apps/api/src/durable-objects/project-orchestrator/cancel-mission.ts @@ -0,0 +1,236 @@ +import { and, asc, eq, gt, notInArray } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { retireTaskCancellationPrompts } from '../../services/task-cancellation-prompts'; +import { taskRecoveryCancellationStatement } from '../../services/task-recovery-cancellation'; +import { cancellationConfig } from './cancellation-config'; +import { logDecision } from './decision-log'; + +/** RPC runs under the same mutex as the alarm. A repeat explicitly retries a blocked episode. */ +export async function cancelTrackedMission( + storage: DurableObjectStorage, + env: Env, + projectId: string, + missionId: string, + serialize: (work: () => Promise) => Promise +): Promise { + if ( + await env.DATABASE.prepare( + 'SELECT 1 FROM missions WHERE id=? AND project_id=? AND workflow_plan_json IS NOT NULL' + ) + .bind(missionId, projectId) + .first() + ) + return false; + const config = await cancellationConfig(env); + const sql = storage.sql; + const tracked = sql + .exec( + 'SELECT status,cancellation_started_at FROM orchestrator_missions WHERE mission_id=?', + missionId + ) + .toArray(); + const trackedMission = tracked[0]; + if (!trackedMission) return false; + if (trackedMission.status !== 'cancelling') { + sql.exec( + `UPDATE orchestrator_missions SET status='cancelling', cancellation_started_at=?, cancellation_deadline_at=?, + cancellation_cursor=NULL, cancellation_pass=0 WHERE mission_id=?`, + Math.max(Date.now(), Number(trackedMission.cancellation_started_at ?? 0) + 1), + Date.now() + config.residenceMs, + missionId + ); + } + sql.exec('DELETE FROM scheduling_queue WHERE mission_id=?', missionId); + // Arm the accepted continuation before task-retirement work. + await storage.put('projectId', projectId); + await storage.setAlarm(Date.now() + config.intervalMs); + await env.DATABASE.prepare( + "UPDATE missions SET status='paused',updated_at=? WHERE id=? AND project_id=?" + ) + .bind(new Date().toISOString(), missionId, projectId) + .run(); + await serialize(() => continueMissionCancellation(sql, env, projectId, missionId)); + return true; +} + +/** Local safety expiry must not depend on settings, D1, or the alarm kill switch. */ +export function expireMissionCancellations(sql: SqlStorage): void { + const result = sql.exec( + `UPDATE orchestrator_missions SET status='cancel_blocked' + WHERE status='cancelling' AND (cancellation_deadline_at IS NULL OR cancellation_deadline_at<=?)`, + Date.now() + ); + if (result.rowsWritten) { + log.error('orchestrator.mission_cancellation_deadlines_exceeded', { + blockedMissions: result.rowsWritten, + reason: 'Cancellation deadline exceeded; explicit retry required', + }); + } +} + +/** One deadline-bound turn; task status itself is durable successful progress. */ +export async function continueMissionCancellation( + sql: SqlStorage, + env: Env, + projectId: string, + missionId: string +): Promise { + const state = sql + .exec( + `SELECT cancellation_started_at, cancellation_deadline_at, cancellation_cursor, cancellation_pass + FROM orchestrator_missions WHERE mission_id=? AND status='cancelling'`, + missionId + ) + .toArray()[0]; + if (!state) return; + const started = Number(state.cancellation_started_at); + const block = (reason: string) => { + sql.exec( + "UPDATE orchestrator_missions SET status='cancel_blocked' WHERE mission_id=?", + missionId + ); + logDecision(sql, missionId, null, 'cancel', reason, Date.now()); + log.error('orchestrator.mission_cancellation_blocked', { projectId, missionId, reason }); + }; + const episodeDeadline = Number(state.cancellation_deadline_at); + if (!Number.isFinite(episodeDeadline) || episodeDeadline <= Date.now()) { + block('Cancellation deadline exceeded; explicit retry required'); + return; + } + const config = await cancellationConfig(env); + if (Date.now() >= episodeDeadline) { + block('Cancellation deadline exceeded; explicit retry required'); + return; + } + // Local expiry precedes D1, so a broken prerequisite cannot keep the alarm alive forever. + await env.DATABASE.prepare( + "UPDATE missions SET status='paused',updated_at=? WHERE id=? AND project_id=?" + ) + .bind(new Date().toISOString(), missionId, projectId) + .run(); + const deadline = Math.min(Date.now() + config.turnMs, episodeDeadline); + const db = drizzle(env.DATABASE, { schema }); + const eligible = and( + eq(schema.tasks.missionId, missionId), + eq(schema.tasks.projectId, projectId), + notInArray(schema.tasks.status, ['completed', 'failed', 'cancelled']) + ); + const tasks = await db + .select({ + id: schema.tasks.id, + projectId: schema.tasks.projectId, + userId: schema.tasks.userId, + status: schema.tasks.status, + chatSessionId: schema.tasks.chatSessionId, + workspaceId: schema.tasks.workspaceId, + }) + .from(schema.tasks) + .where(and(eligible, gt(schema.tasks.id, String(state.cancellation_cursor ?? '')))) + .orderBy(asc(schema.tasks.id)) + .limit(config.pageSize); + if (!tasks.length) { + const remaining = await db + .select({ id: schema.tasks.id }) + .from(schema.tasks) + .where(eligible) + .limit(1) + .get(); + if (remaining) { + const pass = Number(state.cancellation_pass) + 1; + if (pass >= config.retryPasses) { + block('Cancellation retries exhausted; explicit retry required'); + return; + } + sql.exec( + 'UPDATE orchestrator_missions SET cancellation_cursor=NULL,cancellation_pass=? WHERE mission_id=?', + pass, + missionId + ); + return; + } + await completeCancellation(sql, env, projectId, missionId); + return; + } + for (const task of tasks) { + if (Date.now() >= deadline) break; + const assertAuthorized = async () => { + if ( + Date.now() >= deadline || + !sql + .exec( + `SELECT 1 FROM orchestrator_missions + WHERE mission_id=? AND status='cancelling' AND cancellation_started_at=?`, + missionId, + started + ) + .toArray().length + ) + throw new Error('Cancellation episode is no longer authorized'); + }; + const attemptStartedAt = Date.now(); + let timeout: ReturnType | undefined; + try { + // A timed-out RPC can retire prompts late, but never publishes a terminal task verdict. + await Promise.race([ + retireTaskCancellationPrompts(env, task, assertAuthorized, { + acceptedBefore: attemptStartedAt, + }), + new Promise((_, reject) => { + timeout = setTimeout( + () => reject(new Error('Cancellation turn deadline')), + Math.max(1, deadline - Date.now()) + ); + }), + ]); + await assertAuthorized(); + const now = new Date().toISOString(); + await env.DATABASE.batch([ + env.DATABASE.prepare( + `UPDATE tasks SET status='cancelled',scheduler_state='cancelled',completed_at=?,updated_at=? + WHERE id=? AND project_id=? AND mission_id=? AND status=?` + ).bind(now, now, task.id, projectId, missionId, task.status), + taskRecoveryCancellationStatement(env.DATABASE, task, now), + ]); + } catch (error) { + log.warn('orchestrator.mission_task_cancellation_deferred', { + projectId, + missionId, + taskId: task.id, + error: String(error), + }); + } finally { + if (timeout !== undefined) clearTimeout(timeout); + } + // Failed rows move behind healthy work and are retried only on the next finite pass. + sql.exec( + 'UPDATE orchestrator_missions SET cancellation_cursor=?,last_checked_at=? WHERE mission_id=?', + task.id, + Date.now(), + missionId + ); + } + await completeCancellation(sql, env, projectId, missionId); +} + +async function completeCancellation( + sql: SqlStorage, + env: Env, + projectId: string, + missionId: string +) { + const result = await env.DATABASE.prepare( + `UPDATE missions SET status='cancelled',updated_at=? + WHERE id=? AND project_id=? AND NOT EXISTS (SELECT 1 FROM tasks + WHERE tasks.mission_id=missions.id AND tasks.project_id=missions.project_id + AND tasks.status NOT IN ('completed','failed','cancelled'))` + ) + .bind(new Date().toISOString(), missionId, projectId) + .run(); + if (!result.meta.changes) return; + sql.exec('DELETE FROM orchestrator_missions WHERE mission_id=?', missionId); + logDecision(sql, missionId, null, 'cancel', 'Mission cancelled by user', Date.now()); +} diff --git a/apps/api/src/durable-objects/project-orchestrator/cancellation-config.ts b/apps/api/src/durable-objects/project-orchestrator/cancellation-config.ts new file mode 100644 index 0000000000..eb19978812 --- /dev/null +++ b/apps/api/src/durable-objects/project-orchestrator/cancellation-config.ts @@ -0,0 +1,33 @@ +import type { Env } from '../../env'; +import { resolveAdminSetting } from '../../services/admin-settings'; +import { + MISSION_CANCELLATION_DEFAULTS, + MISSION_CANCELLATION_SETTING_NAMES, +} from '../../services/admin-settings-orchestrator-definitions'; + +export async function cancellationConfig(env: Env) { + const keys = Object.keys(MISSION_CANCELLATION_DEFAULTS) as Array< + keyof typeof MISSION_CANCELLATION_DEFAULTS + >; + const values = await Promise.all( + keys.map( + async (key) => + [ + key, + Number(await resolveAdminSetting(env, MISSION_CANCELLATION_SETTING_NAMES[key])), + ] as const + ) + ); + return Object.fromEntries(values) as Record; +} + +export async function continuationDelay( + sql: SqlStorage, + env: Env, + schedulingIntervalMs: number +): Promise { + return sql.exec("SELECT 1 FROM orchestrator_missions WHERE status='cancelling' LIMIT 1").toArray() + .length + ? (await cancellationConfig(env)).intervalMs + : schedulingIntervalMs; +} diff --git a/apps/api/src/durable-objects/project-orchestrator/index.ts b/apps/api/src/durable-objects/project-orchestrator/index.ts index 38d30756f0..5696f57d24 100644 --- a/apps/api/src/durable-objects/project-orchestrator/index.ts +++ b/apps/api/src/durable-objects/project-orchestrator/index.ts @@ -4,12 +4,6 @@ * One instance per project, keyed by projectId: * env.PROJECT_ORCHESTRATOR.idFromName(projectId) * - * Coordinates agent work within a project: - * - Watches missions and manages their lifecycle - * - Routes handoff packets between tasks via durable messages - * - Detects stalled tasks and sends them a non-cancelling status nudge - * - Logs all scheduling decisions for auditability - * * Alarm-driven: wakes on a configurable interval (default 30s) to run * the scheduling loop. Sleeps when no active missions exist. */ @@ -32,8 +26,11 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { deferAlarmWhenDisabled } from '../../services/operational-kill-switch'; import { mapRows, parseRowOrNull } from '../row-validation'; +import { cancelTrackedMission, expireMissionCancellations } from './cancel-mission'; +import { continuationDelay } from './cancellation-config'; import { logDecision, pruneDecisionLog } from './decision-log'; import { runOrchestratorMigrations } from './migrations'; +import { pauseTrackedMission, resumeTrackedMission } from './mission-lifecycle'; import { runSchedulingCycle } from './scheduling'; // ============================================================================= @@ -138,113 +135,36 @@ export class ProjectOrchestrator extends DurableObject { * Pause a mission — stops scheduling new tasks but running tasks continue. */ async pauseMission(projectId: string, missionId: string): Promise { - // Workflow steering is not exposed in Phase 0; do not let legacy mission - // controls bypass workflow ownership or alter durable step state. - if ( - await this.env.DATABASE.prepare( - 'SELECT 1 FROM missions WHERE id = ? AND workflow_plan_json IS NOT NULL' - ) - .bind(missionId) - .first() - ) - return false; - this.projectId = projectId; - const sql = this.ctx.storage.sql; - const result = sql.exec( - `UPDATE orchestrator_missions SET status = 'paused' WHERE mission_id = ? AND status = 'active'`, - missionId + return this.serializeLifecycle(() => + pauseTrackedMission(this.ctx.storage.sql, this.env, projectId, missionId, () => { + this.projectId = projectId; + }) ); - if (result.rowsWritten === 0) return false; - - logDecision(sql, missionId, null, 'pause', 'Mission paused by user', Date.now()); - - // Update D1 mission status - await this.env.DATABASE.prepare('UPDATE missions SET status = ?, updated_at = ? WHERE id = ?') - .bind('paused', new Date().toISOString(), missionId) - .run(); - - log.info('orchestrator.mission_paused', { projectId, missionId }); - return true; } /** * Resume a paused mission — re-enables scheduling. */ async resumeMission(projectId: string, missionId: string): Promise { - // Workflow steering is not exposed in Phase 0; do not let legacy mission - // controls bypass workflow ownership or alter durable step state. - if ( - await this.env.DATABASE.prepare( - 'SELECT 1 FROM missions WHERE id = ? AND workflow_plan_json IS NOT NULL' + return this.serializeLifecycle(() => + resumeTrackedMission( + this.ctx.storage.sql, + this.env, + projectId, + missionId, + () => { + this.projectId = projectId; + }, + () => this.armAlarm() ) - .bind(missionId) - .first() - ) - return false; - this.projectId = projectId; - const sql = this.ctx.storage.sql; - const result = sql.exec( - `UPDATE orchestrator_missions SET status = 'active' WHERE mission_id = ? AND status = 'paused'`, - missionId ); - if (result.rowsWritten === 0) return false; - - logDecision(sql, missionId, null, 'resume', 'Mission resumed by user', Date.now()); - - // Update D1 mission status - await this.env.DATABASE.prepare('UPDATE missions SET status = ?, updated_at = ? WHERE id = ?') - .bind('active', new Date().toISOString(), missionId) - .run(); - - log.info('orchestrator.mission_resumed', { projectId, missionId }); - await this.armAlarm(); - return true; } - /** - * Cancel a mission — marks pending tasks as cancelled. - */ async cancelMission(projectId: string, missionId: string): Promise { - // Workflow steering is not exposed in Phase 0; do not let legacy mission - // controls bypass workflow ownership or alter durable step state. - if ( - await this.env.DATABASE.prepare( - 'SELECT 1 FROM missions WHERE id = ? AND workflow_plan_json IS NOT NULL' - ) - .bind(missionId) - .first() - ) - return false; this.projectId = projectId; - const sql = this.ctx.storage.sql; - - // Verify mission is tracked before proceeding - const tracked = sql - .exec(`SELECT 1 FROM orchestrator_missions WHERE mission_id = ?`, missionId) - .toArray(); - if (tracked.length === 0) return false; - - // Update D1 first (source of truth) — cancel tasks and mission - const now = new Date().toISOString(); - await this.env.DATABASE.prepare( - `UPDATE tasks SET status = 'cancelled', scheduler_state = 'cancelled', updated_at = ? - WHERE mission_id = ? AND status NOT IN ('completed', 'failed', 'cancelled')` - ) - .bind(now, missionId) - .run(); - - await this.env.DATABASE.prepare('UPDATE missions SET status = ?, updated_at = ? WHERE id = ?') - .bind('cancelled', now, missionId) - .run(); - - // Then remove from DO tracking - sql.exec(`DELETE FROM orchestrator_missions WHERE mission_id = ?`, missionId); - sql.exec('DELETE FROM scheduling_queue WHERE mission_id = ?', missionId); - - logDecision(sql, missionId, null, 'cancel', 'Mission cancelled by user', Date.now()); - log.info('orchestrator.mission_cancelled', { projectId, missionId }); - - return true; + return cancelTrackedMission(this.ctx.storage, this.env, projectId, missionId, (work) => + this.serializeLifecycle(work) + ); } /** @@ -450,6 +370,15 @@ export class ProjectOrchestrator extends DurableObject { // ========================================================================= override async alarm(): Promise { + expireMissionCancellations(this.ctx.storage.sql); + if ( + !this.ctx.storage.sql + .exec( + "SELECT 1 FROM orchestrator_missions WHERE status IN ('active', 'completing', 'cancelling') LIMIT 1" + ) + .toArray().length + ) + return; if (await deferAlarmWhenDisabled(this.env, this.ctx.storage, 'ProjectOrchestrator')) return; const config = resolveOrchestratorConfig(this.env); @@ -477,11 +406,16 @@ export class ProjectOrchestrator extends DurableObject { // Re-arm while active or legacy completing missions still need work. const activeMissions = this.ctx.storage.sql - .exec(`SELECT 1 FROM orchestrator_missions WHERE status IN ('active', 'completing') LIMIT 1`) + .exec( + `SELECT 1 FROM orchestrator_missions WHERE status IN ('active', 'completing', 'cancelling') LIMIT 1` + ) .toArray(); if (activeMissions.length > 0) { - await this.ctx.storage.setAlarm(Date.now() + config.schedulingIntervalMs); + await this.ctx.storage.setAlarm( + Date.now() + + (await continuationDelay(this.ctx.storage.sql, this.env, config.schedulingIntervalMs)) + ); } } @@ -489,6 +423,15 @@ export class ProjectOrchestrator extends DurableObject { // Helpers // ========================================================================= + private serializeLifecycle(work: () => Promise): Promise { + const result = this.cycleLock.then(work); + this.cycleLock = result.then( + () => undefined, + () => undefined + ); + return result; + } + private async armAlarm(): Promise { const config = resolveOrchestratorConfig(this.env); const existing = await this.ctx.storage.getAlarm(); diff --git a/apps/api/src/durable-objects/project-orchestrator/migrations.ts b/apps/api/src/durable-objects/project-orchestrator/migrations.ts index 286a830ef1..399c184ea5 100644 --- a/apps/api/src/durable-objects/project-orchestrator/migrations.ts +++ b/apps/api/src/durable-objects/project-orchestrator/migrations.ts @@ -46,6 +46,16 @@ export const ORCHESTRATOR_MIGRATIONS = [ name: '002_workflow_registration', sql: 'ALTER TABLE orchestrator_missions ADD COLUMN workflow_registration_deadline INTEGER;', }, + { + name: '003_cancellation_progress', + sql: `ALTER TABLE orchestrator_missions ADD COLUMN cancellation_started_at INTEGER; + ALTER TABLE orchestrator_missions ADD COLUMN cancellation_cursor TEXT; + ALTER TABLE orchestrator_missions ADD COLUMN cancellation_pass INTEGER NOT NULL DEFAULT 0;`, + }, + { + name: '004_cancellation_deadline', + sql: 'ALTER TABLE orchestrator_missions ADD COLUMN cancellation_deadline_at INTEGER;', + }, ] as const; /** diff --git a/apps/api/src/durable-objects/project-orchestrator/mission-lifecycle.ts b/apps/api/src/durable-objects/project-orchestrator/mission-lifecycle.ts new file mode 100644 index 0000000000..0eefc7fb3d --- /dev/null +++ b/apps/api/src/durable-objects/project-orchestrator/mission-lifecycle.ts @@ -0,0 +1,92 @@ +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { logDecision } from './decision-log'; + +export async function pauseTrackedMission( + sql: SqlStorage, + env: Env, + projectId: string, + missionId: string, + bindProject: () => void +): Promise { + return transitionMission(sql, env, projectId, missionId, 'active', 'paused', bindProject); +} + +export async function resumeTrackedMission( + sql: SqlStorage, + env: Env, + projectId: string, + missionId: string, + bindProject: () => void, + armAlarm: () => Promise +): Promise { + const changed = await transitionMission( + sql, + env, + projectId, + missionId, + 'paused', + 'active', + bindProject + ); + if (changed) await armAlarm(); + return changed; +} + +/** Called under cycleLock. Cancellation may still install its synchronous intent marker. */ +async function transitionMission( + sql: SqlStorage, + env: Env, + projectId: string, + missionId: string, + from: 'active' | 'paused', + to: 'active' | 'paused', + bindProject: () => void +): Promise { + const mission = await env.DATABASE.prepare( + `SELECT status,updated_at FROM missions + WHERE id=? AND project_id=? AND workflow_plan_json IS NULL` + ) + .bind(missionId, projectId) + .first<{ status: string; updated_at: string }>(); + if (!mission || !['planning', 'active', 'paused'].includes(mission.status)) return false; + bindProject(); + if ( + !sql + .exec('SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status=?', missionId, from) + .toArray().length + ) + return false; + const now = new Date(Math.max(Date.now(), Date.parse(mission.updated_at) + 1)).toISOString(); + const result = await env.DATABASE.prepare( + `UPDATE missions SET status=?,updated_at=? + WHERE id=? AND project_id=? AND status=? AND updated_at=? AND workflow_plan_json IS NULL` + ) + .bind(to, now, missionId, projectId, mission.status, mission.updated_at) + .run(); + if (!result.meta.changes) return false; + // A cancellation marker installed during the D1 await wins local ownership. + if ( + !sql.exec( + 'UPDATE orchestrator_missions SET status=? WHERE mission_id=? AND status=?', + to, + missionId, + from + ).rowsWritten + ) + return false; + const action = to === 'paused' ? 'pause' : 'resume'; + logDecision( + sql, + missionId, + null, + action, + `Mission ${to === 'paused' ? 'paused' : 'resumed'} by user`, + Date.now() + ); + log.info(`orchestrator.mission_${to === 'paused' ? 'paused' : 'resumed'}`, { + projectId, + missionId, + }); + return true; +} diff --git a/apps/api/src/durable-objects/project-orchestrator/scheduling.ts b/apps/api/src/durable-objects/project-orchestrator/scheduling.ts index 52510fd3b6..c823d35fa2 100644 --- a/apps/api/src/durable-objects/project-orchestrator/scheduling.ts +++ b/apps/api/src/durable-objects/project-orchestrator/scheduling.ts @@ -6,23 +6,12 @@ * log decisions. */ import type { OrchestratorConfig } from '@simple-agent-manager/shared'; -import type { VMSize } from '@simple-agent-manager/shared'; -import { drizzle } from 'drizzle-orm/d1'; import * as v from 'valibot'; -import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; -import { expectJsonRecord } from '../../lib/runtime-validation'; -import { ulid } from '../../lib/ulid'; -import { - CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS, - capacityPlacementSnapshotSqlValues, -} from '../../services/capacity-placement-snapshot'; -import { resolveTaskStartPlacementCredentialAttribution } from '../../services/placement-resolver'; import * as projectDataService from '../../services/project-data'; import { recomputeMissionSchedulerStates } from '../../services/scheduler-state-sync'; -import { startTaskRunnerDO } from '../../services/task-runner-do'; import { getWorkflowConfig } from '../../services/workflow-config'; import { cleanupTerminalWorkflowWaits, @@ -30,6 +19,8 @@ import { } from '../../services/workflow-reconcile'; import type { WorkflowRunRow } from '../../services/workflow-runs'; import { mapRows } from '../row-validation'; +import { autoDispatchSchedulableTasks } from './auto-dispatch'; +import { continueMissionCancellation } from './cancel-mission'; import { logDecision } from './decision-log'; import { buildHandoffContent, parseRoutableHandoff, type RoutableHandoff } from './handoff-content'; import { detectStalls, resolveActiveSessionIdsForTaskIds } from './stall-detection'; @@ -78,7 +69,7 @@ export async function runSchedulingCycle( .exec( `SELECT mission_id, status, registered_at, workflow_registration_deadline FROM orchestrator_missions - WHERE status IN ('active', 'completing') ORDER BY last_checked_at, mission_id` + WHERE status IN ('active', 'completing', 'cancelling') ORDER BY last_checked_at, mission_id` ) .toArray(), SchedulingMissionRowSchema, @@ -92,6 +83,10 @@ export async function runSchedulingCycle( let workflowBudgetLoaded = false; for (const mission of missions) { try { + if (mission.status === 'cancelling') { + await continueMissionCancellation(sql, env, projectId, mission.mission_id); + continue; + } const workflow = await env.DATABASE.prepare( 'SELECT * FROM missions WHERE id = ? AND project_id = ? AND workflow_plan_json IS NOT NULL' ) @@ -123,6 +118,15 @@ export async function runSchedulingCycle( cleanupMissionTracking(sql, mission.mission_id); continue; } + if ( + !sql + .exec( + "SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status IN ('active','completing')", + mission.mission_id + ) + .toArray().length + ) + continue; const status = mission.status ?? 'active'; if (status === 'completing') { cleanupMissionTracking(sql, mission.mission_id); @@ -186,6 +190,12 @@ async function processMission( .bind(missionId) .all(); + if ( + !sql + .exec("SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status='active'", missionId) + .toArray().length + ) + return; const tasks = tasksResult.results ?? []; if (tasks.length === 0) { if (now - registeredAt >= config.zeroTaskGraceMs) { @@ -208,6 +218,12 @@ async function processMission( // 3. Auto-dispatch schedulable tasks await autoDispatchSchedulableTasks(sql, env, projectId, missionId, config, now); + if ( + !sql + .exec("SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status='active'", missionId) + .toArray().length + ) + return; // 5. Find newly completed tasks — check for handoff packets to route const completedTasks = tasks.filter((t) => t.status === 'completed'); for (const task of completedTasks) { @@ -217,6 +233,12 @@ async function processMission( // 6. Detect stalled tasks await detectStalls(sql, env, projectId, missionId, tasks, config, now); + if ( + !sql + .exec("SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status='active'", missionId) + .toArray().length + ) + return; // 7. Check if mission is complete (all tasks terminal) const allTerminal = tasks.every( (t) => t.status === 'completed' || t.status === 'failed' || t.status === 'cancelled' @@ -260,360 +282,42 @@ async function terminalizeMission( reason: string, now: number ): Promise { - await env.DATABASE.prepare('UPDATE missions SET status = ?, updated_at = ? WHERE id = ?') - .bind(status, new Date(now).toISOString(), missionId) + const result = await env.DATABASE.prepare( + `UPDATE missions SET status = ?, updated_at = ? WHERE id = ? + AND project_id = ? AND status IN ('planning','active') + AND (? = 'max_mission_lifetime' OR NOT EXISTS ( + SELECT 1 FROM tasks WHERE tasks.mission_id=missions.id + AND tasks.project_id=missions.project_id AND tasks.status NOT IN ('completed','failed','cancelled') + ))` + ) + .bind(status, new Date(now).toISOString(), missionId, projectId, reason) .run(); + if (!result.meta.changes) { + const current = await env.DATABASE.prepare( + 'SELECT status FROM missions WHERE id=? AND project_id=?' + ) + .bind(missionId, projectId) + .first<{ status: string }>(); + if (current && !['completed', 'failed', 'cancelled'].includes(current.status)) return; + } + // Cancellation can install its durable marker while the D1 write is suspended. + // Only the cancellation owner may remove that tracking row. + if ( + sql + .exec( + "SELECT 1 FROM orchestrator_missions WHERE mission_id=? AND status IN ('cancelling','cancel_blocked')", + missionId + ) + .toArray().length + ) + return; cleanupMissionTracking(sql, missionId); log.info('orchestrator.mission_terminal', { projectId, missionId, status, reason }); } // ── Auto-Dispatch ───────────────────────────────────────────────────────────── -interface DispatchableTaskRow { - id: string; - title: string; - description: string | null; - user_id: string; - project_id: string; - output_branch: string | null; - agent_profile_hint: string | null; - dispatch_depth: number; - priority: number; -} - -/** - * Find schedulable tasks and auto-dispatch them via startTaskRunnerDO. - * Respects concurrency limits from mission budget_config and per-cycle max. - */ -async function autoDispatchSchedulableTasks( - sql: SqlStorage, - env: Env, - projectId: string, - missionId: string, - config: OrchestratorConfig, - now: number -): Promise { - // Re-read task states from D1 (fresh after recompute) - const schedulableResult = await env.DATABASE.prepare( - `SELECT id, title, description, user_id, project_id, output_branch, agent_profile_hint, dispatch_depth, priority - FROM tasks - WHERE mission_id = ? - AND scheduler_state = 'schedulable' - AND status = 'queued' - AND chat_session_id IS NULL - AND NOT EXISTS ( - SELECT 1 - FROM vm_task_admissions - WHERE vm_task_admissions.task_id = tasks.id - AND vm_task_admissions.state IN ( - 'queued', 'waiting', 'provisioning_granted', 'provisioning', 'node_ready' - ) - ) - ORDER BY priority DESC, created_at ASC - LIMIT ?` - ) - .bind(missionId, config.maxDispatchesPerCycle) - .all(); - - const schedulable = schedulableResult.results ?? []; - if (schedulable.length === 0) return; - - // Check concurrency limit: count currently active tasks in this mission - const activeCountResult = await env.DATABASE.prepare( - `SELECT COUNT(*) as cnt FROM tasks - WHERE mission_id = ? - AND ( - status IN ('in_progress', 'delegated') - OR (status = 'queued' AND chat_session_id IS NOT NULL) - OR EXISTS ( - SELECT 1 - FROM vm_task_admissions - WHERE vm_task_admissions.task_id = tasks.id - AND vm_task_admissions.state IN ( - 'queued', 'waiting', 'provisioning_granted', 'provisioning', 'node_ready' - ) - ) - )` - ) - .bind(missionId) - .first<{ cnt: number }>(); - - const activeCount = activeCountResult?.cnt ?? 0; - - // Resolve max active tasks from mission budget_config - const missionRow = await env.DATABASE.prepare('SELECT budget_config FROM missions WHERE id = ?') - .bind(missionId) - .first<{ budget_config: string | null }>(); - - let maxActive = config.maxActiveTasksPerMission; - if (missionRow?.budget_config) { - try { - const budget = expectJsonRecord( - JSON.parse(missionRow.budget_config), - 'mission.budget_config' - ); - if (typeof budget.maxActiveTasks === 'number' && budget.maxActiveTasks > 0) { - maxActive = budget.maxActiveTasks; - } - } catch { - // Invalid JSON — use default - } - } - - const slotsAvailable = Math.max(0, maxActive - activeCount); - if (slotsAvailable === 0) { - logDecision( - sql, - missionId, - null, - 'skip', - `${schedulable.length} schedulable task(s) held: concurrency limit reached (${activeCount}/${maxActive} active)`, - now - ); - return; - } - - // Fetch project info (needed for startTaskRunnerDO) - const projectRow = await env.DATABASE.prepare( - `SELECT repository, installation_id, default_branch, default_vm_size, - default_agent_type, default_workspace_profile, default_devcontainer_config_name, - task_execution_timeout_ms, node_cpu_threshold_percent, - node_memory_threshold_percent, warm_node_timeout_ms - FROM projects WHERE id = ?` - ) - .bind(projectId) - .first<{ - repository: string; - installation_id: string; - default_branch: string; - default_vm_size: string | null; - default_agent_type: string | null; - default_workspace_profile: string | null; - default_devcontainer_config_name: string | null; - task_execution_timeout_ms: number | null; - node_cpu_threshold_percent: number | null; - node_memory_threshold_percent: number | null; - warm_node_timeout_ms: number | null; - }>(); - - if (!projectRow) { - logDecision(sql, missionId, null, 'skip', 'Project not found — cannot dispatch', now); - return; - } - - const db = drizzle(env.DATABASE, { schema }); - const toDispatch = schedulable.slice(0, Math.min(slotsAvailable, config.maxDispatchesPerCycle)); - let dispatched = 0; - - for (const task of toDispatch) { - try { - // Resolve user info for git config - const userRow = await env.DATABASE.prepare( - 'SELECT name, email, github_id FROM users WHERE id = ?' - ) - .bind(task.user_id) - .first<{ name: string | null; email: string | null; github_id: string | null }>(); - - const placementResolution = await resolveTaskStartPlacementCredentialAttribution( - db, - { - entryPoint: 'orchestrator-dispatch', - taskId: task.id, - projectId, - userId: task.user_id, - project: { - id: projectId, - defaultVmSize: projectRow.default_vm_size, - defaultWorkspaceProfile: projectRow.default_workspace_profile, - defaultDevcontainerConfigName: projectRow.default_devcontainer_config_name, - defaultAgentType: projectRow.default_agent_type, - }, - profile: null, - credentialProjectPolicy: 'current-project', - taskModeDefault: 'task', - resourceRequirements: {}, - }, - { env } - ); - if ('error' in placementResolution) { - logDecision(sql, missionId, task.id, 'skip', placementResolution.error, now); - continue; - } - const { - placement, - effectiveProvider, - credentialAttributionUserId, - credentialAttributionProjectId, - credentialAttributionSource, - capacityPoolSelection, - capacityPlacementSnapshot, - } = placementResolution; - const { - vmSize: resolvedVmSize, - vmSizeSource, - vmLocation: resolvedVmLocation, - workspaceProfile: resolvedWorkspaceProfile, - devcontainerConfigName: resolvedDevcontainerConfig, - agentType: resolvedAgentType, - resolvedReservation, - } = placement; - - // Create chat session for the task - const sessionId = await projectDataService.createSession( - env, - projectId, - null, - task.title, - task.id, - task.user_id - ); - - if (task.description) { - await projectDataService.persistMessage( - env, - projectId, - sessionId, - 'user', - task.description, - null - ); - } - - // Transition task to queued → provisioning via status update - const dispatchTransition = await env.DATABASE.prepare( - `UPDATE tasks - SET status = 'queued', - chat_session_id = ?, - execution_step = 'node_selection', - requested_vm_size = ?, - requested_vm_size_source = ?, - resource_requirements_source = ?, - resolved_reservation_json = ?, - credential_attribution_user_id = ?, - credential_attribution_project_id = ?, - credential_attribution_source = ?, - ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS}, - updated_at = ? - WHERE id = ? AND (chat_session_id IS NULL OR chat_session_id = ?)` - ) - .bind( - sessionId, - resolvedVmSize, - vmSizeSource, - resolvedReservation.source, - JSON.stringify(resolvedReservation), - credentialAttributionUserId, - credentialAttributionProjectId, - credentialAttributionSource, - ...capacityPlacementSnapshotSqlValues(capacityPlacementSnapshot), - new Date().toISOString(), - task.id, - sessionId - ) - .run(); - if (!dispatchTransition.meta.changes) { - throw new Error('Task was already bound to a different chat session'); - } - - // Start the TaskRunner DO - await startTaskRunnerDO(env, { - taskId: task.id, - projectId, - userId: task.user_id, - vmSize: resolvedVmSize, - vmLocation: resolvedVmLocation, - branch: projectRow.default_branch, - defaultBranch: projectRow.default_branch, - userName: userRow?.name ?? null, - userEmail: userRow?.email ?? null, - githubId: userRow?.github_id ?? null, - taskTitle: task.title, - taskDescription: task.description ?? null, - repository: projectRow.repository, - installationId: projectRow.installation_id, - outputBranch: task.output_branch ?? null, - projectDefaultVmSize: projectRow.default_vm_size as VMSize | null, - chatSessionId: sessionId, - agentType: resolvedAgentType, - workspaceProfile: resolvedWorkspaceProfile, - devcontainerConfigName: resolvedDevcontainerConfig, - cloudProvider: placement.provider ?? effectiveProvider, - explicitVmLocation: placement.explicitVmLocation === true, - credentialAttributionUserId, - credentialAttributionProjectId, - credentialAttributionSource, - agentProfileHint: task.agent_profile_hint ?? null, - effort: null, - projectScaling: { - taskExecutionTimeoutMs: projectRow.task_execution_timeout_ms ?? null, - nodeCpuThresholdPercent: projectRow.node_cpu_threshold_percent ?? null, - nodeMemoryThresholdPercent: projectRow.node_memory_threshold_percent ?? null, - warmNodeTimeoutMs: projectRow.warm_node_timeout_ms ?? null, - }, - resolvedReservation, - capacityPoolSelection, - vmSizeSource, - }); - - // Record in scheduling_queue - sql.exec( - `INSERT INTO scheduling_queue (id, mission_id, task_id, scheduled_at, dispatched_at, reason) - VALUES (?, ?, ?, ?, ?, ?)`, - ulid(), - missionId, - task.id, - now, - now, - 'auto-dispatch: task became schedulable' - ); - - logDecision( - sql, - missionId, - task.id, - 'dispatch', - `Auto-dispatched schedulable task (slot ${dispatched + 1}/${slotsAvailable})`, - now - ); - - dispatched++; - - log.info('orchestrator.task_dispatched', { - projectId, - missionId, - taskId: task.id, - slot: dispatched, - slotsAvailable, - }); - } catch (err) { - log.error('orchestrator.auto_dispatch_failed', { - projectId, - missionId, - taskId: task.id, - error: err instanceof Error ? err.message : String(err), - }); - logDecision( - sql, - missionId, - task.id, - 'skip', - `Auto-dispatch failed: ${err instanceof Error ? err.message : String(err)}`, - now - ); - } - } - - if (dispatched > 0) { - // Update last_dispatch_at - sql.exec( - 'UPDATE orchestrator_missions SET last_dispatch_at = ? WHERE mission_id = ?', - now, - missionId - ); - } -} - // ── Handoff Routing ─────────────────────────────────────────────────────────── /** diff --git a/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts b/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts index a2791592fb..d4aa927b88 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop-helpers.ts @@ -218,5 +218,4 @@ export function toOpenAIMessages(rows: MessageRow[]): OpenAIMessage[] { return messages; } -// One Anthropic URL builder for the proxy and the SAM agent (rule 24). export { buildAnthropicGatewayUrl } from '../../services/ai-proxy-shared'; diff --git a/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts index 79c3dc6e37..5ee3c50880 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts @@ -15,7 +15,6 @@ import { fetchChatTarget, LlmUnavailableError, resolveCloudflareWorkersAiTarget, - withStreamUsageRequested, } from '../../services/llm-chat-target'; import { aiGatewayOnlyHeaders } from '../../services/platform-capabilities'; import { getPlatformAgentCredential } from '../../services/platform-credentials'; @@ -52,8 +51,7 @@ export async function callLLM( userId: string, conversationId: string, baseSystemPrompt: string, - tools: AnthropicToolDef[], - endpoint: ChatCompletionsTarget | null + { tools, endpoint }: { tools: AnthropicToolDef[]; endpoint: ChatCompletionsTarget | null } ): Promise { const model = config.model; const systemPrompt = config.systemPromptAppend @@ -185,7 +183,7 @@ async function callAnthropicLLM( } /** Call an OpenAI-format chat completions target (Workers AI or an OpenAI-compatible endpoint). */ -async function callOpenAIChatLLM( +function callOpenAIChatLLM( target: ChatCompletionsTarget, systemPrompt: string, messages: OpenAIMessage[], @@ -200,14 +198,12 @@ async function callOpenAIChatLLM( method: 'POST', signal, headers: chatTargetHeaders(target, { 'cf-aig-metadata': aigMetadata }), - body: JSON.stringify( - withStreamUsageRequested(target, { - model: target.model, - max_tokens: maxTokens, - messages: fullMessages, - tools: openAITools.length > 0 ? openAITools : undefined, - stream: true, - }) - ), + body: JSON.stringify({ + model: target.model, + max_tokens: maxTokens, + messages: fullMessages, + tools: openAITools.length > 0 ? openAITools : undefined, + stream: true, + }), }); } diff --git a/apps/api/src/durable-objects/sam-session/agent-loop.ts b/apps/api/src/durable-objects/sam-session/agent-loop.ts index ca5e3e4a33..7381cfa260 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop.ts @@ -1,3 +1,7 @@ +import { + estimateInputTokensFromMessages, + monthlyCostCapMessage, +} from '@simple-agent-manager/ai-proxy'; /** * Agent loop — unified OpenAI-format code path routed through AI Gateway. * @@ -19,7 +23,6 @@ import { import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { expectJsonRecord } from '../../lib/runtime-validation'; -import { upstreamErrorLogFields } from '../../services/ai-proxy-shared'; import { checkAiUsageGate } from '../../services/ai-token-budget'; import { attachTokenUsageAccounting } from '../../services/ai-token-usage-accounting'; import { LlmUnavailableError, resolveOpenAICompatibleTarget } from '../../services/llm-chat-target'; @@ -84,8 +87,6 @@ export async function runAgentLoop( ]; const systemPrompt = options?.systemPrompt ?? SAM_SYSTEM_PROMPT; - // An admin-configured OpenAI-compatible endpoint replaces the model route for SAM and project - // agents (services/llm-chat-target.ts); without one the configured model routes as before. let endpoint; try { endpoint = await resolveOpenAICompatibleTarget(env, 'agent', baseConfig.model); @@ -95,7 +96,7 @@ export async function runAgentLoop( await writer.write(encodeSseEvent({ type: 'done' })); return; } - const config: SamConfig = endpoint ? { ...baseConfig, model: endpoint.model } : baseConfig; + const config = endpoint ? { ...baseConfig, model: endpoint.model } : baseConfig; const tools = options?.tools ?? []; const executeToolFn = options?.executeTool ?? (async () => ({ error: 'No tool executor configured' })); @@ -112,7 +113,7 @@ export async function runAgentLoop( // unless the user explicitly set SAM_MAX_REQUEST_BODY_BYTES as an override. const hasExplicitOverride = !!env.SAM_MAX_REQUEST_BODY_BYTES; const effectiveBudget = - !hasExplicitOverride && (endpoint !== null || isWorkersAIModel(config.model)) + !hasExplicitOverride && isWorkersAIModel(config.model) ? DEFAULT_SAM_MAX_REQUEST_BODY_BYTES_WORKERS_AI : config.maxRequestBodyBytes; const fixedOverhead = systemPrompt.length + JSON.stringify(tools).length + 500; @@ -140,7 +141,7 @@ export async function runAgentLoop( const message = usageGate.reason === 'daily-token-budget' ? 'Daily token budget exceeded. Resets at midnight UTC.' - : 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.'; + : monthlyCostCapMessage(usageGate.monthlyCap); log.warn('sam.ai_usage_gate_denied', { userId, conversationId, @@ -153,33 +154,25 @@ export async function runAgentLoop( let response: Response; try { - response = await callLLM( - env, - config, - llmMessages, - userId, - conversationId, - systemPrompt, + response = await callLLM(env, config, llmMessages, userId, conversationId, systemPrompt, { tools, - endpoint - ); + endpoint, + }); response = await attachTokenUsageAccounting(response, { env, userId, format: tokenUsageFormat, - executionCtx, estimateMissingUsage: endpoint !== null, - // An operator endpoint serves its own model, which has no catalog price. - costModelId: endpoint === null ? config.model : undefined, + fallbackInputTokens: endpoint + ? estimateInputTokensFromMessages([ + { role: 'system', content: systemPrompt }, + ...llmMessages, + ]) + : undefined, + costModelId: endpoint ? undefined : config.model, + executionCtx, }); } catch (fetchErr) { - // No model on this installation (no endpoint configured, no Cloudflare route): retrying - // cannot help, so say what an admin must do instead of reporting a transient failure. - if (fetchErr instanceof LlmUnavailableError) { - log.warn('sam.llm_unavailable', { model: config.model }); - await writer.write(encodeSseEvent({ type: 'error', message: fetchErr.message })); - break; - } const errMsg = fetchErr instanceof Error ? fetchErr.message : String(fetchErr); const isTimeout = errMsg.includes('abort'); log.error('sam.llm_fetch_error', { @@ -205,10 +198,10 @@ export async function runAgentLoop( }); if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); log.error('sam.llm_error', { status: response.status, - // An admin-configured endpoint is third-party: a bounded, sanitized reason, never its body. - ...(await upstreamErrorLogFields(response, endpoint !== null)), + body: endpoint ? '[external endpoint body omitted]' : errorText.slice(0, 500), model: config.model, }); await writer.write( diff --git a/apps/api/src/durable-objects/sam-session/operator/agent.ts b/apps/api/src/durable-objects/sam-session/operator/agent.ts index 714199e7f0..05ad99147c 100644 --- a/apps/api/src/durable-objects/sam-session/operator/agent.ts +++ b/apps/api/src/durable-objects/sam-session/operator/agent.ts @@ -1,8 +1,9 @@ +import type { MonthlyCostCapCheck } from '@simple-agent-manager/ai-proxy'; import { PLATFORM_AI_MODELS, resolveSamConfig } from '@simple-agent-manager/shared'; import type { Env } from '../../../env'; import { getTrustedApiOrigin } from '../../../lib/trusted-origins'; -import { checkAiUsageGate } from '../../../services/ai-token-budget'; +import { checkAiUsageGate,monthlyCostCapMessage } from '../../../services/ai-token-budget'; import { projectOperatorContext } from './context'; import { assertGroundedOperatorResponse, @@ -11,10 +12,23 @@ import { OperatorGroundingError, } from './grounding'; import type { OperatorLive } from './live'; -import { operatorProviderOptions, recordOperatorStepUsage, resolveOperatorModel } from './model'; +import { + assertOperatorModelSupportsTools, + operatorProviderOptions, + recordOperatorStepUsage, + resolveOperatorModel, +} from './model'; import { assertOperatorExecution, operatorTools } from './operations'; import type { OperatorStore, OperatorTurn } from './store'; +/** Only trusted budget recovery copy may cross the controller's error sanitization boundary. */ +export class OperatorMonthlyCostCapError extends Error { + override name = 'OperatorMonthlyCostCapError'; + constructor(cap: MonthlyCostCapCheck) { + super(monthlyCostCapMessage(cap)); + } +} + export const OPERATOR_INSTRUCTIONS = `You are SAM, the user's private account assistant. Use live platform operations for claims about projects and work. Always name the project and link to the source task/session. Distinguish accepted, running, agent-reported completion and independently verified results. Say when evidence is incomplete or stale. Questions about the current state of work (what is running, what changed, shipped or failed recently, what needs attention) MUST be answered from operations you call in this turn, never from conversation history. Earlier turns appear as sam_historical_turn_status records with a recordedAt time: they describe the past, may be months old and are never current status. Never write such records yourself; always answer in plain prose. Compare returned timestamps with the current time given at the end of these instructions, say how recent items are, and never call an item recent unless a returned timestamp shows it. @@ -76,10 +90,23 @@ export async function runOperatorAgent(options: { metadata: JSON.stringify({ source: config.aigSource, userId, turnId: turn.id }), sessionAffinity: `sam-${turn.conversation_id}`, }); + const customEndpoint = + typeof model === 'object' && + model !== null && + 'provider' in model && + String(model.provider).startsWith('sam-openai-compatible'); + assertOperatorModelSupportsTools(catalogModel, customEndpoint); assertCurrent(); let toolAttempted = false; let inferenceFailed = false; let startedSteps = 0; + let monthlyDenial: OperatorMonthlyCostCapError | undefined; + // Mastra may wrap prepareStep failures or return them in full.error. Keep our own denial, + // never provider error text, and recheck the turn fence before exposing its recovery advice. + const rethrowFailure = (error: unknown): never => { + assertCurrent(); + throw monthlyDenial ?? error; + }; const instructions = `${OPERATOR_INSTRUCTIONS}\nPrivate unresolved receipt references (evidence only; not permission to retry): ${JSON.stringify(store.unresolvedActions(config.historyLoadLimit))}\n${REPLY_FORMAT}\n${currentTimeInstruction(new Date())}`; const agent = new Agent({ id: 'sam-account-operator', @@ -128,7 +155,7 @@ export async function runOperatorAgent(options: { maxSteps: config.maxTurns - startedSteps, ...(correcting ? { instructions: `${instructions}\n${GROUNDING_CORRECTION}` } : {}), modelSettings: { maxOutputTokens: config.maxTokens, maxRetries: 0 }, - providerOptions: operatorProviderOptions(config.model), + providerOptions: operatorProviderOptions(customEndpoint ? '' : config.model), // Same scheduling as generate(): a tool starts after its step, behind prepareStep's gates. eagerToolExecution: false, onChunk: (chunk) => { @@ -147,8 +174,14 @@ export async function runOperatorAgent(options: { await assertOperatorExecution(env, userId); assertCurrent(); const gate = await checkAiUsageGate(env.KV, userId, env); - if (!gate.allowed) throw new Error('SAM usage budget exhausted'); assertCurrent(); + if (!gate.allowed) { + if (gate.reason === 'monthly-cost-cap') { + monthlyDenial = new OperatorMonthlyCostCapError(gate.monthlyCap); + throw monthlyDenial; + } + throw new Error('SAM usage budget exhausted'); + } startedSteps++; return { toolChoice: correcting && stepNumber === 0 ? ('required' as const) : ('auto' as const), @@ -158,10 +191,11 @@ export async function runOperatorAgent(options: { if (step.finishReason === 'error') inferenceFailed = true; if (step.toolCalls.length > 0) toolAttempted = true; live?.stepFinished(step.toolCalls.length > 0); - await recordOperatorStepUsage(env, userId, config, catalogModel, step); + await recordOperatorStepUsage(env, userId, config, catalogModel, step, customEndpoint); }, - }); - const full = await output.getFullOutput(); + }).catch(rethrowFailure); + const full = await output.getFullOutput().catch(rethrowFailure); + if (monthlyDenial) rethrowFailure(monthlyDenial); if (full.error) throw full.error; return full; }; diff --git a/apps/api/src/durable-objects/sam-session/operator/controller.ts b/apps/api/src/durable-objects/sam-session/operator/controller.ts index b03d74c3ef..808e407766 100644 --- a/apps/api/src/durable-objects/sam-session/operator/controller.ts +++ b/apps/api/src/durable-objects/sam-session/operator/controller.ts @@ -8,7 +8,7 @@ import { OPERATOR_DEFAULTS } from '../../../services/admin-settings-registry'; import { LlmUnavailableError } from '../../../services/llm-chat-target'; import { getOperatorSettings, type OperatorSettings } from '../../../services/operator-settings'; import { handleActionRoute } from './action-routes'; -import { runOperatorAgent } from './agent'; +import { OperatorMonthlyCostCapError, runOperatorAgent } from './agent'; import { OperatorLive } from './live'; import { assertOperatorAccount, assertOperatorExecution } from './operations'; import { actionProjection, projectAccessCache } from './projection'; @@ -321,8 +321,8 @@ export class OperatorController { turn.id, 'interrupted', null, - // No model on this installation: say what an admin must configure, not "retry". - error instanceof LlmUnavailableError + // A spent monthly cap, or no model on this installation: say what must change, not "retry". + error instanceof OperatorMonthlyCostCapError || error instanceof LlmUnavailableError ? error.message : 'SAM could not finish this turn. Review recorded actions before continuing; uncertain actions are not automatically repeated.' ); diff --git a/apps/api/src/durable-objects/sam-session/operator/model.ts b/apps/api/src/durable-objects/sam-session/operator/model.ts index 28371c3e85..a1af3ea86b 100644 --- a/apps/api/src/durable-objects/sam-session/operator/model.ts +++ b/apps/api/src/durable-objects/sam-session/operator/model.ts @@ -1,14 +1,15 @@ import type { MastraModelConfig } from '@mastra/core/llm'; -import { priceModelUsageUsd } from '@simple-agent-manager/ai-proxy'; -import { incrementModelUsage } from '@simple-agent-manager/ai-proxy'; -import type { PlatformAIModel, SamConfig } from '@simple-agent-manager/shared'; +import { + filterModelsForAgentLoop, + type PlatformAIModel, + type SamConfig, +} from '@simple-agent-manager/shared'; import { drizzle } from 'drizzle-orm/d1'; import type { Env } from '../../../env'; import { log } from '../../../lib/logger'; import { resolveUpstreamAuth } from '../../../services/ai-billing'; import { incrementProviderUsage, incrementTokenUsage } from '../../../services/ai-token-budget'; -import { estimateTokensFromText } from '../../../services/ai-token-usage-accounting'; import { type ChatCompletionsTarget, chatTargetHeaders, @@ -114,11 +115,29 @@ function chatHeadersWithoutAuth( ); } +/** + * Hierarchy scopes guide harness selection; the account assistant uses the explicit installation + * SAM_MODEL with the shared agent-loop reliability floor and Chat Completions tools. A custom + * endpoint supplies its own model/capabilities independently of this catalog billing entry. + */ +export function assertOperatorModelSupportsTools( + model: PlatformAIModel, + customEndpoint: boolean +): void { + if ( + !customEndpoint && + (filterModelsForAgentLoop([model]).length === 0 || + model.supportsChatCompletionsToolCalls === false) + ) + throw new Error('SAM model must support reliable Chat Completions tool calls'); +} + /** Model quirks live in one explicit boundary (compare `getTaskTitleModelControls`). */ export function operatorProviderOptions(modelId: string) { switch (modelId) { + case '@cf/deepseek-ai/deepseek-v4.1-flash-1017': case '@cf/zai-org/glm-5.3-flash': - // Reasoning cannot be disabled on this model; low effort keeps tool turns responsive. + // Low effort keeps tool turns responsive (DeepSeek otherwise defaults to high). return { [WORKERS_AI_PROVIDER_ID]: { reasoningEffort: 'low' } }; default: return undefined; @@ -133,6 +152,12 @@ interface StepUsageInput { toolCalls: unknown[]; } +/** Bytes/3 over-counts typical English token density, so an estimate errs toward the budget. */ +function estimateTokens(value: unknown): number { + const text = typeof value === 'string' ? value : (JSON.stringify(value ?? '') ?? ''); + return Math.ceil(new TextEncoder().encode(text).byteLength / 3); +} + /** * Charge one model step to the user's AI budget. A provider that omits usage (a streamed * response without a usage chunk) must not make the step free, so missing counts are @@ -143,16 +168,15 @@ export async function recordOperatorStepUsage( userId: string, config: SamConfig, catalogModel: PlatformAIModel, - step: StepUsageInput + step: StepUsageInput, + customEndpoint = false ): Promise { const reportedInput = step.usage.inputTokens; const reportedOutput = step.usage.outputTokens; - const input = reportedInput ?? estimateTokensFromText(step.request.body); + const input = reportedInput ?? estimateTokens(step.request.body); const output = reportedOutput ?? - estimateTokensFromText( - `${step.text}${step.reasoningText ?? ''}${JSON.stringify(step.toolCalls)}` - ); + estimateTokens(`${step.text}${step.reasoningText ?? ''}${JSON.stringify(step.toolCalls)}`); if (reportedInput === undefined || reportedOutput === undefined) log.warn('sam.operator.usage_estimated', { userId, @@ -163,35 +187,29 @@ export async function recordOperatorStepUsage( output, }); const cached = Math.min(input, Math.max(0, step.usage.cachedInputTokens ?? 0)); + const cachedRate = catalogModel.costPer1kCachedInputTokens ?? catalogModel.costPer1kInputTokens; const anthropic = config.model.startsWith('claude-'); - const costUsd = priceModelUsageUsd(catalogModel, { - inputTokens: input, - outputTokens: output, - cachedInputTokens: cached, - }); + const providerId = anthropic ? 'anthropic' : 'workers-ai'; + const providerName = anthropic ? 'Anthropic' : 'Cloudflare Workers AI'; await incrementTokenUsage(env.KV, userId, input, output, env); await incrementProviderUsage( env.KV, userId, { - providerId: anthropic ? 'anthropic' : 'workers-ai', - providerName: anthropic ? 'Anthropic' : 'Cloudflare Workers AI', - dialect: anthropic ? 'anthropic' : 'openai', + providerId: customEndpoint ? 'openai-compatible' : providerId, + providerName: customEndpoint ? 'OpenAI-compatible endpoint' : providerName, + dialect: !customEndpoint && anthropic ? 'anthropic' : 'openai', }, input, output, env, - costUsd + customEndpoint + ? 0 + : ((input - cached) * catalogModel.costPer1kInputTokens + + cached * cachedRate + + output * catalogModel.costPer1kOutputTokens) / + 1000, + // Per-model breakdown only where SAM's own record is the spend record (ai-model-usage.ts). + !customEndpoint && hasLocalAiCostMetering(env) ? catalogModel.id : undefined ); - if (hasLocalAiCostMetering(env)) { - await incrementModelUsage( - env, - userId, - config.model, - anthropic ? 'anthropic' : 'workers-ai', - input, - output, - costUsd - ); - } } diff --git a/apps/api/src/durable-objects/sam-session/tools/cancel-mission.ts b/apps/api/src/durable-objects/sam-session/tools/cancel-mission.ts index 9ed0129c7f..600a4535a0 100644 --- a/apps/api/src/durable-objects/sam-session/tools/cancel-mission.ts +++ b/apps/api/src/durable-objects/sam-session/tools/cancel-mission.ts @@ -16,7 +16,7 @@ import type { AnthropicToolDef, ToolContext } from '../types'; export const cancelMissionDef: AnthropicToolDef = { name: 'cancel_mission', description: - 'Cancel a running mission and mark all its pending tasks as cancelled. ' + + 'Request cancellation of a mission and its pending tasks. Check mission status for completion. ' + 'Running tasks are NOT automatically stopped — use stop_subtask for those individually.', input_schema: { type: 'object', @@ -32,7 +32,7 @@ export const cancelMissionDef: AnthropicToolDef = { export async function cancelMission( input: { missionId: string }, - ctx: ToolContext, + ctx: ToolContext ): Promise { if (!input.missionId?.trim()) { return { error: 'missionId is required.' }; @@ -52,12 +52,7 @@ export async function cancelMission( }) .from(schema.missions) .innerJoin(schema.projects, eq(schema.missions.projectId, schema.projects.id)) - .where( - and( - eq(schema.missions.id, missionId), - eq(schema.projects.userId, ctx.userId), - ), - ) + .where(and(eq(schema.missions.id, missionId), eq(schema.projects.userId, ctx.userId))) .limit(1); const mission = rows[0]; @@ -70,11 +65,12 @@ export async function cancelMission( return { error: 'Mission could not be cancelled — it may already be in a terminal state.' }; } - log.info('sam.cancel_mission.completed', { missionId, projectId: mission.projectId }); + log.info('sam.cancel_mission.requested', { missionId, projectId: mission.projectId }); return { - cancelled: true, + cancellationRequested: true, + status: 'cancellation_requested', missionId, - message: `Mission '${mission.title || missionId}' has been cancelled. Note: already-running tasks continue until explicitly stopped.`, + message: `Mission '${mission.title || missionId}' cancellation has been requested. Already-running processes may require stop_subtask.`, }; } diff --git a/apps/api/src/durable-objects/sam-session/tools/dispatch-task-storage.ts b/apps/api/src/durable-objects/sam-session/tools/dispatch-task-storage.ts new file mode 100644 index 0000000000..fc70a4412f --- /dev/null +++ b/apps/api/src/durable-objects/sam-session/tools/dispatch-task-storage.ts @@ -0,0 +1,34 @@ +/** Task persistence for the SAM dispatch tool; runtime startup stays with the caller. */ +import type { Env } from '../../../env'; +import { + CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS, + CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS, +} from '../../../services/capacity-placement-snapshot'; + +export function insertSamDispatchedTask( + env: Env, + values: unknown[], + mission: { id: string | null; projectId: string } +): Promise { + return env.DATABASE.prepare( + `INSERT INTO tasks (id, project_id, user_id, parent_task_id, chat_session_id, title, description, + status, execution_step, priority, dispatch_depth, output_branch, created_by, + task_mode, agent_profile_hint, skill_id, skill_hint, mission_id, triggered_by, + requested_vm_size, requested_vm_size_source, resource_requirements_json, resource_requirement_plan_json, resource_requirements_source, resolved_reservation_json, + credential_attribution_user_id, credential_attribution_project_id, credential_attribution_source, + ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS}, + created_at, updated_at) + SELECT ?, ?, ?, ?, ?, ?, ?, 'queued', 'node_selection', ?, ?, ?, ?, + ?, ?, ?, ?, ?, 'mcp', + ?, ?, ?, ?, ?, ?, + ?, ?, ?, + ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS}, + ?, ? + WHERE (? IS NULL OR EXISTS ( + SELECT 1 FROM missions WHERE id = ? AND project_id = ? + AND status NOT IN ('cancelled', 'completed', 'failed') + ))` + ) + .bind(...values, mission.id, mission.id, mission.projectId) + .run(); +} diff --git a/apps/api/src/durable-objects/sam-session/tools/dispatch-task.ts b/apps/api/src/durable-objects/sam-session/tools/dispatch-task.ts index fa39165f00..7cc6d28871 100644 --- a/apps/api/src/durable-objects/sam-session/tools/dispatch-task.ts +++ b/apps/api/src/durable-objects/sam-session/tools/dispatch-task.ts @@ -34,11 +34,7 @@ import { requireProjectCapability } from '../../../middleware/project-auth'; import { requireRepositoryOwnerAccess } from '../../../routes/projects/_helpers'; import { samAssistantAttribution } from '../../../services/agent-authorship'; import { generateBranchName } from '../../../services/branch-name'; -import { - CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS, - CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS, - capacityPlacementSnapshotSqlValues, -} from '../../../services/capacity-placement-snapshot'; +import { capacityPlacementSnapshotSqlValues } from '../../../services/capacity-placement-snapshot'; import { resolveTaskStartPlacementCredentialAttribution } from '../../../services/placement-resolver'; import { resolveProjectAgentDefault } from '../../../services/project-agent-defaults'; import * as projectDataService from '../../../services/project-data'; @@ -47,6 +43,7 @@ import { markTaskFailedIfNonTerminal } from '../../../services/task-failure'; import { startTaskRunnerDO } from '../../../services/task-runner-do'; import { generateTaskTitle, getTaskTitleConfig } from '../../../services/task-title'; import type { AnthropicToolDef, ToolContext } from '../types'; +import { insertSamDispatchedTask } from './dispatch-task-storage'; const VALID_TASK_MODES: TaskMode[] = ['task', 'conversation']; const VALID_WORKSPACE_PROFILES: WorkspaceProfile[] = ['full', 'lightweight']; @@ -389,23 +386,10 @@ export async function dispatchTask(input: DispatchTaskInput, ctx: ToolContext): const now = new Date().toISOString(); - // ── Insert task ──────────────────────────────────────────────────────── - await env.DATABASE.prepare( - `INSERT INTO tasks (id, project_id, user_id, parent_task_id, chat_session_id, title, description, - status, execution_step, priority, dispatch_depth, output_branch, created_by, - task_mode, agent_profile_hint, skill_id, skill_hint, mission_id, triggered_by, - requested_vm_size, requested_vm_size_source, resource_requirements_json, resource_requirement_plan_json, resource_requirements_source, resolved_reservation_json, - credential_attribution_user_id, credential_attribution_project_id, credential_attribution_source, - ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS}, - created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', 'node_selection', ?, ?, ?, ?, - ?, ?, ?, ?, ?, 'mcp', - ?, ?, ?, ?, ?, ?, - ?, ?, ?, - ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS}, - ?, ?)` - ) - .bind( + // Task persistence is separate from placement and runtime startup. + const inserted = await insertSamDispatchedTask( + env, + [ taskId, input.projectId, ctx.userId, @@ -433,9 +417,12 @@ export async function dispatchTask(input: DispatchTaskInput, ctx: ToolContext): credentialAttributionSource, ...capacityPlacementSnapshotSqlValues(capacityPlacementSnapshot), now, - now - ) - .run(); + now, + ], + { id: input.missionId?.trim() || null, projectId: input.projectId } + ); + + if (!inserted.meta.changes) return { error: 'Mission no longer accepts new tasks' }; // Record status event: null -> queued const statusEventId = ulid(); diff --git a/apps/api/src/durable-objects/sam-session/tools/retry-subtask.ts b/apps/api/src/durable-objects/sam-session/tools/retry-subtask.ts index 06ef3328aa..ee3eca94d0 100644 --- a/apps/api/src/durable-objects/sam-session/tools/retry-subtask.ts +++ b/apps/api/src/durable-objects/sam-session/tools/retry-subtask.ts @@ -22,6 +22,7 @@ import { CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS, capacityPlacementSnapshotSqlValues, } from '../../../services/capacity-placement-snapshot'; +import { resolveSystemErrorFor } from '../../../services/inbox/system-error-resolve'; import { resolveTaskStartPlacementCredentialAttribution } from '../../../services/placement-resolver'; import { resolveProjectAgentDefault } from '../../../services/project-agent-defaults'; import * as projectDataService from '../../../services/project-data'; @@ -245,7 +246,7 @@ export async function retrySubtask( const now = new Date().toISOString(); // Insert new task + status event (batched for atomicity) - await env.DATABASE.batch([ + const [inserted] = await env.DATABASE.batch([ env.DATABASE.prepare( // triggered_by 'mcp' like dispatch_task: the agent started this, not the person, so it // must not count as their own new chat (e.g. the new-chat profile picker's recents). @@ -256,12 +257,16 @@ export async function retrySubtask( credential_attribution_user_id, credential_attribution_project_id, credential_attribution_source, ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS}, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, 'queued', 'node_selection', 0, 0, ?, ?, + SELECT ?, ?, ?, ?, ?, ?, 'queued', 'node_selection', 0, 0, ?, ?, ?, ?, ?, ?, ?, ?, 'mcp', ?, ?, ?, ?, ?, ?, ?, ?, ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS}, - ?, ?)` + ?, ? + WHERE (? IS NULL OR EXISTS ( + SELECT 1 FROM missions WHERE id = ? AND project_id = ? + AND status NOT IN ('cancelled', 'completed', 'failed') + ))` ).bind( newTaskId, original.projectId, @@ -287,15 +292,20 @@ export async function retrySubtask( resolvedCredentialAttributionSource, ...capacityPlacementSnapshotSqlValues(capacityPlacementSnapshot), now, - now + now, + original.missionId ?? null, + original.missionId ?? null, + original.projectId ), env.DATABASE.prepare( `INSERT INTO task_status_events (id, task_id, from_status, to_status, actor_type, actor_id, reason, created_at) - VALUES (?, ?, NULL, 'queued', 'user', ?, ?, ?)` - ).bind(ulid(), newTaskId, ctx.userId, `Retry of task ${taskId} via SAM`, now), + SELECT ?, ?, NULL, 'queued', 'user', ?, ?, ? WHERE EXISTS (SELECT 1 FROM tasks WHERE id = ?)` + ).bind(ulid(), newTaskId, ctx.userId, `Retry of task ${taskId} via SAM`, now, newTaskId), ]); + if (!inserted?.meta.changes) return { error: 'Mission no longer accepts retried tasks' }; + // Create chat session let sessionId: string; try { @@ -406,6 +416,15 @@ export async function retrySubtask( const appDomain = `app.${env.BASE_DOMAIN}`; const taskUrl = `https://${appDomain}/projects/${original.projectId}/ideas/${newTaskId}`; + // The retry worked: the original task's inbox error item closes (slice E). Never throws. + await resolveSystemErrorFor(env, { + projectId: original.projectId, + source: 'task', + subjectId: taskId, + resolution: 'retried', + resolvedByUserId: ctx.userId, + }); + log.info('sam.retry_subtask.created', { originalTaskId: taskId, newTaskId, diff --git a/apps/api/src/durable-objects/sam-session/tools/stop-subtask.ts b/apps/api/src/durable-objects/sam-session/tools/stop-subtask.ts index 0e4c4c6507..c98880a030 100644 --- a/apps/api/src/durable-objects/sam-session/tools/stop-subtask.ts +++ b/apps/api/src/durable-objects/sam-session/tools/stop-subtask.ts @@ -13,6 +13,8 @@ import { log } from '../../../lib/logger'; import { ulid } from '../../../lib/ulid'; import { stopAgentSessionOnNode } from '../../../services/node-agent'; import { isSleepingContainerNode } from '../../../services/sleeping-container-runtime'; +import { retireTaskCancellationPrompts } from '../../../services/task-cancellation-prompts'; +import { taskRecoveryCancellationStatement } from '../../../services/task-recovery-cancellation'; import { WAKEABLE_TASK_STATUSES } from '../../../services/task-status'; import { cleanupTerminalTaskResources } from '../../../services/task-terminal-cleanup'; import { syncTriggerExecutionStatus } from '../../../services/trigger-execution-sync'; @@ -50,17 +52,26 @@ type Db = ReturnType>; */ async function cancelTaskWithCas( env: Env, - task: { status: string }, + task: { + id: string; + status: string; + projectId: string; + userId: string; + chatSessionId: string | null; + workspaceId: string | null; + }, taskId: string, userId: string ): Promise<'cancelled' | 'lost_race' | 'error'> { const now = new Date().toISOString(); try { + await retireTaskCancellationPrompts(env, task); const [transition] = await env.DATABASE.batch([ env.DATABASE.prepare( `UPDATE tasks SET status = 'cancelled', error_message = 'Stopped by user via SAM', updated_at = ?, completed_at = ? - WHERE id = ? AND status = ?` - ).bind(now, now, taskId, task.status), + WHERE id = ? AND project_id = ? AND status = ?` + ).bind(now, now, taskId, task.projectId, task.status), + taskRecoveryCancellationStatement(env.DATABASE, task, now), env.DATABASE.prepare( `INSERT INTO task_status_events (id, task_id, from_status, to_status, actor_type, actor_id, reason, created_at) SELECT ?, ?, ?, 'cancelled', 'user', ?, 'Stopped via SAM', ? @@ -142,6 +153,8 @@ export async function stopSubtask(input: { taskId: string }, ctx: ToolContext): const rows = await db .select({ id: schema.tasks.id, + userId: schema.tasks.userId, + chatSessionId: schema.tasks.chatSessionId, status: schema.tasks.status, workspaceId: schema.tasks.workspaceId, projectId: schema.tasks.projectId, diff --git a/apps/api/src/durable-objects/task-runner/agent-session-step.ts b/apps/api/src/durable-objects/task-runner/agent-session-step.ts index 672eba865d..81334c6785 100644 --- a/apps/api/src/durable-objects/task-runner/agent-session-step.ts +++ b/apps/api/src/durable-objects/task-runner/agent-session-step.ts @@ -4,6 +4,8 @@ * Handles the agent_session step: creating the session, generating MCP token, * and starting the agent with the initial prompt. */ +import { parseProviderLimitWait } from '@simple-agent-manager/scheduler-core'; + import { log } from '../../lib/logger'; import { buildSamBootstrapInstructions, @@ -115,6 +117,13 @@ export async function handleAgentSession( agentSessionId: sessionId, // Dispatch resolves the profile hint to its ID before persisting runner state. agentProfileId: state.config.agentProfileHint, + // A previously claimed runner predates this config field. Its newly + // approved receipt carries the same skill checked at every authority fence. + skillId: + state.config.skillId ?? + parseProviderLimitWait(state.config.providerLimitRecoveryApproval?.receipt)?.ownerOverride + ?.skillId ?? + null, label: buildTaskAgentSessionLabel(state.config.taskTitle), agentType, visibleInitialPrompt: buildVisibleTaskInitialPrompt(state), diff --git a/apps/api/src/durable-objects/task-runner/attempt-storage.ts b/apps/api/src/durable-objects/task-runner/attempt-storage.ts index 4a1a776f9e..257dc208f5 100644 --- a/apps/api/src/durable-objects/task-runner/attempt-storage.ts +++ b/apps/api/src/durable-objects/task-runner/attempt-storage.ts @@ -1,3 +1,4 @@ +import type { ProviderLimitRecoveryApproval } from '../../services/provider-limit-recovery-approval'; import { revokeRecoveryAuthority } from './recovery-revocation'; import type { TaskRunnerState } from './types'; @@ -19,6 +20,11 @@ export async function putTaskRunnerState( const superseded = await storage.transaction(async (transaction) => { const current = await transaction.get('state'); if (current && attemptOf(current) !== attemptOf(state)) return { attempt: attemptOf(current) }; + // Step writers retain state across RPCs. A same-attempt owner nudge is the + // sole approval writer; carry its latest receipt into both storage and the + // caller's live state so later assertions cannot silently forget consent. + if (current?.config.providerLimitRecoveryApproval) + state.config.providerLimitRecoveryApproval = current.config.providerLimitRecoveryApproval; await transaction.put('state', state); if (options.deleteAlarm) await transaction.deleteAlarm(); return null; @@ -84,3 +90,32 @@ export function taskRunnerAttemptContext( }, }); } + +/** Merge consent into the current attempt, never persist the pre-RPC state. */ +export async function persistProviderLimitRecoveryNudge( + storage: DurableObjectStorage, + observed: TaskRunnerState, + approval: ProviderLimitRecoveryApproval +): Promise { + return storage.transaction(async (transaction) => { + const current = await transaction.get('state'); + if ( + !current || + current.completed || + current.currentStep === 'running' || + current.currentStep === 'awaiting_followup' + ) + return false; + if ( + current.taskId !== observed.taskId || + current.projectId !== observed.projectId || + current.userId !== approval.ownerUserId || + attemptOf(current) !== attemptOf(observed) + ) + return false; + current.config.providerLimitRecoveryApproval = approval; + await transaction.put('state', current); + await transaction.setAlarm(Date.now()); + return true; + }); +} diff --git a/apps/api/src/durable-objects/task-runner/boot-recovery.ts b/apps/api/src/durable-objects/task-runner/boot-recovery.ts index e1dd31ebb6..3d89d3775f 100644 --- a/apps/api/src/durable-objects/task-runner/boot-recovery.ts +++ b/apps/api/src/durable-objects/task-runner/boot-recovery.ts @@ -88,6 +88,9 @@ export async function recoverNodeBoot( intent.terminated = true; await rc.ctx.storage.put('state', state); } + // Provider termination can outlive owner cancellation. Persist its proof, then + // re-read executable authority before clearing the failed-node ownership. + await assertTaskExecutionAuthority(rc.env, state); await rc.env.DATABASE.batch([ rc.env.DATABASE.prepare( `UPDATE nodes SET status = 'deleted', cleanup_blocked_since = NULL, cleanup_blocked_reason = NULL, updated_at = ? WHERE runtime_termination_confirmed_at IS NOT NULL AND id = ? AND status = 'destroying'` @@ -103,6 +106,8 @@ export async function recoverNodeBoot( state.admissionLeaseToken, 'node_boot_failed' ); + // Lease release is another I/O boundary; it must not revive a cancelled task. + await assertTaskExecutionAuthority(rc.env, state); state.admissionScopeKey = null; state.admissionLeaseToken = null; state.stepResults.nodeId = null; diff --git a/apps/api/src/durable-objects/task-runner/index.ts b/apps/api/src/durable-objects/task-runner/index.ts index 7ebbe1b253..26f9536c65 100644 --- a/apps/api/src/durable-objects/task-runner/index.ts +++ b/apps/api/src/durable-objects/task-runner/index.ts @@ -45,9 +45,17 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { deferAlarmWhenDisabled } from '../../services/operational-kill-switch'; import { capacityPlacementSnapshotForTaskStart } from '../../services/placement-resolver'; +import { + type ProviderLimitRecoveryApproval, + providerLimitRecoveryApprovalIsCurrent, +} from '../../services/provider-limit-recovery-approval'; import { SessionRecoveryAuthorityRevokedError } from '../../services/session-recovery-authority'; import { handleAgentSession } from './agent-session-step'; -import { putTaskRunnerState, taskRunnerAttemptContext } from './attempt-storage'; +import { + persistProviderLimitRecoveryNudge, + putTaskRunnerState, + taskRunnerAttemptContext, +} from './attempt-storage'; import { computeBackoffMs, isTransientError, parseEnvInt } from './helpers'; import { handleNodeAgentReady, handleNodeProvisioning, handleNodeSelection } from './node-steps'; import { recordRunnerPhase } from './phase-timings'; @@ -345,12 +353,26 @@ export class TaskRunner extends DurableObject { * Pull a non-terminal runner's alarm forward after external capacity changes. * Used by VM admission wakeups; safe to call repeatedly. */ - async nudge(reason?: string): Promise { + async nudge(reason?: string, approval?: ProviderLimitRecoveryApproval): Promise { const state = await this.getState(); if (!state || state.completed) return false; if (state.currentStep === 'running' || state.currentStep === 'awaiting_followup') { return false; } + if (approval) { + if ( + !(await providerLimitRecoveryApprovalIsCurrent( + this.env, + state.taskId, + state.projectId, + approval + )) + ) + return false; + if (!state.config.recoveryAttemptId || !(await this.isCurrentRecoveryAttempt(state))) + return false; + return persistProviderLimitRecoveryNudge(this.ctx.storage, state, approval); + } await this.ctx.storage.setAlarm(Date.now()); log.info('task_runner_do.nudged', { taskId: state.taskId, diff --git a/apps/api/src/durable-objects/task-runner/node-steps.ts b/apps/api/src/durable-objects/task-runner/node-steps.ts index da24236d06..65f4f530a8 100644 --- a/apps/api/src/durable-objects/task-runner/node-steps.ts +++ b/apps/api/src/durable-objects/task-runner/node-steps.ts @@ -5,12 +5,13 @@ * `node_agent_ready` in `./node-agent-ready-step`; both are re-exported here so * the DO's step table keeps one import site. See rule 18. */ -import { - resolveEffectiveNodeHostMemoryReserveMb, -} from '@simple-agent-manager/scheduler-core'; +import { resolveEffectiveNodeHostMemoryReserveMb } from '@simple-agent-manager/scheduler-core'; import { log } from '../../lib/logger'; -import { isNodeAgentVersionCompatible } from '../../services/node-agent-compatibility'; +import { + isNodeAgentVersionCompatible, + normalizeAgentVersion, +} from '../../services/node-agent-compatibility'; import { type CapacityAwareNodePlacementRow, capacityPoolNoCandidatesError, @@ -18,9 +19,7 @@ import { resolveReusableNodeCapacitySnapshot, } from '../../services/placement-resolver'; import { filterReusableNodesByCurrentAuthority } from '../../services/reusable-node-authority'; -import { - trustedWorkspaceNodeCapacityColumnsSql, -} from '../../services/workspace-admission-sql'; +import { trustedWorkspaceNodeCapacityColumnsSql } from '../../services/workspace-admission-sql'; import { shouldProvisionSpreadNode } from './capacity-pool-node-limit'; import { findNodeWithCapacity, @@ -108,7 +107,8 @@ export async function handleNodeSelection( placement_explanation_json AS placementExplanationJson, last_metrics AS lastMetrics, last_heartbeat_at AS lastHeartbeatAt, - agent_version AS agentVersion + agent_version AS agentVersion, + agent_ready_at AS agentReadyAt FROM nodes WHERE id = ? AND user_id = ?` ) .bind(state.config.preferredNodeId, state.userId) @@ -117,23 +117,66 @@ export async function handleNodeSelection( id: string; status: string; agentVersion: string | null; + agentReadyAt: string | null; }) | null >(); - if (!node || node.status !== 'running') { + if (!node || !['creating', 'running'].includes(node.status)) { throw Object.assign(new Error('Specified node is not available'), { permanent: true }); } + // Missing version is boot progress, not evidence of a different build. Keep + // the shared compatibility predicate strict for reuse, dispatch and cleanup. + const agentVersion = normalizeAgentVersion(node.agentVersion); + if ( + agentVersion && + !isNodeAgentVersionCompatible(agentVersion, rc.env.VM_AGENT_REQUIRED_VERSION) + ) { + throw Object.assign( + new Error('Specified node agent build differs from the required VM agent build'), + { permanent: true } + ); + } + const waitingForVersion = + !agentVersion && !!normalizeAgentVersion(rc.env.VM_AGENT_REQUIRED_VERSION); + const awaitingReadiness = node.status === 'creating' || !node.agentReadyAt || waitingForVersion; + if (awaitingReadiness || state.agentReadyStartedAt !== null) { + // Stay in selection: each alarm must revalidate ownership, placement and + // reservation capacity before adopting a user-pinned node. Never replace it. + state.agentReadyStartedAt ??= Date.now(); + const deadline = state.agentReadyStartedAt + rc.getAgentReadyTimeoutMs(); + let reason = 'agent readiness deadline exceeded'; + if (waitingForVersion) { + reason = 'agent has not reported a version yet'; + } else if (awaitingReadiness) { + reason = 'agent has not become ready yet'; + } + // The callback timestamp is server-assigned. A delayed alarm must not + // reject readiness that arrived on time; current version/admission checks still apply. + const readyAt = node.agentReadyAt ? Date.parse(node.agentReadyAt) : Number.NaN; + const readyByDeadline = !awaitingReadiness && Number.isFinite(readyAt) && readyAt <= deadline; + if (Date.now() >= deadline && !readyByDeadline) { + throw Object.assign(new Error(`Specified node not ready by deadline: ${reason}`), { + permanent: true, + }); + } + if (awaitingReadiness) { + log.info('task_runner_do.preferred_node_waiting', { + taskId: state.taskId, + nodeId: node.id, + reason, + deadline, + }); + await rc.ctx.storage.put('state', state); + await rc.ctx.storage.setAlarm(Math.min(deadline, Date.now() + rc.getAgentPollIntervalMs())); + return; + } + } if (!nodeSatisfiesTaskResources(node, state)) { throw Object.assign(new Error('Specified node does not satisfy the requested resources'), { permanent: true, }); } - if (!isNodeAgentVersionCompatible(node.agentVersion, rc.env.VM_AGENT_REQUIRED_VERSION)) { - throw Object.assign(new Error('Specified node is running an incompatible VM agent build'), { - permanent: true, - }); - } if (!(await hasReusableNodeReservationCapacity(rc, state, node))) { throw Object.assign( new Error('Specified node lacks aggregate reservation capacity or fresh safe telemetry'), diff --git a/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts b/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts index d93faee1c0..4c99f171e4 100644 --- a/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts +++ b/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts @@ -110,19 +110,37 @@ export async function holdTaskForProviderLimit( // 01M73WJGGD2TZP6XDFHJJWHD33). It covers only the exact, non-null credential it was granted // for: any other selection falls through to the checks below and blocks for review. A real // provider rejection later builds a fresh wait without the override and parks as usual. + const approval = previous?.ownerOverride; + const approvalScopeChanged = + approval?.expiresAt !== undefined && + (approval.expiresAt <= now || + approval.profileId !== (row?.agent_profile_hint ?? null) || + approval.skillId !== (row?.skill_id ?? null) || + (approval.runConfigurationId ?? null) !== (row?.agent_configuration_id ?? null) || + approval.agentType !== + (state.config.agentType || rc.env.DEFAULT_TASK_AGENT_TYPE || 'opencode') || + (approval.profileId !== null && profile?.profileId !== approval.profileId) || + (profile !== null && profile.agentType !== null && profile.agentType !== approval.agentType)); if ( key !== null && previous?.phase === 'released' && - previous.ownerOverride?.credentialKey === key + approval?.credentialKey === key && + !approvalScopeChanged ) return false; const window = await rejectedProviderWindow(rc.env, reference, now); let wait = previous; - if (!ownerResumed && previous?.credentialKey && previous.credentialKey !== key) { + if ( + previous && + (approvalScopeChanged || + (!ownerResumed && previous.credentialKey && previous.credentialKey !== key)) + ) { wait = { ...previous, phase: 'blocked', - reason: 'Blocked: selected provider credential changed; review before resuming.', // A blocked wait needs fresh review; an earlier start-anyway must not carry over. + reason: approvalScopeChanged + ? 'Blocked: provider resume approval expired or the selected profile changed; review before resuming.' + : 'Blocked: selected provider credential changed; review before resuming.', // A blocked wait needs fresh review; an earlier start-anyway must not carry over. ownerOverride: undefined, }; } else if (previous?.phase === 'blocked') { @@ -164,8 +182,11 @@ export async function holdTaskForProviderLimit( } else if (!window) { if (previous && (previous.phase !== 'released' || ownerResumed)) { await rc.assertRecoveryAuthority(state); + // The queued watchdog measures runnable orchestration time. A deliberate + // provider wait is outside that interval; release starts a fresh clock. + // Its terminal CAS also checks this timestamp, fencing an earlier scan. const released = await rc.env.DATABASE.prepare( - `UPDATE tasks SET provider_limit_wait_json = ?, admission_state = NULL, admission_reason = NULL, admission_next_retry_at = NULL + `UPDATE tasks SET provider_limit_wait_json = ?, admission_state = NULL, admission_reason = NULL, admission_next_retry_at = NULL, updated_at = ? WHERE id = ? AND provider_limit_wait_json IS ?` ) .bind( @@ -181,6 +202,7 @@ export async function holdTaskForProviderLimit( } : {}), }), + new Date(now).toISOString(), state.taskId, row?.provider_limit_wait_json ?? null ) diff --git a/apps/api/src/durable-objects/task-runner/recovery-authority.ts b/apps/api/src/durable-objects/task-runner/recovery-authority.ts index 13731badfd..d30037097e 100644 --- a/apps/api/src/durable-objects/task-runner/recovery-authority.ts +++ b/apps/api/src/durable-objects/task-runner/recovery-authority.ts @@ -7,7 +7,13 @@ * source task and any project-event wake still authorize it. Every refusal names * the check that failed and logs it with the snapshot claim (`recovery-revocation.ts`). */ +import { parseProviderLimitWait } from '@simple-agent-manager/scheduler-core'; + import type { Env } from '../../env'; +import { + loadProviderLimitRecoveryApproval, + providerLimitRecoveryApprovalIsCurrent, +} from '../../services/provider-limit-recovery-approval'; import { assertReplacementDeletionConfirmed } from '../../services/replacement-deletion-fence'; import { findSessionRecoveryTaskAndEventAuthorityFailure, @@ -35,13 +41,20 @@ type RecoveryAttemptFailure = Extract< async function findRecoveryAttemptFailure( env: Env, ctx: DurableObjectState, - input: StartTaskInput | TaskRunnerState + input: StartTaskInput | TaskRunnerState, + persistedState?: TaskRunnerState | null ): Promise { if ('stepResults' in input) { - const persisted = await ctx.storage.get('state'); + const persisted = + persistedState === undefined + ? await ctx.storage.get('state') + : persistedState; if ( persisted && - (persisted.config.recoveryAttemptId ?? null) !== (input.config.recoveryAttemptId ?? null) + (persisted.taskId !== input.taskId || + persisted.projectId !== input.projectId || + persisted.userId !== input.userId || + (persisted.config.recoveryAttemptId ?? null) !== (input.config.recoveryAttemptId ?? null)) ) return 'runner_attempt_superseded'; } @@ -83,8 +96,76 @@ export async function findRecoveryAuthorityFailure( ctx: DurableObjectState, input: StartTaskInput | TaskRunnerState ): Promise { - const attemptFailure = await findRecoveryAttemptFailure(env, ctx, input); + const persisted = 'stepResults' in input ? await ctx.storage.get('state') : null; + const attemptFailure = await findRecoveryAttemptFailure(env, ctx, input, persisted ?? null); if (attemptFailure) return attemptFailure; + // A nudge can install consent while this step is awaiting an external call. + // The captured input must not erase or bypass the same-attempt stored guard. + const approval = + persisted?.config.providerLimitRecoveryApproval ?? input.config.providerLimitRecoveryApproval; + if ( + approval && + !(await providerLimitRecoveryApprovalIsCurrent( + env, + input.taskId, + input.projectId, + approval, + true + )) + ) + return 'recovery_task_authority'; + // Owner force-resume can approve a previously unguarded human-message wake. + // Keep its existing claim, while making that approval revocable at every + // external runner boundary rather than only when the owner clicked. + // Only snapshot-restoration runners can receive this consent. Ordinary + // runners add no task read; an installed approval already checks membership + // and the complete current receipt in the shared SQL fence above. + const ownerApproval = + !approval && input.config.resumeSnapshotChatSessionId + ? await env.DATABASE.prepare( + `SELECT t.provider_limit_wait_json, + EXISTS (SELECT 1 FROM project_members m JOIN users u ON u.id=m.user_id + WHERE m.project_id=t.project_id AND m.user_id=t.user_id AND m.status='active' + AND m.role IN ('owner','admin','maintainer') AND u.status='active') AS member_active + FROM tasks t WHERE t.id=? AND t.project_id=? AND t.user_id=? + AND json_valid(t.provider_limit_wait_json) + AND json_type(t.provider_limit_wait_json,'$.ownerOverride.expiresAt')='integer'` + ) + .bind(input.taskId, input.projectId, input.userId) + .first<{ provider_limit_wait_json: string; member_active: number }>() + : null; + if ( + ownerApproval && + !ownerApproval.member_active && + parseProviderLimitWait(ownerApproval.provider_limit_wait_json)?.ownerOverride + ) + return 'recovery_task_authority'; + // The same live state is used by bootstrap and its legacy skill fallback. + if (approval) input.config.providerLimitRecoveryApproval = approval; + // The owner CAS may commit before the nudge reaches this runner. Reconstruct + // that live scoped guard rather than treating an old unguarded state as consent. + if (!approval && ownerApproval) { + const wait = parseProviderLimitWait(ownerApproval.provider_limit_wait_json); + if (wait?.ownerOverride?.ownerUserId && wait.ownerOverride.snapshotId) { + const liveApproval = await loadProviderLimitRecoveryApproval( + env, + input.taskId, + ownerApproval.provider_limit_wait_json + ); + if ( + !liveApproval || + !(await providerLimitRecoveryApprovalIsCurrent( + env, + input.taskId, + input.projectId, + liveApproval, + true + )) + ) + return 'recovery_task_authority'; + input.config.providerLimitRecoveryApproval = liveApproval; + } + } const sourceTaskId = input.config.recoverySourceTaskId ?? null; const chatSessionId = input.config.resumeSnapshotChatSessionId ?? null; // A human follow-up may recover a completed conversation without a live diff --git a/apps/api/src/durable-objects/task-runner/types.ts b/apps/api/src/durable-objects/task-runner/types.ts index 129eb6103e..d27ae6fd49 100644 --- a/apps/api/src/durable-objects/task-runner/types.ts +++ b/apps/api/src/durable-objects/task-runner/types.ts @@ -22,6 +22,7 @@ import type { import type { Env } from '../../env'; import type { TaskStartCapacityPoolSelection } from '../../services/placement-resolver'; +import type { ProviderLimitRecoveryApproval } from '../../services/provider-limit-recovery-approval'; import type { ProjectEventWakeRecoveryGuard } from '../../services/session-recovery-authority'; import type { TaskRunnerStartGuard } from '../../services/task-runner-start-guard'; @@ -134,6 +135,8 @@ export interface TaskRunConfig { systemPromptAppend: string | null; /** Agent profile ID — stored on workspace for GitHub CLI policy enforcement. */ agentProfileHint: string | null; + /** Saved skill identity; optional for runners persisted before skill propagation. */ + skillId?: string | null; /** File attachments uploaded to R2 before task submission. Null = no attachments. */ attachments: TaskAttachment[] | null; /** Per-project scaling overrides. Null values mean "use platform default". */ @@ -182,6 +185,7 @@ export interface TaskRunConfig { projectEventWakeGuard?: ProjectEventWakeRecoveryGuard | null; /** Member whose continued write permission authorizes a scheduled wake. */ recoveryRequiredProjectMemberId?: string | null; + providerLimitRecoveryApproval?: ProviderLimitRecoveryApproval | null; } export interface TaskRunnerState { diff --git a/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts b/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts index 5ab07bf550..dcbc669a24 100644 --- a/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts +++ b/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts @@ -11,7 +11,7 @@ import type { TaskRunnerContext, TaskRunnerState } from './types'; type TaskRunnerProjectRepo = { repoProvider: string | null; - repository?: string | null; + repository: string; }; async function loadTaskRunnerProjectRepo( @@ -41,7 +41,7 @@ async function createWorkspaceOnVmAgent( const gitSource = await resolveWorkspaceGitSource(drizzle(rc.env.DATABASE, { schema }), { id: state.projectId, repoProvider: projectRepo?.repoProvider ?? 'github', - ...(projectRepo?.repository ? { repository: projectRepo.repository } : {}), + repository: projectRepo?.repository ?? state.config.repository, }); const checkoutBranch = state.config.outputBranch || state.config.branch; const baseBranch = diff --git a/apps/api/src/durable-objects/user-access-token-lock.ts b/apps/api/src/durable-objects/user-access-token-lock.ts index ce8664137f..b059c5d3e6 100644 --- a/apps/api/src/durable-objects/user-access-token-lock.ts +++ b/apps/api/src/durable-objects/user-access-token-lock.ts @@ -186,7 +186,9 @@ export abstract class UserAccessTokenLock extends DurableObject { userId: payload.userId, error: err instanceof Error ? err.message : String(err), }); - return Response.json({ error: 'token_unavailable' }, { status: 401 }); + const authError = err instanceof Error && 'statusCode' in err ? err.statusCode : undefined; + // Unknown failures and upstream outages cannot prove authorization expired. + return Response.json({ error: 'token_unavailable' }, { status: authError === 401 ? 401 : 503 }); } } } diff --git a/apps/api/src/durable-objects/vm-agent-container-runtime.ts b/apps/api/src/durable-objects/vm-agent-container-runtime.ts index ee1dffa95a..972a8aeb9b 100644 --- a/apps/api/src/durable-objects/vm-agent-container-runtime.ts +++ b/apps/api/src/durable-objects/vm-agent-container-runtime.ts @@ -98,6 +98,7 @@ export async function probeLiveRuntimeSession(input: { ); const response = await input.containerFetch( new Request(url.toString(), { + redirect: 'manual', headers: { Authorization: `Bearer ${token}`, 'X-SAM-Node-Id': input.nodeId, diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index 10dbc5f443..e0c0f4bcc2 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -1285,8 +1285,6 @@ export interface Env ANALYTICS_DEFAULT_PERIOD_DAYS?: string; // Default query period (default: 30) ANALYTICS_DATASET?: string; // Dataset name (set by deployment from resource prefix) ANALYTICS_TOP_EVENTS_LIMIT?: string; // Max events in top events query (default: 50) - ANALYTICS_GEO_LIMIT?: string; // Max countries in geo distribution (default: 50) - ANALYTICS_RETENTION_WEEKS?: string; // Retention cohort lookback weeks (default: 12) ANALYTICS_WEBSITE_TRAFFIC_TOP_PAGES_LIMIT?: string; // Max top pages per section in website traffic (default: 20) // Analytics ingest endpoint (Phase 2 — client-side events) ANALYTICS_INGEST_ENABLED?: string; // "true" (default) or "false" @@ -1431,7 +1429,6 @@ export interface Env AI_PROXY_RATE_LIMIT_WINDOW_SECONDS?: string; // Rate limit window in seconds (default: 60) // Cost Monitoring COST_MONITORING_ENABLED?: string; // Enable/disable cost monitoring endpoint (default: true) - COMPUTE_VCPU_HOUR_COST_USD?: string; // Estimated cost per vCPU-hour in USD (default: 0.003) /** Deployment environment name ("staging" | "production"), set by the deploy pipeline. */ ENVIRONMENT?: string; // Cloudflare Artifacts (GitHub-optional project creation) @@ -1449,7 +1446,7 @@ export interface Env /** Max changed files returned by an Artifacts compare before truncating (default: 300). */ REPO_BROWSE_MAX_COMPARE_FILES?: string; // SAM Agent (Top-Level Agent) configuration - SAM_MODEL?: string; // LLM model (default: claude-sonnet-5) + SAM_MODEL?: string; // LLM model (default: @cf/deepseek-ai/deepseek-v4.1-flash-1017) SAM_MAX_TOKENS?: string; // Max output tokens per turn (default: 4096) SAM_MAX_TURNS?: string; // Max tool-use loop iterations (default: 20) SAM_SYSTEM_PROMPT_APPEND?: string; // Additional system prompt text diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 08a11c815d..226ef73b31 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -59,6 +59,7 @@ import { adminCcBackfillRoutes } from './routes/admin-cc-backfill'; import { adminCostRoutes } from './routes/admin-costs'; import { adminGithubInstallationLeakSweepRoutes } from './routes/admin-github-installation-leak-sweep'; import { adminGithubRepoIdBackfillRoutes } from './routes/admin-github-repo-id-backfill'; +import { adminHealthCostRoutes } from './routes/admin-health-cost'; import { adminOperationsApprovalRoutes } from './routes/admin-operations-approvals'; import { adminPlatformConfigRoutes } from './routes/admin-platform-config'; import { adminPlatformCredentialRoutes } from './routes/admin-platform-credentials'; @@ -80,6 +81,7 @@ import { aiProxyAnthropicRoutes } from './routes/ai-proxy-anthropic'; import { aiProxyPassthroughRoutes } from './routes/ai-proxy-passthrough'; import { analyticsIngestRoutes } from './routes/analytics-ingest'; import { apiTokenRoutes } from './routes/api-tokens'; +import { artifactsConfigRoutes } from './routes/artifacts-config'; import { authRoutes } from './routes/auth'; import { bootstrapRoutes } from './routes/bootstrap'; import { cachedCommandRoutes } from './routes/cached-commands'; @@ -114,6 +116,7 @@ import { googleAuthRoutes } from './routes/google-auth'; import { ideaUpdateRoutes } from './routes/idea-updates'; import { ideaRoutes } from './routes/ideas'; import { inboxRoutes, projectInboxRoutes } from './routes/inbox'; +import { projectInboxTaskRoutes } from './routes/inbox-tasks'; import { handleInteractivePreviewRequest, isInteractivePreviewRequest, @@ -132,6 +135,7 @@ import { nodesRoutes } from './routes/nodes'; import { notificationRoutes } from './routes/notifications'; import { observabilityIngestRoutes } from './routes/observability-ingest'; import { orchestratorRoutes } from './routes/orchestrator'; +import { platformCapabilitiesRoutes } from './routes/platform-capabilities'; import { policyRoutes } from './routes/policies'; import { profileRuntimeRoutes } from './routes/profile-runtime'; import { projectAgentRoutes } from './routes/project-agent'; @@ -163,7 +167,6 @@ import { reportIssueRoutes } from './routes/report-issue'; import { resolutionStatusRoute } from './routes/resolution-status'; import { resourceLinkRoutes } from './routes/resource-links'; import { samRoutes } from './routes/sam'; -import { createSelfHostGatewayRoutes } from './routes/self-host-gateway'; import { setupRoutes } from './routes/setup'; import { skillRuntimeRoutes } from './routes/skill-runtime'; import { skillRoutes } from './routes/skills'; @@ -184,8 +187,6 @@ import { scheduled } from './scheduled/handler'; import { handleInboundAgentEmail } from './services/agent-email/inbound'; import { agentEmailConfig } from './services/agent-email/setup-state'; import { isAgentSignInEnabled } from './services/agent-sign-in/config'; -import { isArtifactsAvailable } from './services/platform-capabilities'; -import { resolvePublicPlatformCapabilities } from './services/speech-endpoints'; import { isInstantRuntimeAvailable } from './services/vm-agent-container'; // Global error handler — catches errors from all routes including subrouters. @@ -278,17 +279,9 @@ app.get('/health', (c) => { }); // Public config — exposes feature flags the UI needs before auth -app.get('/api/config/artifacts-enabled', (c) => { - applyCacheHeaders(c, 'public-config'); - return c.json({ enabled: isArtifactsAvailable(c.env) }); -}); +app.route('/api/config', artifactsConfigRoutes); -// Public config — which platform services this installation has, so the UI can hide entry -// points that cannot work here (services/platform-capabilities.ts). Booleans only. -app.get('/api/config/platform-capabilities', async (c) => { - applyCacheHeaders(c, 'public-config'); - return c.json(await resolvePublicPlatformCapabilities(c.env)); -}); +app.route('/api/config', platformCapabilitiesRoutes); // Public config — whether agents can run on Instant (Cloudflare Containers) with no cloud account. app.get('/api/config/instant-runtime', (c) => { @@ -380,12 +373,6 @@ app.route('/api/auth', agentSignInRoutes); app.route('/api/auth', deviceFlowRoutes); app.route('/api/auth', authRoutes); app.route('/api/setup', setupRoutes); -// Self-hosted box gateway (frps plugin, Caddy forward_auth). Own secret auth, no session -// middleware; 404 unless REVERSE_TUNNEL_GATEWAY_SECRET is configured (routes/self-host-gateway.ts). -app.route( - '/api/self-host/gateway', - createSelfHostGatewayRoutes((request, env, ctx) => app.fetch(request, env, ctx)) -); app.route('/api/credentials', resolutionStatusRoute); app.route('/api/credentials', credentialLimitsRoute); app.route('/api/credentials', credentialsRoutes); @@ -446,6 +433,8 @@ app.route('/api/projects/:projectId/ideas', ideaRoutes); app.route('/api/projects/:projectId/overview', projectOverviewRoutes); app.route('/api/projects/:projectId/insights', projectInsightsRoutes); app.route('/api/projects/:projectId/inbox', projectInboxRoutes); +// Human tasks (inbox slice H1): steps, comments, claim, reassign, done, reopen. +app.route('/api/projects/:projectId/inbox', projectInboxTaskRoutes); app.route('/api/projects/:projectId/tasks', tasksRoutes); app.route('/api/projects/:projectId/operation-receipts', cliOperationReceiptRoutes); app.route('/api/projects/:projectId/cli', cliProjectMetadataRoutes); @@ -500,6 +489,7 @@ app.route('/api/admin/operations/approvals', adminOperationsApprovalRoutes); app.route('/api/admin/settings', adminSettingsRoutes); app.route('/api/admin/usage', adminUsageRoutes); app.route('/api/admin/costs', adminCostRoutes); +app.route('/api/admin/health-cost', adminHealthCostRoutes); app.route('/api/admin/cc-backfill', adminCcBackfillRoutes); app.route('/api/admin/github-repo-id-backfill', adminGithubRepoIdBackfillRoutes); app.route('/api/admin/github-installation-leak-sweep', adminGithubInstallationLeakSweepRoutes); diff --git a/apps/api/src/lib/client-ip.ts b/apps/api/src/lib/client-ip.ts index 10def9e72d..5efc967787 100644 --- a/apps/api/src/lib/client-ip.ts +++ b/apps/api/src/lib/client-ip.ts @@ -4,9 +4,9 @@ * One rule for every caller (rate-limit keys, stored diagnostics, heartbeat IP backfill, * forwarded-for on the VM hop): * - * - Only `CF-Connecting-IP` is trusted. On Cloudflare the edge always sets it and overwrites any - * value a client sent; the self-hosted ingress (deploy/selfhost Caddy) does the same from the - * TCP peer address. `X-Forwarded-For` is never read: wherever the trusted header is missing, + * - Only `CF-Connecting-IP` is trusted. On normal Cloudflare edge ingress it overwrites any + * value a client sent. Another trusted ingress must do the same from the TCP peer address + * and prevent direct origin access. `X-Forwarded-For` is never read: wherever the trusted header is missing, * nothing guarantees who wrote `X-Forwarded-For`, so a key taken from it is a bypass. * - A well-formed value is returned exactly as received, so Cloudflare rate-limit keys and stored * addresses stay byte-identical to what SAM produced before this helper existed. diff --git a/apps/api/src/lib/network-hosts/index.ts b/apps/api/src/lib/network-hosts/index.ts index 7c5334e2e0..9f0a69c8d8 100644 --- a/apps/api/src/lib/network-hosts/index.ts +++ b/apps/api/src/lib/network-hosts/index.ts @@ -15,4 +15,3 @@ export { type OutboundRefusalReason, OutboundRequestRefusedError, } from '@simple-agent-manager/worker-core'; -export { guardedFetchWithDeadline } from '@simple-agent-manager/worker-core'; diff --git a/apps/api/src/middleware/analytics.ts b/apps/api/src/middleware/analytics.ts index cbb834fea1..4ea68bd15b 100644 --- a/apps/api/src/middleware/analytics.ts +++ b/apps/api/src/middleware/analytics.ts @@ -58,10 +58,7 @@ const EVENT_NAME_MAP: Record = { 'GET /api/admin/users': 'admin_users_viewed', 'GET /api/admin/analytics/dau': 'admin_analytics_dau', 'GET /api/admin/analytics/events': 'admin_analytics_events', - 'GET /api/admin/analytics/funnel': 'admin_analytics_funnel', 'GET /api/admin/analytics/feature-adoption': 'admin_analytics_feature_adoption', - 'GET /api/admin/analytics/geo': 'admin_analytics_geo', - 'GET /api/admin/analytics/retention': 'admin_analytics_retention', // Notifications 'GET /api/notifications': 'notifications_viewed', diff --git a/apps/api/src/middleware/app-error-handler.ts b/apps/api/src/middleware/app-error-handler.ts index 636b216ba1..cf13bd5407 100644 --- a/apps/api/src/middleware/app-error-handler.ts +++ b/apps/api/src/middleware/app-error-handler.ts @@ -96,7 +96,7 @@ function scheduleErrorPersistence( workspaceId: identifiers.workspaceId ?? null, taskId: identifiers.taskId ?? null, sessionId: identifiers.sessionId ?? null, - ipAddress: clientIpFromHeaders((name) => c.req.header(name)), + ipAddress: clientIpFromHeaders((name) => c.req.header(name)) ?? null, userAgent: c.req.header('User-Agent') ?? null, }, c.env diff --git a/apps/api/src/middleware/error.ts b/apps/api/src/middleware/error.ts index abb68c2e13..16ced0b052 100644 --- a/apps/api/src/middleware/error.ts +++ b/apps/api/src/middleware/error.ts @@ -14,9 +14,9 @@ export const errors = { ...coreErrors, /** - * A platform service this installation does not have (for example Workers AI off - * Cloudflare). A designed 4xx: the request was valid, the installation cannot serve it, - * and retrying will not help. `feature` names the capability in + * A platform service this installation does not have (for example Workers AI on a + * runtime without it). A designed 4xx: the request was valid, the installation cannot + * serve it, and retrying will not help. `feature` names the capability in * services/platform-capabilities.ts. */ featureUnavailable: (feature: PlatformCapability, message: string) => diff --git a/apps/api/src/middleware/rate-limit.ts b/apps/api/src/middleware/rate-limit.ts index 50afd9715a..b2eb70c305 100644 --- a/apps/api/src/middleware/rate-limit.ts +++ b/apps/api/src/middleware/rate-limit.ts @@ -47,9 +47,6 @@ export const DEFAULT_RATE_LIMITS = { // Voice transcription runs Workers AI Whisper on every request. Per MINUTE, not per hour // (`DEFAULT_TRANSCRIBE_WINDOW_SECONDS`): dictation is bursty, and the budget is for abuse. TRANSCRIBE: 30, - // Server read-aloud through an admin's paid speech endpoint (`speech.synthesis.*`), per user - // per hour. The Workers AI path is not limited here (unchanged on Cloudflare). - TTS_SYNTHESIZE: 120, // Workspace callback-token renewal, per workspace. A healthy VM agent asks about once // per half token lifetime, so this only bounds a holder of both proofs replaying them // (`services/workspace-callback-token-renewal-rate-limit.ts`). @@ -168,9 +165,9 @@ export class RateLimitError extends AppError { type RateLimitResult = { allowed: boolean; remaining: number; resetAt: number }; -// The table's CHECK (migration 0174) also admits the retired 'session-summarize' bucket; -// adding a bucket needs a migration that widens it. -export type AiSpendRateLimitBucket = 'transcribe'; +// Migration 0174 also admits the retired 'session-summarize' bucket. Synthesis uses +// the additive 0259 table so existing counters/constraints never need rebuilding. +export type AiSpendRateLimitBucket = 'transcribe' | 'speech-synthesis'; interface AiSpendRateLimitRow { count: number; @@ -178,7 +175,7 @@ interface AiSpendRateLimitRow { } /** - * Atomically check and update a Workers AI spend rate limit in D1. + * Atomically check and update an AI/endpoint spend rate limit in D1. * * The generic KV helper above is intentionally left for low-stakes buckets; these * buckets guard direct Workers AI spend and must not lose increments under parallel @@ -191,15 +188,19 @@ export async function checkAiSpendRateLimit( limit: number, windowSeconds: number ): Promise { + // These internal literals are the only SQL identifiers interpolated below. + const table = bucket === 'speech-synthesis' + ? 'speech_synthesis_rate_limits' + : 'ai_spend_rate_limits'; const windowStart = getCurrentWindowStart(windowSeconds); const row = await db .prepare( - `INSERT INTO ai_spend_rate_limits (bucket, user_id, window_start, count) + `INSERT INTO ${table} (bucket, user_id, window_start, count) VALUES (?, ?, ?, 1) ON CONFLICT(bucket, user_id) DO UPDATE SET count = CASE - WHEN ai_spend_rate_limits.window_start = excluded.window_start - THEN ai_spend_rate_limits.count + 1 + WHEN ${table}.window_start = excluded.window_start + THEN ${table}.count + 1 ELSE 1 END, window_start = excluded.window_start diff --git a/apps/api/src/operation-ports.ts b/apps/api/src/operation-ports.ts index d50f9126d3..294d025bae 100644 --- a/apps/api/src/operation-ports.ts +++ b/apps/api/src/operation-ports.ts @@ -5,6 +5,7 @@ * method closes over the request's `env`, so operations never pass the full worker `Env`. * Construction is a handful of closures per request; there is no I/O here. */ +import { cronToHumanReadable } from '@simple-agent-manager/cron'; import type { OperationPorts, ProjectEventErrorKind } from '@simple-agent-manager/operations'; import type { OperationContext, OperationDeps } from '@simple-agent-manager/operations'; import { drizzle } from 'drizzle-orm/d1'; @@ -56,9 +57,10 @@ import { listOwnCredentialLimitsByReferences, listProjectCredentialLimits, } from './services/credential-limit-events/read'; -import { cronToHumanReadable } from './services/cron-utils'; import { getInstallationToken } from './services/github-app'; import { createInboxPort } from './services/inbox/port'; +import { createInboxTaskPort } from './services/inbox/task-port'; +import { readLifecycleLatencyRange } from './services/lifecycle-latency/range-report'; import { resolveProfileAccountBindings } from './services/profile-account-bindings'; import * as projectData from './services/project-data'; import { describeRootSearchCoverage } from './services/project-data-search-coverage'; @@ -120,6 +122,7 @@ export function createOperationPorts(env: Env): OperationPorts { getMailboxMessage: (...a) => projectData.getMailboxMessage(env, ...a), listActiveAttentionMarkers: (...a) => projectData.listActiveAttentionMarkers(env, ...a), getRunReceiptFacts: (...a) => projectData.getRunReceiptFacts(env, ...a), + countRunNudges: (...a) => projectData.countRunNudges(env, ...a), searchKnowledgeObservations: (...a) => projectData.searchKnowledgeObservations(env, ...a), getIdeaWorkSnapshots: (...a) => projectData.getIdeaWorkSnapshots(env, ...a), addIdeaUpdate: (...a) => projectData.addIdeaUpdate(env, ...a), @@ -152,6 +155,7 @@ export function createOperationPorts(env: Env): OperationPorts { connectorReadLimits: () => getConnectorReadLimits(env), }, inbox: createInboxPort(env), + inboxTasks: createInboxTaskPort(env), access: { requireProjectAccess: (projectId, userId) => requireProjectAccess(db(), projectId, userId), requireProjectCapability: (projectId, userId, capability) => @@ -246,6 +250,9 @@ export function createOperationPorts(env: Env): OperationPorts { missions: { startOrchestration: (projectId, missionId) => startOrchestration(env, projectId, missionId), }, + lifecycleLatency: { + rangeReport: (input) => readLifecycleLatencyRange(env, input), + }, }; } diff --git a/apps/api/src/project-data-ports/credentials.ts b/apps/api/src/project-data-ports/credentials.ts index da434b3c1b..938afa2e6d 100644 --- a/apps/api/src/project-data-ports/credentials.ts +++ b/apps/api/src/project-data-ports/credentials.ts @@ -1,4 +1,5 @@ -import type { CredentialsPort } from '../durable-objects/project-data/ports'; +import type { CredentialsPort } from '@simple-agent-manager/project-data'; + import { credentialLimitReferenceKey } from '../services/credential-limit-events/values'; /** Credential reference keys as provider-limit events store them. */ diff --git a/apps/api/src/project-data-ports/inbox-errors.ts b/apps/api/src/project-data-ports/inbox-errors.ts new file mode 100644 index 0000000000..457be8e2dd --- /dev/null +++ b/apps/api/src/project-data-ports/inbox-errors.ts @@ -0,0 +1,73 @@ +import { quotedName } from '@simple-agent-manager/operations'; + +import type { InboxErrorsPort } from '../durable-objects/project-data/ports'; +import { log, serializeError } from '../lib/logger'; +import { workerEnv } from './worker-env'; + +/** Failed chat wakes as inbox error items (slice E), filed for the ProjectData object. */ +export const inboxErrorsPort: InboxErrorsPort = { + async fileWakeFailure(projectDataEnv, input) { + const env = workerEnv(projectDataEnv); + try { + // `ensureSessionRecovery` wakes VM chats; an Instant chat wakes when it gets a message, so + // offering Wake there would be a button that always refuses. + const snapshot = await env.DATABASE.prepare( + 'SELECT runtime FROM session_snapshots WHERE chat_session_id = ? AND project_id = ?' + ) + .bind(input.sessionId, input.projectId) + .first<{ runtime: string | null }>(); + // The chat's own task, not the task that sent the undelivered message (a parent wake's + // sender is the child). Without one the item cannot be tied to the chat, so the + // ProjectData object keeps its own marker instead (`wake-failure.ts`). + const bound = await env.DATABASE.prepare( + `SELECT t.id, t.user_id, p.user_id AS project_owner_id + FROM tasks t JOIN projects p ON p.id = t.project_id + WHERE t.project_id = ? AND t.chat_session_id = ?` + ) + .bind(input.projectId, input.sessionId) + .first<{ id: string; user_id: string | null; project_owner_id: string | null }>(); + if (!bound) { + log.warn('inbox.wake_failure_unbound_chat', { + projectId: input.projectId, + sessionId: input.sessionId, + action: 'marker_fallback', + }); + return null; + } + // The chat's creator; for a chat with no recorded creator, the owner of the chat's own + // task, then the project's owner. Never the owner of the task that sent the undelivered + // message (a parent wake's sender is the child), who may not be able to open this chat. + const owner = input.createdByUserId ?? bound.user_id ?? bound.project_owner_id; + if (!owner) { + log.warn('inbox.wake_failure_unaddressable', { + projectId: input.projectId, + sessionId: input.sessionId, + action: 'marker_fallback', + }); + return null; + } + const canWake = snapshot?.runtime !== 'cf-container'; + // Loaded on use: the filing service builds operation ports, whose graph imports this port. + const { fileAndNotify } = await import('../services/inbox/system-errors'); + return await fileAndNotify(env, { + projectId: input.projectId, + assigneeUserId: owner, + source: 'wake', + subjectId: input.sessionId, + title: `Couldn't wake ${quotedName(input.topic, 'a chat')}`, + body: 'SAM could not restart the agent for this chat, so the message waiting for it was not delivered.', + actions: canWake ? ['wake', 'open_chat'] : ['open_chat'], + sourceTaskId: bound.id, + sourceSessionId: input.sessionId, + links: [{ kind: 'chat', id: input.sessionId, label: null }], + }); + } catch (error) { + log.error('inbox.wake_failure_file_failed', { + projectId: input.projectId, + sessionId: input.sessionId, + ...serializeError(error), + }); + return null; + } + }, +}; diff --git a/apps/api/src/project-data-ports/index.ts b/apps/api/src/project-data-ports/index.ts index 0630d4e909..cbdbf49895 100644 --- a/apps/api/src/project-data-ports/index.ts +++ b/apps/api/src/project-data-ports/index.ts @@ -5,8 +5,10 @@ * worker own. One module per port, so a consumer (or a test) loads only the * worker modules its port needs. Installed by `project-data-wiring.ts`. */ -import type { ProjectDataPorts } from '../durable-objects/project-data/ports'; +import type { ProjectDataPorts } from '@simple-agent-manager/project-data'; + import { credentialsPort } from './credentials'; +import { inboxErrorsPort } from './inbox-errors'; import { noticesPort } from './notices'; import { notificationsPort } from './notifications'; import { observabilityPort } from './observability'; @@ -26,4 +28,5 @@ export const workerProjectDataPorts: ProjectDataPorts = { notifications: notificationsPort, observability: observabilityPort, operations: operationsPort, + inboxErrors: inboxErrorsPort, }; diff --git a/apps/api/src/project-data-ports/notices.ts b/apps/api/src/project-data-ports/notices.ts index 51a0e37fde..98115d955c 100644 --- a/apps/api/src/project-data-ports/notices.ts +++ b/apps/api/src/project-data-ports/notices.ts @@ -1,4 +1,5 @@ -import type { NoticesPort } from '../durable-objects/project-data/ports'; +import type { NoticesPort } from '@simple-agent-manager/project-data'; + import { parentWakeNotice, projectEventWakeNotice, diff --git a/apps/api/src/project-data-ports/notifications.ts b/apps/api/src/project-data-ports/notifications.ts index ac2b243498..94718d28bf 100644 --- a/apps/api/src/project-data-ports/notifications.ts +++ b/apps/api/src/project-data-ports/notifications.ts @@ -1,5 +1,6 @@ +import type { NotificationsPort } from '@simple-agent-manager/project-data'; + import type { NotificationService } from '../durable-objects/notification'; -import type { NotificationsPort } from '../durable-objects/project-data/ports'; import type { ProjectDataEnv } from '../durable-objects/project-data/types'; function notificationStub( diff --git a/apps/api/src/project-data-ports/observability.ts b/apps/api/src/project-data-ports/observability.ts index 2f88d243da..7be01dd441 100644 --- a/apps/api/src/project-data-ports/observability.ts +++ b/apps/api/src/project-data-ports/observability.ts @@ -1,4 +1,5 @@ -import type { ObservabilityPort } from '../durable-objects/project-data/ports'; +import type { ObservabilityPort } from '@simple-agent-manager/project-data'; + import { persistError } from '../services/observability'; import { recordAcpActivityCallbackMetric, diff --git a/apps/api/src/project-data-ports/operations.ts b/apps/api/src/project-data-ports/operations.ts index aedcf72282..42d30ad390 100644 --- a/apps/api/src/project-data-ports/operations.ts +++ b/apps/api/src/project-data-ports/operations.ts @@ -1,4 +1,5 @@ -import type { OperationsPort } from '../durable-objects/project-data/ports'; +import type { OperationsPort } from '@simple-agent-manager/project-data'; + import { alertProjectDataArchiveBreakerOpened } from '../scheduled/project-data-archive-breaker-alerts'; import { classifyReconciliationLoop, @@ -10,14 +11,18 @@ import { workerEnv } from './worker-env'; /** Operational brakes, the stalled-task loop classifier and operator alerts. */ export const operationsPort: OperationsPort = { + skipUnsubscribedGitHubCi: async (env) => + (await resolveAdminSetting(workerEnv(env), 'events.skipUnsubscribedGitHubCi')) === true, messageMergeConfig: async (env) => { - const [enabled, maxRowBytes, recentIds] = await Promise.all([ + const [enabled, maxRowBytes, recentIds, toolUpdatesEnabled] = await Promise.all([ resolveAdminSetting(workerEnv(env), 'chat.messageMergingEnabled'), resolveAdminSetting(workerEnv(env), 'chat.messageMergeMaxRowBytes'), resolveAdminSetting(workerEnv(env), 'chat.messageMergeRecentIds'), + resolveAdminSetting(workerEnv(env), 'chat.toolCallMergingEnabled'), ]); return { enabled: enabled === true, + toolUpdatesEnabled: toolUpdatesEnabled === true, maxRowBytes: Number(maxRowBytes), recentIds: Number(recentIds), }; diff --git a/apps/api/src/project-data-ports/runtime.ts b/apps/api/src/project-data-ports/runtime.ts index 41ba2407c2..279527fe85 100644 --- a/apps/api/src/project-data-ports/runtime.ts +++ b/apps/api/src/project-data-ports/runtime.ts @@ -1,5 +1,6 @@ +import type { RuntimePort } from '@simple-agent-manager/project-data'; + import type { NodeLifecycle } from '../durable-objects/node-lifecycle'; -import type { RuntimePort } from '../durable-objects/project-data/ports'; import type { VmAgentContainer } from '../durable-objects/vm-agent-container'; import { isVmAgentContainerLifecycleTerminal } from '../durable-objects/vm-agent-container-lifecycle'; import { cancelAgentSessionOnNode, listAgentSessionsOnNode } from '../services/node-agent'; diff --git a/apps/api/src/project-data-ports/sessions.ts b/apps/api/src/project-data-ports/sessions.ts index 729e54f8b2..f694d23db6 100644 --- a/apps/api/src/project-data-ports/sessions.ts +++ b/apps/api/src/project-data-ports/sessions.ts @@ -1,4 +1,5 @@ -import type { SessionLifecyclePort } from '../durable-objects/project-data/ports'; +import type { SessionLifecyclePort } from '@simple-agent-manager/project-data'; + import { classifySessionIdleness, getFreshHarnessWorkLeaseExpiry, diff --git a/apps/api/src/project-data-ports/task-liveness.ts b/apps/api/src/project-data-ports/task-liveness.ts index 9f2f38d486..7998f9e862 100644 --- a/apps/api/src/project-data-ports/task-liveness.ts +++ b/apps/api/src/project-data-ports/task-liveness.ts @@ -1,4 +1,5 @@ -import type { TaskRuntimeLivenessPort } from '../durable-objects/project-data/ports'; +import type { TaskRuntimeLivenessPort } from '@simple-agent-manager/project-data'; + import { classifyTaskRuntimeDelivery, isSupersededTerminalReason, diff --git a/apps/api/src/project-data-ports/tasks.ts b/apps/api/src/project-data-ports/tasks.ts index 7f8f46c8ba..5adb470a42 100644 --- a/apps/api/src/project-data-ports/tasks.ts +++ b/apps/api/src/project-data-ports/tasks.ts @@ -1,4 +1,5 @@ -import type { TaskLifecyclePort } from '../durable-objects/project-data/ports'; +import type { TaskLifecyclePort } from '@simple-agent-manager/project-data'; + import { submitReservedTask } from '../services/reserved-task-submission'; import { WAKEABLE_TASK_STATUSES } from '../services/task-status'; import { transitionTaskToTerminal } from '../services/task-terminal-transition'; diff --git a/apps/api/src/repo-hosting-ports/artifacts.ts b/apps/api/src/repo-hosting-ports/artifacts.ts index a6d7208089..5f249eae58 100644 --- a/apps/api/src/repo-hosting-ports/artifacts.ts +++ b/apps/api/src/repo-hosting-ports/artifacts.ts @@ -1,20 +1,17 @@ import type { ArtifactsBackendPort } from '@simple-agent-manager/repo-hosting/ports'; import type { Env } from '../env'; -import { - artifactsRemoteFetch, - isLocalHostedGitActive, - resolveArtifactsBackend, -} from '../services/hosted-git/backend'; +import { resolveArtifactsBackend } from '../services/hosted-git/backend'; +import { artifactsRemoteFetch, isLocalHostedGitActive } from '../services/hosted-git/local-backend'; /** - * Repo hosting resolves the SAM-native repository backend through the worker's hosted-git - * module: the Cloudflare Artifacts binding when present, otherwise SAM's own git server when - * the self-host deploy configured it. A Cloudflare deployment always gets its binding. + * Repo hosting resolves the SAM-native repository backend through the worker's hosted-git seam: + * the Cloudflare Artifacts binding, or the backend a self-host build registered. The package hands + * over its narrow env; the full worker env is what reached it. */ export const artifactsPort: ArtifactsBackendPort = { resolve: (env) => resolveArtifactsBackend(env as Env), - // SAM-hosted repositories are read in-process, not through the public ingress. + // SAM-hosted repositories (self-host only) are read in-process, not through the public ingress. localRemoteFetch: (env) => isLocalHostedGitActive(env as Env) ? artifactsRemoteFetch(env as Env) : null, }; diff --git a/apps/api/src/repo-hosting-ports/platform-config.ts b/apps/api/src/repo-hosting-ports/platform-config.ts index f90019c8da..532cd0b325 100644 --- a/apps/api/src/repo-hosting-ports/platform-config.ts +++ b/apps/api/src/repo-hosting-ports/platform-config.ts @@ -14,8 +14,8 @@ import { * hands over its narrow env; the full worker env is what reached it. */ export const platformConfigPort: PlatformConfigPort = { + outboundMaxRedirects: (env) => resolveOutboundMaxRedirects(env as Env), githubApp: (env) => getGitHubAppConfig(env as Env), githubOAuth: (env) => getGitHubOAuthConfig(env as Env), gitlabOAuth: (env) => getGitLabOAuthConfig(env as Env), - outboundMaxRedirects: (env) => resolveOutboundMaxRedirects(env as Env), }; diff --git a/apps/api/src/routes/account-linking.ts b/apps/api/src/routes/account-linking.ts new file mode 100644 index 0000000000..e7d191f62b --- /dev/null +++ b/apps/api/src/routes/account-linking.ts @@ -0,0 +1,78 @@ +import { isAPIError } from 'better-auth/api'; +import { Hono } from 'hono'; +import * as v from 'valibot'; + +import { createAuth } from '../auth'; +import type { Env } from '../env'; +import { errors } from '../middleware/error'; +import { jsonValidator } from '../schemas/_validator'; +import { assertLinkSession, linkProofHash, linkProofIdentifier } from '../services/account-linking'; +import { resolveAdminSetting } from '../services/admin-settings-resolution'; +import { agentEmailDomain } from '../services/agent-email/address'; +import { agentEmailSenderFor } from '../services/agent-email/provider'; +import { rateLimitSignInCodes, withinEmailBudget } from '../services/email-sign-in'; + +export const accountLinkingRoutes = new Hono<{ Bindings: Env }>(); + +accountLinkingRoutes.post( + '/account-link/request', + rateLimitSignInCodes('account-link-email-ip'), + jsonValidator(v.object({ provider: v.picklist(['github', 'gitlab']) })), + async (c) => { + // This route is outside BetterAuth: preserve its same-origin CSRF boundary explicitly. + if (c.req.header('origin') !== `https://app.${c.env.BASE_DOMAIN}`) + throw errors.forbidden('Origin refused'); + const auth = await createAuth(c.env); + const session = await auth.api.getSession({ + headers: c.req.raw.headers, + query: { disableCookieCache: true, disableRefresh: true }, + }); + let current; + try { + current = assertLinkSession(session); + } catch (error) { + if (isAPIError(error)) throw errors.forbidden('Sign in again before connecting an account'); + throw error; + } + const sender = agentEmailSenderFor(c.env); + if (!current.user.emailVerified || !sender) { + throw errors.forbidden( + 'Connecting an account requires a confirmed account email and email delivery. Sign in with your existing provider to confirm your email, or contact your installation administrator.' + ); + } + if (!(await withinEmailBudget(c.env, current.user.email))) + throw errors.forbidden('Too many confirmation emails; try later'); + const { provider } = c.req.valid('json'); + const configured = (await auth.$context).socialProviders.some((entry) => entry.id === provider); + if (!configured) throw errors.badRequest('This sign-in provider is not configured'); + const seconds = Number(await resolveAdminSetting(c.env, 'security.accountLinkProofTtlSeconds')); + if (!Number.isSafeInteger(seconds) || seconds <= 0) + throw errors.internal('Invalid account link confirmation lifetime'); + const token = crypto.randomUUID() + crypto.randomUUID(); + const identifier = linkProofIdentifier(current.user.id, current.session.id, provider); + const expiresAt = Date.now() + seconds * 1000; + // Deterministic primary key bounds outstanding proof to one per session/provider. + await c.env.DATABASE.prepare( + 'INSERT INTO verifications (id, identifier, value, expires_at) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at' + ) + .bind(identifier, identifier, await linkProofHash(token), expiresAt) + .run(); + const url = new URL(`https://app.${c.env.BASE_DOMAIN}/settings/github`); + url.hash = new URLSearchParams({ linkToken: token, provider }).toString(); + try { + await sender.send({ + from: { email: `security@${agentEmailDomain(c.env.BASE_DOMAIN)}`, name: 'SAM security' }, + to: current.user.email, + subject: `Confirm connecting ${provider === 'github' ? 'GitHub' : 'GitLab'} to SAM`, + text: `To confirm it is you, open this link in the same browser where you requested the connection, then choose Confirm connection:\n\n${url}\n\nThis one-time sign-in check expires in ${seconds / 60} minutes. If you did not request this, ignore this email.`, + headers: {}, + }); + } catch { + await c.env.DATABASE.prepare('DELETE FROM verifications WHERE id = ? AND value = ?') + .bind(identifier, await linkProofHash(token)) + .run(); + throw errors.internal('Could not deliver confirmation email; try again'); + } + return c.json({ success: true }); + } +); diff --git a/apps/api/src/routes/admin-analytics-query.ts b/apps/api/src/routes/admin-analytics-query.ts index 79e5180e0a..d7460a6e38 100644 --- a/apps/api/src/routes/admin-analytics-query.ts +++ b/apps/api/src/routes/admin-analytics-query.ts @@ -15,15 +15,8 @@ export const DEFAULT_PERIOD_DAYS = 30; export const DEFAULT_TOP_EVENTS_LIMIT = 50; -export const DEFAULT_GEO_LIMIT = 50; - -export const DEFAULT_RETENTION_WEEKS = 12; - export const DEFAULT_WEBSITE_TRAFFIC_TOP_PAGES_LIMIT = 20; -/** Analytics Engine hard cap on result rows; queries without explicit LIMIT silently truncate here. */ -export const MAX_RETENTION_QUERY_ROWS = 10_000; - export const analyticsSqlResponseSchema = v.object({ data: v.optional(v.array(v.unknown())), meta: v.optional(v.array(v.unknown())), diff --git a/apps/api/src/routes/admin-analytics-audience.ts b/apps/api/src/routes/admin-analytics-website-traffic.ts similarity index 61% rename from apps/api/src/routes/admin-analytics-audience.ts rename to apps/api/src/routes/admin-analytics-website-traffic.ts index 11f30cb967..7096d1b4fb 100644 --- a/apps/api/src/routes/admin-analytics-audience.ts +++ b/apps/api/src/routes/admin-analytics-website-traffic.ts @@ -3,122 +3,13 @@ import { type Hono } from 'hono'; import type { Env } from '../env'; import { getAnalyticsDataset } from '../lib/analytics-config'; import { - DEFAULT_RETENTION_WEEKS, DEFAULT_WEBSITE_TRAFFIC_TOP_PAGES_LIMIT, - MAX_RETENTION_QUERY_ROWS, parsePeriod, parsePositiveInt, periodToInterval, queryAnalyticsEngine, } from './admin-analytics-query'; -export function registerAdminAudienceAnalyticsRoutes( - adminAnalyticsRoutes: Hono<{ Bindings: Env }> -) { - adminAnalyticsRoutes.get('/retention', async (c) => { - const dataset = getAnalyticsDataset(c.env); - const weeks = parsePositiveInt( - c.req.query('weeks') || c.env.ANALYTICS_RETENTION_WEEKS, - DEFAULT_RETENTION_WEEKS - ); - - // Two-query approach: - // 1. Get cohort week (first activity) per user - // 2. Get all active weeks per user - // Then compute retention on the API layer for flexibility. - // - // NOTE: Analytics Engine SQL does not support toStartOfWeek — use - // toStartOfInterval(timestamp, INTERVAL '7' DAY) which buckets into - // epoch-aligned 7-day intervals. - - const cohortSql = ` - SELECT - index1 AS user_id, - min(toStartOfInterval(timestamp, INTERVAL '7' DAY)) AS cohort_week - FROM ${dataset} - WHERE timestamp >= NOW() - INTERVAL '${weeks * 7}' DAY - AND index1 != 'anonymous' - AND blob1 != '' - GROUP BY user_id - LIMIT ${MAX_RETENTION_QUERY_ROWS} - `; - - const activitySql = ` - SELECT - index1 AS user_id, - toStartOfInterval(timestamp, INTERVAL '7' DAY) AS active_week - FROM ${dataset} - WHERE timestamp >= NOW() - INTERVAL '${weeks * 7}' DAY - AND index1 != 'anonymous' - AND blob1 != '' - GROUP BY user_id, active_week - LIMIT ${MAX_RETENTION_QUERY_ROWS} - `; - - const [cohortData, activityData] = await Promise.all([ - queryAnalyticsEngine(c.env, cohortSql) as Promise< - Array<{ user_id: string; cohort_week: string }> - >, - queryAnalyticsEngine(c.env, activitySql) as Promise< - Array<{ user_id: string; active_week: string }> - >, - ]); - - // Build cohort map: userId -> cohort_week - const userCohort = new Map(); - for (const row of cohortData) { - userCohort.set(row.user_id, row.cohort_week); - } - - // Build retention matrix: cohort_week -> { week_offset -> Set } - const cohorts = new Map>>(); - for (const row of activityData) { - const cw = userCohort.get(row.user_id); - if (!cw) continue; - - const cohortTime = new Date(cw).getTime(); - const activeTime = new Date(row.active_week).getTime(); - const weekOffset = Math.round((activeTime - cohortTime) / (7 * 24 * 60 * 60 * 1000)); - - if (weekOffset < 0 || weekOffset > weeks) continue; - - let weekMap = cohorts.get(cw); - if (!weekMap) { - weekMap = new Map>(); - cohorts.set(cw, weekMap); - } - let userSet = weekMap.get(weekOffset); - if (!userSet) { - userSet = new Set(); - weekMap.set(weekOffset, userSet); - } - userSet.add(row.user_id); - } - - // Convert to serializable format, sorted by cohort week - const retention = Array.from(cohorts.entries()) - .sort(([a], [b]) => a.localeCompare(b)) - .map(([cohortWeek, weekMap]) => { - const cohortSize = weekMap.get(0)?.size ?? 0; - const weekOffsets: Array<{ week: number; users: number; rate: number }> = []; - - for (const [offset, users] of Array.from(weekMap.entries()).sort(([a], [b]) => a - b)) { - weekOffsets.push({ - week: offset, - users: users.size, - rate: cohortSize > 0 ? Math.round((users.size / cohortSize) * 100) : 0, - }); - } - - return { cohortWeek, cohortSize, weeks: weekOffsets }; - }); - - const truncated = - cohortData.length >= MAX_RETENTION_QUERY_ROWS || - activityData.length >= MAX_RETENTION_QUERY_ROWS; - - return c.json({ retention, weeks, truncated }); - }); - +export function registerAdminWebsiteTrafficRoutes(adminAnalyticsRoutes: Hono<{ Bindings: Env }>) { /** * GET /api/admin/analytics/website-traffic — Website traffic by section and top pages * Query param: ?period=24h|7d|30d|90d (default 7d) @@ -294,8 +185,4 @@ export function registerAdminAudienceAnalyticsRoutes( return c.json({ hosts, trend, period }); }); - - /** - * GET /api/admin/analytics/forward-status — Forwarding configuration and cursor state - */ } diff --git a/apps/api/src/routes/admin-analytics.ts b/apps/api/src/routes/admin-analytics.ts index 1e4c218bbe..c21ebb665b 100644 --- a/apps/api/src/routes/admin-analytics.ts +++ b/apps/api/src/routes/admin-analytics.ts @@ -6,9 +6,7 @@ import { requireApproved, requireAuth, requireSuperadmin } from '../middleware/a import { errors } from '../middleware/error'; import { getForwardStatus } from '../services/analytics-forward'; import { resolvePlatformCapabilities } from '../services/platform-capabilities'; -import { registerAdminAudienceAnalyticsRoutes } from './admin-analytics-audience'; import { - DEFAULT_GEO_LIMIT, DEFAULT_PERIOD_DAYS, DEFAULT_TOP_EVENTS_LIMIT, FEATURE_EVENTS, @@ -17,6 +15,7 @@ import { periodToInterval, queryAnalyticsEngine, } from './admin-analytics-query'; +import { registerAdminWebsiteTrafficRoutes } from './admin-analytics-website-traffic'; const adminAnalyticsRoutes = new Hono<{ Bindings: Env }>(); // All analytics routes require superadmin @@ -109,36 +108,6 @@ adminAnalyticsRoutes.get('/events', async (c) => { return c.json({ events, period }); }); -/** - * GET /api/admin/analytics/funnel — Conversion funnel - * signup → project_created → workspace_created → task_submitted - */ -adminAnalyticsRoutes.get('/funnel', async (c) => { - const periodDays = parsePositiveInt(c.env.ANALYTICS_DEFAULT_PERIOD_DAYS, DEFAULT_PERIOD_DAYS); - const dataset = getAnalyticsDataset(c.env); - - const sql = ` - SELECT - blob1 AS event_name, - count(DISTINCT index1) AS unique_users - FROM ${dataset} - WHERE timestamp >= NOW() - INTERVAL '${periodDays}' DAY - AND blob1 IN ('signup', 'login', 'project_created', 'workspace_created', 'task_submitted') - AND index1 != 'anonymous' - GROUP BY event_name - `; - - const data = (await queryAnalyticsEngine(c.env, sql)) as Array<{ - event_name: string; - unique_users: string; - }>; - const funnel = data.map((row) => ({ - event_name: row.event_name, - unique_users: Number(row.unique_users), - })); - return c.json({ funnel, periodDays }); -}); - /** * GET /api/admin/analytics/feature-adoption — Feature adoption with daily trend * Query param: ?period=24h|7d|30d|90d (default 30d) @@ -203,53 +172,11 @@ adminAnalyticsRoutes.get('/feature-adoption', async (c) => { return c.json({ totals, trend, period }); }); -/** - * GET /api/admin/analytics/geo — Geographic distribution of users - * Query param: ?period=24h|7d|30d|90d (default 30d) - */ -adminAnalyticsRoutes.get('/geo', async (c) => { - const period = parsePeriod(c.req.query('period') || '30d'); - const dataset = getAnalyticsDataset(c.env); - const intervalExpr = periodToInterval(period); - const geoLimit = parsePositiveInt(c.env.ANALYTICS_GEO_LIMIT, DEFAULT_GEO_LIMIT); - - const sql = ` - SELECT - blob10 AS country, - count() AS event_count, - count(DISTINCT index1) AS unique_users - FROM ${dataset} - WHERE timestamp >= NOW() - ${intervalExpr} - AND blob10 != '' - AND index1 != 'anonymous' - GROUP BY country - ORDER BY unique_users DESC - LIMIT ${geoLimit} - `; - - const data = (await queryAnalyticsEngine(c.env, sql)) as Array<{ - country: string; - event_count: string; - unique_users: string; - }>; - const geo = data.map((row) => ({ - country: row.country, - event_count: Number(row.event_count), - unique_users: Number(row.unique_users), - })); - return c.json({ geo, period }); -}); +registerAdminWebsiteTrafficRoutes(adminAnalyticsRoutes); /** - * GET /api/admin/analytics/retention — Weekly cohort retention - * Query param: ?weeks=N (default from ANALYTICS_RETENTION_WEEKS, fallback 12) - * - * Groups users by signup week, then checks how many returned in each subsequent week. - * Uses a self-join style query: first appearance (signup event) defines the cohort week, - * then any subsequent event defines "returned in week N". + * GET /api/admin/analytics/forward-status — Forwarding configuration and cursor state */ -registerAdminAudienceAnalyticsRoutes(adminAnalyticsRoutes); - adminAnalyticsRoutes.get('/forward-status', async (c) => { const status = await getForwardStatus(c.env); return c.json(status); diff --git a/apps/api/src/routes/admin-costs.ts b/apps/api/src/routes/admin-costs.ts index 226aa6a566..42909365d2 100644 --- a/apps/api/src/routes/admin-costs.ts +++ b/apps/api/src/routes/admin-costs.ts @@ -1,15 +1,13 @@ /** - * Admin Cost Monitoring — aggregates LLM costs from AI Gateway and compute - * costs from node usage into a unified cost dashboard. + * Admin Cost Monitoring — aggregates LLM costs from AI Gateway. Compute spend lives on + * Admin Health & cost (`GET /api/admin/health-cost`), which prices each machine at the provider + * price recorded on it rather than a flat vCPU-hour estimate. * * Mounts at /api/admin/costs (registered in index.ts). */ -import { drizzle } from 'drizzle-orm/d1'; import { Hono } from 'hono'; -import * as schema from '../db/schema'; import type { Env } from '../env'; -import { log } from '../lib/logger'; import { requireApproved, requireAuth, requireSuperadmin } from '../middleware/auth'; import { type GatewayPeriod, @@ -17,7 +15,6 @@ import { getPeriodLabel, iterateGatewayLogs, } from '../services/ai-gateway-logs'; -import { getAllUsersNodeUsageSummary } from '../services/node-usage'; import { resolveAiGatewayId } from '../services/platform-capabilities'; // --------------------------------------------------------------------------- @@ -27,9 +24,6 @@ import { resolveAiGatewayId } from '../services/platform-capabilities'; const VALID_PERIODS = ['current-month', '30d', '90d'] as const; type AdminCostPeriod = (typeof VALID_PERIODS)[number]; -/** Default estimated cost per vCPU-hour in USD. Override via COMPUTE_VCPU_HOUR_COST_USD. */ -const DEFAULT_COMPUTE_VCPU_HOUR_COST_USD = 0.003; - function parsePeriod(raw: string | undefined): AdminCostPeriod { return (VALID_PERIODS as readonly string[]).includes(raw ?? '') ? (raw as AdminCostPeriod) @@ -87,14 +81,6 @@ interface CostProjection { daysInMonth: number; } -interface ComputeCostSummary { - totalNodeHours: number; - totalVcpuHours: number; - estimatedCostUsd: number; - activeNodes: number; - vcpuHourCostUsd: number; -} - export interface CostSummaryResponse { llm: { totalCostUsd: number; @@ -108,7 +94,6 @@ export interface CostSummaryResponse { byUser: CostByUser[]; }; projection: CostProjection; - compute: ComputeCostSummary; period: string; periodLabel: string; } @@ -145,12 +130,6 @@ adminCostRoutes.get('/', async (c) => { let cachedRequests = 0; let errorRequests = 0; - // Settle immediately so a compute failure cannot become an unhandled rejection - // while the independent gateway walk is in progress. - const nodeUsagePromise = getAllUsersNodeUsageSummary(drizzle(c.env.DATABASE, { schema })).then( - (value) => ({ value }), - (error: unknown) => ({ error }) - ); const gatewayId = resolveAiGatewayId(c.env); if (gatewayId) { await iterateGatewayLogs(c.env, gatewayId, periodBounds.startDate, (entry) => { @@ -226,38 +205,6 @@ adminCostRoutes.get('/', async (c) => { daysInMonth: projectionInfo.daysInMonth, }; - // --- Compute Costs --- - const vcpuHourCost = - parseFloat(c.env.COMPUTE_VCPU_HOUR_COST_USD || '') || DEFAULT_COMPUTE_VCPU_HOUR_COST_USD; - - let compute: ComputeCostSummary = { - totalNodeHours: 0, - totalVcpuHours: 0, - estimatedCostUsd: 0, - activeNodes: 0, - vcpuHourCostUsd: vcpuHourCost, - }; - - try { - const nodeResult = await nodeUsagePromise; - if ('error' in nodeResult) throw nodeResult.error; - const nodeUsage = nodeResult.value; - const totalVcpuHours = nodeUsage.users.reduce((sum, u) => sum + u.totalVcpuHours, 0); - const totalNodeHours = nodeUsage.users.reduce((sum, u) => sum + u.totalNodeHours, 0); - const activeNodes = nodeUsage.users.reduce((sum, u) => sum + u.activeNodes, 0); - compute = { - totalNodeHours, - totalVcpuHours, - estimatedCostUsd: totalVcpuHours * vcpuHourCost, - activeNodes, - vcpuHourCostUsd: vcpuHourCost, - }; - } catch (err) { - log.error('admin_costs.compute_error', { - error: err instanceof Error ? err.message : String(err), - }); - } - const summary: CostSummaryResponse = { llm: { totalCostUsd, @@ -271,7 +218,6 @@ adminCostRoutes.get('/', async (c) => { byUser: Array.from(userMap.values()).sort((a, b) => b.costUsd - a.costUsd), }, projection, - compute, period, periodLabel: getPeriodLabel(period as GatewayPeriod), }; diff --git a/apps/api/src/routes/admin-health-cost.ts b/apps/api/src/routes/admin-health-cost.ts new file mode 100644 index 0000000000..720dbc3b7d --- /dev/null +++ b/apps/api/src/routes/admin-health-cost.ts @@ -0,0 +1,68 @@ +/** + * Admin "Health & cost" (Insights slices H and CF), superadmin only: + * - GET /api/admin/health-cost?range=7d|30d|month: a thin adapter over the shared + * `installationHealth` operation, which owns the superadmin check, the queries and their limits + * (policy 5cb362e8). + * - POST /api/admin/health-cost/cloudflare/refresh: runs the daily Cloudflare cost snapshot now, + * the "Refresh now" button on the Cloudflare card (policy 2b97aefc: admin actions are buttons). + * At most once per `insights.cloudflareCostRefreshMinSeconds`; sooner answers 429. + * Per-route middleware so nothing leaks to other routers mounted under /api/admin + * (`.claude/rules/06-api-patterns.md`). + */ +import { installationHealth, toOperationHttpError } from '@simple-agent-manager/operations'; +import { Hono } from 'hono'; + +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import { getUserId, requireApproved, requireAuth, requireSuperadmin } from '../middleware/auth'; +import { errors } from '../middleware/error'; +import { webOperationContext } from '../operation-ports'; +import { resolveAdminSetting } from '../services/admin-settings-resolution'; +import { + claimCloudflareCostRefresh, + runCloudflareCostSnapshot, +} from '../services/cloudflare-cost-snapshot'; + +export const adminHealthCostRoutes = new Hono<{ Bindings: Env }>(); + +adminHealthCostRoutes.get('/', requireAuth(), requireApproved(), requireSuperadmin(), async (c) => { + const userId = getUserId(c); + try { + return c.json( + await installationHealth(webOperationContext(c, userId), { range: c.req.query('range') }) + ); + } catch (error) { + throw toOperationHttpError(error); + } +}); + +adminHealthCostRoutes.post( + '/cloudflare/refresh', + requireAuth(), + requireApproved(), + requireSuperadmin(), + async (c) => { + const userId = getUserId(c); + // One analytics request per interval, claimed atomically, so repeated or overlapping presses + // cannot burn the Cloudflare API token's GraphQL rate limit, which Admin Analytics shares. + const minSeconds = Number( + await resolveAdminSetting(c.env, 'insights.cloudflareCostRefreshMinSeconds') + ); + const nowMs = Date.now(); + const claim = await claimCloudflareCostRefresh(c.env, nowMs, minSeconds * 1000); + if (!claim.claimed) { + log.info('admin.cloudflare_cost_refresh_throttled', { + userId, + waitMs: claim.waitMs, + action: 'rejected', + }); + throw errors.tooManyRequests( + `Cloudflare cost was refreshed moments ago. Try again in ${Math.ceil(claim.waitMs / 1000)} seconds.` + ); + } + log.info('admin.cloudflare_cost_refresh_requested', { userId }); + // Cloudflare failures come back as a recorded status; the card shows them. Only a settings or + // D1 failure underneath throws, and the app error handler answers that as a 500. + return c.json(await runCloudflareCostSnapshot(c.env, nowMs)); + } +); diff --git a/apps/api/src/routes/admin-project-events.ts b/apps/api/src/routes/admin-project-events.ts index 4d9222e408..ac2670ef35 100644 --- a/apps/api/src/routes/admin-project-events.ts +++ b/apps/api/src/routes/admin-project-events.ts @@ -212,6 +212,7 @@ function buildInspectorResponse(input: { batches, attempts, accounting: input.status.accounting, + admission: input.status.admission, hasMore: input.status.hasMore, }; } diff --git a/apps/api/src/routes/agent-sign-in.ts b/apps/api/src/routes/agent-sign-in.ts index f3a025ba03..d0665342cb 100644 --- a/apps/api/src/routes/agent-sign-in.ts +++ b/apps/api/src/routes/agent-sign-in.ts @@ -195,6 +195,7 @@ async function exchange(c: Context<{ Bindings: Env }>, trust: AgentSignInTrust): // The approval gate already ran above, before anything was recorded. const session = await createSessionCookieForUser(env, user.id, { expiresAt: new Date(sessionExpiresAtMs), + headers: c.req.raw.headers, }); await linkAgentSignInSession(env, claim.id, session.sessionId); log.info('agent_sign_in.accepted', { diff --git a/apps/api/src/routes/ai-proxy-admission.ts b/apps/api/src/routes/ai-proxy-admission.ts index 2db1d06c1c..d4f3460ab7 100644 --- a/apps/api/src/routes/ai-proxy-admission.ts +++ b/apps/api/src/routes/ai-proxy-admission.ts @@ -1,3 +1,4 @@ +import { monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; /** * Request admission for the platform AI proxy (`routes/ai-proxy.ts`): authentication, request-size * limits, and every gate a request must pass before it may spend platform credentials. @@ -24,11 +25,7 @@ import { getCurrentWindowStart, } from '../middleware/rate-limit'; import { checkModelTierAllowance, describeModelTierDenial } from '../services/ai-model-tier-gate'; -import { - aiProxyDisabledMessage, - isAiProxyKillSwitchEngaged, - resolveAiProxyAvailability, -} from '../services/ai-proxy-availability'; +import { isAiProxyEnabled } from '../services/ai-proxy-availability'; import { AIProxyAuthError, extractCallbackToken, @@ -76,11 +73,6 @@ export function aiProxyBodyParseError(c: AIProxyContext, error: unknown): Respon export async function prepareAIProxyRequest( c: AIProxyContext ): Promise { - // Kill switch first; the no-gateway gate runs after auth (resolveAiProxyAvailability). - if (isAiProxyKillSwitchEngaged(c.env)) { - return proxyJsonError(c, 'AI proxy is disabled', 'service_unavailable', 503); - } - const token = extractCallbackToken(c.req.header('Authorization'), undefined); if (!token) { return proxyJsonError( @@ -92,14 +84,9 @@ export async function prepareAIProxyRequest( } const db = drizzle(c.env.DATABASE, { schema }); + let auth; try { - const auth = await verifyAIProxyAuth(token, c.env, db); - // No AI Gateway and the admin has not enabled the direct upstream. - const availability = await resolveAiProxyAvailability(c.env); - if (!availability.enabled) { - return proxyJsonError(c, aiProxyDisabledMessage(availability), 'service_unavailable', 503); - } - return { ...auth, db }; + auth = await verifyAIProxyAuth(token, c.env, db); } catch (err) { if (err instanceof AIProxyAuthError) { return proxyJsonError( @@ -111,6 +98,9 @@ export async function prepareAIProxyRequest( } return proxyJsonError(c, 'Invalid or expired token', 'invalid_request_error', 401); } + if (!(await isAiProxyEnabled(c.env))) + return proxyJsonError(c, 'AI proxy is disabled', 'service_unavailable', 503); + return { ...auth, db }; } export async function enforceRateLimit( @@ -165,18 +155,12 @@ export async function enforceUsageGate( ); } - return proxyJsonError( - c, - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429, - { - monthlyCost: { - used: usageGate.monthlyCap.costUsd, - cap: usageGate.monthlyCap.capUsd, - }, - } - ); + return proxyJsonError(c, monthlyCostCapMessage(usageGate.monthlyCap), 'rate_limit_error', 429, { + monthlyCost: { + used: usageGate.monthlyCap.costUsd, + cap: usageGate.monthlyCap.capUsd, + }, + }); } export function validateAllowedModel(c: AIProxyContext, modelId: string): Response | null { diff --git a/apps/api/src/routes/ai-proxy-anthropic-support.ts b/apps/api/src/routes/ai-proxy-anthropic-support.ts index d2ab0d08d3..ff3857c9dc 100644 --- a/apps/api/src/routes/ai-proxy-anthropic-support.ts +++ b/apps/api/src/routes/ai-proxy-anthropic-support.ts @@ -1,3 +1,4 @@ +import { type MonthlyCostCapCheck,monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; /** * Error shapes and platform-credential telemetry for the native Anthropic proxy * (`routes/ai-proxy-anthropic.ts`). @@ -50,7 +51,8 @@ export function anthropicProviderErrorHeaders(upstreamHeaders: Headers): Headers } export function anthropicUsageGateError( - reason: 'daily-token-budget' | 'monthly-cost-cap' + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck ): Response { if (reason === 'daily-token-budget') { return anthropicError( @@ -60,11 +62,7 @@ export function anthropicUsageGateError( ); } - return anthropicError( - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429 - ); + return anthropicError(monthlyCostCapMessage(cap), 'rate_limit_error', 429); } export function anthropicBodyMaxBytes(c: AnthropicProxyContext): number { diff --git a/apps/api/src/routes/ai-proxy-anthropic.ts b/apps/api/src/routes/ai-proxy-anthropic.ts index 1928a1fb9b..5f252d8a5c 100644 --- a/apps/api/src/routes/ai-proxy-anthropic.ts +++ b/apps/api/src/routes/ai-proxy-anthropic.ts @@ -30,12 +30,9 @@ import { createRateLimitKey, getCurrentWindowStart, } from '../middleware/rate-limit'; +import { proxyRunUsageRecorder } from '../services/agent-run-usage'; import { resolveUpstreamAuth } from '../services/ai-billing'; -import { - aiProxyDisabledMessage, - isAiProxyKillSwitchEngaged, - resolveAiProxyAvailability, -} from '../services/ai-proxy-availability'; +import { isAiProxyEnabled } from '../services/ai-proxy-availability'; import { AIProxyAuthError, buildAIGatewayMetadata, @@ -71,11 +68,6 @@ const aiProxyAnthropicRoutes = new Hono<{ Bindings: Env }>(); // ============================================================================= aiProxyAnthropicRoutes.post('/messages', async (c) => { - // Kill switch first; the no-gateway gate runs after auth (resolveAiProxyAvailability). - if (isAiProxyKillSwitchEngaged(c.env)) { - return anthropicError('AI proxy is disabled', 'api_error', 503); - } - // --- Auth: extract token from x-api-key or Authorization: Bearer --- const token = extractCallbackToken(c.req.header('Authorization'), c.req.header('x-api-key')); if (!token) { @@ -97,12 +89,8 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { } return anthropicError('Invalid or expired API key', 'authentication_error', 401); } - - // No AI Gateway and the admin has not enabled the direct upstream. - const availability = await resolveAiProxyAvailability(c.env); - if (!availability.enabled) { - return anthropicError(aiProxyDisabledMessage(availability), 'api_error', 503); - } + if (!(await isAiProxyEnabled(c.env))) + return anthropicError('AI proxy is disabled', 'api_error', 503); const { userId, workspaceId, projectId, chatSessionId } = auth; @@ -164,7 +152,10 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { const usageGate = await checkAiUsageGate(c.env.KV, userId, c.env); if (!usageGate.allowed) { - return anthropicUsageGateError(usageGate.reason); + return anthropicUsageGateError( + usageGate.reason, + usageGate.reason === 'monthly-cost-cap' ? usageGate.monthlyCap : undefined + ); } // --- Resolve upstream auth (Unified Billing or platform key) --- @@ -285,10 +276,15 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { env: c.env, userId, format: 'anthropic', + costModelId: modelId, fallbackInputTokens: estimateInputTokensFromMessages(body.messages), + onMeasuredUsage: proxyRunUsageRecorder(c.env, auth, { + model: modelId, + credentialReference: upstreamAuth.credentialReference, + credentialSource: upstreamAuth.credentialSource, + }), executionCtx: optionalExecutionContext(() => c.executionCtx), headers: responseHeaders, - costModelId: modelId, }); } catch (err) { log.error('ai_proxy_anthropic.fetch_error', { @@ -306,11 +302,6 @@ aiProxyAnthropicRoutes.post('/messages', async (c) => { // ============================================================================= aiProxyAnthropicRoutes.post('/messages/count_tokens', async (c) => { - // Kill switch first; the no-gateway gate runs after auth (resolveAiProxyAvailability). - if (isAiProxyKillSwitchEngaged(c.env)) { - return anthropicError('AI proxy is disabled', 'api_error', 503); - } - // --- Auth --- const token = extractCallbackToken(c.req.header('Authorization'), c.req.header('x-api-key')); if (!token) { @@ -332,12 +323,8 @@ aiProxyAnthropicRoutes.post('/messages/count_tokens', async (c) => { } return anthropicError('Invalid or expired API key', 'authentication_error', 401); } - - // No AI Gateway and the admin has not enabled the direct upstream. - const availability = await resolveAiProxyAvailability(c.env); - if (!availability.enabled) { - return anthropicError(aiProxyDisabledMessage(availability), 'api_error', 503); - } + if (!(await isAiProxyEnabled(c.env))) + return anthropicError('AI proxy is disabled', 'api_error', 503); const { userId, workspaceId, projectId, chatSessionId } = auth; @@ -398,7 +385,10 @@ aiProxyAnthropicRoutes.post('/messages/count_tokens', async (c) => { const usageGate = await checkAiUsageGate(c.env.KV, userId, c.env); if (!usageGate.allowed) { - return anthropicUsageGateError(usageGate.reason); + return anthropicUsageGateError( + usageGate.reason, + usageGate.reason === 'monthly-cost-cap' ? usageGate.monthlyCap : undefined + ); } // --- Resolve upstream auth (Unified Billing or platform key) --- diff --git a/apps/api/src/routes/ai-proxy-passthrough-errors.ts b/apps/api/src/routes/ai-proxy-passthrough-errors.ts index 8b59b14e77..e4cf847ebf 100644 --- a/apps/api/src/routes/ai-proxy-passthrough-errors.ts +++ b/apps/api/src/routes/ai-proxy-passthrough-errors.ts @@ -1,3 +1,5 @@ +import { type MonthlyCostCapCheck,monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; + import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; function jsonErrorHeaders(headers?: HeadersInit): Headers { @@ -37,7 +39,8 @@ export function openaiError( } export function anthropicUsageGateError( - reason: 'daily-token-budget' | 'monthly-cost-cap' + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck ): Response { if (reason === 'daily-token-budget') { return anthropicError( @@ -47,21 +50,16 @@ export function anthropicUsageGateError( ); } - return anthropicError( - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429 - ); + return anthropicError(monthlyCostCapMessage(cap), 'rate_limit_error', 429); } -export function openaiUsageGateError(reason: 'daily-token-budget' | 'monthly-cost-cap'): Response { +export function openaiUsageGateError( + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck +): Response { if (reason === 'daily-token-budget') { return openaiError('Daily token budget exceeded.', 'rate_limit_error', 429); } - return openaiError( - 'Monthly cost cap exceeded. Adjust your cap in Settings > Usage.', - 'rate_limit_error', - 429 - ); + return openaiError(monthlyCostCapMessage(cap), 'rate_limit_error', 429); } diff --git a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts index 5397a2e06a..13ad419e24 100644 --- a/apps/api/src/routes/ai-proxy-passthrough-prepare.ts +++ b/apps/api/src/routes/ai-proxy-passthrough-prepare.ts @@ -1,20 +1,37 @@ /** - * Request preparation for the AI proxy passthrough routes (ai-proxy-passthrough.ts): workspace - * token auth, rate limit, body parsing, usage gate and upstream resolution, plus the guarded - * upstream fetch. + * AI proxy passthrough routes — URL-path-based workspace auth. + * + * These routes embed the workspace callback token in the URL path instead of + * auth headers, so protocol auth headers can be reserved for upstream provider + * credentials that are resolved server-side. + * + * Routes: + * POST /ai/proxy/:wstoken/anthropic/v1/messages + * POST /ai/proxy/:wstoken/anthropic/v1/messages/count_tokens + * POST /ai/proxy/:wstoken/openai/v1/chat/completions + * + * The wstoken is verified as a workspace callback token to extract userId, + * workspaceId, and projectId. Upstream provider credentials are never accepted + * from, or returned to, tenant workspaces. */ import { + findPricedModel, + hasLocalAiCostMetering, + type MeasuredTokenUsage, + type MonthlyCostCapCheck, +} from '@simple-agent-manager/ai-proxy'; +import { + AI_PROVIDER_BASE_URLS, DEFAULT_AI_PROXY_RATE_LIMIT_RPM, DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS, DEFAULT_AI_PROXY_REQUEST_BODY_MAX_BYTES, type Dialect, } from '@simple-agent-manager/shared'; import { drizzle } from 'drizzle-orm/d1'; -import type { Context } from 'hono'; +import { type Context } from 'hono'; import * as schema from '../db/schema'; import type { Env } from '../env'; -import { guardedFetch, OutboundRequestRefusedError } from '../lib/network-hosts'; import { parsePositiveInt } from '../lib/route-helpers'; import { readRequestJsonRecord, RequestBodyTooLargeError } from '../lib/runtime-validation'; import { @@ -22,10 +39,10 @@ import { createRateLimitKey, getCurrentWindowStart, } from '../middleware/rate-limit'; -import { isAiProxyEnabled, isAiProxyKillSwitchEngaged } from '../services/ai-proxy-availability'; +import { proxyRunUsageRecorder } from '../services/agent-run-usage'; +import { isAiProxyEnabled } from '../services/ai-proxy-availability'; import { AIProxyAuthError, verifyAIProxyAuth } from '../services/ai-proxy-shared'; import { checkAiUsageGate } from '../services/ai-token-budget'; -import { resolveOutboundMaxRedirects } from '../services/outbound-fetch-settings'; import type { PreloadedRuntimeRows } from '../services/workspace-runtime-assets'; import { anthropicError, @@ -39,8 +56,9 @@ import { trimTrailingSlashes, } from './ai-proxy-passthrough-upstream'; -export type ProxyContext = Context<{ Bindings: Env }>; -export interface PassthroughAuthResult { +type ProxyContext = Context<{ Bindings: Env }>; + +interface PassthroughAuthResult { userId: string; workspaceId: string; projectId: string | null; @@ -55,16 +73,18 @@ export interface PassthroughAuthResult { agentCredentialGeneration: number; } -export interface PreparedProxyRequest extends PassthroughAuthResult { +interface PreparedProxyRequest extends PassthroughAuthResult { body: Record; modelId: string; upstream: ResolvedProxyUpstream; + /** Insights run usage hook for this request (`proxyRunUsageRecorder`). */ + recordRunUsage: (usage: MeasuredTokenUsage) => Promise; } -export type PreparedProxyResult = +type PreparedProxyResult = { ok: true; value: PreparedProxyRequest } | { ok: false; response: Response }; -export interface PrepareProxyOptions { +interface PrepareProxyOptions { dialect: Dialect; jsonContext: string; disabledResponse: () => Response; @@ -75,7 +95,10 @@ export interface PrepareProxyOptions { requestTooLargeResponse: (maxBytes: number) => Response; invalidBodyResponse?: (body: Record) => Response | null; missingModelResponse: () => Response; - usageGateResponse: (reason: 'daily-token-budget' | 'monthly-cost-cap') => Response; + usageGateResponse: ( + reason: 'daily-token-budget' | 'monthly-cost-cap', + cap?: MonthlyCostCapCheck + ) => Response; missingUpstreamResponse: () => Response; } @@ -84,37 +107,14 @@ async function verifyPassthroughAuth(wstoken: string, env: Env): Promise { - if ( - upstream.capability.authStyle === 'bearer-token' || - upstream.dialect === 'openai-compatible' - ) { - return { Authorization: `Bearer ${upstream.apiKey}` }; - } - if (upstream.capability.authStyle === 'api-key' && upstream.dialect === 'anthropic') { - return { 'x-api-key': upstream.apiKey }; - } - return {}; -} - async function checkPassthroughRateLimit( env: Env, userId: string ): Promise<{ allowed: boolean; remaining: number; resetAt: number; limit: number }> { const rpmLimit = - parseInt(env.AI_PROXY_RATE_LIMIT_RPM || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_RPM; + Number.parseInt(env.AI_PROXY_RATE_LIMIT_RPM || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_RPM; const windowSeconds = - parseInt(env.AI_PROXY_RATE_LIMIT_WINDOW_SECONDS || '', 10) || + Number.parseInt(env.AI_PROXY_RATE_LIMIT_WINDOW_SECONDS || '', 10) || DEFAULT_AI_PROXY_RATE_LIMIT_WINDOW_SECONDS; const windowStart = getCurrentWindowStart(windowSeconds); const rateLimitKey = createRateLimitKey('ai-proxy', userId, windowStart); @@ -183,15 +183,60 @@ export function openaiProxyOptions(jsonContext: string): PrepareProxyOptions { }; } -export async function prepareProxyRequest( +/** A model id prices only its vendor's endpoint, not an arbitrary compatible alias. */ +function hasCanonicalCatalogPrice(upstream: ResolvedProxyUpstream, modelId: string): boolean { + const model = findPricedModel(modelId); + if (!model || model.provider === 'workers-ai') return false; + const dialect = model.provider === 'anthropic' ? 'anthropic' : 'openai-compatible'; + if (upstream.dialect !== dialect) return false; + try { + const actual = new URL(upstream.baseUrl); + const canonical = new URL(AI_PROVIDER_BASE_URLS[model.provider]); + return ( + !actual.username && + !actual.password && + !actual.search && + !actual.hash && + actual.origin === canonical.origin && + trimTrailingSlashes(actual.pathname) === trimTrailingSlashes(canonical.pathname) + ); + } catch { + return false; + } +} + +/** Admission depends on the resolved owner; locally funded calls must be priceable. */ +async function enforcePassthroughFunding( c: ProxyContext, + userId: string, + modelId: string, + upstream: ResolvedProxyUpstream, options: PrepareProxyOptions -): Promise { - // Kill switch first; the no-gateway gate runs after auth (isAiProxyEnabled). - if (isAiProxyKillSwitchEngaged(c.env)) { - return { ok: false, response: options.disabledResponse() }; +): Promise { + const platformBilled = upstream.credentialSource === 'platform'; + if ( + platformBilled && + hasLocalAiCostMetering(c.env) && + !hasCanonicalCatalogPrice(upstream, modelId) + ) { + const message = + 'Model and upstream endpoint must match a catalog-priced provider to use an installation-funded credential.'; + return options.dialect === 'anthropic' + ? anthropicError(message, 'invalid_request_error', 400) + : openaiError(message, 'invalid_request_error', 400); } + const usageGate = await checkAiUsageGate(c.env.KV, userId, c.env, { platformBilled }); + if (usageGate.allowed) return null; + return options.usageGateResponse( + usageGate.reason, + usageGate.reason === 'monthly-cost-cap' ? usageGate.monthlyCap : undefined + ); +} +export async function prepareProxyRequest( + c: ProxyContext, + options: PrepareProxyOptions +): Promise { const wstoken = c.req.param('wstoken'); if (!wstoken) { return { ok: false, response: options.invalidTokenResponse() }; @@ -207,10 +252,7 @@ export async function prepareProxyRequest( return { ok: false, response: options.invalidTokenResponse() }; } - // No AI Gateway and the admin has not enabled the direct upstream. - if (!(await isAiProxyEnabled(c.env))) { - return { ok: false, response: options.disabledResponse() }; - } + if (!(await isAiProxyEnabled(c.env))) return { ok: false, response: options.disabledResponse() }; const { allowed, remaining, resetAt, limit } = await checkPassthroughRateLimit( c.env, @@ -247,11 +289,6 @@ export async function prepareProxyRequest( return { ok: false, response: options.missingModelResponse() }; } - const usageGate = await checkAiUsageGate(c.env.KV, auth.userId, c.env); - if (!usageGate.allowed) { - return { ok: false, response: options.usageGateResponse(usageGate.reason) }; - } - const upstream = await resolveProxyUpstream({ env: c.env, userId: auth.userId, @@ -266,53 +303,15 @@ export async function prepareProxyRequest( return { ok: false, response: options.missingUpstreamResponse() }; } - return { ok: true, value: { ...auth, body, modelId, upstream } }; -} - -export function buildJsonUpstreamHeaders(upstream: ResolvedProxyUpstream): Record { - return { - ...buildUpstreamAuthHeaders(upstream), - 'Content-Type': 'application/json', - }; -} + const fundingError = await enforcePassthroughFunding(c, auth.userId, modelId, upstream, options); + if (fundingError) return { ok: false, response: fundingError }; -export function upstreamFetchErrorMeta(err: unknown): Record { - if (err instanceof OutboundRequestRefusedError) { - return { errorName: err.name, refusal: err.reason }; - } - if (err instanceof Error) { - return { errorName: err.name }; - } - return { errorType: typeof err }; -} - -/** - * The upstream base URL is chosen by the user (an `openai-compatible` credential or a - * configuration's `baseUrl`), so the request goes through the guarded fetch: public hosts only, - * and every redirect hop re-validated instead of followed by the runtime. A refused URL or hop - * throws `OutboundRequestRefusedError`, which each route reports as an upstream failure. - */ -export async function fetchProxyUpstream( - env: Env, - url: string, - headers: Record, - body: Record -): Promise { - return guardedFetch( - url, - { method: 'POST', headers, body: JSON.stringify(body) }, - { allowPrivateNetwork: false, maxRedirects: await resolveOutboundMaxRedirects(env) } - ); -} - -export function addAnthropicRequestHeaders( - headers: Record, - c: ProxyContext -): Record { - // Anthropic-compatible Messages calls require an API version header. - // https://docs.anthropic.com/en/api/versioning - headers['anthropic-version'] = c.req.header('anthropic-version') || '2023-06-01'; - const anthropicBeta = c.req.header('anthropic-beta'); - if (anthropicBeta) headers['anthropic-beta'] = anthropicBeta; - return headers; + // Insights run usage: the measured tokens go to this workspace's run, keyed by the credential + // the proxy forwards with. + const recordRunUsage = proxyRunUsageRecorder(c.env, auth, { + model: modelId, + credentialReference: upstream.credentialReference, + credentialSource: upstream.credentialSource, + }); + return { ok: true, value: { ...auth, body, modelId, upstream, recordRunUsage } }; } diff --git a/apps/api/src/routes/ai-proxy-passthrough.ts b/apps/api/src/routes/ai-proxy-passthrough.ts index 9f6b09beb2..b2a6cb4c75 100644 --- a/apps/api/src/routes/ai-proxy-passthrough.ts +++ b/apps/api/src/routes/ai-proxy-passthrough.ts @@ -1,3 +1,5 @@ +import { hasLocalAiCostMetering } from '@simple-agent-manager/ai-proxy'; +import { guardedFetch } from '@simple-agent-manager/worker-core'; /** * AI proxy passthrough routes — URL-path-based workspace auth. * @@ -12,36 +14,98 @@ * * The wstoken is verified as a workspace callback token to extract userId, * workspaceId, and projectId. Upstream provider credentials are never accepted - * from, or returned to, tenant workspaces. The upstream URL can be user-chosen, so - * every upstream request goes through `fetchProxyUpstream` (guarded fetch). + * from, or returned to, tenant workspaces. */ -import { Hono } from 'hono'; +import { type Context, Hono } from 'hono'; import type { Env } from '../env'; import { log } from '../lib/logger'; import { attachUpstreamTokenUsageAccounting, estimateInputTokensFromMessages, + estimateInputTokensFromRequest, optionalExecutionContext, } from '../services/ai-token-usage-accounting'; import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; +import { resolveOutboundMaxRedirects } from '../services/outbound-fetch-settings'; import { anthropicError, credentialErrorHeaders, openaiError } from './ai-proxy-passthrough-errors'; import { - addAnthropicRequestHeaders, anthropicProxyOptions, - buildJsonUpstreamHeaders, - buildUpstreamAuthHeaders, - fetchProxyUpstream, - joinUpstreamUrl, openaiProxyOptions, prepareProxyRequest, retryAfterSeconds, - upstreamFetchErrorMeta, } from './ai-proxy-passthrough-prepare'; import { schedulePassthroughLimitHeaders } from './ai-proxy-passthrough-telemetry'; -import { resolveProxyUpstream } from './ai-proxy-passthrough-upstream'; +import { type ResolvedProxyUpstream, trimTrailingSlashes } from './ai-proxy-passthrough-upstream'; const aiProxyPassthroughRoutes = new Hono<{ Bindings: Env }>(); +type ProxyContext = Context<{ Bindings: Env }>; + +// ============================================================================= +// Error Helpers +// ============================================================================= + +// ============================================================================= +// Shared: verify workspace token from URL path + rate limit + budget +// ============================================================================= + +function trimLeadingSlashes(value: string): string { + let start = 0; + while (start < value.length && value.charCodeAt(start) === 47) start++; + return value.slice(start); +} + +function joinUpstreamUrl(baseUrl: string, path: string): string { + return `${trimTrailingSlashes(baseUrl)}/${trimLeadingSlashes(path)}`; +} + +/** + * A passthrough call served by a platform-owned credential spends the installation's money, so + * where SAM prices spend itself (no AI Gateway) it is priced into the monthly cap and ceiling like + * every other platform-billed call. A user's or project's own credential is their own spend. + */ +function platformCostModelId(upstream: ResolvedProxyUpstream, modelId: string): string | undefined { + return upstream.credentialSource === 'platform' ? modelId : undefined; +} + +function buildUpstreamAuthHeaders(upstream: ResolvedProxyUpstream): Record { + if ( + upstream.capability.authStyle === 'bearer-token' || + upstream.dialect === 'openai-compatible' + ) { + return { Authorization: `Bearer ${upstream.apiKey}` }; + } + if (upstream.capability.authStyle === 'api-key' && upstream.dialect === 'anthropic') { + return { 'x-api-key': upstream.apiKey }; + } + return {}; +} + +function buildJsonUpstreamHeaders(upstream: ResolvedProxyUpstream): Record { + return { + ...buildUpstreamAuthHeaders(upstream), + 'Content-Type': 'application/json', + }; +} + +function upstreamFetchErrorMeta(err: unknown): Record { + if (err instanceof Error) { + return { errorName: err.name }; + } + return { errorType: typeof err }; +} + +function addAnthropicRequestHeaders( + headers: Record, + c: ProxyContext +): Record { + // Anthropic-compatible Messages calls require an API version header. + // https://docs.anthropic.com/en/api/versioning + headers['anthropic-version'] = c.req.header('anthropic-version') || '2023-06-01'; + const anthropicBeta = c.req.header('anthropic-beta'); + if (anthropicBeta) headers['anthropic-beta'] = anthropicBeta; + return headers; +} // ============================================================================= // Anthropic Passthrough: POST /:wstoken/anthropic/v1/messages @@ -84,7 +148,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/anthropic/v1/messages', async (c) => { const upstreamUrl = joinUpstreamUrl(upstream.baseUrl, 'v1/messages'); try { - const upstreamResponse = await fetchProxyUpstream(c.env, upstreamUrl, upstreamHeaders, body); + const upstreamResponse = await guardedFetch( + upstreamUrl, + { + method: 'POST', + headers: upstreamHeaders, + body: JSON.stringify(body), + }, + { maxRedirects: await resolveOutboundMaxRedirects(c.env) } + ); log.info('ai_proxy_passthrough.anthropic.response', { userId, @@ -134,8 +206,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/anthropic/v1/messages', async (c) => { env: c.env, userId, format: 'anthropic', - fallbackInputTokens: estimateInputTokensFromMessages(body.messages), + fallbackInputTokens: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env) + ? estimateInputTokensFromRequest(body) + : estimateInputTokensFromMessages(body.messages), provider: upstream.provider, + costModelId: platformCostModelId(upstream, modelId), + estimateMissingUsage: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env), + onMeasuredUsage: prepared.value.recordRunUsage, executionCtx: optionalExecutionContext(() => c.executionCtx), headers: responseHeaders, }); @@ -169,7 +248,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/anthropic/v1/messages/count_tokens', as const countTokensUrl = joinUpstreamUrl(upstream.baseUrl, 'v1/messages/count_tokens'); try { - const upstreamResponse = await fetchProxyUpstream(c.env, countTokensUrl, upstreamHeaders, body); + const upstreamResponse = await guardedFetch( + countTokensUrl, + { + method: 'POST', + headers: upstreamHeaders, + body: JSON.stringify(body), + }, + { maxRedirects: await resolveOutboundMaxRedirects(c.env) } + ); if (!upstreamResponse.ok) { log.error('ai_proxy_passthrough.anthropic.count_tokens_error', { @@ -247,7 +334,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/openai/v1/chat/completions', async (c) }); try { - const upstreamResponse = await fetchProxyUpstream(c.env, upstreamUrl, upstreamHeaders, body); + const upstreamResponse = await guardedFetch( + upstreamUrl, + { + method: 'POST', + headers: upstreamHeaders, + body: JSON.stringify(body), + }, + { maxRedirects: await resolveOutboundMaxRedirects(c.env) } + ); log.info('ai_proxy_passthrough.openai.response', { userId, @@ -301,8 +396,15 @@ aiProxyPassthroughRoutes.post('/:wstoken/openai/v1/chat/completions', async (c) env: c.env, userId, format: 'openai', - fallbackInputTokens: estimateInputTokensFromMessages(body.messages), + fallbackInputTokens: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env) + ? estimateInputTokensFromRequest(body) + : estimateInputTokensFromMessages(body.messages), provider: upstream.provider, + costModelId: platformCostModelId(upstream, modelId), + estimateMissingUsage: + upstream.credentialSource === 'platform' && hasLocalAiCostMetering(c.env), + onMeasuredUsage: prepared.value.recordRunUsage, executionCtx: optionalExecutionContext(() => c.executionCtx), headers: responseHeaders, }); @@ -317,9 +419,6 @@ aiProxyPassthroughRoutes.post('/:wstoken/openai/v1/chat/completions', async (c) } }); -export { - aiProxyPassthroughRoutes, - buildUpstreamAuthHeaders, - joinUpstreamUrl, - resolveProxyUpstream, -}; +export { aiProxyPassthroughRoutes, buildUpstreamAuthHeaders, joinUpstreamUrl }; + +export { resolveProxyUpstream } from './ai-proxy-passthrough-upstream'; diff --git a/apps/api/src/routes/ai-proxy-platform-billing.ts b/apps/api/src/routes/ai-proxy-platform-billing.ts index 7bc4fa6bf8..43c4823316 100644 --- a/apps/api/src/routes/ai-proxy-platform-billing.ts +++ b/apps/api/src/routes/ai-proxy-platform-billing.ts @@ -5,6 +5,8 @@ * * Split out of ai-proxy.ts per .claude/rules/18-file-size-limits.md. */ +import type { MeasuredTokenUsage } from '@simple-agent-manager/ai-proxy'; + import type { Env } from '../env'; import { log } from '../lib/logger'; import { getCredentialEncryptionKey } from '../lib/secrets'; @@ -141,7 +143,9 @@ export function accountingResponse( response: Response, userId: string, estimatedInputTokens: number, - options: { estimateMissingUsage?: boolean; costModelId?: string } = {} + /** Insights run usage hook (`proxyRunUsageRecorder`); receives measured usage only. */ + onMeasuredUsage?: (usage: MeasuredTokenUsage) => Promise, + metering: { costModelId?: string; estimateMissingUsage?: boolean } = {} ): Promise { let executionCtx: Pick | undefined; try { @@ -155,7 +159,7 @@ export function accountingResponse( format: 'openai', fallbackInputTokens: estimatedInputTokens, executionCtx, - estimateMissingUsage: options.estimateMissingUsage === true, - costModelId: options.costModelId, + onMeasuredUsage, + ...metering, }); } diff --git a/apps/api/src/routes/ai-proxy-upstream.ts b/apps/api/src/routes/ai-proxy-upstream.ts index 5aa3465a2e..bb1d2e0302 100644 --- a/apps/api/src/routes/ai-proxy-upstream.ts +++ b/apps/api/src/routes/ai-proxy-upstream.ts @@ -1,3 +1,4 @@ +export const customEndpointResponses = new WeakSet(); /** * AI proxy upstream forwarding — sends prepared requests to Workers AI, * Anthropic, or OpenAI through Cloudflare AI Gateway, translating Anthropic's @@ -6,11 +7,12 @@ * Split out of ai-proxy.ts per .claude/rules/18-file-size-limits.md — pure * extraction, no behavior change. */ +import { AI_PROVIDER_BASE_URLS } from '@simple-agent-manager/shared'; import * as v from 'valibot'; import type { Env } from '../env'; import { log } from '../lib/logger'; -import { maybeJsonRecord, readResponseJson } from '../lib/runtime-validation'; +import { readResponseJson } from '../lib/runtime-validation'; import { createAnthropicToOpenAIStream, translateRequestToAnthropic, @@ -18,21 +20,15 @@ import { } from '../services/ai-anthropic-translate'; import type { UpstreamAuth } from '../services/ai-billing'; import { resolveUnifiedBillingToken } from '../services/ai-billing'; -import { buildAnthropicGatewayUrl, upstreamErrorLogFields } from '../services/ai-proxy-shared'; +import { buildAnthropicGatewayUrl } from '../services/ai-proxy-shared'; import { copyCredentialLimitHeaders } from '../services/credential-limit-events'; import { chatTargetHeaders, fetchChatTarget, - isCloudflareChatTarget, LlmUnavailableError, resolveWorkersAiChatTarget, - withStreamUsageRequested, } from '../services/llm-chat-target'; -import { - aiGatewayOnlyHeaders, - hasLocalAiCostMetering, - resolveAiGatewayId, -} from '../services/platform-capabilities'; +import { aiGatewayOnlyHeaders, resolveAiGatewayId } from '../services/platform-capabilities'; const anthropicContentBlockSchema = v.variant('type', [ v.object({ type: v.literal('text'), text: v.string() }), @@ -63,7 +59,7 @@ function buildOpenAIUrl(env: Env): string { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/openai/v1/chat/completions`; } // Fallback: direct OpenAI API (no gateway monitoring) - return 'https://api.openai.com/v1/chat/completions'; + return `${AI_PROVIDER_BASE_URLS.openai}/chat/completions`; } /** Build upstream URL for OpenAI Responses API via AI Gateway. */ @@ -72,64 +68,40 @@ function buildOpenAIResponsesUrl(env: Env): string { if (gatewayId) { return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/openai/v1/responses`; } - return 'https://api.openai.com/v1/responses'; + return `${AI_PROVIDER_BASE_URLS.openai}/responses`; } // ============================================================================= // Forwarding Functions // ============================================================================= -/** - * A forwarded Workers AI-route response, and whether its usage may need estimating: an - * admin-configured OpenAI-compatible endpoint can omit `usage`, Cloudflare's routes report it. - */ -export interface WorkersAiForward { - response: Response; - estimateMissingUsage: boolean; -} - /** Forward request to Workers AI (transparent OpenAI-format pass-through). */ export async function forwardToWorkersAI( env: Env, body: Record, modelId: string, aigMetadata: string -): Promise { - const forward = (response: Response, estimateMissingUsage = false): WorkersAiForward => ({ - response, - estimateMissingUsage, - }); - let target: Awaited>; +): Promise { + let target; try { target = await resolveWorkersAiChatTarget(env, 'aiProxy', modelId); } catch (err) { if (!(err instanceof LlmUnavailableError)) throw err; - // The endpoint settings could not be read; the call is refused rather than sent elsewhere. - return forward( - new Response( - JSON.stringify({ - error: { message: err.message, type: 'api_error', code: 'LLM_SETTINGS_UNAVAILABLE' }, - }), - { status: 503, headers: { 'Content-Type': 'application/json' } } - ) + return new Response( + JSON.stringify({ + error: { message: err.message, type: 'api_error', code: 'LLM_SETTINGS_UNAVAILABLE' }, + }), + { status: 503, headers: { 'Content-Type': 'application/json' } } ); } - if (!target) { - // No Workers AI on this installation and no OpenAI-compatible endpoint configured. - return forward( - new Response( - JSON.stringify({ - error: { - message: 'This model route is not available on this installation.', - type: 'invalid_request_error', - code: 'FEATURE_UNAVAILABLE', - }, - }), - { status: 404, headers: { 'Content-Type': 'application/json' } } - ) + if (!target) + return new Response( + JSON.stringify({ + error: { message: 'Model route is unavailable', code: 'FEATURE_UNAVAILABLE' }, + }), + { status: 404, headers: { 'Content-Type': 'application/json' } } ); - } - const gatewayBody = withStreamUsageRequested(target, { ...body, model: target.model }); + const gatewayBody = { ...body, model: target.model }; const response = await fetchChatTarget(target, { method: 'POST', @@ -138,23 +110,24 @@ export async function forwardToWorkersAI( }); if (!response.ok) { + const errorText = await response.text(); log.error('ai_proxy.workers_ai_error', { status: response.status, - target: target.kind, - ...(await upstreamErrorLogFields(response, !isCloudflareChatTarget(target))), + body: + target.kind === 'openai-compatible' + ? '[external endpoint body omitted]' + : errorText.slice(0, 500), }); const errorHeaders = new Headers({ 'Content-Type': 'application/json' }); copyCredentialLimitHeaders(response.headers, errorHeaders); - return forward( - new Response( - JSON.stringify({ - error: { - message: `AI inference failed (${response.status}). Please try again.`, - type: 'server_error', - }, - }), - { status: response.status, headers: errorHeaders } - ) + return new Response( + JSON.stringify({ + error: { + message: `AI inference failed (${response.status}). Please try again.`, + type: 'server_error', + }, + }), + { status: response.status, headers: errorHeaders } ); } @@ -168,10 +141,12 @@ export async function forwardToWorkersAI( responseHeaders.set('X-Accel-Buffering', 'no'); } - return forward( - new Response(response.body, { status: response.status, headers: responseHeaders }), - !isCloudflareChatTarget(target) - ); + const forwarded = new Response(response.body, { + status: response.status, + headers: responseHeaders, + }); + if (target.kind === 'openai-compatible') customEndpointResponses.add(forwarded); + return forwarded; } /** Forward request to Anthropic via AI Gateway (with format translation). */ @@ -256,18 +231,6 @@ export async function forwardToAnthropic( } /** Forward request to OpenAI via AI Gateway (OpenAI-native format, no translation needed). */ -/** - * Without AI Gateway, SAM's own metering is the only spend record (`hasLocalAiCostMetering`), and - * OpenAI reports a stream's usage only when asked (`stream_options.include_usage`). Ask on every - * direct streamed call so a client that omits it cannot stream unmetered output. Gateway calls are - * sent byte for byte as before. - */ -function withDirectStreamUsage(env: Env, body: Record): Record { - if (!hasLocalAiCostMetering(env) || body.stream !== true) return body; - const streamOptions = maybeJsonRecord(body.stream_options) ?? {}; - return { ...body, stream_options: { ...streamOptions, include_usage: true } }; -} - export async function forwardToOpenAI( env: Env, body: Record, @@ -276,7 +239,7 @@ export async function forwardToOpenAI( openaiApiKey: string ): Promise { const gatewayUrl = buildOpenAIUrl(env); - const gatewayBody = withDirectStreamUsage(env, { ...body, model: modelId }); + const gatewayBody = { ...body, model: modelId }; // Use cf-aig-authorization for Unified Billing when available, otherwise standard Bearer const cfToken = resolveUnifiedBillingToken(env); diff --git a/apps/api/src/routes/ai-proxy.ts b/apps/api/src/routes/ai-proxy.ts index e3eb578cf1..8b36f15e98 100644 --- a/apps/api/src/routes/ai-proxy.ts +++ b/apps/api/src/routes/ai-proxy.ts @@ -1,3 +1,4 @@ +import { hasLocalAiCostMetering } from '@simple-agent-manager/ai-proxy'; /** * AI inference proxy — routes to Workers AI, Anthropic, or OpenAI via Cloudflare AI Gateway. * @@ -18,6 +19,7 @@ import { Hono } from 'hono'; import type { Env } from '../env'; import { log } from '../lib/logger'; import { readRequestJsonRecord } from '../lib/runtime-validation'; +import { proxyRunUsageRecorder } from '../services/agent-run-usage'; import type { UpstreamAuth } from '../services/ai-billing'; import { resolveUpstreamAuth } from '../services/ai-billing'; import { isAnthropicModel } from '../services/ai-proxy-shared'; @@ -47,6 +49,7 @@ import { schedulePlatformProxyLimitHeaders, } from './ai-proxy-platform-billing'; import { + customEndpointResponses, forwardToAnthropic, forwardToOpenAI, forwardToOpenAIResponses, @@ -167,7 +170,6 @@ aiProxyRoutes.post('/chat/completions', async (c) => { try { let response: Response; - let estimateMissingUsage = false; if (provider === 'anthropic') { if (!anthropicAuth) { // provider === 'anthropic' guarantees anthropicAuth was resolved above @@ -181,12 +183,7 @@ aiProxyRoutes.post('/chat/completions', async (c) => { } response = await forwardToOpenAI(c.env, body, modelId, aigMetadata, openaiCredential.apiKey); } else { - ({ response, estimateMissingUsage } = await forwardToWorkersAI( - c.env, - body, - modelId, - aigMetadata - )); + response = await forwardToWorkersAI(c.env, body, modelId, aigMetadata); } log.info('ai_proxy.response', { @@ -217,11 +214,23 @@ aiProxyRoutes.post('/chat/completions', async (c) => { }); } - return accountingResponse(c, response, prepared.userId, estimatedInputTokens, { - estimateMissingUsage, - // An admin's OpenAI-compatible endpoint serves its own model, which has no catalog price. - costModelId: estimateMissingUsage ? undefined : modelId, - }); + const attribution = provider === 'anthropic' ? anthropicAuth : openaiCredential; + return accountingResponse( + c, + response, + prepared.userId, + estimatedInputTokens, + proxyRunUsageRecorder(c.env, prepared, { + model: modelId, + credentialReference: attribution?.credentialReference ?? null, + credentialSource: attribution?.credentialSource ?? null, + }), + { + costModelId: customEndpointResponses.has(response) ? undefined : modelId, + estimateMissingUsage: + customEndpointResponses.has(response) || hasLocalAiCostMetering(c.env), + } + ); } catch (err) { log.error('ai_proxy.fetch_error', { userId: prepared.userId, @@ -335,9 +344,18 @@ aiProxyRoutes.post('/responses', async (c) => { source: 'ai-proxy.openai.responses', }); - return accountingResponse(c, response, prepared.userId, estimatedInputTokens, { - costModelId: modelId, - }); + return accountingResponse( + c, + response, + prepared.userId, + estimatedInputTokens, + proxyRunUsageRecorder(c.env, prepared, { + model: modelId, + credentialReference: openaiCredential.credentialReference, + credentialSource: openaiCredential.credentialSource, + }), + { costModelId: modelId, estimateMissingUsage: hasLocalAiCostMetering(c.env) } + ); } catch (err) { log.error('ai_proxy.responses.fetch_error', { userId: prepared.userId, diff --git a/apps/api/src/routes/api-tokens.ts b/apps/api/src/routes/api-tokens.ts index ff4aa2b2fe..583858d562 100644 --- a/apps/api/src/routes/api-tokens.ts +++ b/apps/api/src/routes/api-tokens.ts @@ -199,7 +199,7 @@ apiTokenRoutes.post( .set({ lastUsedAt: new Date() }) .where(eq(schema.apiTokens.id, tokenRecord.id)); - return buildSessionLoginResponse(c.env, user); + return buildSessionLoginResponse(c.env, user, c.req.raw.headers); } ); diff --git a/apps/api/src/routes/artifacts-config.ts b/apps/api/src/routes/artifacts-config.ts new file mode 100644 index 0000000000..8674a45f8b --- /dev/null +++ b/apps/api/src/routes/artifacts-config.ts @@ -0,0 +1,17 @@ +import { Hono } from 'hono'; + +import type { Env } from '../env'; +import { applyCacheHeaders } from '../lib/cache-headers'; +import { isArtifactsAvailable } from '../services/hosted-git/backend'; + +/** + * Public config: whether this install can create SAM-native (Artifacts) repositories. True only + * when ARTIFACTS_ENABLED is set and a backend exists (the Cloudflare binding, or the backend a + * self-host build registered), so the UI never offers a provider that would fail on use. + */ +export const artifactsConfigRoutes = new Hono<{ Bindings: Env }>(); + +artifactsConfigRoutes.get('/artifacts-enabled', (c) => { + applyCacheHeaders(c, 'public-config'); + return c.json({ enabled: isArtifactsAvailable(c.env) }); +}); diff --git a/apps/api/src/routes/auth.ts b/apps/api/src/routes/auth.ts index 87d53a3939..e4baca996b 100644 --- a/apps/api/src/routes/auth.ts +++ b/apps/api/src/routes/auth.ts @@ -18,8 +18,10 @@ import { } from '../services/email-sign-in'; import { readAuthSession } from '../services/read-auth-session'; import { assertUserNotSuspended } from '../services/signup-approval'; +import { accountLinkingRoutes } from './account-linking'; const authRoutes = new Hono<{ Bindings: Env }>(); +authRoutes.route('/', accountLinkingRoutes); /** * GET /api/auth/me - Get current authenticated user @@ -97,25 +99,6 @@ authRoutes.post(EMAIL_CODE_SIGN_IN_PATH, async (c, next) => { } }); -/** - * "Connect GitHub/GitLab" links only the providers whose sign-in keeps a linked account's own - * email (`keepLinkedAccountEmail` in their `getUserInfo`); linking accepts a provider account - * with a different email (`accountLinking.allowDifferentEmails`), so any other provider could - * later overwrite the SAM email at sign-in. - */ -const LINKABLE_PROVIDERS = new Set(['github', 'gitlab']); -authRoutes.post('/link-social', async (c, next) => { - const body: unknown = await c.req.raw - .clone() - .json() - .catch(() => null); - const provider = maybeJsonRecord(body)?.provider; - if (typeof provider !== 'string' || !LINKABLE_PROVIDERS.has(provider)) { - throw errors.badRequest('Only GitHub and GitLab can be connected to an account'); - } - return next(); -}); - /** * better-auth endpoints that hand out, refresh or use a stored provider token. SAM reads tokens * server-side through `getBetterAuthAccessTokenForProvider`, which only uses an account the diff --git a/apps/api/src/routes/chat-load-diagnostics.ts b/apps/api/src/routes/chat-load-diagnostics.ts index 807e2bc2e9..abc938b8ae 100644 --- a/apps/api/src/routes/chat-load-diagnostics.ts +++ b/apps/api/src/routes/chat-load-diagnostics.ts @@ -71,7 +71,7 @@ export async function recordChatSessionLoadFailure( context, userId: input.userId, sessionId: input.sessionId, - ipAddress: clientIpFromHeaders((name) => c.req.header(name)), + ipAddress: clientIpFromHeaders((name) => c.req.header(name)) ?? null, userAgent: c.req.header('User-Agent') ?? null, }, c.env diff --git a/apps/api/src/routes/chat-session-detail.ts b/apps/api/src/routes/chat-session-detail.ts index 57d1fe3e53..57089f83d2 100644 --- a/apps/api/src/routes/chat-session-detail.ts +++ b/apps/api/src/routes/chat-session-detail.ts @@ -24,6 +24,7 @@ import { errors } from '../middleware/error'; import { operationDeps } from '../operation-ports'; import { resolveTaskAgentProfileHint } from '../services/agent-profile-display'; import * as projectDataService from '../services/project-data'; +import { canResumeProviderLimitTaskAnyway } from '../services/provider-limit-force-resume'; import { canStartProviderLimitTaskAnyway } from '../services/provider-limit-recovery'; import { publicPlacementExplanationJson } from '../services/public-placement-explanation'; import { isTaskStatus } from '../services/task-status'; @@ -38,6 +39,7 @@ import { } from './chat-message-query'; import { getChatSessionRouteContext } from './chat-route-context'; import { enrichSessionWithAccess } from './chat-session-ownership'; +import { readChatToolChanges } from './chat-tool-changes'; export function registerChatSessionDetailRoute(chatRoutes: Hono<{ Bindings: Env }>): void { /** @@ -71,6 +73,7 @@ export function registerChatSessionDetailRoute(chatRoutes: Hono<{ Bindings: Env throw errors.notFound('Chat session'); } + const toolChanges = await readChatToolChanges(c, projectId, sessionId); const limit = getSessionMessageLimit(c.env, c.req.query('limit')); const before = getMessageCursor('before', c.req.query('before')); const after = getMessageCursor('after', c.req.query('after')); @@ -184,6 +187,13 @@ export function registerChatSessionDetailRoute(chatRoutes: Hono<{ Bindings: Env taskRow, parseProviderLimitWait(taskRow.providerLimitWaitJson) ), + providerLimitCanResumeAnyway: + taskRow.userId === userId && + sessionRecord.status === 'sleeping' && + canResumeProviderLimitTaskAnyway( + taskRow, + parseProviderLimitWait(taskRow.providerLimitWaitJson) + ), status: isTaskStatus(taskRow.status) ? taskRow.status : 'draft', executionStep: isTaskExecutionStep(taskRow.executionStep) ? taskRow.executionStep @@ -245,6 +255,7 @@ export function registerChatSessionDetailRoute(chatRoutes: Hono<{ Bindings: Env { access: loaded.access, grants: loaded.grants, undelivered: loaded.undelivered } ), messages: messagesResult.messages, + ...(toolChanges ? { toolChanges } : {}), hasMore: messagesResult.hasMore, state: stateWithRecovery, }); diff --git a/apps/api/src/routes/chat-stop.ts b/apps/api/src/routes/chat-stop.ts index e7510869a7..21c9eab870 100644 --- a/apps/api/src/routes/chat-stop.ts +++ b/apps/api/src/routes/chat-stop.ts @@ -13,7 +13,9 @@ import * as chatPersistence from '../services/chat-persistence'; import { requireSessionWriter } from '../services/session-access'; import { ensureSessionTaskBacked } from '../services/session-task-repair'; import { isSleepingContainerRuntime } from '../services/sleeping-container-runtime'; -import { isExecutableTaskStatus, isTaskStatus } from '../services/task-status'; +import { retireTaskCancellationPrompts } from '../services/task-cancellation-prompts'; +import { taskRecoveryCancellationQuery } from '../services/task-recovery-cancellation'; +import { canTransitionTaskStatus, isTaskStatus } from '../services/task-status'; import { cleanupTerminalTaskResources, type TerminalTaskCleanupStatus, @@ -37,6 +39,10 @@ type TaskForStop = { id: string; status: string; errorMessage: string | null; + projectId: string; + userId: string; + chatSessionId: string | null; + workspaceId: string | null; }; async function findTaskForStop( @@ -49,6 +55,10 @@ async function findTaskForStop( id: schema.tasks.id, status: schema.tasks.status, errorMessage: schema.tasks.errorMessage, + projectId: schema.tasks.projectId, + userId: schema.tasks.userId, + chatSessionId: schema.tasks.chatSessionId, + workspaceId: schema.tasks.workspaceId, }) .from(schema.tasks) .where( @@ -77,20 +87,31 @@ async function cancelExecutableTaskForArchive( taskId: string, userId: string ): Promise { - if (!isTaskStatus(task.status) || !isExecutableTaskStatus(task.status)) { + if (!isTaskStatus(task.status) || !canTransitionTaskStatus(task.status, 'cancelled')) { return; } const now = new Date().toISOString(); - await db - .update(schema.tasks) - .set({ - status: 'cancelled', - errorMessage: 'Archived by user', - completedAt: now, - updatedAt: now, - }) - .where(eq(schema.tasks.id, taskId)); + const [cancelled] = await db.batch([ + db + .update(schema.tasks) + .set({ + status: 'cancelled', + errorMessage: 'Archived by user', + completedAt: now, + updatedAt: now, + }) + .where( + and( + eq(schema.tasks.id, taskId), + eq(schema.tasks.projectId, task.projectId), + eq(schema.tasks.status, task.status) + ) + ) + .returning({ id: schema.tasks.id }), + taskRecoveryCancellationQuery(db, task, now), + ]); + if (!cancelled.length) return; await db.insert(schema.taskStatusEvents).values({ id: ulid(), taskId, @@ -114,6 +135,8 @@ async function stopTaskBackedSession( await context.assertEffectAllowed?.(); if (task && !terminalStatus) { + await retireTaskCancellationPrompts(env, task, context.assertEffectAllowed); + await context.assertEffectAllowed?.(); await cancelExecutableTaskForArchive(db, task, taskId, context.actorUserId); } @@ -124,6 +147,7 @@ async function stopTaskBackedSession( errorMessage: cleanupStatus === 'failed' ? (task?.errorMessage ?? null) : 'Archived by user', destructiveSessionEnd: true, requireStopAcknowledgement: context.requireStopAcknowledgement, + beforeSideEffect: context.assertEffectAllowed, logContext: { projectId: context.projectId, sessionId: context.sessionId, diff --git a/apps/api/src/routes/chat-tool-changes.ts b/apps/api/src/routes/chat-tool-changes.ts new file mode 100644 index 0000000000..f8ddbaea51 --- /dev/null +++ b/apps/api/src/routes/chat-tool-changes.ts @@ -0,0 +1,27 @@ +import { CHAT_TOOL_REPLACE_CAPABILITY } from '@simple-agent-manager/shared'; +import type { Context } from 'hono'; + +import type { Env } from '../env'; +import { errors } from '../middleware/error'; +import { resolveAdminSetting } from '../services/admin-settings'; +import { getToolChanges } from '../services/project-data'; + +/** Legacy reads seal mutability BEFORE their snapshot. OFF adds no transcript writes/RPC. */ +export async function readChatToolChanges( + c: Context<{ Bindings: Env }>, + projectId: string, + sessionId: string +) { + if ((await resolveAdminSetting(c.env, 'chat.toolCallMergingEnabled')) !== true) return undefined; + const raw = c.req.query('afterToolRevision'); + const afterRevision = raw === undefined ? undefined : Number(raw); + if (afterRevision !== undefined && (!Number.isSafeInteger(afterRevision) || afterRevision < 0)) + throw errors.badRequest('afterToolRevision must be a nonnegative integer'); + return getToolChanges( + c.env, + projectId, + sessionId, + afterRevision, + c.req.query('toolReplace') !== CHAT_TOOL_REPLACE_CAPABILITY + ); +} diff --git a/apps/api/src/routes/chat.ts b/apps/api/src/routes/chat.ts index 3e75bdf5a5..39aee2bef6 100644 --- a/apps/api/src/routes/chat.ts +++ b/apps/api/src/routes/chat.ts @@ -42,6 +42,7 @@ import { registerChatSessionDetailRoute } from './chat-session-detail'; import { registerChatSessionListRoute } from './chat-session-list'; import { chatStateRoutes } from './chat-state'; import { registerChatStopRoute } from './chat-stop'; +import { readChatToolChanges } from './chat-tool-changes'; import { registerChatWorkloadIdentityRoute } from './chat-workload-identity'; const chatRoutes = new Hono<{ Bindings: Env }>(); @@ -162,6 +163,7 @@ chatRoutes.get('/:sessionId/messages', async (c) => { const compact = getCompactMode(c.req.query('compact'), getDefaultCompactMode(c.env)); + const toolChanges = await readChatToolChanges(c, projectId, sessionId); const messagesResult = await projectDataService.getMessages( c.env, projectId, @@ -174,7 +176,7 @@ chatRoutes.get('/:sessionId/messages', async (c) => { order ); - return c.json(messagesResult); + return c.json({ ...messagesResult, ...(toolChanges ? { toolChanges } : {}) }); }); /** @@ -204,6 +206,8 @@ chatRoutes.get('/:sessionId/messages/:messageId/tool-content', async (c) => { throw errors.notFound('Message tool content'); } + // A canonical tool ID has mutable output; browser/proxy caches must revalidate it. + c.header('Cache-Control', 'no-store'); return c.json(toolContent); }); diff --git a/apps/api/src/routes/device-flow.ts b/apps/api/src/routes/device-flow.ts index 4b5994d61e..0af9a8d89d 100644 --- a/apps/api/src/routes/device-flow.ts +++ b/apps/api/src/routes/device-flow.ts @@ -233,7 +233,7 @@ deviceFlowRoutes.post( await c.env.KV.delete(`device:${deviceCode}`); - return buildSessionLoginResponse(c.env, user); + return buildSessionLoginResponse(c.env, user, c.req.raw.headers); } ); diff --git a/apps/api/src/routes/github-installation-sync.ts b/apps/api/src/routes/github-installation-sync.ts index f905063290..e548c6987c 100644 --- a/apps/api/src/routes/github-installation-sync.ts +++ b/apps/api/src/routes/github-installation-sync.ts @@ -5,7 +5,6 @@ import * as schema from '../db/schema'; import type { Env } from '../env'; import { log } from '../lib/logger'; import { ulid } from '../lib/ulid'; -import { errors } from '../middleware/error'; import { type AuthenticatedGitHubUser, getAuthenticatedUserOrganizations, @@ -57,10 +56,7 @@ export async function getRequiredGitHubUserAccessToken( tokenPresent: Boolean(accessToken), }); if (!accessToken) { - // Never linked (an email-signed account): say what fixes it. Otherwise keep the 403. - const unavailable = await githubUserTokenUnavailableError(c.env, userId); - if (unavailable.error === 'GITHUB_NOT_CONNECTED') throw unavailable; - throw errors.forbidden('GitHub user token unavailable'); + throw await githubUserTokenUnavailableError(c.env, userId); } return accessToken; } diff --git a/apps/api/src/routes/github-installations.ts b/apps/api/src/routes/github-installations.ts index ab5bfdcc68..02e2ed68b7 100644 --- a/apps/api/src/routes/github-installations.ts +++ b/apps/api/src/routes/github-installations.ts @@ -13,6 +13,7 @@ import { IoTimeoutError, withDeadline } from '../services/fetch-timeout'; import { getAuthenticatedGitHubUser, getUserAccessibleInstallations } from '../services/github-app'; import { normalizeAccountType } from '../services/github-installation-accounts'; import { getExternalInstallationId } from '../services/github-installation-ids'; +import { githubUserTokenUnavailableError } from '../services/github-token-errors'; import { getGitHubUserAccessToken } from '../services/github-user-access-token'; import { filterVisibleInstallations, syncUserInstallations } from './github-installation-sync'; export function registerGitHubInstallationsRoute(githubRoutes: Hono<{ Bindings: Env }>) { @@ -37,6 +38,7 @@ export function registerGitHubInstallationsRoute(githubRoutes: Hono<{ Bindings: userId, tokenPresent: Boolean(accessToken), }); + if (!accessToken) throw await githubUserTokenUnavailableError(c.env, userId); const verified = accessToken ? await Promise.all([ getAuthenticatedGitHubUser(accessToken, { flow: 'sync', userId, ...io }), diff --git a/apps/api/src/routes/inbox-tasks.ts b/apps/api/src/routes/inbox-tasks.ts new file mode 100644 index 0000000000..e295e8fdd5 --- /dev/null +++ b/apps/api/src/routes/inbox-tasks.ts @@ -0,0 +1,158 @@ +/** + * Human tasks, the person side (inbox slice H1): tick a step, comment, take a team task, hand it + * on, mark it done, reopen it. Archive is the inbox's own `POST …/items/:ref/archive`, which closes + * a task through the same operation. Each route is a thin adapter over + * `packages/operations/src/inbox-task-core.ts`; the task view is `GET …/items/:ref` (`task`). + * + * Mounted at `/api/projects/:projectId/inbox` beside `projectInboxRoutes`. Browser-facing session + * routes (rule 34 does not apply); writes require the app's Origin and a JSON body like every + * other inbox write. `:ref` is `ask:`; any other ref names no task and reads not-found. + */ +import { + claimTask, + commentOnTask, + completeTask, + reassignTask, + reopenTask, + setTaskStep, + TASK_NOT_FOUND, + toOperationHttpError, +} from '@simple-agent-manager/operations'; +import { parseInboxRef } from '@simple-agent-manager/shared'; +import { type Context, Hono } from 'hono'; +import * as v from 'valibot'; + +import type { Env } from '../env'; +import { requireRouteParam } from '../lib/route-helpers'; +import { getUserId, requireApproved, requireAuth } from '../middleware/auth'; +import { errors } from '../middleware/error'; +import { webOperationContext } from '../operation-ports'; +import { jsonValidator } from '../schemas/_validator'; +import { assertBrowserJsonWrite } from './projects/secret-requests'; + +const session = [requireAuth(), requireApproved()] as const; +type AppContext = Context<{ Bindings: Env }>; + +// Lengths are checked by the operations against `inbox.answerMaxChars`; these bound the shape. +const StepSchema = v.object({ done: v.boolean() }); +const CommentSchema = v.object({ + body: v.pipe(v.string(), v.minLength(1), v.maxLength(20_000)), + threadId: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(128))), + mentions: v.optional( + v.pipe( + v.array(v.object({ userId: v.pipe(v.string(), v.minLength(1), v.maxLength(128)) })), + v.maxLength(20) + ) + ), +}); +const ReassignSchema = v.union([ + v.object({ assigneeUserId: v.pipe(v.string(), v.minLength(1), v.maxLength(128)) }), + v.object({ team: v.literal(true) }), +]); +const DoneSchema = v.object({ note: v.optional(v.pipe(v.string(), v.maxLength(20_000))) }); +const EmptySchema = v.object({}); + +async function run(fn: () => Promise): Promise { + try { + return await fn(); + } catch (error) { + throw toOperationHttpError(error); + } +} + +function target(c: AppContext): { projectId: string; askId: string } { + const parsed = parseInboxRef(requireRouteParam(c, 'ref')); + if (!parsed || parsed.store !== 'ask') throw errors.notFound(TASK_NOT_FOUND); + return { projectId: requireRouteParam(c, 'projectId'), askId: parsed.id }; +} + +function context(c: AppContext) { + assertBrowserJsonWrite(c, 'inbox'); + return webOperationContext(c, getUserId(c)); +} + +export const projectInboxTaskRoutes = new Hono<{ Bindings: Env }>(); + +projectInboxTaskRoutes.post( + '/items/:ref/steps/:index', + ...session, + jsonValidator(StepSchema), + async (c) => { + const ctx = context(c); + const raw = requireRouteParam(c, 'index'); + // The whole segment must be digits: `parseInt('1junk')` would otherwise address step 1. + if (!/^\d{1,4}$/.test(raw)) throw errors.badRequest('No such step'); + const index = Number(raw); + const { done } = c.req.valid('json'); + return c.json(await run(() => setTaskStep(ctx, { ...target(c), index, done }))); + } +); + +projectInboxTaskRoutes.post( + '/items/:ref/comments', + ...session, + jsonValidator(CommentSchema), + async (c) => { + const ctx = context(c); + const body = c.req.valid('json'); + return c.json( + await run(() => + commentOnTask(ctx, { + ...target(c), + body: body.body, + threadId: body.threadId, + mentionUserIds: body.mentions?.map((mention) => mention.userId), + }) + ) + ); + } +); + +projectInboxTaskRoutes.post( + '/items/:ref/claim', + ...session, + jsonValidator(EmptySchema), + async (c) => { + const ctx = context(c); + return c.json(await run(() => claimTask(ctx, target(c)))); + } +); + +projectInboxTaskRoutes.post( + '/items/:ref/reassign', + ...session, + jsonValidator(ReassignSchema), + async (c) => { + const ctx = context(c); + const body = c.req.valid('json'); + return c.json( + await run(() => + reassignTask(ctx, { + ...target(c), + ...('team' in body ? { team: true } : { assigneeUserId: body.assigneeUserId }), + }) + ) + ); + } +); + +projectInboxTaskRoutes.post( + '/items/:ref/done', + ...session, + jsonValidator(DoneSchema), + async (c) => { + const ctx = context(c); + const { note } = c.req.valid('json'); + return c.json(await run(() => completeTask(ctx, { ...target(c), note }))); + } +); + +projectInboxTaskRoutes.post( + '/items/:ref/reopen', + ...session, + jsonValidator(EmptySchema), + async (c) => { + const ctx = context(c); + return c.json(await run(() => reopenTask(ctx, target(c)))); + } +); diff --git a/apps/api/src/routes/inbox.ts b/apps/api/src/routes/inbox.ts index b1893c0546..72d461bb87 100644 --- a/apps/api/src/routes/inbox.ts +++ b/apps/api/src/routes/inbox.ts @@ -9,6 +9,7 @@ * GET /api/projects/:projectId/inbox/count * GET /api/projects/:projectId/inbox/items/:ref?context=true — one item (+ transcript context) * POST /api/projects/:projectId/inbox/items/:ref/answer — answer through the item's store + * (a system error item takes `{action}`: retry, wake or resume, `inbox-error-core.ts`) * POST /api/projects/:projectId/inbox/items/:ref/archive — close; the agent is told * * Writes come only from the app's own pages (exact origin, JSON body), like the interaction and @@ -25,13 +26,24 @@ import { listInbox, toOperationHttpError, } from '@simple-agent-manager/operations'; -import { INBOX_FILTERS, type InboxFilter } from '@simple-agent-manager/shared'; +import { + INBOX_ERROR_ACTIONS, + INBOX_FILTERS, + type InboxErrorAction, + type InboxFilter, + parseInboxRef, +} from '@simple-agent-manager/shared'; import { type Context, Hono } from 'hono'; import type { Env } from '../env'; import { readBoundedRequestBody, RequestBodyTooLargeError } from '../lib/bounded-request-body'; import { requireRouteParam } from '../lib/route-helpers'; -import { getUserId, requireApproved, requireAuth } from '../middleware/auth'; +import { + assertNotAgentSignInSession, + getUserId, + requireApproved, + requireAuth, +} from '../middleware/auth'; import { errors } from '../middleware/error'; import { webOperationContext } from '../operation-ports'; import { getRuntimeLimits } from '../services/limits'; @@ -138,6 +150,14 @@ async function readAnswerBody(c: AppContext): Promise { projectInboxRoutes.post('/items/:ref/answer', ...session, async (c) => { assertBrowserJsonWrite(c, 'inbox'); const body = await readAnswerBody(c); + // A system error's fix (retry, wake, resume) is a person's call: an agent's sign-in session may + // not run it, as the trigger PATCH route refuses an agent a resume (`onlyStandsDown`). + if (body.action !== undefined) assertNotAgentSignInSession(c); const ctx = webOperationContext(c, getUserId(c)); return c.json( await run(() => @@ -213,13 +236,23 @@ projectInboxRoutes.post('/items/:ref/answer', ...session, async (c) => { projectInboxRoutes.post('/items/:ref/archive', ...session, async (c) => { assertBrowserJsonWrite(c, 'inbox'); + const projectId = requireRouteParam(c, 'projectId'); + const ref = requireRouteParam(c, 'ref'); + // A system error item is SAM's alert to the person, and archiving it keeps later repeats quiet: + // an agent's sign-in session may not dismiss it. One read, for agent sign-in sessions only. + if (c.get('auth')?.session.agentSignIn && (await isErrorItemRef(c.env, projectId, ref))) + assertNotAgentSignInSession(c); const ctx = webOperationContext(c, getUserId(c)); - return c.json( - await run(() => - archiveInboxItem(ctx, { - projectId: requireRouteParam(c, 'projectId'), - ref: requireRouteParam(c, 'ref'), - }) - ) - ); + return c.json(await run(() => archiveInboxItem(ctx, { projectId, ref }))); }); + +async function isErrorItemRef(env: Env, projectId: string, ref: string): Promise { + const parsed = parseInboxRef(ref); + if (parsed?.store !== 'ask') return false; + const row = await env.DATABASE.prepare( + `SELECT 1 AS ok FROM asks WHERE id = ? AND project_id = ? AND kind = 'error'` + ) + .bind(parsed.id, projectId) + .first(); + return Boolean(row); +} diff --git a/apps/api/src/routes/mcp/dispatch-task-storage.ts b/apps/api/src/routes/mcp/dispatch-task-storage.ts new file mode 100644 index 0000000000..24455d741d --- /dev/null +++ b/apps/api/src/routes/mcp/dispatch-task-storage.ts @@ -0,0 +1,64 @@ +/** Atomic dispatch task persistence, separated from profile/runtime orchestration. */ +import type { Env } from '../../env'; +import { + CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS, + CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS, +} from '../../services/capacity-placement-snapshot'; +import { ACTIVE_STATUSES } from './_helpers'; + +export function insertDispatchedTask( + env: Env, + values: unknown[], + limits: { + parentTaskId: string; + projectId: string; + maxPerTask: number; + maxActive: number; + missionId: string | null; + } +): Promise { + const statusPlaceholders = ACTIVE_STATUSES.map(() => '?').join(', '); + return env.DATABASE.prepare( + `INSERT INTO tasks (id, project_id, user_id, parent_task_id, chat_session_id, title, description, + status, execution_step, priority, dispatch_depth, output_branch, created_by, + task_mode, agent_profile_hint, skill_id, skill_hint, mission_id, coordination_channel, triggered_by, + requested_vm_size, requested_vm_size_source, resource_requirements_json, resource_requirement_plan_json, resource_requirements_source, resolved_reservation_json, + credential_attribution_user_id, credential_attribution_project_id, credential_attribution_source, + ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS}, + created_at, updated_at) + SELECT ?, ?, ?, ?, ?, ?, ?, 'queued', 'node_selection', ?, ?, ?, ?, + ?, ?, ?, ?, ?, ?, 'mcp', + ?, ?, ?, ?, ?, ?, + ?, ?, ?, + ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS}, + ?, ? + WHERE ( + SELECT count(*) FROM tasks + WHERE parent_task_id = ? AND project_id = ? + AND status IN (${statusPlaceholders}) + ) < ? + AND ( + SELECT count(*) FROM tasks + WHERE project_id = ? AND status IN (${statusPlaceholders}) + AND dispatch_depth > 0 + ) < ? + AND (? IS NULL OR EXISTS ( + SELECT 1 FROM missions WHERE id = ? AND project_id = ? + AND status NOT IN ('cancelled', 'completed', 'failed') + ))` + ) + .bind( + ...values, + limits.parentTaskId, + limits.projectId, + ...ACTIVE_STATUSES, + limits.maxPerTask, + limits.projectId, + ...ACTIVE_STATUSES, + limits.maxActive, + limits.missionId, + limits.missionId, + limits.projectId + ) + .run(); +} diff --git a/apps/api/src/routes/mcp/dispatch-tool.ts b/apps/api/src/routes/mcp/dispatch-tool.ts index 67a8228fa2..c817096eb8 100644 --- a/apps/api/src/routes/mcp/dispatch-tool.ts +++ b/apps/api/src/routes/mcp/dispatch-tool.ts @@ -21,11 +21,7 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { ulid } from '../../lib/ulid'; import { generateBranchName } from '../../services/branch-name'; -import { - CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS, - CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS, - capacityPlacementSnapshotSqlValues, -} from '../../services/capacity-placement-snapshot'; +import { capacityPlacementSnapshotSqlValues } from '../../services/capacity-placement-snapshot'; import { PlacementResolutionError, resolveTaskStartPlacement, @@ -62,6 +58,7 @@ import { launchDispatchedInstantSession, } from './dispatch-instant'; import { buildDispatchTaskSuccessResponse } from './dispatch-task-response'; +import { insertDispatchedTask } from './dispatch-task-storage'; import { parseDispatchTaskParams } from './dispatch-tool-params'; import { requireMcpTaskWriteProject } from './task-project-access'; @@ -445,35 +442,10 @@ export async function handleDispatchTask( } } - // ── Atomic conditional INSERT (prevents TOCTOU race) ───────────────── - const statusPlaceholders = ACTIVE_STATUSES.map(() => '?').join(', '); - const conditionalInsertResult = await env.DATABASE.prepare( - `INSERT INTO tasks (id, project_id, user_id, parent_task_id, chat_session_id, title, description, - status, execution_step, priority, dispatch_depth, output_branch, created_by, - task_mode, agent_profile_hint, skill_id, skill_hint, mission_id, coordination_channel, triggered_by, - requested_vm_size, requested_vm_size_source, resource_requirements_json, resource_requirement_plan_json, resource_requirements_source, resolved_reservation_json, - credential_attribution_user_id, credential_attribution_project_id, credential_attribution_source, - ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_COLUMNS}, - created_at, updated_at) - SELECT ?, ?, ?, ?, ?, ?, ?, 'queued', 'node_selection', ?, ?, ?, ?, - ?, ?, ?, ?, ?, ?, 'mcp', - ?, ?, ?, ?, ?, ?, - ?, ?, ?, - ${CAPACITY_PLACEMENT_SNAPSHOT_SQL_PLACEHOLDERS}, - ?, ? - WHERE ( - SELECT count(*) FROM tasks - WHERE parent_task_id = ? AND project_id = ? - AND status IN (${statusPlaceholders}) - ) < ? - AND ( - SELECT count(*) FROM tasks - WHERE project_id = ? AND status IN (${statusPlaceholders}) - AND dispatch_depth > 0 - ) < ?` - ) - .bind( - // INSERT values + // Atomic persistence includes the existing project/parent dispatch limits. + const conditionalInsertResult = await insertDispatchedTask( + env, + [ taskId, tokenData.projectId, tokenData.userId, @@ -503,29 +475,30 @@ export async function handleDispatchTask( ...capacityPlacementSnapshotSqlValues(capacityPlacementSnapshot), now, now, - // Per-task child count subquery - tokenData.taskId, - tokenData.projectId, - ...ACTIVE_STATUSES, - effectiveMaxPerTask, - // Per-project active count subquery - tokenData.projectId, - ...ACTIVE_STATUSES, - effectiveMaxActive - ) - .run(); + ], + { + parentTaskId: tokenData.taskId, + projectId: tokenData.projectId, + maxPerTask: effectiveMaxPerTask, + maxActive: effectiveMaxActive, + missionId: explicitMissionId ?? currentTask.missionId ?? null, + } + ); if (!conditionalInsertResult.meta.changes || conditionalInsertResult.meta.changes === 0) { log.warn('mcp.dispatch_task.atomic_limit_breach', { taskId, projectId: tokenData.projectId, + missionId: explicitMissionId ?? currentTask.missionId ?? null, maxPerTask: effectiveMaxPerTask, maxActive: effectiveMaxActive, }); return jsonRpcError( requestId, INVALID_PARAMS, - 'Dispatch rate limit exceeded (concurrent dispatch detected). Please retry.' + (explicitMissionId ?? currentTask.missionId) + ? 'Dispatch admission rejected: the mission is unavailable or the concurrent dispatch limit was reached.' + : 'Dispatch rate limit exceeded (concurrent dispatch detected). Please retry.' ); } diff --git a/apps/api/src/routes/mcp/inbox-tools.ts b/apps/api/src/routes/mcp/inbox-tools.ts index beae2565d6..a169eb47a4 100644 --- a/apps/api/src/routes/mcp/inbox-tools.ts +++ b/apps/api/src/routes/mcp/inbox-tools.ts @@ -1,16 +1,22 @@ /** - * MCP adapters for the agent inbox tools (slice D): `inbox_write` (ask, review, update, cancel) + * MCP adapters for the agent inbox tools (slices D and H1): `inbox_write` (ask, review, result, + * assign, comment, attach, update, cancel) * and `inbox_read` (list, get). Each one resolves where the call came from (project, chat, task, * person) from the verified token, runs the shared operation (`fileAgentAsk`, ...), and formats * the result. No inbox rule lives here. */ import { + type AgentAssignResult, type AgentFileResult, type AgentInboxSource, + assignAgentTask, + attachAgentTask, cancelAgentAsk, + commentAgentTask, fileAgentAsk, + fileAgentResult, fileAgentReview, - getAgentAsk, + getAgentItem, listAgentAsks, type OperationContext, OperationError, @@ -149,7 +155,9 @@ function filed(result: AgentFileResult) { ? `This idempotencyKey already filed ${result.ref}; nothing new was filed.` : result.blocking ? 'Filed in the person’s inbox. End your turn if you cannot continue: you will be woken in this chat when they answer.' - : 'Filed in the person’s inbox. Keep working: you will be told in this chat when they answer.'; + : result.kind === 'result' + ? 'Filed in the person’s inbox. If they reply while your task is still running, you will be woken in this chat with the reply; "Got it" does not wake you.' + : 'Filed in the person’s inbox. Keep working: you will be told in this chat when they answer.'; const duplicateHint = result.similar.length > 0 ? ' Similar open items exist (see `similar`): if one already covers this, cancel yours with inbox_write method cancel and say which one to use.' @@ -186,6 +194,11 @@ export const handleInboxReview: Handler = (requestId, params, tokenData, env) => filed(await fileAgentReview(ctx, source, params as Parameters[2])) ); +export const handleInboxResult: Handler = (requestId, params, tokenData, env) => + run(requestId, 'inbox_write result', tokenData, env, async (ctx, source) => + filed(await fileAgentResult(ctx, source, params as Parameters[2])) + ); + export const handleInboxUpdateItem: Handler = (requestId, params, tokenData, env) => run(requestId, 'inbox_write update', tokenData, env, (ctx, source) => updateAgentAsk(ctx, source, params as Parameters[2]) @@ -208,5 +221,49 @@ export const handleInboxListItems: Handler = (requestId, params, tokenData, env) export const handleInboxGetItem: Handler = (requestId, params, tokenData, env) => run(requestId, 'inbox_read get', tokenData, env, async (ctx, source) => ({ - item: await getAgentAsk(ctx, source, { ref: typeof params.ref === 'string' ? params.ref : '' }), + item: await getAgentItem(ctx, source, { + ref: typeof params.ref === 'string' ? params.ref : '', + }), })); + +/** The assign result: `inboxItem` is what the chat card reads, as for an ask or a review. */ +function assigned(result: AgentAssignResult) { + const next = !result.created + ? `This task was already assigned as ${result.ref}; nothing new was filed.` + : 'Assigned. It does not block you: keep working. You will be woken in this chat when the person comments, takes it, hands it on, finishes, reopens or archives it.'; + const watch = result.watching + ? '' + : ' This chat could not be subscribed to the task yet; repeat this assign call with the same idempotencyKey (or title) to subscribe it.'; + const duplicateHint = + result.similar.length > 0 + ? ' Similar open items exist (see `similar`): if one already covers this, cancel yours with inbox_write method cancel.' + : ''; + return { + message: next + watch + duplicateHint, + inboxItem: { + ref: result.ref, + id: result.id, + sessionId: result.sessionId, + kind: result.kind, + blocking: result.blocking, + }, + created: result.created, + watching: result.watching, + similar: result.similar, + }; +} + +export const handleInboxAssign: Handler = (requestId, params, tokenData, env) => + run(requestId, 'inbox_write assign', tokenData, env, async (ctx, source) => + assigned(await assignAgentTask(ctx, source, params as Parameters[2])) + ); + +export const handleInboxComment: Handler = (requestId, params, tokenData, env) => + run(requestId, 'inbox_write comment', tokenData, env, (ctx, source) => + commentAgentTask(ctx, source, params as Parameters[2]) + ); + +export const handleInboxAttach: Handler = (requestId, params, tokenData, env) => + run(requestId, 'inbox_write attach', tokenData, env, (ctx, source) => + attachAgentTask(ctx, source, params as Parameters[2]) + ); diff --git a/apps/api/src/routes/mcp/instruction-inbox-guidance.ts b/apps/api/src/routes/mcp/instruction-inbox-guidance.ts index 2240b12c0c..2a59f24672 100644 --- a/apps/api/src/routes/mcp/instruction-inbox-guidance.ts +++ b/apps/api/src/routes/mcp/instruction-inbox-guidance.ts @@ -1,18 +1,28 @@ /** * The turn-end rule every agent session gets from `get_instructions` (inbox slice D, idea - * 01M7G03ZCQ6TM6CMEYDRKQ8ST9 spec section 5). It is loaded into every session of every project, - * so it stays one paragraph (about 1.1 KB) and is not repeated elsewhere; tool descriptions and - * the MCP server instructions only point at the tools. It names SAM tools only, never a - * repository's own skills or conventions (policy "idea execution must be repository-agnostic"). + * 01M7G03ZCQ6TM6CMEYDRKQ8ST9 spec section 5; Result items, task + * `tasks/archive/2026-11-18-inbox-result-items-and-turn-end-guidance.md`). It is loaded into every + * session of every project, so it stays one paragraph (about 1.8 KB) and is not repeated elsewhere; + * tool descriptions and the MCP server instructions only point at the tools. It names SAM tools + * only, never a repository's own skills or conventions (policy "idea execution must be + * repository-agnostic"). + * + * Raphaël, 2026-11-17: "a human will never see anything in this chat session unless you put it in + * the inbox ... agents should be careful to only put things that really matter in there and to + * phrase things in a very human manner." 2026-11-18: "guide agents to use markdown, clear and + * simple language, and provide some brief easy-to-read context for everything they put in the + * inbox." The inbox renders `why` as markdown (`InboxItemView`, `InboxItemCard`). */ export const INBOX_TURN_END_INSTRUCTION = - 'People do not watch chats; they read their inbox. When you end a turn you must be in exactly one of three states: ' + - '(1) finished: say so, and in task mode call `complete_task`; ' + + 'Nobody reads this chat. A person sees only what you put in their inbox (`inbox_write`), so anything meant for them goes there: ' + + 'the answer or finished work they asked for (method `result`), something you want them to check (`review`), a decision you need (`ask`), or work only a person can do (`assign`). ' + + 'When you end a turn you must be in exactly one of three states: ' + + '(1) finished: if a person asked for this, file a `result` with what they need; if another agent dispatched this task, report back to that agent instead and file nothing; a routine run with nothing worth a person’s attention files nothing; in task mode also call `complete_task`, and since a person cannot reply to you once your task has completed, `ask` before completing when you need their answer; ' + '(2) waiting on a machine (subtasks, CI, a schedule): a durable wait is registered; ' + - '(3) waiting on a person: an open inbox item from this chat (`inbox_write`) states exactly what you need. ' + - 'A question that exists only in your message will not be seen: if you end a turn without filing an inbox item, the person will assume there is nothing for them to do, review or check, and will not open this chat. ' + - 'If you want them to evaluate something, file a review (`inbox_write` method `review`). ' + + '(3) waiting on a person: an open inbox item from this chat states exactly what you need. ' + + 'If you end a turn without filing an item, the person will assume there is nothing for them and will not open this chat. ' + + 'File only what is worth a person’s time, one thing per item. ' + + 'Write like a short note to a colleague, in clear, simple language: the title is the outcome or the ask in one plain sentence (no markdown); `why` always gives brief, easy-to-read context in markdown (short paragraphs, bullet lists, **bold** for what matters) so they can understand and act without opening the chat; lead with what matters; no IDs, jargon or tool names; link the ideas, Library files, PRs or previews they need instead of pasting them. ' + 'Before filing, call `inbox_read` method `list`; if an open item already covers it, do not file another. ' + - 'File one ask per item, with a one-sentence title, a short reason, and links to the ideas, Library files, policies, PRs or previews the person needs. ' + - 'Use a blocking ask only when you cannot continue; otherwise file a non-blocking one and keep working. ' + - 'You will be woken in this chat when the person answers.'; + 'Use a blocking ask only when you cannot continue; otherwise keep working. ' + + 'You will be woken in this chat when the person answers or replies.'; diff --git a/apps/api/src/routes/mcp/instruction-tools.ts b/apps/api/src/routes/mcp/instruction-tools.ts index a095e5814a..e47f0429fa 100644 --- a/apps/api/src/routes/mcp/instruction-tools.ts +++ b/apps/api/src/routes/mcp/instruction-tools.ts @@ -323,12 +323,20 @@ export async function handleGetInstructions( }, instructions: [ 'Tool names in these instructions refer to SAM MCP tools from the `sam-mcp` MCP server.', + // How to reach a person; the inbox tools need a task-backed agent token. Second, so it is + // read before the mode details: an agent that saw it eighth still answered in the chat. + ...(tokenData.taskId ? [INBOX_TURN_END_INSTRUCTION] : []), 'After reading this response, check whether the current chat session topic/title accurately reflects the actual work. ' + 'If the title is stale, generic, copied from a fork such as "get details from previous session", or the session changes direction later, ' + 'call the SAM MCP `update_session_topic` tool with a concise descriptive topic.', ...(isConversation ? [ - 'You are in a conversation with a human. Respond to their messages directly.', + // The chat is where the person writes to you, not where they read: answers go to + // their inbox (INBOX_TURN_END_INSTRUCTION, above). The inbox tools need a task, so a + // taskless conversation keeps answering in the chat. + tokenData.taskId + ? 'A person started this conversation and may write to you here, but they do not watch it: whatever you want them to see goes in their inbox, as described above.' + : 'You are in a conversation with a human. Respond to their messages directly.', 'Use the SAM MCP `dispatch_task` tool to spawn follow-up work to other agents when needed.', 'Use the SAM MCP `update_task_status` tool to report significant findings or progress.', 'Do NOT call the SAM MCP `complete_task` tool — the human will end the conversation when they are ready.', @@ -340,8 +348,6 @@ export async function handleGetInstructions( 'Push your changes to the output branch before calling the SAM MCP `complete_task` tool.', 'If you encounter blockers, report them via the SAM MCP `update_task_status` tool with a clear description.', ]), - // How to reach a person; the inbox tools need a task-backed agent token. - ...(tokenData.taskId ? [INBOX_TURN_END_INSTRUCTION] : []), // Event tools need a task-backed agent token. ...(tokenData.taskId ? buildEventingInstructions({ diff --git a/apps/api/src/routes/mcp/onboarding-tools.ts b/apps/api/src/routes/mcp/onboarding-tools.ts index bfc81d4946..720f9836e3 100644 --- a/apps/api/src/routes/mcp/onboarding-tools.ts +++ b/apps/api/src/routes/mcp/onboarding-tools.ts @@ -60,7 +60,7 @@ This connects to the SAM control plane. It's how you interact with tasks, projec - \`update_task_status\` — Report progress at significant milestones. The human sees these in the SAM dashboard in real time. Use them liberally — a human monitoring a long-running task has no other visibility into what you're doing. - \`complete_task\` — Call when ALL work is done and pushed. Include a clear summary and, when a pull request exists, pass its URL as \`evidence.prUrl\`. Only used in task mode — in conversation mode, the human ends the session. - \`dispatch_task\` — Spawn a new task for another agent. Use this when you discover work that's adjacent but outside your current scope. Describe the task clearly — the receiving agent gets only what you write here. -- \`inbox_write\` / \`inbox_read\` — How you reach a person: they read their inbox, not chats. Method \`ask\` files one question (blocking only when you cannot continue), \`review\` asks them to evaluate your work; check \`inbox_read\` method \`list\` first. \`request_human_input\` is an alias of a blocking ask. You are woken in this chat when they answer. +- \`inbox_write\` / \`inbox_read\` — The only way to reach a person: nobody reads the chat. Method \`result\` hands them the answer or finished work they asked for, \`review\` asks them to evaluate your work, \`ask\` files one question (blocking only when you cannot continue); check \`inbox_read\` method \`list\` first, and file only what matters, in plain words. \`request_human_input\` is an alias of a blocking ask. You are woken in this chat when they answer or reply. **Knowledge & History:** - \`tasks_read\` method \`search\` / \`tasks_read\` method \`get\` — Find and inspect other tasks in the project. Useful for understanding what work has been done or is in progress. diff --git a/apps/api/src/routes/mcp/orchestration-dependency-tools.ts b/apps/api/src/routes/mcp/orchestration-dependency-tools.ts index 055350d40a..74023520f3 100644 --- a/apps/api/src/routes/mcp/orchestration-dependency-tools.ts +++ b/apps/api/src/routes/mcp/orchestration-dependency-tools.ts @@ -14,6 +14,8 @@ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { ulid } from '../../lib/ulid'; +import { retireTaskCancellationPrompts } from '../../services/task-cancellation-prompts'; +import { taskRecoveryCancellationQuery } from '../../services/task-recovery-cancellation'; import { syncTriggerExecutionStatus } from '../../services/trigger-execution-sync'; import { ACTIVE_STATUSES, @@ -247,6 +249,9 @@ export async function handleRemovePendingSubtask( parentTaskId: schema.tasks.parentTaskId, status: schema.tasks.status, projectId: schema.tasks.projectId, + userId: schema.tasks.userId, + chatSessionId: schema.tasks.chatSessionId, + workspaceId: schema.tasks.workspaceId, }) .from(schema.tasks) .where(and(eq(schema.tasks.id, childTaskId), eq(schema.tasks.projectId, tokenData.projectId))) @@ -279,21 +284,29 @@ export async function handleRemovePendingSubtask( const now = new Date().toISOString(); - // Cancel the task - await db - .update(schema.tasks) - .set({ - status: 'cancelled', - completedAt: now, - updatedAt: now, - }) - .where(eq(schema.tasks.id, childTaskId)); + await retireTaskCancellationPrompts(env, childTask); + const [cancelled] = await db.batch([ + db + .update(schema.tasks) + .set({ status: 'cancelled', completedAt: now, updatedAt: now }) + .where( + and( + eq(schema.tasks.id, childTaskId), + eq(schema.tasks.projectId, childTask.projectId), + eq(schema.tasks.status, 'queued') + ) + ) + .returning({ id: schema.tasks.id }), + taskRecoveryCancellationQuery(db, childTask, now), + ]); + if (!cancelled.length) + return jsonRpcError( + requestId, + INVALID_PARAMS, + 'Task changed while removing the pending subtask' + ); - // Sync trigger execution status (best-effort) — without this, cron triggers - // with skipIfRunning=true permanently stop firing because the execution stays 'running'. await syncTriggerExecutionStatus(env.DATABASE, childTaskId, 'cancelled'); - - // Record status event await db.insert(schema.taskStatusEvents).values({ id: ulid(), taskId: childTaskId, diff --git a/apps/api/src/routes/mcp/orchestration-retry-storage.ts b/apps/api/src/routes/mcp/orchestration-retry-storage.ts new file mode 100644 index 0000000000..4828d7662d --- /dev/null +++ b/apps/api/src/routes/mcp/orchestration-retry-storage.ts @@ -0,0 +1,31 @@ +/** Replacement-task persistence, separate from retry placement and startup orchestration. */ +import { getTableColumns, sql } from 'drizzle-orm'; +import type { drizzle } from 'drizzle-orm/d1'; + +import * as schema from '../../db/schema'; + +type Db = ReturnType>; + +export async function insertMcpRetriedTask(db: Db, values: typeof schema.tasks.$inferInsert) { + // Keep the same typed row and Drizzle column encoders while making mission + // admission part of INSERT itself, rather than an earlier awaited check. + const columns = getTableColumns(schema.tasks); + const entries = Object.entries(values) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => ({ column: columns[key as keyof typeof columns], value })); + const columnNames = sql.join( + entries.map(({ column }) => sql.identifier(column.name)), + sql`, ` + ); + const boundValues = sql.join( + entries.map(({ column, value }) => sql`${sql.param(value, column)}`), + sql`, ` + ); + const missionId = values.missionId ?? null; + return db.run(sql`INSERT INTO ${schema.tasks} (${columnNames}) SELECT ${boundValues} + WHERE (${missionId} IS NULL OR EXISTS ( + SELECT 1 FROM ${schema.missions} WHERE ${schema.missions.id} = ${missionId} + AND ${schema.missions.projectId} = ${values.projectId} + AND ${schema.missions.status} NOT IN ('cancelled', 'completed', 'failed') + ))`); +} diff --git a/apps/api/src/routes/mcp/orchestration-stop.ts b/apps/api/src/routes/mcp/orchestration-stop.ts index e0adac2dda..1104f20e07 100644 --- a/apps/api/src/routes/mcp/orchestration-stop.ts +++ b/apps/api/src/routes/mcp/orchestration-stop.ts @@ -9,6 +9,8 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { ulid } from '../../lib/ulid'; import { sendPromptToAgentOnNode, stopAgentSessionOnNode } from '../../services/node-agent'; +import { retireTaskCancellationPrompts } from '../../services/task-cancellation-prompts'; +import { taskRecoveryCancellationStatement } from '../../services/task-recovery-cancellation'; import { cleanupTerminalTaskResources } from '../../services/task-terminal-cleanup'; import { syncTriggerExecutionStatus } from '../../services/trigger-execution-sync'; import { @@ -132,12 +134,18 @@ export async function handleStopSubtask( let preservedTerminalStatus: string | null = null; try { const cancelFromStatus = async (fromStatus: string): Promise => { + await retireTaskCancellationPrompts(env, { + ...task, + userId: tokenData.userId, + chatSessionId: workspace.chatSessionId, + }); const [transition] = await env.DATABASE.batch([ env.DATABASE.prepare( `UPDATE tasks SET status = 'cancelled', error_message = ?, completed_at = ?, updated_at = ? - WHERE id = ? AND status = ?` - ).bind(stopReason, now, now, taskId, fromStatus), + WHERE id = ? AND project_id = ? AND status = ?` + ).bind(stopReason, now, now, taskId, task.projectId, fromStatus), + taskRecoveryCancellationStatement(env.DATABASE, task, now), env.DATABASE.prepare( `INSERT INTO task_status_events (id, task_id, from_status, to_status, actor_type, actor_id, reason, created_at) diff --git a/apps/api/src/routes/mcp/orchestration-tools.ts b/apps/api/src/routes/mcp/orchestration-tools.ts index 220a4d940e..24b172b7d0 100644 --- a/apps/api/src/routes/mcp/orchestration-tools.ts +++ b/apps/api/src/routes/mcp/orchestration-tools.ts @@ -20,6 +20,7 @@ import { ulid } from '../../lib/ulid'; import { parentAgentAttribution, withoutAuthorAttribution } from '../../services/agent-authorship'; import { generateBranchName } from '../../services/branch-name'; import { capacityPlacementSnapshotDbValues } from '../../services/capacity-placement-snapshot'; +import { resolveSystemErrorFor } from '../../services/inbox/system-error-resolve'; import { PlacementResolutionError, resolveTaskStartPlacement, @@ -47,6 +48,7 @@ import { import { resolveCallerChatSession } from './mailbox-target'; import { denyWhenMcpActorLacksCurrentProjectCapability } from './orchestration-authority'; import { stopActiveChildAgentForRetry } from './orchestration-retry-stop'; +import { insertMcpRetriedTask } from './orchestration-retry-storage'; // ─── retry_subtask ────────────────────────────────────────────────────────── @@ -365,12 +367,16 @@ export async function handleRetrySubtask( // default branch. const checkoutBranch = branchName; + // Reserve the session in the INSERT so the mission orchestrator cannot start it too. + const chatSessionId = crypto.randomUUID(); + // Insert replacement task - await db.insert(schema.tasks).values({ + const inserted = await insertMcpRetriedTask(db, { id: taskId, projectId: tokenData.projectId, userId: tokenData.userId, parentTaskId: tokenData.taskId, + chatSessionId, title: taskTitle, description: replacementDescription, status: 'queued', @@ -383,7 +389,8 @@ export async function handleRetrySubtask( requestedVmSizeSource: vmSizeSource, agentProfileHint: childTask.agentProfileHint, skillId: childTask.skillId, - // The replacement keeps its predecessor's feature coordination channel. + // A replacement remains part of its predecessor's mission and coordination channel. + missionId: childTask.missionId, coordinationChannel: childTask.coordinationChannel, resourceRequirementsJson: persistedResourceRequirementsJson, resourceRequirementPlanJson: persistedResourceRequirementPlanJson, @@ -398,6 +405,9 @@ export async function handleRetrySubtask( updatedAt: now, }); + if (!inserted.meta.changes) + return jsonRpcError(requestId, INVALID_PARAMS, 'Mission no longer accepts retried tasks'); + // Record status event await db.insert(schema.taskStatusEvents).values({ id: ulid(), @@ -419,7 +429,8 @@ export async function handleRetrySubtask( null, taskTitle, taskId, - tokenData.userId + tokenData.userId, + chatSessionId ); await projectDataService.persistMessage( @@ -498,6 +509,14 @@ export async function handleRetrySubtask( return jsonRpcError(requestId, INTERNAL_ERROR, `Failed to start task runner: ${errorMsg}`); } + // The retry worked: the failed child's inbox error item closes (slice E). Never throws. + await resolveSystemErrorFor(env, { + projectId: tokenData.projectId, + source: 'task', + subjectId: childTaskId, + resolution: 'retried', + }); + log.info('orchestration.retry_subtask.success', { stoppedTaskId: childTaskId, newTaskId: taskId, diff --git a/apps/api/src/routes/mcp/orchestrator-lifecycle-tools.ts b/apps/api/src/routes/mcp/orchestrator-lifecycle-tools.ts index 7554249a64..6d0f09c9b1 100644 --- a/apps/api/src/routes/mcp/orchestrator-lifecycle-tools.ts +++ b/apps/api/src/routes/mcp/orchestrator-lifecycle-tools.ts @@ -100,7 +100,7 @@ export async function handleCancelMission( if (!ok) return jsonRpcError(requestId, INVALID_PARAMS, 'Mission not found'); return jsonRpcSuccess(requestId, { - content: [{ type: 'text', text: JSON.stringify({ success: true, missionId, status: 'cancelled' }) }], + content: [{ type: 'text', text: JSON.stringify({ success: true, missionId, status: 'cancellation_requested' }) }], }); } diff --git a/apps/api/src/routes/mcp/project-insights-tool.ts b/apps/api/src/routes/mcp/project-insights-tool.ts new file mode 100644 index 0000000000..94948ecd0f --- /dev/null +++ b/apps/api/src/routes/mcp/project-insights-tool.ts @@ -0,0 +1,139 @@ +/** + * sam-mcp `project_insights` (Insights slice I): validates with the catalog operation's own schema + * (`sam_project_insights`, packages/operations/src/insights-agent.ts) and its method checks, spends + * one call of the chat's budget, then runs the shared operation with the token's project. + * + * Identity: the project always comes from the MCP token. A `projectId` argument that differs is + * refused before any read, and `authorizeProjectOperation` refuses it again (rule 51). + * + * Rate limit: per chat session (the token's chat, else its agent session, else its workspace), + * `insights.agentToolCallsPerWindow` calls per `insights.agentToolWindowSeconds` (admin runtime + * settings). The counter is the `McpRateCounter` Durable Object, which admits or refuses inside one + * storage transaction, so parallel calls cannot overspend it. One RPC per call. The ceiling is per + * chat on purpose: new chats come only from dispatch and triggers, which have their own limits, and + * every call also spends the task-keyed /mcp HTTP limit. The Connector path has no chat; it spends + * the per-user `connector.readRateLimitPerMinute` budget instead (`routes/connector-mcp.ts`). + */ +import { + getInsightsAgentRateLimit, + OperationError, + projectInsights, + projectInsightsInputError, + ProjectInsightsInputSchema, +} from '@simple-agent-manager/operations'; +import * as v from 'valibot'; + +import type { McpRateCounter, McpRateResult } from '../../durable-objects/mcp-rate-counter'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { + INTERNAL_ERROR, + INVALID_PARAMS, + jsonRpcError, + type JsonRpcResponse, + jsonRpcSuccess, + type McpTokenData, +} from './_helpers'; +import { + operationErrorToWorkspaceJsonRpc, + projectMismatch, + workspaceOperationContext, +} from './workspace-operation-adapter'; + +/** JSON-RPC server error code the /mcp HTTP limiter also uses for "rate limited". */ +const RATE_LIMITED = -32000; + +/** The session a call is charged to. Never empty: every token has a workspace. */ +export function projectInsightsRateKey(token: McpTokenData): string { + if (token.chatSessionId) return `project_insights:chat:${token.chatSessionId}`; + if (token.agentSessionId) return `project_insights:agent:${token.agentSessionId}`; + return `project_insights:workspace:${token.workspaceId}`; +} + +/** Spend one call of `key`'s budget for the window containing `nowMs`. */ +export async function consumeProjectInsightsBudget( + env: Env, + key: string, + limit: { callsPerWindow: number; windowSeconds: number }, + nowMs = Date.now() +): Promise { + if (!env.MCP_RATE_COUNTER) throw new Error('MCP_RATE_COUNTER binding is required'); + const now = Math.floor(nowMs / 1000); + const windowStart = Math.floor(now / limit.windowSeconds) * limit.windowSeconds; + const stub = env.MCP_RATE_COUNTER.get( + env.MCP_RATE_COUNTER.idFromName(key) + ) as DurableObjectStub; + return stub.consume(windowStart, windowStart + limit.windowSeconds, limit.callsPerWindow); +} + +export async function handleProjectInsights( + requestId: string | number | null, + params: Record, + token: McpTokenData, + env: Env +): Promise { + const mismatch = projectMismatch(requestId, params, token); + if (mismatch) { + log.warn('mcp.project_insights.project_mismatch', { + tokenProjectId: token.projectId, + requestedProjectId: + typeof params.projectId === 'string' + ? params.projectId.slice(0, 64) + : typeof params.projectId, + taskId: token.taskId, + workspaceId: token.workspaceId, + action: 'rejected', + }); + return mismatch; + } + const parsed = v.safeParse(ProjectInsightsInputSchema, { + ...params, + projectId: token.projectId, + }); + if (!parsed.success) { + const issue = parsed.issues[0]; + const path = issue?.path?.map((item) => String(item.key)).join('.') ?? 'input'; + return jsonRpcError(requestId, INVALID_PARAMS, `Invalid ${path}`); + } + // Method-specific refusals before the budget, so correcting a malformed call costs nothing. + const refusal = projectInsightsInputError(parsed.output); + if (refusal !== null) return jsonRpcError(requestId, INVALID_PARAMS, refusal); + + const ctx = workspaceOperationContext(requestId, token, env); + let admission: McpRateResult; + try { + const limit = await getInsightsAgentRateLimit(ctx); + admission = await consumeProjectInsightsBudget(env, projectInsightsRateKey(token), limit); + } catch (error) { + // Fail closed: an unreadable counter must not turn into unlimited reads. + log.error('mcp.project_insights.rate_limit_unavailable', { + projectId: token.projectId, + workspaceId: token.workspaceId, + error: error instanceof Error ? error.message : String(error), + }); + return jsonRpcError(requestId, INTERNAL_ERROR, 'project_insights is temporarily unavailable'); + } + if (!admission.allowed) { + return jsonRpcError( + requestId, + RATE_LIMITED, + `project_insights rate limit reached for this chat; retry after ${admission.retryAfter}s (${new Date(admission.resetAt * 1000).toISOString()}).` + ); + } + + try { + const result = await projectInsights(ctx, parsed.output); + return jsonRpcSuccess(requestId, { + content: [{ type: 'text', text: JSON.stringify(result) }], + }); + } catch (error) { + if (error instanceof OperationError) return operationErrorToWorkspaceJsonRpc(requestId, error); + // Never pass a storage or runtime error's text to the agent. + log.error('mcp.project_insights.read_failed', { + projectId: token.projectId, + method: parsed.output.method, + error: error instanceof Error ? error.message : String(error), + }); + return jsonRpcError(requestId, INTERNAL_ERROR, 'project_insights is temporarily unavailable'); + } +} diff --git a/apps/api/src/routes/mcp/task-tools.ts b/apps/api/src/routes/mcp/task-tools.ts index 68e3eeb904..7705aed1f6 100644 --- a/apps/api/src/routes/mcp/task-tools.ts +++ b/apps/api/src/routes/mcp/task-tools.ts @@ -277,28 +277,8 @@ export async function handleCompleteTask( failureLogEvent: 'mcp.complete_task.conversation_activity_event_failed', }); - // Emit session_ended notification for conversation-mode remap (agent finished turn) - // Use tokenData.userId as authoritative target - if (env.NOTIFICATION && tokenData.userId) { - try { - const [projectName, sessionId] = await Promise.all([ - notificationService.getProjectName(env, tokenData.projectId), - notificationService.getChatSessionId(env, tokenData.workspaceId), - ]); - await notificationService.notifySessionEnded(env, tokenData.userId, { - projectId: tokenData.projectId, - projectName, - sessionId, - taskId: tokenData.taskId, - taskTitle: taskRow.title, - }); - } catch (err) { - log.warn('mcp.complete_task.conversation_notification_failed', { - taskId: tokenData.taskId, - error: err instanceof Error ? err.message : String(err), - }); - } - } + // No "your turn" notification: the agent files what the person needs in the inbox + // (spec decision 2 of idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9; inbox Result items). return jsonRpcSuccess(requestId, { content: [{ type: 'text', text: 'Acknowledged. Conversation remains open for follow-up.' }], diff --git a/apps/api/src/routes/mcp/tool-annotations.ts b/apps/api/src/routes/mcp/tool-annotations.ts index 6b03a8e587..8a94e7e51b 100644 --- a/apps/api/src/routes/mcp/tool-annotations.ts +++ b/apps/api/src/routes/mcp/tool-annotations.ts @@ -55,6 +55,7 @@ const READ_ONLY_TOOLS = new Set([ 'ops_timeline', 'ops_why_is_node_alive', 'ops_workspace_agent_sessions', + 'project_insights', ]); const DESTRUCTIVE_TOOLS = new Set([ diff --git a/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts b/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts index 3fa6de8572..d29687deda 100644 --- a/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts +++ b/apps/api/src/routes/mcp/tool-definitions-inbox-tools.ts @@ -1,6 +1,7 @@ /** * Agent inbox tools (slice D, idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9). Listed to agents as the domain - * groups `inbox_read` (list, get) and `inbox_write` (ask, review, update, cancel) in + * groups `inbox_read` (list, get) and `inbox_write` (ask, review, result, assign, comment, attach, + * update, cancel) in * `tool-groups.ts`; these members stay callable by name. Properties shared by several members are * one object each, because a group merges same-named properties and they must agree. */ @@ -13,11 +14,12 @@ import { const title = { type: 'string', description: - 'One sentence the person reads in their inbox, on one line. State exactly what you need.', + 'One plain sentence (no markdown) the person reads in their inbox, on one line: the outcome, or exactly what you need.', }; const why = { type: 'string', - description: 'Short reason and the context the person needs to act without opening the chat.', + description: + 'Always give it: brief, easy-to-read context in markdown (short paragraphs, bullet lists, bold for what matters) and clear, simple language, so the person can understand and act without opening the chat.', }; const links = { type: 'array', @@ -45,6 +47,11 @@ const idempotencyKey = { 'Any unique string; a retried call with the same key returns the item already filed.', }; const ref = { type: 'string', description: 'Item reference, `ask:`, as returned when filed.' }; +const wakeOnSteps = { + type: 'boolean', + description: + 'Default false: step ticks are recorded and you read them at your next wake. true: also wake on each tick (ticks close together arrive together).', +}; export const INBOX_TOOLS = [ { @@ -91,6 +98,84 @@ export const INBOX_TOOLS = [ additionalProperties: false, }, }, + { + name: 'inbox_result', + description: + 'Hand the person what they asked for: an answer, a finding, finished work. Title: the outcome in one plain sentence. why: the details, written as a short note to a colleague. Non-blocking; they mark it "Got it" (you are not woken) or reply (you are woken with the reply).', + inputSchema: { + type: 'object' as const, + properties: { title, why, links, groupKey, idempotencyKey }, + required: ['title'], + additionalProperties: false, + }, + }, + { + name: 'inbox_assign', + description: + 'Hand a person non-blocking work only a person can do (add a production secret, decide a price, record a demo). It goes to their inbox under Tasks; you keep working. You are woken in this chat when they comment, take it, hand it on, finish, reopen or archive it. It never expires.', + inputSchema: { + type: 'object' as const, + properties: { + title, + why, + steps: { + type: 'array', + items: { type: 'string' }, + description: 'Optional ordered steps, one line each. The person ticks them off.', + }, + assignee: { + type: 'object', + description: + '`{ "userId": "" }` for one active project member, or `{ "team": true }` for anyone in the project (one member takes it).', + properties: { + userId: { type: 'string' }, + team: { type: 'boolean', description: 'true for the team.' }, + }, + additionalProperties: false, + }, + dueHint: { + type: 'string', + description: + 'Optional soft due date in words ("before Friday\'s launch"). Sorts and highlights only.', + }, + links, + wakeOnSteps, + groupKey, + idempotencyKey, + }, + required: ['title', 'assignee'], + additionalProperties: false, + }, + }, + { + name: 'inbox_comment', + description: + "Reply in a task's discussion (a task this chat assigned or watches, or one addressed to your person or the team). The person is notified.", + inputSchema: { + type: 'object' as const, + properties: { + ref, + body: { type: 'string', description: 'Your reply.' }, + threadId: { + type: 'string', + description: 'Reply in this discussion thread (from inbox_read get); omit to start one.', + }, + }, + required: ['ref', 'body'], + additionalProperties: false, + }, + }, + { + name: 'inbox_attach', + description: + 'Watch an open task another of your chats assigned instead of assigning a duplicate: this chat is woken when it is taken, handed on, finished, reopened or archived (comments wake the assigning chat; read them with inbox_read get).', + inputSchema: { + type: 'object' as const, + properties: { ref, wakeOnSteps }, + required: ['ref'], + additionalProperties: false, + }, + }, { name: 'inbox_update_item', description: 'Edit the title, reason or links of an open item this chat filed.', @@ -129,7 +214,8 @@ export const INBOX_TOOLS = [ }, { name: 'inbox_get_item', - description: "One item of this project with its status, the person's answer and the outcome.", + description: + "One item of this project with its status, the person's answer and the outcome; for a task also its steps, assignee, who took it, activity and discussion.", inputSchema: { type: 'object' as const, properties: { ref }, diff --git a/apps/api/src/routes/mcp/tool-definitions-insights-tools.ts b/apps/api/src/routes/mcp/tool-definitions-insights-tools.ts new file mode 100644 index 0000000000..63f86a9b53 --- /dev/null +++ b/apps/api/src/routes/mcp/tool-definitions-insights-tools.ts @@ -0,0 +1,71 @@ +/** + * MCP tool definition — `project_insights` (Insights slice I). The tool runs the catalog operation + * `sam_project_insights` (`packages/operations/src/insights-agent.ts`); this JSON schema mirrors + * that operation's input minus `projectId`, which always comes from the MCP token. A test keeps the + * two in step (`tests/unit/routes/mcp/project-insights-tool.test.ts`). + */ +import { + MAX_PHASE_STATS_PHASES, + MAX_PHASE_STATS_WINDOW_DAYS, + PROJECT_INSIGHTS_METHODS, +} from '@simple-agent-manager/operations'; +import { + INSIGHTS_RANGES, + INSIGHTS_SETUP_GROUPINGS, + PROJECT_LIFECYCLE_PHASE_OPERATIONS, +} from '@simple-agent-manager/shared'; + +/** Bounds the handler enforces (`ProjectInsightsInputSchema`); the test compares them all. */ +const id = (description: string) => ({ + type: 'string', + minLength: 1, + maxLength: 200, + description, +}); + +export const INSIGHTS_TOOLS = [ + { + name: 'project_insights', + description: + "Numbers about this project's runs, for sizing and planning work. method: receipt (taskId: one run's phases, CI state, peak memory vs requested, tokens), flow (range: CI first-try pass rate, flaky checks, why runs stopped), setups (range, groupBy: memory p90 vs requested, median to PR, tokens per merged PR per profile/skill/model), phases (skillId or agentProfileId: usual phase durations), accounts (range: account limit windows and limit stalls). Rate-limited per chat.", + inputSchema: { + type: 'object' as const, + properties: { + method: { type: 'string', enum: [...PROJECT_INSIGHTS_METHODS] }, + taskId: id('receipt (required): the task to read.'), + range: { + type: 'string', + enum: [...INSIGHTS_RANGES], + description: 'flow, setups, accounts: window (default 30d).', + }, + groupBy: { + type: 'string', + enum: [...INSIGHTS_SETUP_GROUPINGS], + description: 'setups: grouping (default profile).', + }, + skillId: id('phases: exactly one of skillId or agentProfileId.'), + agentProfileId: id('phases: exactly one of skillId or agentProfileId.'), + operation: { + type: 'string', + enum: [...PROJECT_LIFECYCLE_PHASE_OPERATIONS], + description: 'phases: only workspace, wake, sleep, runner_start or runner_wake.', + }, + phaseNames: { + type: 'array', + items: { type: 'string', pattern: '^[a-z0-9_-]{1,64}$' }, + minItems: 1, + maxItems: MAX_PHASE_STATS_PHASES, + description: 'phases: only these phases (default all).', + }, + windowDays: { + type: 'integer', + minimum: 1, + maximum: MAX_PHASE_STATS_WINDOW_DAYS, + description: 'phases: days back (default 30).', + }, + }, + required: ['method'], + additionalProperties: false, + }, + }, +]; diff --git a/apps/api/src/routes/mcp/tool-definitions.ts b/apps/api/src/routes/mcp/tool-definitions.ts index 0da054b212..482ea37949 100644 --- a/apps/api/src/routes/mcp/tool-definitions.ts +++ b/apps/api/src/routes/mcp/tool-definitions.ts @@ -9,6 +9,7 @@ import { WORKFLOW_TOOLS } from './tool-definitions-workflow-tools'; * See the individual files for the full schema of each group: * - tool-definitions-task-tools.ts (task lifecycle, dispatch, notifications) * - tool-definitions-project-awareness.ts (list/get/search tasks, sessions, messages) + * - tool-definitions-insights-tools.ts (project_insights: Insights numbers for agents) * - tool-definitions-session-idea-tools.ts (session management, idea CRUD, linking) * - tool-definitions-workspace-tools.ts (workspace info, env, CI, cost, onboarding) * - tool-definitions-library-tools.ts (project file library) @@ -49,6 +50,7 @@ import { DEPLOYMENT_TOOLS } from './tool-definitions-deployment-tools'; import { PROJECT_EVENT_SUBSCRIPTION_TOOLS } from './tool-definitions-event-subscription-tools'; import { INBOX_TOOLS } from './tool-definitions-inbox-tools'; import { INCIDENT_TOOLS } from './tool-definitions-incident-tools'; +import { INSIGHTS_TOOLS } from './tool-definitions-insights-tools'; import { KNOWLEDGE_TOOLS } from './tool-definitions-knowledge-tools'; import { LIBRARY_FILE_COMMENT_TOOLS } from './tool-definitions-library-file-comment-tools'; import { LIBRARY_TOOLS } from './tool-definitions-library-tools'; @@ -74,6 +76,7 @@ export const MCP_TOOLS = [ ...TASK_LIFECYCLE_TOOLS, ...INBOX_TOOLS, ...PROJECT_AWARENESS_TOOLS, + ...INSIGHTS_TOOLS, ...SESSION_IDEA_TOOLS, ...WORKSPACE_TOOLS, ...AGENT_MODEL_TOOLS, diff --git a/apps/api/src/routes/mcp/tool-groups.ts b/apps/api/src/routes/mcp/tool-groups.ts index cd3fe7d54b..b6cc1dac75 100644 --- a/apps/api/src/routes/mcp/tool-groups.ts +++ b/apps/api/src/routes/mcp/tool-groups.ts @@ -103,7 +103,8 @@ export const MCP_TOOL_GROUPS: readonly McpToolGroup[] = [ }, get: { tool: 'inbox_get_item', - summary: "one item with its status, the person's answer and outcome", + summary: + "one item with its status, the person's answer and outcome; a task with steps, assignee, activity and discussion", }, }, }, @@ -113,7 +114,7 @@ export const MCP_TOOL_GROUPS: readonly McpToolGroup[] = [ destructive: true, requiresTask: true, summary: - 'File what you need from a person in their inbox; they read the inbox, not chats. One ask per item. You are woken in this chat when they answer.', + 'File what you need from a person in their inbox; they read the inbox, not chats. One ask per item. You are woken in this chat when they answer or reply.', methods: { ask: { tool: 'inbox_ask', @@ -124,6 +125,21 @@ export const MCP_TOOL_GROUPS: readonly McpToolGroup[] = [ tool: 'inbox_review', summary: 'ask the person to evaluate something you made; answered "Looks good" or a reply', }, + result: { + tool: 'inbox_result', + summary: + 'hand the person what they asked for (an answer, a finding, finished work); "Got it" closes it, a reply wakes you', + }, + assign: { + tool: 'inbox_assign', + summary: + 'hand a person (or the team) non-blocking work only a person can do; you keep working and are woken when they act', + }, + comment: { tool: 'inbox_comment', summary: "reply in a task's discussion" }, + attach: { + tool: 'inbox_attach', + summary: 'watch a task another of your chats assigned instead of assigning a duplicate', + }, update: { tool: 'inbox_update_item', summary: 'edit the wording or links of your open item' }, cancel: { tool: 'inbox_cancel_item', diff --git a/apps/api/src/routes/mcp/tool-handler-table.ts b/apps/api/src/routes/mcp/tool-handler-table.ts index 5eaf6e6a1e..0312401d59 100644 --- a/apps/api/src/routes/mcp/tool-handler-table.ts +++ b/apps/api/src/routes/mcp/tool-handler-table.ts @@ -28,9 +28,13 @@ import { } from './idea-tools'; import { handleInboxAsk, + handleInboxAssign, + handleInboxAttach, handleInboxCancelItem, + handleInboxComment, handleInboxGetItem, handleInboxListItems, + handleInboxResult, handleInboxReview, handleInboxUpdateItem, } from './inbox-tools'; @@ -128,6 +132,7 @@ import { handleUpdateAgentProfile, } from './profile-tools'; import { handleAckEventDelivery, handleGetEvent } from './project-event-tools'; +import { handleProjectInsights } from './project-insights-tool'; import { handleListRuntimeEnv, handleRequestSecret } from './secret-request-tools'; import { handleGetResourceHistory, @@ -209,8 +214,12 @@ export const MCP_TOOL_HANDLERS: ReadonlyMap = new Map< ['request_human_input', handleRequestHumanInput], ['inbox_ask', handleInboxAsk], ['inbox_review', handleInboxReview], + ['inbox_result', handleInboxResult], ['inbox_update_item', handleInboxUpdateItem], ['inbox_cancel_item', handleInboxCancelItem], + ['inbox_assign', handleInboxAssign], + ['inbox_comment', handleInboxComment], + ['inbox_attach', handleInboxAttach], ['inbox_list_items', handleInboxListItems], ['inbox_get_item', handleInboxGetItem], ['request_secret', handleRequestSecret], @@ -229,6 +238,7 @@ export const MCP_TOOL_HANDLERS: ReadonlyMap = new Map< ['list_tasks', handleListTasks], ['get_task_details', handleGetTaskDetails], ['search_tasks', handleSearchTasks], + ['project_insights', handleProjectInsights], ['list_sessions', handleListSessions], ['get_session_messages', handleGetSessionMessages], ['get_resource_history', handleGetResourceHistory], diff --git a/apps/api/src/routes/mcp/trigger-create-tool.ts b/apps/api/src/routes/mcp/trigger-create-tool.ts index d3c9c3bc4c..fb0d802c95 100644 --- a/apps/api/src/routes/mcp/trigger-create-tool.ts +++ b/apps/api/src/routes/mcp/trigger-create-tool.ts @@ -1,3 +1,4 @@ +import { cronToHumanReadable } from '@simple-agent-manager/cron'; import { ResourceRequirementsValidationError, serializeModernResourceRequirementsInput, @@ -12,7 +13,6 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { AppError } from '../../middleware/error'; import { CreateTriggerSchema } from '../../schemas/triggers'; -import { cronToHumanReadable } from '../../services/cron-utils'; import { readGitHubTriggerConfig } from '../../services/github-trigger-config'; import { createTrigger } from '../../services/trigger-create'; import { areWebhookTriggersEnabled } from '../../services/webhook-trigger-config'; diff --git a/apps/api/src/routes/mcp/trigger-tool-shared.ts b/apps/api/src/routes/mcp/trigger-tool-shared.ts index 26cbbed9ba..ee92e215cd 100644 --- a/apps/api/src/routes/mcp/trigger-tool-shared.ts +++ b/apps/api/src/routes/mcp/trigger-tool-shared.ts @@ -1,8 +1,8 @@ +import { cronToHumanReadable } from '@simple-agent-manager/cron'; import { DEFAULT_TRIGGER_DEFAULT_MAX_CONCURRENT } from '@simple-agent-manager/shared'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; -import { cronToHumanReadable } from '../../services/cron-utils'; import { INVALID_PARAMS, jsonRpcError, type JsonRpcResponse, type McpTokenData } from './_helpers'; export interface TriggerDbRow { diff --git a/apps/api/src/routes/mcp/trigger-tools.ts b/apps/api/src/routes/mcp/trigger-tools.ts index 20c2889a1e..3a11461382 100644 --- a/apps/api/src/routes/mcp/trigger-tools.ts +++ b/apps/api/src/routes/mcp/trigger-tools.ts @@ -2,6 +2,11 @@ * MCP trigger management tool — update_trigger. * Create/delete live in focused modules and are re-exported for compatibility. */ +import { + cronToHumanReadable, + cronToNextFire, + validateCronExpression, +} from '@simple-agent-manager/cron'; import { ResourceRequirementsValidationError, serializeModernResourceRequirementsInput, @@ -20,11 +25,6 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { parsePositiveInt } from '../../lib/route-helpers'; import { AppError } from '../../middleware/error'; -import { - cronToHumanReadable, - cronToNextFire, - validateCronExpression, -} from '../../services/cron-utils'; import { assertGitHubTriggerConfigExists, readGitHubTriggerConfig, diff --git a/apps/api/src/routes/mcp/workspace-operation-adapter.ts b/apps/api/src/routes/mcp/workspace-operation-adapter.ts index 719fb6d468..ec50c5164c 100644 --- a/apps/api/src/routes/mcp/workspace-operation-adapter.ts +++ b/apps/api/src/routes/mcp/workspace-operation-adapter.ts @@ -54,28 +54,9 @@ export async function runWorkspaceOperation( env: Env ): Promise { const projectId = token.projectId; - if (params.projectId !== undefined && params.projectId !== projectId) { - return operationErrorToWorkspaceJsonRpc( - requestId, - new OperationError('forbidden', 'Project does not match workspace token') - ); - } - const ctx: OperationContext = { - env, - ports: createOperationPorts(env), - requestId: String(requestId ?? ''), - actor: { - userId: token.userId, - via: 'workspace-agent', - scopes: new Set(['sam.read', 'sam.write']), - workspace: { - workspaceId: token.workspaceId, - taskId: token.taskId, - projectId, - agentSessionId: token.agentSessionId, - }, - }, - }; + const mismatch = projectMismatch(requestId, params, token); + if (mismatch) return mismatch; + const ctx = workspaceOperationContext(requestId, token, env); const operation = workspaceOperations[name]; if (!operation) throw new OperationError('invalid_input', `Unknown workspace operation: ${name}`); const input = { @@ -97,8 +78,45 @@ export async function runWorkspaceOperation( } } +/** A workspace token may only read its own project; a different `projectId` is refused (rule 51). */ +export function projectMismatch( + requestId: string | number | null, + params: Record, + token: McpTokenData +): JsonRpcResponse | null { + if (params.projectId === undefined || params.projectId === token.projectId) return null; + return operationErrorToWorkspaceJsonRpc( + requestId, + new OperationError('forbidden', 'Project does not match workspace token') + ); +} + +/** The operation context for a workspace MCP token: its user, its project, nothing else. */ +export function workspaceOperationContext( + requestId: string | number | null, + token: McpTokenData, + env: Env +): OperationContext { + return { + env, + ports: createOperationPorts(env), + requestId: String(requestId ?? ''), + actor: { + userId: token.userId, + via: 'workspace-agent', + scopes: new Set(['sam.read', 'sam.write']), + workspace: { + workspaceId: token.workspaceId, + taskId: token.taskId, + projectId: token.projectId, + agentSessionId: token.agentSessionId, + }, + }, + }; +} + /** The workspace protocol has historically used INVALID_PARAMS for tool-level failures. */ -function operationErrorToWorkspaceJsonRpc( +export function operationErrorToWorkspaceJsonRpc( requestId: string | number | null, error: OperationError ): JsonRpcResponse { diff --git a/apps/api/src/routes/node-heartbeat-ip.ts b/apps/api/src/routes/node-heartbeat-ip.ts new file mode 100644 index 0000000000..01e823fe6b --- /dev/null +++ b/apps/api/src/routes/node-heartbeat-ip.ts @@ -0,0 +1,153 @@ +/** IP and DNS reconciliation for the authenticated node heartbeat. */ +import { sql } from 'drizzle-orm'; +import type { Context } from 'hono'; + +import type { Node } from '../db/schema'; +import type { Env } from '../env'; +import { clientIpFromHeaders } from '../lib/client-ip'; +import { log } from '../lib/logger'; +import { createNodeBackendDNSRecord, updateDNSRecord } from '../services/dns'; +import { nodeHasTunnelIngress } from '../services/node-transport-extension'; + +const NODE_DNS_ERROR_MESSAGE_MAX_LENGTH = 500; +const NODE_BACKEND_DNS_ERROR_PREFIX = 'Backend DNS record creation failed:'; + +function truncateNodeLifecycleError(value: string): string { + return value.length > NODE_DNS_ERROR_MESSAGE_MAX_LENGTH + ? `${value.slice(0, NODE_DNS_ERROR_MESSAGE_MAX_LENGTH - 3)}...` + : value; +} + +function isBackendDnsError(errorMessage: string | null | undefined): boolean { + return !!errorMessage && errorMessage.startsWith(NODE_BACKEND_DNS_ERROR_PREFIX); +} + +function isValidIPv4Address(value: string | null | undefined): value is string { + if (!value) return false; + + const octets = value.split('.'); + if (octets.length !== 4) return false; + + return octets.every((octet) => { + if (!/^\d+$/.test(octet)) return false; + const numeric = Number(octet); + return numeric >= 0 && numeric <= 255; + }); +} + +type HeartbeatIpParams = { + c: Context<{ Bindings: Env }>; + node: Node; + nodeId: string; + updatePayload: Record; +}; + +function selectHeartbeatIp( + node: Node, + nodeId: string, + connectingIp: string | undefined +): string | undefined { + // Tunnel-transport nodes are reached via a proxied CNAME → cloudflared, NOT a public-IP A record, + // and their CF-Connecting-IP is the tunnel/NAT egress. Suppress ALL IP/A-record backfill for them + // server-side (keyed on stored transport or tunnelId, NOT nodeClass — a future public-IP BYO mode still wants + // backfill) so a heartbeat can never create an A record that conflicts with the enrollment CNAME. + // See security-critique #8 / architecture-critique #7. + // One exception: a deployment-role tunnel node whose provider reported no IP at create. Its + // app routes are grey-cloud A records to the node's public IP (services/dns-app-routes.ts), + // so it records the heartbeat's IPv4 egress as `ip_address` only. It never gets a backend A + // record: `effectiveNodeIp` stays null for every tunnel node. + const hasTunnelIngress = nodeHasTunnelIngress(node); + const deploymentTunnelIpBackfill = + hasTunnelIngress && + node.transport !== 'reverse-tunnel' && + node.nodeRole === 'deployment' && + node.nodeClass === 'managed' && + !node.ipAddress; + if (hasTunnelIngress && !deploymentTunnelIpBackfill) { + log.debug('heartbeat.ip_backfill_skipped_tunnel_node', { nodeId, action: 'skipped' }); + } + if (!hasTunnelIngress || (deploymentTunnelIpBackfill && isValidIPv4Address(connectingIp))) { + return connectingIp; + } + return undefined; +} + +function backfillNodeIp( + node: Node, + nodeId: string, + heartbeatIp: string | undefined, + updatePayload: Record +): void { + if (node.ipAddress || !heartbeatIp) return; + log.info('heartbeat.ip_backfilled', { + nodeId, + backfilledIp: heartbeatIp, + action: 'ip_backfilled', + }); + updatePayload.ipAddress = heartbeatIp; + // Explicit SQL NULL is required: an undefined property is dropped by Drizzle/D1. + updatePayload.errorMessage = sql`NULL`; + if (node.status === 'creating' || node.status === 'error') updatePayload.status = 'running'; +} + +async function reconcileHeartbeatDns( + params: HeartbeatIpParams, + heartbeatIp: string | undefined, + effectiveNodeIp: string +): Promise { + const { c, node, nodeId, updatePayload } = params; + const heartbeatIpv4 = isValidIPv4Address(heartbeatIp) ? heartbeatIp : null; + const dnsIp = heartbeatIpv4 || effectiveNodeIp; + try { + if (node.backendDnsRecordId) { + if (heartbeatIpv4 && heartbeatIpv4 !== node.ipAddress) { + await updateDNSRecord(node.backendDnsRecordId, heartbeatIpv4, c.env); + log.info('heartbeat.backend_dns_updated', { + nodeId, + ipAddress: heartbeatIpv4, + previousIpAddress: node.ipAddress, + }); + } + return; + } + const dnsRecordId = await createNodeBackendDNSRecord(nodeId, dnsIp, c.env); + updatePayload.backendDnsRecordId = dnsRecordId; + if (isBackendDnsError(node.errorMessage)) { + updatePayload.errorMessage = sql`NULL`; + if (node.status === 'error') { + updatePayload.status = 'running'; + } + } + log.info('heartbeat.backend_dns_backfilled', { + nodeId, + ipAddress: dnsIp, + source: heartbeatIpv4 ? 'heartbeat' : 'stored', + }); + } catch (dnsErr) { + const message = dnsErr instanceof Error ? dnsErr.message : String(dnsErr); + updatePayload.errorMessage = truncateNodeLifecycleError( + `${NODE_BACKEND_DNS_ERROR_PREFIX} ${message}` + ); + log.error('heartbeat.backend_dns_backfill_failed', { + nodeId, + ipAddress: dnsIp, + hasExistingDnsRecord: !!node.backendDnsRecordId, + error: String(dnsErr), + }); + } +} + +export async function applyHeartbeatIp(params: HeartbeatIpParams): Promise { + const { c, node, nodeId, updatePayload } = params; + // Also heal an old awaiting-IP error when the address was backfilled on a prior heartbeat. + if (node.ipAddress && node.errorMessage?.includes('Awaiting IP allocation')) { + updatePayload.errorMessage = sql`NULL`; + } + const connectingIp = clientIpFromHeaders((name) => c.req.header(name)) ?? undefined; + const heartbeatIp = selectHeartbeatIp(node, nodeId, connectingIp); + backfillNodeIp(node, nodeId, heartbeatIp, updatePayload); + // A tunnel's app-route IP may be recorded, but its CNAME must never get a backend A record. + const tunnelIngress = nodeHasTunnelIngress(node); + const effectiveNodeIp = tunnelIngress ? null : node.ipAddress || heartbeatIp; + if (effectiveNodeIp) await reconcileHeartbeatDns(params, heartbeatIp, effectiveNodeIp); +} diff --git a/apps/api/src/routes/node-lifecycle.ts b/apps/api/src/routes/node-lifecycle.ts index 3d6d86c2b7..186620d63f 100644 --- a/apps/api/src/routes/node-lifecycle.ts +++ b/apps/api/src/routes/node-lifecycle.ts @@ -1,4 +1,3 @@ -// FILE SIZE EXCEPTION: Pre-existing VM node lifecycle route surface (~570 lines after the deployment heartbeat moved to node-heartbeat-deployment.ts). See .claude/rules/18-file-size-limits.md /** * Node lifecycle routes — VM-agent callbacks plus browser token issuance. * @@ -6,22 +5,20 @@ * the browser (token). VM-agent callbacks use callback JWT auth; the token * issuance route uses user session auth through the nodes route middleware. */ -import { isTunnelNodeTransport, isUserOwnedNodeClass } from '@simple-agent-manager/shared'; -import { and, eq, isNull, ne, notInArray, sql } from 'drizzle-orm'; +import { isUserOwnedNodeClass } from '@simple-agent-manager/shared'; +import { and, eq, isNull, ne, notInArray } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import { Hono } from 'hono'; import * as schema from '../db/schema'; import type { Env } from '../env'; import { extractBearerToken } from '../lib/auth-helpers'; -import { clientIpFromHeaders } from '../lib/client-ip'; import { log } from '../lib/logger'; import { maybeJsonRecord } from '../lib/runtime-validation'; import { credentialNotAfter, getUserId } from '../middleware/auth'; import { errors } from '../middleware/error'; import { requireNodeOwnership } from '../middleware/node-auth'; import { jsonValidator, NodeHeartbeatSchema } from '../schemas'; -import { createNodeBackendDNSRecord, updateDNSRecord } from '../services/dns'; import { shouldRefreshCallbackToken, signCurrentWorkspaceCallbackToken, @@ -45,10 +42,9 @@ import { wakeVmAdmissionWaiters } from '../services/vm-admission-control'; import { resolveWorkspaceGitSourceByProjectId } from '../services/workspace-git-source'; import { nodeDiagnosticIncidentRoutes } from './node-diagnostic-incidents'; import { applyDeploymentHeartbeat } from './node-heartbeat-deployment'; +import { applyHeartbeatIp } from './node-heartbeat-ip'; const nodeLifecycleRoutes = new Hono<{ Bindings: Env }>(); -const NODE_DNS_ERROR_MESSAGE_MAX_LENGTH = 500; -const NODE_BACKEND_DNS_ERROR_PREFIX = 'Backend DNS record creation failed:'; function rejectTerminalNodeCallback( nodeId: string, @@ -65,29 +61,6 @@ function rejectTerminalNodeCallback( throw errors.gone(`Node is ${observedStatus}; callback resource is gone`); } -function truncateNodeLifecycleError(value: string): string { - return value.length > NODE_DNS_ERROR_MESSAGE_MAX_LENGTH - ? `${value.slice(0, NODE_DNS_ERROR_MESSAGE_MAX_LENGTH - 3)}...` - : value; -} - -function isBackendDnsError(errorMessage: string | null | undefined): boolean { - return !!errorMessage && errorMessage.startsWith(NODE_BACKEND_DNS_ERROR_PREFIX); -} - -function isValidIPv4Address(value: string | null | undefined): value is string { - if (!value) return false; - - const octets = value.split('.'); - if (octets.length !== 4) return false; - - return octets.every((octet) => { - if (!/^\d+$/.test(octet)) return false; - const numeric = Number(octet); - return numeric >= 0 && numeric <= 255; - }); -} - /** * POST /:id/token — Issue a node-scoped management token for direct VM Agent access. * The browser uses this token to call the VM Agent directly for node-level data @@ -281,8 +254,7 @@ nodeLifecycleRoutes.post('/:id/origin-ca-certificate', async (c) => { // Server-side ownership gate: NEVER hand a platform-wide `*.{BASE_DOMAIN}` wildcard Origin CA // cert to a user-owned (BYO) machine — a BYO owner holds a valid callback token for their own // node and could otherwise `curl` this endpoint to extract the platform wildcard cert+key. - // Tunnel-transport nodes (cloudflare-tunnel, reverse-tunnel) never need Origin CA at all: the - // connector carries plain HTTP from the agent's loopback listener. + // Tunnel-transport nodes never need Origin CA at all (cloudflared terminates TLS at the edge). // This gate is independent of what the agent chooses to send. See security-critique #2, rule 28. const gateDb = drizzle(c.env.DATABASE, { schema }); const nodeRow = await gateDb @@ -297,7 +269,7 @@ nodeLifecycleRoutes.post('/:id/origin-ca-certificate', async (c) => { if (!nodeRow || nodeStatusTerminatesCallbacks(nodeRow.status)) { rejectTerminalNodeCallback(nodeId, nodeRow?.status, 'origin_ca_certificate'); } - if (isUserOwnedNodeClass(nodeRow.nodeClass) || isTunnelNodeTransport(nodeRow.transport)) { + if (isUserOwnedNodeClass(nodeRow.nodeClass) || (nodeRow.transport === 'cloudflare-tunnel' || nodeRow.transport === 'reverse-tunnel')) { log.error('node_origin_ca_certificate.denied_user_owned', { nodeId, nodeClass: nodeRow.nodeClass, @@ -372,110 +344,7 @@ nodeLifecycleRoutes.post('/:id/heartbeat', jsonValidator(NodeHeartbeatSchema), a }); } - // Self-heal stale "Awaiting IP allocation" error on nodes that already have an IP. - // This handles nodes where the IP was backfilled before this fix was deployed. - if (node.ipAddress && node.errorMessage?.includes('Awaiting IP allocation')) { - updatePayload.errorMessage = sql`NULL`; - } - - // Tunnel-transport nodes are reached via a proxied CNAME → cloudflared, NOT a public-IP A record, - // and their CF-Connecting-IP is the tunnel/NAT egress. Suppress ALL IP/A-record backfill for them - // server-side (keyed on tunnelId presence, NOT nodeClass — a future public-IP BYO mode still wants - // backfill) so a heartbeat can never create an A record that conflicts with the enrollment CNAME. - // See security-critique #8 / architecture-critique #7. - // The `tunnelId` conjunct is the exact pre-existing predicate for every other transport (a - // cloudflare-tunnel node whose tunnel_id is still NULL keeps backfilling, as before). - // Reverse-tunnel nodes have no tunnelId and no DNS record at all (frpc dials the box), so - // they are added separately from the node row's own transport, never from the agent. - const tunnelIngress = !!node.tunnelId || node.transport === 'reverse-tunnel'; - // One exception: a deployment-role Cloudflare tunnel node whose provider reported no IP at - // create. Its app routes are grey-cloud A records to the node's public IP - // (services/dns-app-routes.ts), so it records the heartbeat's IPv4 egress as `ip_address` - // only. It never gets a backend A record: `effectiveNodeIp` stays null for every tunnel node. - // Reverse-tunnel deployment nodes do not exist (resolveManagedNodeTransport excludes them). - const deploymentTunnelIpBackfill = - !!node.tunnelId && - node.nodeRole === 'deployment' && - node.nodeClass === 'managed' && - !node.ipAddress; - if (tunnelIngress && !deploymentTunnelIpBackfill) { - log.debug('heartbeat.ip_backfill_skipped_tunnel_node', { nodeId, action: 'skipped' }); - } - const connectingIp = clientIpFromHeaders((name) => c.req.header(name)); - let heartbeatIp: string | null = null; - if (!tunnelIngress) { - heartbeatIp = connectingIp; - } else if (deploymentTunnelIpBackfill && isValidIPv4Address(connectingIp)) { - heartbeatIp = connectingIp; - } - - // Defense-in-depth: backfill IP from heartbeat if node has no IP stored. - // This self-heals Scaleway nodes where the IP wasn't captured at creation time. - let effectiveNodeIp = tunnelIngress ? null : node.ipAddress; - - if (!node.ipAddress) { - if (heartbeatIp) { - log.info('heartbeat.ip_backfilled', { - nodeId, - backfilledIp: heartbeatIp, - action: 'ip_backfilled', - }); - updatePayload.ipAddress = heartbeatIp; - effectiveNodeIp = node.tunnelId ? null : heartbeatIp; - - // Always clear the "Awaiting IP allocation" error when IP is backfilled. - // Use explicit SQL null to ensure Drizzle/D1 generates SET errorMessage = NULL - // (assigning null to a Record property may be silently dropped). - updatePayload.errorMessage = sql`NULL`; - - // Transition to running if the node was awaiting IP allocation - if (node.status === 'creating' || node.status === 'error') { - updatePayload.status = 'running'; - } - } - } - - if (effectiveNodeIp) { - const heartbeatIpv4 = isValidIPv4Address(heartbeatIp) ? heartbeatIp : null; - const dnsIp = heartbeatIpv4 || effectiveNodeIp; - try { - if (node.backendDnsRecordId) { - if (heartbeatIpv4 && heartbeatIpv4 !== node.ipAddress) { - await updateDNSRecord(node.backendDnsRecordId, heartbeatIpv4, c.env); - log.info('heartbeat.backend_dns_updated', { - nodeId, - ipAddress: heartbeatIpv4, - previousIpAddress: node.ipAddress, - }); - } - } else { - const dnsRecordId = await createNodeBackendDNSRecord(nodeId, dnsIp, c.env); - updatePayload.backendDnsRecordId = dnsRecordId; - if (isBackendDnsError(node.errorMessage)) { - updatePayload.errorMessage = sql`NULL`; - if (node.status === 'error') { - updatePayload.status = 'running'; - } - } - log.info('heartbeat.backend_dns_backfilled', { - nodeId, - ipAddress: dnsIp, - source: heartbeatIpv4 ? 'heartbeat' : 'stored', - }); - } - } catch (dnsErr) { - const message = dnsErr instanceof Error ? dnsErr.message : String(dnsErr); - updatePayload.errorMessage = truncateNodeLifecycleError( - `${NODE_BACKEND_DNS_ERROR_PREFIX} ${message}` - ); - log.error('heartbeat.backend_dns_backfill_failed', { - nodeId, - ipAddress: dnsIp, - hasExistingDnsRecord: !!node.backendDnsRecordId, - error: String(dnsErr), - }); - } - } + await applyHeartbeatIp({ c, node, nodeId, updatePayload }); if (updatePayload.status) { updatePayload.cleanupBlockedSince = null; diff --git a/apps/api/src/routes/nodes.ts b/apps/api/src/routes/nodes.ts index 6b1d467611..4036f72ea9 100644 --- a/apps/api/src/routes/nodes.ts +++ b/apps/api/src/routes/nodes.ts @@ -21,7 +21,7 @@ import { scheduleDirectProvisioning } from '../services/direct-provisioning'; import { getRuntimeLimits } from '../services/limits'; import { stopWorkspaceOnNode } from '../services/node-agent'; import { getNodeResourceUsage } from '../services/node-resource-usage'; -import { isReverseTunnelInstallation } from '../services/node-tunnel-config'; +import { provisionsExtensionTransportNodes } from '../services/node-transport-extension'; import { createNodeRecord, stopNodeResources } from '../services/nodes'; import { recordNodeRoutingMetric } from '../services/telemetry'; import { deleteNodeRoute } from './nodes/delete'; @@ -125,12 +125,12 @@ nodesRoutes.post('/', jsonValidator(CreateNodeSchema), async (c) => { const provider = body.provider; // Without a location in the request: on Cloudflare installs, DEFAULT_VM_LOCATION (Hetzner - // nbg1), as always. On a self-hosted box (the reverse-tunnel installation, the box's existing - // self-host marker) none: the installation pool then decides, and it holds only the locations + // nbg1), as always. On a self-hosted box (it provisions nodes on an installed extension + // transport, the reverse tunnel) none: the installation pool then decides, and it holds only the locations // of the box's platform credential. A GCP-only box has no nbg1, so the constant could never be // placed there (box round R13 D8). const vmLocation = - body.vmLocation ?? (isReverseTunnelInstallation(c.env) ? null : DEFAULT_VM_LOCATION); + body.vmLocation ?? (provisionsExtensionTransportNodes(c.env) ? null : DEFAULT_VM_LOCATION); // Validate location against provider if provider is specified if (provider && vmLocation !== null && !isValidLocationForProvider(provider, vmLocation)) { diff --git a/apps/api/src/routes/nodes/diagnostics.ts b/apps/api/src/routes/nodes/diagnostics.ts index f9e6a60302..836dba3bad 100644 --- a/apps/api/src/routes/nodes/diagnostics.ts +++ b/apps/api/src/routes/nodes/diagnostics.ts @@ -174,17 +174,17 @@ nodeDiagnosticsRoutes.get('/:id/logs/stream', async (c) => { headers.set('Authorization', `Bearer ${token}`); headers.set('X-SAM-Node-Id', nodeId); - // Self-hosted WebSocket gateway: same auth and headers; Caddy carries the socket. + // Self-hosted WebSocket gateway: same auth and headers; the box's Caddy carries the socket. + // The node row is already loaded above, so this adds no read on any transport. if (isGatewayAuthorizationRequest(c.req.raw)) { let route: NodeAgentRoute; try { - route = await resolveNodeAgentRoute(c.env, nodeId); + route = await resolveNodeAgentRoute(c.env, nodeId, node); } catch (err) { - // A reverse-tunnel node without a live lease: refused as unreachable, like the ws-* proxy. if (!(err instanceof NodeAgentRouteError)) throw err; return c.json({ error: 'NODE_UNREACHABLE', message: 'Node is not reachable' }, 503); } - return gatewayDecisionResponse(c.req.raw, route, { url: vmUrl, headers }, c.env); + return gatewayDecisionResponse(c.req.raw, route, { url: vmUrl, headers }); } return fetchNodeAgent( diff --git a/apps/api/src/routes/platform-capabilities.ts b/apps/api/src/routes/platform-capabilities.ts new file mode 100644 index 0000000000..3e6ff03269 --- /dev/null +++ b/apps/api/src/routes/platform-capabilities.ts @@ -0,0 +1,23 @@ +import { Hono } from 'hono'; + +import type { Env } from '../env'; +import { applyCacheHeaders } from '../lib/cache-headers'; +import { getWorkersAiBindingOrNull } from '../services/platform-capabilities'; +import { resolvePublicPlatformCapabilities } from '../services/speech-backend'; + +/** + * Public config: which platform services this installation has, so the UI can hide entry points + * that cannot work here (services/platform-capabilities.ts). Booleans only, no auth. On Cloudflare + * (Workers AI bound) there are no D1, KV or binding calls: the answer is computed from the + * environment alone. Only a runtime without Workers AI that installed a speech backend + * (services/speech-backend.ts) reads that backend's settings. + */ +export const platformCapabilitiesRoutes = new Hono<{ Bindings: Env }>(); + +platformCapabilitiesRoutes.get('/platform-capabilities', async (c) => { + // Endpoint settings can change without a deploy. Do not let a stale browser response + // refresh the client's capability query with the previous settings snapshot. + if (getWorkersAiBindingOrNull(c.env)) applyCacheHeaders(c, 'public-config'); + else c.header('Cache-Control', 'no-store'); + return c.json(await resolvePublicPlatformCapabilities(c.env)); +}); diff --git a/apps/api/src/routes/project-comments.ts b/apps/api/src/routes/project-comments.ts index 69c90a6c60..b871f5fc89 100644 --- a/apps/api/src/routes/project-comments.ts +++ b/apps/api/src/routes/project-comments.ts @@ -15,7 +15,9 @@ * a VM-agent callback, so .claude/rules/34 does not apply. The handler still * asserts the caller's project capability explicitly before touching data. */ +import { TASK_READABLE_SQL } from '@simple-agent-manager/operations'; import type { ProjectCommentListResponse } from '@simple-agent-manager/shared'; +import { chunk, D1_MAX_BOUND_PARAMETERS } from '@simple-agent-manager/worker-core'; import { drizzle } from 'drizzle-orm/d1'; import { Hono } from 'hono'; @@ -66,9 +68,36 @@ projectCommentRoutes.get('/', async (c) => { columns: { id: true, filename: true }, }); + // Task discussion (inbox slice H1) shares the one ranked read above. A team task is readable + // by every member; a person's task only by its assignee and the person whose chat filed it, + // so threads on items this viewer cannot read are dropped here (the DO cannot read D1). + // `?? []`: an object still running the previous build returns no inbox-item threads. + const itemThreads = inbox.inboxItemThreads ?? []; + const itemIds = [...new Set(itemThreads.map((thread) => thread.itemId))]; + // Chunked under the D1 bind limit: projectId and two userId binds ride with each chunk. + const readableItems: Array<{ id: string; title: string }> = []; + for (const ids of chunk(itemIds, D1_MAX_BOUND_PARAMETERS - 3)) { + const rows = await c.env.DATABASE.prepare( + `SELECT a.id, a.title FROM asks a + WHERE a.project_id = ? AND a.kind = 'task' + AND a.id IN (${ids.map(() => '?').join(', ')}) + AND ${TASK_READABLE_SQL}` + ) + .bind(projectId, ...ids, userId, userId) + .all<{ id: string; title: string }>(); + readableItems.push(...(rows.results ?? [])); + } + const readable = new Set(readableItems.map((item) => item.id)); + const response: ProjectCommentListResponse = { messageThreads: inbox.messageThreads, fileThreads: inbox.fileThreads, + inboxItemThreads: itemThreads.filter((thread) => readable.has(thread.itemId)), + inboxItems: readableItems.map((item) => ({ + ref: `ask:${item.id}`, + id: item.id, + title: item.title, + })), sessions: inbox.sessions, files, hasMore: inbox.hasMore, diff --git a/apps/api/src/routes/project-insights.ts b/apps/api/src/routes/project-insights.ts index 398dc12755..3a9e0a2614 100644 --- a/apps/api/src/routes/project-insights.ts +++ b/apps/api/src/routes/project-insights.ts @@ -1,10 +1,25 @@ /** - * GET /api/projects/:projectId/insights/flow?range=7d|30d|90d — Insights · Flow (slice F). A thin - * adapter over the shared `projectFlow` operation, which owns the membership check, the queries - * and their limits (policy 5cb362e8). The Insights page and the Project Overview's "This week" - * pane both read it. + * The project Insights page's reads, each a thin adapter over its shared operation, which owns the + * membership check, the queries and their limits (policy 5cb362e8): + * - GET /api/projects/:projectId/insights/flow?range=7d|30d|90d — Flow (slice F, `projectFlow`), + * read by the Insights page and the Project Overview's "This week" pane; + * - GET /api/projects/:projectId/insights/accounts?range=7d|30d|90d — Accounts (slice A, + * `projectAccounts`). Private to the viewer (their own account names and limit windows), so + * never cached by a shared cache; + * - GET /api/projects/:projectId/insights/setups?range=7d|30d|90d&groupBy=profile|skill|model — + * Agent setups (slice S, `projectSetups`). Private for the same reason: it names the viewer's + * own personal profiles and skills; + * - GET /api/projects/:projectId/insights/people?range=7d|30d|90d — People (slice P, + * `projectPeople`). Private to the viewer (what they may read of each waiting item), so never + * cached by a shared cache. */ -import { projectFlow, toOperationHttpError } from '@simple-agent-manager/operations'; +import { + projectAccounts, + projectFlow, + projectPeople, + projectSetups, + toOperationHttpError, +} from '@simple-agent-manager/operations'; import { Hono } from 'hono'; import type { Env } from '../env'; @@ -27,3 +42,49 @@ projectInsightsRoutes.get('/flow', requireAuth(), requireApproved(), async (c) = throw toOperationHttpError(error); } }); + +projectInsightsRoutes.get('/accounts', requireAuth(), requireApproved(), async (c) => { + const userId = getUserId(c); + const projectId = requireRouteParam(c, 'projectId'); + c.header('Cache-Control', 'private, no-store'); + try { + const result = await projectAccounts(webOperationContext(c, userId), { + projectId, + range: c.req.query('range'), + }); + return c.json(result); + } catch (error) { + throw toOperationHttpError(error); + } +}); + +projectInsightsRoutes.get('/setups', requireAuth(), requireApproved(), async (c) => { + const userId = getUserId(c); + const projectId = requireRouteParam(c, 'projectId'); + c.header('Cache-Control', 'private, no-store'); + try { + const result = await projectSetups(webOperationContext(c, userId), { + projectId, + range: c.req.query('range'), + groupBy: c.req.query('groupBy'), + }); + return c.json(result); + } catch (error) { + throw toOperationHttpError(error); + } +}); + +projectInsightsRoutes.get('/people', requireAuth(), requireApproved(), async (c) => { + const userId = getUserId(c); + const projectId = requireRouteParam(c, 'projectId'); + c.header('Cache-Control', 'private, no-store'); + try { + const result = await projectPeople(webOperationContext(c, userId), { + projectId, + range: c.req.query('range'), + }); + return c.json(result); + } catch (error) { + throw toOperationHttpError(error); + } +}); diff --git a/apps/api/src/routes/project-overview.ts b/apps/api/src/routes/project-overview.ts index 7947e33296..d9b208274b 100644 --- a/apps/api/src/routes/project-overview.ts +++ b/apps/api/src/routes/project-overview.ts @@ -2,14 +2,24 @@ * GET /api/projects/:projectId/overview — the Project Overview page's one aggregated read * (Inbox slice F1). A thin adapter over the shared `projectOverviewGet` operation, which owns * the membership check, the queries and their limits (policy 5cb362e8). + * + * After the response, the generated brief (inbox slice I) is brought up to date in the + * background (`refreshProjectBriefIfDue`): the page shows the stored brief at once and never + * waits on the model. The refresh runs only after the read authorized the viewer. */ -import { projectOverviewGet, toOperationHttpError } from '@simple-agent-manager/operations'; +import { + getProjectBriefSettings, + projectOverviewGet, + toOperationHttpError, +} from '@simple-agent-manager/operations'; import { Hono } from 'hono'; import type { Env } from '../env'; +import { log } from '../lib/logger'; import { parsePositiveInt, requireRouteParam } from '../lib/route-helpers'; import { getUserId, requireApproved, requireAuth } from '../middleware/auth'; import { webOperationContext } from '../operation-ports'; +import { refreshProjectBriefIfDue } from '../services/project-brief/refresh'; export const projectOverviewRoutes = new Hono<{ Bindings: Env }>(); @@ -18,14 +28,23 @@ projectOverviewRoutes.get('/', requireAuth(), requireApproved(), async (c) => { const projectId = requireRouteParam(c, 'projectId'); const runningLimit = parsePositiveInt(c.req.query('runningLimit'), 0) || undefined; const recentLimit = parsePositiveInt(c.req.query('recentLimit'), 0) || undefined; + const ctx = webOperationContext(c, userId); + let result; try { - const result = await projectOverviewGet(webOperationContext(c, userId), { - projectId, - runningLimit, - recentLimit, - }); - return c.json(result); + result = await projectOverviewGet(ctx, { projectId, runningLimit, recentLimit }); } catch (error) { throw toOperationHttpError(error); } + + const refresh = getProjectBriefSettings(ctx).then((settings) => + refreshProjectBriefIfDue({ env: c.env, projectId: result.projectId, settings }) + ); + try { + c.executionCtx.waitUntil(refresh); + } catch { + // No ExecutionContext (some test harnesses): the refresh never throws, so it may run + // detached; it is simply not kept alive past the response. + log.warn('project_brief.refresh_detached', { projectId }); + } + return c.json(result); }); diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index ad7fa9b5a9..37ab252899 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -17,7 +17,7 @@ import { deleteProjectLibraryObjects, getProjectDeleteCleanupBatchSize, } from '../../services/file-library'; -import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; +import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history'; import { registerProjectCreateRoute } from './project-create'; @@ -43,9 +43,8 @@ async function cleanupArtifactsRepoOnProjectDelete( action: 'orphaned_artifacts_repo_on_delete', }; - // The Cloudflare binding even when ARTIFACTS_ENABLED was turned off since creation (unchanged), - // else this install's own hosted git backend. - const artifacts = env.ARTIFACTS ?? resolveArtifactsBackend(env); + // Disabling Artifacts stops serving, but must not prevent cleanup of existing repositories. + const artifacts = resolveArtifactsBackendForCleanup(env); if (!artifacts || typeof artifacts.delete !== 'function') { log.warn('project_delete.artifacts_delete_unavailable', orphanDetails); return; @@ -214,6 +213,10 @@ crudRoutes.delete('/:id', async (c) => { statements.push( db.delete(schema.agentProfiles).where(eq(schema.agentProfiles.projectId, projectId)) ); + // Run token usage (Insights slice U) has no FK to cascade from. + statements.push( + db.delete(schema.agentRunUsage).where(eq(schema.agentRunUsage.projectId, projectId)) + ); statements.push( db .delete(schema.projectGithubRepositories) diff --git a/apps/api/src/routes/projects/hosted-git-token.ts b/apps/api/src/routes/projects/hosted-git-token.ts index bd4f87a3af..5c35a8f8d3 100644 --- a/apps/api/src/routes/projects/hosted-git-token.ts +++ b/apps/api/src/routes/projects/hosted-git-token.ts @@ -15,7 +15,7 @@ import type { Env } from '../../env'; import { getUserId } from '../../middleware/auth'; import { errors } from '../../middleware/error'; import { requireProjectCapability } from '../../middleware/project-auth'; -import { hostedGitHost, isLocalHostedGitActive } from '../../services/hosted-git/backend'; +import { hostedGitHost, isLocalHostedGitActive } from '../../services/hosted-git/local-backend'; import { mintHostedGitToken } from '../../services/hosted-git/tokens'; const hostedGitTokenRoutes = new Hono<{ Bindings: Env }>(); diff --git a/apps/api/src/routes/projects/member-invite-helpers.ts b/apps/api/src/routes/projects/member-invite-helpers.ts new file mode 100644 index 0000000000..d9e84fc5cc --- /dev/null +++ b/apps/api/src/routes/projects/member-invite-helpers.ts @@ -0,0 +1,304 @@ +import type { + ProjectAccessRequestResponse, + ProjectInviteGithubAccessStatus, + ProjectInviteLinkResponse, + ProjectInviteLinkStatus, + ProjectMemberResponse, +} from '@simple-agent-manager/shared'; +import { and, eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { getTokenHashKey } from '../../lib/secrets'; +import { errors } from '../../middleware/error'; +import { clearCredentialAttributionHealthCache } from '../../services/credential-attribution-health'; +import { getUserInstallationRepositories } from '../../services/github-app'; +import { getExternalInstallationId } from '../../services/github-installation-ids'; +import { githubUserTokenUnavailableError } from '../../services/github-token-errors'; +import { + getGitHubUserAccessTokenForOwner, + getGitHubUserAccessTokenWithHeaders, +} from '../../services/github-user-access-token'; +import { clearProjectMultiplayerStateCache } from '../../services/project-multiplayer'; + +const INVITE_TOKEN_PREFIX = 'sam_inv_'; + +export function clearProjectMemberDerivedCaches(projectId: string): void { + clearProjectMultiplayerStateCache(projectId); + clearCredentialAttributionHealthCache(projectId); +} +export function parsePositiveEnvInt(value: string | undefined, fallback: number): number { + const parsed = Number.parseInt(value ?? '', 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; +} +export function addDays(now: Date, days: number): Date { + const next = new Date(now); + next.setUTCDate(next.getUTCDate() + days); + return next; +} +export function generateInviteToken(tokenBytes: number): string { + const bytes = new Uint8Array(tokenBytes); + crypto.getRandomValues(bytes); + let binary = ''; + for (const byte of bytes) binary += String.fromCodePoint(byte); + const base64url = btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); + return `${INVITE_TOKEN_PREFIX}${base64url}`; +} + +export async function hmacInviteToken(rawToken: string, secret: string): Promise { + const key = await crypto.subtle.importKey( + 'raw', + new TextEncoder().encode(secret), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ); + const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(rawToken)); + return Array.from(new Uint8Array(sig)) + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); +} +export function inviteStatus( + row: schema.ProjectInviteLink, + now = new Date() +): ProjectInviteLinkStatus { + if (row.revokedAt) return 'revoked'; + if (new Date(row.expiresAt).getTime() <= now.getTime()) return 'expired'; + return 'active'; +} +export function toUser(row: { + id: string | null; + name: string | null; + email: string | null; + image: string | null; + avatarUrl: string | null; +}): ProjectMemberResponse['user'] { + if (!row.id) return null; + return { + id: row.id, + name: row.name, + email: row.email, + image: row.image, + avatarUrl: row.avatarUrl, + }; +} +export function toInviteLinkResponse(row: schema.ProjectInviteLink): ProjectInviteLinkResponse { + return { + id: row.id, + projectId: row.projectId, + status: inviteStatus(row), + expiresAt: row.expiresAt, + revokedAt: row.revokedAt, + createdBy: row.createdBy, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + lastUsedAt: row.lastUsedAt, + useCount: row.useCount, + }; +} +export function toAccessRequestResponse(row: { + request: schema.ProjectAccessRequest; + userId: string | null; + name: string | null; + email: string | null; + image: string | null; + avatarUrl: string | null; +}): ProjectAccessRequestResponse { + return { + id: row.request.id, + projectId: row.request.projectId, + inviteLinkId: row.request.inviteLinkId, + requesterUserId: row.request.requesterUserId, + status: row.request.status as ProjectAccessRequestResponse['status'], + githubAccessStatus: row.request + .githubAccessStatus as ProjectAccessRequestResponse['githubAccessStatus'], + githubAccessCheckedAt: row.request.githubAccessCheckedAt, + githubAccessMessage: row.request.githubAccessMessage, + requestedAt: row.request.requestedAt, + decidedAt: row.request.decidedAt, + decidedBy: row.request.decidedBy, + decisionNote: row.request.decisionNote, + createdAt: row.request.createdAt, + updatedAt: row.request.updatedAt, + requester: toUser({ + id: row.userId, + name: row.name, + email: row.email, + image: row.image, + avatarUrl: row.avatarUrl, + }), + }; +} +async function getProjectInstallation( + db: ReturnType>, + project: schema.Project +): Promise { + const rows = await db + .select() + .from(schema.githubInstallations) + .where(eq(schema.githubInstallations.id, project.installationId)) + .limit(1); + const installation = rows[0]; + if (!installation) { + throw errors.notFound('Installation'); + } + return installation; +} +export async function evaluateRequesterGithubAccess(input: { + env: Env; + headers: Headers; + db: ReturnType>; + project: schema.Project; + requesterUserId: string; + currentRequestUserId?: string; +}): Promise<{ + status: ProjectInviteGithubAccessStatus; + checkedAt: string; + message: string | null; +}> { + const checkedAt = new Date().toISOString(); + if (input.project.repoProvider === 'artifacts') { + return { + status: 'unsupported-provider', + checkedAt, + message: 'GitHub repository access is not required for Artifacts-backed projects.', + }; + } + if (input.project.repoProvider && input.project.repoProvider !== 'github') { + return { + status: 'unsupported-provider', + checkedAt, + message: 'Repository provider is not supported for invite access checks.', + }; + } + + try { + const accessToken = + input.currentRequestUserId === input.requesterUserId + ? await getGitHubUserAccessTokenWithHeaders( + input.env, + input.headers, + input.requesterUserId, + 'project-invite-request' + ) + : await getGitHubUserAccessTokenForOwner( + input.env, + input.requesterUserId, + 'project-invite-approval' + ); + if (!accessToken) { + const unavailable = await githubUserTokenUnavailableError(input.env, input.requesterUserId); + return { + status: 'missing-token', + checkedAt, + message: + unavailable.error === 'GITHUB_NOT_CONNECTED' + ? 'Requester has not connected GitHub. Connect it in Settings → GitHub before running work.' + : 'Requester must reauthenticate with GitHub before repository access can be verified.', + }; + } + + const installation = await getProjectInstallation(input.db, input.project); + const externalInstallationId = getExternalInstallationId(installation); + const repositories = await getUserInstallationRepositories( + accessToken, + externalInstallationId, + { + flow: 'project-invite', + userId: input.requesterUserId, + installationId: externalInstallationId, + repository: input.project.repository, + } + ); + const matchedRepo = repositories.find( + (repo) => repo.fullName.toLowerCase() === input.project.repository.toLowerCase() + ); + if (!matchedRepo) { + return { + status: 'no-access', + checkedAt, + message: 'Requester does not have GitHub access to the project repository.', + }; + } + if (input.project.githubRepoId !== null && matchedRepo.id !== input.project.githubRepoId) { + return { + status: 'no-access', + checkedAt, + message: 'Requester GitHub access resolved to a different repository id.', + }; + } + return { + status: 'verified', + checkedAt, + message: null, + }; + } catch (err) { + log.warn('project_invite.github_access_check_failed', { + projectId: input.project.id, + requesterUserId: input.requesterUserId, + error: err instanceof Error ? err.message : String(err), + }); + return { + status: 'check-failed', + checkedAt, + message: 'GitHub access could not be verified. Retry after GitHub connectivity is restored.', + }; + } +} +export async function loadProjectInviteByToken( + c: { env: Env }, + token: string +): Promise<{ + db: ReturnType>; + link: schema.ProjectInviteLink; + project: schema.Project; +}> { + if (!token.startsWith(INVITE_TOKEN_PREFIX)) { + throw errors.notFound('Invite link'); + } + const db = drizzle(c.env.DATABASE, { schema }); + const tokenHash = await hmacInviteToken(token, getTokenHashKey(c.env)); + const rows = await db + .select({ link: schema.projectInviteLinks, project: schema.projects }) + .from(schema.projectInviteLinks) + .innerJoin(schema.projects, eq(schema.projectInviteLinks.projectId, schema.projects.id)) + .where(eq(schema.projectInviteLinks.tokenHash, tokenHash)) + .limit(1); + const row = rows[0]; + if (!row) { + throw errors.notFound('Invite link'); + } + return { db, link: row.link, project: row.project }; +} + +export async function loadAccessRequestWithUser( + db: ReturnType>, + projectId: string, + requestId: string +): Promise> { + const rows = await db + .select({ + request: schema.projectAccessRequests, + userId: schema.users.id, + name: schema.users.name, + email: schema.users.email, + image: schema.users.image, + avatarUrl: schema.users.avatarUrl, + }) + .from(schema.projectAccessRequests) + .leftJoin(schema.users, eq(schema.projectAccessRequests.requesterUserId, schema.users.id)) + .where( + and( + eq(schema.projectAccessRequests.projectId, projectId), + eq(schema.projectAccessRequests.id, requestId) + ) + ) + .limit(1); + const row = rows[0]; + if (!row) { + throw errors.notFound('Access request'); + } + return toAccessRequestResponse(row); +} diff --git a/apps/api/src/routes/projects/member-offboarding.ts b/apps/api/src/routes/projects/member-offboarding.ts index f1825119b3..aa081315c2 100644 --- a/apps/api/src/routes/projects/member-offboarding.ts +++ b/apps/api/src/routes/projects/member-offboarding.ts @@ -10,6 +10,7 @@ import type { Env } from '../../env'; import { getUserId } from '../../middleware/auth'; import { requireProjectCapability } from '../../middleware/project-auth'; import { ApplyProjectMemberOffboardingSchema, jsonValidator } from '../../schemas'; +import { moveDepartedMemberTasksToTeam } from '../../services/inbox/departed-member-tasks'; import { applyProjectMemberOffboarding } from '../../services/project-offboarding-apply'; import { createProjectMemberOffboardingPreview } from '../../services/project-offboarding-preview'; import { revokeSessionAccessForDepartedMember } from '../../services/session-access'; @@ -62,6 +63,8 @@ projectMemberOffboardingRoutes.post( // session; this also deletes their stored grants (and grants on sessions they own) so a // later re-approval cannot bring them back. await revokeSessionAccessForDepartedMember(c.env, projectId, memberUserId); + // Their open human tasks go to the team; the agents that assigned them are told. + await moveDepartedMemberTasksToTeam(c.env, projectId, memberUserId); } return c.json(response); diff --git a/apps/api/src/routes/projects/members.ts b/apps/api/src/routes/projects/members.ts index 501f5ba82e..0687157310 100644 --- a/apps/api/src/routes/projects/members.ts +++ b/apps/api/src/routes/projects/members.ts @@ -1,9 +1,5 @@ import type { CreatedProjectInviteLinkResponse, - ProjectAccessRequestResponse, - ProjectInviteGithubAccessStatus, - ProjectInviteLinkResponse, - ProjectInviteLinkStatus, ProjectInvitePreviewResponse, ProjectMemberResponse, ProjectMemberRole, @@ -16,7 +12,6 @@ import { Hono } from 'hono'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; -import { log } from '../../lib/logger'; import { getTokenHashKey } from '../../lib/secrets'; import { ulid } from '../../lib/ulid'; import { getUserId, rejectAgentSignInSession } from '../../middleware/auth'; @@ -27,24 +22,28 @@ import { DecideProjectAccessRequestSchema, jsonValidator, } from '../../schemas'; -import { clearCredentialAttributionHealthCache } from '../../services/credential-attribution-health'; -import { getUserInstallationRepositories } from '../../services/github-app'; -import { getExternalInstallationId } from '../../services/github-installation-ids'; -import { githubUserTokenUnavailableError } from '../../services/github-token-errors'; -import { - getGitHubUserAccessTokenForOwner, - getGitHubUserAccessTokenWithHeaders, -} from '../../services/github-user-access-token'; import { inviteMembershipStatus, resolveConcurrentAccessRequest, resolveConcurrentRequestInsert, } from '../../services/project-access-request-reentry'; -import { clearProjectMultiplayerStateCache } from '../../services/project-multiplayer'; +import { + addDays, + clearProjectMemberDerivedCaches, + evaluateRequesterGithubAccess, + generateInviteToken, + hmacInviteToken, + inviteStatus, + loadAccessRequestWithUser, + loadProjectInviteByToken, + parsePositiveEnvInt, + toAccessRequestResponse, + toInviteLinkResponse, + toUser, +} from './member-invite-helpers'; import { projectMemberOffboardingRoutes } from './member-offboarding'; import { projectOwnershipTransferRoutes } from './ownership-transfer'; -const INVITE_TOKEN_PREFIX = 'sam_inv_'; const DEFAULT_INVITE_TOKEN_BYTES = 32; const DEFAULT_INVITE_EXPIRY_DAYS = 7; const DEFAULT_INVITE_MAX_EXPIRY_DAYS = 30; @@ -53,281 +52,6 @@ const projectMembersRoutes = new Hono<{ Bindings: Env }>(); projectMembersRoutes.route('/', projectOwnershipTransferRoutes); projectMembersRoutes.route('/', projectMemberOffboardingRoutes); -function clearProjectMemberDerivedCaches(projectId: string): void { - clearProjectMultiplayerStateCache(projectId); - clearCredentialAttributionHealthCache(projectId); -} -function parsePositiveEnvInt(value: string | undefined, fallback: number): number { - const parsed = parseInt(value ?? '', 10); - return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; -} -function addDays(now: Date, days: number): Date { - const next = new Date(now); - next.setUTCDate(next.getUTCDate() + days); - return next; -} -function generateInviteToken(tokenBytes: number): string { - const bytes = new Uint8Array(tokenBytes); - crypto.getRandomValues(bytes); - let binary = ''; - for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i] ?? 0); - const base64url = btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); - return `${INVITE_TOKEN_PREFIX}${base64url}`; -} - -async function hmacInviteToken(rawToken: string, secret: string): Promise { - const key = await crypto.subtle.importKey( - 'raw', - new TextEncoder().encode(secret), - { name: 'HMAC', hash: 'SHA-256' }, - false, - ['sign'] - ); - const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(rawToken)); - return Array.from(new Uint8Array(sig)) - .map((b) => b.toString(16).padStart(2, '0')) - .join(''); -} -function inviteStatus(row: schema.ProjectInviteLink, now = new Date()): ProjectInviteLinkStatus { - if (row.revokedAt) return 'revoked'; - if (new Date(row.expiresAt).getTime() <= now.getTime()) return 'expired'; - return 'active'; -} -function toUser(row: { - id: string | null; - name: string | null; - email: string | null; - image: string | null; - avatarUrl: string | null; -}): ProjectMemberResponse['user'] { - if (!row.id) return null; - return { - id: row.id, - name: row.name, - email: row.email, - image: row.image, - avatarUrl: row.avatarUrl, - }; -} -function toInviteLinkResponse(row: schema.ProjectInviteLink): ProjectInviteLinkResponse { - return { - id: row.id, - projectId: row.projectId, - status: inviteStatus(row), - expiresAt: row.expiresAt, - revokedAt: row.revokedAt, - createdBy: row.createdBy, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - lastUsedAt: row.lastUsedAt, - useCount: row.useCount, - }; -} -function toAccessRequestResponse(row: { - request: schema.ProjectAccessRequest; - userId: string | null; - name: string | null; - email: string | null; - image: string | null; - avatarUrl: string | null; -}): ProjectAccessRequestResponse { - return { - id: row.request.id, - projectId: row.request.projectId, - inviteLinkId: row.request.inviteLinkId, - requesterUserId: row.request.requesterUserId, - status: row.request.status as ProjectAccessRequestResponse['status'], - githubAccessStatus: row.request - .githubAccessStatus as ProjectAccessRequestResponse['githubAccessStatus'], - githubAccessCheckedAt: row.request.githubAccessCheckedAt, - githubAccessMessage: row.request.githubAccessMessage, - requestedAt: row.request.requestedAt, - decidedAt: row.request.decidedAt, - decidedBy: row.request.decidedBy, - decisionNote: row.request.decisionNote, - createdAt: row.request.createdAt, - updatedAt: row.request.updatedAt, - requester: toUser({ - id: row.userId, - name: row.name, - email: row.email, - image: row.image, - avatarUrl: row.avatarUrl, - }), - }; -} -async function getProjectInstallation( - db: ReturnType>, - project: schema.Project -): Promise { - const rows = await db - .select() - .from(schema.githubInstallations) - .where(eq(schema.githubInstallations.id, project.installationId)) - .limit(1); - const installation = rows[0]; - if (!installation) { - throw errors.notFound('Installation'); - } - return installation; -} -async function evaluateRequesterGithubAccess(input: { - env: Env; - headers: Headers; - db: ReturnType>; - project: schema.Project; - requesterUserId: string; - currentRequestUserId?: string; -}): Promise<{ - status: ProjectInviteGithubAccessStatus; - checkedAt: string; - message: string | null; -}> { - const checkedAt = new Date().toISOString(); - if (input.project.repoProvider === 'artifacts') { - return { - status: 'unsupported-provider', - checkedAt, - message: 'GitHub repository access is not required for Artifacts-backed projects.', - }; - } - if (input.project.repoProvider && input.project.repoProvider !== 'github') { - return { - status: 'unsupported-provider', - checkedAt, - message: 'Repository provider is not supported for invite access checks.', - }; - } - - const accessToken = - input.currentRequestUserId === input.requesterUserId - ? await getGitHubUserAccessTokenWithHeaders( - input.env, - input.headers, - input.requesterUserId, - 'project-invite-request' - ) - : await getGitHubUserAccessTokenForOwner( - input.env, - input.requesterUserId, - 'project-invite-approval' - ); - if (!accessToken) { - const unavailable = await githubUserTokenUnavailableError(input.env, input.requesterUserId); - return { - status: 'missing-token', - checkedAt, - message: - unavailable.error === 'GITHUB_NOT_CONNECTED' - ? 'Requester has not connected GitHub to their SAM account. They can join, but cannot run work in this project until they connect GitHub in Settings → GitHub.' - : 'Requester must reauthenticate with GitHub before repository access can be verified.', - }; - } - - try { - const installation = await getProjectInstallation(input.db, input.project); - const externalInstallationId = getExternalInstallationId(installation); - const repositories = await getUserInstallationRepositories( - accessToken, - externalInstallationId, - { - flow: 'project-invite', - userId: input.requesterUserId, - installationId: externalInstallationId, - repository: input.project.repository, - } - ); - const matchedRepo = repositories.find( - (repo) => repo.fullName.toLowerCase() === input.project.repository.toLowerCase() - ); - if (!matchedRepo) { - return { - status: 'no-access', - checkedAt, - message: 'Requester does not have GitHub access to the project repository.', - }; - } - if (input.project.githubRepoId !== null && matchedRepo.id !== input.project.githubRepoId) { - return { - status: 'no-access', - checkedAt, - message: 'Requester GitHub access resolved to a different repository id.', - }; - } - return { - status: 'verified', - checkedAt, - message: null, - }; - } catch (err) { - log.warn('project_invite.github_access_check_failed', { - projectId: input.project.id, - requesterUserId: input.requesterUserId, - error: err instanceof Error ? err.message : String(err), - }); - return { - status: 'check-failed', - checkedAt, - message: 'GitHub access could not be verified. Retry after GitHub connectivity is restored.', - }; - } -} -async function loadProjectInviteByToken( - c: { env: Env }, - token: string -): Promise<{ - db: ReturnType>; - link: schema.ProjectInviteLink; - project: schema.Project; -}> { - if (!token.startsWith(INVITE_TOKEN_PREFIX)) { - throw errors.notFound('Invite link'); - } - const db = drizzle(c.env.DATABASE, { schema }); - const tokenHash = await hmacInviteToken(token, getTokenHashKey(c.env)); - const rows = await db - .select({ link: schema.projectInviteLinks, project: schema.projects }) - .from(schema.projectInviteLinks) - .innerJoin(schema.projects, eq(schema.projectInviteLinks.projectId, schema.projects.id)) - .where(eq(schema.projectInviteLinks.tokenHash, tokenHash)) - .limit(1); - const row = rows[0]; - if (!row) { - throw errors.notFound('Invite link'); - } - return { db, link: row.link, project: row.project }; -} - -async function loadAccessRequestWithUser( - db: ReturnType>, - projectId: string, - requestId: string -): Promise> { - const rows = await db - .select({ - request: schema.projectAccessRequests, - userId: schema.users.id, - name: schema.users.name, - email: schema.users.email, - image: schema.users.image, - avatarUrl: schema.users.avatarUrl, - }) - .from(schema.projectAccessRequests) - .leftJoin(schema.users, eq(schema.projectAccessRequests.requesterUserId, schema.users.id)) - .where( - and( - eq(schema.projectAccessRequests.projectId, projectId), - eq(schema.projectAccessRequests.id, requestId) - ) - ) - .limit(1); - const row = rows[0]; - if (!row) { - throw errors.notFound('Access request'); - } - return toAccessRequestResponse(row); -} - projectMembersRoutes.get('/:id/members', async (c) => { const userId = getUserId(c); const projectId = c.req.param('id'); diff --git a/apps/api/src/routes/projects/project-create.ts b/apps/api/src/routes/projects/project-create.ts index 066e4f1ea4..3af17b7d70 100644 --- a/apps/api/src/routes/projects/project-create.ts +++ b/apps/api/src/routes/projects/project-create.ts @@ -20,16 +20,16 @@ import { requireGitLabUserAccessToken, verifyGitLabProjectAccess, } from '../../services/gitlab'; -import { - artifactsRemoteFetch, - isLocalHostedGitActive, - resolveArtifactsBackend, -} from '../../services/hosted-git/backend'; +import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { importIntoHostedRepository, parseHostedGitImportUrl, resolveImportDefaultBranch, } from '../../services/hosted-git/import'; +import { + artifactsRemoteFetch, + isLocalHostedGitActive, +} from '../../services/hosted-git/local-backend'; import { getRuntimeLimits } from '../../services/limits'; import { assertRepositoryAccess, @@ -93,13 +93,9 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): if (!artifactsEnabled) { throw errors.badRequest('Artifacts repo provider is not enabled'); } - // Enabled but no binding: this runtime has no Cloudflare Artifacts (not a server fault). const artifacts = resolveArtifactsBackend(c.env); if (!artifacts) { - throw errors.featureUnavailable( - 'artifacts', - 'SAM-native Git repositories are not available on this installation' - ); + throw errors.internal('Artifacts binding is not configured'); } // Check per-user Artifacts repo limit diff --git a/apps/api/src/routes/tasks/_helpers.ts b/apps/api/src/routes/tasks/_helpers.ts index c2a3adf1fb..248df5ebd6 100644 --- a/apps/api/src/routes/tasks/_helpers.ts +++ b/apps/api/src/routes/tasks/_helpers.ts @@ -13,6 +13,7 @@ import { log } from '../../lib/logger'; import { ulid } from '../../lib/ulid'; import { errors } from '../../middleware/error'; import { getBlockedTaskIds, isTaskBlocked } from '../../services/task-graph'; +import { taskRecoveryCancellationQuery } from '../../services/task-recovery-cancellation'; import { triggerExecutionSyncableWhere } from '../../services/trigger-execution-sync'; import { assertWorkspaceCallbackIdentityCurrent, @@ -283,7 +284,7 @@ export async function setTaskStatus( let updatedTask: schema.Task | undefined; if (options.callbackFence) { - const rows = await db + const update = db .update(schema.tasks) .set(nextValues) .where( @@ -297,15 +298,26 @@ export async function setTaskStatus( ) ) .returning(); + const rows = + toStatus === 'cancelled' + ? (await db.batch([update, taskRecoveryCancellationQuery(db, task, now)]))[0] + : await update; updatedTask = rows[0]; if (!updatedTask) return rejectChangedTaskCallbackFence(options.callbackFence); } else { // project_id is defence-in-depth (rule 11): callers already resolved `task` through // requireProjectTaskById, but the write predicate must not depend on that alone. - await db + const update = db .update(schema.tasks) .set(nextValues) .where(and(eq(schema.tasks.id, task.id), eq(schema.tasks.projectId, task.projectId))); + if (toStatus === 'cancelled') { + // Cancellation revokes this wake attempt in the SAME D1 transaction. + // Keep the snapshot available for a later, fresh human follow-up. + await db.batch([update, taskRecoveryCancellationQuery(db, task, now)]); + } else { + await update; + } } await appendStatusEvent( diff --git a/apps/api/src/routes/tasks/callback.ts b/apps/api/src/routes/tasks/callback.ts index 15d1ea2579..0d68bf4234 100644 --- a/apps/api/src/routes/tasks/callback.ts +++ b/apps/api/src/routes/tasks/callback.ts @@ -11,6 +11,7 @@ import { toTaskResponse } from '../../lib/mappers'; import { requireRouteParam } from '../../lib/route-helpers'; import { errors } from '../../middleware/error'; import { jsonValidator, UpdateTaskStatusSchema } from '../../schemas'; +import { fileTaskFailure } from '../../services/inbox/system-errors'; import { verifyCallbackToken } from '../../services/jwt'; import * as notificationService from '../../services/notification'; import * as projectDataService from '../../services/project-data'; @@ -18,6 +19,7 @@ import { isLifecycleTaskStatus, recordTaskLifecycleEventBestEffort, } from '../../services/project-lifecycle-events'; +import { retireTaskCancellationPrompts } from '../../services/task-cancellation-prompts'; import { canTransitionTaskStatus, getAllowedTaskTransitions, @@ -373,6 +375,10 @@ taskCallbackRoute.post( } const prUpdate = await callbackPr.prepareStatusCallbackPullRequest(db, projectId, task, body); + if (body.toStatus === 'cancelled') { + await retireTaskCancellationPrompts(c.env, task, revalidateWorkspace); + await revalidateWorkspace(); + } const updatedTask = await setTaskStatus( db, task, @@ -475,6 +481,11 @@ taskCallbackRoute.post( outputBranch: updatedTask.outputBranch, }); } else if (body.toStatus === 'failed') { + // File the inbox error item first so the notification opens it (slice E). Filing + // never throws; a normal ending files nothing and keeps the chat link. + const filed = await fileTaskFailure(c.env, projectId, taskId); + // The sweep filed it first and already told the person: one notification per item. + if (filed && !filed.created) return; await notificationService.notifyTaskFailed(c.env, task.userId, { projectId, projectName, @@ -482,6 +493,7 @@ taskCallbackRoute.post( taskTitle: task.title, errorMessage: body.errorMessage, sessionId, + inboxRef: filed?.ref ?? null, }); } })().catch((e) => { diff --git a/apps/api/src/routes/tasks/crud.ts b/apps/api/src/routes/tasks/crud.ts index ae15523ff2..242fe9889a 100644 --- a/apps/api/src/routes/tasks/crud.ts +++ b/apps/api/src/routes/tasks/crud.ts @@ -1,3 +1,4 @@ +import { cronToHumanReadable } from '@simple-agent-manager/cron'; import { toOperationHttpError } from '@simple-agent-manager/operations'; import { applyIdeaStatusTransition, isIdeaStatus } from '@simple-agent-manager/operations'; import { getIdeaSessionLinks } from '@simple-agent-manager/operations'; @@ -38,7 +39,6 @@ import { resolveTaskAgentProfileHints, } from '../../services/agent-profile-display'; import { cancelTask } from '../../services/cancel-task'; -import { cronToHumanReadable } from '../../services/cron-utils'; import { getRuntimeLimits } from '../../services/limits'; import * as projectDataService from '../../services/project-data'; import { diff --git a/apps/api/src/routes/transcribe.ts b/apps/api/src/routes/transcribe.ts index a5a18cdfa3..867bbadb26 100644 --- a/apps/api/src/routes/transcribe.ts +++ b/apps/api/src/routes/transcribe.ts @@ -2,15 +2,11 @@ import { Hono, type MiddlewareHandler } from 'hono'; import type { Env } from '../env'; import { createModuleLogger, serializeError } from '../lib/logger'; -import { requireApproved, requireAuth } from '../middleware/auth'; +import { requireApproved,requireAuth } from '../middleware/auth'; import { errors } from '../middleware/error'; import { rateLimitTranscribe } from '../middleware/rate-limit'; import { getWorkersAiBindingOrNull } from '../services/platform-capabilities'; -import { - resolveSpeechEndpoint, - SpeechEndpointError, - transcribeWithEndpoint, -} from '../services/speech-endpoints'; +import { resolveSpeechTranscriptionBackend } from '../services/speech-backend'; const log = createModuleLogger('transcribe'); @@ -53,12 +49,12 @@ const limitTranscription: MiddlewareHandler<{ Bindings: Env }> = (c, next) => */ transcribeRoutes.post('/', limitTranscription, async (c) => { const startTime = Date.now(); - // Whisper runs on Workers AI. Without the binding, an admin-configured OpenAI-compatible - // transcription endpoint (`speech.transcription.*`) serves instead; with neither, refuse before - // reading the upload so the client gets a clear answer instead of a 500. + // Whisper runs on Workers AI. Without the binding, a backend the self-host build installed + // (services/speech-backend.ts) serves instead; with neither, refuse before reading the upload + // so the client gets a clear answer instead of a 500. With the binding nothing else is read. const ai = getWorkersAiBindingOrNull(c.env); - const endpoint = ai ? null : await resolveSpeechEndpoint(c.env, 'transcription'); - if (!ai && !endpoint) { + const backend = ai ? null : await resolveSpeechTranscriptionBackend(c.env); + if (!ai && !backend) { throw errors.featureUnavailable( 'speechToText', 'Speech-to-text is not available on this installation' @@ -116,25 +112,24 @@ transcribeRoutes.post('/', limitTranscription, async (c) => { ); } - if (!ai && endpoint) { + if (!ai) { + if (!backend) throw errors.internal('Speech-to-text has no backend'); + let text: string; try { - const text = await transcribeWithEndpoint(endpoint, audioFile); - log.info('request_complete', { - via: 'endpoint', - totalDurationMs: Date.now() - startTime, - inputSizeKB: Math.round(audioFile.size / 1024), - outputLength: text.trim().length, - }); - return c.json({ text: text.trim() }); + text = (await backend.transcribe(audioFile)).trim(); } catch (err) { - log.error('endpoint_transcription_failed', { - error: err instanceof Error ? err.message : String(err), - status: err instanceof SpeechEndpointError ? err.status : null, - }); + // The cause can name the admin's endpoint host or the provider's status; keep it in the log. + log.error('backend_transcription_failed', serializeError(err)); throw errors.serviceUnavailable('Speech-to-text failed. Try again shortly.'); } + log.info('request_complete', { + via: 'backend', + totalDurationMs: Date.now() - startTime, + inputSizeKB: Math.round(audioFile.size / 1024), + outputLength: text.length, + }); + return c.json({ text }); } - if (!ai) throw errors.internal('Speech-to-text has no backend'); // Convert audio to base64 for Workers AI Whisper input const audioBuffer = await audioFile.arrayBuffer(); @@ -145,8 +140,8 @@ transcribeRoutes.post('/', limitTranscription, async (c) => { }); // Determine model ID (configurable via env var, per Constitution Principle XI) - const modelId = (c.env.WHISPER_MODEL_ID || - DEFAULT_WHISPER_MODEL) as '@cf/openai/whisper-large-v3-turbo'; + const modelId = (c.env.WHISPER_MODEL_ID || DEFAULT_WHISPER_MODEL) as + '@cf/openai/whisper-large-v3-turbo'; log.info('calling_workers_ai', { model: modelId }); // Call Workers AI Whisper model diff --git a/apps/api/src/routes/triggers/crud.ts b/apps/api/src/routes/triggers/crud.ts index 66ff231b9a..b8fe080ffd 100644 --- a/apps/api/src/routes/triggers/crud.ts +++ b/apps/api/src/routes/triggers/crud.ts @@ -1,4 +1,5 @@ /** Authenticated trigger CRUD. Execution actions live in actions.ts. */ +import { cronToNextFire } from '@simple-agent-manager/cron'; import { ResourceRequirementsValidationError, serializeResourceRequirementsInput, @@ -33,7 +34,6 @@ import { toEmailTriggerConfig, } from '../../services/agent-email/trigger-config'; import { buildCredentialAttributionForTriggers } from '../../services/credential-attribution-health'; -import { cronToNextFire } from '../../services/cron-utils'; import { assertGitHubTriggerConfigExists, githubTriggerConfigUpdate, diff --git a/apps/api/src/routes/tts.ts b/apps/api/src/routes/tts.ts index 4032b3bdeb..c79b193784 100644 --- a/apps/api/src/routes/tts.ts +++ b/apps/api/src/routes/tts.ts @@ -2,20 +2,13 @@ import { Hono } from 'hono'; import type { Env } from '../env'; import { log } from '../lib/logger'; -import { getAuth, requireApproved, requireAuth } from '../middleware/auth'; +import { getAuth, requireApproved,requireAuth } from '../middleware/auth'; import { errors } from '../middleware/error'; -import { - checkRateLimit, - createRateLimitKey, - DEFAULT_WINDOW_SECONDS, - getCurrentWindowStart, - getRateLimit, - RateLimitError, -} from '../middleware/rate-limit'; +import { RateLimitError } from '../middleware/rate-limit'; import { parseOptionalBody, TtsRequestSchema } from '../schemas'; import { getWorkersAiBindingOrNull } from '../services/platform-capabilities'; -import { resolveSpeechEndpoint } from '../services/speech-endpoints'; -import { getAudioFromR2, getTTSConfig, synthesizeSpeech } from '../services/tts'; +import { resolveSpeechSynthesisBackend } from '../services/speech-backend'; +import { getAudioFromR2, getTTSConfig,synthesizeSpeech } from '../services/tts'; const ttsRoutes = new Hono<{ Bindings: Env }>(); @@ -42,30 +35,23 @@ ttsRoutes.post('/synthesize', async (c) => { if (!config.enabled) { throw errors.badRequest('Text-to-speech is disabled'); } - // Synthesis runs on Workers AI, or without the binding on an admin-configured OpenAI-compatible - // speech endpoint (`speech.synthesis.*`). With neither, say so instead of retrying into a 500. + // Synthesis runs on Workers AI. Without the binding, a backend the self-host build installed + // (services/speech-backend.ts) serves instead; with neither, say so instead of failing with a + // 500. With the binding nothing else is read. const binding = getWorkersAiBindingOrNull(c.env); - const ai = binding ?? (await resolveSpeechEndpoint(c.env, 'synthesis')); + const backend = binding ? null : await resolveSpeechSynthesisBackend(c.env); + const ai = binding ?? backend; if (!ai) { throw errors.featureUnavailable( 'textToSpeech', 'Text-to-speech is not available on this installation' ); } - if (!binding) { - // Every miss spends the admin's speech endpoint: bound it per user (KV, per hour). - const limit = getRateLimit(c.env, 'TTS_SYNTHESIZE'); - const window = getCurrentWindowStart(DEFAULT_WINDOW_SECONDS); - const result = await checkRateLimit( - c.env.KV, - createRateLimitKey('tts-synthesize', userId, window), - limit, - DEFAULT_WINDOW_SECONDS - ); - if (!result.allowed) { - throw new RateLimitError(Math.max(1, result.resetAt - Math.floor(Date.now() / 1000))); - } - } + // A backend spends the admin's endpoint on every miss; it decides whether this user may. + await backend?.admit(c.env, userId).catch((err: unknown) => { + if (err instanceof RateLimitError) c.header('Retry-After', String(err.retryAfter)); + throw err; + }); const body = await parseOptionalBody(c.req.raw, TtsRequestSchema, {}); if (!body.text || !body.storageId) { @@ -99,8 +85,8 @@ ttsRoutes.post('/synthesize', async (c) => { textLength: text.length, mode, }); - // An endpoint error can name the admin's host or the provider's status; keep it in the log. - if (!binding) throw errors.serviceUnavailable('Text-to-speech failed. Try again shortly.'); + // A backend error can name the admin's endpoint host or the provider's status; log only. + if (backend) throw errors.serviceUnavailable('Text-to-speech failed. Try again shortly.'); const errorMessage = err instanceof Error ? err.message : String(err); throw errors.internal(`TTS synthesis failed: ${errorMessage}`); } diff --git a/apps/api/src/routes/usage.ts b/apps/api/src/routes/usage.ts index 071ca2fdb4..cf4896c38f 100644 --- a/apps/api/src/routes/usage.ts +++ b/apps/api/src/routes/usage.ts @@ -1,4 +1,10 @@ -import { getLocalUsageBreakdown } from '@simple-agent-manager/ai-proxy'; +import { + getLocalMonthlyAiCostUsd, + getLocalUsageBreakdown, + hasLocalAiCostMetering, + isMonthlyCostCapAvailable, + resolveAiGatewayId, +} from '@simple-agent-manager/ai-proxy'; import type { UserAiBudgetResponse, UserAiUsageResponse, @@ -27,19 +33,19 @@ import { } from '../services/ai-gateway-logs'; import { deleteUserBudgetSettings, + effectiveMonthlyCostCapUsd, getAdminAiAllowance, - getLocalMonthlyAiCostUsd, getProviderUsage, getTokenUsage, getUserBudgetSettings, resolveEffectiveLimits, + resolveMonthlyCostCeilingUsd, saveUserBudgetSettings, validateBudgetUpdate, } from '../services/ai-token-budget'; import { checkQuotaForUser, userHasOwnCloudCredentials } from '../services/compute-quotas'; import { getCurrentPeriodBounds } from '../services/compute-usage'; import { getUserNodeUsageSummary } from '../services/node-usage'; -import { isMonthlyCostCapAvailable, resolveAiGatewayId } from '../services/platform-capabilities'; const usageRoutes = new Hono<{ Bindings: Env }>(); @@ -100,7 +106,12 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { const gatewayId = resolveAiGatewayId(c.env); if (!gatewayId) { const providerMap = new Map(); - const localProviderUsage = await getProviderUsage(c.env.KV, userId, new Date(periodBounds.startDate), c.env); + const localProviderUsage = await getProviderUsage( + c.env.KV, + userId, + new Date(periodBounds.startDate), + c.env + ); let totalRequests = 0; let totalInputTokens = 0; let totalOutputTokens = 0; @@ -113,8 +124,8 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { totalCostUsd += entry.estimatedCostUsd; } - // Gateway not configured: SAM's own records (overnight B3 A2), not an error. - // A failed breakdown read degrades to empty views, never a failed usage page. + // Gateway not configured: SAM's own records, not an error. A failed per-model read degrades + // to empty breakdowns, never a failed usage page. const breakdown = await getLocalUsageBreakdown( c.env, userId, @@ -193,7 +204,12 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { } satisfies UserAiUsageResponse); } - const localProviderUsage = await getProviderUsage(c.env.KV, userId, new Date(periodBounds.startDate), c.env); + const localProviderUsage = await getProviderUsage( + c.env.KV, + userId, + new Date(periodBounds.startDate), + c.env + ); for (const entry of localProviderUsage) { mergeLocalProviderUsage(providerMap, entry); totalRequests += entry.requests; @@ -210,7 +226,9 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { cachedRequests, errorRequests, byModel: Array.from(modelMap.values()).sort((a, b) => b.costUsd - a.costUsd), - byProvider: Array.from(providerMap.values()).sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens), + byProvider: Array.from(providerMap.values()).sort( + (a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens + ), byDay: Array.from(dayMap.values()).sort((a, b) => a.date.localeCompare(b.date)), period, periodLabel: getPeriodLabel(period), @@ -221,7 +239,7 @@ usageRoutes.get('/ai', requireAuth(), requireApproved(), async (c) => { function mergeLocalProviderUsage( map: Map, - entry: Awaited>[number], + entry: Awaited>[number] ): void { const key = `${entry.providerId}:${entry.dialect}`; const existing = map.get(key); @@ -260,15 +278,18 @@ function mergeLocalProviderUsage( usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { const userId = getUserId(c); - const [userSettings, dailyUsage] = await Promise.all([ + const [userSettings, dailyUsage, ceilingUsd] = await Promise.all([ getUserBudgetSettings(c.env.KV, userId), getTokenUsage(c.env.KV, userId, c.env), + resolveMonthlyCostCeilingUsd(c.env), ]); const effectiveLimits = resolveEffectiveLimits(userSettings, c.env); // Get current month cost from AI Gateway (reuse the same aggregation) - let monthCostUsd = 0; + let monthCostUsd = hasLocalAiCostMetering(c.env) + ? await getLocalMonthlyAiCostUsd(c.env.KV, userId, c.env) + : 0; const gatewayId = resolveAiGatewayId(c.env); if (gatewayId) { const periodBounds = getGatewayPeriodBounds('current-month'); @@ -283,16 +304,6 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { error: err instanceof Error ? err.message : String(err), }); } - } else { - // No gateway: SAM's own priced total, the same figure the cap is enforced against. - try { - monthCostUsd = await getLocalMonthlyAiCostUsd(c.env.KV, userId, c.env); - } catch (err) { - log.error('usage.budget_local_cost_error', { - userId, - error: err instanceof Error ? err.message : String(err), - }); - } } const settings = userSettings ?? { @@ -302,21 +313,27 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { alertThresholdPercent: DEFAULT_AI_USAGE_ALERT_THRESHOLD_PERCENT, }; - const dailyInputPercent = effectiveLimits.dailyInputTokenLimit > 0 - ? Math.min(100, (dailyUsage.inputTokens / effectiveLimits.dailyInputTokenLimit) * 100) - : 0; - const dailyOutputPercent = effectiveLimits.dailyOutputTokenLimit > 0 - ? Math.min(100, (dailyUsage.outputTokens / effectiveLimits.dailyOutputTokenLimit) * 100) - : 0; - // A gateway without the account API cannot price spend, so its cap has no utilization. - const monthlyCostCapAvailable = isMonthlyCostCapAvailable(c.env); + const dailyInputPercent = + effectiveLimits.dailyInputTokenLimit > 0 + ? Math.min(100, (dailyUsage.inputTokens / effectiveLimits.dailyInputTokenLimit) * 100) + : 0; + const dailyOutputPercent = + effectiveLimits.dailyOutputTokenLimit > 0 + ? Math.min(100, (dailyUsage.outputTokens / effectiveLimits.dailyOutputTokenLimit) * 100) + : 0; + // The same cap the gate enforces (checkMonthlyCostCap); a gateway without the account API + // cannot price spend, so there the cap has no utilization. + const capAvailable = isMonthlyCostCapAvailable(c.env); + const effectiveCapUsd = capAvailable + ? effectiveMonthlyCostCapUsd(settings.monthlyCostCapUsd, ceilingUsd) + : null; const monthlyCostPercent = - monthlyCostCapAvailable && settings.monthlyCostCapUsd !== null && settings.monthlyCostCapUsd > 0 - ? Math.min(100, (monthCostUsd / settings.monthlyCostCapUsd) * 100) - : null; + effectiveCapUsd !== null ? Math.min(100, (monthCostUsd / effectiveCapUsd) * 100) : null; - const exceeded = dailyInputPercent >= 100 || dailyOutputPercent >= 100 - || (monthlyCostPercent !== null && monthlyCostPercent >= 100); + const exceeded = + dailyInputPercent >= 100 || + dailyOutputPercent >= 100 || + (monthlyCostPercent !== null && monthlyCostPercent >= 100); const response: UserAiBudgetResponse = { settings, @@ -327,11 +344,12 @@ usageRoutes.get('/ai/budget', requireAuth(), requireApproved(), async (c) => { }, effectiveLimits, monthCostUsd, - monthlyCostCapAvailable, + monthlyCostCap: { available: capAvailable, ceilingUsd, effectiveCapUsd }, utilization: { dailyInputPercent: Math.round(dailyInputPercent * 10) / 10, dailyOutputPercent: Math.round(dailyOutputPercent * 10) / 10, - monthlyCostPercent: monthlyCostPercent !== null ? Math.round(monthlyCostPercent * 10) / 10 : null, + monthlyCostPercent: + monthlyCostPercent !== null ? Math.round(monthlyCostPercent * 10) / 10 : null, }, exceeded, }; @@ -352,14 +370,20 @@ usageRoutes.put('/ai/budget', requireAuth(), requireApproved(), async (c) => { return c.json({ error: 'INVALID_JSON', message: 'Invalid JSON body' }, 400); } - // Fetch admin allowance to enforce ceilings on user-set limits - const adminAllowance = await getAdminAiAllowance(c.env.KV, userId); + // Admin allowance (per user) and installation ceiling bound what the user may set. + const [adminAllowance, ceilingUsd] = await Promise.all([ + getAdminAiAllowance(c.env.KV, userId), + resolveMonthlyCostCeilingUsd(c.env), + ]); let settings; try { - settings = validateBudgetUpdate(body, c.env, adminAllowance); + settings = validateBudgetUpdate(body, c.env, adminAllowance, ceilingUsd); } catch (err) { - return c.json({ error: 'VALIDATION_ERROR', message: err instanceof Error ? err.message : String(err) }, 400); + return c.json( + { error: 'VALIDATION_ERROR', message: err instanceof Error ? err.message : String(err) }, + 400 + ); } await saveUserBudgetSettings(c.env.KV, userId, settings); diff --git a/apps/api/src/routes/workspace-subdomain-proxy.ts b/apps/api/src/routes/workspace-subdomain-proxy.ts index 449bc5ac33..3a22474f81 100644 --- a/apps/api/src/routes/workspace-subdomain-proxy.ts +++ b/apps/api/src/routes/workspace-subdomain-proxy.ts @@ -4,10 +4,6 @@ * D1, then proxy to the node's vm-agent or the Instant container. Moved verbatim out of * `index.ts` (rule 18); `index.ts` mounts it with `app.use('*', workspaceSubdomainProxy)` at * the same position in the middleware chain. - * - * On a self-hosted box the same handler also answers Caddy forward_auth for WebSocket upgrades - * (`routes/self-host-gateway.ts`): when the request is a gateway authorization request it - * returns the upstream decision instead of fetching, so the gateway runs exactly this auth. */ import type { WorkspaceStatus } from '@simple-agent-manager/shared'; import { and, eq } from 'drizzle-orm'; @@ -26,8 +22,7 @@ import { getNodeBackendBaseUrl } from '../services/node-agent-readiness'; import { type NodeAgentRoute, NodeAgentRouteError, - nodeAgentRouteFromRow, - readNodeAgentRouteRow, + resolveNodeAgentRoute, } from '../services/node-agent-route'; import { gatewayDecisionResponse, @@ -147,11 +142,15 @@ export async function workspaceSubdomainProxy( } const workspaceStatus = workspace.status as WorkspaceStatus; - // One read for runtime, transport and the current incarnation's reverse-tunnel lease port. - const nodeRouteRow = workspace.nodeId - ? await readNodeAgentRouteRow(c.env, workspace.nodeId) - : null; - const nodeRuntime = nodeRouteRow?.runtime ?? 'vm'; + // One node read, as before; `transport` routes a build-extension node (self-host tunnel). + const nodeRow = workspace.nodeId + ? await db + .select({ runtime: schema.nodes.runtime, transport: schema.nodes.transport }) + .from(schema.nodes) + .where(eq(schema.nodes.id, workspace.nodeId)) + .get() + : undefined; + const nodeRuntime = nodeRow?.runtime ?? 'vm'; const gatewayRequest = isGatewayAuthorizationRequest(c.req.raw); if (workspaceStatus !== 'running' && workspaceStatus !== 'recovery') { @@ -266,7 +265,6 @@ export async function workspaceSubdomainProxy( ); const containerRequest = new Request(containerUrl.toString(), { - // Never follow a node's redirect; it goes back to the browser as-is (nodeAgentRequestInit). redirect: 'manual', method: c.req.raw.method, headers, @@ -306,6 +304,9 @@ export async function workspaceSubdomainProxy( ); } + const redirectFailure = refuseNodeRedirect(response, targetPort, containerUrl); + if (redirectFailure) return redirectFailure; + if (targetPort !== null) { const responseHeaders = new Headers(response.headers); responseHeaders.delete('set-cookie'); @@ -322,28 +323,8 @@ export async function workspaceSubdomainProxy( // Proxy to the VM agent via its proxied (orange-clouded) backend hostname. // The explicit scriptless *.vm route prevents recursion through this Worker. - // Its DNS record selects legacy public-IP or Cloudflare Tunnel transport. A reverse-tunnel - // node has no DNS record: it is reached on its leased loopback port on this box. - let nodeRoute: NodeAgentRoute; - try { - nodeRoute = nodeAgentRouteFromRow(workspace.nodeId || workspaceId, nodeRouteRow, c.env); - } catch (err) { - if (!(err instanceof NodeAgentRouteError)) throw err; - log.warn('ws_proxy_node_route_unavailable', { workspaceId, nodeId: workspace.nodeId }); - if (portsListRequest) { - return c.json( - workspacePortsReadinessPayload( - 'not_ready', - workspaceStatus, - 'Workspace ports are not ready', - true, - { runtime: 'vm', reason: 'node_route_unavailable' } - ), - 202 - ); - } - return c.json({ error: 'NODE_UNREACHABLE', message: 'Workspace node is not reachable' }, 503); - } + // Its DNS record selects legacy public-IP or Cloudflare Tunnel transport; a node on a + // build-extension transport (self-host reverse tunnel) is routed by `resolveNodeAgentRoute`. const routedNodeId = (workspace.nodeId || workspaceId).toLowerCase(); const backendHostname = `${routedNodeId}.vm.${baseDomain}`; log.info('ws_proxy_route', { @@ -363,12 +344,22 @@ export async function workspaceSubdomainProxy( }, c.env ); - // Both origins come from trusted routing config, never from the request: the fixed loopback - // lease origin for a reverse-tunnel node, the backend hostname for every other transport. - const vmUrl = - nodeRoute.kind === 'reverse-tunnel' - ? new URL(nodeRoute.origin) - : new URL(getNodeBackendBaseUrl(routedNodeId, c.env)); + let nodeRoute: NodeAgentRoute; + try { + nodeRoute = await resolveNodeAgentRoute(c.env, workspace.nodeId || workspaceId, nodeRow); + } catch (err) { + // A tunnel-only node without a current lease: unreachable, never the public hostname. + if (!(err instanceof NodeAgentRouteError)) throw err; + log.warn('ws_proxy_node_unroutable', { + workspaceId, + nodeId: workspace.nodeId, + action: 'rejected', + }); + return c.json({ error: 'NODE_UNREACHABLE', message: 'Node is not reachable' }, 503); + } + const vmUrl = new URL( + nodeRoute.kind === 'container' ? getNodeBackendBaseUrl(routedNodeId, c.env) : nodeRoute.origin + ); vmUrl.pathname = url.pathname; vmUrl.search = url.search; @@ -403,7 +394,7 @@ export async function workspaceSubdomainProxy( headers.delete('x-sam-node-id'); headers.delete('x-sam-workspace-id'); headers.delete('x-forwarded-host'); - // The self-hosted gateway secret authenticates Caddy to the Worker; it never goes to a node. + // The self-host gateway secret authenticates Caddy/frps to the API; it never goes to a node. headers.delete('x-sam-gateway-secret'); headers.set('X-SAM-Node-Id', workspace.nodeId || workspaceId); headers.set('X-SAM-Workspace-Id', workspaceId); @@ -415,19 +406,13 @@ export async function workspaceSubdomainProxy( headers.set('X-Forwarded-Host', hostname); headers.set('X-Forwarded-Proto', 'https'); - // Self-hosted WebSocket gateway: everything above (auth, ownership, status, port token, - // header rewriting) has run unchanged; Caddy proxies the socket to the decided upstream. - if (gatewayRequest) { - return gatewayDecisionResponse(c.req.raw, nodeRoute, { url: vmUrl, headers }, c.env); - } + // Self-hosted WebSocket gateway: same auth and headers above; the box's Caddy carries it. + if (gatewayRequest) return gatewayDecisionResponse(c.req.raw, nodeRoute, { url: vmUrl, headers }); let response: Response; try { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM builds the node URL from its routing metadata; node redirects are never followed response = await fetch(vmUrl.toString(), { - // Never follow a node's redirect, on any transport: the 3xx goes back to the browser - // as-is (nodeAgentRequestInit). On Cloudflare the incoming request's mode was already - // `manual`; a runtime whose incoming requests default to `follow` (celld) would otherwise - // follow a node's redirect into this box's loopback with the proxied headers. redirect: 'manual', method: c.req.raw.method, headers, @@ -464,6 +449,9 @@ export async function workspaceSubdomainProxy( ); } + const redirectFailure = refuseNodeRedirect(response, targetPort, vmUrl); + if (redirectFailure) return redirectFailure; + // 5e: Strip Set-Cookie headers from container responses on port-proxy path. // Prevents a malicious container app from overwriting the sam_port_access cookie. if (targetPort !== null) { @@ -480,3 +468,23 @@ export async function workspaceSubdomainProxy( return response; } + +/** Node control redirects fail; application redirects may pass without the injected SAM JWT. + * This Worker check also protects requests to older, still-running VM/Instant agents. + */ +function refuseNodeRedirect( + response: Response, + targetPort: number | null, + upstream: URL +): Response | null { + // Cache revalidation cannot trigger a follow and must preserve its response headers. + if (response.status === 304 || response.status < 300 || response.status >= 400) return null; + const location = response.headers.get('location') ?? ''; + const token = upstream.searchParams.get('token'); + if (targetPort !== null && !(token && location.includes(token))) return null; + void response.body?.cancel().catch(() => undefined); + return Response.json( + { error: 'NODE_REDIRECT_REFUSED', message: 'Node returned a redirect' }, + { status: 502 } + ); +} diff --git a/apps/api/src/routes/workspaces/_helpers.ts b/apps/api/src/routes/workspaces/_helpers.ts index 1cbed71b77..be3d6628cf 100644 --- a/apps/api/src/routes/workspaces/_helpers.ts +++ b/apps/api/src/routes/workspaces/_helpers.ts @@ -91,22 +91,25 @@ export async function assertWorkspaceCallbackResourceById( return assertWorkspaceAcceptsCallback(env, workspace, workspaceId, callback, allowedStatuses); } +/** Shared projection keeps every callback's lifecycle and incarnation fence identical. */ +export const workspaceCallbackIdentityFields = { + workspaceId: schema.workspaces.id, + userId: schema.workspaces.userId, + projectId: schema.workspaces.projectId, + chatSessionId: schema.workspaces.chatSessionId, + status: schema.workspaces.status, + nodeId: schema.workspaces.nodeId, + nodeStatus: schema.nodes.status, + callbackGeneration: schema.workspaces.callbackGeneration, +}; + export async function loadWorkspaceCallbackIdentity( env: Env, workspaceId: string ): Promise { const db = drizzle(env.DATABASE, { schema }); const rows = await db - .select({ - workspaceId: schema.workspaces.id, - userId: schema.workspaces.userId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, - }) + .select(workspaceCallbackIdentityFields) .from(schema.workspaces) .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) .where(eq(schema.workspaces.id, workspaceId)) diff --git a/apps/api/src/routes/workspaces/agent-credential-attribution.ts b/apps/api/src/routes/workspaces/agent-credential-attribution.ts index a577483dfe..5931f33bda 100644 --- a/apps/api/src/routes/workspaces/agent-credential-attribution.ts +++ b/apps/api/src/routes/workspaces/agent-credential-attribution.ts @@ -29,6 +29,20 @@ type PersistedAgentCredentialAttribution = { credentialGeneration: number; }; +function parsePersistedAttribution( + row: Record | null +): PersistedAgentCredentialAttribution | null { + if ( + !row || + typeof row.id !== 'string' || + typeof row.credentialGeneration !== 'number' || + !Number.isSafeInteger(row.credentialGeneration) || + row.credentialGeneration < 1 + ) + return null; + return { agentSessionId: row.id, credentialGeneration: row.credentialGeneration }; +} + export async function persistAgentCredentialAttribution( env: Env, workspace: WorkspaceCallbackIdentitySnapshot, @@ -44,7 +58,10 @@ export async function persistAgentCredentialAttribution( await assertProviderLimitCredentialPin( env, input.workspaceId, - input.attribution.credentialReference + input.attribution.credentialReference, + workspace, + input.agentType, + input.agentSessionId ); const now = new Date().toISOString(); @@ -76,12 +93,13 @@ export async function persistAgentCredentialAttribution( workspace.userId, input.agentType ) - .first(); + .first(); - if (!update) { + const attribution = parsePersistedAttribution(update); + if (!attribution) { throw errors.forbidden('Agent session does not match workspace callback identity'); } - return update; + return attribution; } const target = await env.DATABASE.prepare( @@ -127,8 +145,8 @@ export async function persistAgentCredentialAttribution( now, target.id ) - .first(); - return update; + .first(); + return parsePersistedAttribution(update); } export function credentialAttributionFromData( diff --git a/apps/api/src/routes/workspaces/local-forward.ts b/apps/api/src/routes/workspaces/local-forward.ts index 098d020c8b..42474cca7c 100644 --- a/apps/api/src/routes/workspaces/local-forward.ts +++ b/apps/api/src/routes/workspaces/local-forward.ts @@ -258,7 +258,10 @@ async function handleLocalForwardProxy(c: Context<{ Bindings: Env }>) { // @ts-expect-error Cloudflare Workers support streaming request bodies. duplex: c.req.raw.body ? 'half' : undefined, }, - getNodeAgentRequestTimeoutMs(c.env) + getNodeAgentRequestTimeoutMs(c.env), + // The local CLI must receive app redirects, but the Worker must never follow + // them with its internal forwarding credential. + { allowApplicationRedirects: true } ); return new Response(response.body, { diff --git a/apps/api/src/routes/workspaces/runtime-agent-key.ts b/apps/api/src/routes/workspaces/runtime-agent-key.ts new file mode 100644 index 0000000000..349c8dd345 --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-agent-key.ts @@ -0,0 +1,411 @@ +import { + AI_PROXY_DEFAULT_MODEL_KV_KEY, + type AIProxyConfig, + DEFAULT_AI_PROXY_ANTHROPIC_MODEL, + DEFAULT_AI_PROXY_MODEL, + DEFAULT_AI_PROXY_OPENAI_MODEL, + getAgentDefinition, + HARNESS_CAPABILITIES, + isValidAgentType, + resolveHarnessDialect, +} from '@simple-agent-manager/shared'; +import { and, eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; +import { Hono } from 'hono'; + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { getCredentialEncryptionKey } from '../../lib/secrets'; +import { errors } from '../../middleware/error'; +import { AgentTypeBodySchema, jsonValidator } from '../../schemas'; +import { resolveSessionProfileCredentialContext } from '../../services/composable-credentials/profile-context'; +import { extractScalewaySecretKey } from '../../services/provider-credentials'; +import { refuseHaltedRunAccount } from '../../services/run-agent-configuration'; +import { + isAiProxyEnabled, + PROXY_ELIGIBLE_AGENTS, + requiresExplicitSamProvider, +} from '../../services/sam-ai-proxy-fallback'; +import { getDecryptedAgentKey, getDecryptedCredentialRecord } from '../credentials'; +import { + assertWorkspaceCallbackIdentityCurrent, + assertWorkspaceCallbackResourceById, + verifyWorkspaceCallbackAuth, +} from './_helpers'; +import { + agentCredentialProviderFallback, + credentialAttributionFromData, + persistAgentCredentialAttribution, + platformProxyAttribution, +} from './agent-credential-attribution'; +import { callbackJsonWithJit } from './runtime-callback-response'; +function getProxyCapability(agentType: string) { + const capability = HARNESS_CAPABILITIES.find((entry) => entry.agentType === agentType); + if (!capability?.proxyRouteSegment || !capability.proxyProviderTag) return null; + return capability; +} + +function buildPassthroughInferenceConfig(input: { + agentType: string; + baseDomain: string; + defaultModel: string; +}) { + const capability = getProxyCapability(input.agentType); + if (!capability) return null; + return { + provider: capability.proxyProviderTag, + baseURL: `https://api.${input.baseDomain}/ai/proxy/{wstoken}/${capability.proxyRouteSegment}`, + model: input.defaultModel, + apiKeySource: 'callback-token' as const, + }; +} + +function buildPlatformInferenceConfig(input: { + agentType: string; + baseDomain: string; + defaultModel: string; +}) { + const capability = getProxyCapability(input.agentType); + if (!capability) return null; + let provider = 'openai-proxy'; + if (capability.proxyProviderTag === 'anthropic-passthrough') provider = 'anthropic-proxy'; + else if (capability.usesOpencodeConfig) provider = 'openai-compatible'; + const routeSegment = capability.proxyRouteSegment === 'anthropic' ? 'anthropic' : 'v1'; + return { + provider, + baseURL: `https://api.${input.baseDomain}/ai/${routeSegment}`, + model: input.defaultModel, + apiKeySource: 'callback-token' as const, + }; +} + +const runtimeRoutes = new Hono<{ Bindings: Env }>(); +runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async (c) => { + const workspaceId = c.req.param('id'); + await verifyWorkspaceCallbackAuth(c, workspaceId); + const body = c.req.valid('json'); + + const db = drizzle(c.env.DATABASE, { schema }); + + const workspace = await assertWorkspaceCallbackResourceById(c.env, workspaceId, 'agent_key'); + + // OpenCode always uses a user-supplied credential (zen/go/custom). It never + // routes through the SAM platform proxy, so it always requires a dedicated key. + const opencodeRequiresDedicatedCredential = body.agentType === 'opencode'; + + const encryptionKey = getCredentialEncryptionKey(c.env); + // The session's profile decides whether a personal profile pin applies; the AI + // proxy and provider-limit admission resolve the same context. + const profile = await resolveSessionProfileCredentialContext(db, { + workspaceId, + agentSessionId: body.agentSessionId, + }); + let credentialData = await getDecryptedAgentKey( + db, + workspace.userId, + body.agentType, + encryptionKey, + workspace.projectId, + profile + ); + let credentialProviderMode = 'direct'; + + const persistAttribution = ( + attribution: Parameters[2]['attribution'] + ) => + persistAgentCredentialAttribution(c.env, workspace, { + workspaceId, + agentSessionId: body.agentSessionId, + agentType: body.agentType, + attribution, + }); + const returnCredential = async ( + data: NonNullable, + providerMode: string, + inferenceConfig?: NonNullable> + ) => { + const persistedAttribution = await persistAttribution( + credentialAttributionFromData(data, body.agentType, providerMode) + ); + return callbackJsonWithJit( + c, + workspace, + 'agent_key', + { + apiKey: inferenceConfig ? '__sam_proxy__' : data.credential, + credentialKind: data.credentialKind, + credentialSource: data.credentialSource, + credentialReference: data.credentialReference, + credentialProvider: + data.credentialProvider ?? + (inferenceConfig ? data.providerDialect : undefined) ?? + agentCredentialProviderFallback(body.agentType), + providerMode, + credentialGeneration: persistedAttribution?.credentialGeneration, + ...(inferenceConfig ? { inferenceConfig } : {}), + }, + persistedAttribution?.agentSessionId + ); + }; + const trackTaskCredentialSource = async ( + source: NonNullable['credentialSource'] + ) => { + const [task] = await db + .select({ id: schema.tasks.id }) + .from(schema.tasks) + .where(eq(schema.tasks.workspaceId, workspaceId)) + .limit(1); + if (task) { + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); + await db + .update(schema.tasks) + .set({ agentCredentialSource: source }) + .where(eq(schema.tasks.id, task.id)); + } + }; + + // An account chosen for this run that can no longer be used (paused, removed) must stop + // the run here. Without this, "no credential" would continue to the platform proxy or a + // fallback below and run the chat on an account nobody chose for it. + if (!credentialData && profile?.runConfigurationId) { + await refuseHaltedRunAccount(db, { + workspaceId, + userId: workspace.userId, + projectId: workspace.projectId, + agentType: body.agentType, + encryptionKey, + profile, + }); + } + + // SECURITY: Never return raw platform-managed credentials to tenant workspaces. + // Platform credentials are control-plane secrets and must only be used via + // SAM-mediated proxy flows (callback-token auth), not injected into tenant + // containers as env vars or auth files. + if (credentialData?.credentialSource === 'platform') { + credentialData = null; + } + + // Cloud provider credential fallback: if no dedicated agent key, check if the agent + // definition specifies a cloud provider whose credential can be used instead. + const agentDef = isValidAgentType(body.agentType) + ? getAgentDefinition(body.agentType) + : undefined; + const fallbackCloudProvider = agentDef?.fallbackCloudProvider; + if (!credentialData && fallbackCloudProvider) { + const fallbackCredential = await getDecryptedCredentialRecord( + db, + workspace.userId, + fallbackCloudProvider, + encryptionKey + ); + if (fallbackCredential) { + const secretKey = extractScalewaySecretKey(fallbackCredential.credential); + if (secretKey) { + credentialData = { + credential: secretKey, + credentialKind: 'api-key', + credentialSource: 'user', + credentialScope: 'user', + credentialReference: fallbackCredential.credentialReference, + credentialProvider: fallbackCredential.credentialProvider, + }; + credentialProviderMode = 'fallback-cloud-provider'; + } else { + log.warn('agent_key.scaleway_credential_missing_secret_key', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + }); + } + } + } + + if (credentialData && !credentialData.baseUrl && opencodeRequiresDedicatedCredential) { + return returnCredential(credentialData, credentialProviderMode); + } + + if (!credentialData && opencodeRequiresDedicatedCredential) { + log.info('agent_key.opencode_byo_provider_missing_credential', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + }); + throw errors.notFound('Agent credential'); + } + + // AI proxy: when enabled and agent is eligible, return proxy config when the + // credential can be forwarded to the upstream provider. + // Two modes: + // - Claude/Codex with no user credential + providerMode='sam' → platform proxy (callback-token auth) + // - User has upstream-compatible credential → passthrough proxy (user credential + // forwarded via auth headers, wstoken in URL path for analytics/rate-limiting) + // Note: platform proxy fallback requires explicit provider selection. + // Without it, users with no credential get a 404 (agent not configured). + if (PROXY_ELIGIBLE_AGENTS.has(body.agentType) && (await isAiProxyEnabled(c.env))) { + const baseDomain = c.env.BASE_DOMAIN; + const isClaudeCode = body.agentType === 'claude-code'; + const isCodex = body.agentType === 'openai-codex'; + let explicitProviderMode: string | null | undefined; + const getExplicitProviderMode = async (): Promise => { + if (explicitProviderMode !== undefined) return explicitProviderMode; + const settingsRows = await db + .select({ providerMode: schema.agentSettings.providerMode }) + .from(schema.agentSettings) + .where( + and( + eq(schema.agentSettings.userId, workspace.userId), + eq(schema.agentSettings.agentType, body.agentType) + ) + ) + .limit(1); + explicitProviderMode = settingsRows[0]?.providerMode ?? null; + return explicitProviderMode; + }; + + // Resolve default model: KV (admin-set) > env var > shared constant + let defaultModel: string; + if (isClaudeCode) { + defaultModel = c.env.AI_PROXY_DEFAULT_ANTHROPIC_MODEL ?? DEFAULT_AI_PROXY_ANTHROPIC_MODEL; + } else if (isCodex) { + defaultModel = c.env.AI_PROXY_DEFAULT_OPENAI_MODEL ?? DEFAULT_AI_PROXY_OPENAI_MODEL; + } else { + defaultModel = c.env.AI_PROXY_DEFAULT_MODEL ?? DEFAULT_AI_PROXY_MODEL; + try { + const kvConfig = await c.env.KV.get(AI_PROXY_DEFAULT_MODEL_KV_KEY); + if (kvConfig) { + const parsed: AIProxyConfig = JSON.parse(kvConfig); + if (parsed.defaultModel) defaultModel = parsed.defaultModel; + } + } catch { + /* KV unavailable or corrupt data — use env/default */ + } + } + + // Claude Code/Codex explicit SAM mode must route through the SAM proxy, + // not through legacy platform agent credentials as user-style passthrough. + if ((isClaudeCode || isCodex) && credentialData?.credentialSource === 'platform') { + credentialData = null; + } + + if ( + credentialData && + credentialData.baseUrl && + credentialData.providerDialect && + resolveHarnessDialect(body.agentType, credentialData.providerDialect) && + !((isClaudeCode || isCodex) && credentialData.credentialKind === 'oauth-token') + ) { + // User has their own credential — use passthrough proxy routes. + // URL-path auth: wstoken embedded in URL, user credential in auth headers. + const inferenceConfig = buildPassthroughInferenceConfig({ + agentType: body.agentType, + baseDomain, + defaultModel, + }); + if (!inferenceConfig) { + throw errors.notFound('Agent credential'); + } + + log.info('agent_key.ai_proxy_passthrough', { + workspaceId, + userId: workspace.userId, + proxyBaseUrl: inferenceConfig.baseURL, + agentType: body.agentType, + }); + + await trackTaskCredentialSource(credentialData.credentialSource); + + return returnCredential(credentialData, 'proxy-passthrough', inferenceConfig); + } + + if (credentialData?.baseUrl) { + log.warn('agent_key.ai_proxy_incompatible_passthrough_credential', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + providerDialect: credentialData.providerDialect ?? null, + }); + throw errors.notFound('Agent credential'); + } + + if (credentialData) { + return returnCredential(credentialData, credentialProviderMode); + } + + // Claude Code and Codex require an explicit SAM provider selection before + // using platform proxy. OpenCode never reaches this block — it always + // requires a dedicated user credential and returns/throws above. + if (requiresExplicitSamProvider(body.agentType)) { + const providerMode = await getExplicitProviderMode(); + + if (providerMode !== 'sam') { + log.info('agent_key.no_credential_no_sam_provider', { + workspaceId, + userId: workspace.userId, + agentType: body.agentType, + providerMode, + }); + throw errors.notFound('Agent credential'); + } + } + + // Activate platform proxy. + // Auth via callback token in headers. + const inferenceConfig = buildPlatformInferenceConfig({ + agentType: body.agentType, + baseDomain, + defaultModel, + }); + if (!inferenceConfig) { + throw errors.notFound('Agent credential'); + } + + log.info('agent_key.ai_proxy_sam_provider', { + workspaceId, + userId: workspace.userId, + proxyBaseUrl: inferenceConfig.baseURL, + agentType: body.agentType, + }); + + await trackTaskCredentialSource('platform'); + + const platformAttribution = platformProxyAttribution(body.agentType); + const persistedAttribution = await persistAttribution(platformAttribution); + + return callbackJsonWithJit( + c, + workspace, + 'agent_key', + { + apiKey: '__platform_proxy__', + credentialKind: 'api-key' as const, + credentialSource: 'platform' as const, + credentialReference: platformAttribution.credentialReference, + credentialProvider: platformAttribution.credentialProvider, + providerMode: platformAttribution.providerMode, + credentialGeneration: persistedAttribution?.credentialGeneration, + inferenceConfig, + }, + persistedAttribution?.agentSessionId + ); + } + + if (!credentialData || credentialData.baseUrl) { + throw errors.notFound('Agent credential'); + } + + // Track credential source on associated task if applicable + if (credentialData.credentialSource === 'platform') { + await trackTaskCredentialSource('platform'); + } + + return returnCredential(credentialData, credentialProviderMode); +}); + +/** + * POST /:id/agent-settings — VM agent callback to fetch user's agent settings. + * Uses workspace callback auth (same as agent-key). + */ + +export { runtimeRoutes as agentKeyRoutes }; diff --git a/apps/api/src/routes/workspaces/runtime-callback-response.ts b/apps/api/src/routes/workspaces/runtime-callback-response.ts new file mode 100644 index 0000000000..157bfc6dc8 --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-callback-response.ts @@ -0,0 +1,38 @@ +import { type Context } from 'hono'; + +import type { Env } from '../../env'; +import { assertProviderLimitCredentialPin } from '../../services/provider-limit-credential-pin'; +import { type WorkspaceDeletionCallbackKind } from '../../services/workspace-deletion-callback-signal'; +import { + assertWorkspaceCallbackIdentityCurrent, + type WorkspaceCallbackIdentitySnapshot, +} from './_helpers'; + +type RuntimeContext = Context<{ Bindings: Env }>; +export async function callbackJsonWithJit>( + c: RuntimeContext, + expected: WorkspaceCallbackIdentitySnapshot, + callback: WorkspaceDeletionCallbackKind, + body: T, + agentSessionId?: string | null +) { + await assertWorkspaceCallbackIdentityCurrent(c.env, expected, callback); + if ( + callback === 'agent_key' && + body.credentialSource !== 'platform' && + typeof body.credentialReference === 'string' + ) + await assertProviderLimitCredentialPin( + c.env, + expected.workspaceId, + body.credentialReference, + expected, + undefined, + agentSessionId, + { + credentialGeneration: + typeof body.credentialGeneration === 'number' ? body.credentialGeneration : undefined, + } + ); + return c.json(body); +} diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts new file mode 100644 index 0000000000..3c371337a4 --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -0,0 +1,477 @@ +import { eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; +import { Hono } from 'hono'; + +import * as schema from '../../db/schema'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { errors } from '../../middleware/error'; +import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; +import { + GitHubCliPolicyError, + resolveWorkspaceGitHubTokenOptions, +} from '../../services/github-cli-policy'; +import { getExternalInstallationId } from '../../services/github-installation-ids'; +import { backfillProjectGithubRepoId } from '../../services/github-repo-id-backfill'; +import { getGitHubUserAccessTokenForOwner } from '../../services/github-user-access-token'; +import { + getProjectGitLabRepository, + requireGitLabUserAccessTokenResultForOwner, + verifyGitLabProjectAccess, +} from '../../services/gitlab'; +import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; +import { isLocalHostedGitActive } from '../../services/hosted-git/local-backend'; +import { mintHostedGitToken } from '../../services/hosted-git/tokens'; +import { boundArtifactsRepositoryHost } from '../../services/workspace-git-source'; +import { assertRepositoryAccess } from '../projects/_helpers'; +import { + assertWorkspaceAcceptsCallback, + assertWorkspaceCallbackIdentityCurrent, + verifyWorkspaceCallbackAuth, + workspaceCallbackIdentityFields, +} from './_helpers'; +import { callbackJsonWithJit } from './runtime-callback-response'; +const runtimeRoutes = new Hono<{ Bindings: Env }>(); +async function verifyWorkspaceGitHubOwnerAccess(input: { + env: Env; + workspaceId: string; + projectId: string | null; + userId: string; + repository: string; + externalInstallationId: string; + githubRepoId: number | null; +}): Promise { + const accessToken = await getGitHubUserAccessTokenForOwner( + input.env, + input.userId, + 'workspace-git-token' + ); + if (!accessToken) { + log.warn('workspace_git_token_user_access_missing', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + action: 'rejected', + }); + throw errors.forbidden('GitHub user token unavailable'); + } + + // Every git and gh credential exchange lands here, so pass env to use the + // pagination hint (GITHUB_REPO_ACCESS_CACHE_TTL_SECONDS). Every exchange + // still verifies current user access against GitHub; hints never grant access. + const verifiedRepo = await assertRepositoryAccess( + accessToken, + input.externalInstallationId, + input.repository, + input.userId, + 'project-access', + input.env + ); + + if (input.githubRepoId !== null && verifiedRepo.id !== input.githubRepoId) { + log.warn('workspace_git_token_repo_id_drift', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + expectedRepoId: input.githubRepoId, + verifiedRepoId: verifiedRepo.id, + action: 'rejected', + }); + throw errors.forbidden('GitHub repository access has changed; repository ID no longer matches'); + } + + return verifiedRepo.id; +} + +/** + * Resolve numeric repository IDs for a project's additional Repository Access + * entries, re-verifying user∩app access at the token-mint boundary. Stored rows + * whose access has been revoked (or whose installation no longer exposes them) + * are dropped from the scope — an unselected/inaccessible repo simply never makes + * it into the minted token's `repository_ids`, so it fails clearly downstream. + * Failure to fetch the accessible set returns the empty set rather than throwing, + * so the primary-repo token still mints (additional repos degrade, never break + * the primary clone). + */ +async function resolveAdditionalRepositoryIds(input: { + env: Env; + db: ReturnType>; + workspaceId: string; + projectId: string; + userId: string; + externalInstallationId: string; +}): Promise { + const rows = await input.db + .select({ + repository: schema.projectGithubRepositories.repository, + githubRepoId: schema.projectGithubRepositories.githubRepoId, + }) + .from(schema.projectGithubRepositories) + .where(eq(schema.projectGithubRepositories.projectId, input.projectId)); + if (rows.length === 0) { + return []; + } + + const accessToken = await getGitHubUserAccessTokenForOwner( + input.env, + input.userId, + 'workspace-git-token' + ); + if (!accessToken) { + log.warn('workspace_git_token_additional_repos_user_access_missing', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + action: 'additional_repos_skipped', + }); + return []; + } + + let accessibleById: Map; + try { + const repositories = await getUserInstallationRepositories( + accessToken, + input.externalInstallationId, + { + flow: 'project-access', + userId: input.userId, + installationId: input.externalInstallationId, + } + ); + accessibleById = new Map(repositories.map((r) => [r.fullName.toLowerCase(), r.id])); + } catch (err) { + log.warn('workspace_git_token_additional_repos_unavailable', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + error: err instanceof Error ? err.message : String(err), + action: 'additional_repos_skipped', + }); + return []; + } + + const ids: number[] = []; + for (const row of rows) { + const accessibleId = accessibleById.get(row.repository.toLowerCase()); + if (accessibleId === undefined) { + log.warn('workspace_git_token_additional_repo_access_revoked', { + workspaceId: input.workspaceId, + projectId: input.projectId, + userId: input.userId, + repository: row.repository, + action: 'excluded_from_scope', + }); + continue; + } + // Prefer the live, rename-stable id from the accessible set. Stored ids can + // drift if the repo was deleted/recreated; the live id is authoritative. + ids.push(accessibleId); + } + return ids; +} + +runtimeRoutes.post('/:id/git-token', async (c) => { + const workspaceId = c.req.param('id'); + await verifyWorkspaceCallbackAuth(c, workspaceId); + + const db = drizzle(c.env.DATABASE, { schema }); + + // Look up workspace → project to determine repo provider + const workspaceRows = await db + .select({ + ...workspaceCallbackIdentityFields, + installationId: schema.workspaces.installationId, + }) + .from(schema.workspaces) + .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) + .where(eq(schema.workspaces.id, workspaceId)) + .limit(1); + + const workspace = await assertWorkspaceAcceptsCallback( + c.env, + workspaceRows[0], + workspaceId, + 'git_token' + ); + + // Look up the project to check repoProvider + let repoProvider = 'github'; + let artifactsRepoId: string | null = null; + let githubRepoId: number | null = null; + let repositoryName: string | null = null; + if (workspace.projectId) { + const projectRows = await db + .select({ + repoProvider: schema.projects.repoProvider, + artifactsRepoId: schema.projects.artifactsRepoId, + githubRepoId: schema.projects.githubRepoId, + repository: schema.projects.repository, + }) + .from(schema.projects) + .where(eq(schema.projects.id, workspace.projectId)) + .limit(1); + + const project = projectRows[0]; + if (project) { + repoProvider = project.repoProvider || 'github'; + artifactsRepoId = project.artifactsRepoId; + githubRepoId = project.githubRepoId; + repositoryName = project.repository; + } + } + + if (repoProvider === 'artifacts') { + // ─── Artifacts token ────────────────────────────────────────────── + if (c.env.ARTIFACTS_ENABLED !== 'true') { + throw errors.forbidden('Artifacts provider is not enabled'); + } + const artifacts = resolveArtifactsBackend(c.env); + if (!artifacts || !artifactsRepoId) { + throw errors.internal('Artifacts binding or repo ID missing'); + } + + // Clamp the token TTL to a sane range: a negative/zero/NaN or excessively + // large configured value must not mint a token that never expires (or expires + // instantly). Default 1h; hard cap 24h. + const rawTtl = Number.parseInt(c.env.ARTIFACTS_TOKEN_TTL_SECONDS || '', 10); + const ttl = Number.isFinite(rawTtl) && rawTtl > 0 && rawTtl <= 86400 ? rawTtl : 3600; + // Use requested scope or default to 'write' (agents need push access) + const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); + const repo = await artifacts.get(artifactsRepoId); + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + // SAM-hosted repositories (self-host): the token is bound to this workspace, so the git + // server refuses it once the workspace stops (services/hosted-git/http.ts). + const localHostedGit = isLocalHostedGitActive(c.env); + const tokenResult = localHostedGit + ? await mintHostedGitToken(c.env, { + repo: artifactsRepoId, + scope: requestedScope, + ttlSeconds: ttl, + workspaceId: workspace.workspaceId, + callbackGeneration: workspace.callbackGeneration ?? null, + userId: workspace.userId, + }).then((minted) => ({ + plaintext: minted.token, + expiresAt: minted.expiresAt, + expires_at: undefined, + })) + : await repo.createToken(requestedScope, ttl); + + // Strip ?expires= suffix from token for git credential use + const tokenSecret = tokenResult.plaintext.split('?expires=')[0] || tokenResult.plaintext; + + // Prefer the stored project.repository as the clone URL: it is `created.remote` + // captured at project creation and is exactly what the VM agent cloned, so its + // host is guaranteed to match what git requests from the credential helper. The + // Artifacts binding's `get().remote` has been observed to come back empty on + // staging (unlike `create().remote`); when that happens an empty cloneUrl makes + // the VM agent default the credential host to github.com, which then fails to + // match the real Artifacts host and returns no credential (git fetch/push break). + const cloneUrl = repositoryName || repo.remote || ''; + if (!repo.remote) { + log.warn('workspace_git_token.artifacts_remote_empty', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + artifactsRepoId, + usedStoredRepository: !!repositoryName, + action: 'fell_back_to_stored_repository', + }); + } + if (!cloneUrl) { + log.error('workspace_git_token.artifacts_clone_url_missing', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + artifactsRepoId, + action: 'clone_url_empty', + }); + } + + return callbackJsonWithJit(c, workspace, 'git_token', { + token: tokenSecret, + expiresAt: tokenResult.expiresAt ?? tokenResult.expires_at, + cloneUrl, + // The VM agent's credential helper answers with username "x" only for Cloudflare Artifacts + // hosts it knows by name. For a bound self-hosted host, name it here so a refresh presents + // the same username the clone used. Cloudflare responses are unchanged. + ...(boundArtifactsRepositoryHost(cloneUrl) ? { username: 'x' } : {}), + }); + } + + if (repoProvider === 'gitlab') { + if (!workspace.projectId) { + throw errors.forbidden('GitLab workspace has no project'); + } + const metadata = await getProjectGitLabRepository(db, workspace.projectId); + if (!metadata) { + throw errors.forbidden('GitLab repository metadata is missing'); + } + if (metadata.userId !== workspace.userId) { + // The stored GitLab repo binding belongs to a different user than the + // workspace owner — vending the owner's OAuth token against another + // user's binding would cross a tenant boundary. Fail closed. + log.error('workspace_git_token.gitlab_user_mismatch', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + workspaceUserId: workspace.userId, + metadataUserId: metadata.userId, + action: 'rejected', + }); + throw errors.forbidden('GitLab repository is not linked for this workspace owner'); + } + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + const tokenResult = await requireGitLabUserAccessTokenResultForOwner( + c.env, + workspace.userId, + 'workspace-git-token' + ); + const verified = await verifyGitLabProjectAccess( + c.env, + tokenResult.accessToken, + metadata.gitlabProjectId + ); + if ( + verified.host !== metadata.host || + verified.gitlabProjectId !== metadata.gitlabProjectId || + verified.pathWithNamespace !== metadata.pathWithNamespace + ) { + throw errors.forbidden('GitLab repository access has changed; repository no longer matches'); + } + + return callbackJsonWithJit(c, workspace, 'git_token', { + provider: 'gitlab', + token: tokenResult.accessToken, + expiresAt: tokenResult.accessTokenExpiresAt, + cloneUrl: metadata.httpUrlToRepo, + host: metadata.host, + username: 'oauth2', + repositoryPath: metadata.pathWithNamespace, + }); + } + + // ─── GitHub token (existing flow) ────────────────────────────────── + if (!workspace.installationId) { + throw errors.notFound('Workspace has no GitHub installation'); + } + // Scope the token to a single repo. Prefer the verified numeric repo ID; fall + // back to the repository name for legacy projects created before github_repo_id + // was backfilled (PR #1236). Both paths scope to exactly one repository, so the + // personal-installation leak fix is preserved. + const repoShortName = + repositoryName && repositoryName.includes('/') + ? (repositoryName.split('/').pop() ?? null) + : repositoryName; + if (!githubRepoId && !repoShortName) { + throw errors.forbidden('GitHub repository is not verified for this workspace'); + } + + const installations = await db + .select({ + installationId: schema.githubInstallations.installationId, + externalInstallationId: schema.githubInstallations.externalInstallationId, + userId: schema.githubInstallations.userId, + }) + .from(schema.githubInstallations) + .where(eq(schema.githubInstallations.id, workspace.installationId)) + .limit(1); + + const installation = installations[0]; + if (!installation) { + log.warn('workspace_git_token_installation_owner_mismatch', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + installationRowId: workspace.installationId, + expectedUserId: workspace.userId, + action: 'rejected', + }); + throw errors.notFound('GitHub installation'); + } + if (installation.userId !== workspace.userId) { + log.info('workspace_git_token_project_installation_shared', { + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + installationRowId: workspace.installationId, + workspaceUserId: workspace.userId, + installationOwnerUserId: installation.userId, + action: 'allowed_after_user_access_verification', + }); + } + + if (!repositoryName) { + throw errors.forbidden('GitHub repository is not verified for this workspace'); + } + + const verifiedRepoId = await verifyWorkspaceGitHubOwnerAccess({ + env: c.env, + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + userId: workspace.userId, + repository: repositoryName, + externalInstallationId: getExternalInstallationId(installation), + githubRepoId, + }); + + // Lazy self-heal: legacy projects created before the numeric repo id was + // captured have github_repo_id = null. Fetch + persist it now, BEFORE policy + // resolution, so custom GitHub CLI policies (which require the numeric id) work + // and scoping uses the rename-stable repositoryIds path. On any failure we fall + // through to the name-based fallback below (no regression). + if (!githubRepoId && repositoryName && workspace.projectId) { + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + const backfill = await backfillProjectGithubRepoId(db, c.env, { + projectId: workspace.projectId, + repository: repositoryName, + externalInstallationId: getExternalInstallationId(installation), + }); + if (backfill.githubRepoId) { + githubRepoId = backfill.githubRepoId; + } + } + githubRepoId ??= verifiedRepoId; + + let tokenOptions = null; + try { + tokenOptions = await resolveWorkspaceGitHubTokenOptions(db, { + workspaceId: workspace.workspaceId, + userId: workspace.userId, + githubRepoId, + }); + } catch (err) { + if (err instanceof GitHubCliPolicyError) { + throw errors.forbidden('GitHub CLI policy prevents token minting'); + } + throw err; + } + // Additional Repository Access: same-installation repos selected in Project + // Settings. Re-verified at this boundary; revoked/inaccessible entries are + // dropped from the scope. Primary repo is always included implicitly. + const additionalRepoIds = + githubRepoId && workspace.projectId + ? await resolveAdditionalRepositoryIds({ + env: c.env, + db, + workspaceId: workspace.workspaceId, + projectId: workspace.projectId, + userId: workspace.userId, + externalInstallationId: getExternalInstallationId(installation), + }) + : []; + + const scopedTokenOptions = { + ...tokenOptions, + ...(githubRepoId + ? { repositoryIds: [githubRepoId, ...additionalRepoIds.filter((id) => id !== githubRepoId)] } + : { repositories: [repoShortName as string] }), + }; + await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); + const token = await getInstallationToken( + getExternalInstallationId(installation), + c.env, + scopedTokenOptions + ); + return callbackJsonWithJit(c, workspace, 'git_token', { + token: token.token, + expiresAt: token.expiresAt, + }); +}); + +export { runtimeRoutes as gitTokenRoutes }; diff --git a/apps/api/src/routes/workspaces/runtime-message-helpers.ts b/apps/api/src/routes/workspaces/runtime-message-helpers.ts new file mode 100644 index 0000000000..2bb5daaeb5 --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-message-helpers.ts @@ -0,0 +1,448 @@ +import { type Context } from 'hono'; +import * as v from 'valibot'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { parsePositiveInt } from '../../lib/route-helpers'; +import { errors } from '../../middleware/error'; +import { formatIssues, MessageBatchSchema } from '../../schemas'; +import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; +import { persistError } from '../../services/observability'; +import { + loadWorkspaceCallbackIdentity, + safeParseJson, + type WorkspaceCallbackIdentitySnapshot, +} from './_helpers'; + +type RuntimeContext = Context<{ Bindings: Env }>; +type MessageBatchBody = v.InferOutput; +export const DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES = 256 * 1024; +export const DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES = 102400; +export const ACTIVE_MESSAGE_WORKSPACE_STATUSES = new Set(['creating', 'running', 'recovery']); +export const VALID_MESSAGE_ROLES = new Set([ + 'user', + 'assistant', + 'system', + 'tool', + 'thinking', + 'plan', +]); + +export type MessageWorkspace = WorkspaceCallbackIdentitySnapshot & { + projectId: string | null; + chatSessionId: string | null; +}; + +export type MessageBatchPersistenceRouteResult = { + persisted: number; + duplicates: number; + limitReached?: boolean; + maxMessages?: number; + remainingCapacity?: number; +}; + +export type MessageRouteContext = { + workspaceId: string; + projectId: string; + sessionId: string; + messageCount: number; +}; + +export function waitUntilIfAvailable( + c: { executionCtx: { waitUntil(promise: Promise): void } }, + promise: Promise | void +): void { + if (!promise) return; + try { + c.executionCtx.waitUntil(promise); + } catch (err) { + if (!(err instanceof Error) || !err.message.includes('no ExecutionContext')) { + throw err; + } + } +} + +export async function readRequestBodyWithLimit( + request: Request, + maxBytes: number +): Promise { + const contentLengthHeader = request.headers.get('content-length'); + if (contentLengthHeader) { + const contentLength = Number.parseInt(contentLengthHeader, 10); + if (!Number.isFinite(contentLength) || contentLength < 0) { + throw errors.badRequest('Invalid Content-Length header'); + } + if (contentLength > maxBytes) { + throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); + } + } + + if (!request.body) { + return ''; + } + + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let totalBytes = 0; + let done = false; + + try { + while (!done) { + const read = await reader.read(); + done = read.done; + if (done) continue; + const { value } = read; + totalBytes += value.byteLength; + if (totalBytes > maxBytes) { + await reader.cancel(); + throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + + const body = new Uint8Array(totalBytes); + let offset = 0; + for (const chunk of chunks) { + body.set(chunk, offset); + offset += chunk.byteLength; + } + return new TextDecoder().decode(body); +} + +export async function parseMessageBatchRequest(c: RuntimeContext): Promise { + const maxPayloadBytes = parsePositiveInt( + c.env.MAX_MESSAGES_PAYLOAD_BYTES as string, + DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES + ); + const rawBody = await readRequestBodyWithLimit(c.req.raw, maxPayloadBytes); + + let parsed: unknown; + try { + parsed = JSON.parse(rawBody); + } catch { + throw errors.badRequest('Invalid JSON in request body'); + } + + const result = v.safeParse(MessageBatchSchema, parsed); + if (!result.success) { + throw errors.badRequest(formatIssues(result.issues)); + } + return result.output; +} + +export function resolveMaxMessageBytes(env: Env): number { + return env.MESSAGE_SIZE_THRESHOLD + ? Number.parseInt(env.MESSAGE_SIZE_THRESHOLD, 10) + : DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES; +} + +export function validateMessageEntry( + msg: MessageBatchBody['messages'][number], + maxMessageBytes: number +): void { + if (!msg.messageId) { + throw errors.badRequest('Each message must have a messageId string'); + } + if (!msg.sessionId) { + throw errors.badRequest('Each message must have a sessionId string'); + } + if (!msg.role || !VALID_MESSAGE_ROLES.has(msg.role)) { + throw errors.badRequest( + `Invalid role "${msg.role}". Must be one of: user, assistant, system, tool, thinking, plan` + ); + } + if (!msg.content) { + throw errors.badRequest('Each message must have non-empty content'); + } + if (msg.content.length > maxMessageBytes) { + throw errors.badRequest(`Individual message content exceeds ${maxMessageBytes} byte limit`); + } + if (!msg.timestamp) { + throw errors.badRequest('Each message must have a timestamp string'); + } +} + +export function validateMessageBatch(env: Env, body: MessageBatchBody): string { + if (body.messages.length === 0) { + throw errors.badRequest('messages array must not be empty'); + } + const maxMessagesPerBatch = parsePositiveInt(env.MAX_MESSAGES_PER_BATCH, 100); + if (body.messages.length > maxMessagesPerBatch) { + throw errors.badRequest(`Maximum ${maxMessagesPerBatch} messages per batch`); + } + + const firstMessage = body.messages[0]; + if (!firstMessage) { + throw errors.badRequest('messages array must not be empty'); + } + const maxMessageBytes = resolveMaxMessageBytes(env); + const sessionId = firstMessage.sessionId; + for (const msg of body.messages) { + validateMessageEntry(msg, maxMessageBytes); + if (msg.sessionId !== sessionId) { + throw errors.badRequest('All messages in a batch must target the same sessionId'); + } + } + return sessionId; +} + +export function loadMessageWorkspace( + env: Env, + workspaceId: string +): Promise { + return loadWorkspaceCallbackIdentity(env, workspaceId); +} + +export function terminalMessagePersistenceResponse( + c: RuntimeContext, + context: Omit & { projectId: string | null }, + status: string, + reason: string +): Response { + const logContext = { + ...context, + status, + reason, + action: 'dropped_terminal_resource', + }; + log.info('message_persistence.inactive_workspace', logContext); + return c.body(null, 204); +} + +export function maybeTerminalMessageWorkspaceResponse( + c: RuntimeContext, + workspace: MessageWorkspace | null, + workspaceId: string, + sessionId: string, + messageCount: number +): Response | null { + const context = { + workspaceId, + projectId: workspace?.projectId ?? null, + sessionId, + messageCount, + }; + if (!workspace) { + return terminalMessagePersistenceResponse(c, context, 'missing', 'workspace_missing'); + } + if (!ACTIVE_MESSAGE_WORKSPACE_STATUSES.has(workspace.status)) { + return terminalMessagePersistenceResponse(c, context, workspace.status, 'workspace_inactive'); + } + if ( + !workspace.nodeId || + !workspace.nodeStatus || + nodeStatusTerminatesCallbacks(workspace.nodeStatus) + ) { + return terminalMessagePersistenceResponse( + c, + context, + workspace.nodeStatus ?? 'missing', + 'workspace_node_terminal' + ); + } + return null; +} + +export function rejectMessageSessionMismatch( + c: RuntimeContext, + context: MessageRouteContext, + expectedSessionId: string +): never { + const logContext = { + ...context, + expectedSessionId, + receivedSessionId: context.sessionId, + action: 'rejected_batch', + }; + log.error('message_routing.session_mismatch', logContext); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: `Message routing mismatch: workspace ${context.workspaceId} linked to session ${expectedSessionId}, but messages target ${context.sessionId}`, + context: logContext, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + throw errors.badRequest( + `Session mismatch: workspace is linked to session ${expectedSessionId}, ` + + `but messages target session ${context.sessionId}` + ); +} + +export function rejectWorkspaceWithoutChatSession( + c: RuntimeContext, + context: MessageRouteContext +): never { + const logContext = { + ...context, + providedSessionId: context.sessionId, + action: 'rejected_no_session_link', + }; + log.warn('message_routing.no_chat_session_linked', logContext); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'warn', + message: `Rejecting messages for workspace ${context.workspaceId}: no chatSessionId linked yet`, + context: logContext, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + throw errors.conflict( + 'Workspace has no linked chat session yet — messages cannot be routed safely' + ); +} + +export function assertMessageWorkspaceAcceptsBatch( + c: RuntimeContext, + workspace: MessageWorkspace | null, + workspaceId: string, + sessionId: string, + messageCount: number +): asserts workspace is MessageWorkspace & { projectId: string; chatSessionId: string } { + if (!workspace) { + throw errors.notFound('Workspace'); + } + if (!workspace.projectId) { + throw errors.badRequest('Workspace is not linked to a project'); + } + + const context: MessageRouteContext = { + workspaceId, + projectId: workspace.projectId, + sessionId, + messageCount, + }; + if (workspace.chatSessionId && workspace.chatSessionId !== sessionId) { + rejectMessageSessionMismatch(c, context, workspace.chatSessionId); + } + if (!workspace.chatSessionId) { + rejectWorkspaceWithoutChatSession(c, context); + } +} + +export function toProjectDataMessages(body: MessageBatchBody) { + return body.messages.map((m) => ({ + messageId: m.messageId, + role: m.role, + content: m.content, + toolMetadata: m.toolMetadata ? safeParseJson(m.toolMetadata) : null, + timestamp: m.timestamp, + sequence: m.sequence, + origin: m.origin ?? null, + })); +} + +export function sessionLimitReachedResponse( + c: RuntimeContext, + context: MessageRouteContext +): Response { + log.error('message_persistence.session_message_limit_exceeded', { + ...context, + action: 'rejected_session_message_limit', + }); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: `Session ${context.sessionId} has reached the message limit`, + context: { ...context, action: 'rejected_session_message_limit' }, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + return c.json( + { + error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', + message: 'Session message limit reached; no additional messages can be persisted', + }, + 409 + ); +} + +export function handleMessagePersistenceError( + c: RuntimeContext, + context: MessageRouteContext, + err: unknown +): Response { + const message = err instanceof Error ? err.message : 'Failed to persist messages'; + if (message.includes('SESSION_MESSAGE_LIMIT_EXCEEDED') || message.includes('message limit')) { + return sessionLimitReachedResponse(c, context); + } + if (message.includes('not found') || message.includes('is stopped')) { + log.info('message_persistence.dropped_terminal_do_response', { + ...context, + error: message, + action: 'dropped_terminal_resource', + }); + return c.body(null, 204); + } + log.error('message_persistence.do_error_transient', { + ...context, + error: message, + action: 'rejected_transient', + }); + return c.json( + { error: 'SERVICE_UNAVAILABLE', message: 'Message persistence temporarily unavailable' }, + 503 + ); +} + +export function partialSessionLimitResponse( + c: RuntimeContext, + context: MessageRouteContext, + result: MessageBatchPersistenceRouteResult +): Response { + const logContext = { + ...context, + persisted: result.persisted, + duplicates: result.duplicates, + maxMessages: result.maxMessages, + remainingCapacity: result.remainingCapacity, + action: 'partial_persist_session_message_limit', + }; + log.error('message_persistence.session_message_limit_reached', logContext); + waitUntilIfAvailable( + c, + persistError( + c.env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: `Session ${context.sessionId} reached the message limit while persisting a batch`, + context: logContext, + workspaceId: context.workspaceId, + }, + c.env + ) + ); + return c.json( + { + error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', + message: 'Session message limit reached; only part of the batch was persisted', + persisted: result.persisted, + duplicates: result.duplicates, + maxMessages: result.maxMessages, + remainingCapacity: result.remainingCapacity, + }, + 409 + ); +} diff --git a/apps/api/src/routes/workspaces/runtime-messages.ts b/apps/api/src/routes/workspaces/runtime-messages.ts new file mode 100644 index 0000000000..8c55035262 --- /dev/null +++ b/apps/api/src/routes/workspaces/runtime-messages.ts @@ -0,0 +1,128 @@ +import { MESSAGE_OUTBOX_INCARNATION_HEADER } from '@simple-agent-manager/shared'; +import { Hono } from 'hono'; +import * as v from 'valibot'; + +import type { Env } from '../../env'; +import * as projectDataService from '../../services/project-data'; +import { signalWorkspaceDeletionUnconfirmedCallback } from '../../services/workspace-deletion-callback-signal'; +import { sameWorkspaceCallbackIdentity, verifyWorkspaceCallbackAuth } from './_helpers'; +import { + assertMessageWorkspaceAcceptsBatch, + handleMessagePersistenceError, + loadMessageWorkspace, + maybeTerminalMessageWorkspaceResponse, + type MessageBatchPersistenceRouteResult, + type MessageRouteContext, + parseMessageBatchRequest, + partialSessionLimitResponse, + terminalMessagePersistenceResponse, + toProjectDataMessages, + validateMessageBatch, +} from './runtime-message-helpers'; +const runtimeRoutes = new Hono<{ Bindings: Env }>(); +runtimeRoutes.post('/:id/messages', async (c) => { + const workspaceId = c.req.param('id'); + await verifyWorkspaceCallbackAuth(c, workspaceId); + + // Authenticate and resolve terminal state before reading an untrusted body. + // Late deletion callbacks are discarded without parsing or persisting payloads. + const workspace = await loadMessageWorkspace(c.env, workspaceId); + const preflightTerminalResponse = maybeTerminalMessageWorkspaceResponse( + c, + workspace, + workspaceId, + '', + 0 + ); + if (preflightTerminalResponse) { + await signalWorkspaceDeletionUnconfirmedCallback(c.env, workspaceId, 'messages'); + return preflightTerminalResponse; + } + + const body = await parseMessageBatchRequest(c); + const sessionId = validateMessageBatch(c.env, body); + + // Rule 49: re-read immediately before crossing into ProjectData. Deletion or + // reassignment that wins while the body is read must suppress all persistence. + const currentWorkspace = await loadMessageWorkspace(c.env, workspaceId); + const terminalResponse = maybeTerminalMessageWorkspaceResponse( + c, + currentWorkspace, + workspaceId, + sessionId, + body.messages.length + ); + if (terminalResponse) { + return terminalResponse; + } + if ( + !currentWorkspace || + !workspace || + !sameWorkspaceCallbackIdentity(currentWorkspace, workspace) + ) { + return terminalMessagePersistenceResponse( + c, + { + workspaceId, + projectId: currentWorkspace?.projectId ?? null, + sessionId, + messageCount: body.messages.length, + }, + currentWorkspace?.status ?? 'missing', + 'workspace_incarnation_changed' + ); + } + assertMessageWorkspaceAcceptsBatch( + c, + currentWorkspace, + workspaceId, + sessionId, + body.messages.length + ); + + // Delegate to ProjectData DO with structured error handling. + // On failure, return appropriate status codes so the VM agent outbox + // can distinguish transient (retry) from permanent (discard) errors. + const context: MessageRouteContext = { + workspaceId, + projectId: currentWorkspace.projectId, + sessionId, + messageCount: body.messages.length, + }; + let result: MessageBatchPersistenceRouteResult; + const outboxIncarnation = c.req.header(MESSAGE_OUTBOX_INCARNATION_HEADER); + try { + result = await projectDataService.persistMessageBatch( + c.env, + currentWorkspace.projectId, + sessionId, + toProjectDataMessages(body), + { + workspaceId, + callbackGeneration: currentWorkspace.callbackGeneration ?? null, + // This is transport identity, not an auth claim. Missing/malformed IDs + // retain the legacy per-message path instead of guessing about replay. + outboxIncarnation: v.is(v.pipe(v.string(), v.uuid()), outboxIncarnation) + ? outboxIncarnation.toLowerCase() + : undefined, + } + ); + } catch (err) { + return handleMessagePersistenceError(c, context, err); + } + + if (result.limitReached) { + return partialSessionLimitResponse(c, context, result); + } + + return c.json({ + persisted: result.persisted, + duplicates: result.duplicates, + }); +}); + +// Legacy compatibility endpoint for node-side bootstrap exchange. +// This route requires BOTH user session auth AND callback token auth +// (it was not in the original auth skip list in workspaces.ts). + +export { runtimeRoutes as messageRoutes }; diff --git a/apps/api/src/routes/workspaces/runtime.ts b/apps/api/src/routes/workspaces/runtime.ts index 8ff38387f2..f3611855d2 100644 --- a/apps/api/src/routes/workspaces/runtime.ts +++ b/apps/api/src/routes/workspaces/runtime.ts @@ -1,1137 +1,37 @@ -// FILE SIZE EXCEPTION: Workspace runtime routes — splitting credential resolution logic across files increases fragmentation risk. See .claude/rules/18-file-size-limits.md import { - AI_PROXY_DEFAULT_MODEL_KV_KEY, - type AIProxyConfig, type BootstrapTokenData, DEFAULT_AGENT_PERMISSION_MODE, - DEFAULT_AI_PROXY_ANTHROPIC_MODEL, - DEFAULT_AI_PROXY_MODEL, - DEFAULT_AI_PROXY_OPENAI_MODEL, - getAgentDefinition, - HARNESS_CAPABILITIES, - isValidAgentType, - MESSAGE_OUTBOX_INCARNATION_HEADER, - resolveHarnessDialect, } from '@simple-agent-manager/shared'; import { and, eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; -import { type Context, Hono } from 'hono'; -import * as v from 'valibot'; +import { Hono } from 'hono'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; -import { log } from '../../lib/logger'; -import { parsePositiveInt } from '../../lib/route-helpers'; import { getCredentialEncryptionKey } from '../../lib/secrets'; import { ulid } from '../../lib/ulid'; import { requireApproved, requireAuth } from '../../middleware/auth'; -import { errors } from '../../middleware/error'; -import { - AgentTypeBodySchema, - BootLogEntrySchema, - formatIssues, - jsonValidator, - MessageBatchSchema, -} from '../../schemas'; -import { isAiProxyEnabled } from '../../services/ai-proxy-availability'; +import { AgentTypeBodySchema, BootLogEntrySchema, jsonValidator } from '../../schemas'; import { appendBootLog } from '../../services/boot-log'; import { registerBootstrapTokenConsume } from '../../services/bootstrap'; -import { resolveSessionProfileCredentialContext } from '../../services/composable-credentials/profile-context'; -import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; -import { - GitHubCliPolicyError, - resolveWorkspaceGitHubTokenOptions, -} from '../../services/github-cli-policy'; -import { getExternalInstallationId } from '../../services/github-installation-ids'; -import { backfillProjectGithubRepoId } from '../../services/github-repo-id-backfill'; -import { getGitHubUserAccessTokenForOwner } from '../../services/github-user-access-token'; -import { - getProjectGitLabRepository, - requireGitLabUserAccessTokenResultForOwner, - verifyGitLabProjectAccess, -} from '../../services/gitlab'; -import { - hostedGitHost, - isLocalHostedGitActive, - resolveArtifactsBackend, -} from '../../services/hosted-git/backend'; -import { mintHostedGitToken } from '../../services/hosted-git/tokens'; -import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; -import { persistError } from '../../services/observability'; import { resolveProjectAgentDefault } from '../../services/project-agent-defaults'; -import * as projectDataService from '../../services/project-data'; -import { extractScalewaySecretKey } from '../../services/provider-credentials'; -import { assertProviderLimitCredentialPin } from '../../services/provider-limit-credential-pin'; -import { refuseHaltedRunAccount } from '../../services/run-agent-configuration'; -import { - PROXY_ELIGIBLE_AGENTS, - requiresExplicitSamProvider, -} from '../../services/sam-ai-proxy-fallback'; -import { - signalWorkspaceDeletionUnconfirmedCallback, - type WorkspaceDeletionCallbackKind, -} from '../../services/workspace-deletion-callback-signal'; import { getWorkspaceRuntimeAssets } from '../../services/workspace-runtime-assets'; -import { getDecryptedAgentKey, getDecryptedCredentialRecord } from '../credentials'; -import { assertRepositoryAccess } from '../projects/_helpers'; import { assertWorkspaceAcceptsCallback, assertWorkspaceCallbackIdentityCurrent, assertWorkspaceCallbackResourceById, - safeParseJson, - sameWorkspaceCallbackIdentity, verifyWorkspaceCallbackAuth, - type WorkspaceCallbackIdentitySnapshot, + workspaceCallbackIdentityFields, } from './_helpers'; -import { - agentCredentialProviderFallback, - credentialAttributionFromData, - persistAgentCredentialAttribution, - platformProxyAttribution, -} from './agent-credential-attribution'; - -function getProxyCapability(agentType: string) { - const capability = HARNESS_CAPABILITIES.find((entry) => entry.agentType === agentType); - if (!capability?.proxyRouteSegment || !capability.proxyProviderTag) return null; - return capability; -} - -function buildPassthroughInferenceConfig(input: { - agentType: string; - baseDomain: string; - defaultModel: string; -}) { - const capability = getProxyCapability(input.agentType); - if (!capability) return null; - return { - provider: capability.proxyProviderTag, - baseURL: `https://api.${input.baseDomain}/ai/proxy/{wstoken}/${capability.proxyRouteSegment}`, - model: input.defaultModel, - apiKeySource: 'callback-token' as const, - }; -} - -function buildPlatformInferenceConfig(input: { - agentType: string; - baseDomain: string; - defaultModel: string; -}) { - const capability = getProxyCapability(input.agentType); - if (!capability) return null; - const provider = - capability.proxyProviderTag === 'anthropic-passthrough' - ? 'anthropic-proxy' - : capability.usesOpencodeConfig - ? 'openai-compatible' - : 'openai-proxy'; - const routeSegment = capability.proxyRouteSegment === 'anthropic' ? 'anthropic' : 'v1'; - return { - provider, - baseURL: `https://api.${input.baseDomain}/ai/${routeSegment}`, - model: input.defaultModel, - apiKeySource: 'callback-token' as const, - }; -} - +import { agentKeyRoutes } from './runtime-agent-key'; +import { callbackJsonWithJit } from './runtime-callback-response'; +import { gitTokenRoutes } from './runtime-git-token'; +import { messageRoutes } from './runtime-messages'; +export { resolveMaxMessageBytes } from './runtime-message-helpers'; const runtimeRoutes = new Hono<{ Bindings: Env }>(); -type RuntimeContext = Context<{ Bindings: Env }>; -type MessageBatchBody = v.InferOutput; - -async function callbackJsonWithJit>( - c: RuntimeContext, - expected: WorkspaceCallbackIdentitySnapshot, - callback: WorkspaceDeletionCallbackKind, - body: T -) { - await assertWorkspaceCallbackIdentityCurrent(c.env, expected, callback); - if ( - callback === 'agent_key' && - body.credentialSource !== 'platform' && - typeof body.credentialReference === 'string' - ) - await assertProviderLimitCredentialPin( - c.env, - expected.workspaceId, - body.credentialReference, - expected - ); - return c.json(body); -} - -const DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES = 256 * 1024; -const DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES = 102400; -const ACTIVE_MESSAGE_WORKSPACE_STATUSES = new Set(['creating', 'running', 'recovery']); -const VALID_MESSAGE_ROLES = new Set(['user', 'assistant', 'system', 'tool', 'thinking', 'plan']); - -type MessageWorkspace = WorkspaceCallbackIdentitySnapshot & { - projectId: string | null; - chatSessionId: string | null; -}; - -type MessageBatchPersistenceRouteResult = { - persisted: number; - duplicates: number; - limitReached?: boolean; - maxMessages?: number; - remainingCapacity?: number; -}; - -type MessageRouteContext = { - workspaceId: string; - projectId: string; - sessionId: string; - messageCount: number; -}; - -function waitUntilIfAvailable( - c: { executionCtx: { waitUntil(promise: Promise): void } }, - promise: Promise | void -): void { - if (!promise) return; - try { - c.executionCtx.waitUntil(promise); - } catch (err) { - if (!(err instanceof Error) || !err.message.includes('no ExecutionContext')) { - throw err; - } - } -} - -async function readRequestBodyWithLimit(request: Request, maxBytes: number): Promise { - const contentLengthHeader = request.headers.get('content-length'); - if (contentLengthHeader) { - const contentLength = Number.parseInt(contentLengthHeader, 10); - if (!Number.isFinite(contentLength) || contentLength < 0) { - throw errors.badRequest('Invalid Content-Length header'); - } - if (contentLength > maxBytes) { - throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); - } - } - - if (!request.body) { - return ''; - } - - const reader = request.body.getReader(); - const chunks: Uint8Array[] = []; - let totalBytes = 0; - let done = false; - - try { - while (!done) { - const read = await reader.read(); - done = read.done; - if (done) continue; - const { value } = read; - totalBytes += value.byteLength; - if (totalBytes > maxBytes) { - await reader.cancel(); - throw errors.badRequest(`Payload exceeds ${maxBytes} byte limit`); - } - chunks.push(value); - } - } finally { - reader.releaseLock(); - } - - const body = new Uint8Array(totalBytes); - let offset = 0; - for (const chunk of chunks) { - body.set(chunk, offset); - offset += chunk.byteLength; - } - return new TextDecoder().decode(body); -} - -async function parseMessageBatchRequest(c: RuntimeContext): Promise { - const maxPayloadBytes = parsePositiveInt( - c.env.MAX_MESSAGES_PAYLOAD_BYTES as string, - DEFAULT_MAX_MESSAGES_PAYLOAD_BYTES - ); - const rawBody = await readRequestBodyWithLimit(c.req.raw, maxPayloadBytes); - - let parsed: unknown; - try { - parsed = JSON.parse(rawBody); - } catch { - throw errors.badRequest('Invalid JSON in request body'); - } - - const result = v.safeParse(MessageBatchSchema, parsed); - if (!result.success) { - throw errors.badRequest(formatIssues(result.issues)); - } - return result.output; -} - -export function resolveMaxMessageBytes(env: Env): number { - return env.MESSAGE_SIZE_THRESHOLD - ? Number.parseInt(env.MESSAGE_SIZE_THRESHOLD, 10) - : DEFAULT_MESSAGE_SIZE_THRESHOLD_BYTES; -} - -function validateMessageEntry( - msg: MessageBatchBody['messages'][number], - maxMessageBytes: number -): void { - if (!msg.messageId) { - throw errors.badRequest('Each message must have a messageId string'); - } - if (!msg.sessionId) { - throw errors.badRequest('Each message must have a sessionId string'); - } - if (!msg.role || !VALID_MESSAGE_ROLES.has(msg.role)) { - throw errors.badRequest( - `Invalid role "${msg.role}". Must be one of: user, assistant, system, tool, thinking, plan` - ); - } - if (!msg.content) { - throw errors.badRequest('Each message must have non-empty content'); - } - if (msg.content.length > maxMessageBytes) { - throw errors.badRequest(`Individual message content exceeds ${maxMessageBytes} byte limit`); - } - if (!msg.timestamp) { - throw errors.badRequest('Each message must have a timestamp string'); - } -} - -function validateMessageBatch(env: Env, body: MessageBatchBody): string { - if (body.messages.length === 0) { - throw errors.badRequest('messages array must not be empty'); - } - const maxMessagesPerBatch = parsePositiveInt(env.MAX_MESSAGES_PER_BATCH, 100); - if (body.messages.length > maxMessagesPerBatch) { - throw errors.badRequest(`Maximum ${maxMessagesPerBatch} messages per batch`); - } - - const firstMessage = body.messages[0]; - if (!firstMessage) { - throw errors.badRequest('messages array must not be empty'); - } - const maxMessageBytes = resolveMaxMessageBytes(env); - const sessionId = firstMessage.sessionId; - for (const msg of body.messages) { - validateMessageEntry(msg, maxMessageBytes); - if (msg.sessionId !== sessionId) { - throw errors.badRequest('All messages in a batch must target the same sessionId'); - } - } - return sessionId; -} - -async function loadMessageWorkspace( - env: Env, - workspaceId: string -): Promise { - const db = drizzle(env.DATABASE, { schema }); - const workspaceRows = await db - .select({ - workspaceId: schema.workspaces.id, - userId: schema.workspaces.userId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, - }) - .from(schema.workspaces) - .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) - .where(eq(schema.workspaces.id, workspaceId)) - .limit(1); - return workspaceRows[0] ?? null; -} - -function terminalMessagePersistenceResponse( - c: RuntimeContext, - context: Omit & { projectId: string | null }, - status: string, - reason: string -): Response { - const logContext = { - ...context, - status, - reason, - action: 'dropped_terminal_resource', - }; - log.info('message_persistence.inactive_workspace', logContext); - return c.body(null, 204); -} - -function maybeTerminalMessageWorkspaceResponse( - c: RuntimeContext, - workspace: MessageWorkspace | null, - workspaceId: string, - sessionId: string, - messageCount: number -): Response | null { - const context = { - workspaceId, - projectId: workspace?.projectId ?? null, - sessionId, - messageCount, - }; - if (!workspace) { - return terminalMessagePersistenceResponse(c, context, 'missing', 'workspace_missing'); - } - if (!ACTIVE_MESSAGE_WORKSPACE_STATUSES.has(workspace.status)) { - return terminalMessagePersistenceResponse(c, context, workspace.status, 'workspace_inactive'); - } - if ( - !workspace.nodeId || - !workspace.nodeStatus || - nodeStatusTerminatesCallbacks(workspace.nodeStatus) - ) { - return terminalMessagePersistenceResponse( - c, - context, - workspace.nodeStatus ?? 'missing', - 'workspace_node_terminal' - ); - } - return null; -} - -function rejectMessageSessionMismatch( - c: RuntimeContext, - context: MessageRouteContext, - expectedSessionId: string -): never { - const logContext = { - ...context, - expectedSessionId, - receivedSessionId: context.sessionId, - action: 'rejected_batch', - }; - log.error('message_routing.session_mismatch', logContext); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'error', - message: `Message routing mismatch: workspace ${context.workspaceId} linked to session ${expectedSessionId}, but messages target ${context.sessionId}`, - context: logContext, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - throw errors.badRequest( - `Session mismatch: workspace is linked to session ${expectedSessionId}, ` + - `but messages target session ${context.sessionId}` - ); -} - -function rejectWorkspaceWithoutChatSession(c: RuntimeContext, context: MessageRouteContext): never { - const logContext = { - ...context, - providedSessionId: context.sessionId, - action: 'rejected_no_session_link', - }; - log.warn('message_routing.no_chat_session_linked', logContext); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'warn', - message: `Rejecting messages for workspace ${context.workspaceId}: no chatSessionId linked yet`, - context: logContext, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - throw errors.conflict( - 'Workspace has no linked chat session yet — messages cannot be routed safely' - ); -} - -function assertMessageWorkspaceAcceptsBatch( - c: RuntimeContext, - workspace: MessageWorkspace | null, - workspaceId: string, - sessionId: string, - messageCount: number -): asserts workspace is MessageWorkspace & { projectId: string; chatSessionId: string } { - if (!workspace) { - throw errors.notFound('Workspace'); - } - if (!workspace.projectId) { - throw errors.badRequest('Workspace is not linked to a project'); - } - - const context: MessageRouteContext = { - workspaceId, - projectId: workspace.projectId, - sessionId, - messageCount, - }; - if (workspace.chatSessionId && workspace.chatSessionId !== sessionId) { - rejectMessageSessionMismatch(c, context, workspace.chatSessionId); - } - if (!workspace.chatSessionId) { - rejectWorkspaceWithoutChatSession(c, context); - } -} - -function toProjectDataMessages(body: MessageBatchBody) { - return body.messages.map((m) => ({ - messageId: m.messageId, - role: m.role, - content: m.content, - toolMetadata: m.toolMetadata ? safeParseJson(m.toolMetadata) : null, - timestamp: m.timestamp, - sequence: m.sequence, - origin: m.origin ?? null, - })); -} - -function sessionLimitReachedResponse(c: RuntimeContext, context: MessageRouteContext): Response { - log.error('message_persistence.session_message_limit_exceeded', { - ...context, - action: 'rejected_session_message_limit', - }); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'error', - message: `Session ${context.sessionId} has reached the message limit`, - context: { ...context, action: 'rejected_session_message_limit' }, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - return c.json( - { - error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', - message: 'Session message limit reached; no additional messages can be persisted', - }, - 409 - ); -} - -function handleMessagePersistenceError( - c: RuntimeContext, - context: MessageRouteContext, - err: unknown -): Response { - const message = err instanceof Error ? err.message : 'Failed to persist messages'; - if (message.includes('SESSION_MESSAGE_LIMIT_EXCEEDED') || message.includes('message limit')) { - return sessionLimitReachedResponse(c, context); - } - if (message.includes('not found') || message.includes('is stopped')) { - log.info('message_persistence.dropped_terminal_do_response', { - ...context, - error: message, - action: 'dropped_terminal_resource', - }); - return c.body(null, 204); - } - log.error('message_persistence.do_error_transient', { - ...context, - error: message, - action: 'rejected_transient', - }); - return c.json( - { error: 'SERVICE_UNAVAILABLE', message: 'Message persistence temporarily unavailable' }, - 503 - ); -} - -function partialSessionLimitResponse( - c: RuntimeContext, - context: MessageRouteContext, - result: MessageBatchPersistenceRouteResult -): Response { - const logContext = { - ...context, - persisted: result.persisted, - duplicates: result.duplicates, - maxMessages: result.maxMessages, - remainingCapacity: result.remainingCapacity, - action: 'partial_persist_session_message_limit', - }; - log.error('message_persistence.session_message_limit_reached', logContext); - waitUntilIfAvailable( - c, - persistError( - c.env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'error', - message: `Session ${context.sessionId} reached the message limit while persisting a batch`, - context: logContext, - workspaceId: context.workspaceId, - }, - c.env - ) - ); - return c.json( - { - error: 'SESSION_MESSAGE_LIMIT_EXCEEDED', - message: 'Session message limit reached; only part of the batch was persisted', - persisted: result.persisted, - duplicates: result.duplicates, - maxMessages: result.maxMessages, - remainingCapacity: result.remainingCapacity, - }, - 409 - ); -} - -async function verifyWorkspaceGitHubOwnerAccess(input: { - env: Env; - workspaceId: string; - projectId: string | null; - userId: string; - repository: string; - externalInstallationId: string; - githubRepoId: number | null; -}): Promise { - const accessToken = await getGitHubUserAccessTokenForOwner( - input.env, - input.userId, - 'workspace-git-token' - ); - if (!accessToken) { - log.warn('workspace_git_token_user_access_missing', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - action: 'rejected', - }); - throw errors.forbidden('GitHub user token unavailable'); - } - - // Every git and gh credential exchange lands here, so pass env to use the - // pagination hint (GITHUB_REPO_ACCESS_CACHE_TTL_SECONDS). Every exchange - // still verifies current user access against GitHub; hints never grant access. - const verifiedRepo = await assertRepositoryAccess( - accessToken, - input.externalInstallationId, - input.repository, - input.userId, - 'project-access', - input.env - ); - - if (input.githubRepoId !== null && verifiedRepo.id !== input.githubRepoId) { - log.warn('workspace_git_token_repo_id_drift', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - expectedRepoId: input.githubRepoId, - verifiedRepoId: verifiedRepo.id, - action: 'rejected', - }); - throw errors.forbidden('GitHub repository access has changed; repository ID no longer matches'); - } - - return verifiedRepo.id; -} - -/** - * Resolve numeric repository IDs for a project's additional Repository Access - * entries, re-verifying user∩app access at the token-mint boundary. Stored rows - * whose access has been revoked (or whose installation no longer exposes them) - * are dropped from the scope — an unselected/inaccessible repo simply never makes - * it into the minted token's `repository_ids`, so it fails clearly downstream. - * Failure to fetch the accessible set returns the empty set rather than throwing, - * so the primary-repo token still mints (additional repos degrade, never break - * the primary clone). - */ -async function resolveAdditionalRepositoryIds(input: { - env: Env; - db: ReturnType>; - workspaceId: string; - projectId: string; - userId: string; - externalInstallationId: string; -}): Promise { - const rows = await input.db - .select({ - repository: schema.projectGithubRepositories.repository, - githubRepoId: schema.projectGithubRepositories.githubRepoId, - }) - .from(schema.projectGithubRepositories) - .where(eq(schema.projectGithubRepositories.projectId, input.projectId)); - if (rows.length === 0) { - return []; - } - - const accessToken = await getGitHubUserAccessTokenForOwner( - input.env, - input.userId, - 'workspace-git-token' - ); - if (!accessToken) { - log.warn('workspace_git_token_additional_repos_user_access_missing', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - action: 'additional_repos_skipped', - }); - return []; - } - - let accessibleById = new Map(); - try { - const repositories = await getUserInstallationRepositories( - accessToken, - input.externalInstallationId, - { - flow: 'project-access', - userId: input.userId, - installationId: input.externalInstallationId, - } - ); - accessibleById = new Map(repositories.map((r) => [r.fullName.toLowerCase(), r.id])); - } catch (err) { - log.warn('workspace_git_token_additional_repos_unavailable', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - error: err instanceof Error ? err.message : String(err), - action: 'additional_repos_skipped', - }); - return []; - } - - const ids: number[] = []; - for (const row of rows) { - const accessibleId = accessibleById.get(row.repository.toLowerCase()); - if (accessibleId === undefined) { - log.warn('workspace_git_token_additional_repo_access_revoked', { - workspaceId: input.workspaceId, - projectId: input.projectId, - userId: input.userId, - repository: row.repository, - action: 'excluded_from_scope', - }); - continue; - } - // Prefer the live, rename-stable id from the accessible set. Stored ids can - // drift if the repo was deleted/recreated; the live id is authoritative. - ids.push(accessibleId); - } - return ids; -} - -runtimeRoutes.post('/:id/agent-key', jsonValidator(AgentTypeBodySchema), async (c) => { - const workspaceId = c.req.param('id'); - await verifyWorkspaceCallbackAuth(c, workspaceId); - const body = c.req.valid('json'); - - const db = drizzle(c.env.DATABASE, { schema }); - - const workspace = await assertWorkspaceCallbackResourceById(c.env, workspaceId, 'agent_key'); - - // OpenCode always uses a user-supplied credential (zen/go/custom). It never - // routes through the SAM platform proxy, so it always requires a dedicated key. - const opencodeRequiresDedicatedCredential = body.agentType === 'opencode'; - - const encryptionKey = getCredentialEncryptionKey(c.env); - // The session's profile decides whether a personal profile pin applies; the AI - // proxy and provider-limit admission resolve the same context. - const profile = await resolveSessionProfileCredentialContext(db, { - workspaceId, - agentSessionId: body.agentSessionId, - }); - let credentialData = await getDecryptedAgentKey( - db, - workspace.userId, - body.agentType, - encryptionKey, - workspace.projectId, - profile - ); - let credentialProviderMode = 'direct'; - - // An account chosen for this run that can no longer be used (paused, removed) must stop - // the run here. Without this, "no credential" would continue to the platform proxy or a - // fallback below and run the chat on an account nobody chose for it. - if (!credentialData && profile?.runConfigurationId) { - await refuseHaltedRunAccount(db, { - workspaceId, - userId: workspace.userId, - projectId: workspace.projectId, - agentType: body.agentType, - encryptionKey, - profile, - }); - } - - // SECURITY: Never return raw platform-managed credentials to tenant workspaces. - // Platform credentials are control-plane secrets and must only be used via - // SAM-mediated proxy flows (callback-token auth), not injected into tenant - // containers as env vars or auth files. - if (credentialData?.credentialSource === 'platform') { - credentialData = null; - } - - // Cloud provider credential fallback: if no dedicated agent key, check if the agent - // definition specifies a cloud provider whose credential can be used instead. - const agentDef = isValidAgentType(body.agentType) - ? getAgentDefinition(body.agentType) - : undefined; - const fallbackCloudProvider = agentDef?.fallbackCloudProvider; - if (!credentialData && fallbackCloudProvider) { - const fallbackCredential = await getDecryptedCredentialRecord( - db, - workspace.userId, - fallbackCloudProvider, - encryptionKey - ); - if (fallbackCredential) { - const secretKey = extractScalewaySecretKey(fallbackCredential.credential); - if (secretKey) { - credentialData = { - credential: secretKey, - credentialKind: 'api-key', - credentialSource: 'user', - credentialScope: 'user', - credentialReference: fallbackCredential.credentialReference, - credentialProvider: fallbackCredential.credentialProvider, - }; - credentialProviderMode = 'fallback-cloud-provider'; - } else { - log.warn('agent_key.scaleway_credential_missing_secret_key', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - }); - } - } - } - - if (credentialData && opencodeRequiresDedicatedCredential) { - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); - } - - if (!credentialData && opencodeRequiresDedicatedCredential) { - log.info('agent_key.opencode_byo_provider_missing_credential', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - }); - throw errors.notFound('Agent credential'); - } - - // AI proxy: when enabled and agent is eligible, return proxy config when the - // credential can be forwarded to the upstream provider. - // Two modes: - // - Claude/Codex with no user credential + providerMode='sam' → platform proxy (callback-token auth) - // - User has upstream-compatible credential → passthrough proxy (user credential - // forwarded via auth headers, wstoken in URL path for analytics/rate-limiting) - // Note: platform proxy fallback requires explicit provider selection. - // Without it, users with no credential get a 404 (agent not configured). - const aiProxyEnabled = await isAiProxyEnabled(c.env); - if (PROXY_ELIGIBLE_AGENTS.has(body.agentType) && aiProxyEnabled) { - const baseDomain = c.env.BASE_DOMAIN; - const isClaudeCode = body.agentType === 'claude-code'; - const isCodex = body.agentType === 'openai-codex'; - let explicitProviderMode: string | null | undefined; - const getExplicitProviderMode = async (): Promise => { - if (explicitProviderMode !== undefined) return explicitProviderMode; - const settingsRows = await db - .select({ providerMode: schema.agentSettings.providerMode }) - .from(schema.agentSettings) - .where( - and( - eq(schema.agentSettings.userId, workspace.userId), - eq(schema.agentSettings.agentType, body.agentType) - ) - ) - .limit(1); - explicitProviderMode = settingsRows[0]?.providerMode ?? null; - return explicitProviderMode; - }; - - // Resolve default model: KV (admin-set) > env var > shared constant - let defaultModel: string; - if (isClaudeCode) { - defaultModel = c.env.AI_PROXY_DEFAULT_ANTHROPIC_MODEL ?? DEFAULT_AI_PROXY_ANTHROPIC_MODEL; - } else if (isCodex) { - defaultModel = c.env.AI_PROXY_DEFAULT_OPENAI_MODEL ?? DEFAULT_AI_PROXY_OPENAI_MODEL; - } else { - defaultModel = c.env.AI_PROXY_DEFAULT_MODEL ?? DEFAULT_AI_PROXY_MODEL; - try { - const kvConfig = await c.env.KV.get(AI_PROXY_DEFAULT_MODEL_KV_KEY); - if (kvConfig) { - const parsed: AIProxyConfig = JSON.parse(kvConfig); - if (parsed.defaultModel) defaultModel = parsed.defaultModel; - } - } catch { - /* KV unavailable or corrupt data — use env/default */ - } - } - - // Claude Code/Codex explicit SAM mode must route through the SAM proxy, - // not through legacy platform agent credentials as user-style passthrough. - if ((isClaudeCode || isCodex) && credentialData?.credentialSource === 'platform') { - credentialData = null; - } - - if ( - credentialData && - credentialData.baseUrl && - credentialData.providerDialect && - resolveHarnessDialect(body.agentType, credentialData.providerDialect) && - !((isClaudeCode || isCodex) && credentialData.credentialKind === 'oauth-token') - ) { - // User has their own credential — use passthrough proxy routes. - // URL-path auth: wstoken embedded in URL, user credential in auth headers. - const inferenceConfig = buildPassthroughInferenceConfig({ - agentType: body.agentType, - baseDomain, - defaultModel, - }); - if (!inferenceConfig) { - throw errors.notFound('Agent credential'); - } - - log.info('agent_key.ai_proxy_passthrough', { - workspaceId, - userId: workspace.userId, - proxyBaseUrl: inferenceConfig.baseURL, - agentType: body.agentType, - }); - - // Track credential source on associated task - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: credentialData.credentialSource }) - .where(eq(schema.tasks.id, task.id)); - } - - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - 'proxy-passthrough' - ), - }); - - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: '__sam_proxy__', - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? - credentialData.providerDialect ?? - agentCredentialProviderFallback(body.agentType), - providerMode: 'proxy-passthrough', - credentialGeneration: persistedAttribution?.credentialGeneration, - inferenceConfig, - }); - } - - if (credentialData?.baseUrl) { - log.warn('agent_key.ai_proxy_incompatible_passthrough_credential', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - providerDialect: credentialData.providerDialect ?? null, - }); - throw errors.notFound('Agent credential'); - } - - if (credentialData) { - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); - } - - // Claude Code and Codex require an explicit SAM provider selection before - // using platform proxy. OpenCode never reaches this block — it always - // requires a dedicated user credential and returns/throws above. - if (requiresExplicitSamProvider(body.agentType)) { - const providerMode = await getExplicitProviderMode(); - - if (providerMode !== 'sam') { - log.info('agent_key.no_credential_no_sam_provider', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - providerMode, - }); - throw errors.notFound('Agent credential'); - } - } - - // Activate platform proxy. - // Auth via callback token in headers. - const inferenceConfig = buildPlatformInferenceConfig({ - agentType: body.agentType, - baseDomain, - defaultModel, - }); - if (!inferenceConfig) { - throw errors.notFound('Agent credential'); - } - - log.info('agent_key.ai_proxy_sam_provider', { - workspaceId, - userId: workspace.userId, - proxyBaseUrl: inferenceConfig.baseURL, - agentType: body.agentType, - }); - - // Track credential source on associated task - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: 'platform' }) - .where(eq(schema.tasks.id, task.id)); - } - - const platformAttribution = platformProxyAttribution(body.agentType); - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: platformAttribution, - }); - - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: '__platform_proxy__', - credentialKind: 'api-key' as const, - credentialSource: 'platform' as const, - credentialReference: platformAttribution.credentialReference, - credentialProvider: platformAttribution.credentialProvider, - providerMode: platformAttribution.providerMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - inferenceConfig, - }); - } - - if (!credentialData) { - throw errors.notFound('Agent credential'); - } - - // A credential that names a custom base URL is served only through the passthrough proxy above. - // This response carries no base URL, so returning the key here would send it to the vendor's - // default endpoint (another company's API) instead of the endpoint it was issued for. - if (credentialData.baseUrl && PROXY_ELIGIBLE_AGENTS.has(body.agentType)) { - log.warn('agent_key.custom_base_url_requires_ai_proxy', { - workspaceId, - userId: workspace.userId, - agentType: body.agentType, - aiProxyEnabled, - action: 'rejected', - }); - throw errors.notFound('Agent credential'); - } - - // Track credential source on associated task if applicable - if (credentialData.credentialSource === 'platform') { - const taskRows = await db - .select({ id: schema.tasks.id }) - .from(schema.tasks) - .where(eq(schema.tasks.workspaceId, workspaceId)) - .limit(1); - const task = taskRows[0]; - if (task) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'agent_key'); - await db - .update(schema.tasks) - .set({ agentCredentialSource: 'platform' }) - .where(eq(schema.tasks.id, task.id)); - } - } - - const persistedAttribution = await persistAgentCredentialAttribution(c.env, workspace, { - workspaceId, - agentSessionId: body.agentSessionId, - agentType: body.agentType, - attribution: credentialAttributionFromData( - credentialData, - body.agentType, - credentialProviderMode - ), - }); - - return callbackJsonWithJit(c, workspace, 'agent_key', { - apiKey: credentialData.credential, - credentialKind: credentialData.credentialKind, - credentialSource: credentialData.credentialSource, - credentialReference: credentialData.credentialReference, - credentialProvider: - credentialData.credentialProvider ?? agentCredentialProviderFallback(body.agentType), - providerMode: credentialProviderMode, - credentialGeneration: persistedAttribution?.credentialGeneration, - }); -}); - -/** - * POST /:id/agent-settings — VM agent callback to fetch user's agent settings. - * Uses workspace callback auth (same as agent-key). - */ +runtimeRoutes.route('/', agentKeyRoutes); +runtimeRoutes.route('/', gitTokenRoutes); +runtimeRoutes.route('/', messageRoutes); runtimeRoutes.post('/:id/agent-settings', jsonValidator(AgentTypeBodySchema), async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); @@ -1187,16 +87,9 @@ runtimeRoutes.get('/:id/runtime', async (c) => { const workspaceRows = await db .select({ - workspaceId: schema.workspaces.id, - userId: schema.workspaces.userId, + ...workspaceCallbackIdentityFields, repository: schema.workspaces.repository, branch: schema.workspaces.branch, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, }) .from(schema.workspaces) .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) @@ -1237,322 +130,6 @@ runtimeRoutes.get('/:id/runtime-assets', async (c) => { return c.json(assets); }); -runtimeRoutes.post('/:id/git-token', async (c) => { - const workspaceId = c.req.param('id'); - await verifyWorkspaceCallbackAuth(c, workspaceId); - - const db = drizzle(c.env.DATABASE, { schema }); - - // Look up workspace → project to determine repo provider - const workspaceRows = await db - .select({ - workspaceId: schema.workspaces.id, - installationId: schema.workspaces.installationId, - projectId: schema.workspaces.projectId, - chatSessionId: schema.workspaces.chatSessionId, - userId: schema.workspaces.userId, - status: schema.workspaces.status, - nodeId: schema.workspaces.nodeId, - nodeStatus: schema.nodes.status, - callbackGeneration: schema.workspaces.callbackGeneration, - }) - .from(schema.workspaces) - .leftJoin(schema.nodes, eq(schema.nodes.id, schema.workspaces.nodeId)) - .where(eq(schema.workspaces.id, workspaceId)) - .limit(1); - - const workspace = await assertWorkspaceAcceptsCallback( - c.env, - workspaceRows[0], - workspaceId, - 'git_token' - ); - - // Look up the project to check repoProvider - let repoProvider = 'github'; - let artifactsRepoId: string | null = null; - let githubRepoId: number | null = null; - let repositoryName: string | null = null; - if (workspace.projectId) { - const projectRows = await db - .select({ - repoProvider: schema.projects.repoProvider, - artifactsRepoId: schema.projects.artifactsRepoId, - githubRepoId: schema.projects.githubRepoId, - repository: schema.projects.repository, - }) - .from(schema.projects) - .where(eq(schema.projects.id, workspace.projectId)) - .limit(1); - - const project = projectRows[0]; - if (project) { - repoProvider = project.repoProvider || 'github'; - artifactsRepoId = project.artifactsRepoId; - githubRepoId = project.githubRepoId; - repositoryName = project.repository; - } - } - - if (repoProvider === 'artifacts') { - // ─── Artifacts token ────────────────────────────────────────────── - if (c.env.ARTIFACTS_ENABLED !== 'true') { - throw errors.forbidden('Artifacts provider is not enabled'); - } - const artifacts = resolveArtifactsBackend(c.env); - if (!artifacts) { - throw errors.featureUnavailable( - 'artifacts', - 'SAM-native Git repositories are not available on this installation' - ); - } - if (!artifactsRepoId) { - throw errors.internal('Artifacts binding or repo ID missing'); - } - - // Clamp the token TTL to a sane range: a negative/zero/NaN or excessively - // large configured value must not mint a token that never expires (or expires - // instantly). Default 1h; hard cap 24h. - const rawTtl = Number.parseInt(c.env.ARTIFACTS_TOKEN_TTL_SECONDS || '', 10); - const ttl = Number.isFinite(rawTtl) && rawTtl > 0 && rawTtl <= 86400 ? rawTtl : 3600; - // Use requested scope or default to 'write' (agents need push access) - const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); - const repo = await artifacts.get(artifactsRepoId); - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - // SAM-hosted repositories (self-host): the token is bound to this workspace, so the git - // server refuses it once the workspace stops (services/hosted-git/http.ts). - const localHostedGit = isLocalHostedGitActive(c.env); - const tokenResult = localHostedGit - ? await mintHostedGitToken(c.env, { - repo: artifactsRepoId, - scope: requestedScope, - ttlSeconds: ttl, - workspaceId: workspace.workspaceId, - callbackGeneration: workspace.callbackGeneration ?? null, - userId: workspace.userId, - }).then((minted) => ({ - plaintext: minted.token, - expiresAt: minted.expiresAt, - expires_at: undefined, - })) - : await repo.createToken(requestedScope, ttl); - - // Strip ?expires= suffix from token for git credential use - const tokenSecret = tokenResult.plaintext.split('?expires=')[0] || tokenResult.plaintext; - - // Prefer the stored project.repository as the clone URL: it is `created.remote` - // captured at project creation and is exactly what the VM agent cloned, so its - // host is guaranteed to match what git requests from the credential helper. The - // Artifacts binding's `get().remote` has been observed to come back empty on - // staging (unlike `create().remote`); when that happens an empty cloneUrl makes - // the VM agent default the credential host to github.com, which then fails to - // match the real Artifacts host and returns no credential (git fetch/push break). - const cloneUrl = repositoryName || repo.remote || ''; - if (!repo.remote) { - log.warn('workspace_git_token.artifacts_remote_empty', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - artifactsRepoId, - usedStoredRepository: !!repositoryName, - action: 'fell_back_to_stored_repository', - }); - } - if (!cloneUrl) { - log.error('workspace_git_token.artifacts_clone_url_missing', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - artifactsRepoId, - action: 'clone_url_empty', - }); - } - - return callbackJsonWithJit(c, workspace, 'git_token', { - token: tokenSecret, - expiresAt: tokenResult.expiresAt ?? tokenResult.expires_at, - cloneUrl, - // The VM agent's credential helper answers for this host with this username; a hosted - // repository's host (api.) is not one it recognizes by name. - ...(localHostedGit ? { host: hostedGitHost(c.env), username: 'x' } : {}), - }); - } - - if (repoProvider === 'gitlab') { - if (!workspace.projectId) { - throw errors.forbidden('GitLab workspace has no project'); - } - const metadata = await getProjectGitLabRepository(db, workspace.projectId); - if (!metadata) { - throw errors.forbidden('GitLab repository metadata is missing'); - } - if (metadata.userId !== workspace.userId) { - // The stored GitLab repo binding belongs to a different user than the - // workspace owner — vending the owner's OAuth token against another - // user's binding would cross a tenant boundary. Fail closed. - log.error('workspace_git_token.gitlab_user_mismatch', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - workspaceUserId: workspace.userId, - metadataUserId: metadata.userId, - action: 'rejected', - }); - throw errors.forbidden('GitLab repository is not linked for this workspace owner'); - } - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const tokenResult = await requireGitLabUserAccessTokenResultForOwner( - c.env, - workspace.userId, - 'workspace-git-token' - ); - const verified = await verifyGitLabProjectAccess( - c.env, - tokenResult.accessToken, - metadata.gitlabProjectId - ); - if ( - verified.host !== metadata.host || - verified.gitlabProjectId !== metadata.gitlabProjectId || - verified.pathWithNamespace !== metadata.pathWithNamespace - ) { - throw errors.forbidden('GitLab repository access has changed; repository no longer matches'); - } - - return callbackJsonWithJit(c, workspace, 'git_token', { - provider: 'gitlab', - token: tokenResult.accessToken, - expiresAt: tokenResult.accessTokenExpiresAt, - cloneUrl: metadata.httpUrlToRepo, - host: metadata.host, - username: 'oauth2', - repositoryPath: metadata.pathWithNamespace, - }); - } - - // ─── GitHub token (existing flow) ────────────────────────────────── - if (!workspace.installationId) { - throw errors.notFound('Workspace has no GitHub installation'); - } - // Scope the token to a single repo. Prefer the verified numeric repo ID; fall - // back to the repository name for legacy projects created before github_repo_id - // was backfilled (PR #1236). Both paths scope to exactly one repository, so the - // personal-installation leak fix is preserved. - const repoShortName = - repositoryName && repositoryName.includes('/') - ? (repositoryName.split('/').pop() ?? null) - : repositoryName; - if (!githubRepoId && !repoShortName) { - throw errors.forbidden('GitHub repository is not verified for this workspace'); - } - - const installations = await db - .select({ - installationId: schema.githubInstallations.installationId, - externalInstallationId: schema.githubInstallations.externalInstallationId, - userId: schema.githubInstallations.userId, - }) - .from(schema.githubInstallations) - .where(eq(schema.githubInstallations.id, workspace.installationId)) - .limit(1); - - const installation = installations[0]; - if (!installation) { - log.warn('workspace_git_token_installation_owner_mismatch', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - installationRowId: workspace.installationId, - expectedUserId: workspace.userId, - action: 'rejected', - }); - throw errors.notFound('GitHub installation'); - } - if (installation.userId !== workspace.userId) { - log.info('workspace_git_token_project_installation_shared', { - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - installationRowId: workspace.installationId, - workspaceUserId: workspace.userId, - installationOwnerUserId: installation.userId, - action: 'allowed_after_user_access_verification', - }); - } - - if (!repositoryName) { - throw errors.forbidden('GitHub repository is not verified for this workspace'); - } - - const verifiedRepoId = await verifyWorkspaceGitHubOwnerAccess({ - env: c.env, - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - userId: workspace.userId, - repository: repositoryName, - externalInstallationId: getExternalInstallationId(installation), - githubRepoId, - }); - - // Lazy self-heal: legacy projects created before the numeric repo id was - // captured have github_repo_id = null. Fetch + persist it now, BEFORE policy - // resolution, so custom GitHub CLI policies (which require the numeric id) work - // and scoping uses the rename-stable repositoryIds path. On any failure we fall - // through to the name-based fallback below (no regression). - if (!githubRepoId && repositoryName && workspace.projectId) { - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const backfill = await backfillProjectGithubRepoId(db, c.env, { - projectId: workspace.projectId, - repository: repositoryName, - externalInstallationId: getExternalInstallationId(installation), - }); - if (backfill.githubRepoId) { - githubRepoId = backfill.githubRepoId; - } - } - githubRepoId ??= verifiedRepoId; - - let tokenOptions = null; - try { - tokenOptions = await resolveWorkspaceGitHubTokenOptions(db, { - workspaceId: workspace.workspaceId, - userId: workspace.userId, - githubRepoId, - }); - } catch (err) { - if (err instanceof GitHubCliPolicyError) { - throw errors.forbidden('GitHub CLI policy prevents token minting'); - } - throw err; - } - // Additional Repository Access: same-installation repos selected in Project - // Settings. Re-verified at this boundary; revoked/inaccessible entries are - // dropped from the scope. Primary repo is always included implicitly. - const additionalRepoIds = - githubRepoId && workspace.projectId - ? await resolveAdditionalRepositoryIds({ - env: c.env, - db, - workspaceId: workspace.workspaceId, - projectId: workspace.projectId, - userId: workspace.userId, - externalInstallationId: getExternalInstallationId(installation), - }) - : []; - - const scopedTokenOptions = { - ...(tokenOptions ?? {}), - ...(githubRepoId - ? { repositoryIds: [githubRepoId, ...additionalRepoIds.filter((id) => id !== githubRepoId)] } - : { repositories: [repoShortName as string] }), - }; - await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const token = await getInstallationToken( - getExternalInstallationId(installation), - c.env, - scopedTokenOptions - ); - return callbackJsonWithJit(c, workspace, 'git_token', { - token: token.token, - expiresAt: token.expiresAt, - }); -}); - runtimeRoutes.post('/:id/boot-log', jsonValidator(BootLogEntrySchema), async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); @@ -1578,110 +155,6 @@ runtimeRoutes.post('/:id/boot-log', jsonValidator(BootLogEntrySchema), async (c) * Uses workspace callback auth. Accepts 1-100 messages per batch. * All messages must target the same sessionId. */ -runtimeRoutes.post('/:id/messages', async (c) => { - const workspaceId = c.req.param('id'); - await verifyWorkspaceCallbackAuth(c, workspaceId); - - // Authenticate and resolve terminal state before reading an untrusted body. - // Late deletion callbacks are discarded without parsing or persisting payloads. - const workspace = await loadMessageWorkspace(c.env, workspaceId); - const preflightTerminalResponse = maybeTerminalMessageWorkspaceResponse( - c, - workspace, - workspaceId, - '', - 0 - ); - if (preflightTerminalResponse) { - await signalWorkspaceDeletionUnconfirmedCallback(c.env, workspaceId, 'messages'); - return preflightTerminalResponse; - } - - const body = await parseMessageBatchRequest(c); - const sessionId = validateMessageBatch(c.env, body); - - // Rule 49: re-read immediately before crossing into ProjectData. Deletion or - // reassignment that wins while the body is read must suppress all persistence. - const currentWorkspace = await loadMessageWorkspace(c.env, workspaceId); - const terminalResponse = maybeTerminalMessageWorkspaceResponse( - c, - currentWorkspace, - workspaceId, - sessionId, - body.messages.length - ); - if (terminalResponse) { - return terminalResponse; - } - if ( - !currentWorkspace || - !workspace || - !sameWorkspaceCallbackIdentity(currentWorkspace, workspace) - ) { - return terminalMessagePersistenceResponse( - c, - { - workspaceId, - projectId: currentWorkspace?.projectId ?? null, - sessionId, - messageCount: body.messages.length, - }, - currentWorkspace?.status ?? 'missing', - 'workspace_incarnation_changed' - ); - } - assertMessageWorkspaceAcceptsBatch( - c, - currentWorkspace, - workspaceId, - sessionId, - body.messages.length - ); - - // Delegate to ProjectData DO with structured error handling. - // On failure, return appropriate status codes so the VM agent outbox - // can distinguish transient (retry) from permanent (discard) errors. - const context: MessageRouteContext = { - workspaceId, - projectId: currentWorkspace.projectId, - sessionId, - messageCount: body.messages.length, - }; - let result: MessageBatchPersistenceRouteResult; - const outboxIncarnation = c.req.header(MESSAGE_OUTBOX_INCARNATION_HEADER); - try { - result = await projectDataService.persistMessageBatch( - c.env, - currentWorkspace.projectId, - sessionId, - toProjectDataMessages(body), - { - workspaceId, - callbackGeneration: currentWorkspace.callbackGeneration ?? null, - // This is transport identity, not an auth claim. Missing/malformed IDs - // retain the legacy per-message path instead of guessing about replay. - outboxIncarnation: v.is(v.pipe(v.string(), v.uuid()), outboxIncarnation) - ? outboxIncarnation.toLowerCase() - : undefined, - } - ); - } catch (err) { - return handleMessagePersistenceError(c, context, err); - } - - if (result.limitReached) { - return partialSessionLimitResponse(c, context, result); - } - - return c.json({ - persisted: result.persisted, - duplicates: result.duplicates, - }); -}); - -// Legacy compatibility endpoint for node-side bootstrap exchange. -// This route requires BOTH user session auth AND callback token auth -// (it was not in the original auth skip list in workspaces.ts). runtimeRoutes.post('/:id/bootstrap-token', requireAuth(), requireApproved(), async (c) => { const workspaceId = c.req.param('id'); await verifyWorkspaceCallbackAuth(c, workspaceId); diff --git a/apps/api/src/routes/workspaces/workspace-create.ts b/apps/api/src/routes/workspaces/workspace-create.ts index 7cbfa8d306..70185b3886 100644 --- a/apps/api/src/routes/workspaces/workspace-create.ts +++ b/apps/api/src/routes/workspaces/workspace-create.ts @@ -550,7 +550,11 @@ export function registerWorkspaceCreateRoute(crudRoutes: Hono<{ Bindings: Env }> resolvedReservation, createdAt: now, }, - linkedProject: { id: linkedProject.id, repoProvider: linkedProject.repoProvider }, + linkedProject: { + id: linkedProject.id, + repoProvider: linkedProject.repoProvider, + repository: linkedProject.repository, + }, taskId: chatTaskId, chatSessionId, mustProvisionNode, diff --git a/apps/api/src/scheduled/cron-triggers.ts b/apps/api/src/scheduled/cron-triggers.ts index 534ab2315e..57dd7c5bae 100644 --- a/apps/api/src/scheduled/cron-triggers.ts +++ b/apps/api/src/scheduled/cron-triggers.ts @@ -1,4 +1,5 @@ /** Cron source adapter. Scheduling stays here; execution policy lives in trigger-admission. */ +import { cronToNextFire } from '@simple-agent-manager/cron'; import { DEFAULT_CRON_MAX_FIRE_PER_SWEEP } from '@simple-agent-manager/shared'; import { and, asc, eq, gt, isNotNull, lte } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; @@ -9,7 +10,6 @@ import { databaseFailureCategory } from '../lib/database-failure-category'; import { log } from '../lib/logger'; import { parsePositiveInt } from '../lib/route-helpers'; import { expectJsonRecord } from '../lib/runtime-validation'; -import { cronToNextFire } from '../services/cron-utils'; import { admitAndSubmitTriggerExecution } from '../services/trigger-admission'; import { buildCronContext, renderTemplate } from '../services/trigger-template'; diff --git a/apps/api/src/scheduled/daily-jobs.ts b/apps/api/src/scheduled/daily-jobs.ts new file mode 100644 index 0000000000..ec22d32f93 --- /dev/null +++ b/apps/api/src/scheduled/daily-jobs.ts @@ -0,0 +1,58 @@ +/** + * The daily `0 3 * * *` cron. Every job is its own `waitUntil` promise with its own catch, so one + * failing or slow job cannot skip or delay the others (`.claude/rules/53`). Split out of + * `handler.ts` (`.claude/rules/18-file-size-limits.md`). + */ +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import { runCloudflareCostSnapshot } from '../services/cloudflare-cost-snapshot'; +import { runLifecycleLatencyDailyEvaluation } from '../services/lifecycle-latency'; +import { purgeRuntimeSecretMaterial } from '../services/runtime-secret-request-maintenance'; +import { runAnalyticsForwardJob } from './analytics-forward'; +import { runDebugPackagePurge } from './debug-package-purge'; +import { runOperationsAuditPurge } from './operations-audit-purge'; +import { runOperationsTelemetryRetention } from './operations-telemetry-retention'; + +export const DAILY_CRON = '0 3 * * *'; + +function logFailure(event: string) { + return (err: unknown) => { + log.error(event, { error: err instanceof Error ? err.message : String(err) }); + }; +} + +export function scheduleDailyJobs( + env: Env, + cron: string, + waitUntil: (promise: Promise) => void +): void { + waitUntil( + (async () => { + const forward = await runAnalyticsForwardJob(env); + log.info('cron.completed', { + cron, + type: 'daily-forward', + forwardEnabled: forward.enabled, + forwardEventsQueried: forward.eventsQueried, + forwardSegmentSent: forward.segment.sent, + forwardGA4Sent: forward.ga4.sent, + forwardCursorUpdated: forward.cursorUpdated, + }); + })().catch(logFailure('cron.analytics_forward_failed')) + ); + // Separate promise: an analytics failure must not skip the audit retention purge. + waitUntil(runOperationsAuditPurge(env, cron)); + waitUntil(runDebugPackagePurge(env, cron)); + waitUntil(runOperationsTelemetryRetention(env, cron)); + // Expired collected secret values are already refused at read time; this deletes them. + waitUntil(purgeRuntimeSecretMaterial(env).catch(logFailure('cron.runtime_secret_purge_failed'))); + // Separate promise again, so none of the jobs above can suppress the latency check. + waitUntil( + runLifecycleLatencyDailyEvaluation(env).catch(logFailure('cron.lifecycle_latency_daily_failed')) + ); + // Insights slice CF: the previous days' Cloudflare usage for Admin Health & cost. It records its + // own Cloudflare failures; this catch covers settings or D1 failing underneath it. + waitUntil( + runCloudflareCostSnapshot(env).catch(logFailure('cron.cloudflare_cost_snapshot_failed')) + ); +} diff --git a/apps/api/src/scheduled/handler.ts b/apps/api/src/scheduled/handler.ts index d8f5265802..f71e5c9d04 100644 --- a/apps/api/src/scheduled/handler.ts +++ b/apps/api/src/scheduled/handler.ts @@ -11,37 +11,29 @@ import { reconcileDiagnosisRuns } from '../services/diagnosis-runner'; import { reconcileDiagnosticIncidents } from '../services/diagnostic-incident-reconciliation'; import { refreshGcpPriceTableIfDue } from '../services/gcp-price-table'; import { runGitHubTriggerRecovery } from '../services/github-trigger-recovery'; +import { runInboxAutomationErrorSweep } from '../services/inbox/automation-errors'; import { runInboxAskSweep } from '../services/inbox/sweep'; -import { - runLifecycleLatencyDailyEvaluation, - runLifecycleLatencyWatchdog, -} from '../services/lifecycle-latency'; -import { runReverseTunnelLeaseSweep } from '../services/node-reverse-tunnel-leases'; +import { runInboxSystemErrorSweep } from '../services/inbox/system-errors'; +import { runLifecycleLatencyWatchdog } from '../services/lifecycle-latency'; import { runNodeTunnelCleanupSweep } from '../services/node-tunnel-cleanup'; import { isOperationalLoopEnabled } from '../services/operational-kill-switch'; -import { - purgeRuntimeSecretMaterial, - runRuntimeSecretRequestSweep, -} from '../services/runtime-secret-request-maintenance'; +import { runRuntimeSecretRequestSweep } from '../services/runtime-secret-request-maintenance'; import { checkProvisioningTimeouts } from '../services/timeout'; import { migrateOrphanedWorkspaces } from '../services/workspace-migration'; import { runWorkspaceResourceHistoryCleanup } from '../services/workspace-resource-history'; -import { runAnalyticsForwardJob } from './analytics-forward'; import { runScheduledCapacityPoolContinuations } from './capacity-pool-continuation'; import { runScheduledCapacityPoolReconciliation } from './capacity-pool-reconciliation'; import { runScheduledComposeImageArtifactCleanup } from './compose-image-artifact-cleanup'; import { runComputeUsageCleanup } from './compute-usage-cleanup'; import { runCronTriggerSweep } from './cron-triggers'; import { runScheduledDeploymentReleaseRetention } from './d1-retention'; -import { runDebugPackagePurge } from './debug-package-purge'; +import { DAILY_CRON, scheduleDailyJobs } from './daily-jobs'; import { runDeploymentNodeCleanup } from './deployment-node-cleanup'; import { runDeploymentPublishJobSweep } from './deployment-publish-jobs'; import { notifyFailedSweeps } from './failed-sweep-notifications'; import { runIncidentTriggerSweep } from './incident-triggers'; import { runNodeCleanupSweep } from './node-cleanup'; import { runObservabilityPurge } from './observability-purge'; -import { runOperationsAuditPurge } from './operations-audit-purge'; -import { runOperationsTelemetryRetention } from './operations-telemetry-retention'; import { isHourlyPlatformMaintenanceCron, scheduleHourlyPlatformMaintenance, @@ -95,7 +87,7 @@ export async function scheduled( } return; } - const isDailyForward = controller.cron === '0 3 * * *'; + const isDailyForward = controller.cron === DAILY_CRON; const isMonthlyCostAggregation = isHourlyPlatformMaintenanceCron(controller.cron); const cronType = isDailyForward @@ -109,41 +101,7 @@ export async function scheduled( if (scheduleHourlyPlatformMaintenance(controller.cron, env, ctx.waitUntil.bind(ctx))) return; if (isDailyForward) { - ctx.waitUntil( - (async () => { - const forward = await runAnalyticsForwardJob(env); - log.info('cron.completed', { - cron: controller.cron, - type: 'daily-forward', - forwardEnabled: forward.enabled, - forwardSkipReason: forward.skipReason ?? null, - forwardEventsQueried: forward.eventsQueried, - forwardSegmentSent: forward.segment.sent, - forwardGA4Sent: forward.ga4.sent, - forwardCursorUpdated: forward.cursorUpdated, - }); - })() - ); - // Separate promise: an analytics failure must not skip the audit retention purge. - ctx.waitUntil(runOperationsAuditPurge(env, controller.cron)); - ctx.waitUntil(runDebugPackagePurge(env, controller.cron)); - ctx.waitUntil(runOperationsTelemetryRetention(env, controller.cron)); - // Expired collected secret values are already refused at read time; this deletes them. - ctx.waitUntil( - purgeRuntimeSecretMaterial(env).catch((err) => { - log.error('cron.runtime_secret_purge_failed', { - error: err instanceof Error ? err.message : String(err), - }); - }) - ); - // Separate promise again, so none of the jobs above can suppress the latency check. - ctx.waitUntil( - runLifecycleLatencyDailyEvaluation(env).catch((err) => { - log.error('cron.lifecycle_latency_daily_failed', { - error: err instanceof Error ? err.message : String(err), - }); - }) - ); + scheduleDailyJobs(env, controller.cron, ctx.waitUntil.bind(ctx)); return; } @@ -200,12 +158,6 @@ export async function scheduled( const nodeTunnelCleanup = await sweeps.isolate('node_tunnel_cleanup', () => runNodeTunnelCleanupSweep(env) ); - // Backstop for every reverse-tunnel lease whose incarnation is no longer live (node row - // hard-deleted, incarnation replaced, termination proof): one D1 statement, no external I/O. - // A no-op without a D1 call unless VM_AGENT_TRANSPORT='reverse-tunnel' (skip reason logged). - const reverseTunnelLeases = await sweeps.isolate('reverse_tunnel_lease_release', () => - runReverseTunnelLeaseSweep(env) - ); let providerOrphans: Awaited> | undefined; await sweeps.isolate('provider_orphan_reconciliation', async () => { const result = await runProviderOrphanReconciliation(env); @@ -240,6 +192,16 @@ export async function scheduled( ); // Two indexed reads per idle tick; work is capped by inbox.sweepBatchSize. const inboxAskSweep = await sweeps.isolate('inbox_ask_sweep', () => runInboxAskSweep(env)); + // One indexed scan of recently failed tasks plus one UPDATE per idle tick; filings capped by + // inbox.errorSweepBatchSize (`services/inbox/system-errors.ts`). + const inboxSystemErrorSweep = await sweeps.isolate('inbox_system_error_sweep', () => + runInboxSystemErrorSweep(env) + ); + // Failing or auto-paused automations: bounded by inbox.errorSweepBatchSize + // (`services/inbox/automation-errors.ts`). + const inboxAutomationErrorSweep = await sweeps.isolate('inbox_automation_error_sweep', () => + runInboxAutomationErrorSweep(env) + ); const sessionTaskRepair = await sweeps.isolate('session_task_reconciliation', () => runSessionTaskReconciliation(env) ); @@ -351,11 +313,6 @@ export async function scheduled( nodeTunnelsReleased: nodeTunnelCleanup?.released, nodeTunnelCleanupsAttempted: nodeTunnelCleanup?.attempted, nodeTunnelsCleaned: nodeTunnelCleanup?.cleaned, - reverseTunnelLeasesReleased: reverseTunnelLeases?.released, - reverseTunnelLeaseSweepSkipReason: - reverseTunnelLeases && 'skipReason' in reverseTunnelLeases - ? reverseTunnelLeases.skipReason - : undefined, orphanedWorkspacesFlagged: nodeCleanup?.orphanedWorkspacesFlagged, orphanedNodesDestroyed: nodeCleanup?.orphanedNodesDestroyed, orphanedNodesSkipped: nodeCleanup?.orphanedNodesSkipped, @@ -424,6 +381,10 @@ export async function scheduled( secretRequestNoticesRetried: secretRequestSweep?.noticesRetried, inboxAsksExpired: inboxAskSweep?.expired, inboxAskNoticesRetried: inboxAskSweep?.noticesRetried, + inboxSystemErrorsFiled: inboxSystemErrorSweep?.filed, + inboxSystemErrorsClosed: inboxSystemErrorSweep?.closed, + inboxAutomationErrorsFiled: inboxAutomationErrorSweep?.filed, + inboxAutomationErrorsClosed: inboxAutomationErrorSweep?.closed, sessionTaskRepairScanned: sessionTaskRepair?.scanned, sessionTaskRepairRepaired: sessionTaskRepair?.repaired, sessionTaskRepairReused: sessionTaskRepair?.reused, diff --git a/apps/api/src/scheduled/stuck-tasks.ts b/apps/api/src/scheduled/stuck-tasks.ts index 39646146c9..9dec1f2c82 100644 --- a/apps/api/src/scheduled/stuck-tasks.ts +++ b/apps/api/src/scheduled/stuck-tasks.ts @@ -316,7 +316,8 @@ export async function selectStuckTaskCandidates( const forward = await env.DATABASE.prepare( `SELECT ${STUCK_TASK_CANDIDATE_COLUMNS} FROM tasks - WHERE status IN ('queued', 'delegated', 'in_progress') + WHERE (status IN ('queued', 'delegated', 'in_progress') + OR (status='sleeping' AND admission_state='provider_limit_recovery_pending')) AND (updated_at, id) > (?, ?) ORDER BY updated_at ASC, id ASC LIMIT ?` @@ -333,7 +334,8 @@ export async function selectStuckTaskCandidates( FROM ( SELECT ${STUCK_TASK_CANDIDATE_COLUMNS} FROM tasks - WHERE status IN ('queued', 'delegated', 'in_progress') + WHERE (status IN ('queued', 'delegated', 'in_progress') + OR (status='sleeping' AND admission_state='provider_limit_recovery_pending')) ORDER BY updated_at DESC, id DESC LIMIT ? ) @@ -350,7 +352,8 @@ export async function selectStuckTaskCandidates( const wrap = await env.DATABASE.prepare( `SELECT ${STUCK_TASK_CANDIDATE_COLUMNS} FROM tasks - WHERE status IN ('queued', 'delegated', 'in_progress') + WHERE (status IN ('queued', 'delegated', 'in_progress') + OR (status='sleeping' AND admission_state='provider_limit_recovery_pending')) AND (updated_at, id) <= (?, ?) ORDER BY updated_at ASC, id ASC LIMIT ?` @@ -1314,7 +1317,7 @@ export async function recoverStuckTasks(env: Env): Promise { reason = `Instant session start accepted but still queued for ${Math.round(elapsedMs / 1000)}s (threshold: ${Math.round(instantStartStaleTimeoutMs / 1000)}s).${stepInfo} Background container launch may not have completed.`; } else if (elapsedMs > queuedTimeoutMs) { isStuck = true; - reason = `Task stuck in 'queued' for ${Math.round(elapsedMs / 1000)}s (threshold: ${Math.round(queuedTimeoutMs / 1000)}s).${stepInfo} Node provisioning may have failed silently.`; + reason = `Task stuck in 'queued' without recorded orchestration progress for ${Math.round(elapsedMs / 1000)}s (threshold: ${Math.round(queuedTimeoutMs / 1000)}s).${stepInfo}`; } break; case 'delegated': @@ -1639,6 +1642,14 @@ export async function recoverStuckTasks(env: Env): Promise { taskId: task.id, projectId: task.project_id, status: terminalStatus, + // holdTaskForProviderLimit release and placement may advance this row + // across any await above. The verdict belongs to this exact observation, + // never the newer status loaded by transitionTaskToTerminal (rule 58). + expectedTaskVersion: { + status: task.status, + workspaceId: task.workspace_id, + updatedAt: task.updated_at, + }, reason, source: compactionLoopRecovery ? 'scheduled.stuck_tasks.compaction_loop' diff --git a/apps/api/src/schemas/acp-sessions.ts b/apps/api/src/schemas/acp-sessions.ts index a0df624e1d..0466dc8f27 100644 --- a/apps/api/src/schemas/acp-sessions.ts +++ b/apps/api/src/schemas/acp-sessions.ts @@ -1,4 +1,8 @@ -import { DEFAULT_CREDENTIAL_LIMIT_MAX_OBSERVATIONS_PER_REPORT } from '@simple-agent-manager/shared'; +import { + DEFAULT_CREDENTIAL_LIMIT_MAX_OBSERVATIONS_PER_REPORT, + RUN_USAGE_MAX_MODELS_PER_REPORT, + RUN_USAGE_MAX_TOKENS_PER_COUNTER, +} from '@simple-agent-manager/shared'; import * as v from 'valibot'; const UsageIdentifierSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(160)); @@ -72,6 +76,39 @@ export const AcpSessionUsageLimitObservationSchema = v.object({ freshnessMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))), }); +/** + * A token counter in one usage report. The ceiling (one trillion) is far above any real run and + * keeps summed reads well inside SQLite's integer range whatever a reporter sends. + */ +const TokenCountSchema = v.pipe( + v.number(), + v.integer(), + v.minValue(0), + v.maxValue(RUN_USAGE_MAX_TOKENS_PER_COUNTER) +); + +/** + * Insights slice U: cumulative token totals of one VM-agent usage epoch, per model. Optional, so an + * old agent (no field) and a new agent (field present) both pass; an old control plane strips it. + */ +export const AcpSessionTokenUsageSchema = v.object({ + epoch: UsageIdentifierSchema, + models: v.pipe( + v.array( + v.object({ + // '' or absent: the harness did not say which model ran. + model: v.optional(v.pipe(v.string(), v.maxLength(160))), + inputTokens: TokenCountSchema, + outputTokens: TokenCountSchema, + cacheReadTokens: v.optional(TokenCountSchema), + cacheWriteTokens: v.optional(TokenCountSchema), + reasoningTokens: v.optional(TokenCountSchema), + }) + ), + v.maxLength(RUN_USAGE_MAX_MODELS_PER_REPORT) + ), +}); + export const AcpSessionUsageReportSchema = v.object({ nodeId: UsageIdentifierSchema, agentType: v.optional(UsageIdentifierSchema), @@ -84,6 +121,7 @@ export const AcpSessionUsageReportSchema = v.object({ v.array(AcpSessionUsageLimitObservationSchema), v.maxLength(DEFAULT_CREDENTIAL_LIMIT_MAX_OBSERVATIONS_PER_REPORT) ), + tokenUsage: v.optional(AcpSessionTokenUsageSchema), }); export const AcpSessionForkSchema = v.object({ diff --git a/apps/api/src/selfhost/build.ts b/apps/api/src/selfhost/build.ts new file mode 100644 index 0000000000..3f894411c6 --- /dev/null +++ b/apps/api/src/selfhost/build.ts @@ -0,0 +1,19 @@ +/** + * What the self-host (celld) build adds to the shared Worker entry, applied once by the generated + * celld entry (`scripts/selfhost/celld-project.ts`) before any request. `apps/api/src/index.ts` + * never imports this module, so the Cloudflare bundle carries none of it + * (tests/unit/selfhost/reverse-tunnel-placement.test.ts). + * + * - speech-to-text and read-aloud through admin-configured endpoints (`speech/`, L14); + * - the reverse-tunnel transport, gateway routes and lease sweep (`reverse-tunnel/entry.ts`, + * L17b), with the shared cloud-init generator as the frpc boot renderer. + */ +import { generateCloudInit } from '@simple-agent-manager/cloud-init'; + +import { type SharedWorkerEntry, withReverseTunnel } from './reverse-tunnel/entry'; +import { installSpeechEndpoints } from './speech'; + +export function withSelfHostBuild(worker: T): T { + installSpeechEndpoints(); + return withReverseTunnel(worker, generateCloudInit); +} diff --git a/apps/api/src/selfhost/hosted-git.ts b/apps/api/src/selfhost/hosted-git.ts index ecefc05e40..9c37211017 100644 --- a/apps/api/src/selfhost/hosted-git.ts +++ b/apps/api/src/selfhost/hosted-git.ts @@ -9,18 +9,27 @@ * binding and the class's migration (`SELFHOST_DURABLE_OBJECTS` in * scripts/selfhost/selfhost-durable-objects.ts); `apps/api/wrangler.toml` does not. * - * The rest of hosted git is shared code: `services/hosted-git/` selects Cloudflare Artifacts or - * this git server (`resolveArtifactsBackend`) and reaches the Durable Object only through the + * Loading this module also registers SAM's own git server as the Artifacts fallback in the shared + * seam (`registerArtifactsBackendFallback` in `services/hosted-git/backend.ts`), so project + * creation, browsing, git tokens and deletion use it when no Cloudflare Artifacts binding exists. + * The backend (`services/hosted-git/local-backend.ts`) reaches the Durable Object only through the * `HOSTED_GIT` namespace binding, which exists only on a self-host deployment. */ import type { Hono } from 'hono'; import type { Env } from '../env'; -import { isLocalHostedGitActive } from '../services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../services/hosted-git/backend'; import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from '../services/hosted-git/http'; +import { + isLocalHostedGitActive, + localHostedGitBackendFallback, +} from '../services/hosted-git/local-backend'; export { HostedGitRepo } from '../durable-objects/hosted-git-repo'; +// Once, at module load: the celld entry imports this module before any request is served. +registerArtifactsBackendFallback(localHostedGitBackendFallback); + /** * Mounts git smart HTTP for SAM-hosted repositories (`/git/.git/...`). Authenticated per * request with a repository token, not a session cookie. Inactive (falls through to the 404 diff --git a/apps/api/src/selfhost/key-rotation/control.ts b/apps/api/src/selfhost/key-rotation/control.ts index 43edd1a61c..d392359735 100644 --- a/apps/api/src/selfhost/key-rotation/control.ts +++ b/apps/api/src/selfhost/key-rotation/control.ts @@ -64,7 +64,7 @@ function rotatingRoles(env: KeyRotationEnv): Record { /** * Active reverse-tunnel leases created before `before` (the switch to the new key): their frp - * credential is an HMAC under the old ENCRYPTION_KEY (node-reverse-tunnel-config.ts), so whoever + * credential is an HMAC under the old ENCRYPTION_KEY (selfhost/reverse-tunnel/config.ts), so whoever * holds that key and the lease ids can still log in to frps as those nodes until they are * replaced. Reported, not fixed: re-credentialing a live node needs the VM agent. Null when * unknown (no `before`, or the table cannot be read). diff --git a/apps/api/src/db/migrations/0232_node_reverse_tunnel_leases.sql b/apps/api/src/selfhost/migrations/0255_node_reverse_tunnel_leases.sql similarity index 88% rename from apps/api/src/db/migrations/0232_node_reverse_tunnel_leases.sql rename to apps/api/src/selfhost/migrations/0255_node_reverse_tunnel_leases.sql index 8e818b95a6..35fbc869fb 100644 --- a/apps/api/src/db/migrations/0232_node_reverse_tunnel_leases.sql +++ b/apps/api/src/selfhost/migrations/0255_node_reverse_tunnel_leases.sql @@ -11,7 +11,9 @@ -- Release frees the port: status becomes 'released' (rows are never deleted). Released rows keep -- their port for history and for least-recently-released port reuse. -- --- Existing rows: none. Additive only; no triggers (D1 counts trigger writes in meta.changes, which +-- Fresh installs have no rows. Upgrades from integration migration0232 preserve its existing +-- leases and indexes through IF NOT EXISTS; renumbering never recreates the table. +-- Additive only; no triggers (D1 counts trigger writes in meta.changes, which -- would break the compare-and-set writers of this table). CREATE TABLE IF NOT EXISTS node_reverse_tunnel_leases ( id TEXT PRIMARY KEY, diff --git a/apps/api/src/selfhost/reverse-tunnel-migrations.ts b/apps/api/src/selfhost/reverse-tunnel-migrations.ts new file mode 100644 index 0000000000..93becb15d7 --- /dev/null +++ b/apps/api/src/selfhost/reverse-tunnel-migrations.ts @@ -0,0 +1,8 @@ +/** + * Paths relative to apps/api/src. The self-host packager appends these to DATABASE's + * flat migration projection AFTER shared SQL. Never add them to wrangler.toml's directory. + * A formerly deployed 0232 table is preserved by the additive IF NOT EXISTS DDL. + */ +export const REVERSE_TUNNEL_MIGRATIONS = [ + 'selfhost/migrations/0255_node_reverse_tunnel_leases.sql', +] as const; diff --git a/apps/api/src/services/node-reverse-tunnel-authz.ts b/apps/api/src/selfhost/reverse-tunnel/authz.ts similarity index 70% rename from apps/api/src/services/node-reverse-tunnel-authz.ts rename to apps/api/src/selfhost/reverse-tunnel/authz.ts index 2982da850a..c88dc684d4 100644 --- a/apps/api/src/services/node-reverse-tunnel-authz.ts +++ b/apps/api/src/selfhost/reverse-tunnel/authz.ts @@ -1,41 +1,10 @@ -/** - * Authorization decisions for the box's frps server plugin (Login, NewProxy, Ping, NewWorkConn). - * - * frps is the only party that holds per-node tunnel listeners, and it asks SAM before every - * login, every proxy registration, every heartbeat and every work connection. SAM answers from - * values IT stored: - * - * 1. the presented credential's SHA-256 equals the lease row's `credential_hash` - * (constant-time), for the exact (node id, incarnation) the frpc claims; - * 2. the lease is `active` and its incarnation is the node row's live incarnation of a managed - * reverse-tunnel VM that is not being torn down; - * 3. on NewProxy, the proxy is the node's one `tcp` proxy and binds exactly the leased port. - * - * A node holding a valid credential for itself therefore cannot bind another node's port, - * claim another node's identity, or keep a released lease alive: Ping re-runs 1-2, so frps - * drops a session within one heartbeat of the lease being released. Anything malformed, - * unknown or unsupported is refused (fail closed). - * - * NewWorkConn (verified against frps 0.72.0, server/service.go RegisterWorkConn): the content is - * `{ user: { user, metas, run_id }, run_id }`, where `user` is copied from the CONTROL session - * that owns the presented run_id, not from the dialing connection, and nothing in it describes - * the dialer (no address, no privilege key without auth.additionalScopes). So the plugin binds - * each work connection to that control's lease (1-2 again), which refuses work connections into - * a released or superseded lease immediately instead of at the next Ping. The run_id equality - * is a consistency check only (frps looked the control up by that run_id), kept so a change in - * frps' payload fails closed. The plugin cannot tell the owner from another party presenting - * the owner's run_id: that rests on the run_id being unknown to other nodes. frps assigns a - * 64-bit crypto/rand value (util.RandID) when a client logs in without one and returns it only - * on that client's TLS session; a client may choose its own run_id at Login, which only weakens - * its own sessions. SAM never logs run_ids. - */ -import { REVERSE_TUNNEL_PROXY_NAME } from '@simple-agent-manager/cloud-init'; +const REVERSE_TUNNEL_PROXY_NAME = 'sam-agent'; import * as v from 'valibot'; -import type { Env } from '../env'; -import { constantTimeEqual } from '../lib/constant-time'; -import { log } from '../lib/logger'; -import { hashReverseTunnelCredential } from './node-reverse-tunnel-config'; +import { constantTimeEqual } from '../../lib/constant-time'; +import { log } from '../../lib/logger'; +import { deriveReverseTunnelRunId, hashReverseTunnelCredential } from './config'; +import type { ReverseTunnelEnv as Env } from './env'; export type FrpsPluginOp = 'Login' | 'NewProxy' | 'Ping' | 'NewWorkConn'; export const FRPS_PLUGIN_OPS: readonly FrpsPluginOp[] = [ @@ -45,7 +14,7 @@ export const FRPS_PLUGIN_OPS: readonly FrpsPluginOp[] = [ 'NewWorkConn', ]; -export type FrpsPluginDecision = { allow: true } | { allow: false; reason: string; code: string }; +export type FrpsPluginDecision = { allow: true; replacementContent?: Record } | { allow: false; reason: string; code: string }; const BoundedString = v.pipe(v.string(), v.minLength(1), v.maxLength(256)); const MetasSchema = v.object({ @@ -53,7 +22,7 @@ const MetasSchema = v.object({ incarnation: BoundedString, credential: BoundedString, }); -const UserSchema = v.object({ user: BoundedString, metas: MetasSchema }); +const UserSchema = v.object({ user: BoundedString, metas: MetasSchema, run_id: BoundedString }); const LoginContentSchema = v.object({ user: BoundedString, metas: MetasSchema }); const NewProxyContentSchema = v.object({ user: UserSchema, @@ -78,9 +47,18 @@ interface LeaseAuthorityRow { nodeClass: string | null; nodeTransport: string | null; nodeIncarnation: string | null; + nodeUser: string | null; + leaseUser: string; nodeTerminatedAt: string | null; } +const LeaseAuthoritySchema = v.object({ + leaseId: v.string(), port: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), + credentialHash: v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/)), leaseStatus: v.string(), + nodeStatus: v.nullable(v.string()), nodeRuntime: v.nullable(v.string()), nodeClass: v.nullable(v.string()), + nodeTransport: v.nullable(v.string()), nodeIncarnation: v.nullable(v.string()), + nodeTerminatedAt: v.nullable(v.string()), nodeUser: v.nullable(v.string()), leaseUser: v.string(), +}); const NODE_TEARDOWN_STATUSES = new Set(['deleted', 'stopped', 'destroying']); function refuse(code: string, reason: string): FrpsPluginDecision { @@ -92,6 +70,7 @@ interface ClaimedIdentity { nodeId: string; incarnation: string; credential: string; + runId?: string; } function parseIdentity( @@ -100,8 +79,7 @@ function parseIdentity( ): { identity: ClaimedIdentity; proxy?: v.InferOutput; - /** NewWorkConn only: the work connection's run_id is the control session's own. */ - workConnRunIdMatches?: boolean; + workConnRunIdMatches?: boolean; } | null { if (op === 'Login') { const parsed = v.safeParse(LoginContentSchema, content); @@ -126,6 +104,7 @@ function parseIdentity( nodeId: user.metas.node_id, incarnation: user.metas.incarnation, credential: user.metas.credential, + runId: user.run_id, }, proxy: parsed.output, }; @@ -140,6 +119,7 @@ function parseIdentity( nodeId: user.metas.node_id, incarnation: user.metas.incarnation, credential: user.metas.credential, + runId: user.run_id, }, workConnRunIdMatches: runId === user.run_id, }; @@ -153,6 +133,7 @@ function parseIdentity( nodeId: user.metas.node_id, incarnation: user.metas.incarnation, credential: user.metas.credential, + runId: user.run_id, }, }; } @@ -162,24 +143,28 @@ async function readLeaseAuthority( nodeId: string, incarnation: string ): Promise { - return await env.DATABASE.prepare( + const row = await env.DATABASE.prepare( `SELECT l.id AS leaseId, l.port AS port, l.credential_hash AS credentialHash, l.status AS leaseStatus, n.status AS nodeStatus, n.runtime AS nodeRuntime, n.node_class AS nodeClass, n.transport AS nodeTransport, n.runtime_incarnation_id AS nodeIncarnation, + n.user_id AS nodeUser, l.user_id AS leaseUser, n.runtime_termination_confirmed_at AS nodeTerminatedAt FROM node_reverse_tunnel_leases l LEFT JOIN nodes n ON n.id = l.node_id WHERE l.node_id = ? AND l.runtime_incarnation_id = ?` ) .bind(nodeId, incarnation) - .first(); + .first(); + const parsed = v.safeParse(LeaseAuthoritySchema, row); + if (row && !parsed.success) log.warn('node_reverse_tunnel.invalid_authority', { nodeId, incarnation }); + return parsed.success ? parsed.output : null; } -/** The lease row's node is the live managed reverse-tunnel incarnation the frpc claims. */ function isLiveLeaseNode(lease: LeaseAuthorityRow, incarnation: string): boolean { return ( lease.nodeIncarnation === incarnation && + lease.nodeUser === lease.leaseUser && lease.nodeTerminatedAt === null && lease.nodeRuntime === 'vm' && lease.nodeClass === 'managed' && @@ -189,7 +174,6 @@ function isLiveLeaseNode(lease: LeaseAuthorityRow, incarnation: string): boolean ); } -/** NewProxy: exactly the node's one tcp proxy, on exactly its leased port. */ function newProxyRefusal( proxy: v.InferOutput, nodeId: string, @@ -205,7 +189,6 @@ function newProxyRefusal( return null; } -/** Credential, lease and node checks shared by every op. */ async function leaseRefusal( env: Pick, identity: ClaimedIdentity @@ -230,9 +213,8 @@ async function leaseRefusal( return { lease }; } -/** Decide one frps plugin request. Never throws for bad input; D1 failures propagate. */ export async function authorizeFrpsPluginRequest( - env: Pick, + env: Pick, op: string | undefined, body: unknown ): Promise { @@ -242,7 +224,7 @@ export async function authorizeFrpsPluginRequest( const pluginOp = op as FrpsPluginOp; const envelope = v.safeParse(BodySchema, body); const parsed = envelope.success ? parseIdentity(pluginOp, envelope.output.content) : null; - if (!parsed) return logged(pluginOp, null, refuse('malformed', 'malformed plugin request')); + if (!envelope.success || !parsed) return logged(pluginOp, null, refuse('malformed', 'malformed plugin request')); const { identity, proxy, workConnRunIdMatches } = parsed; if (workConnRunIdMatches === false) { return logged(pluginOp, identity, refuse('run_id_mismatch', 'work connection run id mismatch')); @@ -251,6 +233,12 @@ export async function authorizeFrpsPluginRequest( const checked = await leaseRefusal(env, identity); if ('refusal' in checked) return logged(pluginOp, identity, checked.refusal); const { lease } = checked; + const runId = await deriveReverseTunnelRunId(env, { + leaseId: lease.leaseId, nodeId: identity.nodeId, runtimeIncarnationId: identity.incarnation, + }); + if (pluginOp !== 'Login' && !constantTimeEqual(identity.runId ?? '', runId)) { + return logged(pluginOp, identity, refuse('session_mismatch', 'control session identity mismatch')); + } const proxyRefusal = proxy ? newProxyRefusal(proxy, identity.nodeId, lease.port) : null; if (proxyRefusal) return logged(pluginOp, identity, proxyRefusal); @@ -264,7 +252,10 @@ export async function authorizeFrpsPluginRequest( port: lease.port, }); } - return { allow: true }; + // Preserve every frp Login field. The gateway MUST use unchange:false for this decision. + return pluginOp === 'Login' + ? { allow: true, replacementContent: { ...envelope.output.content as Record, run_id: runId } } + : { allow: true }; } function logged( diff --git a/apps/api/src/services/node-reverse-tunnel-config.ts b/apps/api/src/selfhost/reverse-tunnel/config.ts similarity index 54% rename from apps/api/src/services/node-reverse-tunnel-config.ts rename to apps/api/src/selfhost/reverse-tunnel/config.ts index 3f796eedc3..5f8523359d 100644 --- a/apps/api/src/services/node-reverse-tunnel-config.ts +++ b/apps/api/src/selfhost/reverse-tunnel/config.ts @@ -1,62 +1,24 @@ -/** - * Configuration and credential primitives for the reverse-tunnel (frp) node transport. - * - * Topology (self-hosted control plane, VM_AGENT_TRANSPORT='reverse-tunnel'): frps runs on the - * control-plane box bound to loopback; each node's frpc dials `wss://api.{BASE_DOMAIN}/~!frp` - * and binds ONE tcp proxy at `127.0.0.1:{leasePort}` on the box. The Worker and Caddy reach the - * node agent at that address. Everything here is bootstrap configuration that must agree with - * the box's frps.toml and Caddy fragments (deploy/selfhost/), so it is not a runtime tunable. - */ -import { - REVERSE_TUNNEL_HEARTBEAT_INTERVAL_SECONDS, - REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, -} from '@simple-agent-manager/cloud-init'; +const REVERSE_TUNNEL_HEARTBEAT_INTERVAL_SECONDS = '30'; +const REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = '90'; -import type { Env } from '../env'; -import { constantTimeEqual } from '../lib/constant-time'; +import { constantTimeEqual } from '../../lib/constant-time'; +import type { ReverseTunnelEnv as Env } from './env'; -/** - * Address frps binds per-node proxies on (frps `proxyBindAddr`); the Worker and Caddy share it. - * Fixed, not configurable: anything but loopback would expose node agents beyond the box. - */ export const REVERSE_TUNNEL_UPSTREAM_HOST = '127.0.0.1'; -/** Default leased port range; must equal frps `allowPorts` in deploy/selfhost/frps/frps.toml. */ export const DEFAULT_REVERSE_TUNNEL_PORT_RANGE_START = 20000; export const DEFAULT_REVERSE_TUNNEL_PORT_RANGE_END = 29999; -/** - * Upper bound on the range size. Allocation enumerates the range inside one SQL statement (a - * recursive CTE with one indexed lookup per candidate), so the worst case is one statement - * walking 20k rows per node provisioning: milliseconds on SQLite, well inside D1's statement - * limits, and provisioning is rare. Without the bound an accidental `1-65535` would walk 64k. - */ export const MAX_REVERSE_TUNNEL_PORT_RANGE_SIZE = 20000; -/** The gateway secret is a random token shared with frps and Caddy; refuse anything guessable. */ export const MIN_REVERSE_TUNNEL_GATEWAY_SECRET_LENGTH = 32; -/** - * frps drops a node that has not heartbeated for this long (frps `transport.heartbeatTimeout`). - * The box's deploy script resolves ONE value and writes it to both frps (gateway.env) and the - * Worker (REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS), so the port-reuse age below is derived - * from the timeout frps actually enforces. Default = the frpc-side timeout cloud-init renders. - */ export const DEFAULT_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = Number( REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS ); -/** frpc pings every 30 s; a timeout under two intervals would drop healthy nodes. */ export const MIN_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = 2 * Number(REVERSE_TUNNEL_HEARTBEAT_INTERVAL_SECONDS); export const MAX_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = 3600; -/** - * A released port is not reissued until it has been released for at least this many heartbeat - * timeouts. Within one timeout frps has dropped any session that stopped pinging; a session - * still pinging is refused (Ping re-checks the lease) within one frpc interval. Twice the - * timeout leaves margin for both, so a new node's traffic (with the Worker-injected - * Authorization and node management tokens) can never land on the previous holder's frpc. - */ export const REVERSE_TUNNEL_PORT_REUSE_HEARTBEAT_MULTIPLE = 2; export const DEFAULT_REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS = REVERSE_TUNNEL_PORT_REUSE_HEARTBEAT_MULTIPLE * DEFAULT_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS; -/** Upper bound on the reuse age: past a day a port is effectively never reused. */ export const MAX_REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS = 86_400; const CREDENTIAL_LABEL = 'sam-reverse-tunnel-credential:v1'; @@ -71,7 +33,6 @@ export type ReverseTunnelEnv = Pick< | 'REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS' >; -/** The leased port range settings alone (route resolution needs no secret). */ export type ReverseTunnelRangeEnv = Pick< Env, 'REVERSE_TUNNEL_PORT_RANGE_START' | 'REVERSE_TUNNEL_PORT_RANGE_END' @@ -91,7 +52,6 @@ function parsePort(name: string, raw: string | undefined, fallback: number): num return Number(value); } -/** The leased port range. Fails closed on a malformed or oversized range. */ export function resolveReverseTunnelPortRange(env: ReverseTunnelRangeEnv): ReverseTunnelPortRange { const start = parsePort( 'REVERSE_TUNNEL_PORT_RANGE_START', @@ -133,7 +93,6 @@ function parseSeconds( return parsed; } -/** frps' heartbeat timeout as the Worker was told it (same resolved value as gateway.env). */ export function resolveReverseTunnelHeartbeatTimeoutSeconds( env: Pick ): number { @@ -148,11 +107,6 @@ export function resolveReverseTunnelHeartbeatTimeoutSeconds( ); } -/** - * Minimum age of a port's latest release before allocation may reissue it. Defaults to - * {@link REVERSE_TUNNEL_PORT_REUSE_HEARTBEAT_MULTIPLE} x the heartbeat timeout; an override may - * lengthen it but never shorten it below that floor (fails closed: no lease is written). - */ export function resolveReverseTunnelPortReuseMinAgeSeconds( env: Pick< Env, @@ -176,13 +130,6 @@ export function resolveReverseTunnelPortReuseMinAgeSeconds( return configured; } -/** - * Fail-closed membership check for a lease port about to become an upstream (a Worker fetch - * target or Caddy's X-SAM-Upstream). The lease table should only ever hold in-range ports, but - * the upstream is loopback on the control-plane box, next to celld's operator listener, frps - * and the object store, so a row outside the range (a manual edit, a range shrunk under live - * leases, a bug) must never be routed to. Throws on an out-of-range port or a malformed range. - */ export function assertReverseTunnelUpstreamPort(env: ReverseTunnelRangeEnv, port: number): void { const range = resolveReverseTunnelPortRange(env); if (!Number.isInteger(port) || port < range.start || port > range.end) { @@ -192,19 +139,11 @@ export function assertReverseTunnelUpstreamPort(env: ReverseTunnelRangeEnv, port } } -/** The configured gateway secret, or null when absent/too short (callers fail closed). */ export function getReverseTunnelGatewaySecret(env: ReverseTunnelEnv): string | null { const secret = env.REVERSE_TUNNEL_GATEWAY_SECRET?.trim() ?? ''; return secret.length >= MIN_REVERSE_TUNNEL_GATEWAY_SECRET_LENGTH ? secret : null; } -/** - * Whether `presented` is the gateway secret. During a self-hosted rotation the Worker also - * accepts REVERSE_TUNNEL_GATEWAY_SECRET_ALTERNATE, so frps, Caddy and sam-mx can be restarted - * with the new value while the Worker answers both (scripts/selfhost/secrets-rotate-steps.ts). - * Both comparisons always run (constant time); the alternate needs the same minimum length. - * Callers check getReverseTunnelGatewaySecret first: without a primary nothing is accepted. - */ export function isAcceptedGatewaySecret(env: ReverseTunnelEnv, presented: string): boolean { const primary = getReverseTunnelGatewaySecret(env); if (!primary) return false; @@ -216,15 +155,14 @@ export function isAcceptedGatewaySecret(env: ReverseTunnelEnv, presented: string return primaryMatch || alternateMatch; } -/** `http://127.0.0.1:{port}`: where the Worker and Caddy reach a reverse-tunnel node's agent. */ export function reverseTunnelUpstreamOrigin(port: number): string { return `http://${REVERSE_TUNNEL_UPSTREAM_HOST}:${port}`; } function base64Url(bytes: ArrayBuffer): string { let binary = ''; - for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte); - return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); + for (const byte of new Uint8Array(bytes)) binary += String.fromCodePoint(byte); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); } function hex(bytes: ArrayBuffer): string { @@ -237,30 +175,38 @@ export interface ReverseTunnelCredentialIdentity { runtimeIncarnationId: string; } -/** - * The node's frp credential: HMAC-SHA256 of the lease identity under the Worker-only - * ENCRYPTION_KEY, with a purpose label for domain separation. Deterministic so a durable - * provisioning resume can re-render the same cloud-init without storing the plaintext; the - * lease row stores only its SHA-256. SECRET: cloud-init only, never logged or persisted. - */ -export async function deriveReverseTunnelCredential( +/** HKDF creates separate HMAC keys for credentials and frps control-session identities. */ +async function signIdentity( env: Pick, + purpose: string, identity: ReverseTunnelCredentialIdentity -): Promise { - if (!env.ENCRYPTION_KEY) - throw new Error('ENCRYPTION_KEY is required for reverse-tunnel credentials'); - const key = await crypto.subtle.importKey( - 'raw', - new TextEncoder().encode(env.ENCRYPTION_KEY), - { name: 'HMAC', hash: 'SHA-256' }, - false, - ['sign'] +): Promise { + if (!env.ENCRYPTION_KEY) throw new Error('ENCRYPTION_KEY is required for reverse-tunnel credentials'); + for (const value of Object.values(identity)) { + if (!value || value.length > 256) throw new Error('Reverse-tunnel identity is required and bounded'); + } + const encoder = new TextEncoder(); + const root = await crypto.subtle.importKey('raw', encoder.encode(env.ENCRYPTION_KEY), 'HKDF', false, ['deriveKey']); + const key = await crypto.subtle.deriveKey( + { name: 'HKDF', hash: 'SHA-256', salt: encoder.encode('sam:reverse-tunnel:v1'), info: encoder.encode(purpose) }, + root, { name: 'HMAC', hash: 'SHA-256', length: 256 }, false, ['sign'] ); - const message = `${CREDENTIAL_LABEL}\n${identity.leaseId}\n${identity.nodeId}\n${identity.runtimeIncarnationId}`; - return base64Url(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message))); + return crypto.subtle.sign('HMAC', key, encoder.encode(JSON.stringify([ + identity.leaseId, identity.nodeId, identity.runtimeIncarnationId, + ]))); +} +export async function deriveReverseTunnelCredential( + env: Pick, identity: ReverseTunnelCredentialIdentity +): Promise { + return base64Url(await signIdentity(env, CREDENTIAL_LABEL, identity)); +} +/** frps replaces the previous control before activating another with this same server-chosen id. */ +export async function deriveReverseTunnelRunId( + env: Pick, identity: ReverseTunnelCredentialIdentity +): Promise { + return hex(await signIdentity(env, 'sam-reverse-tunnel-control:v1', identity)).slice(0, 32); } -/** SHA-256 hex of a presented or minted credential; the only form ever stored. */ export async function hashReverseTunnelCredential(credential: string): Promise { return hex(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(credential))); } diff --git a/apps/api/src/selfhost/reverse-tunnel/entry.ts b/apps/api/src/selfhost/reverse-tunnel/entry.ts new file mode 100644 index 0000000000..ab15af983f --- /dev/null +++ b/apps/api/src/selfhost/reverse-tunnel/entry.ts @@ -0,0 +1,92 @@ +/** + * The self-host build's reverse-tunnel entry: the ONLY place the reverse tunnel is mounted. + * The generated celld entry wraps the shared Worker with it; `apps/api/src/index.ts` never + * imports it (tests/unit/selfhost/reverse-tunnel-placement.test.ts), so the Cloudflare Worker + * carries no gateway route, no lease SQL and no reverse sweep. + * + * - installs the transport driver (provisioning, release, routing) with L18's boot renderer; + * - serves `SELF_HOST_GATEWAY_PATH_PREFIX/*` before the shared app, which never sees those + * paths, so no session middleware or wildcard can shadow them; + * - runs the lease backstop sweep on the shared five-minute sweep cron, after and isolated + * from the shared scheduled handler, honouring the operational cron kill switch. + */ +import type { Context } from 'hono'; + +import type { Env } from '../../env'; +import { log, serializeError } from '../../lib/logger'; +import { DAILY_CRON } from '../../scheduled/daily-jobs'; +import { isHourlyPlatformMaintenanceCron } from '../../scheduled/platform-feedback-hourly'; +import { CAPACITY_POOL_CONTINUATION_CRON } from '../../services/capacity-pool-refresh-defaults'; +import { isOperationalLoopEnabled } from '../../services/operational-kill-switch'; +import type { ReverseTunnelEnv } from './env'; +import { createSelfHostGatewayRoutes, SELF_HOST_GATEWAY_PATH_PREFIX } from './gateway'; +import { runReverseTunnelLeaseSweep } from './leases'; +import { installReverseTunnelTransport, type ReverseTunnelBootVariables } from './transport'; + +export interface SharedWorkerEntry { + fetch(request: Request, env: Env, ctx: Context['executionCtx']): Response | Promise; + scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise; +} + +/** The shared handler's five-minute sweep tick (every cron that is not a dedicated one). */ +export function isReverseTunnelSweepCron(cron: string): boolean { + return ( + cron !== CAPACITY_POOL_CONTINUATION_CRON && + cron !== DAILY_CRON && + !isHourlyPlatformMaintenanceCron(cron) + ); +} + +/** One isolated backstop pass. Never throws; logs its result or why it did nothing. */ +export async function runReverseTunnelSweepTick( + env: ReverseTunnelEnv, + cron: string +): Promise { + try { + if (!(await isOperationalLoopEnabled(env, 'cron'))) { + log.info('cron.reverse_tunnel_lease_sweep', { cron, skipReason: 'cron_disabled' }); + return; + } + const result = await runReverseTunnelLeaseSweep(env); + log.info('cron.reverse_tunnel_lease_sweep', { + cron, + released: result.released, + skipReason: 'skipReason' in result ? result.skipReason : null, + }); + } catch (err) { + log.error('cron.reverse_tunnel_lease_sweep_failed', { cron, ...serializeError(err) }); + } +} + +export function withReverseTunnel( + worker: T, + render: (variables: ReverseTunnelBootVariables) => string +): T { + installReverseTunnelTransport(render); + const gateway = createSelfHostGatewayRoutes((request, env, ctx) => + worker.fetch(request, env, ctx) + ); + return { + ...worker, + fetch(request: Request, env: Env, ctx: Context['executionCtx']) { + const path = new URL(request.url).pathname; + if ( + path === SELF_HOST_GATEWAY_PATH_PREFIX || + path.startsWith(`${SELF_HOST_GATEWAY_PATH_PREFIX}/`) + ) { + return gateway.fetch(request, env, ctx); + } + return worker.fetch(request, env, ctx); + }, + async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext) { + try { + await worker.scheduled(controller, env, ctx); + } finally { + // The shared handler isolates its own steps; this backstop still runs if it throws. + if (isReverseTunnelSweepCron(controller.cron)) { + await runReverseTunnelSweepTick(env, controller.cron); + } + } + }, + }; +} diff --git a/apps/api/src/selfhost/reverse-tunnel/env.ts b/apps/api/src/selfhost/reverse-tunnel/env.ts new file mode 100644 index 0000000000..d628098cbf --- /dev/null +++ b/apps/api/src/selfhost/reverse-tunnel/env.ts @@ -0,0 +1,14 @@ +/** Self-host bootstrap settings. These never become Cloudflare Worker bindings. */ +import type { Env } from '../../env'; + +export interface ReverseTunnelEnv extends Env { + REVERSE_TUNNEL_GATEWAY_SECRET?: string; + REVERSE_TUNNEL_GATEWAY_SECRET_ALTERNATE?: string; + REVERSE_TUNNEL_PORT_RANGE_START?: string; + REVERSE_TUNNEL_PORT_RANGE_END?: string; + REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS?: string; + REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS?: string; +} +export function isReverseTunnelInstallation(env: Pick): boolean { + return env.VM_AGENT_TRANSPORT?.trim() === 'reverse-tunnel'; +} diff --git a/apps/api/src/routes/self-host-gateway.ts b/apps/api/src/selfhost/reverse-tunnel/gateway.ts similarity index 61% rename from apps/api/src/routes/self-host-gateway.ts rename to apps/api/src/selfhost/reverse-tunnel/gateway.ts index d982326501..bd1901b8f2 100644 --- a/apps/api/src/routes/self-host-gateway.ts +++ b/apps/api/src/selfhost/reverse-tunnel/gateway.ts @@ -1,44 +1,42 @@ /** - * Internal endpoints for the self-hosted box's gateway processes (deploy/selfhost/): + * Internal endpoints for the self-hosted box's gateway processes (deploy/selfhost/), mounted + * only by the self-host entry (`entry.ts`); the Cloudflare Worker never loads this module. * - * - `POST /frps-plugin?op=Login|NewProxy|Ping|NewWorkConn` — frps server plugin. Authenticated with HTTP - * basic auth whose password is REVERSE_TUNNEL_GATEWAY_SECRET (frps sends the userinfo of - * its plugin `addr`). Decisions: services/node-reverse-tunnel-authz.ts. - * - `GET /node-websocket` — Caddy forward_auth for node WebSocket upgrades. Authenticated with - * the `X-SAM-Gateway-Secret` header. It re-dispatches the original request through the SAM - * app so the EXISTING ws-* / logs-stream authentication runs unchanged - * (services/node-websocket-gateway.ts), and returns either that handler's refusal (401, 302 - * port-token redirect, 403, 503, ...) for Caddy to send to the client, or a decision naming - * the loopback upstream and the headers Caddy must forward. + * - `POST {prefix}/frps-plugin?op=Login|NewProxy|Ping|NewWorkConn`: frps server plugin, + * authenticated with HTTP basic auth whose password is REVERSE_TUNNEL_GATEWAY_SECRET (frps + * sends its plugin `addr` userinfo). Decisions: `authz.ts`. + * - `GET {prefix}/node-websocket`: Caddy forward_auth for node WebSocket upgrades, + * authenticated with `X-SAM-Gateway-Secret`. It re-dispatches the original request through + * the SAM app so the EXISTING ws-* / logs-stream authentication runs unchanged + * (`services/node-websocket-gateway.ts`), and returns that handler's refusal for Caddy to + * send, or a decision naming the loopback upstream and the headers Caddy must forward. * - * - `POST /inbound-email` — the box's sam-mx SMTP receiver hands over one inbound agent email - * (routes/self-host-gateway-inbound-email.ts). Same secret header, plus its own on-switch. + * - `POST {prefix}/inbound-email`: the box's sam-mx SMTP receiver hands over one inbound agent + * email (`inbound-email.ts`). Same secret header, plus its own on-switch. * - * All are unreachable from the internet: frps and Caddy call celld directly on loopback, and - * the box's Caddy answers 404 for this path prefix on its public listener. Both also fail - * closed here: with no (or a too-short) REVERSE_TUNNEL_GATEWAY_SECRET they answer 404, which - * is every Cloudflare deployment, and a wrong secret is 401. These routes do not use session - * auth and are mounted before every session-auth router. + * frps and Caddy call celld on loopback; the box's Caddy answers 404 for this prefix on its + * public listener (L22 owns that matcher). Both routes also fail closed here: no (or a + * too-short) secret answers 404, and a wrong secret 401. */ import { type Context, Hono } from 'hono'; -import type { Env } from '../env'; -import { log } from '../lib/logger'; -import { readRequestJsonRecord, RequestBodyTooLargeError } from '../lib/runtime-validation'; -import { parseWorkspaceSubdomain } from '../lib/workspace-subdomain'; -import type { InboundDeps } from '../services/agent-email/inbound'; -import { authorizeFrpsPluginRequest } from '../services/node-reverse-tunnel-authz'; -import { - getReverseTunnelGatewaySecret, - isAcceptedGatewaySecret, -} from '../services/node-reverse-tunnel-config'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { readRequestJsonRecord, RequestBodyTooLargeError } from '../../lib/runtime-validation'; +import { parseWorkspaceSubdomain } from '../../lib/workspace-subdomain'; +import { handleAppError } from '../../middleware/app-error-handler'; +import type { InboundDeps } from '../../services/agent-email/inbound'; import { GATEWAY_HEADER, isGatewayDecisionFor, markGatewayAuthorizationRequest, -} from '../services/node-websocket-gateway'; -import { handleInboundEmailGateway } from './self-host-gateway-inbound-email'; +} from '../../services/node-websocket-gateway'; +import { authorizeFrpsPluginRequest, type FrpsPluginDecision } from './authz'; +import { getReverseTunnelGatewaySecret, isAcceptedGatewaySecret } from './config'; +import type { ReverseTunnelEnv } from './env'; +import { handleInboundEmailGateway } from './inbound-email'; +export const SELF_HOST_GATEWAY_PATH_PREFIX = '/api/self-host/gateway'; /** frps plugin bodies are a few hundred bytes; bound them well above that. */ export const FRPS_PLUGIN_MAX_BODY_BYTES = 16 * 1024; export const GATEWAY_SECRET_HEADER = 'X-SAM-Gateway-Secret'; @@ -47,10 +45,8 @@ export const GATEWAY_ORIGINAL_HOST_HEADER = 'X-SAM-Gateway-Original-Host'; /** Basic-auth username frps sends (deploy/selfhost/frps/frps.toml); only the password matters. */ const FRPS_PLUGIN_BASIC_USER = 'frps'; - /** Logs-stream WebSocket on the API host (routes/nodes/diagnostics.ts). */ const LOGS_STREAM_PATH_RE = /^\/api\/nodes\/[A-Za-z0-9_-]{1,64}\/logs\/stream$/; - /** Headers the gateway itself consumes; never forwarded into the re-dispatched request. */ const GATEWAY_INPUT_HEADERS = [ 'host', @@ -60,12 +56,17 @@ const GATEWAY_INPUT_HEADERS = [ 'x-forwarded-uri', 'x-forwarded-method', 'x-forwarded-proto', + // Client-address headers: celld has no edge that overwrites them, so a client copy must never + // become the identity any IP-keyed check in the re-dispatched handler sees. + 'cf-connecting-ip', + 'x-forwarded-for', + 'x-real-ip', ]; export type GatewayDispatch = ( request: Request, env: Env, - executionCtx: Context<{ Bindings: Env }>['executionCtx'] + ctx: Context['executionCtx'] ) => Response | Promise; function notFound(): Response { @@ -92,12 +93,18 @@ function basicAuthPassword(header: string | undefined): string | null { return decoded.slice(separator + 1); } -function frpsReply(decision: { allow: true } | { allow: false; reason: string }): Response { - return Response.json( - decision.allow - ? { reject: false, unchange: true } - : { reject: true, reject_reason: decision.reason } - ); +/** + * frps plugin response (frp v0.72 `pkg/plugin/server/types.go`). An allow that carries + * `replacementContent` MUST be `unchange: false` with `content`: frps applies `content` only + * then, and the Login replacement is what pins the server-chosen run_id that fences duplicate + * control sessions (`authz.ts`). Every other allow leaves the request unchanged. + */ +export function frpsPluginReply(decision: FrpsPluginDecision): Response { + if (!decision.allow) return Response.json({ reject: true, reject_reason: decision.reason }); + if (decision.replacementContent) { + return Response.json({ reject: false, unchange: false, content: decision.replacementContent }); + } + return Response.json({ reject: false, unchange: true }); } /** Which original requests the gateway may authorize: node WebSocket upgrades only. */ @@ -109,10 +116,7 @@ function isGatewayTarget(env: Env, host: string, path: string): boolean { return host === `api.${baseDomain}` && LOGS_STREAM_PATH_RE.test(path); } -/** - * The original request Caddy is asking about, or null when it is not a node WebSocket upgrade - * the gateway may authorize (any other target is refused rather than re-dispatched). - */ +/** The original request Caddy asks about, or null when the gateway may not authorize it. */ function forwardedGatewayTarget(env: Env, headers: Headers): URL | null { // Not X-Forwarded-Host: celld rebuilds request.url from that header, so Caddy sets it to the // API host (keeping this request on this route) and sends the socket's host separately. @@ -126,9 +130,8 @@ function forwardedGatewayTarget(env: Env, headers: Headers): URL | null { } catch { original = null; } - // The target check reads the URL that is re-dispatched (original.hostname), and the host - // must survive URL parsing unchanged: WHATWG parsing drops tabs/newlines, applies IDNA and - // reads userinfo, so a header whose parsed host differs from its text is refused outright + // The host must survive URL parsing unchanged: WHATWG parsing drops tabs/newlines, applies + // IDNA and reads userinfo, so a header whose parsed host differs from its text is refused // rather than authorized as whichever workspace the parser happened to produce. const allowed = !!original && @@ -138,7 +141,7 @@ function forwardedGatewayTarget(env: Env, headers: Headers): URL | null { isGatewayTarget(env, original.hostname, original.pathname); if (!allowed) { log.warn('self_host_gateway.forward_auth_not_a_gateway_route', { - host, + host: host.slice(0, 255), method, upgrade: upgrade || null, action: 'rejected', @@ -182,13 +185,17 @@ export function createSelfHostGatewayRoutes( dispatch: GatewayDispatch, options: { inboundEmailDeps?: InboundDeps } = {} ) { - const routes = new Hono<{ Bindings: Env }>(); + const routes = new Hono<{ Bindings: ReverseTunnelEnv }>().basePath(SELF_HOST_GATEWAY_PATH_PREFIX); + routes.onError(handleAppError); + routes.notFound(notFound); - routes.post('/inbound-email', (c) => handleInboundEmailGateway(c, options.inboundEmailDeps)); + // The celld entry passes the full Worker env; the inbound handler reads agent email settings. + routes.post('/inbound-email', (c) => + handleInboundEmailGateway(c as unknown as Context<{ Bindings: Env }>, options.inboundEmailDeps) + ); routes.post('/frps-plugin', async (c) => { - const secret = getReverseTunnelGatewaySecret(c.env); - if (!secret) return notFound(); + if (!getReverseTunnelGatewaySecret(c.env)) return notFound(); const presented = basicAuthPassword(c.req.header('Authorization')); if (presented === null || !isAcceptedGatewaySecret(c.env, presented)) { log.warn('self_host_gateway.frps_plugin_unauthenticated', { action: 'rejected' }); @@ -199,17 +206,15 @@ export function createSelfHostGatewayRoutes( body = await readRequestJsonRecord(c.req.raw, 'frps-plugin', FRPS_PLUGIN_MAX_BODY_BYTES); } catch (err) { // frps needs a 200 JSON verdict to report the refusal to frpc. - return frpsReply({ - allow: false, - reason: err instanceof RequestBodyTooLargeError ? 'request too large' : 'malformed request', - }); + const reason = + err instanceof RequestBodyTooLargeError ? 'request too large' : 'malformed request'; + return frpsPluginReply({ allow: false, code: 'malformed', reason }); } - return frpsReply(await authorizeFrpsPluginRequest(c.env, c.req.query('op'), body)); + return frpsPluginReply(await authorizeFrpsPluginRequest(c.env, c.req.query('op'), body)); }); routes.get('/node-websocket', async (c) => { - const secret = getReverseTunnelGatewaySecret(c.env); - if (!secret) return notFound(); + if (!getReverseTunnelGatewaySecret(c.env)) return notFound(); if (!isAcceptedGatewaySecret(c.env, c.req.header(GATEWAY_SECRET_HEADER) ?? '')) { log.warn('self_host_gateway.forward_auth_unauthenticated', { action: 'rejected' }); return unauthorized(); diff --git a/apps/api/src/routes/self-host-gateway-inbound-email.ts b/apps/api/src/selfhost/reverse-tunnel/inbound-email.ts similarity index 94% rename from apps/api/src/routes/self-host-gateway-inbound-email.ts rename to apps/api/src/selfhost/reverse-tunnel/inbound-email.ts index 63f0b5b0bb..d0e35221cb 100644 --- a/apps/api/src/routes/self-host-gateway-inbound-email.ts +++ b/apps/api/src/selfhost/reverse-tunnel/inbound-email.ts @@ -23,19 +23,19 @@ */ import type { Context } from 'hono'; -import type { Env } from '../env'; -import { log } from '../lib/logger'; -import { normalizeMailbox } from '../services/agent-email/address'; +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { normalizeMailbox } from '../../services/agent-email/address'; import { handleInboundAgentEmail, type InboundDeps, type InboundEmailMessage, -} from '../services/agent-email/inbound'; -import { isSelfHostInboundEmailConfigured } from '../services/agent-email/self-host-inbound'; +} from '../../services/agent-email/inbound'; +import { isSelfHostInboundEmailConfigured } from '../../services/agent-email/self-host-inbound'; import { getReverseTunnelGatewaySecret, isAcceptedGatewaySecret, -} from '../services/node-reverse-tunnel-config'; +} from './config'; export const INBOUND_EMAIL_HEADER = { secret: 'X-SAM-Gateway-Secret', diff --git a/apps/api/src/services/node-reverse-tunnel-leases.ts b/apps/api/src/selfhost/reverse-tunnel/leases.ts similarity index 61% rename from apps/api/src/services/node-reverse-tunnel-leases.ts rename to apps/api/src/selfhost/reverse-tunnel/leases.ts index 96522f9a84..290ae56fab 100644 --- a/apps/api/src/services/node-reverse-tunnel-leases.ts +++ b/apps/api/src/selfhost/reverse-tunnel/leases.ts @@ -1,25 +1,17 @@ -/** - * D1 access for reverse-tunnel port leases (`node_reverse_tunnel_leases`, migration 0232). - * - * Status machine: active -> released. A lease is written BEFORE the provider VM is requested, - * fenced on the node row still carrying that exact live incarnation, and is released when its - * incarnation is provably no longer the node's live runtime ({@link LIVE_INCARNATION_SQL}, the - * same predicate the Cloudflare tunnel journal uses) or when the provisioner knows no VM was - * ever requested for it. Releasing is the whole cleanup: frps holds no state SAM must delete, - * and the frps plugin refuses Login/NewProxy/Ping/NewWorkConn for a released lease, so a straggling frpc - * is disconnected at its next heartbeat. Rows are never deleted. - */ -import type { Env } from '../env'; -import { log, serializeError } from '../lib/logger'; +import * as v from 'valibot'; + +import { log, serializeError } from '../../lib/logger'; +import { nodeTransportExtension } from '../../services/node-transport-extension'; +import { LIVE_INCARNATION_SQL } from '../../services/node-tunnel-journal'; import { deriveReverseTunnelCredential, hashReverseTunnelCredential, resolveReverseTunnelPortRange, resolveReverseTunnelPortReuseMinAgeSeconds, type ReverseTunnelEnv, -} from './node-reverse-tunnel-config'; -import { isReverseTunnelInstallation } from './node-tunnel-config'; -import { LIVE_INCARNATION_SQL } from './node-tunnel-journal'; +} from './config'; +import type { ReverseTunnelEnv as Env } from './env'; +import { isReverseTunnelInstallation } from './env'; export type ReverseTunnelLeaseStatus = 'active' | 'released'; @@ -33,25 +25,24 @@ export interface ReverseTunnelLeaseRow { status: ReverseTunnelLeaseStatus; } +const LeaseRowSchema = v.object({ + id: v.string(), nodeId: v.string(), userId: v.string(), runtimeIncarnationId: v.string(), + port: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), + credentialHash: v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/)), + status: v.picklist(['active', 'released']), +}); export const REVERSE_TUNNEL_LEASE_COLUMNS = `id, node_id AS nodeId, user_id AS userId, runtime_incarnation_id AS runtimeIncarnationId, port, credential_hash AS credentialHash, status`; -/** - * Fence for writing a lease: the exact live managed VM incarnation. Same shape as the - * Cloudflare tunnel provisioning fence (node-tunnel-provisioning.ts). - */ const NODE_LIVE_FENCE_SQL = `id = ? AND user_id = ? AND runtime = 'vm' AND node_class = 'managed' - AND runtime_incarnation_id = ? AND runtime_termination_confirmed_at IS NULL + AND transport = 'reverse-tunnel' AND runtime_incarnation_id = ? AND runtime_termination_confirmed_at IS NULL AND status NOT IN ('deleted', 'stopped', 'destroying')`; -type LeaseEnv = Pick; +type LeaseEnv = Pick; + +// Build registration owns cleanup: changing admission must not strand an older lease. +// Cloudflare never imports/installs the reverse driver, so it never queries this table. -/** - * Why no lease was written. `port_range_exhausted`: every port in the range is held by an - * active lease. `port_range_cooling_down`: some ports are free but were released less than the - * minimum reuse age ago, so reissuing one could hand a new node's traffic to the previous - * holder's still-connected frpc. Both are capacity conditions; the others are not. - */ export type ReverseTunnelLeaseErrorCode = | 'port_range_exhausted' | 'port_range_cooling_down' @@ -69,14 +60,12 @@ export class ReverseTunnelLeaseError extends Error { } } -/** Sorts after every ISO timestamp: a released row with no released_at is treated as fresh. */ const UNKNOWN_RELEASE_AT = '9999-12-31T23:59:59.999Z'; export interface ReverseTunnelLeaseProvisioning { leaseId: string; port: number; - /** SECRET: cloud-init only; never log or persist. */ - credential: string; + credential: string; } export interface EnsureReverseTunnelLeaseInput { @@ -90,33 +79,27 @@ export async function readReverseTunnelLeaseByIncarnation( nodeId: string, runtimeIncarnationId: string ): Promise { - return await env.DATABASE.prepare( + const row = await env.DATABASE.prepare( `SELECT ${REVERSE_TUNNEL_LEASE_COLUMNS} FROM node_reverse_tunnel_leases WHERE node_id = ? AND runtime_incarnation_id = ?` ) .bind(nodeId, runtimeIncarnationId) - .first(); + .first(); + const parsed = v.safeParse(LeaseRowSchema, row); + if (row && !parsed.success) log.warn('node_reverse_tunnel.invalid_lease', { nodeId, runtimeIncarnationId }); + return parsed.success ? parsed.output : null; } -/** - * Allocate (or adopt, on retry/resume) this incarnation's lease and return its port and - * credential. The port is chosen and written by ONE statement: SQLite executes it with no - * interleaving writer, so two nodes can never be handed the same port, and the partial unique - * index on active ports is a second fence. A released port is NOT a candidate until its latest - * release is older than the minimum reuse age (2 x the frps heartbeat timeout by default, - * {@link resolveReverseTunnelPortReuseMinAgeSeconds}): by then frps has dropped the previous - * holder's session, so a new node's traffic cannot reach it. Among candidates: never-used ports - * in ascending order, then the least recently released. When nothing qualifies the error says - * whether the range is full or only cooling down ({@link ReverseTunnelLeaseErrorCode}). - * - * The credential is derived from the lease id, so the row id is generated first and the hash - * of the resulting credential is written in the same INSERT. Only the (node, incarnation) - * conflict is absorbed (retry/resume adopts its own row); any other constraint failure throws. - */ export async function ensureReverseTunnelLease( env: LeaseEnv & ReverseTunnelEnv & Pick, input: EnsureReverseTunnelLeaseInput ): Promise { + if (!input.nodeId || !input.userId || !input.runtimeIncarnationId) throw new Error('Reverse-tunnel owner identity is required'); + // A durable allocation keeps the transport its VM already booted with, even if the + // installation now selects another transport. Only admission of a NEW lease reads the flag. + const existing = await readReverseTunnelLeaseByIncarnation(env, input.nodeId, input.runtimeIncarnationId); + if (existing) return adoptReverseTunnelLease(env, input, existing); + if (!isReverseTunnelInstallation(env)) throw new Error('Reverse tunnel is disabled'); const range = resolveReverseTunnelPortRange(env); const reuseMinAgeSeconds = resolveReverseTunnelPortReuseMinAgeSeconds(env); const nowMs = Date.now(); @@ -190,37 +173,31 @@ export async function ensureReverseTunnelLease( } throw await noFreePortError(env, input.nodeId, range, reusableBefore, reuseMinAgeSeconds); } + return adoptReverseTunnelLease(env, input, row); +} + +/** Existing authority is adopted only while its exact persisted owner remains live. */ +async function adoptReverseTunnelLease( + env: LeaseEnv & Pick, + input: EnsureReverseTunnelLeaseInput, + row: ReverseTunnelLeaseRow +): Promise { if (row.userId !== input.userId || row.status !== 'active') { - throw new ReverseTunnelLeaseError( - 'lease_released', - 'Reverse-tunnel lease for this node incarnation was released' - ); + throw new ReverseTunnelLeaseError('lease_released', 'Reverse-tunnel lease for this node incarnation was released'); } - // Adopting an earlier attempt's row (retry or durable resume): re-derive ITS credential. A - // mismatch (for example a rotated ENCRYPTION_KEY) must not hand a VM a credential the plugin - // will refuse; fail closed instead. - const credential = - row.id === leaseId - ? candidateCredential - : await deriveReverseTunnelCredential(env, { - leaseId: row.id, - nodeId: row.nodeId, - runtimeIncarnationId: row.runtimeIncarnationId, - }); + const live = await env.DATABASE.prepare(`SELECT 1 AS live FROM nodes WHERE ${NODE_LIVE_FENCE_SQL}`) + .bind(input.nodeId, input.userId, input.runtimeIncarnationId).first<{ live: number }>(); + if (!live) throw new ReverseTunnelLeaseError('incarnation_not_live', 'Reverse-tunnel lease owner is no longer live'); + // A rotated root must never hand a VM a credential the plugin will refuse. + const credential = await deriveReverseTunnelCredential(env, { + leaseId: row.id, nodeId: row.nodeId, runtimeIncarnationId: row.runtimeIncarnationId, + }); if ((await hashReverseTunnelCredential(credential)) !== row.credentialHash) { - throw new ReverseTunnelLeaseError( - 'credential_mismatch', - 'Reverse-tunnel credential cannot be re-derived for this lease' - ); + throw new ReverseTunnelLeaseError('credential_mismatch', 'Reverse-tunnel credential cannot be re-derived for this lease'); } return { leaseId: row.id, port: row.port, credential }; } -/** - * Distinguish "every port is held" from "only recently released ports remain", record which, - * and name the earliest moment a cooling port becomes reusable. Failure path only: one - * statement over the range's released rows (indexed on port, released_at). - */ async function noFreePortError( env: LeaseEnv, nodeId: string, @@ -269,16 +246,13 @@ async function noFreePortError( ); } -/** - * Release one incarnation that the caller KNOWS no VM can still use: failure or cancellation - * before the provider create call, or a provider-confirmed direct delete. - */ export async function releaseUnallocatedReverseTunnelLease( env: LeaseEnv, nodeId: string, runtimeIncarnationId: string, reason: string ): Promise { + if (!nodeTransportExtension('reverse-tunnel')) return false; const now = new Date().toISOString(); const result = await env.DATABASE.prepare( `UPDATE node_reverse_tunnel_leases @@ -290,16 +264,12 @@ export async function releaseUnallocatedReverseTunnelLease( return (result.meta?.changes ?? 0) === 1; } -/** - * Release every active lease whose incarnation is no longer live: node row gone, incarnation - * replaced, or termination proof recorded. Scoped to one node when `nodeId` is given; - * installation-wide otherwise (cron sweep). One D1 statement; never touches a live lease. - */ export async function releaseNonLiveReverseTunnelLeases( env: LeaseEnv, reason: string, nodeId?: string ): Promise { + if (!nodeTransportExtension('reverse-tunnel')) return 0; const now = new Date().toISOString(); const result = await env.DATABASE.prepare( `UPDATE node_reverse_tunnel_leases AS t @@ -313,7 +283,6 @@ export async function releaseNonLiveReverseTunnelLeases( return result.meta?.changes ?? 0; } -/** Node-scoped release that never throws: the cron sweep is the backstop for a failed write. */ export async function releaseNodeReverseTunnelLeases( env: LeaseEnv, nodeId: string, @@ -328,20 +297,13 @@ export async function releaseNodeReverseTunnelLeases( } export type ReverseTunnelLeaseSweepResult = - { released: number } | { released: null; skipReason: 'transport_not_reverse_tunnel' }; + { released: number } | { released: null; skipReason: 'driver_not_installed' }; -/** - * Cron sweep: release every non-live active lease installation-wide (one statement). Runs only - * on an installation configured for the reverse-tunnel transport; every other deployment - * (vm-public-dns, cloudflare-tunnel, Instant) makes no D1 call and reports why it skipped, so - * the tick is distinguishable from "ran and found nothing" in `cron.completed`. Leases are - * also released node-by-node on every teardown path, which does not depend on this sweep. - */ export async function runReverseTunnelLeaseSweep( env: LeaseEnv & Pick ): Promise { - if (!isReverseTunnelInstallation(env)) { - return { released: null, skipReason: 'transport_not_reverse_tunnel' }; + if (!nodeTransportExtension('reverse-tunnel')) { + return { released: null, skipReason: 'driver_not_installed' }; } return { released: await releaseNonLiveReverseTunnelLeases(env, 'runtime_not_live') }; } diff --git a/apps/api/src/services/node-reverse-tunnel-provisioning.ts b/apps/api/src/selfhost/reverse-tunnel/provisioning.ts similarity index 60% rename from apps/api/src/services/node-reverse-tunnel-provisioning.ts rename to apps/api/src/selfhost/reverse-tunnel/provisioning.ts index 5571a8a2f5..34b422365d 100644 --- a/apps/api/src/services/node-reverse-tunnel-provisioning.ts +++ b/apps/api/src/selfhost/reverse-tunnel/provisioning.ts @@ -1,22 +1,15 @@ -/** - * Provision the reverse-tunnel (frp) side of one managed workspace node incarnation: lease a - * loopback port on the control-plane box and mint the node's frp credential, BEFORE the - * provider VM is requested (so every later failure can release the lease). No DNS record, no - * Origin CA and no public IP are involved for this transport. - */ -import type { Env } from '../env'; -import { log } from '../lib/logger'; -import { getReverseTunnelGatewaySecret } from './node-reverse-tunnel-config'; +import { log } from '../../lib/logger'; +import { resolveVmAgentTunnelPort } from '../../services/node-tunnel-config'; +import { getReverseTunnelGatewaySecret } from './config'; +import type { ReverseTunnelEnv as Env } from './env'; import { ensureReverseTunnelLease, type EnsureReverseTunnelLeaseInput, type ReverseTunnelLeaseProvisioning, -} from './node-reverse-tunnel-leases'; -import { resolveVmAgentTunnelPort } from './node-tunnel-config'; +} from './leases'; export interface NodeReverseTunnelProvisioning extends ReverseTunnelLeaseProvisioning { - /** The vm-agent's loopback tunnel listener port (frpc `localPort`). */ - localPort: string; + localPort: string; } export async function ensureNodeReverseTunnelForProvisioning( diff --git a/apps/api/src/selfhost/reverse-tunnel/route.ts b/apps/api/src/selfhost/reverse-tunnel/route.ts new file mode 100644 index 0000000000..21ea77a921 --- /dev/null +++ b/apps/api/src/selfhost/reverse-tunnel/route.ts @@ -0,0 +1,32 @@ +import { NodeAgentRouteError } from '../../services/node-agent-route'; +import { assertReverseTunnelUpstreamPort, reverseTunnelUpstreamOrigin } from './config'; +import type { ReverseTunnelEnv as Env } from './env'; + +/** + * Loopback origin of a reverse-tunnel node's agent: the ACTIVE lease of the node's CURRENT + * incarnation. A released or superseded lease is never routed to, so a revoked node stops + * receiving control-plane traffic on the next request, whatever frps still holds open. One + * indexed read (`node_id` + incarnation unique key); only reverse-tunnel nodes reach it. + */ +export async function resolveReverseTunnelAgentOrigin(env: Env, nodeId: string): Promise { + const row = await env.DATABASE.prepare( + `SELECT l.port AS port + FROM node_reverse_tunnel_leases l + JOIN nodes n ON n.id = l.node_id AND n.runtime_incarnation_id = l.runtime_incarnation_id + AND n.user_id = l.user_id + WHERE l.node_id = ? AND l.status = 'active'` + ) + .bind(nodeId) + .first<{ port: unknown }>(); + if (!row) { + throw new NodeAgentRouteError( + nodeId, + 'Node has no active reverse-tunnel route for its current incarnation' + ); + } + // Caddy and fetch() connect to exactly this loopback port: the assertion refuses a + // non-integer value and anything outside the configured lease range. + const port = Number(row.port); + assertReverseTunnelUpstreamPort(env, port); + return reverseTunnelUpstreamOrigin(port); +} diff --git a/apps/api/src/selfhost/reverse-tunnel/transport.ts b/apps/api/src/selfhost/reverse-tunnel/transport.ts new file mode 100644 index 0000000000..24937eef83 --- /dev/null +++ b/apps/api/src/selfhost/reverse-tunnel/transport.ts @@ -0,0 +1,44 @@ +/** Imported only by the self-host build, which supplies L18's frpc cloud-init renderer. */ +import type { CloudInitVariables } from '@simple-agent-manager/cloud-init'; + +import { installNodeTransportExtension } from '../../services/node-transport-extension'; +import { nodeTunnelBootVariables } from '../../services/node-tunnel-config'; +import { releaseNodeReverseTunnelLeases, releaseUnallocatedReverseTunnelLease } from './leases'; +import { ensureNodeReverseTunnelForProvisioning } from './provisioning'; +import { resolveReverseTunnelAgentOrigin } from './route'; + +export interface ReverseTunnelBootVariables extends CloudInitVariables { + reverseTunnelCredential: string; + reverseTunnelRemotePort: string; + reverseTunnelLocalPort: string; +} +export function installReverseTunnelTransport( + render: (variables: ReverseTunnelBootVariables) => string +): void { + if (typeof render !== 'function') + throw new Error('Reverse tunnel requires its self-host boot renderer'); + installNodeTransportExtension({ + transport: 'reverse-tunnel', + select: (node) => + node.runtime === 'vm' && node.nodeClass === 'managed' && node.nodeRole === 'workspace' + ? 'reverse-tunnel' + : null, + prepare: async (env, owner) => { + const lease = await ensureNodeReverseTunnelForProvisioning(env, owner); + return (variables) => + render({ + ...variables, + ...nodeTunnelBootVariables(env), + // Cloudflared belongs only to the Cloudflare driver, not the shared listener timings. + cloudflaredVersion: undefined, + originCaCertificateUrl: undefined, + reverseTunnelCredential: lease.credential, + reverseTunnelRemotePort: String(lease.port), + reverseTunnelLocalPort: lease.localPort, + }); + }, + releaseUnallocated: releaseUnallocatedReverseTunnelLease, + releaseNonLive: releaseNodeReverseTunnelLeases, + resolveAgentOrigin: resolveReverseTunnelAgentOrigin, + }); +} diff --git a/apps/api/src/selfhost/speech/endpoints.ts b/apps/api/src/selfhost/speech/endpoints.ts new file mode 100644 index 0000000000..537a2ccba4 --- /dev/null +++ b/apps/api/src/selfhost/speech/endpoints.ts @@ -0,0 +1,248 @@ +/** + * OpenAI-compatible speech endpoints for the self-host build (no Workers AI binding). Settings: + * `./settings.ts`; the Worker reaches this only through services/speech-backend.ts. + * + * Every call goes through `guardedFetch`: the host and each redirect hop are checked, cloud + * metadata is refused, a private-network host needs the admin's `allowPrivateNetwork` opt-in, and + * the Bearer key is dropped on any cross-origin hop. Response bodies are never logged: a provider + * error body can echo the user's audio transcript or text. + */ +import { classifyHost, guardedFetch, maybeJsonRecord } from '@simple-agent-manager/worker-core'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { resolveAdminSettingDetailsMany } from '../../services/admin-settings-resolution'; +import { outboundMaxRedirectsValue } from '../../services/outbound-fetch-settings'; +import { audioContentType } from '../../services/tts'; +import { + DEFAULT_SPEECH_ENDPOINT_TIMEOUT_MS, + DEFAULT_SPEECH_SYNTHESIS_MAX_AUDIO_BYTES, + DEFAULT_SPEECH_TRANSCRIPTION_MAX_RESPONSE_BYTES, + type SpeechEndpointKind, + speechSettingName, + validSpeechBaseUrl, +} from './settings'; + +export interface SpeechEndpoint { + kind: SpeechEndpointKind; + /** Base URL without a trailing slash. */ + baseUrl: string; + apiKey: string | null; + model: string; + /** Synthesis only. */ + voice: string | null; + allowPrivateNetwork: boolean; + maxRedirects: number; + /** Per-request budget (`speech.endpointTimeoutMs`). */ + timeoutMs: number; + maxAudioBytes: number; + maxTranscriptionResponseBytes: number; +} + +export class SpeechEndpointError extends Error { + constructor( + readonly kind: SpeechEndpointKind, + readonly status: number | null, + message: string + ) { + super(message); + this.name = 'SpeechEndpointError'; + } +} + +function stringValue(value: unknown): string | null { + return typeof value === 'string' && value.trim() ? value.trim() : null; +} + +/** + * The configured endpoint, or null without a base URL, model (or synthesis voice), when the + * settings cannot be read, or when its host is private and the admin has not opted in. Null keeps + * the feature off, as on an installation that never set it up. + */ +export async function resolveSpeechEndpoint( + env: Env, + kind: SpeechEndpointKind +): Promise { + let values: unknown[]; + try { + const details = await resolveAdminSettingDetailsMany(env, [ + speechSettingName(kind, 'baseUrl'), + speechSettingName(kind, 'apiKey'), + speechSettingName(kind, 'model'), + speechSettingName(kind, 'allowPrivateNetwork'), + speechSettingName('synthesis', 'voice'), + speechSettingName(null, 'endpointTimeoutMs'), + 'outbound.maxRedirects', + speechSettingName('synthesis', 'maxAudioBytes'), + speechSettingName('transcription', 'maxResponseBytes'), + ]); + values = details.map((detail) => detail.value); + } catch (err) { + log.warn('speech_endpoint.settings_unreadable', { + kind, + error: err instanceof Error ? err.message : String(err), + }); + return null; + } + const [ + baseUrl, + apiKey, + model, + allowPrivate, + voice, + timeout, + maxRedirects, + maxAudioBytes, + maxTranscriptionResponseBytes, + ] = values; + const modelId = stringValue(model); + if (!validSpeechBaseUrl(kind, baseUrl) || !modelId) return null; + if (kind === 'synthesis' && !stringValue(voice)) return null; + const normalized = String(baseUrl).trim().replace(/\/+$/, ''); + const allowPrivateNetwork = allowPrivate === true; + if (!allowPrivateNetwork && classifyHost(new URL(normalized).hostname) === 'private') { + log.warn('speech_endpoint.private_network_not_allowed', { kind }); + return null; + } + return { + kind, + baseUrl: normalized, + apiKey: stringValue(apiKey), + model: modelId, + voice: kind === 'synthesis' ? stringValue(voice) : null, + allowPrivateNetwork, + maxRedirects: outboundMaxRedirectsValue(maxRedirects), + maxAudioBytes: + typeof maxAudioBytes === 'number' && Number.isInteger(maxAudioBytes) && maxAudioBytes > 0 + ? maxAudioBytes + : DEFAULT_SPEECH_SYNTHESIS_MAX_AUDIO_BYTES, + maxTranscriptionResponseBytes: + typeof maxTranscriptionResponseBytes === 'number' && + Number.isInteger(maxTranscriptionResponseBytes) && + maxTranscriptionResponseBytes > 0 + ? maxTranscriptionResponseBytes + : DEFAULT_SPEECH_TRANSCRIPTION_MAX_RESPONSE_BYTES, + timeoutMs: + typeof timeout === 'number' && Number.isInteger(timeout) && timeout > 0 + ? timeout + : DEFAULT_SPEECH_ENDPOINT_TIMEOUT_MS, + }; +} + +async function send(endpoint: SpeechEndpoint, path: string, init: RequestInit): Promise { + const headers = new Headers(init.headers); + if (endpoint.apiKey) headers.set('Authorization', `Bearer ${endpoint.apiKey}`); + const response = await guardedFetch( + `${endpoint.baseUrl}${path}`, + { ...init, headers, signal: AbortSignal.timeout(endpoint.timeoutMs) }, + { allowPrivateNetwork: endpoint.allowPrivateNetwork, maxRedirects: endpoint.maxRedirects } + ); + if (!response.ok) { + // Status only: a provider error body can echo the request (audio text, prompt). + await response.body?.cancel().catch(() => undefined); + log.warn('speech_endpoint.upstream_error', { kind: endpoint.kind, status: response.status }); + throw new SpeechEndpointError( + endpoint.kind, + response.status, + `The ${endpoint.kind} endpoint answered HTTP ${response.status}` + ); + } + return response; +} + +/** Transcribe one recording: multipart POST `/audio/transcriptions`, returns its text. */ +export async function transcribeWithEndpoint( + endpoint: SpeechEndpoint, + audio: File +): Promise { + const form = new FormData(); + form.set('file', audio, audio.name || 'audio.webm'); + form.set('model', endpoint.model); + form.set('response_format', 'json'); + const response = await send(endpoint, '/audio/transcriptions', { method: 'POST', body: form }); + const bytes = await readSpeechResponse(response, endpoint.maxTranscriptionResponseBytes); + // Parse only the bounded buffer; invalid provider JSON must not leak its contents in errors. + const payload = maybeJsonRecord(await new Response(bytes).json().catch(() => null)); + if (typeof payload?.text !== 'string') { + throw new SpeechEndpointError( + 'transcription', + response.status, + 'The transcription endpoint returned no text' + ); + } + return payload.text; +} + +/** Synthesize one chunk: JSON POST `/audio/speech`, returns the audio bytes. */ +export async function synthesizeWithEndpoint( + endpoint: SpeechEndpoint, + text: string, + format: string, + maxBytes = endpoint.maxAudioBytes +): Promise { + // Raw PCM has no container/sample metadata for browser playback or our cached audio route. + if (format === 'pcm') throw new Error('Raw PCM endpoint output is not supported'); + const response = await send(endpoint, '/audio/speech', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + model: endpoint.model, + input: text, + response_format: format, + ...(endpoint.voice ? { voice: endpoint.voice } : {}), + }), + }); + const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase(); + const aliases: Readonly> = { + 'audio/mp3': 'audio/mpeg', + 'audio/x-wav': 'audio/wav', + 'audio/x-flac': 'audio/flac', + 'audio/opus': 'audio/ogg', + }; + const declared = contentType ? (aliases[contentType] ?? contentType) : null; + if ( + declared && + declared !== 'application/octet-stream' && + declared !== audioContentType(format) + ) { + await response.body?.cancel().catch(() => undefined); + throw new SpeechEndpointError( + 'synthesis', + response.status, + 'The synthesis endpoint returned an unexpected audio content type' + ); + } + return readSpeechResponse(response, maxBytes); +} + +/** Bound actual streamed bytes even when Content-Length is absent or untruthful. */ +async function readSpeechResponse(response: Response, maxBytes: number): Promise { + const reader = response.body?.getReader(); + if (!reader) return new ArrayBuffer(0); + const chunks: Uint8Array[] = []; + let size = 0; + try { + if (Number(response.headers.get('content-length')) > maxBytes) { + throw new Error('Speech response exceeds configured byte limit'); + } + while (true) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maxBytes) throw new Error('Speech response exceeds configured byte limit'); + chunks.push(value); + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes.buffer; + } catch (err) { + await reader.cancel().catch(() => undefined); + throw err; + } finally { + reader.releaseLock(); + } +} diff --git a/apps/api/src/selfhost/speech/index.ts b/apps/api/src/selfhost/speech/index.ts new file mode 100644 index 0000000000..64c3a6c710 --- /dev/null +++ b/apps/api/src/selfhost/speech/index.ts @@ -0,0 +1,95 @@ +/** + * The self-host build's speech backend: speech-to-text and read-aloud through admin-configured + * OpenAI-compatible endpoints, on a runtime without Workers AI. Imported only by the self-host + * entry, which calls `installSpeechEndpoints()` once before any request; the shared Worker entry + * (`src/index.ts`) never imports this directory, so the Cloudflare bundle does not contain it. + */ +import type { Env } from '../../env'; +import { errors } from '../../middleware/error'; +import { + checkAiSpendRateLimit, + DEFAULT_WINDOW_SECONDS, + RateLimitError, +} from '../../middleware/rate-limit'; +import { installAdminSettingDefinitions } from '../../services/admin-settings-registry'; +import { resolveAdminSettingDetails } from '../../services/admin-settings-resolution'; +import { + installSpeechBackendExtension, + type SpeechBackendExtension, + type SpeechSynthesisBackend, + type SpeechTranscriptionBackend, +} from '../../services/speech-backend'; +import { + resolveSpeechEndpoint, + type SpeechEndpoint, + synthesizeWithEndpoint, + transcribeWithEndpoint, +} from './endpoints'; +import { + DEFAULT_SPEECH_SYNTHESIS_REQUESTS_PER_HOUR, + SPEECH_ENDPOINT_SETTINGS, + speechSettingName, +} from './settings'; + +/** Read-aloud requests per user per hour (`speech.synthesis.maxRequestsPerHour`). */ +async function synthesisRequestsPerHour(env: Env): Promise { + try { + const { value } = await resolveAdminSettingDetails( + env, + speechSettingName('synthesis', 'maxRequestsPerHour') + ); + return typeof value === 'number' && Number.isInteger(value) && value > 0 + ? value + : DEFAULT_SPEECH_SYNTHESIS_REQUESTS_PER_HOUR; + } catch { + return DEFAULT_SPEECH_SYNTHESIS_REQUESTS_PER_HOUR; + } +} + +function transcriptionBackend(endpoint: SpeechEndpoint): SpeechTranscriptionBackend { + return { transcribe: (audio) => transcribeWithEndpoint(endpoint, audio) }; +} + +function synthesisBackend(endpoint: SpeechEndpoint): SpeechSynthesisBackend { + // A fresh backend is resolved per request. Bound combined payload bytes across chunks; + // concatenation retains those buffers plus one final copy (up to twice this payload cap). + let audioBytes = 0; + return { + // Paid endpoint admission must retain every concurrent increment (D1, per hour). + admit: async (env, userId) => { + const limit = await synthesisRequestsPerHour(env); + const result = await checkAiSpendRateLimit( + env.DATABASE, 'speech-synthesis', userId, limit, DEFAULT_WINDOW_SECONDS + ).catch(() => { + throw errors.serviceUnavailable('Speech rate limit unavailable. Try again shortly.'); + }); + if (!result.allowed) { + throw new RateLimitError(Math.max(1, result.resetAt - Math.floor(Date.now() / 1000))); + } + }, + synthesize: async (text, encoding) => { + const remaining = endpoint.maxAudioBytes - audioBytes; + if (remaining <= 0) throw new Error('Speech response exceeds configured byte limit'); + const audio = await synthesizeWithEndpoint(endpoint, text, encoding, remaining); + audioBytes += audio.byteLength; + return audio; + }, + }; +} + +export const speechEndpointBackend: SpeechBackendExtension = { + transcription: async (env) => { + const endpoint = await resolveSpeechEndpoint(env, 'transcription'); + return endpoint ? transcriptionBackend(endpoint) : null; + }, + synthesis: async (env) => { + const endpoint = await resolveSpeechEndpoint(env, 'synthesis'); + return endpoint ? synthesisBackend(endpoint) : null; + }, +}; + +/** Registers the speech settings and backend. Idempotent; call before any request. */ +export function installSpeechEndpoints(): void { + installAdminSettingDefinitions(SPEECH_ENDPOINT_SETTINGS); + installSpeechBackendExtension(speechEndpointBackend); +} diff --git a/apps/api/src/selfhost/speech/settings.ts b/apps/api/src/selfhost/speech/settings.ts new file mode 100644 index 0000000000..c82d293340 --- /dev/null +++ b/apps/api/src/selfhost/speech/settings.ts @@ -0,0 +1,179 @@ +/** + * Admin settings for the self-host build's OpenAI-compatible speech endpoints: speech-to-text + * (`/audio/transcriptions`) and read-aloud (`/audio/speech`), used where the + * runtime has no Workers AI binding. Hosted OpenAI, Groq, or a server on the box such as speaches + * or Kokoro-FastAPI. + * + * Only the self-host entry registers these (`installSpeechEndpoints`), so a Cloudflare admin + * never sees them. Setup needs a base URL and a model, plus a voice for synthesis. Keys are stored + * encrypted in `platform_credentials` like the LLM endpoint key. + */ +import { classifyHost } from '@simple-agent-manager/worker-core'; + +import { + type AdminSettingDefinition, + type AdminSettingName, + integerDefinition, +} from '../../services/admin-setting-definitions'; + +export type SpeechEndpointKind = 'transcription' | 'synthesis'; + +const COMMON_KEYS = ['baseUrl', 'apiKey', 'model', 'allowPrivateNetwork'] as const; +type CommonKey = (typeof COMMON_KEYS)[number]; + +/** Default per-request budget for one speech endpoint call (`speech.endpointTimeoutMs`). */ +export const DEFAULT_SPEECH_ENDPOINT_TIMEOUT_MS = 60_000; + +/** + * Default read-aloud requests per user per hour that reach the endpoint + * (`speech.synthesis.maxRequestsPerHour`). Each one spends the admin's endpoint. + */ +export const DEFAULT_SPEECH_SYNTHESIS_REQUESTS_PER_HOUR = 120; + +/** Request-wide audio ceiling; shared across every read-aloud chunk. */ +export const DEFAULT_SPEECH_SYNTHESIS_MAX_AUDIO_BYTES = 8 * 1024 * 1024; +/** Bound provider JSON before parsing it (speech.transcription.maxResponseBytes). */ +export const DEFAULT_SPEECH_TRANSCRIPTION_MAX_RESPONSE_BYTES = 1024 * 1024; + +const MAX_URL_LENGTH = 2048; +const MAX_API_KEY_LENGTH = 4096; +const MIN_API_KEY_LENGTH = 8; +const MAX_ID_LENGTH = 200; + +const ROUTE_SUFFIX: Readonly> = { + transcription: /\/audio\/transcriptions\/?$/, + synthesis: /\/audio\/speech\/?$/, +}; + +/** These names exist only in the self-host build, so they are not in the shared name union. */ +export function speechSettingName(kind: SpeechEndpointKind | null, key: string): AdminSettingName { + return (kind ? `speech.${kind}.${key}` : `speech.${key}`) as AdminSettingName; +} + +/** + * An OpenAI-compatible base URL such as `https://api.openai.com/v1`: HTTPS to any host but a + * metadata or link-local one, plain HTTP only to a private-network host, so the API key never + * crosses the internet unencrypted (the rule `llm.openAICompatible.baseUrl` uses). No + * credentials, query or fragment: SAM appends the route itself. + */ +export function validSpeechBaseUrl(kind: SpeechEndpointKind, value: unknown): boolean { + if (typeof value !== 'string' || !value.trim() || value.length > MAX_URL_LENGTH) return false; + try { + const url = new URL(value.trim()); + const hostClass = classifyHost(url.hostname); + return ( + !url.username && + !url.password && + !url.search && + !url.hash && + hostClass !== 'forbidden' && + (url.protocol === 'https:' || (url.protocol === 'http:' && hostClass === 'private')) && + !ROUTE_SUFFIX[kind].test(url.pathname) + ); + } catch { + return false; + } +} + +function validId(value: unknown): boolean { + if (typeof value !== 'string') return false; + const trimmed = value.trim(); + return trimmed.length > 0 && trimmed.length <= MAX_ID_LENGTH && !/\s/.test(trimmed); +} + +const LABEL: Readonly> = { + transcription: 'speech-to-text (the chat microphone; POST /audio/transcriptions)', + synthesis: 'server read-aloud (POST /audio/speech)', +}; + +function definition(kind: SpeechEndpointKind, key: CommonKey | 'voice'): AdminSettingDefinition { + const base = { + name: speechSettingName(kind, key), + type: 'string' as const, + defaultValue: null, + category: 'AI models' as const, + secret: false, + risky: false, + }; + switch (key) { + case 'baseUrl': + return { + ...base, + description: `OpenAI-compatible base URL for ${LABEL[kind]}, for example https://api.openai.com/v1. Needs a model too. Empty keeps the feature off.`, + // Sends users' audio or text to this endpoint. + risky: true, + validate: (value) => validSpeechBaseUrl(kind, value), + }; + case 'apiKey': + return { + ...base, + description: `API key sent as a Bearer token to the ${kind} endpoint. Optional.`, + secret: true, + risky: true, + credential: { provider: `speech-${kind}`, kind: 'api-key' }, + validate: (value) => + typeof value === 'string' && + value.trim().length >= MIN_API_KEY_LENGTH && + value.length <= MAX_API_KEY_LENGTH, + }; + case 'model': + return { + ...base, + description: + kind === 'transcription' + ? 'Speech-to-text model id on the endpoint (for example gpt-4o-mini-transcribe, whisper-large-v3).' + : 'Text-to-speech model id on the endpoint (for example tts-1, kokoro).', + validate: validId, + }; + case 'voice': + return { + ...base, + description: + 'Voice id on the text-to-speech endpoint (for example alloy). Required to enable read-aloud.', + validate: validId, + }; + case 'allowPrivateNetwork': + return { + ...base, + type: 'boolean', + defaultValue: false, + risky: true, + description: `Let SAM call a ${kind} endpoint on this machine or its private network (loopback, 10/8, 172.16/12, 192.168/16, a Docker service name). Off: such a base URL is refused when used. Cloud metadata addresses are refused either way.`, + validate: (value) => typeof value === 'boolean', + }; + } +} + +export const SPEECH_ENDPOINT_SETTINGS: readonly AdminSettingDefinition[] = [ + ...COMMON_KEYS.map((key) => definition('transcription', key)), + ...COMMON_KEYS.map((key) => definition('synthesis', key)), + definition('synthesis', 'voice'), + integerDefinition( + speechSettingName('transcription', 'maxResponseBytes'), + DEFAULT_SPEECH_TRANSCRIPTION_MAX_RESPONSE_BYTES, + 'AI models', + 'Maximum transcription JSON response bytes, checked before parsing. Oversized transcripts are refused.', + { min: 1, max: 4 * 1024 * 1024 } + ), + integerDefinition( + speechSettingName('synthesis', 'maxAudioBytes'), + DEFAULT_SPEECH_SYNTHESIS_MAX_AUDIO_BYTES, + 'AI models', + 'Maximum combined audio response bytes per read-aloud request, shared across chunks. Oversized responses are refused before caching.', + { min: 1, max: 32 * 1024 * 1024 } + ), + integerDefinition( + speechSettingName(null, 'endpointTimeoutMs'), + DEFAULT_SPEECH_ENDPOINT_TIMEOUT_MS, + 'AI models', + 'Milliseconds SAM waits for one speech endpoint request (a recording to transcribe, or one chunk of read-aloud audio) before giving up.', + { min: 1_000, max: 600_000 } + ), + integerDefinition( + speechSettingName('synthesis', 'maxRequestsPerHour'), + DEFAULT_SPEECH_SYNTHESIS_REQUESTS_PER_HOUR, + 'AI models', + 'Read-aloud requests per user per hour on an installation using the text-to-speech endpoint. Every request counts, including ones answered from cached audio.', + { min: 1, max: 100_000 } + ), +]; diff --git a/apps/api/src/services/account-linking.ts b/apps/api/src/services/account-linking.ts new file mode 100644 index 0000000000..7d0023ff57 --- /dev/null +++ b/apps/api/src/services/account-linking.ts @@ -0,0 +1,141 @@ +/** Action-specific email reauthentication for explicit social links. Proof is never a session. */ +import type { BetterAuthOptions, BetterAuthPlugin } from 'better-auth'; +import { + addOAuthServerContext, + APIError, + createAuthMiddleware, + getAuthoritativeSessionFromCtx, + getOAuthState, +} from 'better-auth/api'; + +import type { Env } from '../env'; +import { maybeJsonRecord } from '../lib/runtime-validation'; +import { isAgentSignInSession, isPastHardExpiry } from './agent-sign-in/session-cap'; +import { emailSignInAvailable } from './email-sign-in'; + +export const LINKABLE_PROVIDERS = new Set(['github', 'gitlab']); + +type LinkSession = Awaited>; + +export function assertLinkSession(current: LinkSession) { + if ( + !current || + isAgentSignInSession(current.session) || + isPastHardExpiry(current.session) || + current.user.status === 'suspended' || + current.session.expiresAt.getTime() <= Date.now() + ) { + throw new APIError('FORBIDDEN', { + code: 'LINK_SESSION_REQUIRED', + message: 'Sign in again before connecting an account', + }); + } + return current; +} + +export function linkProofIdentifier(userId: string, sessionId: string, provider: string) { + return `account-link:${userId}:${sessionId}:${provider}`; +} + +export async function linkProofHash(token: string): Promise { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(''); +} + +/** Runs inside BetterAuth, after its origin gate and before its OAuth state generation. */ +export function accountLinkingPlugin(env: Env): BetterAuthPlugin { + return { + id: 'sam-account-linking', + hooks: { + before: [ + { + matcher: (ctx) => ctx.path === '/unlink-account', + handler: createAuthMiddleware(async (ctx) => { + const current = assertLinkSession(await getAuthoritativeSessionFromCtx(ctx)); + const body = maybeJsonRecord(ctx.body); + const rows = await ctx.context.internalAdapter.findAccounts(current.user.id); + const account = rows.find((row) => row.id === body?.accountId); + if (!account || !LINKABLE_PROVIDERS.has(account.providerId)) { + throw new APIError('BAD_REQUEST', { + message: 'Only connected GitHub or GitLab accounts can be removed here', + }); + } + if (!(current.user.emailVerified && emailSignInAvailable(env))) { + throw new APIError('BAD_REQUEST', { + code: 'LAST_SIGN_IN_METHOD', + message: + 'Confirm your account email and enable email sign-in before disconnecting a provider', + }); + } + }), + }, + { + matcher: (ctx) => ctx.path === '/link-social', + handler: createAuthMiddleware(async (ctx) => { + const body = maybeJsonRecord(ctx.body); + const provider = body?.provider; + if ( + typeof provider !== 'string' || + !LINKABLE_PROVIDERS.has(provider) || + body?.idToken + ) { + throw new APIError('BAD_REQUEST', { + code: 'LINK_PROVIDER_REFUSED', + message: 'Only GitHub and GitLab can be connected', + }); + } + const current = assertLinkSession(await getAuthoritativeSessionFromCtx(ctx)); + const token = maybeJsonRecord(body?.additionalData)?.samLinkToken; + if (typeof token !== 'string') throw stepUpRequired(); + const identifier = linkProofIdentifier(current.user.id, current.session.id, provider); + // All bindings participate in the atomic consume. A different session cannot burn proof. + const row = await env.DATABASE.prepare( + 'DELETE FROM verifications WHERE identifier = ? AND value = ? AND expires_at > ? RETURNING expires_at AS expiresAt' + ) + .bind(identifier, await linkProofHash(token), Date.now()) + .first<{ expiresAt: number }>(); + if (!row || typeof row.expiresAt !== 'number') throw stepUpRequired(); + await addOAuthServerContext({ + samAccountLink: { + userId: current.user.id, + sessionId: current.session.id, + provider, + expiresAt: row.expiresAt, + }, + }); + }), + }, + ], + }, + }; +} + +function stepUpRequired() { + return new APIError('FORBIDDEN', { + code: 'LINK_STEP_UP_REQUIRED', + message: 'Confirm this connection using the email sent to your account address', + }); +} + +/** Covers BOTH new links and token updates to an already-linked provider on callback. */ +export const validateLinkUserInfo: NonNullable< + NonNullable['validateUserInfo'] +> = async ({ user, source }, ctx) => { + if (source.action !== 'link-account') return; + const proof = maybeJsonRecord((await getOAuthState())?.serverContext?.samAccountLink); + const current = assertLinkSession(await getAuthoritativeSessionFromCtx(ctx)); + if ( + !proof || + proof.userId !== current.user.id || + user.id !== current.user.id || + proof.sessionId !== current.session.id || + proof.provider !== source.oauth?.providerId || + typeof proof.expiresAt !== 'number' || + proof.expiresAt <= Date.now() + ) { + return { + error: 'LINK_STEP_UP_REQUIRED', + errorDescription: 'Connection confirmation expired; start again in Settings', + }; + } +}; diff --git a/apps/api/src/services/acp-usage-callback-handler.ts b/apps/api/src/services/acp-usage-callback-handler.ts index 7f4f718917..e5645772d5 100644 --- a/apps/api/src/services/acp-usage-callback-handler.ts +++ b/apps/api/src/services/acp-usage-callback-handler.ts @@ -16,6 +16,7 @@ import { } from '../middleware/rate-limit'; import { type AcpActivityBinding, buildAcpActivityBinding } from './acp-activity-admission'; import { assertAcpActivityCallbackResourcesActive } from './acp-activity-callback-flush'; +import { type HarnessTokenUsageReport, recordHarnessTokenReport } from './agent-run-usage'; import { type CredentialLimitObservation, credentialLimitReferenceKey, @@ -48,6 +49,7 @@ export interface AcpUsageCallbackReport { observedAt?: number; source?: string; rateLimits: AcpUsageLimitObservationReport[]; + tokenUsage?: HarnessTokenUsageReport; } type ExistingAcpSession = NonNullable>>; @@ -418,6 +420,23 @@ export async function handleAcpUsageCallback( } const serverAttribution = await assertServerAttributionMatchesCallback(row, body); + if (body.tokenUsage && binding.chatSessionId) { + // Every identity is server-verified above: project and chat session from the bound ACP + // session and the D1 workspace row, the credential from the server's own attribution. + await recordHarnessTokenReport( + c.env, + { + projectId, + chatSessionId: binding.chatSessionId, + workspaceId: row.workspace_id, + agentSessionId: row.id, + agentType: row.agent_type ?? body.agentType ?? null, + credentialReference: serverAttribution?.credentialReference ?? null, + credentialSource: serverAttribution?.credentialSource ?? null, + }, + body.tokenUsage + ); + } if (!serverAttribution || body.rateLimits.length === 0) { log.info('acp_usage.no_supported_credential_limit_observation', { projectId, diff --git a/apps/api/src/services/admin-setting-definitions.ts b/apps/api/src/services/admin-setting-definitions.ts index 3fabedd78d..4a65416254 100644 --- a/apps/api/src/services/admin-setting-definitions.ts +++ b/apps/api/src/services/admin-setting-definitions.ts @@ -1,17 +1,23 @@ import type { DeploymentPublishJobSettingName } from '@simple-agent-manager/app-deployment'; import type { - InsightsFlowSettingName, + InsightsAgentSettingName, + InsightsCloudflareCostSettingName, + InsightsInstallationSettingName, + InsightsPageSettingName, InsightsReceiptSettingName, + ProjectBriefSettingName, } from '@simple-agent-manager/operations'; import type { Env } from '../env'; import { type GcpCatalogSettingName } from './admin-settings-gcp-catalog-definitions'; +import { type InfomaniakSettingName } from './admin-settings-infomaniak-definitions'; import { type InstructionBudgetSettingName } from './admin-settings-instructions-definitions'; import type { NodeTunnelSettingName } from './admin-settings-node-tunnel-definitions'; +import type { OrchestratorSettingName } from './admin-settings-orchestrator-definitions'; import { type OutboundSettingName } from './admin-settings-outbound-definitions'; import { type AgentEmailSettingName } from './agent-email/setting-definitions'; import { type AgentModelSettingKey } from './agent-models/settings-definition'; -import { type AiProxySettingName } from './ai-proxy-settings'; +import type { AiProxySettingName } from './ai-proxy-settings'; import { type ConnectorReadSettingName } from './connector-read-settings-definition'; import { CONNECTOR_DEFAULTS, @@ -21,10 +27,9 @@ import { import { type FleetOpsSettingName } from './fleet-ops/settings-definitions'; import { type InboxSettingName } from './inbox-settings-definition'; import { type LifecycleLatencySettingKey } from './lifecycle-latency/defaults'; -import { type LlmEndpointSettingName } from './llm-endpoint-settings'; +import type { LlmEndpointSettingName } from './llm-endpoint-settings'; import { type OperationsTelemetrySettingName } from './operations-telemetry-defaults'; import { type RuntimeSecretRequestSettingName } from './runtime-secret-request-settings-definition'; -import { type SpeechEndpointSettingName } from './speech-endpoint-settings'; import { type StalledClassifierEndpointSettingName } from './stalled-task-classifier-endpoint-settings'; import { type WORKFLOW_DEFAULTS } from './workflow-defaults'; @@ -33,11 +38,19 @@ export type AdminSettingValue = boolean | number | string | readonly string[] | export type AdminSettingType = 'boolean' | 'integer' | 'string' | 'string-list' | 'enum'; export type AdminSettingName = + | 'security.accountLinkProofTtlSeconds' + | LlmEndpointSettingName + | AiProxySettingName | DeploymentPublishJobSettingName + | 'credentialSetup.cleanupRecoveryStepTimeoutMs' + | 'credentialSetup.cleanupRecoveryMaxAttempts' | 'deployments.publishCallbackMaxBodyBytes' + | 'events.skipUnsubscribedGitHubCi' | 'chat.messageMergingEnabled' + | 'chat.toolCallMergingEnabled' | 'chat.messageMergeMaxRowBytes' | 'chat.messageMergeRecentIds' + | 'insights.runUsageMaxRowsPerSession' | `workflow.${keyof typeof WORKFLOW_DEFAULTS}` | `lifecycleLatency.${LifecycleLatencySettingKey}` | `aiModels.${AgentModelSettingKey}` @@ -45,16 +58,19 @@ export type AdminSettingName = | ConnectorReadSettingName | InboxSettingName | InsightsReceiptSettingName - | InsightsFlowSettingName + | InsightsPageSettingName + | InsightsInstallationSettingName + | InsightsCloudflareCostSettingName + | ProjectBriefSettingName + | InsightsAgentSettingName | RuntimeSecretRequestSettingName | AgentEmailSettingName | FleetOpsSettingName | NodeTunnelSettingName - | LlmEndpointSettingName - | AiProxySettingName - | SpeechEndpointSettingName | StalledClassifierEndpointSettingName + | OrchestratorSettingName | GcpCatalogSettingName + | InfomaniakSettingName | InstructionBudgetSettingName | OperationsTelemetrySettingName | OutboundSettingName @@ -176,6 +192,8 @@ export interface AdminSettingDefinition { readonly credential?: { readonly provider: string; readonly kind: string }; readonly range?: { readonly min: number; readonly max: number }; readonly choices?: readonly string[]; + /** Explicit fail-closed value for invalid overrides or unavailable storage; absent uses normal fallback. */ + readonly unavailableValue?: AdminSettingValue; readonly validate: (value: unknown) => boolean; } @@ -290,6 +308,10 @@ export function connectorDefinition(key: ConnectorSettingKey): AdminSettingDefin type, // Reuse the shipped defaults; integration will move their ownership here without duplication. defaultValue: Array.isArray(value) ? Object.freeze([...value]) : value, + // Invalid security controls must restrict access, not inherit permissive defaults. + ...(type === 'boolean' ? { unavailableValue: false } : {}), + ...(key === 'clientRegistration' ? { unavailableValue: 'allowlist' } : {}), + ...(key === 'allowedRedirectHosts' ? { unavailableValue: Object.freeze([]) } : {}), category: 'Connector', description: connectorDescriptions[key], secret: false, @@ -334,7 +356,7 @@ export function switchDefinition( defaultValue: boolean, category: AdminSettingDefinition['category'], description: string, - legacy: Pick + legacy: Pick ): AdminSettingDefinition { return { name, diff --git a/apps/api/src/services/admin-settings-account-linking-definitions.ts b/apps/api/src/services/admin-settings-account-linking-definitions.ts new file mode 100644 index 0000000000..76a731fea3 --- /dev/null +++ b/apps/api/src/services/admin-settings-account-linking-definitions.ts @@ -0,0 +1,13 @@ +import { type AdminSettingDefinition, integerDefinition } from './admin-setting-definitions'; + +export const DEFAULT_ACCOUNT_LINK_PROOF_TTL_SECONDS = 300; + +export const ACCOUNT_LINKING_SETTINGS: AdminSettingDefinition[] = [ + integerDefinition( + 'security.accountLinkProofTtlSeconds', + DEFAULT_ACCOUNT_LINK_PROOF_TTL_SECONDS, + 'Email', + 'Seconds to complete a one-time emailed account-link sign-in check, including provider consent. Applies to new confirmation emails; existing proofs retain their original deadline.', + { min: 60, max: 900 } + ), +]; diff --git a/apps/api/src/services/admin-settings-core-definitions.ts b/apps/api/src/services/admin-settings-core-definitions.ts index 1e3ddd33e0..767b29f346 100644 --- a/apps/api/src/services/admin-settings-core-definitions.ts +++ b/apps/api/src/services/admin-settings-core-definitions.ts @@ -20,6 +20,7 @@ import { DEFAULT_NODE_PROVIDER_DELETION_CONFIRM_MAX_MS, DEFAULT_NODE_PROVIDER_DELETION_REQUEST_TIMEOUT_MS, DEFAULT_NODE_PROVISIONING_ATTEMPT_DEADLINE_MS, + DEFAULT_RUN_USAGE_MAX_ROWS_PER_SESSION, DEFAULT_WEBHOOK_QUEUE_MAX_PENDING, DEFAULT_WEBHOOK_QUEUE_TTL_SECONDS, DEFAULT_WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, @@ -50,6 +51,17 @@ import { DEFAULT_CAPACITY_POOL_CANDIDATE_PUBLISH_BUDGET_MS } from './default-cap import { ENV_KEYS, SECRET_KINDS, SETTING_KEYS } from './platform-config-store'; import { DEFAULT_SESSION_STALE_TURN_NO_WORK_MINUTES } from './session-idleness'; export const CORE_SETTINGS: AdminSettingDefinition[] = [ + { + ...integerDefinition( + 'insights.runUsageMaxRowsPerSession', + DEFAULT_RUN_USAGE_MAX_ROWS_PER_SESSION, + 'Operations', + 'Lifetime bound on new harness usage rows per chat across epochs, models and credentials. Existing counters remain updatable; history is never deleted.', + { min: 1, max: 10000 } + ), + // Refuse new keys if policy cannot be resolved; existing counters still update. + unavailableValue: 0, + }, integerDefinition( 'operations.nodeCleanupRefusalWarnAfterMs', DEFAULT_CLEANUP_REFUSAL_WARN_AFTER_MS, diff --git a/apps/api/src/services/admin-settings-credential-setup-definitions.ts b/apps/api/src/services/admin-settings-credential-setup-definitions.ts new file mode 100644 index 0000000000..5beeea1347 --- /dev/null +++ b/apps/api/src/services/admin-settings-credential-setup-definitions.ts @@ -0,0 +1,21 @@ +import { type AdminSettingDefinition, integerDefinition } from './admin-setting-definitions'; + +export const DEFAULT_SETUP_SESSION_CLEANUP_RECOVERY_STEP_TIMEOUT_MS = 5_000; +export const DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS = 3; + +export const CREDENTIAL_SETUP_SETTINGS: readonly AdminSettingDefinition[] = [ + integerDefinition( + 'credentialSetup.cleanupRecoveryStepTimeoutMs', + DEFAULT_SETUP_SESSION_CLEANUP_RECOVERY_STEP_TIMEOUT_MS, + 'Operations', + 'Per-step deadline in milliseconds for guided-login cleanup recovery: D1 repair, sandbox scrub, destruction and pool release each get this budget, capped by the interactive sandbox exec timeout. The retry cap is configured separately.', + { min: 1, max: 10_000 } + ), + integerDefinition( + 'credentialSetup.cleanupRecoveryMaxAttempts', + DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS, + 'Operations', + 'Maximum failed guided-login cleanup recovery attempts before quarantine, snapshotted when recovery first starts. A nonzero cap preserves cleanup; the finite maximum bounds recovery work.', + { min: 1, max: 10 } + ), +]; diff --git a/apps/api/src/services/admin-settings-features-definitions.ts b/apps/api/src/services/admin-settings-features-definitions.ts index 40a3c04c40..ff9806989c 100644 --- a/apps/api/src/services/admin-settings-features-definitions.ts +++ b/apps/api/src/services/admin-settings-features-definitions.ts @@ -1,5 +1,8 @@ import { - INSIGHTS_FLOW_SETTINGS, + INSIGHTS_AGENT_SETTINGS, + INSIGHTS_CLOUDFLARE_COST_SETTINGS, + INSIGHTS_INSTALLATION_SETTINGS, + INSIGHTS_PAGE_SETTINGS, INSIGHTS_RECEIPT_SETTINGS, } from '@simple-agent-manager/operations'; import { DEFAULT_COMMENT_NOTIFICATION_WINDOW_MS } from '@simple-agent-manager/shared'; @@ -160,7 +163,34 @@ export const FEATURE_SETTINGS: AdminSettingDefinition[] = [ setting.range ) ), - ...INSIGHTS_FLOW_SETTINGS.map((setting) => + ...INSIGHTS_PAGE_SETTINGS.map((setting) => + integerDefinition( + setting.name, + setting.defaultValue, + 'Operations', + setting.description, + setting.range + ) + ), + ...INSIGHTS_INSTALLATION_SETTINGS.map((setting) => + integerDefinition( + setting.name, + setting.defaultValue, + 'Operations', + setting.description, + setting.range + ) + ), + ...INSIGHTS_AGENT_SETTINGS.map((setting) => + integerDefinition( + setting.name, + setting.defaultValue, + 'Operations', + setting.description, + setting.range + ) + ), + ...INSIGHTS_CLOUDFLARE_COST_SETTINGS.map((setting) => integerDefinition( setting.name, setting.defaultValue, @@ -353,6 +383,7 @@ export const FEATURE_SETTINGS: AdminSettingDefinition[] = [ OPERATOR_DEFAULTS.disabled, 'Operations', 'Disable the private SAM assistant for every account. Does not opt users in.', - {} + // Inverse polarity: containment requires the disabled switch to be true. + { unavailableValue: true } ), ]; diff --git a/apps/api/src/services/admin-settings-infomaniak-definitions.ts b/apps/api/src/services/admin-settings-infomaniak-definitions.ts new file mode 100644 index 0000000000..83c97eca4b --- /dev/null +++ b/apps/api/src/services/admin-settings-infomaniak-definitions.ts @@ -0,0 +1,19 @@ +import { + DEFAULT_INFOMANIAK_BOOT_VOLUME_GB, + INFOMANIAK_BOOT_VOLUME_MAX_GB, + INFOMANIAK_BOOT_VOLUME_MIN_GB, +} from '@simple-agent-manager/shared'; + +import { type AdminSettingDefinition, integerDefinition } from './admin-setting-definitions'; + +export type InfomaniakSettingName = 'infomaniak.bootVolumeGb'; + +export const INFOMANIAK_SETTINGS: readonly AdminSettingDefinition[] = [ + integerDefinition( + 'infomaniak.bootVolumeGb', + DEFAULT_INFOMANIAK_BOOT_VOLUME_GB, + 'Operations', + "Size in GB of the volume new Infomaniak VMs boot from, instead of the flavor's small local root disk. Applies to the catalog and new VMs from the next catalog refresh; running VMs keep their disk.", + { min: INFOMANIAK_BOOT_VOLUME_MIN_GB, max: INFOMANIAK_BOOT_VOLUME_MAX_GB } + ), +]; diff --git a/apps/api/src/services/admin-settings-invalid-stored.ts b/apps/api/src/services/admin-settings-invalid-stored.ts new file mode 100644 index 0000000000..e2d9e339bf --- /dev/null +++ b/apps/api/src/services/admin-settings-invalid-stored.ts @@ -0,0 +1,48 @@ +import { log } from '../lib/logger'; +import type { AdminSettingDefinition, AdminSettingValue } from './admin-settings-registry'; +import type { OverrideRows } from './admin-settings-resolution'; + +/** Distinguish a bad override from a storage or dependency outage. */ +export class InvalidStoredAdminSettingError extends Error {} + +// Bounded by registry keys per database binding. Never serialize stored values into logs. +const warnedRows = new WeakMap>(); + +/** Admin presentation only: runtime keeps its safety-specific outage fallback. */ +export function invalidStoredSettingDetails( + db: D1Database, + def: AdminSettingDefinition, + rows: OverrideRows, + fallbackValue: AdminSettingValue +) { + const row = rows.find((row) => row.key === def.name); + if (!row) throw new InvalidStoredAdminSettingError('Stored override row missing'); + let warned = warnedRows.get(db); + if (!warned) { + warned = new Map(); + warnedRows.set(db, warned); + } + const version = JSON.stringify([row.updatedAt, row.value]); + if (warned.get(def.name) !== version) { + warned.set(def.name, version); + log.warn('admin_settings.invalid_stored_value', { + key: def.name, + context: 'platform_settings', + reason: 'Stored override fails current definition validation', + action: 'show_fallback', + }); + } + return { + value: def.secret ? null : fallbackValue, + storedValueFallback: + JSON.stringify(fallbackValue) === JSON.stringify(def.defaultValue) + ? ('default' as const) + : ('safe' as const), + configured: false, + source: 'default' as const, + storedValueInvalid: true as const, + ...(def.secret ? {} : { storedValue: row.value }), + updatedAt: row.updatedAt, + updatedBy: row.updatedBy, + }; +} diff --git a/apps/api/src/services/admin-settings-message-merge-definitions.ts b/apps/api/src/services/admin-settings-message-merge-definitions.ts index b80b3bd335..2841afaf13 100644 --- a/apps/api/src/services/admin-settings-message-merge-definitions.ts +++ b/apps/api/src/services/admin-settings-message-merge-definitions.ts @@ -7,6 +7,13 @@ import { } from './admin-setting-definitions'; export const MESSAGE_MERGE_SETTINGS: AdminSettingDefinition[] = [ + switchDefinition( + 'chat.toolCallMergingEnabled', + DEFAULT_MESSAGE_MERGE_CONFIG.toolUpdatesEnabled, + 'Operations', + 'Store one current snapshot per agent tool call. Disable to resume individual tool notification rows.', + {} + ), switchDefinition( 'chat.messageMergingEnabled', DEFAULT_MESSAGE_MERGE_CONFIG.enabled, diff --git a/apps/api/src/services/admin-settings-mutations.ts b/apps/api/src/services/admin-settings-mutations.ts index 72a6386597..45f0aa1a73 100644 --- a/apps/api/src/services/admin-settings-mutations.ts +++ b/apps/api/src/services/admin-settings-mutations.ts @@ -4,8 +4,8 @@ import { getCredentialEncryptionKey } from '../lib/secrets'; import { AppError, errors } from '../middleware/error'; import { AdminSettingsUnavailableError } from './admin-settings-cache'; import { - ADMIN_SETTINGS_REGISTRY, type AdminSettingName, + adminSettingsRegistry, type AdminSettingValue, findAdminSetting, } from './admin-settings-registry'; @@ -181,7 +181,7 @@ function validateMutationInput(input: { }): void { if ( !input.changes.length || - input.changes.length > ADMIN_SETTINGS_REGISTRY.length || + input.changes.length > adminSettingsRegistry().length || new Set(input.changes.map((x) => x.name)).size !== input.changes.length || input.changes.some( (change) => diff --git a/apps/api/src/services/admin-settings-orchestrator-definitions.ts b/apps/api/src/services/admin-settings-orchestrator-definitions.ts new file mode 100644 index 0000000000..e9b08fc7ef --- /dev/null +++ b/apps/api/src/services/admin-settings-orchestrator-definitions.ts @@ -0,0 +1,52 @@ +import { type AdminSettingDefinition, integerDefinition } from './admin-setting-definitions'; + +export const MISSION_CANCELLATION_DEFAULTS = { + pageSize: 25, + turnMs: 5_000, + retryPasses: 3, + residenceMs: 900_000, + intervalMs: 1_000, +} as const; + +export const MISSION_CANCELLATION_SETTING_NAMES = { + pageSize: 'orchestrator.cancellationPageSize', + turnMs: 'orchestrator.cancellationTurnMs', + retryPasses: 'orchestrator.cancellationRetryPasses', + residenceMs: 'orchestrator.cancellationResidenceMs', + intervalMs: 'orchestrator.cancellationIntervalMs', +} as const; + +export type OrchestratorSettingName = + (typeof MISSION_CANCELLATION_SETTING_NAMES)[keyof typeof MISSION_CANCELLATION_SETTING_NAMES]; + +const details = { + pageSize: { max: 100, description: 'Maximum tasks visited in one mission cancellation turn.' }, + turnMs: { + max: 30_000, + description: 'Elapsed work budget in milliseconds for one mission cancellation turn.', + }, + retryPasses: { + max: 10, + description: 'Maximum cancellation passes before explicit retry is required.', + }, + residenceMs: { + max: 86_400_000, + description: 'Maximum mission cancellation episode residence in milliseconds before blocking.', + }, + intervalMs: { + max: 300_000, + description: 'Alarm delay in milliseconds between pending mission cancellation turns.', + }, +} as const; + +export const ORCHESTRATOR_SETTINGS: readonly AdminSettingDefinition[] = ( + Object.keys(MISSION_CANCELLATION_DEFAULTS) as Array +).map((key) => + integerDefinition( + MISSION_CANCELLATION_SETTING_NAMES[key], + MISSION_CANCELLATION_DEFAULTS[key], + 'Operations', + details[key].description, + { min: 1, max: details[key].max } + ) +); diff --git a/apps/api/src/services/admin-settings-outbound-definitions.ts b/apps/api/src/services/admin-settings-outbound-definitions.ts index f800707d0a..70f84d5f96 100644 --- a/apps/api/src/services/admin-settings-outbound-definitions.ts +++ b/apps/api/src/services/admin-settings-outbound-definitions.ts @@ -22,7 +22,7 @@ export const OUTBOUND_SETTINGS: readonly AdminSettingDefinition[] = [ 'outbound.maxRedirects', DEFAULT_OUTBOUND_MAX_REDIRECTS, 'Operations', - 'Redirect hops a guarded outbound request follows when the server it calls answers with a redirect (today: check_dns_status, whose workspace host is answered by a node the user controls; it also stays on the workspace origin). Every hop is re-checked; 0 refuses every redirect.', + 'Redirect hops a guarded outbound request follows when the server it calls answers with a redirect (including GitLab profile/API calls and check_dns_status; DNS checks also stay on the workspace origin). Every hop is re-checked; 0 refuses every redirect.', { min: 0, max: MAX_OUTBOUND_REDIRECTS } ), switchDefinition( diff --git a/apps/api/src/services/admin-settings-overview-brief-definitions.ts b/apps/api/src/services/admin-settings-overview-brief-definitions.ts new file mode 100644 index 0000000000..8972c29cc6 --- /dev/null +++ b/apps/api/src/services/admin-settings-overview-brief-definitions.ts @@ -0,0 +1,35 @@ +/** + * Project Overview brief controls (inbox slice I). The definitions live in + * `@simple-agent-manager/operations` beside the resolver the Overview read and the generator use; + * this file registers them in the admin settings registry under "AI models", next to the other + * platform model spend controls. + */ +import { + PROJECT_BRIEF_ENABLED_SETTING, + PROJECT_BRIEF_INTEGER_SETTINGS, +} from '@simple-agent-manager/operations'; + +import { + type AdminSettingDefinition, + integerDefinition, + switchDefinition, +} from './admin-setting-definitions'; + +export const OVERVIEW_BRIEF_SETTINGS: AdminSettingDefinition[] = [ + switchDefinition( + PROJECT_BRIEF_ENABLED_SETTING.name, + PROJECT_BRIEF_ENABLED_SETTING.defaultValue, + 'AI models', + PROJECT_BRIEF_ENABLED_SETTING.description, + {} + ), + ...PROJECT_BRIEF_INTEGER_SETTINGS.map((setting) => + integerDefinition( + setting.name, + setting.defaultValue, + 'AI models', + setting.description, + setting.range + ) + ), +]; diff --git a/apps/api/src/services/admin-settings-project-event-definitions.ts b/apps/api/src/services/admin-settings-project-event-definitions.ts new file mode 100644 index 0000000000..ae89bd4b16 --- /dev/null +++ b/apps/api/src/services/admin-settings-project-event-definitions.ts @@ -0,0 +1,11 @@ +import { type AdminSettingDefinition, switchDefinition } from './admin-setting-definitions'; + +export const PROJECT_EVENT_SETTINGS: AdminSettingDefinition[] = [ + switchDefinition( + 'events.skipUnsubscribedGitHubCi', + true, + 'Operations', + 'Skip storing unmatched GitHub check_run, check_suite and workflow_run events. The event inspector shows volatile admission counts instead of skipped event history. Disable to restore full CI history for future admissions.', + {} + ), +]; diff --git a/apps/api/src/services/admin-settings-registry.ts b/apps/api/src/services/admin-settings-registry.ts index 9299e69116..b4357844be 100644 --- a/apps/api/src/services/admin-settings-registry.ts +++ b/apps/api/src/services/admin-settings-registry.ts @@ -1,20 +1,24 @@ import type { AdminSettingDefinition } from './admin-setting-definitions'; +import { ACCOUNT_LINKING_SETTINGS } from './admin-settings-account-linking-definitions'; import { CORE_SETTINGS } from './admin-settings-core-definitions'; +import { CREDENTIAL_SETUP_SETTINGS } from './admin-settings-credential-setup-definitions'; import { DEPLOYMENT_PUBLISH_SETTINGS } from './admin-settings-deployment-publish-definitions'; import { FEATURE_SETTINGS } from './admin-settings-features-definitions'; import { GCP_CATALOG_SETTINGS } from './admin-settings-gcp-catalog-definitions'; +import { INFOMANIAK_SETTINGS } from './admin-settings-infomaniak-definitions'; import { INSTRUCTION_BUDGET_SETTINGS } from './admin-settings-instructions-definitions'; import { LIFECYCLE_LATENCY_SETTINGS } from './admin-settings-lifecycle-latency-definitions'; import { MESSAGE_MERGE_SETTINGS } from './admin-settings-message-merge-definitions'; import { NODE_TUNNEL_SETTINGS } from './admin-settings-node-tunnel-definitions'; import { OPERATIONS_TELEMETRY_SETTINGS } from './admin-settings-operations-telemetry-definitions'; import { OPERATOR_SETTINGS } from './admin-settings-operator-definitions'; +import { ORCHESTRATOR_SETTINGS } from './admin-settings-orchestrator-definitions'; import { OUTBOUND_SETTINGS } from './admin-settings-outbound-definitions'; +import { OVERVIEW_BRIEF_SETTINGS } from './admin-settings-overview-brief-definitions'; +import { PROJECT_EVENT_SETTINGS } from './admin-settings-project-event-definitions'; import { AI_PROXY_SETTINGS } from './ai-proxy-settings'; import { llmEndpointSettingDefinitions } from './llm-endpoint-settings'; -import { SPEECH_ENDPOINT_SETTINGS } from './speech-endpoint-settings'; import { STALLED_CLASSIFIER_ENDPOINT_SETTINGS } from './stalled-task-classifier-endpoint-settings'; - export { type AdminSettingDefinition, type AdminSettingName, @@ -31,37 +35,78 @@ export { OPERATOR_DEFAULTS, } from './admin-setting-definitions'; const definitions = [ + ...ACCOUNT_LINKING_SETTINGS, + ...llmEndpointSettingDefinitions(), + ...AI_PROXY_SETTINGS, ...MESSAGE_MERGE_SETTINGS, + ...PROJECT_EVENT_SETTINGS, ...DEPLOYMENT_PUBLISH_SETTINGS, ...CORE_SETTINGS, + ...CREDENTIAL_SETUP_SETTINGS, ...NODE_TUNNEL_SETTINGS, ...FEATURE_SETTINGS, ...GCP_CATALOG_SETTINGS, + ...INFOMANIAK_SETTINGS, ...OPERATOR_SETTINGS, + ...ORCHESTRATOR_SETTINGS, ...LIFECYCLE_LATENCY_SETTINGS, ...OPERATIONS_TELEMETRY_SETTINGS, ...OUTBOUND_SETTINGS, - ...llmEndpointSettingDefinitions(), - ...AI_PROXY_SETTINGS, - ...SPEECH_ENDPOINT_SETTINGS, ...STALLED_CLASSIFIER_ENDPOINT_SETTINGS, ...INSTRUCTION_BUDGET_SETTINGS, + ...OVERVIEW_BRIEF_SETTINGS, ]; +function frozenDefinition(definition: AdminSettingDefinition): AdminSettingDefinition { + return Object.freeze({ + ...definition, + ...(definition.range ? { range: Object.freeze(definition.range) } : {}), + ...(definition.choices ? { choices: Object.freeze(definition.choices) } : {}), + ...(definition.credential ? { credential: Object.freeze(definition.credential) } : {}), + }); +} + +/** Settings every build has. */ export const ADMIN_SETTINGS_REGISTRY: readonly AdminSettingDefinition[] = Object.freeze( - definitions.map((definition) => - Object.freeze({ - ...definition, - ...(definition.range ? { range: Object.freeze(definition.range) } : {}), - ...(definition.choices ? { choices: Object.freeze(definition.choices) } : {}), - ...(definition.credential ? { credential: Object.freeze(definition.credential) } : {}), - }) - ) + definitions.map(frozenDefinition) ); +let registry: readonly AdminSettingDefinition[] = ADMIN_SETTINGS_REGISTRY; +let installed = new WeakSet(); + +/** + * Adds settings only a separately built entry has (the self-host build's speech endpoints, + * selfhost/speech/). Called once at entry initialization, before any request. The Cloudflare + * Worker installs nothing, so its registry is exactly `ADMIN_SETTINGS_REGISTRY`. Installing the + * same definition objects again is a no-op; a name that is already registered otherwise throws. + */ +export function installAdminSettingDefinitions(added: readonly AdminSettingDefinition[]): void { + const fresh = added.filter((definition) => !installed.has(definition)); + const names = new Set(registry.map((definition) => definition.name)); + for (const definition of fresh) { + if (names.has(definition.name)) { + throw new Error(`Admin setting ${definition.name} is already registered`); + } + names.add(definition.name); + } + for (const definition of fresh) installed.add(definition); + registry = Object.freeze([...registry, ...fresh.map(frozenDefinition)]); +} + +/** Test seam: back to the settings every build has. */ +export function resetInstalledAdminSettingDefinitionsForTests(): void { + registry = ADMIN_SETTINGS_REGISTRY; + installed = new WeakSet(); +} + +/** Every setting this build has: the shared registry plus any installed by the build's entry. */ +export function adminSettingsRegistry(): readonly AdminSettingDefinition[] { + return registry; +} + /** Never resolve untrusted names through inherited object properties. */ export function findAdminSetting(name: string): AdminSettingDefinition | undefined { - return ADMIN_SETTINGS_REGISTRY.find((definition) => definition.name === name); + return registry.find((definition) => definition.name === name); } /** Metadata only. Secret effective values must be separately projected to configured/source. */ diff --git a/apps/api/src/services/admin-settings-resolution.ts b/apps/api/src/services/admin-settings-resolution.ts index 03a41d19d1..4ea24d80fd 100644 --- a/apps/api/src/services/admin-settings-resolution.ts +++ b/apps/api/src/services/admin-settings-resolution.ts @@ -12,9 +12,13 @@ import { } from './admin-settings-cache'; import { DecryptedCredentialValues } from './admin-settings-credential-values'; import { - ADMIN_SETTINGS_REGISTRY, + InvalidStoredAdminSettingError, + invalidStoredSettingDetails, +} from './admin-settings-invalid-stored'; +import { type AdminSettingDefinition, type AdminSettingName, + adminSettingsRegistry, type AdminSettingValue, findAdminSetting, publicAdminSettingDefinition, @@ -23,7 +27,6 @@ import { readAdminSettingsSnapshot } from './admin-settings-snapshot'; import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from './config-read-deadline'; import { withDeadline } from './fetch-timeout'; import { INTEGRATION_CREDENTIAL_TYPE } from './platform-config-store'; - export function requiredDefinition(name: string): AdminSettingDefinition { const def = findAdminSetting(name); if (!def) throw errors.badRequest('Unknown admin setting'); @@ -33,11 +36,11 @@ export const cache = new AdminSettingsCache(); let generations = new WeakMap(); let generationClock = 0; let resetGeneration = 0; -function generationOf(db: D1Database): number { +export function adminSettingsGeneration(db: D1Database): number { return generations.get(db) ?? resetGeneration; } function assertGeneration(db: D1Database, generation: number): void { - if (generationOf(db) !== generation) throw new AdminSettingsUnavailableError(); + if (adminSettingsGeneration(db) !== generation) throw new AdminSettingsUnavailableError(); } export type CredentialRow = { provider: string; @@ -66,7 +69,7 @@ export async function credentialRows( if (attempt >= 3) throw new AdminSettingsUnavailableError(); const db = resolveD1BindingIdentity(env.DATABASE); if (!db || typeof db.prepare !== 'function') throw new AdminSettingsUnavailableError(); - const generation = generationOf(db); + const generation = adminSettingsGeneration(db); const ttlMs = adminSettingCacheMs(env, 'integration.github.clientSecret'); const useCache = !fresh && ttlMs > 0; const existing = credentialCache.get(db); @@ -113,7 +116,7 @@ export async function credentialRows( if (useCache && credentialCache.get(db) !== entry) return credentialRows(env, false, attempt + 1); if ( - generationOf(db) !== generation || + adminSettingsGeneration(db) !== generation || Date.now() >= entry.deadlineAt || (ttlMs > 0 && Date.now() >= entry.expiresAt) ) @@ -155,7 +158,7 @@ async function legacyKv( } if (attempt >= 3) throw new AdminSettingsUnavailableError(); const db = resolveD1BindingIdentity(env.DATABASE); - const generation = generationOf(db); + const generation = adminSettingsGeneration(db); let map = kvCache.get(db); if (!map) { map = new Map(); @@ -175,7 +178,7 @@ async function legacyKv( const value = joined.value; if (map.get(key) !== cached) return legacyKv(env, key, false, ttlMs, attempt + 1); if ( - generationOf(db) !== generation || + adminSettingsGeneration(db) !== generation || Date.now() >= Math.min(cached.expiresAt, cached.startedAt + ttlMs) ) throw new AdminSettingsUnavailableError(); @@ -193,7 +196,7 @@ async function legacyKv( const value = await entry.promise; if (useCache && map.get(key) !== entry) return legacyKv(env, key, false, ttlMs, attempt + 1); if ( - generationOf(db) !== generation || + adminSettingsGeneration(db) !== generation || Date.now() >= entry.deadlineAt || (ttlMs > 0 && Date.now() >= entry.expiresAt) ) @@ -304,7 +307,7 @@ async function overrideDetails( const row = rows.find((row) => row.key === def.name); if (!row) return null; const value = parseValue(def, row.value); - if (!validStoredValue(def, value)) throw new AdminSettingsUnavailableError(); + if (!validStoredValue(def, value)) throw new InvalidStoredAdminSettingError(); if (value === true && (await hasEmergencyVeto(env, def, fresh, kvReads))) return kvDetails(env, def, false); observe(env, def.name, value as AdminSettingValue); @@ -380,7 +383,7 @@ export async function resolveAdminSettingDetailsMany( const primary = resolveD1BindingIdentity(env.DATABASE); const maxAge = Math.min(...names.map((name) => adminSettingCacheMs(env, name))); for (let attempt = 0; attempt < 3; attempt++) { - const generation = generationOf(primary); + const generation = adminSettingsGeneration(primary); try { const [rows, credentials] = await Promise.all([ cache.read(primary, options.fresh ?? false, maxAge, DEFAULT_CONFIG_READ_TIMEOUT_MS), @@ -391,10 +394,10 @@ export async function resolveAdminSettingDetailsMany( const values = await Promise.all( definitions.map((def) => resolved(env, def, rows, true, credentials)) ); - if (generationOf(primary) !== generation) continue; + if (adminSettingsGeneration(primary) !== generation) continue; return values; } catch { - if (generationOf(primary) !== generation) continue; + if (adminSettingsGeneration(primary) !== generation) continue; throw new AdminSettingsUnavailableError(); } } @@ -443,8 +446,7 @@ function outageValue( def: AdminSettingDefinition, name: AdminSettingName ): AdminSettingValue { - // This switch has inverse polarity: true is the safe state on a settings outage. - if (name === 'operations.samOperatorDisabled') return true; + if (def.unavailableValue !== undefined) return def.unavailableValue; if ( def.legacyEnvironment && typeof env[def.legacyEnvironment] === 'string' && @@ -452,13 +454,10 @@ function outageValue( ) return false; if (def.type === 'boolean') { - if (name.startsWith('connector.')) return false; return disabled.get(resolveD1BindingIdentity(env.DATABASE))?.has(name) ? false : def.defaultValue; } - if (name === 'connector.clientRegistration') return 'allowlist'; - if (name === 'connector.allowedRedirectHosts') return []; if (def.category === 'OAuth') return null; return def.defaultValue; } @@ -470,7 +469,7 @@ export async function readAdminSettings(env: Env, options: { fresh?: boolean } = DEFAULT_CONFIG_READ_TIMEOUT_MS ); const kvReads = new Map>(); - for (const def of ADMIN_SETTINGS_REGISTRY) { + for (const def of adminSettingsRegistry()) { const key = operationalKvKey(env, def); if (key && !kvReads.has(key)) kvReads.set( @@ -485,10 +484,21 @@ export async function readAdminSettings(env: Env, options: { fresh?: boolean } = if (snapshot.revision === undefined) throw new AdminSettingsUnavailableError(); const { rows, credentials } = snapshot; const settings = await Promise.all( - ADMIN_SETTINGS_REGISTRY.map(async (def) => ({ - ...publicAdminSettingDefinition(def), - ...(await resolved(env, def, rows, false, credentials, options.fresh ?? true, kvReads)), - })) + adminSettingsRegistry().map(async (def) => { + const definition = publicAdminSettingDefinition(def); + try { + return { + ...definition, + ...(await resolved(env, def, rows, false, credentials, options.fresh ?? true, kvReads)), + }; + } catch (error) { + if (!(error instanceof InvalidStoredAdminSettingError)) throw error; + const fallback = (await hasEmergencyVeto(env, def, true, kvReads)) + ? false + : outageValue(env, def, def.name); + return { ...definition, ...invalidStoredSettingDetails(primary, def, rows, fallback) }; + } + }) ); return { revision: snapshot.revision, settings, history: snapshot.history }; } catch { @@ -496,5 +506,4 @@ export async function readAdminSettings(env: Env, options: { fresh?: boolean } = } } export type AdminSettingsView = Awaited>; - export { adminSettingCacheMs } from './admin-settings-cache'; diff --git a/apps/api/src/services/agent-bootstrap-prompt.ts b/apps/api/src/services/agent-bootstrap-prompt.ts index b0f0ca1c86..80edccb91f 100644 --- a/apps/api/src/services/agent-bootstrap-prompt.ts +++ b/apps/api/src/services/agent-bootstrap-prompt.ts @@ -38,6 +38,10 @@ export function buildSamBootstrapInstructions(_input: { return ( `IMPORTANT: Before starting any work, you MUST call the \`get_instructions\` tool from the sam-mcp MCP server. ` + `This provides your task context, project information, output branch name, and instructions for reporting progress. ` + - `Do not proceed until you have called this tool and read its response.` + `Do not proceed until you have called this tool and read its response. ` + + // Agents answered in the chat out of habit even with the inbox rule in get_instructions + // (staging, 2026-11-18), so the first thing they read points at it. Accurate for every + // context: a chat without inbox tools is told to answer in the chat. + `Its response also tells you how to deliver your answer: the person may not read this chat.` ); } diff --git a/apps/api/src/services/agent-email/self-host-inbound.ts b/apps/api/src/services/agent-email/self-host-inbound.ts index 8440463d28..ef2f0669a6 100644 --- a/apps/api/src/services/agent-email/self-host-inbound.ts +++ b/apps/api/src/services/agent-email/self-host-inbound.ts @@ -4,7 +4,7 @@ * Inbound: the box's sam-mx SMTP receiver (deploy/selfhost/sam-mx, compose profile `mail-in`) * accepts mail for `agents.`, checks that the From domain is authenticated (aligned * SPF or DKIM), and posts each message during the SMTP session to the loopback gateway route - * `POST /api/self-host/gateway/inbound-email` (routes/self-host-gateway-inbound-email.ts), which + * `POST /api/self-host/gateway/inbound-email` (selfhost/reverse-tunnel/inbound-email.ts), which * calls the same `handleInboundAgentEmail` the Worker's `email()` export calls on Cloudflare. * * Outbound: replies go through the SMTP relay SAM already uses for sign-in codes @@ -28,7 +28,12 @@ import { import { AGENT_EMAIL_LOCAL_PART } from '@simple-agent-manager/shared'; import type { Env } from '../../env'; -import { getReverseTunnelGatewaySecret } from '../node-reverse-tunnel-config'; + +/** + * Must equal `MIN_REVERSE_TUNNEL_GATEWAY_SECRET_LENGTH` in selfhost/reverse-tunnel/config.ts + * (pinned by tests/unit/selfhost/inbound-email-gateway-secret.test.ts). + */ +export const MIN_GATEWAY_SECRET_LENGTH = 32; export type SelfHostInboundEnv = EmailTransportEnv & Pick; @@ -37,7 +42,12 @@ export type SelfHostInboundEnv = EmailTransportEnv & export function isSelfHostInboundEmailConfigured(env: SelfHostInboundEnv): boolean { if (env.AGENT_EMAIL || !env.BASE_DOMAIN?.trim()) return false; if (env.AGENT_EMAIL_INBOUND_SMTP?.trim().toLowerCase() !== 'true') return false; - if (!getReverseTunnelGatewaySecret(env)) return false; + // The box gateway that hands mail over (selfhost/reverse-tunnel/gateway.ts, self-host build + // only) refuses a missing or short secret; mirror its rule without importing the self-host + // module into Worker-loaded code. + if ((env.REVERSE_TUNNEL_GATEWAY_SECRET?.trim().length ?? 0) < MIN_GATEWAY_SECRET_LENGTH) { + return false; + } return emailTransportKind(env) === 'smtp'; } diff --git a/apps/api/src/services/agent-run-usage.ts b/apps/api/src/services/agent-run-usage.ts new file mode 100644 index 0000000000..5a9fffce25 --- /dev/null +++ b/apps/api/src/services/agent-run-usage.ts @@ -0,0 +1,391 @@ +/** + * Insights slice U: writers for `agent_run_usage` (migration 0253), measured token usage per run. + * + * Two sources, never mixed in one row: + * - `harness`: cumulative totals the VM agent reports on the usage callback + * (`handleAcpUsageCallback`). Each report carries the running totals of one usage epoch, so the + * upsert takes a per-column MAX: a repeated report changes nothing, an older report arriving late + * cannot lower a newer one, and a report lost in between is healed by the next. + * - `ai_proxy`: one measured upstream response at a time, added to the run's row. + * + * Reads live in `packages/operations/src/insights-run-usage.ts`. Rows store a credential KEY + * (`credentialLimitReferenceKey`), never a secret. + */ +import type { MeasuredTokenUsage } from '@simple-agent-manager/ai-proxy'; +import { RUN_USAGE_MAX_TOKENS_PER_COUNTER } from '@simple-agent-manager/shared'; + +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import { resolveAdminSetting } from './admin-settings'; +import { credentialLimitReferenceKey } from './credential-limit-events'; + +export const AI_PROXY_USAGE_EPOCH = 'ai_proxy'; + +export interface RunUsageModelCounts { + /** '' when the harness did not say which model ran. */ + model: string; + inputTokens: number; + outputTokens: number; + cacheReadTokens: number; + cacheWriteTokens: number; + /** Null when reasoning is not reported separately (it is then part of output). */ + reasoningTokens: number | null; +} + +export interface RunUsageScope { + projectId: string; + chatSessionId: string; + workspaceId: string | null; + agentSessionId: string | null; + agentType: string | null; + credentialReference: string | null; + credentialSource: string | null; +} + +const UPSERT_COLUMNS = `project_id, chat_session_id, workspace_id, agent_session_id, source, usage_epoch, + model, credential_key, credential_source, agent_type, input_tokens, output_tokens, + cache_read_tokens, cache_write_tokens, reasoning_tokens, created_at, updated_at`; +const UPSERT_VALUES = '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?'; +const CONFLICT_KEY = 'project_id, chat_session_id, source, usage_epoch, model, credential_key'; + +/** + * Admit all novel model keys in one statement or none; existing keys remain updatable. The count and insert share SQLite's write boundary, + * so concurrent client-selected epochs cannot race past the configured per-run row ceiling. + */ +const HARNESS_ADMISSION_CTE = `WITH report( + project_id, chat_session_id, workspace_id, agent_session_id, usage_epoch, credential_key, + credential_source, agent_type, reported_at, max_rows, models_json + ) AS (VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)), + incoming_raw AS ( + SELECT + TRIM(CAST(json_extract(model.value, '$.model') AS TEXT)) AS model, + CAST(json_extract(model.value, '$.inputTokens') AS INTEGER) AS input_tokens, + CAST(json_extract(model.value, '$.outputTokens') AS INTEGER) AS output_tokens, + CAST(json_extract(model.value, '$.cacheReadTokens') AS INTEGER) AS cache_read_tokens, + CAST(json_extract(model.value, '$.cacheWriteTokens') AS INTEGER) AS cache_write_tokens, + CAST(json_extract(model.value, '$.reasoningTokens') AS INTEGER) AS reasoning_tokens + FROM report, json_each(report.models_json) AS model + ), + incoming AS ( + SELECT model, MAX(input_tokens) AS input_tokens, MAX(output_tokens) AS output_tokens, + MAX(cache_read_tokens) AS cache_read_tokens, + MAX(cache_write_tokens) AS cache_write_tokens, + MAX(reasoning_tokens) AS reasoning_tokens + FROM incoming_raw + GROUP BY model + ), + usage_counts AS MATERIALIZED ( + SELECT + (SELECT COUNT(*) FROM (SELECT 1 FROM agent_run_usage existing + WHERE existing.project_id = report.project_id + AND existing.chat_session_id = report.chat_session_id + AND existing.source = 'harness' LIMIT (SELECT max_rows + 1 FROM report))) AS existing_rows, + (SELECT COUNT(*) FROM incoming + WHERE NOT EXISTS ( + SELECT 1 FROM agent_run_usage existing + WHERE existing.project_id = report.project_id + AND existing.chat_session_id = report.chat_session_id + AND existing.source = 'harness' + AND existing.usage_epoch = report.usage_epoch + AND existing.model = incoming.model + AND existing.credential_key = report.credential_key + )) AS new_rows + FROM report + ), + admission AS MATERIALIZED ( + SELECT new_rows = 0 OR existing_rows + new_rows <= report.max_rows AS allowed + FROM report, usage_counts + )`; + +// Marker first: both statements observe the same pre-write admission decision in one D1 batch. +// One sticky row per chat; rejected epochs/models/credentials cannot grow the marker table. +const HARNESS_ADMISSION_HIT_SQL = `${HARNESS_ADMISSION_CTE} +INSERT INTO agent_run_usage_admission_hits (project_id, chat_session_id, last_rejected_at) + SELECT report.project_id, report.chat_session_id, report.reported_at + FROM report, admission WHERE NOT admission.allowed + ON CONFLICT (project_id, chat_session_id) DO UPDATE SET + last_rejected_at = MAX(last_rejected_at, excluded.last_rejected_at) + WHERE excluded.last_rejected_at > last_rejected_at`; + +const HARNESS_UPSERT_SQL = `${HARNESS_ADMISSION_CTE} +INSERT INTO agent_run_usage (${UPSERT_COLUMNS}) + SELECT report.project_id, report.chat_session_id, report.workspace_id, + report.agent_session_id, 'harness', report.usage_epoch, incoming.model, + report.credential_key, report.credential_source, report.agent_type, + incoming.input_tokens, incoming.output_tokens, incoming.cache_read_tokens, + incoming.cache_write_tokens, incoming.reasoning_tokens, report.reported_at, report.reported_at + FROM report, incoming, admission + WHERE admission.allowed OR EXISTS ( + SELECT 1 FROM agent_run_usage existing + WHERE existing.project_id = report.project_id + AND existing.chat_session_id = report.chat_session_id + AND existing.source = 'harness' + AND existing.usage_epoch = report.usage_epoch + AND existing.model = incoming.model + AND existing.credential_key = report.credential_key + ) + ON CONFLICT (${CONFLICT_KEY}) DO UPDATE SET + input_tokens = MAX(input_tokens, excluded.input_tokens), + output_tokens = MAX(output_tokens, excluded.output_tokens), + cache_read_tokens = MAX(cache_read_tokens, excluded.cache_read_tokens), + cache_write_tokens = MAX(cache_write_tokens, excluded.cache_write_tokens), + reasoning_tokens = CASE + WHEN excluded.reasoning_tokens IS NULL THEN reasoning_tokens + WHEN reasoning_tokens IS NULL THEN excluded.reasoning_tokens + ELSE MAX(reasoning_tokens, excluded.reasoning_tokens) END, + workspace_id = COALESCE(excluded.workspace_id, workspace_id), + agent_session_id = COALESCE(excluded.agent_session_id, agent_session_id), + updated_at = MAX(updated_at, excluded.updated_at) + -- A repeated or older report changes no counter: write nothing. + WHERE excluded.input_tokens > input_tokens + OR excluded.output_tokens > output_tokens + OR excluded.cache_read_tokens > cache_read_tokens + OR excluded.cache_write_tokens > cache_write_tokens + OR (excluded.reasoning_tokens IS NOT NULL + AND (reasoning_tokens IS NULL OR excluded.reasoning_tokens > reasoning_tokens))`; + +/** Increments: one measured upstream response added to the run's row. */ +const PROXY_UPSERT_SQL = `INSERT INTO agent_run_usage (${UPSERT_COLUMNS}) + VALUES (${UPSERT_VALUES}) + ON CONFLICT (${CONFLICT_KEY}) DO UPDATE SET + input_tokens = input_tokens + excluded.input_tokens, + output_tokens = output_tokens + excluded.output_tokens, + cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens, + cache_write_tokens = cache_write_tokens + excluded.cache_write_tokens, + reasoning_tokens = CASE + WHEN excluded.reasoning_tokens IS NULL THEN reasoning_tokens + ELSE COALESCE(reasoning_tokens, 0) + excluded.reasoning_tokens END, + workspace_id = COALESCE(excluded.workspace_id, workspace_id), + agent_session_id = COALESCE(excluded.agent_session_id, agent_session_id), + updated_at = MAX(updated_at, excluded.updated_at)`; + +/** Counters are clamped to the report ceiling so summed reads stay inside SQLite's integer range. */ +function count(value: number | null | undefined): number { + return typeof value === 'number' && Number.isFinite(value) && value > 0 + ? Math.min(Math.floor(value), RUN_USAGE_MAX_TOKENS_PER_COUNTER) + : 0; +} + +function optionalCount(value: number | null | undefined): number | null { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 + ? Math.min(Math.floor(value), RUN_USAGE_MAX_TOKENS_PER_COUNTER) + : null; +} + +function hasTokens(counts: RunUsageModelCounts): boolean { + return ( + count(counts.inputTokens) + + count(counts.outputTokens) + + count(counts.cacheReadTokens) + + count(counts.cacheWriteTokens) + + count(counts.reasoningTokens) > + 0 + ); +} + +function normalizedModels(models: RunUsageModelCounts[]): RunUsageModelCounts[] { + return models.filter(hasTokens).map((counts) => ({ + model: counts.model.trim(), + inputTokens: count(counts.inputTokens), + outputTokens: count(counts.outputTokens), + cacheReadTokens: count(counts.cacheReadTokens), + cacheWriteTokens: count(counts.cacheWriteTokens), + reasoningTokens: optionalCount(counts.reasoningTokens), + })); +} + +async function bindProxyRows( + db: D1Database, + scope: RunUsageScope, + models: RunUsageModelCounts[], + now: number +): Promise { + const credentialKey = (await credentialLimitReferenceKey(scope.credentialReference)) ?? ''; + return normalizedModels(models).map((counts) => + db + .prepare(PROXY_UPSERT_SQL) + .bind( + scope.projectId, + scope.chatSessionId, + scope.workspaceId, + scope.agentSessionId, + 'ai_proxy', + AI_PROXY_USAGE_EPOCH, + counts.model, + credentialKey, + credentialKey ? scope.credentialSource : null, + scope.agentType, + counts.inputTokens, + counts.outputTokens, + counts.cacheReadTokens, + counts.cacheWriteTokens, + counts.reasoningTokens, + now, + now + ) + ); +} + +/** + * Store one harness report: the cumulative totals of `epoch`, per model. One D1 round trip. + * The caller has already verified the callback token, the session binding and the credential + * attribution; `scope` carries only server-verified values. + */ +export async function recordHarnessRunUsage( + env: Env, + scope: RunUsageScope, + epoch: string, + models: RunUsageModelCounts[], + now: number = Date.now() +): Promise { + const normalized = normalizedModels(models); + if (normalized.length === 0) return 0; + const credentialKey = (await credentialLimitReferenceKey(scope.credentialReference)) ?? ''; + const maxRows = Number(await resolveAdminSetting(env, 'insights.runUsageMaxRowsPerSession')); + const statement = (sql: string) => + env.DATABASE.prepare(sql).bind( + scope.projectId, + scope.chatSessionId, + scope.workspaceId, + scope.agentSessionId, + epoch, + credentialKey, + credentialKey ? scope.credentialSource : null, + scope.agentType, + now, + maxRows, + JSON.stringify(normalized) + ); + const results = await env.DATABASE.batch([ + statement(HARNESS_ADMISSION_HIT_SQL), + statement(HARNESS_UPSERT_SQL), + ]); + return results[1]?.meta.changes ?? 0; +} + +/** Cumulative token totals of one VM-agent usage epoch, per model (the callback's `tokenUsage`). */ +export interface HarnessTokenUsageReport { + epoch: string; + models: Array<{ + model?: string; + inputTokens: number; + outputTokens: number; + cacheReadTokens?: number; + cacheWriteTokens?: number; + reasoningTokens?: number; + }>; +} + +/** + * Store a usage callback's token report. A failed write is logged and swallowed: totals are + * cumulative, so the next report restores what this one carried, and the callback's limit + * observations must not be retried because of it. + */ +export async function recordHarnessTokenReport( + env: Env, + scope: RunUsageScope, + report: HarnessTokenUsageReport +): Promise { + try { + await recordHarnessRunUsage( + env, + scope, + report.epoch, + report.models.map((model) => ({ + model: model.model ?? '', + inputTokens: model.inputTokens, + outputTokens: model.outputTokens, + cacheReadTokens: model.cacheReadTokens ?? 0, + cacheWriteTokens: model.cacheWriteTokens ?? 0, + reasoningTokens: model.reasoningTokens ?? null, + })) + ); + } catch (error) { + log.warn('agent_run_usage.harness_record_failed', { + projectId: scope.projectId, + chatSessionId: scope.chatSessionId, + agentSessionId: scope.agentSessionId, + error: error instanceof Error ? error.message : String(error), + action: 'skipped', + }); + } +} + +/** + * Add one measured AI proxy response to the run. A workspace with no chat session or project is + * not a run and is skipped; a failure is logged, never thrown into the proxied response. + */ +export async function recordProxyRunUsage( + env: Pick, + scope: Omit & { + projectId: string | null; + chatSessionId: string | null; + }, + model: string, + usage: MeasuredTokenUsage, + now: number = Date.now() +): Promise { + if (!scope.projectId || !scope.chatSessionId) { + // Not a run (no project or chat bound to the workspace right now); said once per response. + log.info('agent_run_usage.proxy_skipped_no_run', { + workspaceId: scope.workspaceId, + hasProject: Boolean(scope.projectId), + hasChatSession: Boolean(scope.chatSessionId), + }); + return; + } + try { + const statements = await bindProxyRows( + env.DATABASE, + { ...scope, projectId: scope.projectId, chatSessionId: scope.chatSessionId }, + [{ model, ...usage }], + now + ); + if (statements.length === 0) return; + await env.DATABASE.batch(statements); + } catch (error) { + log.warn('agent_run_usage.proxy_record_failed', { + projectId: scope.projectId, + chatSessionId: scope.chatSessionId, + workspaceId: scope.workspaceId, + error: error instanceof Error ? error.message : String(error), + }); + } +} + +/** + * The `onMeasuredUsage` hook for one proxied request: adds the upstream's measured usage to the + * run of the workspace the proxy token belongs to. `auth` is the verified proxy auth; the + * credential is the one the proxy actually forwarded with. + */ +export function proxyRunUsageRecorder( + env: Pick, + auth: { + projectId?: string | null; + chatSessionId?: string | null; + workspaceId: string; + agentSessionId?: string | null; + agentType?: string | null; + }, + attribution: { + model: string | null | undefined; + credentialReference: string | null; + credentialSource: string | null; + } +): (usage: MeasuredTokenUsage) => Promise { + return (usage) => + recordProxyRunUsage( + env, + { + projectId: auth.projectId ?? null, + chatSessionId: auth.chatSessionId ?? null, + workspaceId: auth.workspaceId, + agentSessionId: auth.agentSessionId ?? null, + agentType: auth.agentType ?? null, + credentialReference: attribution.credentialReference, + credentialSource: attribution.credentialSource, + }, + attribution.model ?? '', + usage + ); +} diff --git a/apps/api/src/services/agent-session-acp-lifecycle.ts b/apps/api/src/services/agent-session-acp-lifecycle.ts new file mode 100644 index 0000000000..e22872cf1e --- /dev/null +++ b/apps/api/src/services/agent-session-acp-lifecycle.ts @@ -0,0 +1,188 @@ +/** + * ProjectData ACP-session bookkeeping for `startSamAwareAgentSession` + * (`agent-session-bootstrap.ts`): create the chat's ACP session, reset it for a fresh start + * after a snapshot restore that could not resume the saved agent, and mark it running. + */ +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import type { SamAwareAgentStartInput } from './agent-session-bootstrap'; +import * as projectDataService from './project-data'; + +export async function runMaybePhased( + input: SamAwareAgentStartInput, + name: string, + fn: () => Promise +): Promise { + await input.beforeExternalMutation?.(); + return input.runPhase ? input.runPhase(name, fn) : fn(); +} + +export async function createAcpSessionWithLogging( + env: Env, + input: SamAwareAgentStartInput, + agentSessionId: string +): Promise { + try { + return await runMaybePhased(input, 'create_acp_session', () => + ensureAcpSessionWithEnv(env, input, agentSessionId) + ); + } catch (err) { + log.error('agent_session_bootstrap.acp_session_create_failed', { + projectId: input.projectId, + chatSessionId: input.chatSessionId, + agentSessionId, + error: err instanceof Error ? err.message : String(err), + }); + return null; + } +} + +/** Why a snapshot wake starts the agent fresh instead of resuming its saved session. */ +export type FreshStartReason = 'degraded_restore' | 'transcript_only'; + +/** + * The chat notice for a fresh start. Neither claims an exact restore (policy 2adacc8f); the + * transcript-only one also says that no files came back, because none did. + */ +const FRESH_START_NOTICES: Record = { + degraded_restore: + 'SAM restored this sleeping conversation from a degraded snapshot, so the agent is starting fresh and will read the persisted transcript before continuing.', + transcript_only: + "SAM could not restore this conversation's workspace: its last sleep saved no snapshot or Git recovery point. The agent is starting fresh in a new checkout and will read the persisted transcript before continuing. Files and uncommitted work from the previous workspace were not restored.", +}; + +/** + * Tell the chat the agent is starting fresh. The id is stable per agent session, so a retry + * re-persists the same entry instead of adding one; the same id with different text is refused. + * The bootstrap calls this directly when the chat has no ACP session to reset, so the notice + * never depends on ACP bookkeeping succeeding. + */ +export async function persistFreshStartNotice( + env: Env, + input: SamAwareAgentStartInput, + agentSessionId: string, + reason: FreshStartReason +): Promise { + if (!input.chatSessionId) return; + await projectDataService.persistMessage( + env, + input.projectId, + input.chatSessionId, + 'system', + FRESH_START_NOTICES[reason], + null, + `degraded-wake-${agentSessionId}` + ); +} + +export async function prepareAcpSessionForFreshStart( + env: Env, + input: SamAwareAgentStartInput, + agentSessionId: string, + reason: FreshStartReason = 'degraded_restore' +): Promise { + try { + await persistFreshStartNotice(env, input, agentSessionId, reason); + const session = await runMaybePhased(input, 'prepare_acp_session_fresh_start', () => + projectDataService.prepareAcpSessionForFreshStart(env, input.projectId, agentSessionId, { + actorType: input.actor.type, + actorId: input.actor.id, + reason: + reason === 'transcript_only' + ? `${input.actor.reasonPrefix} prepared fresh start after transcript-only sleep fallback` + : `${input.actor.reasonPrefix} prepared fresh start after degraded snapshot restore`, + workspaceId: input.workspaceId, + nodeId: input.nodeId, + metadata: { + chatSessionId: input.chatSessionId ?? null, + restoreSnapshotChatSessionId: input.restoreSnapshotChatSessionId ?? null, + freshStartReason: reason, + }, + }) + ); + return session.id; + } catch (err) { + log.error('agent_session_bootstrap.acp_session_prepare_fresh_start_failed', { + projectId: input.projectId, + chatSessionId: input.chatSessionId, + agentSessionId, + error: err instanceof Error ? err.message : String(err), + }); + throw err; + } +} + +export async function transitionAcpSessionToRunning( + env: Env, + input: SamAwareAgentStartInput, + acpSessionId: string, + agentSessionId: string, + /** + * Set after a snapshot restore: a failed ACP session may then be reset and retried, and the + * reset re-persists the fresh-start notice for this reason. It must be the reason the start + * already used, because that notice's message id is reused and a different text is refused. + */ + snapshotRestoreRepair: FreshStartReason | null +): Promise { + const transition = () => + projectDataService.transitionAcpSession(env, input.projectId, acpSessionId, 'running', { + actorType: input.actor.type, + actorId: input.actor.id, + reason: `${input.actor.reasonPrefix} started`, + acpSdkSessionId: agentSessionId, + }); + + try { + await runMaybePhased(input, 'mark_acp_session_running', transition); + return; + } catch (err) { + if (!snapshotRestoreRepair) throw err; + const existing = await projectDataService + .getAcpSession(env, input.projectId, acpSessionId) + .catch(() => null); + if (existing?.status !== 'failed') throw err; + log.warn('agent_session_bootstrap.acp_session_failed_before_restore_running_retry', { + projectId: input.projectId, + chatSessionId: input.chatSessionId, + agentSessionId, + acpSessionId, + error: err instanceof Error ? err.message : String(err), + }); + await prepareAcpSessionForFreshStart(env, input, agentSessionId, snapshotRestoreRepair); + await runMaybePhased(input, 'mark_acp_session_running_after_restore_repair', transition); + } +} + +async function ensureAcpSessionWithEnv( + env: Env, + input: SamAwareAgentStartInput, + agentSessionId: string +): Promise { + if (!input.chatSessionId) return null; + + const existing = await projectDataService + .getAcpSession(env, input.projectId, agentSessionId) + .catch(() => null); + if (existing?.id) return existing.id; + + const acpSession = await projectDataService.createAcpSession( + env, + input.projectId, + input.chatSessionId, + null, + input.agentType, + null, + 0, + agentSessionId + ); + + await projectDataService.transitionAcpSession(env, input.projectId, acpSession.id, 'assigned', { + actorType: input.actor.type, + actorId: input.actor.id, + reason: `${input.actor.reasonPrefix} assigned`, + workspaceId: input.workspaceId, + nodeId: input.nodeId, + }); + + return acpSession.id; +} diff --git a/apps/api/src/services/agent-session-bootstrap.ts b/apps/api/src/services/agent-session-bootstrap.ts index 00c78f8603..18945eaed6 100644 --- a/apps/api/src/services/agent-session-bootstrap.ts +++ b/apps/api/src/services/agent-session-bootstrap.ts @@ -4,9 +4,18 @@ import { type drizzle } from 'drizzle-orm/d1'; import * as schema from '../db/schema'; import type { Env } from '../env'; import { log } from '../lib/logger'; +import { maybeJsonRecord } from '../lib/runtime-validation'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { ulid } from '../lib/ulid'; import { buildSamBootstrapInstructions } from './agent-bootstrap-prompt'; +import { + createAcpSessionWithLogging, + type FreshStartReason, + persistFreshStartNotice, + prepareAcpSessionForFreshStart, + runMaybePhased, + transitionAcpSessionToRunning, +} from './agent-session-acp-lifecycle'; import { buildSessionMcpServers } from './mcp-connection-resolution'; import { generateMcpToken, @@ -22,12 +31,12 @@ import { restoreAgentSessionOnNode, startAgentSessionOnNode, } from './node-agent'; -import * as projectDataService from './project-data'; import { loadSnapshotRuntimeContract, parseSessionRuntimeContract, resolveSessionRuntimeContract, } from './session-runtime-contract'; +import { TRANSCRIPT_ONLY_SLEEP_FALLBACK_REASON } from './session-snapshot-restore-response'; type Db = ReturnType>; @@ -82,21 +91,13 @@ export interface SamAwareAgentStartResult { initialPromptSent: boolean; /** * Outcome of the snapshot restore this start ran, if any. `degraded` covers every restore - * failure the VM agent reports (HOME, WIP or git, not only the agent context), so only + * failure the VM agent reports (HOME, WIP or git, not only the agent context) and a + * transcript-only sleep fallback that had no files to restore, so only * `restored` proves the replacement holds the snapshot's files. */ snapshotRestore?: 'restored' | 'degraded'; } -async function runMaybePhased( - input: SamAwareAgentStartInput, - name: string, - fn: () => Promise -): Promise { - await input.beforeExternalMutation?.(); - return input.runPhase ? input.runPhase(name, fn) : fn(); -} - async function ensureAgentSessionRow( db: Db, input: SamAwareAgentStartInput, @@ -137,111 +138,30 @@ async function ensureAgentSessionRow( }); } -function shouldStartFreshAfterSnapshotRestore(restored: unknown): boolean { - const restoreRecord = - restored && typeof restored === 'object' ? (restored as Record) : null; +/** + * What the VM agent's restore (`restoreSessionSnapshot` in + * `packages/vm-agent/internal/server/session_snapshot_restore.go`) leaves the wake to do: + * - `restored`: the saved agent session was loaded; do not start a new one. + * - `degraded`: the files or the agent context could not all come back; start fresh. + * - `transcript-replay` with `transcript_only_sleep_fallback`: the bounded sleep fallback saved + * no recovery point, so there was nothing to restore (`sessionSnapshotRestoreResponse`). The + * workspace is the fresh checkout create-workspace provisioned and the agent session is + * untouched, so start fresh from the transcript (policy a3780107). The recovery task already + * carries the transcript-only wake prompt (`sessionRecoveryInitialPrompt`). + * Anything else fails the wake. That includes `transcript-replay` for a snapshot that vanished + * after the wake claimed it (`snapshot_missing_or_unavailable`), which this does not cover. + */ +function snapshotRestoreOutcome(restored: unknown): 'restored' | FreshStartReason { + const restoreRecord = maybeJsonRecord(restored); const status = restoreRecord?.status; - if (status === 'restored') return false; - if (status === 'degraded') return true; - throw new Error(`Strict session restore failed (${String(status ?? 'unknown')})`); -} - -async function createAcpSessionWithLogging( - env: Env, - input: SamAwareAgentStartInput, - agentSessionId: string -): Promise { - try { - return await runMaybePhased(input, 'create_acp_session', () => - ensureAcpSessionWithEnv(env, input, agentSessionId) - ); - } catch (err) { - log.error('agent_session_bootstrap.acp_session_create_failed', { - projectId: input.projectId, - chatSessionId: input.chatSessionId, - agentSessionId, - error: err instanceof Error ? err.message : String(err), - }); - return null; - } -} - -async function prepareAcpSessionForFreshStart( - env: Env, - input: SamAwareAgentStartInput, - agentSessionId: string -): Promise { - try { - if (input.chatSessionId) { - await projectDataService.persistMessage( - env, - input.projectId, - input.chatSessionId, - 'system', - 'SAM restored this sleeping conversation from a degraded snapshot, so the agent is starting fresh and will read the persisted transcript before continuing.', - null, - `degraded-wake-${agentSessionId}` - ); - } - const session = await runMaybePhased(input, 'prepare_acp_session_fresh_start', () => - projectDataService.prepareAcpSessionForFreshStart(env, input.projectId, agentSessionId, { - actorType: input.actor.type, - actorId: input.actor.id, - reason: `${input.actor.reasonPrefix} prepared fresh start after degraded snapshot restore`, - workspaceId: input.workspaceId, - nodeId: input.nodeId, - metadata: { - chatSessionId: input.chatSessionId ?? null, - restoreSnapshotChatSessionId: input.restoreSnapshotChatSessionId ?? null, - }, - }) - ); - return session.id; - } catch (err) { - log.error('agent_session_bootstrap.acp_session_prepare_fresh_start_failed', { - projectId: input.projectId, - chatSessionId: input.chatSessionId, - agentSessionId, - error: err instanceof Error ? err.message : String(err), - }); - throw err; - } -} - -async function transitionAcpSessionToRunning( - env: Env, - input: SamAwareAgentStartInput, - acpSessionId: string, - agentSessionId: string, - allowSnapshotRestoreRecovery: boolean -): Promise { - const transition = () => - projectDataService.transitionAcpSession(env, input.projectId, acpSessionId, 'running', { - actorType: input.actor.type, - actorId: input.actor.id, - reason: `${input.actor.reasonPrefix} started`, - acpSdkSessionId: agentSessionId, - }); - - try { - await runMaybePhased(input, 'mark_acp_session_running', transition); - return; - } catch (err) { - if (!allowSnapshotRestoreRecovery) throw err; - const existing = await projectDataService - .getAcpSession(env, input.projectId, acpSessionId) - .catch(() => null); - if (existing?.status !== 'failed') throw err; - log.warn('agent_session_bootstrap.acp_session_failed_before_restore_running_retry', { - projectId: input.projectId, - chatSessionId: input.chatSessionId, - agentSessionId, - acpSessionId, - error: err instanceof Error ? err.message : String(err), - }); - await prepareAcpSessionForFreshStart(env, input, agentSessionId); - await runMaybePhased(input, 'mark_acp_session_running_after_restore_repair', transition); + if (status === 'restored') return 'restored'; + if (status === 'degraded') return 'degraded_restore'; + const reason = restoreRecord?.reason; + if (status === 'transcript-replay' && reason === TRANSCRIPT_ONLY_SLEEP_FALLBACK_REASON) { + return 'transcript_only'; } + const detail = typeof reason === 'string' && reason ? `: ${reason.slice(0, 80)}` : ''; + throw new Error(`Strict session restore failed (${String(status ?? 'unknown')}${detail})`); } export async function startSamAwareAgentSession( @@ -385,6 +305,9 @@ export async function startSamAwareAgentSession( let acpSessionId = await createAcpSessionWithLogging(env, input, agentSessionId); let shouldStartFreshSession = true; + // A restore that resumed the saved agent keeps the degraded wording if its ACP session + // later needs the fresh-start repair (`transitionAcpSessionToRunning`). + let snapshotRestoreRepair: FreshStartReason | null = null; const restoreSnapshotChatSessionId = input.restoreSnapshotChatSessionId; if (restoreSnapshotChatSessionId) { const restored = await runMaybePhased(input, 'restore_acp_session', () => { @@ -405,20 +328,33 @@ export async function startSamAwareAgentSession( ? restoreAgentSessionOnNode(...args, guardedMutationOptions) : restoreAgentSessionOnNode(...args); }); - shouldStartFreshSession = shouldStartFreshAfterSnapshotRestore(restored); - if (shouldStartFreshSession) { + const restoreOutcome = snapshotRestoreOutcome(restored); + shouldStartFreshSession = restoreOutcome !== 'restored'; + snapshotRestoreRepair = restoreOutcome === 'restored' ? 'degraded_restore' : restoreOutcome; + if (restoreOutcome !== 'restored') { log.warn('agent_session_bootstrap.snapshot_restore_degraded_starting_fresh', { projectId: input.projectId, chatSessionId: input.chatSessionId, restoreSnapshotChatSessionId, workspaceId: input.workspaceId, agentSessionId, + restoreOutcome, }); if (!acpSessionId) { acpSessionId = await createAcpSessionWithLogging(env, input, agentSessionId); } if (acpSessionId) { - acpSessionId = await prepareAcpSessionForFreshStart(env, input, agentSessionId); + acpSessionId = await prepareAcpSessionForFreshStart( + env, + input, + agentSessionId, + restoreOutcome + ); + } else { + // ACP bookkeeping failed (logged); the chat must still learn what was not restored. + await runMaybePhased(input, 'persist_fresh_start_notice', () => + persistFreshStartNotice(env, input, agentSessionId, restoreOutcome) + ); } } } @@ -463,7 +399,7 @@ export async function startSamAwareAgentSession( input, runningAcpSessionId, agentSessionId, - Boolean(restoreSnapshotChatSessionId) + snapshotRestoreRepair ); } if (restoreSnapshotChatSessionId) { @@ -499,37 +435,3 @@ export async function startSamAwareAgentSession( throw err; } } - -async function ensureAcpSessionWithEnv( - env: Env, - input: SamAwareAgentStartInput, - agentSessionId: string -): Promise { - if (!input.chatSessionId) return null; - - const existing = await projectDataService - .getAcpSession(env, input.projectId, agentSessionId) - .catch(() => null); - if (existing?.id) return existing.id; - - const acpSession = await projectDataService.createAcpSession( - env, - input.projectId, - input.chatSessionId, - null, - input.agentType, - null, - 0, - agentSessionId - ); - - await projectDataService.transitionAcpSession(env, input.projectId, acpSession.id, 'assigned', { - actorType: input.actor.type, - actorId: input.actor.id, - reason: `${input.actor.reasonPrefix} assigned`, - workspaceId: input.workspaceId, - nodeId: input.nodeId, - }); - - return acpSession.id; -} diff --git a/apps/api/src/services/agent-wake-authorization.ts b/apps/api/src/services/agent-wake-authorization.ts index 1ce27fb5be..48caa4a634 100644 --- a/apps/api/src/services/agent-wake-authorization.ts +++ b/apps/api/src/services/agent-wake-authorization.ts @@ -15,6 +15,7 @@ import { import { log } from '../lib/logger'; import { errors } from '../middleware/error'; import type { AppDb } from '../middleware/project-auth'; +import { getSessionAccess } from './project-data'; import { requireSessionWriter, type SessionWriterContext } from './session-access'; export interface AuthorizeAgentWakeInput { @@ -64,3 +65,76 @@ export async function authorizeAgentWake( } return { writer, wake: decision }; } + +/** + * Whether a person's comment on a human task may wake the chat that assigned it (inbox slice H1, + * trigger `inbox_task_comment`). Unlike `authorizeAgentWake` it never throws: a refused comment is + * still recorded, it just does not wake the agent. + * + * Allowed: the task's assignee or the member who took it, and a writer of the filing chat (its + * owner, or an active grantee who is still a member, as `requireSessionWriter` checks). Everyone + * else, a chat that no longer exists, and an owner who left the project: no wake. + */ +export async function decideInboxTaskCommentWake( + env: Env, + input: { + projectId: string; + sessionId: string | null; + actorUserId: string; + assigneeUserId: string | null; + claimedByUserId: string | null; + } +): Promise<{ wake: boolean; teammateInput: boolean; reason: string }> { + if (!input.sessionId) return { wake: false, teammateInput: false, reason: 'no_filing_chat' }; + try { + const { access } = await getSessionAccess( + env, + input.projectId, + input.sessionId, + input.actorUserId + ); + if (!access.found || !access.ownerUserId) + return { wake: false, teammateInput: false, reason: 'filing_chat_missing' }; + // Both the author and the chat's owner must still be active members (every role reads tasks). + // One query for both: `IN` holds one id when the owner comments. + const members = await env.DATABASE.prepare( + `SELECT user_id FROM project_members + WHERE project_id = ? AND status = 'active' AND user_id IN (?, ?)` + ) + .bind(input.projectId, input.actorUserId, access.ownerUserId) + .all<{ user_id: string }>(); + const active = new Set((members.results ?? []).map((row) => row.user_id)); + if (!active.has(input.actorUserId) || !active.has(access.ownerUserId)) + return { wake: false, teammateInput: false, reason: 'not_a_member' }; + const decision = decideAgentWake({ + trigger: 'inbox_task_comment', + sessionId: input.sessionId, + actorUserId: input.actorUserId, + access: { + role: access.role === 'owner' || access.role === 'grantee' ? access.role : 'none', + ownerUserId: access.ownerUserId, + grantId: access.role === 'grantee' ? (access.grant?.id ?? null) : null, + }, + inboxTask: { assigneeUserId: input.assigneeUserId, claimedByUserId: input.claimedByUserId }, + }); + if (!decision.allowed) { + log.info('agent_wake.inbox_task_comment_recorded_only', { + projectId: input.projectId, + sessionId: input.sessionId, + actorUserId: input.actorUserId, + reason: decision.reason, + }); + return { wake: false, teammateInput: false, reason: decision.reason }; + } + return { wake: true, teammateInput: decision.teammateInput, reason: decision.actorRole }; + } catch (error) { + // An unknown answer must not wake someone else's agent: record only. + log.warn('agent_wake.inbox_task_comment_decision_failed', { + projectId: input.projectId, + sessionId: input.sessionId, + actorUserId: input.actorUserId, + error: error instanceof Error ? error.message : String(error), + }); + return { wake: false, teammateInput: false, reason: 'decision_failed' }; + } +} diff --git a/apps/api/src/services/ai-proxy-availability.ts b/apps/api/src/services/ai-proxy-availability.ts index 45214e8f0e..5a9572decd 100644 --- a/apps/api/src/services/ai-proxy-availability.ts +++ b/apps/api/src/services/ai-proxy-availability.ts @@ -1,46 +1,11 @@ -/** - * Whether the SAM AI proxy (`/ai/v1`, `/ai/anthropic/v1`, `/ai/proxy/:wstoken`) and the agent-key - * paths that hand workspaces a proxy config are on. One resolver for every reader (rule 24): the - * proxy routes, agent-key, the agents catalog and the platform OpenCode check. - * - * - `AI_PROXY_ENABLED="false"` is the operator kill switch and always wins. - * - With an addressable AI Gateway (every Cloudflare deployment) the proxy is on, exactly as before, - * and no setting is read. - * - Without one (a self-hosted box) proxied calls go straight to the provider and SAM's own - * metering is the only spend record, so the proxy is off until an admin turns on - * `aiProxy.directUpstreamEnabled`. That is an explicit admin decision, never a silent default. - * A settings read that fails resolves to the setting's default (off): `resolveAdminSetting`. - */ import type { Env } from '../env'; import { resolveAdminSetting } from './admin-settings-resolution'; import { AI_PROXY_DIRECT_UPSTREAM_SETTING } from './ai-proxy-settings'; import { resolveAiGatewayId } from './platform-capabilities'; -export type AiProxyAvailability = - { enabled: true } | { enabled: false; reason: 'kill-switch' | 'direct-upstream-not-enabled' }; - -/** - * The operator kill switch alone. Proxy routes check this before authenticating (an operator brake - * answers every caller, as it always has) and the full `resolveAiProxyAvailability` only after - * authenticating, so an unauthenticated caller still gets 401 and no admin setting is read for it. - */ -export function isAiProxyKillSwitchEngaged(env: Pick): boolean { - return env.AI_PROXY_ENABLED === 'false'; -} - -export async function resolveAiProxyAvailability(env: Env): Promise { - if (isAiProxyKillSwitchEngaged(env)) return { enabled: false, reason: 'kill-switch' }; - if (resolveAiGatewayId(env) !== null) return { enabled: true }; - const enabled = (await resolveAdminSetting(env, AI_PROXY_DIRECT_UPSTREAM_SETTING)) === true; - return enabled ? { enabled: true } : { enabled: false, reason: 'direct-upstream-not-enabled' }; -} - +/** Call only after authentication at HTTP entry points: absence must not leak config. */ export async function isAiProxyEnabled(env: Env): Promise { - return (await resolveAiProxyAvailability(env)).enabled; -} - -/** The 503 message for a disabled proxy; names the admin setting when that is the reason. */ -export function aiProxyDisabledMessage(availability: AiProxyAvailability): string { - if (availability.enabled || availability.reason === 'kill-switch') return 'AI proxy is disabled'; - return `AI proxy is disabled: this installation has no AI Gateway, so an admin must turn on ${AI_PROXY_DIRECT_UPSTREAM_SETTING} in Admin settings (AI models).`; + if (env.AI_PROXY_ENABLED === 'false') return false; + if (resolveAiGatewayId(env)) return true; + return (await resolveAdminSetting(env, AI_PROXY_DIRECT_UPSTREAM_SETTING)) === true; } diff --git a/apps/api/src/services/ai-proxy-ports.ts b/apps/api/src/services/ai-proxy-ports.ts index 087d130def..5a75c6d367 100644 --- a/apps/api/src/services/ai-proxy-ports.ts +++ b/apps/api/src/services/ai-proxy-ports.ts @@ -4,7 +4,8 @@ import { drizzle } from 'drizzle-orm/d1'; import type { Env } from '../env'; import { getCredentialEncryptionKey } from '../lib/secrets'; -import { resolveAdminSetting } from './admin-settings-resolution'; +import { resolveAdminSetting, resolveAdminSettingDetails } from './admin-settings-resolution'; +import { AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING } from './ai-proxy-settings'; import { getPlatformAgentCredential } from './platform-credentials'; /** @@ -23,5 +24,19 @@ export function aiProxyPorts(env: Env, db?: ReturnType): AiProxy }, externalReadTimeoutMs: async () => Number(await resolveAdminSetting(env, 'performance.externalReadTimeoutMs')), + monthlyCostCeilingUsd: () => readMonthlyCostCeilingUsd(env), }; } + +/** + * Read the strict admin-settings snapshot (cached for at most 60 seconds). A failed read must + * remain a failure: defaulting to zero or retaining an older disabled/higher ceiling could spend + * beyond the operator's current limit. The package maps the failure to a retryable 503. + */ +async function readMonthlyCostCeilingUsd(env: Env): Promise { + const { value } = await resolveAdminSettingDetails( + env, + AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING + ); + return Number(value); +} diff --git a/apps/api/src/services/ai-proxy-settings.ts b/apps/api/src/services/ai-proxy-settings.ts index f7543f6f49..72c6ad6337 100644 --- a/apps/api/src/services/ai-proxy-settings.ts +++ b/apps/api/src/services/ai-proxy-settings.ts @@ -5,7 +5,10 @@ import type { AdminSettingDefinition } from './admin-setting-definitions'; export const AI_PROXY_DIRECT_UPSTREAM_SETTING = 'aiProxy.directUpstreamEnabled' as const; -export type AiProxySettingName = typeof AI_PROXY_DIRECT_UPSTREAM_SETTING; +export const AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING = + 'aiProxy.perUserMonthlyCostCeilingUsd' as const; +export type AiProxySettingName = + typeof AI_PROXY_DIRECT_UPSTREAM_SETTING | typeof AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING; export const AI_PROXY_SETTINGS: readonly AdminSettingDefinition[] = [ { @@ -14,10 +17,27 @@ export const AI_PROXY_SETTINGS: readonly AdminSettingDefinition[] = [ defaultValue: false, category: 'AI models', description: - 'Turn on the SAM AI proxy (SAM-managed "sam" provider mode and server-side custom-endpoint keys) on an installation without Cloudflare AI Gateway. Calls then go straight to Anthropic or OpenAI with the platform key stored in Admin, and SAM prices them from its own model price table for the monthly cost cap of each user. Any approved user can then spend the platform key, bounded only by the daily token budgets and the monthly cap each user sets for themselves, so also set a spend limit on the provider account. Ignored where an AI Gateway exists (the proxy is on there).', + 'Turn on the SAM AI proxy (SAM-managed "sam" provider mode and server-side custom-endpoint keys) on an installation without Cloudflare AI Gateway. Calls then go straight to Anthropic or OpenAI with the platform key stored in Admin, and SAM prices them from its own model price table for the monthly cost cap of each user. Any approved user can then spend the platform key, bounded only by the daily token budgets and the monthly cap each user sets for themselves, and by the installation monthly ceiling (aiProxy.perUserMonthlyCostCeilingUsd), so set that ceiling and a spend limit on the provider account. Ignored where an AI Gateway exists (the proxy is on there).', secret: false, // Lets every approved user spend the platform key. risky: true, validate: (value) => typeof value === 'boolean', }, + { + name: AI_PROXY_PER_USER_MONTHLY_COST_CEILING_SETTING, + type: 'integer', + defaultValue: 0, + category: 'AI models', + description: + 'Monthly AI spend ceiling for each user (not a total across users), in whole USD (0 = none). Applies where SAM prices AI calls itself, that is an installation without Cloudflare AI Gateway: no user can spend more than this in a UTC month, whatever monthly cap they set, and clearing their own cap does not remove it. Users cannot set a cap above it. Calls to a model with no catalog price count $0, so daily token limits remain the bound for those. Ignored where an AI Gateway exists (caps there are priced from gateway logs).', + secret: false, + risky: false, + // Representation bound only: the operator chooses the business limit in this setting. + range: { min: 0, max: Number.MAX_SAFE_INTEGER }, + validate: (value) => + typeof value === 'number' && + Number.isSafeInteger(value) && + value >= 0 && + value <= Number.MAX_SAFE_INTEGER, + }, ]; diff --git a/apps/api/src/services/ai-proxy-shared.ts b/apps/api/src/services/ai-proxy-shared.ts index c1f206d01e..8d0e510016 100644 --- a/apps/api/src/services/ai-proxy-shared.ts +++ b/apps/api/src/services/ai-proxy-shared.ts @@ -1,25 +1,6 @@ // Moved to @simple-agent-manager/ai-proxy (worker modularization W5). Re-exported so the // worker's existing importers are unchanged. Request auth stays in the worker -// (./ai-proxy-auth) and is re-exported here as before. `fetchWorkersAIChatCompletion` also stays -// in the worker: it resolves its target through the admin-configured LLM endpoint -// (./llm-chat-target), which reads worker settings. -import { - readSafeGatewayErrorDiagnostic, - type WorkersAIChatMessage, - WorkersAIGatewayError, -} from '@simple-agent-manager/ai-proxy'; -import { expectJsonRecord } from '@simple-agent-manager/worker-core'; - -import type { Env } from '../env'; -import { - chatTargetHeaders, - fetchChatTarget, - isCloudflareChatTarget, - type LlmPurpose, - LlmUnavailableError, - resolveWorkersAiChatTargetWithin, -} from './llm-chat-target'; - +// (./ai-proxy-auth) and is re-exported here as before. export { AIProxyAuthError, type AIProxyAuthResult, @@ -32,76 +13,33 @@ export { buildAIGatewayMetadata, buildAnthropicCountTokensUrl, buildAnthropicGatewayUrl, + buildWorkersAIGatewayUrl, isAnthropicModel, readSafeGatewayErrorDiagnostic, - UPSTREAM_ERROR_BODY_PARSE_MAX_BYTES, - UPSTREAM_ERROR_REASON_MAX_LENGTH, - upstreamErrorLogFields, - type WorkersAIChatMessage, WorkersAIGatewayError, } from '@simple-agent-manager/ai-proxy'; -export interface WorkersAIChatCompletionOptions { - /** Which control-plane caller this is; selects its model on an OpenAI-compatible endpoint. */ - purpose: LlmPurpose; - modelId: string; - maxTokens: number; - timeoutMs: number; - messages: WorkersAIChatMessage[]; - metadata: Record; - responseLabel: string; - reasoningEffort?: string | null; - chatTemplateKwargs?: Record; - errorDiagnosticMaxLength?: number; -} +import { + fetchWorkersAIChatCompletion as fetchCompletion, + LlmUnavailableError, + type WorkersAIChatCompletionOptions, +} from '@simple-agent-manager/ai-proxy'; +import type { Env } from '../env'; +import { resolveWorkersAiChatTargetWithin } from './llm-chat-target'; +import type { LlmPurpose } from './llm-endpoint-settings'; +/** Bind settings at the worker edge; package keeps the protocol and response parsing. */ export async function fetchWorkersAIChatCompletion( env: Env, - options: WorkersAIChatCompletionOptions -): Promise { - // One budget for the whole call, armed before the endpoint settings read. + options: WorkersAIChatCompletionOptions & { purpose?: LlmPurpose } +) { const signal = AbortSignal.timeout(options.timeoutMs); const target = await resolveWorkersAiChatTargetWithin( env, - options.purpose, + options.purpose ?? 'taskTitle', options.modelId, - signal + options.timeoutMs ); - if (!target) throw new LlmUnavailableError(options.purpose); - // reasoning_effort and chat_template_kwargs are Workers AI model quirks keyed by the - // Cloudflare model id; another endpoint's model would reject or misread them. - const cloudflare = isCloudflareChatTarget(target); - const response = await fetchChatTarget(target, { - method: 'POST', - signal, - headers: chatTargetHeaders(target, { 'cf-aig-metadata': JSON.stringify(options.metadata) }), - body: JSON.stringify({ - model: target.model, - max_tokens: options.maxTokens, - messages: options.messages, - ...(cloudflare && options.reasoningEffort !== undefined - ? { reasoning_effort: options.reasoningEffort } - : {}), - ...(cloudflare && options.chatTemplateKwargs - ? { chat_template_kwargs: options.chatTemplateKwargs } - : {}), - }), - }); - - if (!response.ok) { - const diagnostic = options.errorDiagnosticMaxLength - ? await readSafeGatewayErrorDiagnostic(response, options.errorDiagnosticMaxLength) - : undefined; - throw new WorkersAIGatewayError(response.status, diagnostic); - } - - const payload = expectJsonRecord(await response.json(), options.responseLabel); - const choices = Array.isArray(payload.choices) ? payload.choices : []; - const firstChoice = choices[0] - ? expectJsonRecord(choices[0], `${options.responseLabel}.choices[0]`) - : undefined; - const messageRecord = firstChoice?.message - ? expectJsonRecord(firstChoice.message, `${options.responseLabel}.message`) - : undefined; - return typeof messageRecord?.content === 'string' ? messageRecord.content.trim() : null; + if (!target) throw new LlmUnavailableError(options.purpose ?? 'taskTitle'); + return fetchCompletion(env, options, target, signal); } diff --git a/apps/api/src/services/ai-token-budget.ts b/apps/api/src/services/ai-token-budget.ts index 17e1baa6af..a96a7788c3 100644 --- a/apps/api/src/services/ai-token-budget.ts +++ b/apps/api/src/services/ai-token-budget.ts @@ -1,30 +1,49 @@ // Moved to @simple-agent-manager/ai-proxy (worker modularization W5). Re-exported so the // worker's existing importers are unchanged. +import { + checkAiUsageGate as checkAiUsageGateWithPorts, + resolveMonthlyCostCeilingUsd as resolveCeiling, +} from '@simple-agent-manager/ai-proxy'; + +import type { Env } from '../env'; +import { aiProxyPorts } from './ai-proxy-ports'; + export { - type AiBudgetLimits, type AiProviderUsageAttribution, - buildBudgetKey, - buildBudgetSettingsKey, - buildMonthlyCostCacheKey, - checkAiUsageGate, - checkMonthlyCostCap, consumeFeatureTokenBudget, deleteUserBudgetSettings, + effectiveMonthlyCostCapUsd, getAdminAiAllowance, getAiBudgetLimits, - getCachedMonthlyCost, getFeatureTokenBudget, - getLocalMonthlyAiCostUsd, getProviderUsage, getTokenUsage, getUserBudgetSettings, incrementProviderUsage, incrementTokenUsage, - MONTHLY_COST_CAP_UNAVAILABLE_MESSAGE, - type MonthlyCostCapCheck, + monthlyCostCapMessage, releaseFeatureTokenBudget, resolveEffectiveLimits, resolvePlatformDailyTokenLimits, saveUserBudgetSettings, validateBudgetUpdate, } from '@simple-agent-manager/ai-proxy'; + +/** + * Every pre-request AI usage limit, with the installation-wide monthly ceiling bound to this + * worker's admin settings. Every worker caller goes through here, so none can leave the ceiling + * out (rule 61); the ceiling is read only where SAM meters spend itself. + */ +export function checkAiUsageGate( + kv: KVNamespace, + userId: string, + env: Env, + options?: { platformBilled?: boolean } +) { + return checkAiUsageGateWithPorts(kv, userId, env, aiProxyPorts(env), options); +} + +/** The installation ceiling where it applies (null with an AI Gateway, or when unset). */ +export function resolveMonthlyCostCeilingUsd(env: Env): Promise { + return resolveCeiling(env, aiProxyPorts(env)); +} diff --git a/apps/api/src/services/ai-token-usage-accounting.ts b/apps/api/src/services/ai-token-usage-accounting.ts index b12df97d2a..852e3d23ae 100644 --- a/apps/api/src/services/ai-token-usage-accounting.ts +++ b/apps/api/src/services/ai-token-usage-accounting.ts @@ -4,6 +4,6 @@ export { attachTokenUsageAccounting, attachUpstreamTokenUsageAccounting, estimateInputTokensFromMessages, - estimateTokensFromText, + estimateInputTokensFromRequest, optionalExecutionContext, } from '@simple-agent-manager/ai-proxy'; diff --git a/apps/api/src/services/better-auth-access-token.ts b/apps/api/src/services/better-auth-access-token.ts index f453b844de..1269c6eb2c 100644 --- a/apps/api/src/services/better-auth-access-token.ts +++ b/apps/api/src/services/better-auth-access-token.ts @@ -30,9 +30,20 @@ export async function getBetterAuthAccessTokenForProvider( return null; } - const auth = await createAuth(env); - return auth.api.getAccessToken({ - ...(headers ? { headers } : {}), - body: { accountId, userId }, + let refreshFailure: unknown; + const auth = await createAuth(env, { + onGitHubRefreshError: (error) => { + refreshFailure = error; + }, }); + try { + return await auth.api.getAccessToken({ + ...(headers ? { headers } : {}), + body: { accountId, userId }, + }); + } catch (error) { + // BetterAuth deliberately wraps every refresh failure as FAILED_TO_GET_ACCESS_TOKEN. + // Retain the provider's retry/auth category through the same request-local closure. + throw refreshFailure ?? error; + } } diff --git a/apps/api/src/services/cancel-task.ts b/apps/api/src/services/cancel-task.ts index bb5a391639..fa3429d39f 100644 --- a/apps/api/src/services/cancel-task.ts +++ b/apps/api/src/services/cancel-task.ts @@ -1,12 +1,15 @@ +import { and, eq } from 'drizzle-orm'; import type { drizzle } from 'drizzle-orm/d1'; -import type * as schema from '../db/schema'; +import * as schema from '../db/schema'; import type { Env } from '../env'; import { log } from '../lib/logger'; import { errors } from '../middleware/error'; import { setTaskStatus } from '../routes/tasks/_helpers'; import * as projectDataService from './project-data'; import { recordTaskLifecycleEventBestEffort } from './project-lifecycle-events'; +import { retireTaskCancellationPrompts } from './task-cancellation-prompts'; +import { taskRecoveryCancellationQuery } from './task-recovery-cancellation'; import { canTransitionTaskStatus, isTaskStatus } from './task-status'; import { cleanupTerminalTaskResourcesOrThrow } from './task-terminal-cleanup'; @@ -27,9 +30,45 @@ export async function cancelTask( task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled'; if (!terminal && !canTransitionTaskStatus(task.status, 'cancelled')) throw errors.conflict('Task cannot be cancelled in its current state'); - const updated = terminal - ? task - : await setTaskStatus(db, task, 'cancelled', 'user', userId, options); + // Revoke accepted, unissued deliveries before publishing the terminal D1 + // state: an old delivery must not mistake that state for fresh human intent. + await retireTaskCancellationPrompts(env, task); + let updated: schema.Task; + if (terminal) { + // A repeated stop is NEW cancellation intent, even when the verdict is + // already terminal. Move its row-version fence without changing that verdict + // or repeating completion events/trigger side effects. A same-ms retry must + // also invalidate a wake that observed the previous row version. Completion time + // remains the original UI and cleanup-grace clock. + const prior = Date.parse(task.updatedAt); + const now = new Date( + Math.max(Date.now(), Number.isFinite(prior) ? prior + 1 : 0) + ).toISOString(); + const [rows] = await db.batch([ + db + .update(schema.tasks) + .set({ updatedAt: now }) + .where( + and( + eq(schema.tasks.id, task.id), + eq(schema.tasks.projectId, task.projectId), + eq(schema.tasks.status, task.status), + eq(schema.tasks.updatedAt, task.updatedAt) + ) + ) + .returning(), + taskRecoveryCancellationQuery( + db, + task, + now, + task.status as 'completed' | 'failed' | 'cancelled' + ), + ]); + if (!rows[0]) throw errors.conflict('Task changed before cancellation; retry the stop'); + updated = rows[0]; + } else { + updated = await setTaskStatus(db, task, 'cancelled', 'user', userId, options); + } if (!terminal) { const events = Promise.all([ recordTaskLifecycleEventBestEffort(env, { diff --git a/apps/api/src/services/canonical-vm-allocation.ts b/apps/api/src/services/canonical-vm-allocation.ts index 83287fb0bb..0671e23e4c 100644 --- a/apps/api/src/services/canonical-vm-allocation.ts +++ b/apps/api/src/services/canonical-vm-allocation.ts @@ -1,4 +1,7 @@ -import type { NativeVMConfig } from '@simple-agent-manager/providers'; +import { + assertInfomaniakRequestedBootVolumeAllowed, + type NativeVMConfig, +} from '@simple-agent-manager/providers'; import { emptyCapacityPoolMessage } from '@simple-agent-manager/scheduler-core'; import type { CapacityPlacementSnapshot, @@ -15,6 +18,7 @@ import { type drizzle } from 'drizzle-orm/d1'; import type * as schema from '../db/schema'; import type { Env } from '../env'; +import { resolveInfomaniakBootVolumeGb } from './infomaniak-provider-settings'; import { capacityPlacementSnapshotForCandidate, directPlacementAuditSnapshot, @@ -193,6 +197,15 @@ export async function resolveCanonicalVmAllocationPlan( }; } + const bootDiskRefusal = BOOT_DISK_SIZE_IS_USER_SUPPLIED[input.entryPoint] + ? await refuseOversizedRequestedBootDisk( + env, + credential.providerName, + input.explicit?.native?.providerInstanceBootDiskSizeGb + ) + : null; + if (bootDiskRefusal) return { error: bootDiskRefusal, errorKind: 'placement' }; + if ( input.requiredCredentialSource && credential.credentialSource !== input.requiredCredentialSource @@ -257,6 +270,55 @@ export async function resolveCanonicalVmAllocationPlan( }); } +/** + * Whether `explicit.native.providerInstanceBootDiskSizeGb` from this entry point is a size a user + * just asked for (capped below) or one replayed from an existing record. The session-snapshot relay + * copies a source node's stored size, which must keep resolving after an admin lowers the setting. + * Exhaustive on purpose: a new entry point must decide which kind it is. + */ +const BOOT_DISK_SIZE_IS_USER_SUPPLIED: Readonly> = { + 'direct-node': true, + 'direct-workspace': true, + 'task-submit': false, + 'deployment-provisioning': false, + 'session-snapshot-relay': false, + 'mcp-dispatch': false, + 'sam-session-dispatch': false, + 'trigger-submit': false, + 'retry-subtask': false, + 'task-run': false, + 'session-recovery': false, + 'orchestrator-dispatch': false, + 'orchestration-retry': false, +}; + +/** + * A user-supplied `bootDiskSizeGb` (node create, workspace create) is capped here, where the request + * is admitted, not in the provider: sizes stored on node rows and plans reach `createVM` the same + * way and must keep provisioning after an admin lowers the setting. Infomaniak boots from a volume + * of any requested size, and the VM may run on a shared platform credential, so the admin setting + * `infomaniak.bootVolumeGb` is the largest size a request may ask for. Fixed-root providers reject + * sizes above their included disk in `createVM` (`assertIncludedBootDiskCapacity`); GCP's explicit + * sizes are uncapped (tasks/backlog/2026-11-17-infomaniak-boot-volume-follow-ups.md). + */ +async function refuseOversizedRequestedBootDisk( + env: Env, + providerName: CredentialProvider, + requestedGb: number | null | undefined +): Promise { + if (providerName !== 'infomaniak' || requestedGb === null || requestedGb === undefined) + return null; + try { + assertInfomaniakRequestedBootVolumeAllowed( + requestedGb, + await resolveInfomaniakBootVolumeGb(env) + ); + return null; + } catch (error) { + return error instanceof Error ? error.message : String(error); + } +} + export function explicitRuntimeAdapterSnapshot(input: { runtime: 'cf-container'; workloadRole?: CapacityWorkloadRole; diff --git a/apps/api/src/services/capacity-pool-placement-settings.ts b/apps/api/src/services/capacity-pool-placement-settings.ts index cb0a7a6528..65a0b4d1a5 100644 --- a/apps/api/src/services/capacity-pool-placement-settings.ts +++ b/apps/api/src/services/capacity-pool-placement-settings.ts @@ -1,4 +1,8 @@ -import { DEFAULT_CAPACITY_POOL_SELECTION_SETTINGS } from '@simple-agent-manager/scheduler-core'; +import { + DEFAULT_CAPACITY_POOL_SELECTION_SETTINGS, + resolveEffectiveNodeHostMemoryReserveMb, + type WorkspaceAdmissionEnv, +} from '@simple-agent-manager/scheduler-core'; import type { CapacityPoolPlacementSettings, CapacityPoolSelectionWeights, @@ -124,7 +128,11 @@ export async function resolveCapacityPoolPlacementSettings( } export function toSafeCapacityPoolPlacementSettingsSummary( - resolved: ResolvedCapacityPoolPlacementSettings + resolved: ResolvedCapacityPoolPlacementSettings, + env?: Pick< + WorkspaceAdmissionEnv, + 'TASK_RUN_NODE_HOST_MEMORY_RESERVE_MB' | 'VM_AGENT_MEMORY_RESERVE_MB' + > ): SafeCapacityPoolPlacementSettingsSummary { return { version: resolved.placementSettings.version, @@ -134,6 +142,9 @@ export function toSafeCapacityPoolPlacementSettingsSummary( rolloutCohortPercent: resolved.placementSettings.rolloutCohortPercent, source: resolved.placementSettings.source, resourceDefaults: resolved.resourceDefaults, + // The same resolver placement uses (placement-resolver.ts), so the pool view's fit warning + // cannot disagree with what admission subtracts. + hostMemoryReserveMb: resolveEffectiveNodeHostMemoryReserveMb(env ?? {}), }; } @@ -144,10 +155,13 @@ export async function resolveSafeCapacityPoolPlacementSettingsSummary( | 'CAPACITY_POOL_LEGACY_WORKLOAD_MAPPING_JSON' | 'CAPACITY_POOL_SELECTION_SETTINGS_JSON' | 'CAPACITY_POOL_PLATFORM_DEFAULTS_JSON' + | 'TASK_RUN_NODE_HOST_MEMORY_RESERVE_MB' + | 'VM_AGENT_MEMORY_RESERVE_MB' > ): Promise { return toSafeCapacityPoolPlacementSettingsSummary( - await resolveCapacityPoolPlacementSettings(db, env) + await resolveCapacityPoolPlacementSettings(db, env), + env ); } diff --git a/apps/api/src/services/cloudflare-cost-snapshot.ts b/apps/api/src/services/cloudflare-cost-snapshot.ts new file mode 100644 index 0000000000..69f5a744eb --- /dev/null +++ b/apps/api/src/services/cloudflare-cost-snapshot.ts @@ -0,0 +1,369 @@ +/** + * Daily Cloudflare cost snapshot (Insights slice CF, idea 01M7HTS38KX2G78JD0ESAGMKKH). + * + * Fetches the last `insights.cloudflareCostBackfillDays` complete UTC days of billed usage from the + * Cloudflare GraphQL analytics API (the same request and analysis as `pnpm quality:cloudflare-cost`, + * `packages/shared/src/cloudflare-cost/`, rule 76) and upserts one `installation_cost_daily` row per + * day per product line. Re-running is idempotent: every run re-fetches its whole window, so late + * analytics and gaps up to the window converge. + * + * Credential: the Worker's existing `CF_API_TOKEN` + `CF_ACCOUNT_ID`; the token needs + * Account → Account Analytics → Read (Admin Analytics' Analytics Engine queries need the same). + * Without them the run records `not_configured` and does nothing else. + * + * I/O per run (rule 47): 3 settings reads (cached per isolate), 1 D1 read of the stored rows + * from the first month's 1st through the window's end, 1 GraphQL request bounded by `performance.externalReadTimeoutMs`, 1 D1 batch writing every + * row plus the sync status. Callers isolate it (rule 53): the daily cron and the superadmin refresh + * route catch and log; this function itself records failures and never throws for them. + */ +import { + INSIGHTS_CLOUDFLARE_COST_SETTINGS, + type InsightsCloudflareCostSettingName, +} from '@simple-agent-manager/operations'; +import { + CLOUDFLARE_ANALYTICS_MAX_DAYS, + CLOUDFLARE_COST_METRIC_KEYS, + CLOUDFLARE_GRAPHQL_ENDPOINT, + cloudflareCostHttpError, + type CloudflareCostMetricKey, + cloudflareCostQueryBody, + CloudflareCostQueryError, + type CloudflareDailyUsage, + cloudflareDailyUsage, + cloudflareDaysInMonth, + createCloudflarePricing, + dailyCloudflareMetricCosts, + type InstallationCloudflareRefreshResponse, + isCloudflareCostMetricKey, + parseCloudflareCostResponse, +} from '@simple-agent-manager/shared'; +import { chunk, D1_MAX_BOUND_PARAMETERS } from '@simple-agent-manager/worker-core'; + +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import { resolveAdminSetting } from './admin-settings-resolution'; +import { fetchWithTimeout } from './fetch-timeout'; + +export const CLOUDFLARE_COST_SOURCE = 'cloudflare'; +const DAY_MS = 86_400_000; +const ERROR_MESSAGE_MAX_LENGTH = 500; +const UPSERT_COLUMNS = 7; +/** Used only if the `performance.externalReadTimeoutMs` setting resolves to an unusable value. */ +const DEFAULT_EXTERNAL_READ_TIMEOUT_MS = 15_000; + +export type CloudflareCostSnapshotResult = InstallationCloudflareRefreshResponse; + +interface DailyCostRow { + day: string; + productLine: CloudflareCostMetricKey; + usage: number; + unit: string; + costUsd: number; + /** Stored day this fetch had no data for: update its cost only, keep usage and fetch time. */ + costOnly: boolean; +} + +function isoDay(ms: number): string { + return new Date(ms).toISOString().slice(0, 10); +} + +/** The UTC day before `nowMs`, and the first day of a window of `days` ending there. */ +export function cloudflareCostWindow( + nowMs: number, + days: number +): { firstDay: string; lastDay: string } { + const today = Date.UTC( + new Date(nowMs).getUTCFullYear(), + new Date(nowMs).getUTCMonth(), + new Date(nowMs).getUTCDate() + ); + const span = Math.min(Math.max(1, Math.floor(days)), CLOUDFLARE_ANALYTICS_MAX_DAYS); + return { firstDay: isoDay(today - span * DAY_MS), lastDay: isoDay(today - DAY_MS) }; +} + +function monthStart(day: string): string { + return `${day.slice(0, 7)}-01`; +} + +const SETTING_DEFAULTS = Object.fromEntries( + INSIGHTS_CLOUDFLARE_COST_SETTINGS.map((setting) => [setting.name, setting.defaultValue]) +) as Record; + +async function positiveSetting( + env: Env, + name: Parameters[1], + fallback: number +) { + const value = Number(await resolveAdminSetting(env, name)); + return Number.isFinite(value) && value > 0 ? value : fallback; +} + +/** + * Usage already stored from the first month's 1st through the window's end. Days before the + * window set how much of the monthly allowance is used; days inside it stand in for any day this + * fetch returned nothing for. + */ +async function readStoredUsage( + env: Env, + firstDay: string, + lastDay: string +): Promise>> { + const prefix = new Map>(); + const result = await env.DATABASE.prepare( + `SELECT day, product_line, usage_quantity FROM installation_cost_daily + WHERE source = ? AND day >= ? AND day <= ?` + ) + .bind(CLOUDFLARE_COST_SOURCE, monthStart(firstDay), lastDay) + .all<{ day: unknown; product_line: unknown; usage_quantity: unknown }>(); + for (const row of result.results ?? []) { + if (typeof row.day !== 'string' || !isCloudflareCostMetricKey(row.product_line)) continue; + const usage = typeof row.usage_quantity === 'number' ? row.usage_quantity : 0; + const day = prefix.get(row.day) ?? new Map(); + day.set(row.product_line, usage); + prefix.set(row.day, day); + } + return prefix; +} + +/** + * Rows to write, each costed against its calendar month: the month's earlier days (fetched, else + * stored, else zero when never collected) consume the monthly allowance first. + * - A fetched day with data gets a full row. + * - A stored day inside the window that this fetch returned nothing for keeps its usage, but its + * cost is recomputed (`costOnly`), because a corrected earlier day can move how much of the + * allowance is left for it. + */ +export function buildDailyCostRows( + fetched: CloudflareDailyUsage[], + stored: Map>, + window: { firstDay: string; lastDay: string } +): DailyCostRow[] { + const pricing = createCloudflarePricing(); + // A day with no usage at all is a day Cloudflare returned nothing for: storage alone (D1, R2, + // KV) is never zero on a live account. Writing it would replace good stored usage with zeros + // after a partial analytics outage, so it is left unwritten and counts as missing on the card. + const withData = fetched.filter((entry) => + CLOUDFLARE_COST_METRIC_KEYS.some((key) => entry.metrics[key] !== 0) + ); + const fetchedByDay = new Map(withData.map((entry) => [entry.date, entry])); + const inWindow = (day: string) => day >= window.firstDay && day <= window.lastDay; + const writtenDays = [ + ...new Set([...fetchedByDay.keys(), ...[...stored.keys()].filter(inWindow)]), + ].sort((a, b) => a.localeCompare(b)); + const rows: DailyCostRow[] = []; + for (const month of [...new Set(writtenDays.map((day) => day.slice(0, 7)))]) { + const lastDay = writtenDays.filter((day) => day.startsWith(month)).at(-1); + if (!lastDay) continue; + const days = Array.from( + { length: Number(lastDay.slice(8, 10)) }, + (_, index) => `${month}-${String(index + 1).padStart(2, '0')}` + ); + const daysInMonth = cloudflareDaysInMonth(lastDay); + for (const key of CLOUDFLARE_COST_METRIC_KEYS) { + const metric = pricing.metrics[key]; + const values = days.map( + (day) => fetchedByDay.get(day)?.metrics[key] ?? stored.get(day)?.get(key) ?? 0 + ); + const costs = dailyCloudflareMetricCosts(values, metric, daysInMonth); + days.forEach((day, index) => { + const isFetched = fetchedByDay.has(day); + if (!isFetched && !(inWindow(day) && stored.get(day)?.has(key))) return; + rows.push({ + day, + productLine: key, + usage: values[index] ?? 0, + unit: metric.unit, + costUsd: costs[index] ?? 0, + costOnly: !isFetched, + }); + }); + } + } + return rows; +} + +function syncStatement( + env: Env, + result: CloudflareCostSnapshotResult, + attemptAt: number +): D1PreparedStatement { + // A failed attempt leaves the last success, the window it stored and its row count in place + // (rule 73). + return env.DATABASE.prepare( + `INSERT INTO installation_cost_sync + (source, status, last_attempt_at, last_success_at, error_message, first_day, last_day, rows_written) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(source) DO UPDATE SET + status = excluded.status, + last_attempt_at = excluded.last_attempt_at, + last_success_at = COALESCE(excluded.last_success_at, installation_cost_sync.last_success_at), + error_message = excluded.error_message, + first_day = COALESCE(excluded.first_day, installation_cost_sync.first_day), + last_day = COALESCE(excluded.last_day, installation_cost_sync.last_day), + rows_written = CASE WHEN excluded.status = 'ok' + THEN excluded.rows_written ELSE installation_cost_sync.rows_written END` + ).bind( + CLOUDFLARE_COST_SOURCE, + result.status, + attemptAt, + result.status === 'ok' ? attemptAt : null, + result.error, + result.firstDay, + result.lastDay, + result.rowsWritten + ); +} + +const FULL_UPDATE = `usage_quantity = excluded.usage_quantity, + usage_unit = excluded.usage_unit, + estimated_cost_usd = excluded.estimated_cost_usd, + fetched_at = excluded.fetched_at`; +const COST_ONLY_UPDATE = 'estimated_cost_usd = excluded.estimated_cost_usd'; + +function upsertStatements( + env: Env, + rows: DailyCostRow[], + fetchedAt: number +): D1PreparedStatement[] { + const perStatement = Math.floor(D1_MAX_BOUND_PARAMETERS / UPSERT_COLUMNS); + const groups: [DailyCostRow[], string][] = [ + [rows.filter((row) => !row.costOnly), FULL_UPDATE], + [rows.filter((row) => row.costOnly), COST_ONLY_UPDATE], + ]; + return groups.flatMap(([group, update]) => + chunk(group, perStatement).map((batch) => + env.DATABASE.prepare( + `INSERT INTO installation_cost_daily + (source, day, product_line, usage_quantity, usage_unit, estimated_cost_usd, fetched_at) + VALUES ${batch.map(() => '(?, ?, ?, ?, ?, ?, ?)').join(', ')} + ON CONFLICT(source, day, product_line) DO UPDATE SET ${update}` + ).bind( + ...batch.flatMap((row) => [ + CLOUDFLARE_COST_SOURCE, + row.day, + row.productLine, + row.usage, + row.unit, + row.costUsd, + fetchedAt, + ]) + ) + ) + ); +} + +function safeMessage(error: unknown, accountId: string): string { + const text = error instanceof Error ? error.message : String(error); + return text.split(accountId).join('').slice(0, ERROR_MESSAGE_MAX_LENGTH); +} + +export async function runCloudflareCostSnapshot( + env: Env, + nowMs: number = Date.now() +): Promise { + const token = env.CF_API_TOKEN?.trim() ?? ''; + const accountId = env.CF_ACCOUNT_ID?.trim() ?? ''; + let result: CloudflareCostSnapshotResult; + let rowStatements: D1PreparedStatement[] = []; + if (!token || !accountId) { + result = { + status: 'not_configured', + firstDay: null, + lastDay: null, + rowsWritten: 0, + error: null, + }; + } else { + try { + const backfillDays = await positiveSetting( + env, + 'insights.cloudflareCostBackfillDays', + SETTING_DEFAULTS['insights.cloudflareCostBackfillDays'] + ); + const queryLimit = await positiveSetting( + env, + 'insights.cloudflareCostQueryLimit', + SETTING_DEFAULTS['insights.cloudflareCostQueryLimit'] + ); + const timeoutMs = await positiveSetting( + env, + 'performance.externalReadTimeoutMs', + DEFAULT_EXTERNAL_READ_TIMEOUT_MS + ); + const { firstDay, lastDay } = cloudflareCostWindow(nowMs, backfillDays); + const prefix = await readStoredUsage(env, firstDay, lastDay); + const response = await fetchWithTimeout( + CLOUDFLARE_GRAPHQL_ENDPOINT, + { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, + body: cloudflareCostQueryBody({ + accountId, + startDate: firstDay, + endDate: lastDay, + limit: queryLimit, + }), + }, + timeoutMs + ); + if (!response.ok) + throw cloudflareCostHttpError(response.status, await response.json().catch(() => null)); + const fetched = cloudflareDailyUsage( + parseCloudflareCostResponse(await response.json(), queryLimit), + firstDay, + lastDay + ); + const rows = buildDailyCostRows(fetched, prefix, { firstDay, lastDay }); + rowStatements = upsertStatements(env, rows, nowMs); + const rowsWritten = rows.filter((row) => !row.costOnly).length; + result = { status: 'ok', firstDay, lastDay, rowsWritten, error: null }; + } catch (error) { + const permission = error instanceof CloudflareCostQueryError && error.kind === 'permission'; + result = { + status: permission ? 'permission_denied' : 'error', + firstDay: null, + lastDay: null, + rowsWritten: 0, + error: safeMessage(error, accountId), + }; + rowStatements = []; + } + } + + // Rows and status commit together, so the card never shows a success whose rows are missing. + await env.DATABASE.batch([...rowStatements, syncStatement(env, result, nowMs)]); + const event = { ...result, source: CLOUDFLARE_COST_SOURCE }; + if (result.status === 'ok' || result.status === 'not_configured') + log.info('cloudflare_cost_snapshot.completed', event); + else + log.error('cloudflare_cost_snapshot.failed', { ...event, action: 'recorded_for_admin_card' }); + return result; +} + +/** + * Claims the refresh interval for one Refresh now press: a single conditional write that succeeds + * only when the last attempt is older than `minIntervalMs`, so two overlapping presses cannot + * both start a Cloudflare request. Returns how long to wait when the claim is refused. + */ +export async function claimCloudflareCostRefresh( + env: Env, + nowMs: number, + minIntervalMs: number +): Promise<{ claimed: true } | { claimed: false; waitMs: number }> { + // A new row's status is a placeholder the card reads as "not fetched yet"; the run replaces it. + const claim = await env.DATABASE.prepare( + `INSERT INTO installation_cost_sync (source, status, last_attempt_at) VALUES (?, 'refreshing', ?) + ON CONFLICT(source) DO UPDATE SET last_attempt_at = excluded.last_attempt_at + WHERE installation_cost_sync.last_attempt_at <= ?` + ) + .bind(CLOUDFLARE_COST_SOURCE, nowMs, nowMs - minIntervalMs) + .run(); + if ((claim.meta?.changes ?? 0) > 0) return { claimed: true }; + const row = await env.DATABASE.prepare( + `SELECT last_attempt_at FROM installation_cost_sync WHERE source = ?` + ) + .bind(CLOUDFLARE_COST_SOURCE) + .first<{ last_attempt_at: unknown }>(); + const last = typeof row?.last_attempt_at === 'number' ? row.last_attempt_at : nowMs; + return { claimed: false, waitMs: Math.max(1_000, last + minIntervalMs - nowMs) }; +} diff --git a/apps/api/src/services/credential-limit-events/values.ts b/apps/api/src/services/credential-limit-events/values.ts index d01c1c2648..273fa6291f 100644 --- a/apps/api/src/services/credential-limit-events/values.ts +++ b/apps/api/src/services/credential-limit-events/values.ts @@ -124,37 +124,12 @@ export async function fingerprint(value: ProjectEventJsonValue): Promise return `${SHA256_PREFIX}${await sha256Hex(stableStringify(value))}`; } -/** Length of a digest key: `sha256:` plus 64 hex characters. */ -export const CREDENTIAL_REFERENCE_DIGEST_KEY_BYTES = SHA256_PREFIX.length + 64; - -/** - * Key that stands for a credential reference everywhere in the credential-limit - * pipeline: window rows, project-event subject ids and source-outbox guards. The - * outbox requires the window key and the event subject to be one string, so the - * key must fit both the window column (160 characters) and the deployment's - * project-event filter-string limit (`PROJECT_EVENT_FILTER_MAX_STRING_BYTES`). - * A reference no longer than a digest key is its own key; a longer one — ids from - * the 2026-06 composable-credentials backfill embed the legacy ciphertext — - * becomes its SHA-256 digest, which readers recompute from the full reference. - * Keys therefore never exceed 71 bytes whatever the configured limit, and unlike - * truncation they cannot collide or differ from what a reader looks up. - */ -export async function credentialLimitReferenceKey( - value: string | null | undefined -): Promise { - if (typeof value !== 'string') return null; - const reference = value.trim(); - if (!reference) return null; - if (encoder.encode(reference).byteLength <= CREDENTIAL_REFERENCE_DIGEST_KEY_BYTES) { - return reference; - } - return `${SHA256_PREFIX}${await sha256Hex(reference)}`; -} - -/** True when a stored credential reference is a digest key, not the reference itself. */ -export function isCredentialLimitReferenceDigest(key: string): boolean { - return key.startsWith(SHA256_PREFIX); -} +// One implementation for the API and the shared operations (Insights · Accounts reads the same keys). +export { + CREDENTIAL_REFERENCE_DIGEST_KEY_BYTES, + credentialLimitReferenceKey, + isCredentialLimitReferenceDigest, +} from '@simple-agent-manager/shared'; export function normalizeNumber(value: number | null | undefined): number | null { if (typeof value !== 'number' || !Number.isFinite(value)) return null; diff --git a/apps/api/src/services/credential-setup-config.ts b/apps/api/src/services/credential-setup-config.ts index 1dc87f70ab..23b7177966 100644 --- a/apps/api/src/services/credential-setup-config.ts +++ b/apps/api/src/services/credential-setup-config.ts @@ -1,9 +1,44 @@ /** * Configuration readers for guided agent-credential setup - * (Cloudflare Sandbox). All values are env-configurable with a `DEFAULT_*` + * (Cloudflare Sandbox). Values use environment or admin settings with a `DEFAULT_*` * constant fallback (Constitution Principle XI — no hardcoded limits/timeouts). */ import type { Env } from '../env'; +import { resolveAdminSetting } from './admin-settings'; +import { + DEFAULT_SETUP_SESSION_CLEANUP_RECOVERY_STEP_TIMEOUT_MS, + DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS, +} from './admin-settings-credential-setup-definitions'; + +export { DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS } from './admin-settings-credential-setup-definitions'; + +/** Only recovery pays this cached settings read; inline teardown retains the interactive timeout. */ +export async function getSetupSessionCleanupRecoveryStepTimeoutMs(env: Env): Promise { + const value = await resolveAdminSetting(env, 'credentialSetup.cleanupRecoveryStepTimeoutMs'); + return typeof value === 'number' ? value : DEFAULT_SETUP_SESSION_CLEANUP_RECOVERY_STEP_TIMEOUT_MS; +} + +export interface SetupSessionCleanupRecoveryConfig { + stepTimeoutMs: number; + maxAttempts: number; +} + +/** Recovery-only: both settings share the existing override cache/in-flight read. */ +export async function getSetupSessionCleanupRecoveryConfig( + env: Env +): Promise { + const [stepTimeoutMs, maxAttempts] = await Promise.all([ + getSetupSessionCleanupRecoveryStepTimeoutMs(env), + resolveAdminSetting(env, 'credentialSetup.cleanupRecoveryMaxAttempts'), + ]); + return { + stepTimeoutMs, + maxAttempts: + typeof maxAttempts === 'number' + ? maxAttempts + : DEFAULT_SETUP_SESSION_MAX_CLEANUP_RECOVERY_ATTEMPTS, + }; +} /** Concurrency sub-cap for simultaneous setup sessions (below the Sandbox container max_instances). */ export const DEFAULT_MAX_CONCURRENT_SETUP_SESSIONS = 2; @@ -25,6 +60,15 @@ export const DEFAULT_CLAUDE_SETUP_OUTPUT_BUFFER_BYTES = 32_768; export const DEFAULT_CLAUDE_VERIFICATION_CODE_MAX_LENGTH = 1_024; export const DEFAULT_CLAUDE_SETUP_ERROR_DETAIL_MAX_LENGTH = 160; export const DEFAULT_CLAUDE_OAUTH_TOKEN_MAX_LENGTH = 8_192; +/** + * The message `@cloudflare/sandbox` puts on its own permanent container start failure + * (HTTP 500 from `containerFetch`: no such image, no matching container application, + * out of memory, too many subprocesses). The SDK does not retry it, and the session + * reports it as `sandbox_runtime_unavailable`. Pinned against the installed SDK by + * tests/unit/durable-objects/credential-setup-session-teardown.test.ts. + */ +export const SANDBOX_PERMANENT_STARTUP_MESSAGE = + 'Container failed to start due to a permanent error. Check your container configuration.'; function parsePositiveInt(raw: string | undefined, fallback: number): number { const parsed = Number.parseInt(raw ?? '', 10); @@ -110,11 +154,7 @@ export const ACTIVE_SETUP_STATUSES = [ ] as const; export type SetupSessionStatus = - | (typeof ACTIVE_SETUP_STATUSES)[number] - | 'completed' - | 'failed' - | 'cancelled' - | 'expired'; + (typeof ACTIVE_SETUP_STATUSES)[number] | 'completed' | 'failed' | 'cancelled' | 'expired'; export function isTerminalSetupStatus(status: string): boolean { return ( diff --git a/apps/api/src/services/debug-agent-tools.ts b/apps/api/src/services/debug-agent-tools.ts index f4e701d62f..3b82c61837 100644 --- a/apps/api/src/services/debug-agent-tools.ts +++ b/apps/api/src/services/debug-agent-tools.ts @@ -201,7 +201,6 @@ export async function complete( messages: ChatMessage[], maxTokens: number ): Promise { - // One budget for the whole call, armed before the endpoint settings read. const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), config.timeoutMs); try { @@ -209,7 +208,7 @@ export async function complete( env, 'diagnosis', config.model, - controller.signal + config.timeoutMs ); if (!target) throw new LlmUnavailableError('diagnosis'); const response = await fetchChatTarget(target, { diff --git a/apps/api/src/services/default-capacity-source-credentials.ts b/apps/api/src/services/default-capacity-source-credentials.ts index 5fe6ab632a..20347a41a6 100644 --- a/apps/api/src/services/default-capacity-source-credentials.ts +++ b/apps/api/src/services/default-capacity-source-credentials.ts @@ -18,6 +18,7 @@ import type { } from './default-capacity-pools'; import { IoTimeoutError, withDeadline } from './fetch-timeout'; import { resolveGcpBootDiskPolicy } from './gcp-provider-factory'; +import { resolveInfomaniakBootVolumeGb } from './infomaniak-provider-settings'; import { buildProviderCatalogForCredential, getStaticProviderCatalogOfferings, @@ -379,8 +380,10 @@ function normalizeOfferingResolution( async function staticCatalogOptions( provider: CredentialProvider, env: Env | undefined -): Promise<{ gcpBootDiskPolicy?: GcpBootDiskPolicy }> { - return provider === 'gcp' && env - ? { gcpBootDiskPolicy: await resolveGcpBootDiskPolicy(env) } - : {}; +): Promise<{ gcpBootDiskPolicy?: GcpBootDiskPolicy; infomaniakBootVolumeGb?: number }> { + if (!env) return {}; + if (provider === 'gcp') return { gcpBootDiskPolicy: await resolveGcpBootDiskPolicy(env) }; + if (provider === 'infomaniak') + return { infomaniakBootVolumeGb: await resolveInfomaniakBootVolumeGb(env) }; + return {}; } diff --git a/apps/api/src/services/email-sign-in.ts b/apps/api/src/services/email-sign-in.ts index 4de2439d33..7239708fd9 100644 --- a/apps/api/src/services/email-sign-in.ts +++ b/apps/api/src/services/email-sign-in.ts @@ -122,27 +122,17 @@ export async function emailSignUpAllowed(env: Env, email: string): Promise { const normalized = email.trim().toLowerCase(); const account = await findAccountByEmail(env, normalized); - if (account) return !account.providerOnly; - return emailSignUpAllowed(env, normalized); + return account ? !account.providerOnly : emailSignUpAllowed(env, normalized); } -/** - * An account that a provider sign-in created with an unproven email, and that still has its - * provider link. SAM stores a GitHub user's email as unverified when GitHub's `/user/emails` - * call fails (`getUserInfo` in `../auth.ts`). Redeeming an email code for such an account makes - * BetterAuth's emailOTP route call `revokeUnprovenAccountAccess`, which deletes every provider - * link and session of the account (deliberate anti-takeover behaviour), so the user would - * silently lose GitHub. These accounts get no code: `deliverSignInCode` mails a note telling - * them to sign in with their provider, and redemption is refused like a wrong code. - */ -interface EmailAccountState { - providerOnly: boolean; -} - -async function findAccountByEmail(env: Env, email: string): Promise { +/** An OTP would make BetterAuth revoke this unproven account's provider links and sessions. */ +async function findAccountByEmail( + env: Env, + email: string +): Promise<{ providerOnly: boolean } | null> { const row = await env.DATABASE.prepare( `SELECT u.email_verified AS emailVerified, - EXISTS (SELECT 1 FROM accounts a WHERE a.user_id = u.id) AS linked + EXISTS (SELECT 1 FROM accounts a WHERE a.user_id = u.id AND a.provider_id != 'credential') AS linked FROM users u WHERE lower(u.email) = ? LIMIT 1` ) .bind(email) @@ -151,6 +141,13 @@ async function findAccountByEmail(env: Env, email: string): Promise { const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(''); @@ -223,24 +220,6 @@ export function signInCodeEmail(baseDomain: string, code: string) { }; } -/** Sent instead of a code to an account that must sign in with its provider (see above). */ -export function providerSignInRequiredEmail(baseDomain: string) { - const appUrl = `https://app.${baseDomain}`; - return { - subject: 'Sign in to SAM with GitHub', - text: [ - `Someone asked for a code to sign in to SAM at ${appUrl} with this address.`, - '', - 'This account was created by signing in with GitHub (or another provider), and its email', - 'address has not been confirmed, so SAM does not send it sign-in codes: using one would', - 'disconnect the account from GitHub. Open the sign-in page and choose "Sign in with GitHub"', - '(or the provider you used before) instead.', - '', - "If you didn't ask for a code, you can ignore this email.", - ].join('\n'), - }; -} - /** * Sends the code when the address may sign in, a provider sign-in note to an account that must * use its provider, and nothing otherwise. Never throws. @@ -261,7 +240,6 @@ export async function deliverSignInCode(env: Env, email: string, code: string): const message = account?.providerOnly ? providerSignInRequiredEmail(env.BASE_DOMAIN) : signInCodeEmail(env.BASE_DOMAIN, code); - if (account?.providerOnly) log.info('email_sign_in.code_not_sent', { reason: 'provider_only' }); await transport.sender.send({ from: { email: transport.systemFrom(EMAIL_SIGN_IN_LOCAL_PART), name: 'SAM' }, to: email, @@ -269,9 +247,12 @@ export async function deliverSignInCode(env: Env, email: string, code: string): text: message.text, headers: {}, }); - if (!account?.providerOnly) { - log.info('email_sign_in.code_sent', { newAccount: !known, transport: transport.kind }); - } + log.info( + account?.providerOnly + ? 'email_sign_in.provider_required_note_sent' + : 'email_sign_in.code_sent', + { newAccount: !known, transport: transport.kind } + ); } catch (error) { log.error('email_sign_in.send_failed', { error: error instanceof Error ? error.message : String(error), diff --git a/apps/api/src/services/fleet-ops/anomalies-sessions.ts b/apps/api/src/services/fleet-ops/anomalies-sessions.ts index 4a1dbebe1c..ecf7dce208 100644 --- a/apps/api/src/services/fleet-ops/anomalies-sessions.ts +++ b/apps/api/src/services/fleet-ops/anomalies-sessions.ts @@ -2,7 +2,10 @@ * Session snapshot anomaly classes for `ops_find_anomalies`: failed sleeps, captures and * wakes in the lookback window, and wakes that have stayed `waking` too long. */ -import { isLiveWakeTaskStatus } from '../session-snapshot-recovery-conditions'; +import { + isLiveWakeTaskStatus, + LIVE_WAKE_TASK_STATUS_SQL, +} from '../session-snapshot-recovery-conditions'; import { type AnomalyClassResult, int, @@ -65,6 +68,18 @@ export async function snapshotFailures(ctx: SweepContext): Promise ?`; + /** * Wakes still `waking` past `operations.opsAnomalyWakingMinutes`, oldest first, with no * lookback bound: a stuck wake can be weeks old, and that is what this class is for. Age @@ -72,8 +87,12 @@ export async function snapshotFailures(ctx: SweepContext): Promise { const rows = await ctx.env.DATABASE.prepare( @@ -85,13 +104,14 @@ export async function stalledWakes(ctx: SweepContext): Promise(); return result('session_wake_stalled', rows.results ?? [], (row) => { const since = text(row.waking_since); diff --git a/apps/api/src/services/github-project-event-producer.ts b/apps/api/src/services/github-project-event-producer.ts index 1fcc7f0170..36905aab63 100644 --- a/apps/api/src/services/github-project-event-producer.ts +++ b/apps/api/src/services/github-project-event-producer.ts @@ -32,8 +32,8 @@ export type GitHubProjectEventAdmission = { projectId: string; eventType: string; outcome: ProjectEventAdmissionOutcome; - eventId: string; - state: string; + eventId: string | null; + state: string | null; }; export type AdmitGitHubWebhookProjectEventsResult = { @@ -54,7 +54,7 @@ export interface AdmitGitHubWebhookProjectEventsInput { /** * Admit bounded ProjectData events for verified GitHub webhooks that already * flow through SAM. This is intentionally independent from GitHub trigger task - * routing: admission records the project-scoped fact, while delivery matching + * routing: admission retains subscribed CI facts and other project facts, while delivery matching * and prompt/runtime injection remain owned by the B4 subscription layer. */ export async function admitGitHubWebhookProjectEvents( @@ -110,8 +110,8 @@ export async function admitGitHubWebhookProjectEvents( projectId: project.id, eventType: eventInput.eventType, outcome: result.outcome, - eventId: result.event.id, - state: result.event.state, + eventId: result.event?.id ?? null, + state: result.event?.state ?? null, }); } diff --git a/apps/api/src/services/github-pull-request-events.ts b/apps/api/src/services/github-pull-request-events.ts index bdf243734b..855bfa10e1 100644 --- a/apps/api/src/services/github-pull-request-events.ts +++ b/apps/api/src/services/github-pull-request-events.ts @@ -12,6 +12,10 @@ import { findProjectsForGitHubRepository, type GitHubProjectCandidate, } from './github-project-repositories'; +import { + ingestPullRequestReviewWebhook, + isReviewCycleDelivery, +} from './github-pull-request-reviews'; function record(value: unknown): Record | null { return value && typeof value === 'object' && !Array.isArray(value) @@ -28,7 +32,9 @@ export async function ingestPullRequestWebhook( event: string, payload: Record ): Promise { - if (!['pull_request', 'check_run', 'check_suite'].includes(event)) return; + const reviewCycles = isReviewCycleDelivery(event, payload.action); + // Review events matter only for review cycles: anything else returns before the project lookup. + if (!['pull_request', 'check_run', 'check_suite'].includes(event) && !reviewCycles) return; const repo = record(payload.repository); const repositoryFullName = string(repo?.full_name)?.toLowerCase() ?? null; const repositoryId = typeof repo?.id === 'number' ? repo.id : null; @@ -42,9 +48,13 @@ export async function ingestPullRequestWebhook( ); if (projects.length === 0 || !repositoryFullName) return; + // Review cycles for Insights · People; never throws, so it cannot hold up the work below. + if (reviewCycles) + await ingestPullRequestReviewWebhook(env, event, repositoryFullName, projects, payload); if (event === 'pull_request') await ingestLifecycleWebhook(env, repositoryFullName, projects, payload); - else await ingestChecksWebhook(env, event, repositoryFullName, projects, payload); + else if (event === 'check_run' || event === 'check_suite') + await ingestChecksWebhook(env, event, repositoryFullName, projects, payload); } async function ingestLifecycleWebhook( diff --git a/apps/api/src/services/github-pull-request-reviews.ts b/apps/api/src/services/github-pull-request-reviews.ts new file mode 100644 index 0000000000..999f7ce3f4 --- /dev/null +++ b/apps/api/src/services/github-pull-request-reviews.ts @@ -0,0 +1,252 @@ +/** + * Review request cycles for Insights · People "review pickup time" (slice P, migration 0258). The + * GitHub webhook ingest calls this for three deliveries the App already subscribes to: + * + * - `pull_request.review_requested`: open a cycle for that reviewer, unless one is open already. + * - `pull_request.review_request_removed`: close the open cycle as removed (it is not a pickup). + * - `pull_request_review.submitted`: stamp the first review on the reviewer's open cycle, and on + * the pull request's open team cycles (GitHub does not say which team a reviewer answered for, + * so the first review by anyone but the author picks up a team request). + * - `pull_request.closed`: close the pull request's open cycles as removed (never picked up). + * + * Known limits, accepted because they are rare and only skew a statistic: GitHub does not order + * deliveries, so a `review_requested` delivered after its review (or after its removal) opens a + * cycle that only a later review or the pull request closing ends; and of two requests to one + * reviewer racing in, the first to commit keeps its time. + * + * Times are GitHub's (`pull_request.updated_at`, `review.submitted_at`), never the delivery time, + * so a redelivery writes the same values: every statement is idempotent. Bots are skipped: the tab + * is about where work waits on people. Every statement binds the project (rule 11). + * + * A failure is logged and swallowed. These rows only feed a statistic, and the same webhook + * request still has to persist trigger intake for `pull_request_review` automations. + */ +import { parseProjectPullRequestUrl } from '@simple-agent-manager/operations'; + +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import type { GitHubProjectCandidate } from './github-project-repositories'; + +type ReviewerKind = 'user' | 'team'; + +interface Reviewer { + kind: ReviewerKind; + key: string; +} + +function record(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null; +} +function string(value: unknown): string | null { + return typeof value === 'string' && value.length > 0 ? value : null; +} +function isoOf(value: unknown): string | null { + const raw = string(value); + if (!raw) return null; + const ms = Date.parse(raw); + return Number.isFinite(ms) ? new Date(ms).toISOString() : null; +} + +/** The requested reviewer of a `review_requested` / `review_request_removed` delivery. */ +function requestedReviewer(payload: Record): Reviewer | null { + const user = record(payload.requested_reviewer); + if (user) { + const login = string(user.login); + if (!login || user.type === 'Bot') return null; + return { kind: 'user', key: login.toLowerCase() }; + } + const slug = string(record(payload.requested_team)?.slug); + return slug ? { kind: 'team', key: slug.toLowerCase() } : null; +} + +const OPEN_CYCLE_SQL = `first_review_at IS NULL AND removed_at IS NULL`; + +/** The deliveries this module records; `ingestPullRequestWebhook` routes only these here. */ +export function isReviewCycleDelivery(event: string, action: unknown): boolean { + if (event === 'pull_request') + return ( + action === 'review_requested' || action === 'review_request_removed' || action === 'closed' + ); + return event === 'pull_request_review' && action === 'submitted'; +} + +/** + * Called only after the webhook signature was verified by the route. Never throws: a failure is + * logged and the delivery's other work (pull request state, trigger intake) goes on. + */ +export async function ingestPullRequestReviewWebhook( + env: Env, + event: string, + repositoryFullName: string, + projects: GitHubProjectCandidate[], + payload: Record +): Promise { + const action = string(payload.action); + try { + const statements = reviewCycleStatements( + env, + event, + action, + repositoryFullName, + payload, + projects + ); + if (statements.length > 0) await env.DATABASE.batch(statements); + } catch (error) { + log.error('github_review_requests.ingest_failed', { + repository: repositoryFullName, + event, + githubAction: action, + projectIds: projects.map((project) => project.id), + error: error instanceof Error ? error.message : String(error), + action: 'dropped', + }); + } +} + +function reviewCycleStatements( + env: Env, + event: string, + action: string | null, + repositoryFullName: string, + payload: Record, + projects: GitHubProjectCandidate[] +): D1PreparedStatement[] { + const pr = record(payload.pull_request); + const url = string(pr?.html_url); + const number = typeof pr?.number === 'number' ? pr.number : null; + if (!url || !number) return []; + const parsed = parseProjectPullRequestUrl(url, repositoryFullName); + if (parsed?.number !== number) return []; + const target = { repository: parsed.repository, number }; + + let write: ((projectId: string) => D1PreparedStatement) | null = null; + if (event === 'pull_request' && action === 'closed') { + // A request still open when the pull request closed (merged or not) was never picked up. + const at = isoOf(pr?.closed_at) ?? isoOf(pr?.updated_at); + if (!at) return []; + write = (projectId) => closePullRequestCycles(env, projectId, target, at); + } else if ( + event === 'pull_request' && + (action === 'review_requested' || action === 'review_request_removed') + ) { + const reviewer = requestedReviewer(payload); + const at = isoOf(pr?.updated_at); + if (!reviewer || !at) return []; + write = + action === 'review_requested' + ? (projectId) => openCycle(env, projectId, target, reviewer, at) + : (projectId) => removeCycle(env, projectId, target, reviewer, at); + } else if (event === 'pull_request_review' && action === 'submitted') { + const review = record(payload.review); + const reviewerUser = record(review?.user); + const login = string(reviewerUser?.login)?.toLowerCase() ?? null; + const at = isoOf(review?.submitted_at); + if (!login || !at || reviewerUser?.type === 'Bot') return []; + const author = string(record(pr?.user)?.login)?.toLowerCase() ?? null; + write = (projectId) => recordReview(env, projectId, target, login, login === author, at); + } + if (!write) return []; + const statement = write; + return projects.map((project) => statement(project.id)); +} + +interface Target { + repository: string; + number: number; +} + +function openCycle( + env: Env, + projectId: string, + target: Target, + reviewer: Reviewer, + requestedAt: string +): D1PreparedStatement { + // A re-request while one is still open keeps the earlier time: the reviewer has been waited on + // since then. After a review, the next request opens a new cycle. The primary key makes a + // redelivery of a closed cycle's request a no-op. + return env.DATABASE.prepare( + `INSERT INTO pull_request_review_requests + (project_id, repository, pr_number, reviewer_kind, reviewer_key, requested_at) + SELECT ?, ?, ?, ?, ?, ? + WHERE NOT EXISTS (SELECT 1 FROM pull_request_review_requests + WHERE project_id = ? AND repository = ? AND pr_number = ? AND reviewer_kind = ? + AND reviewer_key = ? AND ${OPEN_CYCLE_SQL}) + ON CONFLICT DO NOTHING` + ).bind( + projectId, + target.repository, + target.number, + reviewer.kind, + reviewer.key, + requestedAt, + projectId, + target.repository, + target.number, + reviewer.kind, + reviewer.key + ); +} + +function removeCycle( + env: Env, + projectId: string, + target: Target, + reviewer: Reviewer, + removedAt: string +): D1PreparedStatement { + return env.DATABASE.prepare( + `UPDATE pull_request_review_requests SET removed_at = ? + WHERE project_id = ? AND repository = ? AND pr_number = ? AND reviewer_kind = ? + AND reviewer_key = ? AND ${OPEN_CYCLE_SQL} AND requested_at <= ?` + ).bind( + removedAt, + projectId, + target.repository, + target.number, + reviewer.kind, + reviewer.key, + removedAt + ); +} + +function closePullRequestCycles( + env: Env, + projectId: string, + target: Target, + closedAt: string +): D1PreparedStatement { + return env.DATABASE.prepare( + `UPDATE pull_request_review_requests SET removed_at = ? + WHERE project_id = ? AND repository = ? AND pr_number = ? AND ${OPEN_CYCLE_SQL} + AND requested_at <= ?` + ).bind(closedAt, projectId, target.repository, target.number, closedAt); +} + +function recordReview( + env: Env, + projectId: string, + target: Target, + login: string, + byAuthor: boolean, + submittedAt: string +): D1PreparedStatement { + // The author's own review comment answers no one's request, so it closes no team cycle. + return env.DATABASE.prepare( + `UPDATE pull_request_review_requests SET first_review_at = ? + WHERE project_id = ? AND repository = ? AND pr_number = ? AND ${OPEN_CYCLE_SQL} + AND requested_at <= ? + AND ((reviewer_kind = 'user' AND reviewer_key = ?) OR (reviewer_kind = 'team' AND ? = 0))` + ).bind( + submittedAt, + projectId, + target.repository, + target.number, + submittedAt, + login, + byAuthor ? 1 : 0 + ); +} diff --git a/apps/api/src/services/github-token-errors.ts b/apps/api/src/services/github-token-errors.ts index 6c2f3437e2..afdf161d00 100644 --- a/apps/api/src/services/github-token-errors.ts +++ b/apps/api/src/services/github-token-errors.ts @@ -13,8 +13,7 @@ export const GITHUB_NOT_CONNECTED_MESSAGE = * (BetterAuth `/link-social`, Settings → GitHub) can. * - `GITHUB_REAUTH_REQUIRED` (401): a link exists but its token is missing, expired or could not * be refreshed. - * Runs only on the failure path (one D1 read). If the read fails, it answers the reauth error, - * which is what every caller answered before. + * Runs only on the failure path (one D1 read). A failed read returns a retryable availability error; it cannot prove expiry. */ export async function githubUserTokenUnavailableError( env: Pick, @@ -29,7 +28,11 @@ export async function githubUserTokenUnavailableError( .first<{ present: number }>(); linked = row !== null && row !== undefined; } catch { - linked = true; + return new AppError( + 503, + 'GITHUB_UNAVAILABLE', + 'GitHub account status could not be checked. Please try again later.' + ); } return linked ? new AppError(401, 'GITHUB_REAUTH_REQUIRED', GITHUB_REAUTH_REQUIRED_MESSAGE) diff --git a/apps/api/src/services/gitlab-login-provider.ts b/apps/api/src/services/gitlab-login-provider.ts index 03500cd0b7..460b155f62 100644 --- a/apps/api/src/services/gitlab-login-provider.ts +++ b/apps/api/src/services/gitlab-login-provider.ts @@ -1,144 +1,93 @@ -/** - * The better-auth GitLab sign-in provider, built from the admin's GitLab settings. - * - * Outbound requests, and who controls them (better-auth 1.7.14, @better-auth/core dist): - * - authorization redirect: the browser goes there; the Worker fetches nothing. - * - code exchange (`validateAuthorizationCode`) and token refresh (`refreshAccessToken`, reached - * through `getAccessToken` from the repo-hosting package's gitlab.ts): better-auth's - * `fetchRefusingRedirects` (`oauth2/reject-redirects.mjs`), `redirect: 'manual'`, any 3xx is - * an error. They carry the client secret and refresh token, and go only to - * `/oauth/token`. The provider has no - * fetch hook for these, so SAM guards them by refusing to register the provider at all for a - * host it may not call (`assertGitLabHostAllowed`); DNS answers are the egress fence's job. - * - profile (`getUserInfo`): better-auth's default follows redirects with the access token, so - * SAM replaces it with a guarded fetch (every hop re-checked, cross-origin hops lose the token). - * - * Identity trust (`GitLabOAuthConfig.identityTrusted`): a host SAM does not trust (a self-managed - * host saved at runtime) cannot vouch for an email and cannot reuse another host's account ids. - * Its accounts are stored under a host-scoped key (`untrustedGitLabAccountSubject`), its emails - * count as unverified, it gets no profile override, and `auth.ts` leaves it out of - * `trustedProviders`. +/** GitLab profile requests use the shared outbound guard; OAuth exchange/refresh use + * BetterAuth's fetchRefusingRedirects (manual, any redirect refused). Refusing the + * provider before registration also protects those library-owned token requests. */ import { - DEFAULT_GITLAB_API_TIMEOUT_MS, - gitLabHostVerdict, -} from '@simple-agent-manager/repo-hosting'; + assertOutboundUrl, + getTimeoutMs, + guardedFetch, + readResponseJson, + withDeadline, +} from '@simple-agent-manager/worker-core'; import type { GitlabOptions, GitlabProfile } from 'better-auth/social-providers'; import * as v from 'valibot'; import type { Env } from '../env'; -import { createModuleLogger } from '../lib/logger'; -import { guardedFetchWithDeadline } from '../lib/network-hosts'; -import { readResponseJson } from '../lib/runtime-validation'; -import { getTimeoutMs } from './fetch-timeout'; +import { log } from '../lib/logger'; import { untrustedGitLabAccountSubject } from './gitlab-sign-in-identity'; import { keepLinkedAccountEmail } from './linked-account-identity'; import { resolveOutboundMaxRedirects } from './outbound-fetch-settings'; import type { GitLabOAuthConfig } from './platform-config-oauth'; -const log = createModuleLogger('gitlab-login'); - -/** - * Every scope SAM asks GitLab for, once each. better-auth's GitLab provider prepends its own - * default `read_user` unless `disableDefaultScope` is set, which made the authorize URL ask for - * `read_user` twice (box round R17, D4); the provider below disables that default so this list - * is the whole request. - */ -export const GITLAB_SCOPES = ['read_user', 'api', 'read_repository', 'write_repository']; - +const DEFAULT_GITLAB_API_TIMEOUT_MS = 30_000; const gitlabUserSchema = v.object({ - id: v.number(), - username: v.string(), + id: v.union([v.number(), v.string()]), + username: v.optional(v.nullable(v.string())), name: v.optional(v.nullable(v.string())), email: v.optional(v.nullable(v.string())), - state: v.string(), - locked: v.optional(v.nullable(v.boolean())), avatar_url: v.optional(v.nullable(v.string())), - email_verified: v.optional(v.nullable(v.boolean())), + email_verified: v.optional(v.boolean()), + state: v.optional(v.nullable(v.string())), + locked: v.optional(v.nullable(v.boolean())), }); -type GitLabProvider = GitlabOptions; -type GitLabUserInfo = Awaited>>; - -/** The signed-in GitLab user, fetched through the guarded fetch. Mirrors better-auth's default. */ -export async function fetchGitLabUserInfo( - env: Env, - config: GitLabOAuthConfig, - accessToken: string | undefined -): Promise { - if (!accessToken) return null; - let response: Response; +export function gitLabLoginProvider(env: Env, config: GitLabOAuthConfig): GitlabOptions | null { try { - response = await guardedFetchWithDeadline( - `${config.host}/api/v4/user`, - { headers: { authorization: `Bearer ${accessToken}`, accept: 'application/json' } }, - { - allowPrivateNetwork: config.allowPrivateNetwork, - maxRedirects: await resolveOutboundMaxRedirects(env), - deadlineMs: getTimeoutMs(env.GITLAB_API_TIMEOUT_MS, DEFAULT_GITLAB_API_TIMEOUT_MS), - } - ); - } catch (err) { - log.warn('gitlab_user_fetch_refused', { - error: err instanceof Error ? err.message : String(err), - }); - return null; - } - if (!response.ok) { - log.warn('gitlab_user_fetch_failed', { status: response.status }); - return null; - } - const profile = await readResponseJson(response, gitlabUserSchema, 'gitlab.user'); - if (profile.state !== 'active' || profile.locked) return null; - if (!config.identityTrusted) { - if (!profile.email) return null; - return { - user: { - name: profile.name ?? profile.username ?? '', - email: profile.email, - image: profile.avatar_url ?? undefined, - emailVerified: false, - }, - // better-auth keys the account on `data.id`; the host-scoped key is a string, which - // better-auth stringifies anyway (`resolveOAuthAccountKey`). - data: { - ...profile, - id: untrustedGitLabAccountSubject(config.host, profile.id), - } as unknown as GitlabProfile, - }; - } - // A linked account keeps its own verified SAM email (`keepLinkedAccountEmail`). - const identity = await keepLinkedAccountEmail(env, 'gitlab', String(profile.id), { - email: profile.email, - emailVerified: profile.email_verified ?? false, - }); - return { - user: { - name: profile.name ?? profile.username ?? '', - email: identity.email ?? undefined, - image: profile.avatar_url ?? undefined, - emailVerified: identity.emailVerified, - }, - // better-auth keys the account on `data.id` (`accountSubject: ({ profile }) => profile.id`). - // Only the fields gitlabUserSchema validates exist; nothing in SAM reads the others. - data: profile as GitlabProfile, - }; -} - -/** The GitLab provider, or null when the admin's host may not be called (logged). */ -export function gitLabLoginProvider(env: Env, config: GitLabOAuthConfig): GitLabProvider | null { - const verdict = gitLabHostVerdict(config.host, config.allowPrivateNetwork); - if (verdict !== 'allowed') { - log.warn('gitlab_login_disabled_host_refused', { verdict }); + // A private host needs the admin opt-in `integration.gitlab.allowPrivateNetwork`. + assertOutboundUrl(config.host, { allowPrivateNetwork: config.allowPrivateNetwork }); + } catch { + log.warn('gitlab_login_disabled_host_refused'); return null; } return { clientId: config.clientId, clientSecret: config.clientSecret, issuer: config.host, - scope: GITLAB_SCOPES, + scope: ['read_user', 'api', 'read_repository', 'write_repository'], disableDefaultScope: true, overrideUserInfoOnSignIn: config.identityTrusted, - getUserInfo: (token) => fetchGitLabUserInfo(env, config, token.accessToken), + getUserInfo: async (token) => { + if (!token.accessToken) return null; + try { + const maxRedirects = await resolveOutboundMaxRedirects(env); + return await withDeadline( + async (signal) => { + const response = await guardedFetch( + `${config.host}/api/v4/user`, + { + headers: { authorization: `Bearer ${token.accessToken}` }, + signal, + }, + { maxRedirects, allowPrivateNetwork: config.allowPrivateNetwork } + ); + if (!response.ok) return null; + const profile = await readResponseJson(response, gitlabUserSchema, 'gitlab.user'); + if (profile.state !== 'active' || profile.locked || !profile.email) return null; + const accountId = config.identityTrusted ? String(profile.id) : untrustedGitLabAccountSubject(config.host, profile.id); + const identity = await keepLinkedAccountEmail(env, 'gitlab', accountId, { email: profile.email, emailVerified: config.identityTrusted && (profile.email_verified ?? false) }); + return { + user: { + name: profile.name ?? profile.username ?? '', + email: identity.email ?? profile.email, + image: profile.avatar_url ?? undefined, + emailVerified: identity.emailVerified, + }, + // BetterAuth reads data.id as the account key. Untrusted hosts retain + // their host-scoped string key; GitlabProfile only types numeric ids. + data: { + ...profile, + id: config.identityTrusted + ? profile.id + : untrustedGitLabAccountSubject(config.host, profile.id), + } as unknown as GitlabProfile, + }; + }, + getTimeoutMs(env.GITLAB_API_TIMEOUT_MS, DEFAULT_GITLAB_API_TIMEOUT_MS) + ); + } catch { + log.warn('gitlab_sign_in.user_fetch_refused'); + return null; + } + }, }; } diff --git a/apps/api/src/services/hosted-git/backend.ts b/apps/api/src/services/hosted-git/backend.ts index bb1b2a311b..40aa4feb0a 100644 --- a/apps/api/src/services/hosted-git/backend.ts +++ b/apps/api/src/services/hosted-git/backend.ts @@ -1,149 +1,48 @@ /** * The SAM-native repository backend: one answer to "which `Env.ARTIFACTS` does this install use?". * - * - `ARTIFACTS_ENABLED !== 'true'`: none (unchanged). - * - A Cloudflare Artifacts binding is present: that binding (unchanged on Cloudflare). - * - Otherwise, `HOSTED_GIT_BACKEND === 'durable-object'` with the `HOSTED_GIT` Durable Object - * bound: the local backend below, which implements the same four methods against SAM's own - * git server (`durable-objects/hosted-git-repo.ts`). Only the self-host build sets the var and - * binds the class (`scripts/selfhost/celld-config.ts`, `selfhost-durable-objects.ts`); the - * Cloudflare Worker has neither, and this module never imports the class, only its binding. + * - `ARTIFACTS_ENABLED !== 'true'`: none. + * - A Cloudflare Artifacts binding is present: that binding. This is every Cloudflare deployment. + * - Otherwise, the fallback backend the self-host build registered, if any. The Cloudflare build + * registers none, so on Cloudflare the result is exactly the binding or null. * - * Every caller that used `env.ARTIFACTS` goes through `resolveArtifactsBackend`, so the - * capability, project creation, browsing, git tokens and deletion cannot disagree. + * The self-host build (`apps/api/src/selfhost/`, never imported by `src/index.ts`) registers SAM's own + * git server here. This module holds only the selection, so the Cloudflare bundle carries no + * hosted-git implementation. + * + * Every caller that needs the backend goes through `resolveArtifactsBackend`, so the capability + * flag, project creation, browsing and git tokens cannot disagree. Deletion uses the same + * selection without the enable flag, so disabling the feature cannot orphan existing repositories. */ import type { Env } from '../../env'; -import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from './http'; -import { clampHostedGitTokenTtl, type HostedGitScope, mintHostedGitToken } from './tokens'; export type ArtifactsBackend = NonNullable; -type BackendEnv = Pick< - Env, - 'ARTIFACTS' | 'ARTIFACTS_ENABLED' | 'HOSTED_GIT' | 'HOSTED_GIT_BACKEND' | 'BASE_DOMAIN' -> & - Partial>; - -export function isHostedGitBackendConfigured( - env: Pick -): boolean { - return env.HOSTED_GIT_BACKEND?.trim() === 'durable-object' && !!env.HOSTED_GIT; -} - -/** Base URL of hosted repositories; a repository's remote is `.git`. */ -export function hostedGitBaseUrl(env: Pick): string { - return `https://api.${env.BASE_DOMAIN}${HOSTED_GIT_PATH_PREFIX}`; -} - -export function hostedGitRemote(env: Pick, repo: string): string { - return `${hostedGitBaseUrl(env)}${repo}.git`; -} - -/** Host git clients use for hosted repositories (`api.`). */ -export function hostedGitHost(env: Pick): string { - return `api.${env.BASE_DOMAIN}`; -} - -function repoStub(env: BackendEnv, name: string): DurableObjectStub { - if (!env.HOSTED_GIT) throw new Error('HOSTED_GIT binding is missing'); - return env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(name)); -} +/** Builds the fallback backend for an install with no Artifacts binding, or returns null. */ +export type ArtifactsBackendFallback = (env: Env) => ArtifactsBackend | null; -function requireEncryptionKey(env: BackendEnv): Pick { - if (!env.ENCRYPTION_KEY) - throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories'); - return { ENCRYPTION_KEY: env.ENCRYPTION_KEY }; -} - -/** The local implementation of the four `Env.ARTIFACTS` methods SAM calls. */ -export function createDurableObjectArtifactsBackend(env: BackendEnv): ArtifactsBackend { - const keyEnv = () => requireEncryptionKey(env); - return { - async create(name, opts) { - const defaultBranch = opts?.setDefaultBranch || 'main'; - const res = await repoStub(env, name).fetch('https://hosted-git/init', { - method: 'PUT', - body: JSON.stringify({ defaultBranch }), - }); - if (!res.ok) throw new Error(`Hosted repository init failed: HTTP ${res.status}`); - const { token } = await mintHostedGitToken(keyEnv(), { repo: name, scope: 'write' }); - return { - id: name, - name, - remote: hostedGitRemote(env, name), - token, - default_branch: defaultBranch, - }; - }, - async delete(name) { - const res = await repoStub(env, name).fetch('https://hosted-git/', { method: 'DELETE' }); - return res.ok; - }, - async get(name) { - const res = await repoStub(env, name).fetch('https://hosted-git/info'); - const info = res.ok ? ((await res.json()) as { head?: string }) : {}; - const defaultBranch = (info.head ?? 'refs/heads/main').replace(/^refs\/heads\//, ''); - return { - id: name, - name, - remote: hostedGitRemote(env, name), - defaultBranch, - async createToken(scope?: HostedGitScope, ttl?: number) { - const minted = await mintHostedGitToken(keyEnv(), { - repo: name, - scope: scope ?? 'read', - ttlSeconds: clampHostedGitTokenTtl(ttl), - }); - return { - id: name, - plaintext: minted.token, - scope: scope ?? 'read', - expiresAt: minted.expiresAt, - }; - }, - }; - }, - }; -} +let fallback: ArtifactsBackendFallback | null = null; -/** Whether this install serves SAM-native repositories from its own Durable Object git server. */ -export function isLocalHostedGitActive(env: BackendEnv): boolean { - return env.ARTIFACTS_ENABLED === 'true' && !env.ARTIFACTS && isHostedGitBackendConfigured(env); +/** + * Installs the backend used when Artifacts is enabled but no Cloudflare binding exists. Called once + * at module load by the self-host build. Passing null removes it (tests). + */ +export function registerArtifactsBackendFallback(factory: ArtifactsBackendFallback | null): void { + fallback = factory; } /** The backend this install uses for SAM-native repositories, or null when it has none. */ -export function resolveArtifactsBackend(env: BackendEnv): ArtifactsBackend | null { +export function resolveArtifactsBackend(env: Env): ArtifactsBackend | null { if (env.ARTIFACTS_ENABLED !== 'true') return null; - if (env.ARTIFACTS) return env.ARTIFACTS; - if (isHostedGitBackendConfigured(env)) return createDurableObjectArtifactsBackend(env); - return null; + return resolveArtifactsBackendForCleanup(env); } -/** Whether `remote` is a repository on this install's own git server. */ -export function isHostedGitRemote(env: Pick, remote: string): boolean { - return !!env.BASE_DOMAIN && remote.startsWith(hostedGitBaseUrl(env)); +/** Existing repositories still need cleanup after the feature is disabled. Never use for serving. */ +export function resolveArtifactsBackendForCleanup(env: Env): ArtifactsBackend | null { + return env.ARTIFACTS ?? fallback?.(env) ?? null; } -/** - * A fetch for SAM's own calls to a repository remote (README seeding, browsing). Requests to the - * hosted git server are served in-process through the same authenticated handler external git - * clients reach, instead of leaving the Worker and coming back through the ingress (no hairpin - * through Caddy, no egress-fence exception). Anything else uses the global fetch. - */ -export function artifactsRemoteFetch(env: BackendEnv): typeof fetch { - // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend - if (!isLocalHostedGitActive(env)) return fetch; - return async (input, init) => { - const request = new Request(input, init); - if (!isHostedGitRemote(env, request.url) || !env.DATABASE || !env.ENCRYPTION_KEY) { - // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend - return fetch(request); - } - const response = await handleHostedGitRequest( - request, - { DATABASE: env.DATABASE, ENCRYPTION_KEY: env.ENCRYPTION_KEY, HOSTED_GIT: env.HOSTED_GIT }, - { trustedInternalCaller: true } - ); - return response ?? new Response('not found\n', { status: 404 }); - }; +/** Whether this install can create and serve SAM-native (Artifacts) repositories. */ +export function isArtifactsAvailable(env: Env): boolean { + return resolveArtifactsBackend(env) !== null; } diff --git a/apps/api/src/services/hosted-git/local-backend.ts b/apps/api/src/services/hosted-git/local-backend.ts new file mode 100644 index 0000000000..2dce67d46f --- /dev/null +++ b/apps/api/src/services/hosted-git/local-backend.ts @@ -0,0 +1,145 @@ +/** + * SAM's own git server as an Artifacts backend (self-host only). + * + * `backend.ts` is the seam: it selects the Cloudflare Artifacts binding, else the fallback a + * self-host build registered. This module is that fallback: the four `Env.ARTIFACTS` methods SAM + * calls, implemented against the `HostedGitRepo` Durable Object (`durable-objects/hosted-git-repo.ts`) + * through the `HOSTED_GIT` namespace binding only. It never imports the class. The self-host build + * registers it (`selfhost/hosted-git.ts`); only that build sets `HOSTED_GIT_BACKEND` and binds the + * class (`scripts/selfhost/celld-config.ts`, `selfhost-durable-objects.ts`), so on Cloudflare + * `isLocalHostedGitActive` is always false. + */ +import type { Env } from '../../env'; +import type { ArtifactsBackend } from './backend'; +import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from './http'; +import { clampHostedGitTokenTtl, type HostedGitScope, mintHostedGitToken } from './tokens'; + +type BackendEnv = Pick< + Env, + 'ARTIFACTS' | 'ARTIFACTS_ENABLED' | 'HOSTED_GIT' | 'HOSTED_GIT_BACKEND' | 'BASE_DOMAIN' +> & + Partial>; + +export function isHostedGitBackendConfigured( + env: Pick +): boolean { + return env.HOSTED_GIT_BACKEND?.trim() === 'durable-object' && !!env.HOSTED_GIT; +} + +/** Base URL of hosted repositories; a repository's remote is `.git`. */ +export function hostedGitBaseUrl(env: Pick): string { + return `https://api.${env.BASE_DOMAIN}${HOSTED_GIT_PATH_PREFIX}`; +} + +export function hostedGitRemote(env: Pick, repo: string): string { + return `${hostedGitBaseUrl(env)}${repo}.git`; +} + +/** Host git clients use for hosted repositories (`api.`). */ +export function hostedGitHost(env: Pick): string { + return `api.${env.BASE_DOMAIN}`; +} + +function repoStub(env: BackendEnv, name: string): DurableObjectStub { + if (!env.HOSTED_GIT) throw new Error('HOSTED_GIT binding is missing'); + return env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(name)); +} + +function requireEncryptionKey(env: BackendEnv): Pick { + if (!env.ENCRYPTION_KEY) + throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories'); + return { ENCRYPTION_KEY: env.ENCRYPTION_KEY }; +} + +/** The local implementation of the four `Env.ARTIFACTS` methods SAM calls. */ +export function createDurableObjectArtifactsBackend(env: BackendEnv): ArtifactsBackend { + const keyEnv = () => requireEncryptionKey(env); + return { + async create(name, opts) { + const defaultBranch = opts?.setDefaultBranch || 'main'; + const res = await repoStub(env, name).fetch('https://hosted-git/init', { + method: 'PUT', + body: JSON.stringify({ defaultBranch }), + }); + if (!res.ok) throw new Error(`Hosted repository init failed: HTTP ${res.status}`); + const { token } = await mintHostedGitToken(keyEnv(), { repo: name, scope: 'write' }); + return { + id: name, + name, + remote: hostedGitRemote(env, name), + token, + default_branch: defaultBranch, + }; + }, + async delete(name) { + const res = await repoStub(env, name).fetch('https://hosted-git/', { method: 'DELETE' }); + return res.ok; + }, + async get(name) { + const res = await repoStub(env, name).fetch('https://hosted-git/info'); + const info = res.ok ? ((await res.json()) as { head?: string }) : {}; + const defaultBranch = (info.head ?? 'refs/heads/main').replace(/^refs\/heads\//, ''); + return { + id: name, + name, + remote: hostedGitRemote(env, name), + defaultBranch, + async createToken(scope?: HostedGitScope, ttl?: number) { + const minted = await mintHostedGitToken(keyEnv(), { + repo: name, + scope: scope ?? 'read', + ttlSeconds: clampHostedGitTokenTtl(ttl), + }); + return { + id: name, + plaintext: minted.token, + scope: scope ?? 'read', + expiresAt: minted.expiresAt, + }; + }, + }; + }, + }; +} + +/** + * The fallback the self-host build registers with `registerArtifactsBackendFallback`: SAM's own git + * server when this install configured it, else none. + */ +export function localHostedGitBackendFallback(env: Env): ArtifactsBackend | null { + return isHostedGitBackendConfigured(env) ? createDurableObjectArtifactsBackend(env) : null; +} + +/** Whether this install serves SAM-native repositories from its own Durable Object git server. */ +export function isLocalHostedGitActive(env: BackendEnv): boolean { + return env.ARTIFACTS_ENABLED === 'true' && !env.ARTIFACTS && isHostedGitBackendConfigured(env); +} + +/** Whether `remote` is a repository on this install's own git server. */ +export function isHostedGitRemote(env: Pick, remote: string): boolean { + return !!env.BASE_DOMAIN && remote.startsWith(hostedGitBaseUrl(env)); +} + +/** + * A fetch for SAM's own calls to a repository remote (README seeding, browsing). Requests to the + * hosted git server are served in-process through the same authenticated handler external git + * clients reach, instead of leaving the Worker and coming back through the ingress (no hairpin + * through Caddy, no egress-fence exception). Anything else uses the global fetch. + */ +export function artifactsRemoteFetch(env: BackendEnv): typeof fetch { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend + if (!isLocalHostedGitActive(env)) return fetch; + return async (input, init) => { + const request = new Request(input, init); + if (!isHostedGitRemote(env, request.url) || !env.DATABASE || !env.ENCRYPTION_KEY) { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend + return fetch(request); + } + const response = await handleHostedGitRequest( + request, + { DATABASE: env.DATABASE, ENCRYPTION_KEY: env.ENCRYPTION_KEY, HOSTED_GIT: env.HOSTED_GIT }, + { trustedInternalCaller: true } + ); + return response ?? new Response('not found\n', { status: 404 }); + }; +} diff --git a/apps/api/src/services/inbox/agent-asks.ts b/apps/api/src/services/inbox/agent-asks.ts index 1dfc85739e..6c081bf1c3 100644 --- a/apps/api/src/services/inbox/agent-asks.ts +++ b/apps/api/src/services/inbox/agent-asks.ts @@ -13,6 +13,7 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import * as notificationService from '../notification'; import * as projectDataService from '../project-data'; +import { stripMarkdown } from '../task-title'; import { linkQuestionNotification } from './question-asks'; /** @@ -58,13 +59,20 @@ export async function announceAgentAsk( projectId: input.projectId, projectName, taskId: input.taskId, - taskTitle: task?.title ?? input.title, - context: input.body, + // A result's push leads with its outcome, not the task's name. + taskTitle: input.kind === 'result' ? input.title : (task?.title ?? input.title), + // `why` is markdown in the inbox; a push shows plain text. + context: stripMarkdown(input.body), category, options: input.options.length > 0 ? input.options : null, sessionId: input.sessionId, attentionMarkerId: input.askId, label: input.kind === 'review' ? 'Review' : undefined, + heading: input.kind === 'result' ? 'Result ready' : undefined, + // A review or result opens its inbox item; a question keeps its chat link. + ...(input.kind === 'question' + ? {} + : { inboxKind: input.kind, inboxRef: `ask:${input.askId}` }), }); const scheduled = notification.id !== 'suppressed'; if (scheduled && input.kind === 'question') { diff --git a/apps/api/src/services/inbox/ask-notice.ts b/apps/api/src/services/inbox/ask-notice.ts index 7acee67ece..56374d5ff5 100644 --- a/apps/api/src/services/inbox/ask-notice.ts +++ b/apps/api/src/services/inbox/ask-notice.ts @@ -54,6 +54,11 @@ export function buildInboxAskPrompt( ? `The person reviewed your ${item} and replied:\n\n${answer}` : `The person reviewed your ${item}: it looks good.`; } + if (row.kind === 'result' && outcome === 'answered' && answer) { + // "Got it" closes a result without a notice (`answerAsk`), so an answered result that + // reaches here carries the person's reply. + return `The person replied to your ${item}:\n\n${answer}`; + } switch (outcome) { case 'answered': return answer diff --git a/apps/api/src/services/inbox/automation-errors.ts b/apps/api/src/services/inbox/automation-errors.ts new file mode 100644 index 0000000000..ac9345945f --- /dev/null +++ b/apps/api/src/services/inbox/automation-errors.ts @@ -0,0 +1,226 @@ +/** + * Failing automations as inbox error items (inbox slice E). An automation (`triggers` row) that + * has failed `inbox.automationFailureThreshold` runs in a row files one item for its owner; it is + * updated in place as the streak grows or the automation is auto-paused + * (`trigger-admission.ts`, `TRIGGER_AUTO_PAUSE_AFTER_FAILURES`), and closes by itself when a run + * succeeds or the automation is resumed (both end the streak in `consecutiveFailureCount`, which + * honours the resume reset sequence) or when it is disabled or deleted. + * + * Both halves run in the five-minute operational cron as one isolated step, each half isolated on its own: + * - file: automations with a failed run completed inside `inbox.errorLookbackMinutes` + * (`idx_trigger_executions_failed_completed`) that their item does not reflect yet, one row per + * automation, at most `4 × inbox.errorSweepBatchSize` checked (one streak read each) and + * `inbox.errorSweepBatchSize` filed per tick; + * - close: open or archived automation items holding a dedupe key (`idx_asks_error_key`), each + * with its latest finished run read in the same statement + * (`idx_trigger_executions_trigger_finished`, one seek per item); only items that can close or + * need Resume are returned, at most `4 × inbox.errorSweepBatchSize`, so a still-failing + * automation costs one seek a tick and never holds a slot. + */ +import { + getInboxLimits, + quotedName, + resolveSystemError, + type SystemErrorInput, +} from '@simple-agent-manager/operations'; +import { classifyFailure } from '@simple-agent-manager/shared'; + +import type { Env } from '../../env'; +import { log, serializeError } from '../../lib/logger'; +import { consecutiveFailureCount } from '../trigger-failure-window'; +import { fileAndNotify, systemErrorDeps } from './system-errors'; + +interface FailingTriggerRow { + trigger_id: string; + project_id: string; + user_id: string; + name: string | null; + status: string; + error_message: string | null; +} + +const KEY_PREFIX = 'error:automation:'; + +/** The item for an automation `failures` runs into a failure streak. Never quotes the error. */ +export function automationFailureError(row: FailingTriggerRow, failures: number): SystemErrorInput { + const name = quotedName(row.name, 'An automation'); + const paused = row.status === 'paused'; + return { + projectId: row.project_id, + assigneeUserId: row.user_id, + source: 'automation', + subjectId: row.trigger_id, + title: paused + ? `Automation ${name} was paused after ${failures} failed runs` + : `Automation ${name} failed its last ${failures} runs`, + body: classifyFailure(row.error_message).explanation, + actions: paused ? ['resume'] : [], + links: [{ kind: 'trigger', id: row.trigger_id, label: row.name }], + failureCount: failures, + }; +} + +export interface AutomationErrorSweepStats { + checked: number; + filed: number; + closed: number; +} + +/** + * The newest finished run inside an automation's current failure window + * (`auto_pause_reset_sequence`, moved by a resume): the streak ended when it succeeded or when + * none has finished since a resume. A run still in flight decides nothing, so an item does not + * close and reopen around it. One seek on `idx_trigger_executions_trigger_finished`. + */ +const LATEST_FINISHED_STATUS_SQL = `(SELECT e.status FROM trigger_executions e + WHERE e.trigger_id = tr.id AND e.status IN ('completed', 'failed') + AND (tr.auto_pause_reset_sequence IS NULL + OR e.sequence_number >= tr.auto_pause_reset_sequence) + ORDER BY e.sequence_number DESC LIMIT 1)`; + +export async function runInboxAutomationErrorSweep( + env: Env, + now = Date.now() +): Promise { + const limits = await getInboxLimits(systemErrorDeps(env)); + const threshold = limits.automationFailureThreshold; + const since = new Date(now - limits.errorLookbackMinutes * 60_000).toISOString(); + let checked = 0; + let filed = 0; + let closed = 0; + + // File: one row per automation with a failed run in the window that its item does not reflect + // yet. An archived item reflects every run (the person said they will not act; the key stays + // until the automation recovers), so it never holds a slot here. + try { + const candidates = await env.DATABASE.prepare( + // SQLite: bare columns of a MAX() aggregate come from the row holding the maximum, so + // error_message is the newest failed run's. + `SELECT e.trigger_id, tr.project_id, tr.user_id, tr.name, tr.status, e.error_message, + MAX(e.completed_at) AS last_failed_at + FROM trigger_executions e + JOIN triggers tr ON tr.id = e.trigger_id AND tr.project_id = e.project_id + WHERE e.status = 'failed' AND e.completed_at > ? AND tr.status IN ('active', 'paused') + AND NOT EXISTS (SELECT 1 FROM asks a + WHERE a.project_id = tr.project_id AND a.dedupe_key = '${KEY_PREFIX}' || tr.id + AND (a.status = 'archived' + OR a.updated_at >= CAST((julianday(e.completed_at) - 2440587.5) * 86400000 AS INTEGER))) + GROUP BY e.trigger_id + ORDER BY last_failed_at DESC LIMIT ?` + ) + .bind(since, threshold > 0 ? limits.errorSweepBatchSize * 4 : 0) + .all(); + for (const row of candidates.results ?? []) { + if (filed >= limits.errorSweepBatchSize) break; + checked += 1; + try { + const streak = await consecutiveFailureCount(env, row.trigger_id, Math.max(threshold, 50)); + if (streak.count < threshold) continue; + const result = await fileAndNotify( + env, + automationFailureError(row, streak.count), + 'cron_failure' + ); + if (result) filed += 1; + } catch (error) { + log.error('inbox.automation_error_check_failed', { + triggerId: row.trigger_id, + projectId: row.project_id, + ...serializeError(error), + }); + } + } + } catch (error) { + log.error('inbox.automation_error_scan_failed', serializeError(error)); + } + + // Close or refresh: only the items that need something, decided in SQL so a still-failing + // automation costs one index seek and never holds a slot of the page (rule 47). An item closes + // when its automation is gone or disabled (`cancelled`) or its streak ended (`recovered`); an + // open item whose automation was auto-paused (at the next fire, `trigger-admission.ts`, which + // records no run the file half could see) is refreshed to say so and offer Resume. + try { + const open = await env.DATABASE.prepare( + `SELECT * FROM ( + SELECT a.project_id, a.dedupe_key, a.status AS item_status, a.answer_spec_json, + a.updated_at AS item_updated_at, tr.id AS trigger_id, + tr.status AS trigger_status, tr.user_id, tr.name, + ${LATEST_FINISHED_STATUS_SQL} AS latest_status, + (SELECT e.error_message FROM trigger_executions e + WHERE e.trigger_id = tr.id AND e.status = 'failed' + ORDER BY e.sequence_number DESC LIMIT 1) AS error_message + FROM asks a + LEFT JOIN triggers tr ON tr.project_id = a.project_id + AND tr.id = substr(a.dedupe_key, ${KEY_PREFIX.length + 1}) + WHERE a.kind = 'error' AND a.dedupe_key IS NOT NULL + AND a.dedupe_key >= 'error:automation:' AND a.dedupe_key < 'error:automation;' + AND a.status IN ('open', 'archived')) + WHERE trigger_id IS NULL OR trigger_status = 'disabled' + OR latest_status IS NOT 'failed' + OR (trigger_status = 'paused' AND item_status = 'open' + AND COALESCE(answer_spec_json, '') NOT LIKE '%"resume"%') + ORDER BY item_updated_at LIMIT ?` + ) + .bind(limits.errorSweepBatchSize * 4) + .all<{ + project_id: string; + dedupe_key: string; + trigger_id: string | null; + trigger_status: string | null; + user_id: string | null; + name: string | null; + latest_status: string | null; + error_message: string | null; + }>(); + for (const item of open.results ?? []) { + const subjectId = item.dedupe_key.slice(KEY_PREFIX.length); + try { + // Deleted or switched off by a person: there is nothing left to fix. + const resolution = + !item.trigger_id || item.trigger_status === 'disabled' + ? ('cancelled' as const) + : item.latest_status !== 'failed' + ? ('recovered' as const) + : null; + if (resolution) { + closed += await resolveSystemError( + { env }, + { projectId: item.project_id, source: 'automation', subjectId, resolution } + ); + continue; + } + if (!item.trigger_id || !item.user_id) continue; + const streak = await consecutiveFailureCount(env, item.trigger_id, 50); + if (streak.count === 0) continue; + const refreshed = await fileAndNotify( + env, + automationFailureError( + { + trigger_id: item.trigger_id, + project_id: item.project_id, + user_id: item.user_id, + name: item.name, + status: 'paused', + error_message: item.error_message, + }, + streak.count + ), + 'cron_failure' + ); + if (refreshed) filed += 1; + } catch (error) { + log.error('inbox.automation_error_close_failed', { + projectId: item.project_id, + triggerId: subjectId, + ...serializeError(error), + }); + } + } + } catch (error) { + log.error('inbox.automation_error_close_scan_failed', serializeError(error)); + } + + const stats = { checked, filed, closed }; + if (filed > 0 || closed > 0) log.info('inbox.automation_error_sweep', stats); + return stats; +} diff --git a/apps/api/src/services/inbox/departed-member-tasks.ts b/apps/api/src/services/inbox/departed-member-tasks.ts new file mode 100644 index 0000000000..aaa2350d5a --- /dev/null +++ b/apps/api/src/services/inbox/departed-member-tasks.ts @@ -0,0 +1,107 @@ +/** + * When a member leaves a project, their open human tasks move to the team (inbox slice H1, design + * idea 01M6MFVAJF20DZK8NJ97VAXC7A "the assignee leaves the project"), and a team task they had + * taken is released for someone else to take. Each moved task gets a `reassigned` lifecycle row + * and a `sam.inbox` event from SAM, so the agent that assigned it is told. + * + * Called after the member's status is `removed` (`routes/projects/member-offboarding.ts`), next to + * `revokeSessionAccessForDepartedMember`. Best-effort: a failure is logged, the removal stands, and + * the departed member can no longer read or act on the task anyway (every task read joins an + * active membership). + */ +import { INBOX_SETTINGS } from '@simple-agent-manager/operations'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { createInboxTaskPort } from './task-port'; + +/** Unused for an open task (its watches never expire); required by the event input. */ +const CLOSED_WATCH_HOURS_DEFAULT = + INBOX_SETTINGS.find((setting) => setting.name === 'inbox.closedTaskWatchHours')?.defaultValue ?? + 168; + +export async function moveDepartedMemberTasksToTeam( + env: Env, + projectId: string, + userId: string +): Promise { + try { + const now = Date.now(); + // One statement per shape. Each repeats the membership predicate, so a member who was + // re-added in between keeps their tasks. + const stillGone = `NOT EXISTS (SELECT 1 FROM project_members pm + WHERE pm.project_id = asks.project_id AND pm.user_id = ? AND pm.status = 'active')`; + const assignedWhere = `project_id = ? AND kind = 'task' AND status = 'open' + AND assignee_kind = 'user' AND assignee_user_id = ? AND ${stillGone}`; + const claimedWhere = `project_id = ? AND kind = 'task' AND status = 'open' + AND assignee_kind = 'team' AND claimed_by_user_id = ? AND ${stillGone}`; + const detail = (fromKind: 'user' | 'team') => + JSON.stringify({ + reason: 'member_left', + fromKind, + fromUserId: userId, + toKind: 'team', + toUserId: null, + }); + // One transaction: the lifecycle rows are written from the same predicate, before the rows + // move, so a task never moves without its history (and a failure moves nothing). + const results = await env.DATABASE.batch([ + env.DATABASE.prepare( + `INSERT INTO ask_activity (id, ask_id, project_id, actor_kind, actor_id, kind, detail_json, + created_at) + SELECT lower(hex(randomblob(16))), id, project_id, 'system', NULL, 'reassigned', ?, ? + FROM asks WHERE ${assignedWhere}` + ).bind(detail('user'), now, projectId, userId, userId), + env.DATABASE.prepare( + `INSERT INTO ask_activity (id, ask_id, project_id, actor_kind, actor_id, kind, detail_json, + created_at) + SELECT lower(hex(randomblob(16))), id, project_id, 'system', NULL, 'reassigned', ?, ? + FROM asks WHERE ${claimedWhere}` + ).bind(detail('team'), now, projectId, userId, userId), + env.DATABASE.prepare( + `UPDATE asks SET assignee_kind = 'team', assignee_user_id = NULL, claimed_by_user_id = NULL, + updated_at = ? + WHERE ${assignedWhere} RETURNING id` + ).bind(now, projectId, userId, userId), + env.DATABASE.prepare( + `UPDATE asks SET claimed_by_user_id = NULL, updated_at = ? WHERE ${claimedWhere} RETURNING id` + ).bind(now, projectId, userId, userId), + ]); + const ids = (rows: unknown[] | undefined) => + (rows ?? []).flatMap((row) => + row && typeof row === 'object' && typeof (row as { id?: unknown }).id === 'string' + ? [(row as { id: string }).id] + : [] + ); + const moved = [...ids(results[2]?.results), ...ids(results[3]?.results)].map((id) => ({ id })); + if (moved.length === 0) return 0; + const port = createInboxTaskPort(env); + for (const task of moved) { + const queued = await port.admitEvent({ + projectId, + askId: task.id, + eventType: 'inbox.task.reassigned', + actor: { kind: 'system', id: null, name: 'SAM' }, + teammateInput: false, + detail: { reason: 'member_left', toKind: 'team' }, + taskOpen: true, + closedWatchHours: CLOSED_WATCH_HOURS_DEFAULT, + // Three round trips per task here (watch renewal, intent insert and read); the outbox + // reconcile sweep admits the intents, so a member with many tasks cannot exhaust the + // offboarding request's subrequest budget. + deferAdmission: true, + }); + if (!queued) + log.error('inbox.departed_member_task_event_lost', { projectId, askId: task.id, userId }); + } + log.info('inbox.departed_member_tasks_moved', { projectId, userId, tasks: moved.length }); + return moved.length; + } catch (error) { + log.error('inbox.departed_member_tasks_failed', { + projectId, + userId, + error: error instanceof Error ? error.message : String(error), + }); + return 0; + } +} diff --git a/apps/api/src/services/inbox/port.ts b/apps/api/src/services/inbox/port.ts index 295bb35f93..9ebdfcb677 100644 --- a/apps/api/src/services/inbox/port.ts +++ b/apps/api/src/services/inbox/port.ts @@ -2,11 +2,13 @@ * The worker side of the inbox (`OperationInboxPort`, `packages/operations/src/ports.ts`). Every * method delegates to the path its store already uses; nothing here answers a store a second way. */ -import type { OperationInboxPort } from '@simple-agent-manager/operations'; +import { OperationError, type OperationInboxPort } from '@simple-agent-manager/operations'; import { maybeJsonRecord } from '@simple-agent-manager/worker-core'; +import { and, eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import * as schema from '../../db/schema'; +import { retrySubtask } from '../../durable-objects/sam-session/tools/retry-subtask'; import type { Env } from '../../env'; import { errors } from '../../middleware/error'; import { @@ -22,6 +24,9 @@ import { declineRuntimeSecretRequest, fulfillRuntimeSecretRequest, } from '../runtime-secret-requests'; +import { ensureSessionRecovery } from '../session-recovery'; +import { clearTriggerPageCaches } from '../trigger-cache'; +import { triggerStatusUpdates } from '../trigger-status'; import { announceAgentAsk, checkAgentLinkTargets, withdrawAgentQuestion } from './agent-asks'; import { readAskContext } from './ask-context'; import { deliverInboxAskNotice } from './ask-notice'; @@ -150,6 +155,78 @@ export function createInboxPort(env: Env): OperationInboxPort { notifyAsk: (row, outcome) => deliverInboxAskNotice(env, row, outcome), + async retryTask(userId, projectId, taskId) { + // The existing retry: a new task with the same description, owner-only (`retrySubtask`). + const owned = await env.DATABASE.prepare( + 'SELECT 1 AS ok FROM tasks WHERE id = ? AND project_id = ?' + ) + .bind(taskId, projectId) + .first(); + if (!owned) throw new OperationError('not_found', 'Task not found'); + const result = (await retrySubtask( + { taskId }, + { + env: env as unknown as Record, + userId, + } + )) as { newTaskId?: unknown; error?: unknown }; + if (typeof result.newTaskId !== 'string') { + throw new OperationError( + 'conflict', + typeof result.error === 'string' ? result.error : 'The task could not be retried' + ); + } + return { newTaskId: result.newTaskId }; + }, + + async resumeTrigger(userId, projectId, triggerId) { + const database = db(); + if (!(await hasProjectCapability(database, projectId, userId, 'task:write'))) + throw new OperationError('forbidden', 'You cannot resume automations in this project'); + const trigger = await database + .select() + .from(schema.triggers) + .where(and(eq(schema.triggers.id, triggerId), eq(schema.triggers.projectId, projectId))) + .get(); + if (!trigger) throw new OperationError('not_found', 'Automation not found'); + if (trigger.status !== 'paused') + throw new OperationError('conflict', `This automation is ${trigger.status}, not paused`); + // The trigger PATCH route's status change, as a compare-and-set on `paused`. + const updated = await database + .update(schema.triggers) + .set({ ...triggerStatusUpdates(trigger, 'active'), updatedAt: new Date().toISOString() }) + .where( + and( + eq(schema.triggers.id, triggerId), + eq(schema.triggers.projectId, projectId), + eq(schema.triggers.status, 'paused') + ) + ) + .returning({ id: schema.triggers.id }); + if (updated.length !== 1) + throw new OperationError('conflict', 'The automation changed while it was being resumed'); + clearTriggerPageCaches(projectId); + }, + + async wakeChat(userId, projectId, sessionId) { + await authorizeAgentWake(env, { + projectId, + sessionId, + actorUserId: userId, + trigger: 'user_followup', + action: 'wake the agent in this session', + }); + const result = await ensureSessionRecovery(env, projectId, sessionId); + if (result.status !== 'waking') { + // The refusal reason is a fixed code (`recordSessionRecoveryRefusal`), not error text. + throw new OperationError( + 'conflict', + result.reason === 'container_runtime_wakes_in_place' + ? 'This chat wakes when you send it a message' + : `SAM could not wake this chat (${result.reason})` + ); + } + }, announceAsk: (input) => announceAgentAsk(env, input), withdrawQuestion: (input) => withdrawAgentQuestion(env, input), diff --git a/apps/api/src/services/inbox/system-error-resolve.ts b/apps/api/src/services/inbox/system-error-resolve.ts new file mode 100644 index 0000000000..bdcd3d25ad --- /dev/null +++ b/apps/api/src/services/inbox/system-error-resolve.ts @@ -0,0 +1,16 @@ +/** + * Close a recovered thing's system error inbox item (slice E). Kept apart from + * `system-errors.ts`, which builds operation ports: the retry tools and the wake signal call this + * from modules that the ports themselves import, and must not pull that graph back in. + */ +import { resolveSystemError } from '@simple-agent-manager/operations'; + +import type { Env } from '../../env'; + +/** Never throws. */ +export function resolveSystemErrorFor( + env: Env, + input: Parameters[1] +): Promise { + return resolveSystemError({ env }, input); +} diff --git a/apps/api/src/services/inbox/system-errors.ts b/apps/api/src/services/inbox/system-errors.ts new file mode 100644 index 0000000000..0ab33f08da --- /dev/null +++ b/apps/api/src/services/inbox/system-errors.ts @@ -0,0 +1,516 @@ +/** + * System error inbox items, worker side (inbox slice E). The filing core is + * `packages/operations/src/inbox-error-core.ts`; this module decides what counts as a failure of + * each thing, builds the item's sentences, and notifies the owner once per new item. + * + * Failed tasks are found by `runInboxSystemErrorSweep` (the five-minute operational cron): one scan over the + * recently failed tasks covers every writer of `tasks.status = 'failed'` (task runner, Instant + * launch, dispatch, VM-agent callback, stuck-task recovery, node loss, ProjectData). The VM-agent + * callback also files inline so its existing `error` notification can open the item. + * + * Normal lifecycle endings never file (policy a974b04f), using the classification the code + * already has: `transitionTaskToTerminal({lifecycleOutcome})` leaves `error_message` NULL (or the + * status `cancelled`), a person's own status change is recorded with actor `user`, and + * `classifyFailure()` marks parent stops, superseded wakes and human-input expiry + * `diagnosable: false`. + */ +import { + fileSystemError, + getInboxLimits, + quotedName, + type SystemErrorFiled, + type SystemErrorInput, +} from '@simple-agent-manager/operations'; +import { classifyFailure } from '@simple-agent-manager/shared'; + +import type { Env } from '../../env'; +import { log, serializeError } from '../../lib/logger'; +import { createOperationPorts } from '../../operation-ports'; +import * as notificationService from '../notification'; +import * as projectDataService from '../project-data'; + +export function systemErrorDeps(env: Env) { + return { env, ports: createOperationPorts(env) }; +} + +/** A failed task as the classifier reads it. */ +export interface FailedTaskRow { + id: string; + project_id: string; + user_id: string; + title: string | null; + error_message: string | null; + started_at: string | null; + chat_session_id: string | null; + parent_task_id: string | null; + project_owner_id: string | null; + /** Actor of the newest status event into `failed` (`user` when the person set it). */ + failed_by: string | null; +} + +const FAILED_TASK_COLUMNS = `t.id, t.project_id, t.user_id, t.title, t.error_message, t.started_at, + t.chat_session_id, t.parent_task_id, p.user_id AS project_owner_id, + (SELECT e.actor_type FROM task_status_events e + WHERE e.task_id = t.id AND e.to_status = 'failed' + ORDER BY e.created_at DESC LIMIT 1) AS failed_by`; + +export type TaskFailureVerdict = + | { file: true; started: boolean; explanation: string; retryable: boolean } + | { file: false; reason: 'no_error' | 'set_by_person' | 'normal_ending' }; + +/** Whether a failed task is a genuine failure the owner should hear about. */ +export function classifyTaskFailure(row: FailedTaskRow): TaskFailureVerdict { + const message = row.error_message?.trim(); + // `transitionTaskToTerminal({lifecycleOutcome})` writes no error for a normal ending. + if (!message) return { file: false, reason: 'no_error' }; + // The person set it themselves (`PATCH /tasks/:id/status`): nothing to tell them. + if (row.failed_by === 'user') return { file: false, reason: 'set_by_person' }; + const classification = classifyFailure(message); + // Parent or user stop, superseded wake, expected human-input expiry. + if (!classification.diagnosable) return { file: false, reason: 'normal_ending' }; + return { + file: true, + started: Boolean(row.started_at), + explanation: classification.explanation, + retryable: classification.retryable, + }; +} + +/** The item for a failed task. Title and body never quote the error text. */ +export function taskFailureError( + row: FailedTaskRow, + verdict: Extract +): SystemErrorInput { + const name = quotedName(row.title, 'A task'); + // `retrySubtask` is the project owner's operation; offer it only to someone who can run it. + const canRetry = verdict.retryable && row.project_owner_id === row.user_id; + return { + projectId: row.project_id, + assigneeUserId: row.user_id, + source: 'task', + subjectId: row.id, + title: verdict.started ? `${name} stopped before it finished` : `${name} couldn't start`, + body: verdict.explanation, + actions: [ + ...(canRetry ? (['retry'] as const) : []), + ...(row.chat_session_id ? (['open_chat'] as const) : []), + ], + sourceTaskId: row.id, + sourceSessionId: row.chat_session_id, + links: [ + { kind: 'task', id: row.id, label: null }, + ...(row.chat_session_id ? [{ kind: 'chat', id: row.chat_session_id, label: null }] : []), + ], + // Failed children of one parent stack together. + groupKey: row.parent_task_id ? `task:${row.parent_task_id}` : null, + // A task fails once per run; a re-report (callback and sweep both filing) is not a second. + failureCount: 1, + }; +} + +async function notifyFiled( + env: Env, + input: SystemErrorInput, + filed: SystemErrorFiled, + type: 'error' | 'cron_failure' +): Promise { + if (!filed.created || !env.NOTIFICATION) return; + try { + await notificationService.notifySystemError(env, input.assigneeUserId, { + type, + projectId: input.projectId, + projectName: await notificationService.getProjectName(env, input.projectId), + ref: filed.ref, + title: input.title, + body: input.body, + taskId: input.sourceTaskId ?? null, + sessionId: input.sourceSessionId ?? null, + }); + } catch (error) { + log.warn('inbox.system_error_notify_failed', { + projectId: input.projectId, + ref: filed.ref, + ...serializeError(error), + }); + } +} + +/** File (or update) and notify. Never throws. */ +export async function fileAndNotify( + env: Env, + input: SystemErrorInput, + type: 'error' | 'cron_failure' = 'error' +): Promise { + let filed: SystemErrorFiled | null; + try { + // Building the ports is inside the guard too: filing must never throw into its caller. + filed = await fileSystemError(systemErrorDeps(env), input); + } catch (error) { + log.error('inbox.system_error_file_failed', { + projectId: input.projectId, + source: input.source, + ...serializeError(error), + }); + return null; + } + if (filed) await notifyFiled(env, input, filed, type); + return filed; +} + +/** + * File the item for one failed task, when it is a genuine failure. Used inline by the VM-agent + * task callback, which sends its own notification linking the returned ref. Never throws. + */ +export async function fileTaskFailure( + env: Env, + projectId: string, + taskId: string +): Promise { + try { + const row = await env.DATABASE.prepare( + `SELECT ${FAILED_TASK_COLUMNS} FROM tasks t JOIN projects p ON p.id = t.project_id + WHERE t.id = ? AND t.project_id = ? AND t.status = 'failed'` + ) + .bind(taskId, projectId) + .first(); + if (!row) return null; + const verdict = classifyTaskFailure(row); + if (!verdict.file) return null; + return await fileSystemError(systemErrorDeps(env), taskFailureError(row, verdict)); + } catch (error) { + log.error('inbox.task_failure_file_failed', { projectId, taskId, ...serializeError(error) }); + return null; + } +} + +export interface InboxSystemErrorSweepStats { + scanned: number; + filed: number; + skippedNormal: number; + closed: number; +} + +/** + * Pages of the failed-task window one sweep tick may read, each `4 × inbox.errorSweepBatchSize` + * rows. Rows the classifier skips (a parent stop, an expected expiry) stay in the window until they + * age out of it; paging past them keeps them from holding every slot (rule 47, rule 81). + */ +const TASK_SWEEP_MAX_PAGES = 5; + +/** + * One cron step: file items for genuinely failed tasks of the lookback window that have none, + * then close task items whose task is no longer failed (retried in place, or reset by a person). + * + * Budget (rule 47): indexed pages of failed tasks updated inside `inbox.errorLookbackMinutes` + * (`idx_tasks_failed_updated`), newest first, `4 × inbox.errorSweepBatchSize` rows each, at most + * `TASK_SWEEP_MAX_PAGES` pages; it stops early once `inbox.errorSweepBatchSize` items are filed + * (about five D1 round trips each) or the window is exhausted; then one UPDATE for the closes, + * driven from the tasks changed inside the window (`tasks(updated_at, id)`, then the unique + * dedupe-key index). A candidate leaves the set once it has an item (the NOT EXISTS, + * `idx_asks_error_task`) or once it ages out of the window. A failure a person set themselves is + * excluded in SQL; the other normal endings (classified in code) are paged past. Throughput at the + * defaults (batch 10, lookback 30 min, a tick every 5 min): 200 rows read and 10 items filed per tick, so normal + * endings starve genuine failures only past 200 of them in 30 minutes, installation-wide, and a + * filing backlog drains at 120 items an hour. A failure is filed within one tick (at most 5 min) of + * being written, or at once by the VM-agent callback. + */ +export async function runInboxSystemErrorSweep( + env: Env, + now = Date.now() +): Promise { + const deps = systemErrorDeps(env); + const limits = await getInboxLimits(deps); + const since = new Date(now - limits.errorLookbackMinutes * 60_000).toISOString(); + const pageSize = limits.errorSweepBatchSize * 4; + let cursor: { updatedAt: string; id: string } | null = null; + let scanned = 0; + let filed = 0; + let skippedNormal = 0; + // Each half of this step is isolated (rule 53): a failed scan still lets the closes and the + // undelivered-answer filing run. + try { + for (let page = 0; page < TASK_SWEEP_MAX_PAGES && filed < limits.errorSweepBatchSize; page++) { + const candidates: { results?: Array } = + await env.DATABASE.prepare( + `SELECT ${FAILED_TASK_COLUMNS}, t.updated_at + FROM tasks t JOIN projects p ON p.id = t.project_id + WHERE t.status = 'failed' AND t.updated_at > ? + ${cursor ? 'AND (t.updated_at, t.id) < (?, ?)' : ''} + -- Normal endings with no error (\`lifecycleOutcome\`) never fill the batch. + AND t.error_message IS NOT NULL AND TRIM(t.error_message) != '' + -- Nor one a person set themselves (\`classifyTaskFailure\` 'set_by_person'). + AND COALESCE((SELECT e.actor_type FROM task_status_events e + WHERE e.task_id = t.id AND e.to_status = 'failed' + ORDER BY e.created_at DESC LIMIT 1), '') != 'user' + -- Not while its item is open or archived (key held): a later write to the failed + -- task (an edit) is not another failure. + AND NOT EXISTS (SELECT 1 FROM asks k + WHERE k.project_id = t.project_id AND k.dedupe_key = 'error:task:' || t.id) + -- Nor when an item was filed since the task last changed and has closed already + -- (a retried task stays failed; its closed item must not be filed again). + -- Only this task's own item (its first link is the task): a wake or sleep item of + -- the task's chat carries the same source task. + AND NOT EXISTS (SELECT 1 FROM asks a + WHERE a.kind = 'error' AND a.source_task_id = t.id AND a.project_id = t.project_id + AND a.links_json LIKE '[{"kind":"task","id":"' || t.id || '"%' + AND a.created_at >= CAST((julianday(t.updated_at) - 2440587.5) * 86400000 AS INTEGER)) + ORDER BY t.updated_at DESC, t.id DESC LIMIT ?` + ) + .bind(since, ...(cursor ? [cursor.updatedAt, cursor.id] : []), pageSize) + .all(); + const rows = candidates.results ?? []; + scanned += rows.length; + for (const row of rows) { + if (filed >= limits.errorSweepBatchSize) break; + const verdict = classifyTaskFailure(row); + if (!verdict.file) { + skippedNormal += 1; + continue; + } + const result = await fileAndNotify(env, taskFailureError(row, verdict)); + if (result) filed += 1; + } + const last = rows.at(-1); + if (rows.length < pageSize || !last) break; + cursor = { updatedAt: last.updated_at, id: last.id }; + } + } catch (error) { + log.error('inbox.system_error_scan_failed', serializeError(error)); + } + + // A task that left `failed` (retried in place, reset, or recovered) closes its item. Driven + // from the tasks that changed inside the lookback window (`tasks(updated_at, id)`), not from + // every held key, so the cost follows how often tasks change rather than how many items are + // still open (rule 47). A task that recovers while this sweep is down for longer than the + // window keeps its item open; Retry on it is then refused and the person archives it. + let closed = 0; + try { + const result = await env.DATABASE.prepare( + `UPDATE asks + SET status = CASE WHEN status = 'open' THEN 'done' ELSE status END, + answer_json = CASE WHEN status = 'open' THEN '{"resolution":"recovered"}' ELSE answer_json END, + resolved_at = CASE WHEN status = 'open' THEN ? ELSE resolved_at END, + notified_at = COALESCE(notified_at, ?), dedupe_key = NULL, updated_at = ? + WHERE kind = 'error' AND status IN ('open', 'archived') + AND (project_id, dedupe_key) IN ( + SELECT t.project_id, 'error:task:' || t.id FROM tasks t + WHERE t.updated_at > ? AND t.status != 'failed')` + ) + .bind(now, now, now, since) + .run(); + closed = result.meta?.changes ?? 0; + } catch (error) { + log.error('inbox.system_error_close_failed', serializeError(error)); + } + + let undelivered = 0; + try { + undelivered = await fileUndeliveredAskAnswers(env, limits, now); + } catch (error) { + log.error('inbox.undelivered_answer_sweep_failed', serializeError(error)); + } + + const stats = { scanned, filed: filed + undelivered, skippedNormal, closed }; + if (stats.filed > 0 || stats.closed > 0) log.info('inbox.system_error_sweep', stats); + return stats; +} + +/** + * A person answered, marked done or archived an ask from a chat, and the agent's notice was never + * queued within `inbox.noticeRetryMinutes`: the inbox sweep (`sweep.ts`) has given up on it. + * File one `delivery` error item per such ask for that person, linking the ask. Bounded: asks + * that gave up inside the lookback window, at most `inbox.errorSweepBatchSize` per tick; an ask + * leaves the set once an item links it (read on the project's asks, `idx_asks_project_status`, + * only for the few candidates) or it ages out of the window. + */ +async function fileUndeliveredAskAnswers( + env: Env, + limits: Awaited>, + now: number +): Promise { + const gaveUpBefore = now - limits.noticeRetryMinutes * 60_000; + const result = await env.DATABASE.prepare( + `SELECT a.id, a.project_id, a.source_session_id, a.resolved_by_user_id + FROM asks a + -- The status list is \`idx_asks_unnotified\`'s, term for term, so the index applies. + WHERE a.notified_at IS NULL AND a.status IN ('answered', 'done', 'archived', 'expired') + AND a.status != 'expired' + AND a.kind != 'error' AND a.source_session_id IS NOT NULL + AND a.resolved_by_user_id IS NOT NULL + AND a.resolved_at > ? AND a.resolved_at <= ? + -- Not while the chat's delivery item (open or archived) was written after it was + -- answered: one chat has one delivery item and a repeat filing rewrites its links, so a + -- link alone would let two given-up asks swap the item every tick. A unique-index seek. + AND NOT EXISTS (SELECT 1 FROM asks d + WHERE d.project_id = a.project_id + AND d.dedupe_key = 'error:delivery:' || a.source_session_id + AND d.updated_at >= a.resolved_at) + -- Nor once an item (since closed) linked it. + AND NOT EXISTS (SELECT 1 FROM asks e + WHERE e.kind = 'error' AND e.project_id = a.project_id + AND e.links_json LIKE '%"kind":"ask","id":"' || a.id || '"%') + ORDER BY a.resolved_at LIMIT ?` + ) + .bind( + gaveUpBefore - limits.errorLookbackMinutes * 60_000, + gaveUpBefore, + limits.errorSweepBatchSize + ) + .all<{ + id: string; + project_id: string; + source_session_id: string; + resolved_by_user_id: string; + }>(); + let filed = 0; + for (const row of result.results ?? []) { + let chat: Awaited>; + try { + chat = await loadChatForError(env, row.project_id, row.source_session_id); + } catch { + continue; // Unreadable now; the next tick tries again inside the window. + } + // An archived chat (or one that no longer exists) is a normal ending: nothing to tell. + if (!chat) continue; + const filedItem = await fileAndNotify(env, { + projectId: row.project_id, + assigneeUserId: row.resolved_by_user_id, + source: 'delivery', + subjectId: row.source_session_id, + title: `Your answer didn't reach the agent in ${quotedName(chat.topic, 'a chat')}`, + body: 'SAM kept trying but could not hand your answer to the agent; open the chat and tell it again if it still needs it.', + actions: ['open_chat'], + sourceTaskId: chat.taskId, + sourceSessionId: row.source_session_id, + links: [ + { kind: 'chat', id: row.source_session_id, label: null }, + { kind: 'ask', id: row.id, label: null }, + ], + }); + if (filedItem) filed += 1; + } + return filed; +} + +/** + * A chat as an error item names it: its task, topic and creator. Reads the D1 chat index first + * and falls back to the ProjectData session when the index has not synced the chat yet. + */ +export async function loadChatForError( + env: Env, + projectId: string, + sessionId: string +): Promise<{ taskId: string | null; topic: string | null; createdBy: string | null } | null> { + const row = await env.DATABASE.prepare( + `SELECT ss.task_id, ss.topic, ss.created_by_user_id, ss.status, + (SELECT t.id FROM tasks t WHERE t.project_id = ss.project_id AND t.chat_session_id = ss.id) + AS bound_task_id + FROM session_summaries ss WHERE ss.id = ? AND ss.project_id = ?` + ) + .bind(sessionId, projectId) + .first<{ + task_id: string | null; + topic: string | null; + created_by_user_id: string | null; + status: string | null; + bound_task_id: string | null; + }>(); + // An archived chat is a normal ending: it files nothing (policy a974b04f). + if (row?.status === 'archived') return null; + if (row) { + return { + // `createAsk` requires the chat to be the task's own; prefer the task bound to it now. + taskId: row.bound_task_id ?? row.task_id, + topic: row.topic, + createdBy: row.created_by_user_id, + }; + } + const session = await projectDataService.getSession(env, projectId, sessionId); + if (!session || session.status === 'archived') return null; + const text = (value: unknown) => (typeof value === 'string' && value ? value : null); + const bound = await env.DATABASE.prepare( + 'SELECT id FROM tasks WHERE project_id = ? AND chat_session_id = ?' + ) + .bind(projectId, sessionId) + .first<{ id: string }>(); + return { + taskId: bound?.id ?? text(session.taskId), + topic: text(session.topic), + createdBy: text(session.createdByUserId), + }; +} + +/** + * A fallback sleep released the workspace without a fresh snapshot + * (`session-sleep-fallback.ts:runSessionSleepFallback`): work since the last complete snapshot, + * or everything unsaved when there is none, may be lost. Never throws. + */ +export async function fileSleepLossError( + env: Env, + input: { projectId: string; sessionId: string; userId: string; exactRestore: boolean } +): Promise { + try { + const chat = await loadChatForError(env, input.projectId, input.sessionId); + if (!chat) return null; + const name = quotedName(chat.topic, 'A chat'); + return await fileAndNotify(env, { + projectId: input.projectId, + assigneeUserId: chat.createdBy ?? input.userId, + source: 'sleep', + subjectId: input.sessionId, + title: `${name} went to sleep without saving its latest work`, + body: input.exactRestore + ? 'SAM could not save a fresh snapshot, so it slept the chat from its last complete one; changes made after that snapshot may be lost.' + : 'SAM could not save a snapshot before it shut the workspace down, so unsaved files and uncommitted work may be lost.', + actions: ['open_chat'], + sourceTaskId: chat.taskId, + sourceSessionId: input.sessionId, + links: [{ kind: 'chat', id: input.sessionId, label: null }], + }); + } catch (error) { + log.error('inbox.sleep_loss_file_failed', { + projectId: input.projectId, + sessionId: input.sessionId, + ...serializeError(error), + }); + return null; + } +} + +/** + * The person's answer to a permission, form or link request was never confirmed delivered to the + * agent after the InteractionStore's retry window (`interaction-store.ts:recordDelivery`, + * `delivery_unconfirmed`). One item per chat. Returns `skipped` for a chat that files nothing (an + * archived chat, no recorded creator) and `failed` when the item could not be written, so the + * caller's outbox job can retry instead of losing it. Never throws. + */ +export async function fileUndeliveredAnswerError( + env: Env, + input: { projectId: string; sessionId: string } +): Promise<'filed' | 'skipped' | 'failed'> { + try { + const chat = await loadChatForError(env, input.projectId, input.sessionId); + if (!chat?.createdBy) return 'skipped'; + const name = quotedName(chat.topic, 'a chat'); + const filed = await fileAndNotify(env, { + projectId: input.projectId, + assigneeUserId: chat.createdBy, + source: 'delivery', + subjectId: input.sessionId, + title: `Your answer didn't reach the agent in ${name}`, + body: 'SAM kept trying but the agent never confirmed it received your answer; open the chat and answer again if it is still waiting.', + actions: ['open_chat'], + sourceTaskId: chat.taskId, + sourceSessionId: input.sessionId, + links: [{ kind: 'chat', id: input.sessionId, label: null }], + }); + return filed ? 'filed' : 'failed'; + } catch (error) { + log.error('inbox.undelivered_answer_file_failed', { + projectId: input.projectId, + sessionId: input.sessionId, + ...serializeError(error), + }); + return 'failed'; + } +} diff --git a/apps/api/src/services/inbox/task-port.ts b/apps/api/src/services/inbox/task-port.ts new file mode 100644 index 0000000000..83fd8b56d7 --- /dev/null +++ b/apps/api/src/services/inbox/task-port.ts @@ -0,0 +1,338 @@ +/** + * The worker side of human tasks (`OperationInboxTaskPort`, inbox slice H1): `sam.inbox` events + * through the durable source outbox, task subscriptions in the project's Durable Object, the + * comment core (anchor kind `inbox_item`), the agent-wake policy, and notifications. No task rule + * lives here; `packages/operations/src/inbox-task-core.ts` decides and calls these. + */ +import type { OperationInboxTaskPort } from '@simple-agent-manager/operations'; +import { + type AdmitProjectEventInput, + INBOX_EVENT_SOURCE, + INBOX_EVENT_SUBJECT_TYPE, + INBOX_TASK_DEFAULT_WAKE_EVENT_TYPES, + INBOX_TASK_STEP_EVENT_TYPES, + NOTIFICATION_TYPE_URGENCY, + PROJECT_EVENT_FILTER_VERSION, +} from '@simple-agent-manager/shared'; +import { ulid } from '@simple-agent-manager/worker-core'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { decideInboxTaskCommentWake } from '../agent-wake-authorization'; +import { getProjectName, sendNotification, sendNotificationOnce } from '../notification'; +import * as projectDataService from '../project-data'; +import { + admitProjectEventSourceIntentById, + enqueueProjectEventSourceIntent, +} from '../project-event-source-outbox'; +import { resolveDeliveryPreference } from '../project-event-subscriptions-access'; + +const PREVIEW_MAX = 140; + +async function sha256Hex(value: string): Promise { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); + return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); +} + +async function displayName(env: Env, userId: string | null): Promise { + if (!userId) return null; + const row = await env.DATABASE.prepare('SELECT name, email FROM users WHERE id = ?') + .bind(userId) + .first<{ name: string | null; email: string | null }>(); + return row?.name?.trim() || row?.email?.split('@')[0] || null; +} + +function inboxItemUrl(projectId: string, askId: string): string { + return `/projects/${encodeURIComponent(projectId)}/inbox?item=${encodeURIComponent(`ask:${askId}`)}`; +} + +function preview(body: string): string { + const flat = body.replace(/\s+/g, ' ').trim(); + return flat.length > PREVIEW_MAX ? `${flat.slice(0, PREVIEW_MAX - 1)}…` : flat; +} + +/** Whether every reader of a person's task (not a team task) includes this user. */ +function mayRead(readers: 'project' | string[], userId: string): boolean { + return readers === 'project' || readers.includes(userId); +} + +export function createInboxTaskPort(env: Env): OperationInboxTaskPort { + return { + async admitEvent(input) { + try { + const actorName = + input.actor.name ?? + (input.actor.kind === 'user' ? await displayName(env, input.actor.id) : null); + const occurredAt = Date.now(); + const eventId = ulid(); + const metadata = { + actor: { kind: input.actor.kind, id: input.actor.id, name: actorName }, + teammateInput: input.teammateInput, + askId: input.askId, + ...(input.detail ? { detail: input.detail } : {}), + }; + const event: AdmitProjectEventInput = { + projectId: input.projectId, + source: INBOX_EVENT_SOURCE, + eventType: input.eventType, + subject: { type: INBOX_EVENT_SUBJECT_TYPE, id: input.askId }, + severity: 'info', + // One event per change: the id is minted here, so a retry of the outbox replays it. + deliveryKey: `inbox:${input.askId}:${eventId}`, + payloadFingerprint: await sha256Hex(JSON.stringify([input.eventType, metadata])), + metadata, + occurredAt, + receivedAt: occurredAt, + }; + // Renew the item's watches first, so a task open for days still wakes them (and a closed + // one winds them down). A failure is logged: the event is still worth recording. + await projectDataService + .renewInboxItemWatches(env, input.projectId, { + itemId: input.askId, + open: input.taskOpen, + closedGraceMs: input.closedWatchHours * 60 * 60 * 1000, + }) + .catch((error: unknown) => + log.warn('inbox.task_watch_renew_failed', { + projectId: input.projectId, + askId: input.askId, + error: error instanceof Error ? error.message : String(error), + }) + ); + // The committed intent is the durable part; admission runs after the response when the + // request can wait for it, and the outbox reconcile sweep retries it otherwise. + const intent = await enqueueProjectEventSourceIntent(env, event); + if (input.deferAdmission) return true; + const admit = admitProjectEventSourceIntentById(env, intent.id).catch((error: unknown) => + log.warn('inbox.task_event_admit_deferred', { + projectId: input.projectId, + askId: input.askId, + intentId: intent.id, + error: error instanceof Error ? error.message : String(error), + }) + ); + if (input.waitUntil) input.waitUntil(admit); + else await admit; + return true; + } catch (error) { + log.error('inbox.task_event_admission_failed', { + projectId: input.projectId, + askId: input.askId, + eventType: input.eventType, + error: error instanceof Error ? error.message : String(error), + }); + return false; + } + }, + + async watch(input) { + const session = await projectDataService.getSession(env, input.projectId, input.sessionId); + if (!session || session.taskId !== input.taskId) { + throw new Error('The watching chat is not this task’s chat'); + } + const task = await env.DATABASE.prepare( + 'SELECT recovery_source_task_id FROM tasks WHERE id = ? AND project_id = ?' + ) + .bind(input.taskId, input.projectId) + .first<{ recovery_source_task_id: string | null }>(); + const eventTypes = [ + ...INBOX_TASK_DEFAULT_WAKE_EVENT_TYPES.filter( + (type) => input.includeComments || type !== 'inbox.task.commented' + ), + ...(input.includeSteps ? INBOX_TASK_STEP_EVENT_TYPES : []), + ]; + const result = await projectDataService.createProjectEventSubscription(env, input.projectId, { + // The same owner identity the chat's own subscriptions use, so the agent can list and + // cancel this one with the event tools. + owner: { type: 'agent', id: `${input.projectId}:${input.sessionId}`, name: null }, + idempotencyKey: `inbox-watch:${input.askId}`, + filter: { + version: PROJECT_EVENT_FILTER_VERSION, + source: INBOX_EVENT_SOURCE, + subjectType: INBOX_EVENT_SUBJECT_TYPE, + subjectId: input.askId, + eventType: eventTypes, + }, + deliveryPreference: resolveDeliveryPreference('existing_session_prompt', { + sessionId: input.sessionId, + taskId: input.taskId, + runtimeId: null, + agentId: input.agentSessionId, + }), + ownerTaskId: task?.recovery_source_task_id ?? input.taskId, + reason: 'Watching a human task in the inbox', + // A task never expires, so neither does the watch. When the chat's work is finished + // the source-task guard stops waking it and the events stay recorded. + expiresAt: null, + }); + return { subscriptionId: result.subscription.id, created: !result.idempotent }; + }, + + async closeWatches(projectId, askId, closedWatchHours) { + await projectDataService + .renewInboxItemWatches(env, projectId, { + itemId: askId, + open: false, + closedGraceMs: closedWatchHours * 60 * 60 * 1000, + }) + .catch((error: unknown) => + log.warn('inbox.task_watch_close_failed', { + projectId, + askId, + error: error instanceof Error ? error.message : String(error), + }) + ); + }, + + countWatchers: (projectId, askId) => + projectDataService.countInboxItemWatchers(env, projectId, askId), + + decideCommentWake: (input) => decideInboxTaskCommentWake(env, input), + + listComments: (projectId, askId) => + projectDataService.listInboxItemCommentThreads(env, projectId, { itemId: askId }), + + async createComment(projectId, input) { + const actorName = + input.actor.name ?? + (input.actor.kind === 'human' ? await displayName(env, input.actor.id) : 'Agent'); + const result = await projectDataService.createInboxItemComment(env, projectId, { + itemId: input.askId, + threadId: input.threadId ?? null, + body: input.body, + clientMutationId: input.clientMutationId ?? null, + actor: { kind: input.actor.kind, id: input.actor.id, name: actorName }, + mentions: input.mentions, + }); + return { thread: result.thread, commentId: result.commentId, idempotent: result.idempotent }; + }, + + async resolveMentions(projectId, userIds) { + const ids = [...new Set(userIds.map((id) => id.trim()).filter(Boolean))].slice(0, 20); + if (ids.length === 0) return []; + const rows = await env.DATABASE.prepare( + `SELECT pm.user_id AS user_id, u.name AS name, u.email AS email + FROM project_members pm JOIN users u ON u.id = pm.user_id + WHERE pm.project_id = ? AND pm.status = 'active' + AND pm.user_id IN (${ids.map(() => '?').join(', ')})` + ) + .bind(projectId, ...ids) + .all<{ user_id: string; name: string | null; email: string | null }>(); + const byId = new Map((rows.results ?? []).map((row) => [row.user_id, row])); + return ids.flatMap((userId) => { + const row = byId.get(userId); + return row + ? [{ userId, displayName: row.name?.trim() || row.email?.split('@')[0] || null }] + : []; + }); + }, + + async notifyComment(input) { + if (!env.NOTIFICATION) return; + try { + const [projectName, actorName] = await Promise.all([ + getProjectName(env, input.projectId), + input.actor.name + ? Promise.resolve(input.actor.name) + : displayName(env, input.actor.userId), + ]); + const who = actorName ?? 'A teammate'; + const recipients = new Map(); + for (const mention of input.mentions) recipients.set(mention.userId, 'mention'); + for (const userId of input.participants) { + if (!recipients.has(userId)) recipients.set(userId, 'comment'); + } + recipients.delete(input.actor.userId); + // Only active members hear about it: a participant who left the project gets nothing. + // At most 90 recipients per comment (D1 binds); a mention list is capped at 20 anyway. + const candidates = [...recipients.keys()].slice(0, 90); + if (candidates.length === 0) return; + const active = await env.DATABASE.prepare( + `SELECT user_id FROM project_members WHERE project_id = ? AND status = 'active' + AND user_id IN (${candidates.map(() => '?').join(', ')})` + ) + .bind(input.projectId, ...candidates) + .all<{ user_id: string }>(); + const members = new Set((active.results ?? []).map((row) => row.user_id)); + for (const userId of [...recipients.keys()]) + if (!members.has(userId)) recipients.delete(userId); + const now = Date.now(); + await Promise.all( + [...recipients].map(async ([userId, reason]) => { + // Nobody hears about a task they cannot open (a mention included). + if (!mayRead(input.readers, userId)) return; + const notification = { + projectId: input.projectId, + type: reason, + urgency: NOTIFICATION_TYPE_URGENCY[reason], + title: + reason === 'mention' + ? `${who} mentioned you on the task “${preview(input.title)}”` + : `${who} commented on the task “${preview(input.title)}”`, + body: preview(input.body), + actionUrl: inboxItemUrl(input.projectId, input.askId), + metadata: { + projectName, + reason, + inboxItemRef: `ask:${input.askId}`, + threadId: input.threadId, + commentId: input.commentId, + actorUserId: input.actor.userId, + }, + }; + try { + await sendNotificationOnce( + env, + userId, + `inbox-task-comment:${input.commentId}`, + now + 24 * 60 * 60 * 1000, + notification, + now + ); + } catch (error) { + log.warn('inbox.task_comment_notification_failed', { + projectId: input.projectId, + askId: input.askId, + recipientUserId: userId, + error: error instanceof Error ? error.message : String(error), + }); + } + }) + ); + } catch (error) { + log.warn('inbox.task_comment_notify_failed', { + projectId: input.projectId, + askId: input.askId, + error: error instanceof Error ? error.message : String(error), + }); + } + }, + + async notifyAssigned(input) { + if (!env.NOTIFICATION || input.userIds.length === 0) return; + try { + const projectName = await getProjectName(env, input.projectId); + await Promise.all( + input.userIds.map((userId) => + sendNotification(env, userId, { + projectId: input.projectId, + // Low urgency and in-app only: a task is a to-do, not an interruption. + type: 'progress', + urgency: 'low', + title: `New task for you: ${preview(input.title)}`, + body: 'An agent handed you a task. It does not block the agent.', + actionUrl: inboxItemUrl(input.projectId, input.askId), + metadata: { projectName, inboxItemRef: `ask:${input.askId}` }, + }) + ) + ); + } catch (error) { + log.warn('inbox.task_assigned_notification_failed', { + projectId: input.projectId, + askId: input.askId, + error: error instanceof Error ? error.message : String(error), + }); + } + }, + }; +} diff --git a/apps/api/src/services/infomaniak-provider-settings.ts b/apps/api/src/services/infomaniak-provider-settings.ts new file mode 100644 index 0000000000..8e26d60288 --- /dev/null +++ b/apps/api/src/services/infomaniak-provider-settings.ts @@ -0,0 +1,38 @@ +import type { ProviderConfig } from '@simple-agent-manager/providers'; +import { + type CredentialProvider, + DEFAULT_INFOMANIAK_BOOT_VOLUME_GB, +} from '@simple-agent-manager/shared'; + +import type { Env } from '../env'; +import { buildProviderConfig } from './provider-credential-codecs'; + +/** + * The Infomaniak boot volume size admins set (`infomaniak.bootVolumeGb`). The read shares the + * per-isolate admin settings cache, so it costs no D1 round trip when the cache is warm. During a + * settings outage `resolveAdminSetting` returns the registered default, so provider resolution + * never fails on this setting. + * + * The settings module is loaded on first use, as `gcp-provider-factory.ts` does: a static import + * would pull the settings registry into every module that resolves a provider. + */ +export async function resolveInfomaniakBootVolumeGb(env: Env): Promise { + const { resolveAdminSetting } = await import('./admin-settings-resolution'); + const value = await resolveAdminSetting(env, 'infomaniak.bootVolumeGb'); + return typeof value === 'number' ? value : DEFAULT_INFOMANIAK_BOOT_VOLUME_GB; +} + +/** + * `buildProviderConfig` plus the runtime settings that size what the provider creates. Every + * non-GCP provider the API builds for provisioning or for the catalog goes through here, so the + * disk a pool candidate advertises is the disk the VM gets. Only Infomaniak reads a setting today. + */ +export async function buildProviderConfigForEnv( + provider: Exclude, + decryptedToken: string, + env: Env +): Promise { + const infomaniakBootVolumeGb = + provider === 'infomaniak' ? await resolveInfomaniakBootVolumeGb(env) : undefined; + return buildProviderConfig(provider, decryptedToken, env, { infomaniakBootVolumeGb }); +} diff --git a/apps/api/src/services/instant-restore-workspace.ts b/apps/api/src/services/instant-restore-workspace.ts index 4b0aba571c..990a930c83 100644 --- a/apps/api/src/services/instant-restore-workspace.ts +++ b/apps/api/src/services/instant-restore-workspace.ts @@ -47,6 +47,7 @@ export async function loadInstantRestoreWorkspace( const source = await resolveWorkspaceGitSource(db, { id: input.projectId, repoProvider: row.repoProvider, + repository: row.repository, }); return { workspaceId: input.workspaceId, diff --git a/apps/api/src/services/lifecycle-latency/range-report.ts b/apps/api/src/services/lifecycle-latency/range-report.ts new file mode 100644 index 0000000000..9df0531e6a --- /dev/null +++ b/apps/api/src/services/lifecycle-latency/range-report.ts @@ -0,0 +1,220 @@ +/** + * Lifecycle latency over a time range, for Admin Health & cost (Insights slice H). The daily + * check (`daily-evaluation.ts`) answers "did a state regress in the last day"; this answers + * "how slow was each state over the range the admin picked, and is anything open about it". + * + * It reuses the daily check's statistics (`latencyStats`) and its over-budget verdict + * (`classifyRegression`, with no baseline so only `over_budget` can fire), and the watchdog's + * budgets and messages. Incidents are found by the triage signature the hourly platform-feedback + * triage gives the watchdog's and the daily check's errors (`platformErrorSignature`). + * + * Round trips: settings (cached per isolate), one windowed episode read for every watched state + * at once (the daily check reads one per state), one read of rows stuck past budget now, and one + * incident read. Durations are lower bounds accurate to about one five-minute sample at each end. + */ +import type { + InstallationLatencyIncident, + InstallationLatencyIncidentState, + InstallationLifecycleLatency, +} from '@simple-agent-manager/shared'; + +import type { Env } from '../../env'; +import { log } from '../../lib/logger'; +import { platformErrorSignature } from '../platform-feedback-triage'; +import { classifyRegression, latencyStats, regressionMessage } from './daily-evaluation'; +import { slowStateMessage } from './watchdog'; +import { + budgetMs, + LIFECYCLE_WATCHES, + type LifecycleLatencySettings, + type LifecycleWatch, + resolveLifecycleLatencySettings, +} from './watches'; + +/** Open incident queue states (`ACTIVE_INCIDENT_STATES`, platform-feedback-incidents). */ +const OPEN_INCIDENT_STATES: readonly InstallationLatencyIncidentState[] = [ + 'pending', + 'dispatched', + 'claimed', +]; + +interface EpisodeRow { + entity_type: string; + status: string; + duration_ms: number | null; +} + +interface IncidentRow { + signature: string; + canonical_signature: string | null; + queue_state: string; + first_seen_at: number; + last_seen_at: number; + occurrence_count: number; + idea_id: string | null; + idea_project_id: string | null; +} + +const stateKey = (entityType: string, status: string) => `${entityType}.${status}`; + +/** + * The triage signatures of a watch's two error messages. The messages are fixed per watch, so the + * digests are computed once per isolate rather than 22 times per request. + */ +const signatureCache = new Map>(); +function watchSignatures(watch: LifecycleWatch): Promise { + const key = stateKey(watch.entityType, watch.status); + let cached = signatureCache.get(key); + if (!cached) { + cached = Promise.all([ + platformErrorSignature('api', slowStateMessage(watch.entityType, watch.status)), + platformErrorSignature('api', regressionMessage(watch)), + ]); + // A failed digest is not cached, so the next request retries it. + // shared-flight-join-allowed: local SHA-256 digests only (crypto.subtle), no request I/O to drop. + cached.catch(() => signatureCache.delete(key)); + // shared-flight-join-allowed: local SHA-256 digests only (crypto.subtle), no request I/O to drop. + signatureCache.set(key, cached); + } + // shared-flight-join-allowed: local SHA-256 digests only (crypto.subtle), no request I/O to drop. + return cached; +} + +export async function readLifecycleLatencyRange( + env: Env, + input: { sinceMs: number; untilMs: number }, + settingsOverride?: LifecycleLatencySettings +): Promise { + const settings = settingsOverride ?? (await resolveLifecycleLatencySettings(env)); + // A budget of 0 turns a state's watch off for the watchdog and the daily check; it is not shown. + const active = LIFECYCLE_WATCHES.filter((watch) => budgetMs(settings, watch) > 0); + if (active.length === 0) return { minSamples: settings.minSamples, states: [] }; + const sampleLimit = Math.max(1, settings.evaluationSampleLimit); + const since = new Date(input.sinceMs).toISOString(); + const until = new Date(input.untilMs).toISOString(); + + const signatures = await Promise.all( + active.map(async (watch) => ({ + key: stateKey(watch.entityType, watch.status), + signatures: await watchSignatures(watch), + })) + ); + const allSignatures = signatures.flatMap((entry) => entry.signatures); + + const stuckClauses = active + .map(() => '(entity_type = ? AND status = ? AND first_seen_at <= ?)') + .join(' OR '); + const stuckBinds = active.flatMap((watch) => [ + watch.entityType, + watch.status, + new Date(input.untilMs - budgetMs(settings, watch)).toISOString(), + ]); + const signaturePlaceholders = allSignatures.map(() => '?').join(', '); + const statePlaceholders = OPEN_INCIDENT_STATES.map(() => '?').join(', '); + + const [episodes, stuck, incidents] = await Promise.all([ + // Newest `sampleLimit` finished episodes per state in the range, all states in one read. + env.DATABASE.prepare( + `SELECT entity_type, status, duration_ms FROM ( + SELECT entity_type, status, + (julianday(last_seen_at) - julianday(first_seen_at)) * 86400000.0 AS duration_ms, + ROW_NUMBER() OVER (PARTITION BY entity_type, status ORDER BY ended_at DESC, id DESC) AS rn + FROM lifecycle_state_episodes + WHERE ended_at >= ? AND ended_at < ? + ) WHERE rn <= ?` + ) + .bind(since, until, sampleLimit) + .all(), + env.DATABASE.prepare( + `SELECT entity_type, status, COUNT(*) AS n FROM lifecycle_state_observations + WHERE ${stuckClauses} + GROUP BY entity_type, status` + ) + .bind(...stuckBinds) + .all<{ entity_type: string; status: string; n: number }>(), + env.DATABASE.prepare( + `SELECT t.signature, t.canonical_signature, t.queue_state, t.first_seen_at, t.last_seen_at, + t.occurrence_count, t.idea_id, idea.project_id AS idea_project_id + FROM platform_feedback_triages t + LEFT JOIN tasks idea ON idea.id = t.idea_id + WHERE (t.signature IN (${signaturePlaceholders}) + OR t.canonical_signature IN (${signaturePlaceholders})) + AND t.queue_state IN (${statePlaceholders}) + ORDER BY t.last_seen_at DESC` + ) + .bind(...allSignatures, ...allSignatures, ...OPEN_INCIDENT_STATES) + .all(), + ]); + + const durations = new Map(); + for (const row of episodes.results ?? []) { + // julianday() of an unreadable timestamp is NULL, and Number(null) would be a 0 ms sample. + const duration = row.duration_ms === null ? Number.NaN : Number(row.duration_ms); + if (!Number.isFinite(duration)) { + log.warn('lifecycle_latency.range_episode_skipped', { + state: stateKey(row.entity_type, row.status), + reason: 'unreadable_duration', + action: 'skipped', + }); + continue; + } + const key = stateKey(row.entity_type, row.status); + durations.set(key, [...(durations.get(key) ?? []), Math.max(0, Math.round(duration))]); + } + const stuckByState = new Map( + (stuck.results ?? []).map((row) => [stateKey(row.entity_type, row.status), Number(row.n)]) + ); + const incidentsBySignature = new Map(); + for (const row of incidents.results ?? []) { + const state = OPEN_INCIDENT_STATES.find((candidate) => candidate === row.queue_state); + const firstSeen = Number(row.first_seen_at); + const lastSeen = Number(row.last_seen_at); + if (!state || !Number.isFinite(firstSeen) || !Number.isFinite(lastSeen)) continue; + const incident: InstallationLatencyIncident = { + signature: row.signature, + state, + firstSeenAt: new Date(firstSeen).toISOString(), + lastSeenAt: new Date(lastSeen).toISOString(), + occurrences: Number(row.occurrence_count) || 0, + ideaId: row.idea_id, + ideaProjectId: row.idea_project_id, + }; + // Rows arrive most recently seen first; keep that one when two rows share a signature. + if (!incidentsBySignature.has(row.signature)) incidentsBySignature.set(row.signature, incident); + if (row.canonical_signature && !incidentsBySignature.has(row.canonical_signature)) { + incidentsBySignature.set(row.canonical_signature, incident); + } + } + + const noBaseline = latencyStats([]); + return { + minSamples: settings.minSamples, + states: active.map((watch) => { + const key = stateKey(watch.entityType, watch.status); + const stats = latencyStats(durations.get(key) ?? []); + const stateBudgetMs = budgetMs(settings, watch); + const stateSignatures = signatures.find((entry) => entry.key === key)?.signatures ?? []; + const stateIncidents = [ + ...new Set( + stateSignatures + .map((signature) => incidentsBySignature.get(signature)) + .filter((incident): incident is InstallationLatencyIncident => Boolean(incident)) + ), + ]; + return { + entityType: watch.entityType, + status: watch.status, + budgetMs: stateBudgetMs, + count: stats.count, + p50Ms: stats.p50Ms, + p95Ms: stats.p95Ms, + maxMs: stats.maxMs, + truncated: stats.count >= sampleLimit, + overBudget: + classifyRegression(stats, noBaseline, stateBudgetMs, settings) === 'over_budget', + overBudgetNow: stuckByState.get(key) ?? 0, + incidents: stateIncidents, + }; + }), + }; +} diff --git a/apps/api/src/services/lifecycle-timings.ts b/apps/api/src/services/lifecycle-timings.ts index a64cf62e14..2cc2743f19 100644 --- a/apps/api/src/services/lifecycle-timings.ts +++ b/apps/api/src/services/lifecycle-timings.ts @@ -1,3 +1,5 @@ +import type { LifecyclePhaseOperation } from '@simple-agent-manager/shared'; + import { log } from '../lib/logger'; // Protocol vocabulary, not caller-defined labels: never log paths, commands or errors. @@ -66,10 +68,6 @@ export function boundedLifecycleTimings(value: unknown): LifecycleTiming[] { return [...result.values()]; } -/** Every operation a stored phase timing can name. Runner rows never share a name with VM rows. */ -export type LifecyclePhaseOperation = - 'provision' | 'workspace' | 'sleep' | 'wake' | 'runner_start' | 'runner_wake'; - /** Ids the caller already holds. Task, skill and profile are resolved inside the INSERT. */ export interface LifecyclePhaseIdentity { projectId?: string | null; diff --git a/apps/api/src/services/linked-account-identity.ts b/apps/api/src/services/linked-account-identity.ts index 3e4157aac1..f293f30691 100644 --- a/apps/api/src/services/linked-account-identity.ts +++ b/apps/api/src/services/linked-account-identity.ts @@ -12,7 +12,7 @@ * The providers' `getUserInfo` calls this with the provider account id: when that account is * already linked to a user whose email is verified, the user's stored email is reported instead, * so the override leaves it unchanged. Name and avatar still refresh. New users, implicit - * same-email linking and unverified accounts are unchanged. A failed read changes nothing. + * same-email linking and unverified accounts are unchanged. A failed read aborts sign-in rather than risking an identity overwrite. */ import type { Env } from '../env'; import { createModuleLogger } from '../lib/logger'; @@ -40,15 +40,12 @@ export async function keepLinkedAccountEmail( .bind(providerId, accountId) .first<{ email: string }>(); if (!row?.email) return incoming; - if (incoming.email && incoming.email.trim().toLowerCase() === row.email.toLowerCase()) { - return incoming; - } return { email: row.email, emailVerified: true }; } catch (err) { log.warn('linked_account_identity.lookup_failed', { providerId, error: err instanceof Error ? err.message : String(err), }); - return incoming; + throw new Error('Could not preserve linked account identity'); } } diff --git a/apps/api/src/services/llm-chat-target.ts b/apps/api/src/services/llm-chat-target.ts index 332ce74eac..e8c7ef240d 100644 --- a/apps/api/src/services/llm-chat-target.ts +++ b/apps/api/src/services/llm-chat-target.ts @@ -1,280 +1,122 @@ -/** - * Where SAM's own OpenAI-format chat calls go: one resolver for the SAM agent, project agents, - * task titles, the diagnosis runner and the AI proxy's Workers AI route (rule 24). - * - * Order: - * 1. An admin-configured OpenAI-compatible endpoint (`llm.openAICompatible.*`). Explicit opt-in, - * so it wins wherever it is set. - * 2. Cloudflare AI Gateway's Workers AI route, when the gateway is reachable. - * 3. Cloudflare's Workers AI REST API, when the account API is configured. - * 4. Nothing: the caller reports that no model is available here. - * - * A Cloudflare deployment with no endpoint configured resolves exactly the URLs it used before. - */ +/** Worker settings adapter. Protocol targets and guarded fetch live in packages/ai-proxy. */ +import { + type ChatCompletionsTarget, + chatTarget, + LlmUnavailableError, +} from '@simple-agent-manager/ai-proxy'; +import { classifyHost } from '@simple-agent-manager/worker-core'; + import type { Env } from '../env'; -import { resolveD1BindingIdentity } from '../lib/d1-session'; -import { log } from '../lib/logger'; -import { classifyHost, guardedFetch } from '../lib/network-hosts'; -import { maybeJsonRecord } from '../lib/runtime-validation'; -import { resolveAdminSettingDetailsMany } from './admin-settings-resolution'; +import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from './config-read-deadline'; +import { withDeadline } from './fetch-timeout'; import { LLM_PURPOSE_MODEL_SETTING, type LlmPurpose, normalizeLlmBaseUrl, - validLlmBaseUrl, } from './llm-endpoint-settings'; +import { resolveLlmEndpointSettings } from './llm-endpoint-snapshot'; import { outboundMaxRedirectsValue } from './outbound-fetch-settings'; -import { hasCloudflareAccountApi, resolveAiGatewayId } from './platform-capabilities'; +import { + hasCloudflareAccountApi, + resolveAiGatewayId, + resolveLlmEndpointCapability, +} from './platform-capabilities'; export type { LlmPurpose } from './llm-endpoint-settings'; - -export interface ChatCompletionsTarget { - kind: 'openai-compatible' | 'cloudflare-gateway' | 'cloudflare-api'; - /** OpenAI-style base URL, without `/chat/completions`. */ - baseUrl: string; - /** The chat completions URL. */ - url: string; - /** Bearer token, or null when the endpoint takes none. */ - apiKey: string | null; - /** Model id to send. */ - model: string; - /** - * The admin opted in to this endpoint being on the private network - * (`llm.openAICompatible.allowPrivateNetwork`). Only meaningful for `openai-compatible`. - */ - allowPrivateNetwork: boolean; - /** Redirect hops the guarded fetch follows (`outbound.maxRedirects`). Only for `openai-compatible`. */ - maxRedirects?: number; -} - -/** - * No endpoint can serve this call. `not_configured` is a designed state (nothing is set up here); - * `settings_unreadable` means the endpoint settings could not be read, so the call was refused - * rather than sent to a provider the admin may have opted out of. - */ -export type LlmUnavailableReason = - 'not_configured' | 'settings_unreadable' | 'private_network_not_allowed'; - -const LLM_UNAVAILABLE_MESSAGES: Record = { - not_configured: - 'No language model is available on this installation. Configure an OpenAI-compatible endpoint in admin settings (AI models).', - settings_unreadable: - 'The language model settings could not be read, so the call was not sent. Try again shortly.', - private_network_not_allowed: - 'The configured language model endpoint is on a private network address. Turn on llm.openAICompatible.allowPrivateNetwork in admin settings (AI models) to allow it.', -}; - -export class LlmUnavailableError extends Error { - constructor( - readonly purpose: LlmPurpose, - readonly reason: LlmUnavailableReason = 'not_configured' - ) { - super(LLM_UNAVAILABLE_MESSAGES[reason]); - this.name = 'LlmUnavailableError'; - } -} - -export function isCloudflareChatTarget(target: ChatCompletionsTarget): boolean { - return target.kind !== 'openai-compatible'; -} - -function chatTarget( - kind: ChatCompletionsTarget['kind'], - baseUrl: string, - apiKey: string | null, - model: string, - allowPrivateNetwork = false -): ChatCompletionsTarget { - return { kind, baseUrl, url: `${baseUrl}/chat/completions`, apiKey, model, allowPrivateNetwork }; -} - -/** - * Fetch for a chat target's URL (`url` is `target.url` or an AI SDK provider's request URL on the - * same base). An admin-configured endpoint goes through the guarded fetch: its host and every - * redirect hop are checked, and a private-network host needs the admin's opt-in. Cloudflare - * targets are fixed Cloudflare hosts and keep the plain fetch. - */ -export function fetchChatTarget( - target: ChatCompletionsTarget, - init: RequestInit, - url: string = target.url -): Promise { - // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- Cloudflare chooses the fixed Workers AI endpoint for this target - if (isCloudflareChatTarget(target)) return fetch(url, init); - return guardedFetch(url, init, { - allowPrivateNetwork: target.allowPrivateNetwork, - maxRedirects: target.maxRedirects, - }); -} - -function stringValue(value: unknown): string | null { +export { + type ChatCompletionsTarget, + chatTargetHeaders, + fetchChatTarget, + isCloudflareChatTarget, + LlmUnavailableError, +} from '@simple-agent-manager/ai-proxy'; + +function nonempty(value: unknown): string | null { return typeof value === 'string' && value.trim() ? value.trim() : null; } -/** - * Per D1 binding, whether the last successful read of the base URL found an endpoint. Lets a - * settings outage keep the Cloudflare route for an installation known to have no endpoint. - */ -const lastEndpointConfigured = new WeakMap(); - -function settingsUnreadable(purpose: LlmPurpose, err: unknown): LlmUnavailableError { - log.error('llm.endpoint_settings_unreadable', { - purpose, - error: err instanceof Error ? err.message : String(err), - }); - return new LlmUnavailableError(purpose, 'settings_unreadable'); -} - -/** - * The configured base URL, read alone: it is a plain setting, so an installation without an - * endpoint never queries the credential table. When the read fails after this isolate has seen - * an endpoint configured, the call is refused: an admin who pointed SAM at their own endpoint - * must not have prompts sent to another provider because D1 hiccuped. An isolate that has not - * yet read the setting resolves it to its default (no endpoint), exactly as before endpoints - * existed, so a Cloudflare install keeps its route through an outage. - */ -async function readConfiguredBaseUrl(env: Env, purpose: LlmPurpose): Promise { - const db = resolveD1BindingIdentity(env.DATABASE); - try { - const [setting] = await resolveAdminSettingDetailsMany(env, ['llm.openAICompatible.baseUrl']); - const baseUrl = setting?.value ?? null; - lastEndpointConfigured.set(db, validLlmBaseUrl(baseUrl)); - return baseUrl; - } catch (err) { - if (lastEndpointConfigured.get(db) !== true) return null; - throw settingsUnreadable(purpose, err); - } -} - -/** - * The admin-configured OpenAI-compatible endpoint for `purpose`, or null when none is set. - * `requestedModel` is used only when no endpoint model is configured. Once an endpoint is - * configured, failing to read its key or models throws rather than using another provider. - */ +/** The capability reads the shared per-isolate settings snapshot, never the key on the default path. */ export async function resolveOpenAICompatibleTarget( env: Env, purpose: LlmPurpose, requestedModel: string | null = null ): Promise { - const baseUrl = await readConfiguredBaseUrl(env, purpose); - if (!validLlmBaseUrl(baseUrl)) return null; - let values: unknown[]; + if (!(await resolveLlmEndpointCapability(env))) return null; try { - const details = await resolveAdminSettingDetailsMany(env, [ + // Re-read the URL with its key/model under the same mutation generation. + const details = await resolveLlmEndpointSettings(env, [ + 'llm.openAICompatible.baseUrl', 'llm.openAICompatible.apiKey', 'llm.openAICompatible.model', LLM_PURPOSE_MODEL_SETTING[purpose], 'llm.openAICompatible.allowPrivateNetwork', 'outbound.maxRedirects', ]); - values = details.map((detail) => detail.value); + const [baseUrl, key, fallbackModel, purposeModel, privateNetwork, redirects] = details.map( + (d) => d.value + ); + if (baseUrl === null) return null; // Admin reset the endpoint between the gate and batch. + if (typeof baseUrl !== 'string') throw new LlmUnavailableError(purpose, 'settings_unreadable'); + const model = nonempty(purposeModel) ?? nonempty(fallbackModel) ?? requestedModel; + // An explicitly configured route must never silently fall back to another provider. + if (!model) throw new LlmUnavailableError(purpose, 'not_configured'); + const normalized = normalizeLlmBaseUrl(baseUrl); + if (privateNetwork !== true && classifyHost(new URL(normalized).hostname) === 'private') { + throw new LlmUnavailableError(purpose, 'private_network_not_allowed'); + } + return { + ...chatTarget('openai-compatible', normalized, nonempty(key), model, privateNetwork === true), + maxRedirects: outboundMaxRedirectsValue(redirects), + }; } catch (err) { - throw settingsUnreadable(purpose, err); - } - const [apiKey, defaultModel, purposeModel, allowPrivate, maxRedirects] = values; - const model = stringValue(purposeModel) ?? stringValue(defaultModel) ?? requestedModel; - if (!model) return null; - const normalized = normalizeLlmBaseUrl(String(baseUrl)); - const allowPrivateNetwork = allowPrivate === true; - // Refused here with a reason the admin can act on, rather than as a fetch error later. - if (!allowPrivateNetwork && classifyHost(new URL(normalized).hostname) === 'private') { - throw new LlmUnavailableError(purpose, 'private_network_not_allowed'); + if (err instanceof LlmUnavailableError) throw err; + throw new LlmUnavailableError(purpose, 'settings_unreadable'); } - return { - ...chatTarget('openai-compatible', normalized, stringValue(apiKey), model, allowPrivateNetwork), - maxRedirects: outboundMaxRedirectsValue(maxRedirects), - }; } -/** Cloudflare's Workers AI chat route (gateway first, then REST), or null off Cloudflare. */ export function resolveCloudflareWorkersAiTarget( env: Pick, model: string ): ChatCompletionsTarget | null { const gatewayId = resolveAiGatewayId(env); - if (gatewayId) { + if (gatewayId) return chatTarget( 'cloudflare-gateway', `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/workers-ai/v1`, env.CF_API_TOKEN, model ); - } - if (hasCloudflareAccountApi(env)) { + if (hasCloudflareAccountApi(env)) return chatTarget( 'cloudflare-api', `https://api.cloudflare.com/client/v4/accounts/${env.CF_ACCOUNT_ID}/ai/v1`, env.CF_API_TOKEN, model ); - } return null; } -/** Target for a call that would use a Workers AI model on Cloudflare. */ -export async function resolveWorkersAiChatTarget( - env: Env, - purpose: LlmPurpose, - model: string -): Promise { +export async function resolveWorkersAiChatTarget(env: Env, purpose: LlmPurpose, model: string) { return ( (await resolveOpenAICompatibleTarget(env, purpose, model)) ?? resolveCloudflareWorkersAiTarget(env, model) ); } -/** - * `resolveWorkersAiChatTarget` inside the caller's own time budget. The endpoint settings read - * is a D1 query, so without this a D1 hang would cost a call its settings-read wait on top of its - * own timeout (and a retried call would pay it per attempt). The read cannot be cancelled, so it - * races `signal`: when the budget runs out the call rejects with the signal's reason and the read - * is left to settle unobserved. - */ -export function resolveWorkersAiChatTargetWithin( +/** Allocate at most a quarter of the caller's budget to settings, preserving time for inference. */ +export async function resolveWorkersAiChatTargetWithin( env: Env, purpose: LlmPurpose, model: string, - signal: AbortSignal -): Promise { - if (signal.aborted) return Promise.reject(toError(signal.reason)); - return new Promise((resolve, reject) => { - const onAbort = () => reject(toError(signal.reason)); - signal.addEventListener('abort', onAbort, { once: true }); - resolveWorkersAiChatTarget(env, purpose, model) - .then(resolve, reject) - .finally(() => signal.removeEventListener('abort', onAbort)); - }); -} - -function toError(reason: unknown): Error { - return reason instanceof Error ? reason : new Error(String(reason)); -} - -/** - * A chat request body for `target`. A streamed call to an OpenAI-compatible endpoint asks for the - * final usage chunk (`stream_options.include_usage`, part of the OpenAI chat protocol) so SAM's - * accounting gets real counts. Cloudflare targets get `body` itself, byte for byte as before. - */ -export function withStreamUsageRequested( - target: ChatCompletionsTarget, - body: Record -): Record { - if (isCloudflareChatTarget(target) || body.stream !== true) return body; - const streamOptions = maybeJsonRecord(body.stream_options) ?? {}; - return { ...body, stream_options: { ...streamOptions, include_usage: true } }; -} - -/** - * Request headers for a chat target. `cf-aig-metadata` carries user and workspace ids for - * gateway analytics, so it goes to Cloudflare targets only, never to a third-party endpoint. - */ -export function chatTargetHeaders( - target: ChatCompletionsTarget, - cloudflareHeaders: Record = {} -): Record { - return { - 'Content-Type': 'application/json', - ...(target.apiKey ? { Authorization: `Bearer ${target.apiKey}` } : {}), - ...(isCloudflareChatTarget(target) ? cloudflareHeaders : {}), - }; + timeoutMs: number +) { + try { + return await withDeadline( + () => resolveWorkersAiChatTarget(env, purpose, model), + Math.max(1, Math.min(DEFAULT_CONFIG_READ_TIMEOUT_MS, timeoutMs / 4)) + ); + } catch (err) { + if (err instanceof LlmUnavailableError) throw err; + throw new LlmUnavailableError(purpose, 'settings_unreadable'); + } } diff --git a/apps/api/src/services/llm-endpoint-settings.ts b/apps/api/src/services/llm-endpoint-settings.ts index bcab0d6136..4891bab3df 100644 --- a/apps/api/src/services/llm-endpoint-settings.ts +++ b/apps/api/src/services/llm-endpoint-settings.ts @@ -7,12 +7,9 @@ * encrypted in `platform_credentials` like every other secret admin setting. The dependency * back to the registry is type-only; only the shared secret length floor is imported at runtime. */ -import { isAcceptableOperatorEndpoint } from '../lib/network-hosts'; -import { - type AdminSettingDefinition, - type AdminSettingName, - MIN_SECRET_SETTING_LENGTH, -} from './admin-setting-definitions'; +import { classifyHost } from '@simple-agent-manager/worker-core'; + +import { type AdminSettingDefinition, type AdminSettingName } from './admin-setting-definitions'; /** Which control-plane caller is asking; each can use its own model on the endpoint. */ export type LlmPurpose = 'agent' | 'taskTitle' | 'diagnosis' | 'aiProxy'; @@ -55,7 +52,16 @@ export function validLlmBaseUrl(value: unknown): boolean { if (typeof value !== 'string' || value.trim().length === 0 || value.length > 2048) return false; try { const url = new URL(value.trim()); - return isAcceptableOperatorEndpoint(url) && !/\/chat\/completions\/?$/.test(url.pathname); + return ( + !url.username && + !url.password && + !url.search && + !url.hash && + classifyHost(url.hostname) !== 'forbidden' && + (url.protocol === 'https:' || + (url.protocol === 'http:' && classifyHost(url.hostname) === 'private')) && + !/\/chat\/completions\/?$/.test(url.pathname) + ); } catch { return false; } @@ -63,7 +69,10 @@ export function validLlmBaseUrl(value: unknown): boolean { /** Normalized base URL without a trailing slash. Caller must have validated it. */ export function normalizeLlmBaseUrl(value: string): string { - return value.trim().replace(/\/+$/, ''); + const trimmed = value.trim(); + let end = trimmed.length; + while (end > 0 && trimmed[end - 1] === '/') end--; + return trimmed.slice(0, end); } function validModelId(value: unknown): boolean { @@ -119,9 +128,7 @@ function definition(key: LlmEndpointSettingKey): AdminSettingDefinition { credential: { provider: 'openai-compatible', kind: 'api-key' }, // Same floor as the OAuth secrets: a real key is never this short. validate: (value) => - typeof value === 'string' && - value.trim().length >= MIN_SECRET_SETTING_LENGTH && - value.length <= MAX_API_KEY_LENGTH, + typeof value === 'string' && value.trim().length >= 8 && value.length <= MAX_API_KEY_LENGTH, }; } return { diff --git a/apps/api/src/services/llm-endpoint-snapshot.ts b/apps/api/src/services/llm-endpoint-snapshot.ts new file mode 100644 index 0000000000..7f26653ef3 --- /dev/null +++ b/apps/api/src/services/llm-endpoint-snapshot.ts @@ -0,0 +1,125 @@ +/** Joint endpoint URL/key snapshot: independent caches can mix remote admin generations. */ +import { log, settleSharedFlight } from '@simple-agent-manager/worker-core'; +import * as v from 'valibot'; + +import type { Env } from '../env'; +import { resolveD1BindingIdentity } from '../lib/d1-session'; +import { ADMIN_SETTINGS_CACHE_MAX_MS, AdminSettingsUnavailableError } from './admin-settings-cache'; +import { type AdminSettingName } from './admin-settings-registry'; +import { adminSettingsGeneration, requiredDefinition, resolved } from './admin-settings-resolution'; +import { DEFAULT_CONFIG_READ_TIMEOUT_MS } from './config-read-deadline'; +import { withDeadline } from './fetch-timeout'; +import { INTEGRATION_CREDENTIAL_TYPE } from './platform-config-store'; + +const overrideSchema = v.object({ + key: v.string(), + value: v.string(), + updatedAt: v.string(), + updatedBy: v.nullable(v.string()), +}); +const credentialSchema = v.object({ + id: v.string(), + provider: v.string(), + kind: v.string(), + ciphertext: v.string(), + iv: v.string(), + updatedAt: v.string(), + updatedBy: v.nullable(v.string()), +}); +type Snapshot = { + rows: v.InferOutput[]; + credentials: v.InferOutput[]; +}; +type Entry = { + generation: number; + expiresAt: number; + /** When the load's own deadline fires; joiners wait until then (plus grace), never longer. */ + deadlineAt: number; + promise: Promise; +}; +const snapshots = new WeakMap(); + +async function load(env: Env, db: D1Database): Promise { + // D1 batch is transactional: both halves are from one primary snapshot, even when another + // isolate rotates the endpoint while this read is in flight. Only encrypted keys are cached. + const results = await db.batch([ + db.prepare( + 'SELECT key,value,updated_at AS updatedAt,updated_by AS updatedBy FROM platform_settings' + ), + db + .prepare( + 'SELECT id,provider,credential_kind AS kind,encrypted_token AS ciphertext,iv,updated_at AS updatedAt,COALESCE(updated_by,created_by) AS updatedBy FROM platform_credentials WHERE credential_type=? AND provider=? AND credential_kind=? AND is_enabled=1 ORDER BY updated_at DESC,created_at DESC' + ) + .bind(INTEGRATION_CREDENTIAL_TYPE, 'openai-compatible', 'api-key'), + ]); + if (results.length !== 2 || results.some((result) => !result.success)) + throw new AdminSettingsUnavailableError(); + const rows = v.safeParse(v.array(overrideSchema), results[0]?.results); + if (!rows.success) throw new AdminSettingsUnavailableError(); + const credentials: Snapshot['credentials'] = []; + for (const row of results[1]?.results ?? []) { + const parsed = v.safeParse(credentialSchema, row); + try { + if (!parsed.success) throw new AdminSettingsUnavailableError(); + // Validate/decrypt each candidate independently; a malformed legacy row cannot hide a + // later usable key. Never log parser/decryption messages carrying credential material. + await resolved(env, requiredDefinition('llm.openAICompatible.apiKey'), rows.output, true, [ + parsed.output, + ]); + credentials.push(parsed.output); + } catch { + log.warn('llm_endpoint.credential_row_skipped', { + credentialId: parsed.success ? parsed.output.id : undefined, + provider: 'openai-compatible', + kind: 'api-key', + reason: 'invalid_credential', + }); + } + } + // No key is a valid explicit setup; stored keys that cannot be read are an outage. + if ((results[1]?.results.length ?? 0) > 0 && credentials.length === 0) + throw new AdminSettingsUnavailableError(); + return { rows: rows.output, credentials }; +} + +/** One atomic batch per isolate TTL, shared across purposes and request-scoped D1 facades. */ +export async function resolveLlmEndpointSettings(env: Env, names: AdminSettingName[]) { + const db = resolveD1BindingIdentity(env.DATABASE); + for (let attempt = 0; attempt < 3; attempt++) { + const generation = adminSettingsGeneration(db); + let entry = snapshots.get(db); + if (!entry || entry.generation !== generation || Date.now() >= entry.expiresAt) { + entry = { + generation, + expiresAt: Date.now() + ADMIN_SETTINGS_CACHE_MAX_MS, + deadlineAt: Date.now() + DEFAULT_CONFIG_READ_TIMEOUT_MS, + promise: withDeadline(() => load(env, db), DEFAULT_CONFIG_READ_TIMEOUT_MS), + }; + snapshots.set(db, entry); + } + try { + // Another request may have started this load; on a runtime that drops a disconnected + // request's I/O it can never settle, so join it with a bound (packages/worker-core + // shared-flight.ts) and start a fresh load if it was abandoned. + const joined = await settleSharedFlight(entry.promise, entry.deadlineAt); + if (joined.abandoned) { + if (snapshots.get(db) === entry) snapshots.delete(db); + continue; + } + const snapshot = joined.value; + const values = await Promise.all( + names.map((name) => + resolved(env, requiredDefinition(name), snapshot.rows, true, snapshot.credentials) + ) + ); + if (generation !== adminSettingsGeneration(db)) continue; + if (Date.now() >= entry.expiresAt) throw new AdminSettingsUnavailableError(); + return values; + } catch (error) { + if (snapshots.get(db) === entry) snapshots.delete(db); + if (generation !== adminSettingsGeneration(db)) continue; + throw error; + } + } + throw new AdminSettingsUnavailableError(); +} diff --git a/apps/api/src/services/node-agent-route.ts b/apps/api/src/services/node-agent-route.ts index 58e143498e..919c451d44 100644 --- a/apps/api/src/services/node-agent-route.ts +++ b/apps/api/src/services/node-agent-route.ts @@ -1,152 +1,76 @@ /** - * The one place that decides HOW the control plane reaches a node's vm-agent. + * How the control plane reaches a node's vm-agent, decided from the node row alone. * - * - `cf-container` runtime: the VmAgentContainer Durable Object (handled by the caller). - * - `reverse-tunnel` transport: `http://127.0.0.1:{leasePort}` on the control-plane box, via the - * node's frpc. No per-node DNS record exists for these nodes, so there is NO fallback to the - * public `{nodeId}.vm.{BASE_DOMAIN}` hostname: a missing lease fails closed. - * - anything else (`vm-public-dns`, `cloudflare-tunnel`, legacy NULL): the public backend - * hostname from {@link getNodeBackendBaseUrl}, unchanged. + * - `cf-container` runtime: the VmAgentContainer Durable Object (the caller handles it). + * - A transport owned by an installed build extension (`node-transport-extension.ts`): the + * origin that extension resolves. The self-host build's reverse tunnel resolves a loopback + * lease port of the node's CURRENT incarnation; a released or superseded lease is never + * routed to, so revocation takes effect for control-plane traffic on the next request. + * - Any other transport (`vm-public-dns`, `cloudflare-tunnel`, legacy NULL): the public backend + * hostname, exactly as before. * - * Transport is read from the node row, never from the request, and the lease must belong to the - * node's CURRENT incarnation, so a released or superseded lease can never be routed to. + * A row naming an extension transport that this build did not install fails closed: such a + * node has no DNS record, so the public hostname would be wrong. The Cloudflare Worker installs + * no extension and never stores one, so on Cloudflare this module only adds the `transport` + * column to the node read its callers already made (zero added I/O). */ -import { and, eq } from 'drizzle-orm'; -import { drizzle } from 'drizzle-orm/d1'; - -import * as schema from '../db/schema'; import type { Env } from '../env'; -import { getNodeBackendBaseUrl, type NodeBackendBaseUrlEnv } from './node-agent-readiness'; -import { - assertReverseTunnelUpstreamPort, - type ReverseTunnelRangeEnv, - reverseTunnelUpstreamOrigin, -} from './node-reverse-tunnel-config'; +import { AppError } from '../middleware/error'; +import { getNodeBackendBaseUrl } from './node-agent-readiness'; +import { nodeTransportExtension } from './node-transport-extension'; export type NodeAgentRoute = - | { kind: 'container'; runtime: 'cf-container' } - | { kind: 'reverse-tunnel'; port: number; origin: string } + | { kind: 'container' } + | { kind: 'extension'; origin: string } | { kind: 'public'; origin: string }; -export class NodeAgentRouteError extends Error { - override name = 'NodeAgentRouteError'; - constructor( - readonly nodeId: string, - message: string - ) { - super(message); - } -} - export interface NodeAgentRouteRow { runtime: string | null; transport: string | null; - leasePort: number | null; } -/** - * The node's routing row. Non-reverse-tunnel nodes cost exactly the one node query this seam - * always made (same shape, same columns plus transport); only a reverse-tunnel node pays a - * second, indexed read for its current incarnation's active lease. - */ -export async function readNodeAgentRouteRow( - env: Pick, - nodeId: string -): Promise { - const db = drizzle(env.DATABASE, { schema }); - const node = await db - .select({ runtime: schema.nodes.runtime, transport: schema.nodes.transport }) - .from(schema.nodes) - .where(eq(schema.nodes.id, nodeId)) - .get(); - if (!node) return null; - if (node.transport !== 'reverse-tunnel') { - return { runtime: node.runtime ?? null, transport: node.transport ?? null, leasePort: null }; - } - // The active lease of the node's CURRENT incarnation (a superseded one is never routed to). - const lease = await db - .select({ port: schema.nodeReverseTunnelLeases.port }) - .from(schema.nodeReverseTunnelLeases) - .innerJoin( - schema.nodes, - and( - eq(schema.nodes.id, schema.nodeReverseTunnelLeases.nodeId), - eq(schema.nodes.runtimeIncarnationId, schema.nodeReverseTunnelLeases.runtimeIncarnationId) - ) - ) - .where( - and( - eq(schema.nodeReverseTunnelLeases.nodeId, nodeId), - eq(schema.nodeReverseTunnelLeases.status, 'active') - ) - ) - .get(); - return { - runtime: node.runtime ?? null, - transport: node.transport, - leasePort: lease?.port ?? null, - }; -} +/** Transports a build extension owns; they have no public backend hostname. */ +const EXTENSION_ONLY_TRANSPORTS: ReadonlySet = new Set(['reverse-tunnel']); -/** Resolve a route from an already-loaded row (lets callers fold this into their own query). */ -export function nodeAgentRouteFromRow( - nodeId: string, - row: NodeAgentRouteRow | null, - env: NodeBackendBaseUrlEnv & ReverseTunnelRangeEnv -): NodeAgentRoute { - if (row?.runtime === 'cf-container') return { kind: 'container', runtime: 'cf-container' }; - if (row?.transport === 'reverse-tunnel') { - if (!row.leasePort) { - throw new NodeAgentRouteError( - nodeId, - `Node ${nodeId} uses the reverse-tunnel transport but has no active lease for its current incarnation` - ); - } - // The upstream is a loopback port on this box: never route outside the lease range. - try { - assertReverseTunnelUpstreamPort(env, row.leasePort); - } catch (err) { - throw new NodeAgentRouteError(nodeId, err instanceof Error ? err.message : String(err)); - } - return { - kind: 'reverse-tunnel', - port: row.leasePort, - origin: reverseTunnelUpstreamOrigin(row.leasePort), - }; +/** A designed 503 (`app.onError` maps it): an unroutable node is unreachable, not a server fault. */ +export class NodeAgentRouteError extends AppError { + override name = 'NodeAgentRouteError'; + constructor( + readonly nodeId: string, + message: string + ) { + super(503, 'NODE_UNREACHABLE', message); } - return { kind: 'public', origin: getNodeBackendBaseUrl(nodeId, env) }; } export async function resolveNodeAgentRoute( - env: Pick & NodeBackendBaseUrlEnv & ReverseTunnelRangeEnv, - nodeId: string + env: Env, + nodeId: string, + row: NodeAgentRouteRow | null | undefined ): Promise { - return nodeAgentRouteFromRow(nodeId, await readNodeAgentRouteRow(env, nodeId), env); + if (row?.runtime === 'cf-container') return { kind: 'container' }; + const transport = row?.transport ?? null; + const extension = transport ? nodeTransportExtension(transport) : undefined; + if (extension) { + // The driver names expected missing routes with NodeAgentRouteError. Unexpected + // database/configuration failures retain the global sanitized server-error handling. + return { kind: 'extension', origin: await extension.resolveAgentOrigin(env, nodeId) }; + } + if (transport && EXTENSION_ONLY_TRANSPORTS.has(transport)) { + throw new NodeAgentRouteError( + nodeId, + `Node ${nodeId} uses the ${transport} transport, which this build cannot route` + ); + } + return { kind: 'public', origin: getNodeBackendBaseUrl(nodeId, env) }; } -/** - * Re-target a URL that was built against {@link getNodeBackendBaseUrl} to the node's real - * route, keeping path and query. Public routes are returned unchanged. - */ +/** Keep path and query of a URL built against the public hostname; swap its origin. */ export function retargetNodeAgentUrl(url: string, route: NodeAgentRoute): string { - if (route.kind !== 'reverse-tunnel') return url; + if (route.kind !== 'extension') return url; const original = new URL(url); const target = new URL(route.origin); target.pathname = original.pathname; target.search = original.search; return target.toString(); } - -/** - * Request options for a control-plane fetch to a node, on EVERY route and transport. A node - * agent never redirects the control plane (the vm-agent sends no 3xx), so a redirect can only - * come from a misbehaving or compromised node, and following it would carry the management - * Authorization header wherever it points: on a self-hosted box, celld's loopback services - * and other nodes' lease ports; on any box, an arbitrary host. The 3xx is returned as-is and - * callers treat it as not ok. Proxied browser requests pass it through to the browser - * unchanged. On Cloudflare an incoming request's redirect mode is already `manual`, so the - * workspace proxy behaves as before there. - */ -export function nodeAgentRequestInit(options: RequestInit): RequestInit { - return { ...options, redirect: 'manual' }; -} diff --git a/apps/api/src/services/node-agent.ts b/apps/api/src/services/node-agent.ts index 5ed99baf6b..d6e23e072c 100644 --- a/apps/api/src/services/node-agent.ts +++ b/apps/api/src/services/node-agent.ts @@ -1,6 +1,9 @@ // FILE SIZE EXCEPTION: Cross-boundary node-agent request layer marginally over the limit; interactive/background timeout tiers and cf-container interruption classification are one cohesive concern. Split candidate if it grows further. See .claude/rules/18-file-size-limits.md import type { McpServerEntry } from '@simple-agent-manager/shared'; +import { eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/d1'; +import * as schema from '../db/schema'; import type { VmAgentContainerRequestGuard } from '../durable-objects/vm-agent-container'; import { getRuntimeRecoveryMessage, @@ -18,11 +21,7 @@ import { getNodeBackendBaseUrl, waitForNodeAgentReadyWith, } from './node-agent-readiness'; -import { - nodeAgentRequestInit, - resolveNodeAgentRoute, - retargetNodeAgentUrl, -} from './node-agent-route'; +import { resolveNodeAgentRoute, retargetNodeAgentUrl } from './node-agent-route'; import { recordNodeRoutingMetric } from './telemetry'; import { fetchVmAgentContainer, @@ -57,6 +56,8 @@ interface NodeAgentRequestOptions extends RequestInit { } interface FetchNodeAgentControls { + /** Only the authenticated local port-forward adapter may return app redirects. */ + allowApplicationRedirects?: boolean; sourceTaskGuard?: VmAgentContainerRequestGuard; beforeExternalMutation?: () => Promise; recoverContainerOnTimeout?: boolean; @@ -269,6 +270,22 @@ export async function nodeAgentRequest( } } +/** A node redirect is a failed control response. Discard its Location and body: + * Go's mux can echo a query JWT into both before the route consumes it. + */ +function nodeResponse(response: Response, allowApplicationRedirects = false): Response { + // 304 is cache revalidation, not a followable hop; retain confinement/ETag headers. + if ( + allowApplicationRedirects || + response.status === 304 || + response.status < 300 || + response.status >= 400 + ) + return response; + void response.body?.cancel().catch(() => undefined); + return new Response('Node redirect refused', { status: response.status }); +} + export async function fetchNodeAgent( nodeId: string, env: Env, @@ -277,26 +294,37 @@ export async function fetchNodeAgent( requestTimeoutMs: number, controls: FetchNodeAgentControls = {} ): Promise { + // Node URLs come from SAM routing, never a redirect chosen by the node. + options = { ...options, redirect: 'manual' }; const { sourceTaskGuard, beforeExternalMutation, recoverContainerOnTimeout = true, noWakeContainer = false, + allowApplicationRedirects = false, } = controls; if (!env.DATABASE || typeof env.DATABASE.prepare !== 'function') { await beforeExternalMutation?.(); - return fetchWithTimeout(url, nodeAgentRequestInit(options), requestTimeoutMs); + return nodeResponse( + await fetchWithTimeout(url, options, requestTimeoutMs), + allowApplicationRedirects + ); } - // Single seam for control plane -> node HTTP: the node row decides container, reverse - // tunnel (loopback lease port on this box) or the public backend hostname. - const route = await resolveNodeAgentRoute(env, nodeId); + const db = drizzle(env.DATABASE, { schema }); + const node = await db + .select({ runtime: schema.nodes.runtime, transport: schema.nodes.transport }) + .from(schema.nodes) + .where(eq(schema.nodes.id, nodeId)) + .get(); + + // Same single node read as before; only an installed build transport adds its own lookup. + const route = await resolveNodeAgentRoute(env, nodeId, node); if (route.kind !== 'container') { await beforeExternalMutation?.(); - return fetchWithTimeout( - retargetNodeAgentUrl(url, route), - nodeAgentRequestInit(options), - requestTimeoutMs + return nodeResponse( + await fetchWithTimeout(retargetNodeAgentUrl(url, route), options, requestTimeoutMs), + allowApplicationRedirects ); } @@ -334,19 +362,13 @@ export async function fetchNodeAgent( ? fetchVmAgentContainerNoWake( env, nodeId, - new Request( - containerUrl.toString(), - requestInitWithoutSignal(nodeAgentRequestInit(options)) - ), + new Request(containerUrl.toString(), requestInitWithoutSignal(options)), vmAgentPort ) : fetchVmAgentContainer( env, nodeId, - new Request( - containerUrl.toString(), - requestInitWithoutSignal(nodeAgentRequestInit(options)) - ), + new Request(containerUrl.toString(), requestInitWithoutSignal(options)), vmAgentPort, sourceTaskGuard ), @@ -357,7 +379,7 @@ export async function fetchNodeAgent( ); }), ]); - return response; + return nodeResponse(response, allowApplicationRedirects); } catch (error) { const timedOut = error instanceof Error && error.message.startsWith('Request timed out after '); if (!timedOut) throw error; diff --git a/apps/api/src/services/node-manual-deletion.ts b/apps/api/src/services/node-manual-deletion.ts index 8d9d2df36e..9f0be2bb97 100644 --- a/apps/api/src/services/node-manual-deletion.ts +++ b/apps/api/src/services/node-manual-deletion.ts @@ -9,7 +9,7 @@ import { log, serializeError } from '../lib/logger'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { errors } from '../middleware/error'; import { type OperatorAbsenceProof, proveOperatorRetirement } from './node-operator-retirement'; -import { releaseNodeTunnels } from './node-tunnel-cleanup'; +import { releaseTerminatedNodeIngress } from './node-provisioning-ingress'; import { createProviderForUser, exactProviderCredentialBindingFromPlacementSnapshot, @@ -166,9 +166,7 @@ export async function recordManualNodeDeletion( const runtimeTerminationConfirmedAt = await recordOwnerAttestedRuntimeTermination(db, node); // The proof makes this incarnation non-live: release its Cloudflare tunnel now, as strict // deletion does, rather than waiting for the sweep's non-live scan. Never throws. - if (node.runtime === 'vm' && node.transport === 'cloudflare-tunnel') { - await releaseNodeTunnels(env, node.id, 'owner_attested_termination'); - } + await releaseTerminatedNodeIngress(env, node, 'owner_attested_termination'); log.info('node_manual_deletion.attested', { nodeId, userId, diff --git a/apps/api/src/services/node-provisioning-cloud-init.ts b/apps/api/src/services/node-provisioning-cloud-init.ts index bfc122d8cc..f29bf565b1 100644 --- a/apps/api/src/services/node-provisioning-cloud-init.ts +++ b/apps/api/src/services/node-provisioning-cloud-init.ts @@ -9,7 +9,7 @@ import { import { type TaskMode } from '@simple-agent-manager/shared'; import type { Env } from '../env'; -import type { NodeReverseTunnelProvisioning } from './node-reverse-tunnel-provisioning'; +import type { NodeBootRenderer } from './node-transport-extension'; import { nodeTunnelBootVariables } from './node-tunnel-config'; import type { NodeTunnelProvisioning } from './node-tunnel-provisioning'; import { errorReportCloudInitVariables } from './vm-error-report-config'; @@ -29,12 +29,11 @@ export interface NodeCloudInitInput { deploymentContext?: { environmentId: string }; /** Present only for tunnel-transport workspace nodes. */ tunnel?: NodeTunnelProvisioning | null; - /** Present only for reverse-tunnel-transport workspace nodes (self-hosted control plane). */ - reverseTunnel?: NodeReverseTunnelProvisioning | null; + renderCloudInit?: NodeBootRenderer; } export function buildNodeCloudInit(input: NodeCloudInitInput): string { - const { env, node, taskContext, deploymentContext, tunnel, reverseTunnel } = input; + const { env, node, taskContext, deploymentContext, tunnel } = input; const isDeploymentNode = !!deploymentContext; const variables: CloudInitVariables = { nodeId: node.id, @@ -61,10 +60,9 @@ export function buildNodeCloudInit(input: NodeCloudInitInput): string { // Tunnel nodes never fetch an Origin CA certificate: cloudflared terminates TLS at the // edge and the agent serves plain HTTP on loopback (the node-lifecycle route also // refuses issuance server-side for tunnel transport). - originCaCertificateUrl: - tunnel || reverseTunnel - ? undefined - : `https://api.${env.BASE_DOMAIN}/api/nodes/${node.id}/origin-ca-certificate`, + originCaCertificateUrl: tunnel + ? undefined + : `https://api.${env.BASE_DOMAIN}/api/nodes/${node.id}/origin-ca-certificate`, vmAgentPort: env.VM_AGENT_PORT, vmAgentRequiredVersion: env.VM_AGENT_REQUIRED_VERSION?.trim(), vmAgentMemoryReserveMb: String(resolveEffectiveNodeHostMemoryReserveMb(env)), @@ -96,17 +94,5 @@ export function buildNodeCloudInit(input: NodeCloudInitInput): string { variables.cloudflareTunnelPort = tunnel.tunnelPort; Object.assign(variables, nodeTunnelBootVariables(env)); } - if (reverseTunnel) { - // Same loopback listener, firewall and connector timings as the Cloudflare tunnel; the - // connector is frpc dialling the control plane's own HTTPS endpoint. - const timings = nodeTunnelBootVariables(env); - variables.reverseTunnelCredential = reverseTunnel.credential; - variables.reverseTunnelRemotePort = String(reverseTunnel.port); - variables.reverseTunnelLocalPort = reverseTunnel.localPort; - variables.tunnelListenerWaitSeconds = timings.tunnelListenerWaitSeconds; - variables.tunnelListenerProbeTimeoutSeconds = timings.tunnelListenerProbeTimeoutSeconds; - variables.tunnelListenerProbeIntervalSeconds = timings.tunnelListenerProbeIntervalSeconds; - variables.tunnelConnectorRestartSeconds = timings.tunnelConnectorRestartSeconds; - } - return generateCloudInit(variables); + return input.renderCloudInit ? input.renderCloudInit(variables) : generateCloudInit(variables); } diff --git a/apps/api/src/services/node-provisioning-failure.ts b/apps/api/src/services/node-provisioning-failure.ts new file mode 100644 index 0000000000..055817434f --- /dev/null +++ b/apps/api/src/services/node-provisioning-failure.ts @@ -0,0 +1,227 @@ +import { + isTransientCapacityError, + ProviderError, + type ProviderRequestContext, + rethrowIfProviderRequestAborted, +} from '@simple-agent-manager/providers'; +import type { CredentialProvider } from '@simple-agent-manager/shared'; +import { and, sql } from 'drizzle-orm'; +import type { drizzle } from 'drizzle-orm/d1'; + +import * as schema from '../db/schema'; +import type { Env } from '../env'; +import { log, serializeError } from '../lib/logger'; +import { GcpApiError, sanitizeGcpError } from './gcp-errors'; +import { + type DurableNodeAllocation, + NodeAllocationUncertainError, +} from './node-allocation-recovery'; +import type { ProvisionNodeOptions } from './node-provisioning'; +import { settleNodeTunnelIngress } from './node-provisioning-ingress'; +import { + creatingProvisioningPredicate, + releaseTunnelBeforeVm, + truncateNodeErrorMessage, +} from './node-provisioning-predicates'; +import type { NodeTunnelProvisioningPhase } from './node-tunnel-provisioning'; +import { recordTunnelProvisioningFailure } from './node-tunnel-provisioning-failure'; +import { persistError } from './observability'; + +interface NodeProvisioningFailureInput { + env: Env; + node: typeof schema.nodes.$inferSelect; + options?: ProvisionNodeOptions; + durable?: DurableNodeAllocation; + db: ReturnType>; + tunnelJournaled: boolean; + provisioningRuntimeIncarnationId: string | null; + tunnelPhase: NodeTunnelProvisioningPhase | null; + providerCreateRequested: boolean; + providerContext?: ProviderRequestContext; + attemptedProvider?: CredentialProvider; + providerCreateRejected: boolean; + providerAllocationRejected: boolean; + providerRejectionProofAt: string | null; + rejectedPlacementPredicate: ReturnType; +} + +/** Failure finalization preserves allocation and release ordering. */ +export async function handleNodeProvisioningFailure( + err: unknown, + input: NodeProvisioningFailureInput +): Promise { + const { + env, + node, + options, + durable, + tunnelJournaled, + provisioningRuntimeIncarnationId, + tunnelPhase, + providerCreateRequested, + providerContext, + } = input; + // Record the cause first, aborts included: the abort branches below rethrow before any + // other log or row write, which left staging failures with no recorded cause. + if (tunnelJournaled && provisioningRuntimeIncarnationId) { + await recordTunnelProvisioningFailure(env, { + nodeId: node.id, + runtimeIncarnationId: provisioningRuntimeIncarnationId, + phase: tunnelPhase ?? (providerCreateRequested ? 'provider_create' : 'before_provider'), + durable: !!durable, + aborted: options?.signal?.aborted === true, + error: err, + }); + } + // Only a non-durable call can release before the VM: it minted this incarnation and will + // never resume it. A durable allocation resumes the SAME incarnation on its next attempt + // (a released row would refuse it forever), and an earlier attempt of it may already have + // a VM holding this token. Its row is released by node teardown or the sweep once the + // incarnation is no longer live. + if (tunnelJournaled && !durable && !providerCreateRequested && provisioningRuntimeIncarnationId) { + await releaseTunnelBeforeVm(env, node.id, provisioningRuntimeIncarnationId); + } + if (err instanceof NodeAllocationUncertainError) throw err; + rethrowIfProviderRequestAborted(err, providerContext); + try { + await finalizeNodeProvisioningFailure(err, input); + } finally { + // After the row writes above: a deleted row or rejection proof makes the incarnation + // non-live, which releases its tunnel. A possibly-created VM keeps it until node + // teardown records termination proof. Never throws; the cron sweep is the backstop. + if (tunnelJournaled) await settleNodeTunnelIngress(env, node.id, 'provisioning_failed'); + } +} + +function provisioningFailureMessage(err: unknown): string { + if (err instanceof GcpApiError) return sanitizeGcpError(err, 'node-provisioning'); + return err instanceof Error ? err.message : String(err); +} + +async function recordNodeProvisioningError( + err: unknown, + input: NodeProvisioningFailureInput, + errorMessage: string +): Promise { + const { env, node, attemptedProvider } = input; + // Sanitize GCP errors to prevent leaking resource paths in client-visible errorMessage + const providerName = attemptedProvider ?? 'unknown'; + const statusCode = err instanceof ProviderError ? err.statusCode : undefined; + + log.error('node_provisioning.failed', { + nodeId: node.id, + provider: providerName, + vmSize: node.vmSize, + vmLocation: node.vmLocation, + statusCode, + error: errorMessage, + }); + + // Persist detailed error to observability database + try { + await persistError( + env.OBSERVABILITY_DATABASE, + { + source: 'api', + level: 'error', + message: `Node provisioning failed: ${errorMessage}`, + context: { + component: 'node-provisioning', + nodeId: node.id, + userId: node.userId, + provider: providerName, + vmSize: node.vmSize, + vmLocation: node.vmLocation, + statusCode, + }, + nodeId: node.id, + userId: node.userId, + }, + env + ); + } catch (obsErr) { + log.error('node_provisioning.observability_persist_failed', serializeError(obsErr)); + } +} + +async function finalizeNodeProvisioningFailure( + err: unknown, + input: NodeProvisioningFailureInput +): Promise { + const { options, providerCreateRejected, providerAllocationRejected } = input; + const errorMessage = provisioningFailureMessage(err); + await recordNodeProvisioningError(err, input, errorMessage); + const isCapacityFailure = err instanceof ProviderError && isTransientCapacityError(err); + // Descent-loop mode deletes only a proven pre-identity rejection, then rethrows the + // original error so its caller can choose another capacity offering. + if ( + options?.rethrowProviderError && + ((isCapacityFailure && !providerCreateRejected) || providerAllocationRejected) + ) { + await deleteRejectedProvisioningNode(input); + } else { + await recordFailedProvisioningNode(input, errorMessage); + } + if (options?.rethrowProviderError) throw err; +} + +async function deleteRejectedProvisioningNode(input: NodeProvisioningFailureInput): Promise { + const { + node, + options, + db, + provisioningRuntimeIncarnationId, + providerAllocationRejected, + providerRejectionProofAt, + rejectedPlacementPredicate, + } = input; + if (providerAllocationRejected && (!providerRejectionProofAt || !rejectedPlacementPredicate)) { + throw new Error('Rejected allocation proof identity is unavailable'); + } + await options?.beforeRejectedNodeDelete?.(); + await db + .delete(schema.nodes) + .where( + and( + creatingProvisioningPredicate(node, provisioningRuntimeIncarnationId), + ...(providerAllocationRejected + ? [ + sql`${schema.nodes.runtimeTerminationConfirmedAt} IS ${providerRejectionProofAt}`, + rejectedPlacementPredicate, + ] + : []) + ) + ) + .run(); +} + +async function recordFailedProvisioningNode( + input: NodeProvisioningFailureInput, + errorMessage: string +): Promise { + const { + node, + db, + provisioningRuntimeIncarnationId, + attemptedProvider, + providerAllocationRejected, + } = input; + const providerName = attemptedProvider ?? 'unknown'; + const truncatedError = truncateNodeErrorMessage(errorMessage); + await db + .update(schema.nodes) + .set({ + status: 'error', + healthStatus: 'unhealthy', + errorMessage: `[${providerName}] ${truncatedError}`, + ...(providerAllocationRejected + ? { runtimeTerminationConfirmedAt: new Date().toISOString() } + : {}), + updatedAt: new Date().toISOString(), + cleanupBlockedSince: null, + cleanupBlockedReason: null, + cleanupBlockedAlertedAt: null, + }) + .where(creatingProvisioningPredicate(node, provisioningRuntimeIncarnationId)) + .run(); +} diff --git a/apps/api/src/services/node-provisioning-ingress.ts b/apps/api/src/services/node-provisioning-ingress.ts index 238b03dd2b..b9023b17c5 100644 --- a/apps/api/src/services/node-provisioning-ingress.ts +++ b/apps/api/src/services/node-provisioning-ingress.ts @@ -1,21 +1,9 @@ -/** - * Tunnel ingress set-up and failure settlement for `provisionNode`, one entry point per step - * for both tunnel transports. Split out of `node-provisioning.ts` (rule 18). - * - * - `cloudflare-tunnel`: journal + create the incarnation's named tunnel (node-tunnel-*.ts). - * - `reverse-tunnel`: lease the box-side loopback port and derive the frp credential - * (node-reverse-tunnel-*.ts). - * Both run BEFORE the provider VM exists, so every later failure can release them. - */ -import type { NodeTransport } from '@simple-agent-manager/shared'; - +/** Common ownership boundary, used by Cloudflare and separately installed transport builds. */ import type { Env } from '../env'; -import { releaseNodeReverseTunnelLeases } from './node-reverse-tunnel-leases'; -import { - ensureNodeReverseTunnelForProvisioning, - type NodeReverseTunnelProvisioning, -} from './node-reverse-tunnel-provisioning'; -import { settleNodeTunnels } from './node-tunnel-cleanup'; +import { log, serializeError } from '../lib/logger'; +import { type NodeBootRenderer, nodeTransportExtension } from './node-transport-extension'; +import { releaseNodeTunnels, settleNodeTunnels } from './node-tunnel-cleanup'; +import { releaseUnallocatedNodeTunnel } from './node-tunnel-journal'; import { ensureNodeTunnelForProvisioning, type NodeTunnelProvisioning, @@ -24,64 +12,73 @@ import { export interface NodeTunnelIngress { tunnel: NodeTunnelProvisioning | null; - reverseTunnel: NodeReverseTunnelProvisioning | null; + renderCloudInit?: NodeBootRenderer; } - -export interface PrepareNodeTunnelIngressInput { - nodeId: string; - userId: string; - runtimeIncarnationId: string | null; - signal?: AbortSignal; - /** Called before any ownership write, so the caller's failure path knows to release it. */ - onOwnershipRecorded: () => void; - /** Cloudflare tunnel only: the step in progress, for the failure diagnostic. */ - onPhase?: (phase: NodeTunnelProvisioningPhase) => void; -} - export async function prepareNodeTunnelIngress( env: Env, - transport: NodeTransport | null, - input: PrepareNodeTunnelIngressInput -): Promise { - if (transport !== 'cloudflare-tunnel' && transport !== 'reverse-tunnel') { - return { tunnel: null, reverseTunnel: null }; - } - if (!input.runtimeIncarnationId) { - throw new Error( - transport === 'cloudflare-tunnel' - ? 'Tunnel transport requires a runtime incarnation' - : 'Reverse-tunnel transport requires a runtime incarnation' - ); + transport: string | null, + input: { + nodeId: string; + userId: string; + runtimeIncarnationId: string | null; + signal?: AbortSignal; + onOwnershipRecorded: () => void; + onPhase?: (phase: NodeTunnelProvisioningPhase) => void; } +): Promise { + if (!transport || transport === 'vm-public-dns') return { tunnel: null }; + if (!input.runtimeIncarnationId) + throw new Error('Tunnel transport requires a runtime incarnation'); + const owner = { ...input, runtimeIncarnationId: input.runtimeIncarnationId }; input.onOwnershipRecorded(); - const owner = { - nodeId: input.nodeId, - userId: input.userId, - runtimeIncarnationId: input.runtimeIncarnationId, - }; if (transport === 'cloudflare-tunnel') { - return { - tunnel: await ensureNodeTunnelForProvisioning(env, { - ...owner, - signal: input.signal, - onPhase: input.onPhase, - }), - reverseTunnel: null, - }; + return { tunnel: await ensureNodeTunnelForProvisioning(env, owner) }; } - return { tunnel: null, reverseTunnel: await ensureNodeReverseTunnelForProvisioning(env, owner) }; + const adapter = nodeTransportExtension(transport); + if (!adapter) throw new Error(`Transport ${transport} is unavailable in this build`); + return { tunnel: null, renderCloudInit: await adapter.prepare(env, owner) }; } -/** - * Provisioning failure: release every non-live incarnation's tunnel ownership of this node. - * A possibly-created VM keeps its (live) incarnation's ownership until node teardown records - * termination proof. Never throws; the cron sweeps are the backstop. - */ +/** Exact incarnation proof: no provider POST, or confirmed direct provider deletion. */ +export async function releaseNodeIngressBeforeVm( + env: Env, + nodeId: string, + incarnation: string, + reason: string +): Promise { + const release = async (operation: () => Promise | undefined): Promise => { + try { + await operation(); + } catch (error) { + log.error('node_provisioning.tunnel_release_failed', { + nodeId, + runtimeIncarnationId: incarnation, + ...serializeError(error), + }); + } + }; + await release(() => releaseUnallocatedNodeTunnel(env, nodeId, incarnation, reason)); + await release(() => + nodeTransportExtension()?.releaseUnallocated(env, nodeId, incarnation, reason) + ); +} +export async function releaseTerminatedNodeIngress( + env: Env, + node: { id: string; runtime: string; transport: string | null }, + reason = 'runtime_terminated' +): Promise { + if (node.runtime !== 'vm') return; + if (node.transport === 'cloudflare-tunnel') { + await releaseNodeTunnels(env, node.id, reason); + } else { + await nodeTransportExtension(node.transport)?.releaseNonLive(env, node.id, reason); + } +} export async function settleNodeTunnelIngress( env: Env, nodeId: string, reason: string ): Promise { await settleNodeTunnels(env, nodeId, reason); - await releaseNodeReverseTunnelLeases(env, nodeId, reason); + await nodeTransportExtension()?.releaseNonLive(env, nodeId, reason); } diff --git a/apps/api/src/services/node-provisioning-predicates.ts b/apps/api/src/services/node-provisioning-predicates.ts index a3ea2d7058..cca86ece8d 100644 --- a/apps/api/src/services/node-provisioning-predicates.ts +++ b/apps/api/src/services/node-provisioning-predicates.ts @@ -7,9 +7,7 @@ import { and, eq, sql } from 'drizzle-orm'; import * as schema from '../db/schema'; import type { Env } from '../env'; -import { log, serializeError } from '../lib/logger'; -import { releaseUnallocatedReverseTunnelLease } from './node-reverse-tunnel-leases'; -import { releaseUnallocatedNodeTunnel } from './node-tunnel-journal'; +import { releaseNodeIngressBeforeVm } from './node-provisioning-ingress'; const NODE_ERROR_MESSAGE_MAX_LENGTH = 500; @@ -70,10 +68,8 @@ export function d1WriteChanged( } /** - * Release one incarnation's tunnel (Cloudflare journal row and/or reverse-tunnel port lease) - * when the caller KNOWS no VM can still use it: no provider create was ever requested, or the - * provider confirmed the VM deleted. Each release is one fenced D1 update that is a no-op for - * a transport the incarnation does not use. Never throws. + * Release one incarnation's tunnel when the caller KNOWS no VM can still use it: no provider + * create was ever requested, or the provider confirmed the VM deleted. Never throws. */ export async function releaseTunnelBeforeVm( env: Env, @@ -81,24 +77,7 @@ export async function releaseTunnelBeforeVm( runtimeIncarnationId: string, reason = 'provisioning_failed_before_vm' ): Promise { - try { - await releaseUnallocatedNodeTunnel(env, nodeId, runtimeIncarnationId, reason); - } catch (releaseErr) { - log.error('node_provisioning.tunnel_release_failed', { - nodeId, - runtimeIncarnationId, - ...serializeError(releaseErr), - }); - } - try { - await releaseUnallocatedReverseTunnelLease(env, nodeId, runtimeIncarnationId, reason); - } catch (releaseErr) { - log.error('node_provisioning.reverse_tunnel_release_failed', { - nodeId, - runtimeIncarnationId, - ...serializeError(releaseErr), - }); - } + await releaseNodeIngressBeforeVm(env, nodeId, runtimeIncarnationId, reason); } /** diff --git a/apps/api/src/services/node-provisioning.ts b/apps/api/src/services/node-provisioning.ts index 7ae2529523..c6a2790666 100644 --- a/apps/api/src/services/node-provisioning.ts +++ b/apps/api/src/services/node-provisioning.ts @@ -1,14 +1,11 @@ import { validateCloudInitSize } from '@simple-agent-manager/cloud-init'; import { isProviderCreateNotDispatched, - isTransientCapacityError, - ProviderError, type ProviderRequestContext, - rethrowIfProviderRequestAborted, throwIfProviderRequestAborted, } from '@simple-agent-manager/providers'; import { type CredentialProvider, type TaskMode } from '@simple-agent-manager/shared'; -import { and, eq, sql } from 'drizzle-orm'; +import { type and, eq, sql } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import * as schema from '../db/schema'; @@ -16,7 +13,6 @@ import type { Env } from '../env'; import { log, serializeError } from '../lib/logger'; import { getCredentialEncryptionKey } from '../lib/secrets'; import { createNodeBackendDNSRecord } from './dns'; -import { GcpApiError, sanitizeGcpError } from './gcp-errors'; import { signCurrentNodeCallbackToken } from './jwt'; import { durableAllocationMayHaveCreated, @@ -35,13 +31,13 @@ import { resolveInstallationId, } from './node-provider-labels'; import { buildNodeCloudInit } from './node-provisioning-cloud-init'; +import { handleNodeProvisioningFailure } from './node-provisioning-failure'; import { resolveHetznerBaseImageOverride } from './node-provisioning-image'; import { creatingProvisioningPredicate, d1WriteChanged, isProviderCreateRejectedBeforeVmIdentity, providerIdentityRecordPredicate, - releaseTunnelBeforeVm, truncateNodeErrorMessage, } from './node-provisioning-predicates'; import { @@ -49,12 +45,10 @@ import { deleteCreatedProviderVmDirectly, } from './node-provisioning-race-cleanup'; export { resolveHetznerBaseImageOverride } from './node-provisioning-image'; -import { prepareNodeTunnelIngress, settleNodeTunnelIngress } from './node-provisioning-ingress'; +import { prepareNodeTunnelIngress } from './node-provisioning-ingress'; import { recordRejectedAllocationAbsence } from './node-rejection-proof'; import { resolveManagedNodeTransport, type TunnelEnv } from './node-tunnel-config'; import type { NodeTunnelProvisioningPhase } from './node-tunnel-provisioning'; -import { recordTunnelProvisioningFailure } from './node-tunnel-provisioning-failure'; -import { persistError } from './observability'; import { createProviderForUser, exactProviderCredentialBindingFromPlacementSnapshot, @@ -181,15 +175,14 @@ export async function provisionNode( try { // A resumed allocation keeps the transport its (possibly already created) VM was // booted with; only a new incarnation reads the installation's current choice. - const transport = resuming - ? node.transport === 'cloudflare-tunnel' || node.transport === 'reverse-tunnel' - ? node.transport - : null - : resolveManagedNodeTransport(tunnelEnv, { - runtime: node.runtime, - nodeClass: node.nodeClass, - nodeRole: node.nodeRole, - }); + let transport = node.transport === 'vm-public-dns' ? null : node.transport; + if (!resuming) { + transport = resolveManagedNodeTransport(tunnelEnv, { + runtime: node.runtime, + nodeClass: node.nodeClass, + nodeRole: node.nodeRole, + }); + } if (!resuming) await assertNodeAllocationPlanCurrent( env, @@ -262,20 +255,15 @@ export async function provisionNode( const isDeploymentNode = !!deploymentContext; - // Tunnel ownership (Cloudflare journal or reverse-tunnel lease) is recorded BEFORE the - // provider VM exists, so every later failure can find and release it. - const { tunnel, reverseTunnel } = await prepareNodeTunnelIngress(env, transport, { - nodeId: node.id, - userId: node.userId, + const ingress = await prepareNodeTunnelIngress(env, transport, { + nodeId: node.id, userId: node.userId, runtimeIncarnationId: provisioningRuntimeIncarnationId, signal: options?.signal, - onOwnershipRecorded: () => { - tunnelJournaled = true; - }, - onPhase: (phase) => { - tunnelPhase = phase; - }, + onOwnershipRecorded: () => { tunnelJournaled = true; }, + onPhase: (phase) => { tunnelPhase = phase; }, }); + const { tunnel } = ingress; + const tunnelIngress = !!tunnel || !!ingress.renderCloudInit; tunnelPhase = null; const cloudInit = buildNodeCloudInit({ @@ -287,7 +275,7 @@ export async function provisionNode( taskContext, deploymentContext, tunnel, - reverseTunnel, + renderCloudInit: ingress.renderCloudInit, }); if (!validateCloudInitSize(cloudInit)) { @@ -488,12 +476,10 @@ export async function provisionNode( // Scaleway allocates IPs asynchronously after boot — vm.ip will be empty. // Store the provider instance ID and mark as pending-ip; heartbeat backfill // will capture the IP when the VM agent sends its first heartbeat. - // Tunnel nodes are reached through cloudflared or frpc, never the public IP: no IP wait - // and no A record (the heartbeat never creates one for them, keyed on the node's - // transport). A deployment tunnel node (cloudflare-tunnel only; reverse-tunnel excludes - // deployment nodes) still serves its app routes on the public IP, so it waits for one; - // its heartbeat records that IP without an A record (routes/node-lifecycle.ts). - const tunnelIngress = !!tunnel || !!reverseTunnel; + // Tunnel nodes are reached through cloudflared, never the public IP: no IP wait and no + // A record (the heartbeat never creates one for them, keyed on nodes.tunnel_id). A + // deployment tunnel node still serves its app routes on the public IP, so it waits for + // one; its heartbeat records that IP without an A record (routes/node-lifecycle.ts). if (!vm.ip && (!tunnelIngress || isDeploymentNode)) { log.info('node_provisioning.awaiting_ip_backfill', { nodeId: node.id, @@ -596,152 +582,8 @@ export async function provisionNode( throwIfProviderRequestAborted(publishContext); return { allocationConfirmed: true }; } catch (err) { - // Record the cause first, aborts included: the abort branches below rethrow before any - // other log or row write, which left staging failures with no recorded cause. - if (tunnelJournaled && provisioningRuntimeIncarnationId) { - await recordTunnelProvisioningFailure(env, { - nodeId: node.id, - runtimeIncarnationId: provisioningRuntimeIncarnationId, - phase: tunnelPhase ?? (providerCreateRequested ? 'provider_create' : 'before_provider'), - durable: !!durable, - aborted: options?.signal?.aborted === true, - error: err, - }); - } - // Only a non-durable call can release before the VM: it minted this incarnation and will - // never resume it. A durable allocation resumes the SAME incarnation on its next attempt - // (a released row would refuse it forever), and an earlier attempt of it may already have - // a VM holding this token. Its row is released by node teardown or the sweep once the - // incarnation is no longer live. - if ( - tunnelJournaled && - !durable && - !providerCreateRequested && - provisioningRuntimeIncarnationId - ) { - await releaseTunnelBeforeVm(env, node.id, provisioningRuntimeIncarnationId); - } - if (err instanceof NodeAllocationUncertainError) throw err; - rethrowIfProviderRequestAborted(err, providerContext); - try { - // Sanitize GCP errors to prevent leaking resource paths in client-visible errorMessage - const errorMessage = - err instanceof GcpApiError - ? sanitizeGcpError(err, 'node-provisioning') - : err instanceof Error - ? err.message - : String(err); - const providerName = attemptedProvider ?? 'unknown'; - const statusCode = err instanceof ProviderError ? err.statusCode : undefined; - - log.error('node_provisioning.failed', { - nodeId: node.id, - provider: providerName, - vmSize: node.vmSize, - vmLocation: node.vmLocation, - statusCode, - error: errorMessage, - }); - - // Persist detailed error to observability database - try { - await persistError( - env.OBSERVABILITY_DATABASE, - { - source: 'api', - level: 'error', - message: `Node provisioning failed: ${errorMessage}`, - context: { - component: 'node-provisioning', - nodeId: node.id, - userId: node.userId, - provider: providerName, - vmSize: node.vmSize, - vmLocation: node.vmLocation, - statusCode, - }, - nodeId: node.id, - userId: node.userId, - }, - env - ); - } catch (obsErr) { - log.error('node_provisioning.observability_persist_failed', serializeError(obsErr)); - } - - const isCapacityFailure = err instanceof ProviderError && isTransientCapacityError(err); - - // Descent-loop mode: re-throw so the caller can branch on the error category. - // Delete the failed node row when the create boundary proved the provider rejected - // allocation before returning a VM identity; there is no runtime to tear down. - if (options?.rethrowProviderError) { - if ((isCapacityFailure && !providerCreateRejected) || providerAllocationRejected) { - if ( - providerAllocationRejected && - (!providerRejectionProofAt || !rejectedPlacementPredicate) - ) { - throw new Error('Rejected allocation proof identity is unavailable'); - } - await options.beforeRejectedNodeDelete?.(); - await db - .delete(schema.nodes) - .where( - and( - creatingProvisioningPredicate(node, provisioningRuntimeIncarnationId), - ...(providerAllocationRejected - ? [ - sql`${schema.nodes.runtimeTerminationConfirmedAt} IS ${providerRejectionProofAt}`, - rejectedPlacementPredicate, - ] - : []) - ) - ) - .run(); - } else { - const truncatedError = truncateNodeErrorMessage(errorMessage); - await db - .update(schema.nodes) - .set({ - status: 'error', - healthStatus: 'unhealthy', - errorMessage: `[${providerName}] ${truncatedError}`, - ...(providerAllocationRejected - ? { runtimeTerminationConfirmedAt: new Date().toISOString() } - : {}), - updatedAt: new Date().toISOString(), - cleanupBlockedSince: null, - cleanupBlockedReason: null, - cleanupBlockedAlertedAt: null, - }) - .where(creatingProvisioningPredicate(node, provisioningRuntimeIncarnationId)) - .run(); - } - throw err; - } - - // Legacy mode: store the actual error message (truncated) in the node record. - const truncatedError = truncateNodeErrorMessage(errorMessage); - await db - .update(schema.nodes) - .set({ - status: 'error', - healthStatus: 'unhealthy', - errorMessage: `[${providerName}] ${truncatedError}`, - ...(providerAllocationRejected - ? { runtimeTerminationConfirmedAt: new Date().toISOString() } - : {}), - updatedAt: new Date().toISOString(), - cleanupBlockedSince: null, - cleanupBlockedReason: null, - cleanupBlockedAlertedAt: null, - }) - .where(creatingProvisioningPredicate(node, provisioningRuntimeIncarnationId)) - .run(); - } finally { - // After the row writes above: a deleted row or rejection proof makes the incarnation - // non-live, which releases its tunnel. A possibly-created VM keeps it until node - // teardown records termination proof. Never throws; the cron sweep is the backstop. - if (tunnelJournaled) await settleNodeTunnelIngress(env, node.id, 'provisioning_failed'); - } + await handleNodeProvisioningFailure(err, { + env, node, options, durable, db, tunnelJournaled, provisioningRuntimeIncarnationId, tunnelPhase, providerCreateRequested, providerContext, attemptedProvider, providerCreateRejected, providerAllocationRejected, providerRejectionProofAt, rejectedPlacementPredicate, + }); } } diff --git a/apps/api/src/services/node-transport-extension.ts b/apps/api/src/services/node-transport-extension.ts new file mode 100644 index 0000000000..938f3232e9 --- /dev/null +++ b/apps/api/src/services/node-transport-extension.ts @@ -0,0 +1,66 @@ +/** Build-owned transport adapter. Only the self-host entry installs an extension. */ +import type { CloudInitVariables } from '@simple-agent-manager/cloud-init'; +import type { NodeTransport } from '@simple-agent-manager/shared'; + +import type { Env } from '../env'; + +export type NodeBootRenderer = (variables: CloudInitVariables) => string; +export interface NodeTransportOwner { + nodeId: string; + userId: string; + runtimeIncarnationId: string; +} +export interface NodeTransportExtension { + transport: NodeTransport; + select(node: { runtime: string; nodeClass: string; nodeRole?: string }): NodeTransport | null; + prepare(env: Env, owner: NodeTransportOwner): Promise; + releaseUnallocated( + env: Env, + nodeId: string, + incarnation: string, + reason: string + ): Promise; + releaseNonLive(env: Env, nodeId: string, reason: string): Promise; + /** + * Origin (`scheme://host:port`) the control plane uses for this node's agent. Called only for + * a node whose stored transport is this extension's; it must fail closed (throw) when the + * node has no current route, so a node without DNS is never sent to the public hostname. + */ + resolveAgentOrigin(env: Env, nodeId: string): Promise; +} +let extension: NodeTransportExtension | undefined; + +/** Called once at build entry initialization, before requests and DO dispatch. */ +export function installNodeTransportExtension(value: NodeTransportExtension): void { + if (extension && extension.transport !== value.transport) { + throw new Error('A node transport extension is already installed'); + } + extension = value; +} +export function nodeTransportExtension( + transport?: string | null +): NodeTransportExtension | undefined { + return transport === undefined || transport === extension?.transport ? extension : undefined; +} + +/** + * True when this installation provisions new nodes on an installed extension transport. Such + * nodes are reachable only from the control-plane host (no public backend hostname), so a + * feature that hands one VM another VM's URL must not provision such nodes as upload relays. + * Existing public-transport relays remain selectable through their stored transport. + * Cloudflare installs no extension: always false, no I/O. + */ +export function provisionsExtensionTransportNodes(env: Pick): boolean { + const transport = env.VM_AGENT_TRANSPORT?.trim(); + return !!transport && !!nodeTransportExtension(transport); +} + +/** Stored transport owns ingress even before an external tunnel id is written. */ +export function nodeHasTunnelIngress(node: { + transport: string | null; + tunnelId?: string | null; +}): boolean { + return ( + !!node.tunnelId || node.transport === 'cloudflare-tunnel' || node.transport === 'reverse-tunnel' + ); +} diff --git a/apps/api/src/services/node-tunnel-config.ts b/apps/api/src/services/node-tunnel-config.ts index 7f488d481f..77a589e65d 100644 --- a/apps/api/src/services/node-tunnel-config.ts +++ b/apps/api/src/services/node-tunnel-config.ts @@ -3,13 +3,9 @@ * * `VM_AGENT_TRANSPORT='cloudflare-tunnel'` opts NEW managed VM nodes, workspace and deployment * role alike, into an outbound-only Cloudflare named tunnel for the VM agent's control channel - * (`{nodeId}.vm.{BASE_DOMAIN}`). `VM_AGENT_TRANSPORT='reverse-tunnel'` (self-hosted control - * plane) gives NEW managed workspace VM nodes a pinned frpc that dials the control-plane box - * instead (services/node-reverse-tunnel-*.ts); deployment nodes stay on public-IP transport - * there, because the reverse-tunnel path has only been built and verified for workspace nodes. - * An unset transport keeps legacy public-IP transport unchanged; unsupported values fail - * provisioning. Instant (cf-container) runtimes are excluded: a container runtime has no VM to - * run a tunnel client on. + * (`{nodeId}.vm.{BASE_DOMAIN}`). An unset transport keeps legacy public-IP transport + * unchanged; unsupported values fail provisioning. Instant (cf-container) runtimes are + * excluded: a container runtime has no VM to run cloudflared on. * * Deployment nodes keep their public app ingress: app routes stay grey-cloud A records to the * node IP, with Caddy terminating TLS by ACME (services/dns-app-routes.ts). Routing app @@ -34,6 +30,7 @@ import { type NodeTunnelSettingName, } from './admin-settings-node-tunnel-definitions'; import { getNodeBackendHostname } from './dns-core'; +import { nodeTransportExtension } from './node-transport-extension'; /** Worker configuration is canonical; no separate pre-integration environment contract. */ export type TunnelEnv = Env; @@ -142,8 +139,7 @@ export function nodeTunnelBootVariables(env: TunnelBootConfigEnv) { export interface ManagedNodeTransportInput { runtime: string; nodeClass: string; - /** The node row's own `node_role` ('workspace' | 'deployment'); required so no caller can omit it. */ - nodeRole: string; + nodeRole?: string; } /** @@ -156,29 +152,18 @@ export function resolveManagedNodeTransport( ): NodeTransport | null { const configured = env.VM_AGENT_TRANSPORT?.trim() ?? ''; if (configured === '' || configured === 'vm-public-dns') return null; - if (configured !== 'cloudflare-tunnel' && configured !== 'reverse-tunnel') { + const adapter = nodeTransportExtension(configured); + if (adapter) return adapter.select(node); + if (configured !== 'cloudflare-tunnel') { throw new Error(`Unsupported VM_AGENT_TRANSPORT ${JSON.stringify(configured)}`); } if (node.runtime !== 'vm' || node.nodeClass !== 'managed') return null; - if (configured === 'reverse-tunnel') { - // Self-hosted box: only workspace nodes have a reverse-tunnel path (lease, frpc - // cloud-init, node-agent route seam). Deployment nodes keep public-IP transport. - return node.nodeRole === 'deployment' ? null : 'reverse-tunnel'; - } // Deployment nodes are included: the tunnel carries only their agent control channel, and - // their app routes keep using the public IP. + // their app routes keep using the public IP. A future tunnel transport must decide this + // separately for deployment nodes (their app ingress is not tunnelled). return 'cloudflare-tunnel'; } -/** - * True when this installation provisions reverse-tunnel nodes (a self-hosted box). Used by - * paths that must not hand a node's URL to another VM: a reverse-tunnel node is reachable only - * from the box's loopback. - */ -export function isReverseTunnelInstallation(env: Pick): boolean { - return env.VM_AGENT_TRANSPORT?.trim() === 'reverse-tunnel'; -} - export function resolveVmAgentTunnelPort(env: TunnelTransportEnv): string { const port = env.VM_AGENT_TUNNEL_PORT?.trim() || DEFAULT_CLOUDFLARE_TUNNEL_PORT; const value = Number(port); diff --git a/apps/api/src/services/node-usage-common.ts b/apps/api/src/services/node-usage-common.ts index 46e3214241..3041216d08 100644 --- a/apps/api/src/services/node-usage-common.ts +++ b/apps/api/src/services/node-usage-common.ts @@ -1,10 +1,10 @@ -import type { CredentialSource } from '@simple-agent-manager/shared'; +import { type CredentialSource, NODE_BILLING_ENDED_STATUSES } from '@simple-agent-manager/shared'; // ============================================================================= // Node status helpers // ============================================================================= -export const ENDED_STATUSES_ARRAY = ['destroyed', 'destroying', 'deleted', 'error'] as const; +export const ENDED_STATUSES_ARRAY = NODE_BILLING_ENDED_STATUSES; export const ENDED_STATUSES = new Set(ENDED_STATUSES_ARRAY); diff --git a/apps/api/src/services/node-websocket-gateway.ts b/apps/api/src/services/node-websocket-gateway.ts index 282cb64d34..c2fb1a318f 100644 --- a/apps/api/src/services/node-websocket-gateway.ts +++ b/apps/api/src/services/node-websocket-gateway.ts @@ -1,27 +1,21 @@ /** - * Gateway decisions: how the Worker answers Caddy's forward_auth for node WebSockets on a - * self-hosted box (routes/self-host-gateway.ts). + * Gateway decisions for node WebSockets on the self-hosted box. * - * celld cannot hand a WebSocket obtained from an outbound `fetch()` back to the browser, so on - * the reverse-tunnel transport Caddy carries the socket. The Worker must still make every auth - * decision. To guarantee it makes EXACTLY the decision it makes today, the gateway re-dispatches - * the original request through the normal SAM app with an in-process marker; the existing - * handlers (ws-* proxy, logs stream) run their unchanged authentication and authorization and, - * at the point where they would `fetch` the node, return a decision naming the upstream and the - * request headers they would have sent instead. + * celld cannot hand a WebSocket from an outbound `fetch()` back to the browser, so on the + * reverse-tunnel transport the box's Caddy carries the socket and asks the API (forward_auth) + * whether to. The self-host gateway route (`selfhost/reverse-tunnel/gateway.ts`) re-dispatches + * the original request through the normal app with an in-process marker. The existing ws-* + * proxy and logs-stream handlers then run their unchanged authentication and, where they would + * `fetch` the node, return a decision naming the upstream and the headers they would have sent. * - * The marker is a WeakMap entry keyed by the Request object, so no HTTP input can set it. The - * decision response carries a per-request random nonce so the gateway can tell a decision from - * any other 2xx the inner dispatch might produce (which it then refuses). + * The marker is a WeakMap entry keyed by the Request object, so no HTTP input can set it, and + * the decision carries a per-request random nonce, so the gateway can tell it from any other + * 2xx. Only the self-host gateway marks requests: on Cloudflare `isGatewayAuthorizationRequest` + * is one WeakMap lookup that is always false. */ import type { NodeAgentRoute } from './node-agent-route'; -import { - assertReverseTunnelUpstreamPort, - REVERSE_TUNNEL_UPSTREAM_HOST, - type ReverseTunnelRangeEnv, -} from './node-reverse-tunnel-config'; -/** Response headers Caddy copies into the upstream request (deploy/selfhost/caddy/sam.d/). */ +/** Response headers the box's Caddy copies into the upstream request. */ export const GATEWAY_HEADER = { decision: 'X-SAM-Gateway-Decision', upstream: 'X-SAM-Upstream', @@ -45,11 +39,10 @@ export function isGatewayAuthorizationRequest(request: Request): boolean { return gatewayRequestNonces.has(request); } -/** The handler's upstream request, as it would have been sent to the node. */ -export interface GatewayUpstreamRequest { - /** Path and query on the node agent (e.g. `/terminal/ws?token=...`). */ - url: URL; - headers: Headers; +/** True when `response` is the decision minted for `request` (and not some other 2xx). */ +export function isGatewayDecisionFor(request: Request, response: Response): boolean { + const nonce = gatewayRequestNonces.get(request); + return !!nonce && response.headers.get(GATEWAY_HEADER.decision) === nonce; } function unsupported(message: string): Response { @@ -60,33 +53,26 @@ function unsupported(message: string): Response { } /** - * Build the forward_auth decision for an authorized request. Only reverse-tunnel nodes can be - * reached through the gateway (their upstream is a loopback lease port on this box); any other - * route is refused rather than guessed, so a misrouted socket never reaches a public hostname. + * The forward_auth decision for an authorized request. Only a node on a build-extension route + * (a loopback lease port on this box) can be carried by the gateway; any other route is + * refused rather than guessed, so a misrouted socket never reaches a public hostname. */ export function gatewayDecisionResponse( request: Request, - route: NodeAgentRoute | null, - upstream: GatewayUpstreamRequest, - env: ReverseTunnelRangeEnv + route: NodeAgentRoute, + upstream: { url: URL; headers: Headers } ): Response { const nonce = gatewayRequestNonces.get(request); if (!nonce) throw new Error('gatewayDecisionResponse called for a non-gateway request'); - if (!route || route.kind !== 'reverse-tunnel') { + if (route.kind !== 'extension') { return unsupported('Node is not reachable through the self-hosted WebSocket gateway'); } - // Re-checked where X-SAM-Upstream is minted: Caddy proxies to exactly this address. - try { - assertReverseTunnelUpstreamPort(env, route.port); - } catch { - return unsupported('Node lease port is outside the reverse-tunnel range'); - } const headers = new Headers({ 'Cache-Control': 'no-store' }); headers.set(GATEWAY_HEADER.decision, nonce); - headers.set(GATEWAY_HEADER.upstream, `${REVERSE_TUNNEL_UPSTREAM_HOST}:${route.port}`); + headers.set(GATEWAY_HEADER.upstream, new URL(route.origin).host); headers.set(GATEWAY_HEADER.upstreamUri, `${upstream.url.pathname}${upstream.url.search}`); - // Always present (possibly empty): Caddy replaces the client's Authorization and Cookie - // with exactly what the Worker would have forwarded, so a stripped credential stays stripped. + // Always present (possibly empty): Caddy replaces the client's Authorization and Cookie with + // exactly what the Worker would have forwarded, so a stripped credential stays stripped. headers.set(GATEWAY_HEADER.upstreamAuthorization, upstream.headers.get('authorization') ?? ''); headers.set(GATEWAY_HEADER.upstreamCookie, upstream.headers.get('cookie') ?? ''); headers.set(GATEWAY_HEADER.nodeId, upstream.headers.get('x-sam-node-id') ?? ''); @@ -98,9 +84,3 @@ export function gatewayDecisionResponse( export function gatewayUnsupportedRuntimeResponse(): Response { return unsupported('Instant workspaces are not reachable through the self-hosted gateway'); } - -/** True when `response` is the decision minted for `request` (and not some other 2xx). */ -export function isGatewayDecisionFor(request: Request, response: Response): boolean { - const nonce = gatewayRequestNonces.get(request); - return !!nonce && response.headers.get(GATEWAY_HEADER.decision) === nonce; -} diff --git a/apps/api/src/services/notification.ts b/apps/api/src/services/notification.ts index 84b2ba8b4b..5398be51de 100644 --- a/apps/api/src/services/notification.ts +++ b/apps/api/src/services/notification.ts @@ -9,6 +9,7 @@ import type { CreateNotificationRequest, NotificationResponse } from '@simple-agent-manager/shared'; import { + classifyFailure, type HumanInputCategory, MAX_NOTIFICATION_BODY_LENGTH, MAX_NOTIFICATION_TITLE_LENGTH, @@ -85,6 +86,14 @@ export function buildActionUrl(projectId: string, sessionId?: string | null): st return `/projects/${projectId}`; } +/** + * Relative URL of one inbox item (the project inbox page, `?item=`). Same-origin relative, + * like `buildActionUrl`; the ref is URL-encoded. + */ +export function buildInboxItemActionUrl(projectId: string, ref: string): string { + return `/projects/${projectId}/inbox?item=${encodeURIComponent(ref)}`; +} + /** * Send a notification to a specific user via their Notification DO. * @@ -168,17 +177,23 @@ export async function notifyTaskFailed( taskTitle: string; errorMessage?: string | null; sessionId?: string | null; + /** The task's inbox error item, when one was filed: the notification opens it. */ + inboxRef?: string | null; } ): Promise { await sendNotification(env, userId, { type: 'error', urgency: NOTIFICATION_TYPE_URGENCY.error ?? 'high', title: `Task failed: ${truncate(opts.taskTitle, MAX_NOTIFICATION_TITLE_LENGTH)}`, - body: opts.errorMessage ?? 'Task encountered an error', + // The classified plain sentence, never the agent's raw error text (it can carry command + // fragments, URLs or echoed tokens, and the push body shows on a lock screen). + body: classifyFailure(opts.errorMessage).explanation, projectId: opts.projectId, taskId: opts.taskId, sessionId: opts.sessionId, - actionUrl: buildActionUrl(opts.projectId, opts.sessionId), + actionUrl: opts.inboxRef + ? buildInboxItemActionUrl(opts.projectId, opts.inboxRef) + : buildActionUrl(opts.projectId, opts.sessionId), metadata: { projectName: opts.projectName, }, @@ -186,33 +201,32 @@ export async function notifyTaskFailed( } /** - * Emit a "session_ended" notification when an agent finishes a chat turn. + * Emit the notification for a newly filed system error inbox item (slice E): `error` for a + * failed task, chat wake or answer delivery, `cron_failure` for a failing automation. Title and + * body are the item's own sanitized sentences; the link opens the item. */ -export async function notifySessionEnded( +export async function notifySystemError( env: NotificationEnv, userId: string, opts: ProjectNotificationOpts & { - sessionId?: string | null; + type: 'error' | 'cron_failure'; + ref: string; + title: string; + body: string; taskId?: string | null; - taskTitle?: string | null; + sessionId?: string | null; } ): Promise { - const title = opts.taskTitle - ? `Agent finished: ${truncate(opts.taskTitle, MAX_NOTIFICATION_TITLE_LENGTH)}` - : 'Agent finished — your turn'; - await sendNotification(env, userId, { - type: 'session_ended', - urgency: NOTIFICATION_TYPE_URGENCY.session_ended ?? 'medium', - title, - body: 'The agent has completed its turn. You can continue the conversation.', + type: opts.type, + urgency: NOTIFICATION_TYPE_URGENCY[opts.type] ?? 'high', + title: truncate(opts.title, MAX_NOTIFICATION_TITLE_LENGTH), + body: truncate(opts.body, MAX_NOTIFICATION_BODY_LENGTH), projectId: opts.projectId, - taskId: opts.taskId, - sessionId: opts.sessionId, - actionUrl: buildActionUrl(opts.projectId, opts.sessionId), - metadata: { - projectName: opts.projectName, - }, + taskId: opts.taskId ?? null, + sessionId: opts.sessionId ?? null, + actionUrl: buildInboxItemActionUrl(opts.projectId, opts.ref), + metadata: { projectName: opts.projectName, inboxRef: opts.ref }, }); } @@ -261,8 +275,14 @@ export async function notifyNeedsInput( options?: string[] | null; sessionId?: string | null; attentionMarkerId: string; + /** The ask's inbox item, when it has one: the notification opens it. */ + inboxRef?: string | null; /** Overrides the category label ("Review" for an inbox review item). */ label?: string; + /** Replaces "