release: charge credits per chat turn (#612)
Merged
SW
5mo ago+533+533+012345678901234567890123456789-79-79-01234567890123456789
Summary
Releases PR #612 from `test` โ `main`.
- Closes the silent revenue-loss gap: every successful chat workflow turn now atomically debits the account wallet AND records a `usage_events` audit row
- Refactors to consolidate billing into the existing `handleChatCredits` orchestrator (one path for both `/api/chat` and `/api/chat/workflow`)
- Switches `recordCreditDeduction` to the atomic `deduct_credits_with_audit` Postgres RPC (recoupable/database#26) โ eliminates wallet/meter drift for ALL callers, including the 3 research handlers
- Closes #605 chat-workflow billing gap
Test plan
- 3195 unit tests passing
- Lint / format / tsc clean
- E2E preview verification: wallet 998c โ 997c, audit row `PenhKC1lRbdzyRQjcaSH0` landed with correct fields (`source='api'`, `agent_type='main'`, `model_id='anthropic/claude-haiku-4.5'`, `credits_deducted_cents=1`)
- Post-merge: sanity check on `sandbox.recoupable.com` against `https://api.recoupable.com\` โ trigger a chat and confirm wallet drops
๐ค Generated with Claude Code
Summary by cubic
Charges credits for every successful chat workflow turn with an atomic wallet debit + audit, closing the chat-workflow billing gap. Consolidates billing for both /api/chat and /api/chat/workflow; closes #605.
-
New Features
- Atomic debit + audit via
deduct_credits_with_auditPostgres RPC for each turn (no wallet/meter drift). runAgentWorkflowpersists the assistant message, then bills usinghandleChatCreditswithaccountId, model, gateway cost, and token usage from message metadata.getCreditUsageaccepts a gateway-reported USD cost and short-circuits token math; 1ยข minimum still applies.- Source tagging on audit rows: workflow path uses
source="api"; streaming path defaults tosource="web".
- Atomic debit + audit via
-
Refactors
- Unified billing through
handleChatCreditsfor/api/chatand/api/chat/workflow. - Replaced
deductCredits + insertUsageEventwith a single RPC wrapper:lib/supabase/credits_usage/deductCreditsWithAudit. - Threaded validated
accountIdinto the workflow; updated tests and Supabase RPC types.
- Unified billing through