Re-point POST /api/chat/generate onto runAgentWorkflow + ephemeral key (chat#1813)

Merged
SW
5mo ago
+1155-772

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:

  1. Provisions a headless session + active sandbox (ensurePersonalRepo → insertSession → insertChat → connectSandbox → updateSession(active) → discoverSkills).
  2. 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's recoupAccessToken so the long-lived service key never enters model-issued bash.
  3. Builds the shared RunAgentWorkflowInput via buildRunAgentInput (#701) and start()s the run.
  4. 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's finally deletes it on run end (deleteEphemeralKeyStep).
  • The ~15m expires_at TTL (enforced in getApiKeyAccountId, 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), handleChatGenerate orchestration incl. start-failure key revocation (4), mintEphemeralAccountKey re-added (2), runAgentWorkflow ephemeral-key deletion on/off (2). Full lib/chat + lib/keys + app/lib/workflows suites green (571); tsc adds 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 } and Location: /api/chat/runs/{runId}.
    • GET /api/chat/runs/{runId}: returns { runId, status } normalized to queued|running|completed|failed|cancelled; 404 if unknown.
    • Ephemeral key: mints account-scoped recoup_sk_ via mintEphemeralAccountKey, injects as recoupAccessToken, threads ephemeralKeyId; workflow finally deletes it (deleteEphemeralKeyStep; ~15m TTL as backstop).
  • Refactors

    • Shared provisioning: extracted createSessionWithInitialChat and markSessionSandboxActive; used by headless runs, POST /api/sessions, and POST /api/sandbox (fixes rollback gap on chat insert failure).
    • Status handling: normalizeRunStatus split into its own module.
    • Keys: insertApiKey now writes expires_at for ephemeral keys.
    • Internal rename: lib/chat/generate → lib/chat/runs to match the /api/chat/runs route.

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 prompt or messages, 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.