Re-point POST /api/chat/generate onto runAgentWorkflow + ephemeral key (chat#1813)
Merged
SW
5mo ago+1155+1155+0123456789012345678901234567890123456789-772-772-012345678901234567890123456789
PR 2 (api, the keystone) of the async chat-generation migration tracked in recoupable/chat#1813. Fulfills the contract in docs#249. Merge order: docs#249 → this.
What
POST /api/chat/generate is re-pointed from the synchronous legacy ToolLoopAgent onto the same durable runAgentWorkflow that powers interactive /api/chat. It now:
- Provisions a headless session + active sandbox (
ensurePersonalRepo→insertSession→insertChat→connectSandbox→updateSession(active) →discoverSkills). - Mints a short-lived, account-scoped
recoup_sk_key (mintEphemeralAccountKey, re-added from the deferred half of #700 — minting now has its only consumer), injected as the agent'srecoupAccessTokenso the long-lived service key never enters model-issued bash. - Builds the shared
RunAgentWorkflowInputviabuildRunAgentInput(#701) andstart()s the run. - Returns
{ runId }with 202 immediately — generation, assistant-message persistence, the credit charge, and key revocation happen server-side inside the workflow.
Ephemeral key lifecycle
- Threaded as
agentContext.ephemeralKeyId;runAgentWorkflow'sfinallydeletes it on run end (deleteEphemeralKeyStep). - The ~15m
expires_atTTL (enforced ingetApiKeyAccountId, shipped in #700) is the defense-in-depth backstop. - If the run fails to start, the handler revokes the key directly (the workflow never ran).
Tests (TDD, red→green)
validateGenerateRequest(5),handleChatGenerateorchestration incl. start-failure key revocation (4),mintEphemeralAccountKeyre-added (2),runAgentWorkflowephemeral-key deletion on/off (2). Fulllib/chat+lib/keys+app/lib/workflowssuites green (571);tscadds 0 new errors.- Preview verification (full scheduled flow → 202 → workflow run → persisted assistant message) posted as a comment once the deployment is Ready.
Notes
- The legacy generate helpers (
setupChatRequest,getGeneralAgent,saveChatCompletion, MCP+Composio tool wiring) are now unused by this path; left in place to keep the diff focused — a follow-up can remove any that are fully orphaned. - Composio tools are dropped for scheduled generation (accepted tradeoff, per the issue).
🤖 Generated with Claude Code
Summary by cubic
Re-pointed chat generation onto the durable runAgentWorkflow and shipped async runs via POST /api/chat/runs with a status endpoint at GET /api/chat/runs/{runId}. Each run provisions its own session and active sandbox, mints a short-lived account key, and revokes it when the workflow ends.
-
New Features
POST /api/chat/runs(replaces and removes/api/chat/generate): provisions session + chat, connects an active sandbox, discovers skills, starts the workflow, and returns 202 with{ runId, chatId, sessionId }andLocation: /api/chat/runs/{runId}.GET /api/chat/runs/{runId}: returns{ runId, status }normalized toqueued|running|completed|failed|cancelled; 404 if unknown.- Ephemeral key: mints account-scoped
recoup_sk_viamintEphemeralAccountKey, injects asrecoupAccessToken, threadsephemeralKeyId; workflowfinallydeletes it (deleteEphemeralKeyStep; ~15m TTL as backstop).
-
Refactors
- Shared provisioning: extracted
createSessionWithInitialChatandmarkSessionSandboxActive; used by headless runs,POST /api/sessions, andPOST /api/sandbox(fixes rollback gap on chat insert failure). - Status handling:
normalizeRunStatussplit into its own module. - Keys:
insertApiKeynow writesexpires_atfor ephemeral keys. - Internal rename:
lib/chat/generate→lib/chat/runsto match the/api/chat/runsroute.
- Shared provisioning: extracted
Summary by CodeRabbit
-
New Features
- Added async chat run support that starts generation jobs and returns a run ID, chat ID, and session ID.
- Added a chat run status endpoint for polling run lifecycle (e.g., queued/running/completed/failed/cancelled).
- Added headless request validation supporting either
promptormessages, plus model selection.
-
Bug Fixes
- Improved revocation of short-lived API keys by ensuring cleanup runs reliably when workflows finish.
- Hardened session/sandbox activation and generation session provisioning with safer fallbacks on discovery failures.
-
Refactor
- Centralized session provisioning and initial chat creation to reduce inconsistencies and orphaned-session edge cases.