Repository navigation
refactor(api): split tts, ai-token-budget and agent-loop (L3, pure move) - #2733
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… ai-monthly-cost-cap (L3, pure move) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gent-loop-streams (L3, pure move) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Important Review skippedAuto reviews are limited based on label configuration. 🏷️ Required labels (at least one): 1
Please check the settings in the CodeRabbit UI or the
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@coderabbitai review |
Action not completed
|
|
Coordinator review (self-host coordinator, task 01M7AF82KG9C78WAABTG3V1MN1)Reviewed head My own check, independent of the author's script: per split, every source line removed from the original file compared with every line added to it and its new sibling files, whitespace-normalised.
Main has moved since the base; its only change near these files is Relied on, not re-run by me: CI run 43611717050 (19 passed, 0 failed), the author's staging evidence (usage and budget APIs byte-identical before and after, budget cap enforced, a Project Agent chat through |



Pure reorganization slice of the self-host landing plan (L3). Draft until the self-host coordinator (task 01M7AF82KG9C78WAABTG3V1MN1) approves this head; the coordinator merges.
Summary
Self-host landing plan, slice L3 (idea
01M72M9AEB933ZY8269D376DKC, "LANDING PLAN (part 5 of 7)"): split three oversized API modules into smaller files. Pure moves, no behaviour change. File names and the split points match the integration branchsam/selfhost-pass-2, so later slices apply as small diffs. Every moved body is main's current code, not the integration branch's.apps/api/src/services/tts.tstts.ts436,tts-config.ts134 (TTSConfig,TTSEnvVars,getTTSConfig,retryWithBackoff),tts-text.ts273 (LLM cleanup and summary prompts,cleanTextForSpeech,summarizeTextForSpeech,hasMarkdown,fallbackStripMarkdown,splitTextIntoChunks)packages/ai-proxy/src/ai-token-budget.tsai-token-budget.ts462,ai-budget-settings.ts169 (AiBudgetLimits,getAiBudgetLimits,buildBudgetSettingsKey,get/save/deleteUserBudgetSettings,getAdminAiAllowance,validateBudgetUpdate),ai-monthly-cost-cap.ts62 (buildMonthlyCostCacheKey,getCachedMonthlyCost,checkMonthlyCostCap)apps/api/src/durable-objects/sam-session/agent-loop.tsagent-loop.ts271 (AgentLoopOptions,runAgentLoop),agent-loop-llm.ts197 (getAnthropicApiKey,DEFAULT_LLM_TIMEOUT_MS,callLLM,callAnthropicLLM,callWorkersAILLM),agent-loop-streams.ts230 (processAnthropicStream,processOpenAIStream)tts.tsandai-token-budget.tsre-export everything they used to export;agent-loop.tsexports are unchanged.packages/ai-proxy/src/index.tsand the apps/api shimapps/api/src/services/ai-token-budget.tsare not touched and still export the same names through./ai-token-budget.callLLM,processAnthropicStreamandprocessOpenAIStreamgained theexportkeyword, becauseagent-loop.tsnow imports them. They are not re-exported, so the module's public surface is unchanged.tts-text→tts-config;ai-monthly-cost-cap→ai-budget-settings; the original modules import the new ones, never the reverse.check-file-sizes.tsexemption list, so no exemption changes.Left out, and why
SpeechAudioSource,isSpeechEndpoint(tts);MONTHLY_COST_CAP_UNAVAILABLE_MESSAGE,MonthlyCostCapCheck,currentUtcMonthStart,getLocalMonthlyAiCostUsd(budget);callOpenAIChatLLM(agent loop). Main'scallWorkersAILLMmoves toagent-loop-llm.tswithcallLLM, its only caller (the integration branch replaced it withcallOpenAIChatLLM).Pure-move proof
The splits were produced mechanically: whole top-level statements (with their leading comments) were cut verbatim from main's text by a script. Only the import blocks, re-export blocks and new file header comments were written by hand. A separate proof script (
verify.cjs, scratch in.tmp/, not committed, like L2's) parsesgit show origin/main:<file>and the new files with the TypeScript compiler API. It matches each of main's top-level statements by name across the new files and compares the text after dropping indentation and blank lines, plus a leadingexporton the declaration line. It then diffs the line multisets old vs new.CLEANUP_INSTRUCTIONSandcleanTextForSpeechto NO. Changingnullto0ingetCachedMonthlyCostturned it to NO.exportkeywords above. For example,SAM_ANTHROPIC_VERSION,andparseToolInput,were removed from one import list and re-added in a single-line import in the file their caller moved to.tts
TTSConfigTTSEnvVarsgetTTSConfigretryWithBackoffCLEANUP_INSTRUCTIONSSUMMARY_INSTRUCTIONScleanTextForSpeechsummarizeTextForSpeechhasMarkdownfallbackStripMarkdownsplitTextIntoChunksgenerateSpeechAudioChunkgenerateSpeechAudioconcatenateArrayBuffersbuildR2KeybuildChunkR2KeysimpleHashaudioContentTypegetAudioFromR2storeAudioInR2TTSModeSynthesizeResultsynthesizeSpeechSymbols: 23, identical: 23. Statements in new files that are not on main: none
Lines removed and not re-added (0) / added that were not in the old file (41)
Removed:
Added:
ai-token-budget
TokenBudgetAiProviderUsageAttributionAiProviderUsageEntryAiTokenBudgetCounterStubAiBudgetLimitsPlatformDailyTokenLimitsbuildBudgetDateKeybuildBudgetKeygetBudgetCountergetAiBudgetLimitsparsePositiveIntegerEnvresolvePlatformDailyTokenLimitsgetTokenUsageFeatureTokenBudgetResultbuildFeatureBudgetKeyconsumeFeatureTokenBudgetreleaseFeatureTokenBudgetgetFeatureTokenBudgetbuildBudgetSettingsKeygetUserBudgetSettingssaveUserBudgetSettingsdeleteUserBudgetSettingsgetAdminAiAllowancevalidateBudgetUpdateresolveEffectiveLimitscheckTokenBudgetincrementTokenUsagebuildProviderUsageKeyincrementProviderUsagegetProviderUsageproviderUsageKeymergeProviderUsageEntryeachUtcDatebuildMonthlyCostCacheKeygetCachedMonthlyCostcheckMonthlyCostCapAiUsageGateResultcheckAiUsageGateSymbols: 38, identical: 38. Statements in new files that are not on main: none
Lines removed and not re-added (1) / added that were not in the old file (31)
Removed:
Added:
sam-session agent-loop
getAnthropicApiKeyDEFAULT_LLM_TIMEOUT_MScallLLMcallAnthropicLLMcallWorkersAILLMprocessAnthropicStreamprocessOpenAIStreamAgentLoopOptionsrunAgentLoopSymbols: 9, identical: 9. Statements in new files that are not on main: none
Lines removed and not re-added (5) / added that were not in the old file (26)
Removed:
Added:
Validation
pnpm lint(viapnpm check:fast, exit 0; eslint boundary rules included)pnpm typecheck(packages/ai-proxyandapps/api, afterturbo run build --filter=@simple-agent-manager/api^...in dependency order)pnpm test: fullapps/apivitest, JSON reportersuccess: true: 3,399 files, 15,177 tests, 15,173 passed, 4 skipped, 0 failed.packages/ai-proxy: 9 files, 140/140.project-agent-do5/5;vitest.sam-runtime.config.ts(sam-session-do,sam-grounding-runtime,sam-live-stream) 63/63.quality:file-sizespass.quality:ast-checks0 errors, 752 warnings, identical to main: the fourthrow-without-logwarnings that were inagent-loop.tsmoved with their code toagent-loop-llm.tsandagent-loop-streams.ts.Test edits: none. No test file is in the diff. No module-mock target had to follow a moved symbol, because every consumer, the in-package ai-proxy modules included, still imports through the original module. The two tests that mock
@simple-agent-manager/ai-proxy/internal/ai-token-budgetkeep intercepting exactly as before.Staging Verification (REQUIRED for all code changes — merge-blocking)
7fc3cdf0b6948aa246e72bd6bb4bb4975d874ef8. The Cloudflare deployments API showssam-api-stagingversion8ff3f517-0045-49b5-8ae4-c5bcad3bcb34at 100%, annotatedcommit:7fc3cdf0b6948aa246e72bd6bb4bb4975d874ef8(15:06:13Z).app.sammy.partyas the staging smoke user (token-login againstapi.sammy.party, one login reused), desktop 1280x800.Staging Verification Evidence
Staging window claimed on
feature.pr-shepherd-deps-20261111(TAKEN 14:59Z) after #2732's run finished and #2730 had released it. Smoke user, project Potato (01KWHD8XS7MQ7R6KWXJYRHDVH4). No pool, credential or configuration changes.Budget and usage page, same numbers before and after the deploy. The responses of
GET /api/usage/ai?period=current-month,?period=7d,/api/usage/ai/budgetand/api/usage/quotawere captured at 14:56Z and 15:00Z on the old Worker, and at 15:23Z on this head before any test traffic. All three snapshots are byte-identical JSON. The month shows $0.0472 across 44 requests, with the budget atisCustom:falseand effective limits of 500,000 input and 200,000 output tokens per day.Budget cap (
ai-budget-settings.ts,ai-monthly-cost-cap.ts):PUT /api/usage/ai/budget {monthlyCostCapUsd:-5}returned 400monthlyCostCapUsd must be between 0.01 and 10000(validateBudgetUpdate).{monthlyCostCapUsd:50}returned 200.GETthen showedisCustom:true, cap 50 andmonthlyCostPercent:0.1.checkAiUsageGate→checkMonthlyCostCap.DELETEreturned 200.GETafterwards showed settings,isCustomand effective limits identical to the baseline. Daily usage now shows 27,627 input and 299 output tokens, which is the metered agent turn.Agent loop (
agent-loop.ts,agent-loop-llm.ts,agent-loop-streams.ts). Project Agent chat at/projects/<id>/agent, the ProjectAgent DO callingrunAgentLoop. Prompt: list recent tasks with the project tools, answer in two sentences.POST /api/projects/<id>/agent/chatreturned 200 on Workers AI@cf/zai-org/glm-5.3-flash(4 model requests: three tool rounds plus the answer). SSE events:conversation_started1,tool_start3,tool_result3,text_delta7,done1, zeroerrorevents.Read-aloud (
tts.ts,tts-config.ts,tts-text.ts), on the VM runtime:01M7DANB7A96ZQN0WQB6VTANSB. It ran on node01M7DANKDKB7921VR9CS6TQCH9(runtime: vm, Hetzner cx33, created 15:26:29Z) and produced a ~2,600-character markdown answer with headings, a list and a code block.POST /api/tts/synthesize, which returned 200{"cached":false,"summarized":false}. ThenGET /api/tts/audio/15ebb1cf-…returned 200audio/mpeg, 840,960 bytes.0:03 / 2:20. The fresh synthesis (not cached) ran the LLM markdown cleanup, the chunking and the retry wrapper.SAM-mode note. The
/sampage could not be used.GET /api/sam/settingsreturns{"enabled":false,"available":true}for the shared smoke user, and enabling it would change shared account state, so I left it alone. That page runs the operator-turn agent, notrunAgentLoop. The legacy SamSession/chatrelay is closed with 409, sorunAgentLoopis reachable only through the Project Agent, which was tested above. The budget gate the operator agent shares (checkAiUsageGate) ran in the Project Agent turn.Cleanup. Conversation task closed with
POST …/tasks/<id>/close, which returned 200completedand removed the workspace (a laterDELETE/GETof the workspace returned 404).DELETE /api/nodes/<id>returned 200. D1 audit at 15:38:27Z and again at 15:42:28Z: the node row was absent, staging had 0 non-deleted nodes, the workspace row was absent, and the task wascompleted. The temporary budget cap was deleted, as described above. Staging FREE was published at 15:43Z. Staging keeps serving this head until the next deploy.UI Compliance Checklist (Required for UI changes)
N/A: no UI changes (
apps/web,packages/ui,packages/terminaluntouched).UI Screenshot Evidence
N/A: no UI changes.
End-to-End Verification (Required for multi-component changes)
POST /api/tts/synthesize(routes/tts.ts) →synthesizeSpeech(services/tts.ts) →cleanTextForSpeech/summarizeTextForSpeech/splitTextIntoChunks(tts-text.ts) →generateSpeechAudio→ R2. Project agent:POST /api/projects/:id/agent/chat→ ProjectAgent DO →runAgentLoop(agent-loop.ts) →checkAiUsageGate(ai-token-budget.ts→checkMonthlyCostCapinai-monthly-cost-cap.ts) →callLLM(agent-loop-llm.ts) →processAnthropicStream/processOpenAIStream(agent-loop-streams.ts)./samturns: SamSession operator agent →checkAiUsageGate. Budget page:GET/PUT/DELETE /api/usage/ai/budget→getUserBudgetSettings/validateBudgetUpdate/saveUserBudgetSettings/deleteUserBudgetSettings(ai-budget-settings.ts).Data Flow Trace
See the first checkbox above. Unchanged from main; only the file boundaries moved.
Untested Gaps
/samoperator turns were not run: SAM is disabled for the shared smoke user (enabled:false), see the staging note. Their shared budget gate ran through the Project Agent.@cf/zai-org/glm-5.3-flash: 4 new requests in/api/usage/ai, 17 → 21, one per loop round), socallLLM→callWorkersAILLM→processOpenAIStreamran live. The Anthropic branch (callAnthropicLLM,processAnthropicStream) did not run on staging. Its moved bodies are proven identical and are covered by the unchangedsam-runtimeWorkers suite and the agent-loop unit tests.tts.test.tssuites.Post-Mortem (Required for bug fix PRs)
N/A: not a bug fix.
What broke
N/A
Root cause
N/A
Class of bug
N/A
Why it wasn't caught
N/A
Process fix included in this PR
N/A
Post-mortem file
N/A
Specialist Review Evidence (Required for agent-authored PRs)
needs-human-reviewlabel added and merge deferred to human: N/A, every reviewer completed. The PR stays a draft as the coordinator's hold, per the dispatch brief.internal/*), no integration-branch leakage, headers accurate. LOW:ai-token-budget.tsboth imports and re-exportsgetUserBudgetSettings/checkMonthlyCostCap(needed, it uses them locally). No action.wrangler.tomlor entry change. New modules have no top-level side effects. Lazyimport('drizzle-orm/d1')preserved. AbortController and timeout unchanged. Same I/O per turn.internal/*export map is a wildcard, so it is unaffected. LOW: the three newly exported functions are not re-exported fromagent-loop.ts, as intended.CodeRabbit Review Evidence (Required for agent-authored PRs)
CodeRabbit Notes
Requested at 2026-11-14 15:43:49Z through the trusted
coderabbit-bot-review.ymlworkflow dispatch frommain(run 43611731845, success). The label route does not fire on drafts. CodeRabbit replied at 15:44:03Z with "Action not completed: Review rate limited". It had already posted "Review limit reached" when the draft opened at 15:00:58Z. No review had arrived by 16:03Z. Outcome: no CodeRabbit review, not re-triggered (rule 25).Exceptions (If any)
a6bd681e-26f2-4ea3-9483-7188edcf27d7, message01M7D5HFP5QSME6GJ08CFAF811), so the coordinator merges on its own review.Integration-branch contents beyond this pure move (input for the later AI slices)
tts-config.ts,tts-text.ts,agent-loop-streams.ts: byte-identical to this PR.tts.ts:SpeechAudioSource = Ai | SpeechEndpoint,isSpeechEndpoint, andsynthesizeWithEndpointfrom./speech-endpoints.generateSpeechAudioChunk,generateSpeechAudioandsynthesizeSpeechtakeSpeechAudioSource. The endpoint branch skips LLM cleanup, usesfallbackStripMarkdown, and truncates tochunkSize × (maxChunks − 1).ai-budget-settings.ts:MONTHLY_COST_CAP_UNAVAILABLE_MESSAGE, andvalidateBudgetUpdaterefuses a monthly cap whenisMonthlyCostCapAvailable(env)is false.ai-monthly-cost-cap.ts:checkMonthlyCostCap(kv, userId, env)returnsMonthlyCostCapCheckwithenforced. It adds local metering throughgetLocalMonthlyAiCostUsd(sumsgetProviderUsagefrom month start, which creates a cycle withai-token-budget.ts) and fails closed on a read error. A gateway without the account API reportsenforced: false.ai-token-budget.ts: re-exports the symbols above, andcheckAiUsageGatepassesenvtocheckMonthlyCostCap. The packageindex.tsthere also exportsai-cost-pricing,ai-gateway-availabilityandai-model-usage, plusbuildBudgetKeyandestimateTokensFromText.agent-loop-llm.ts:callLLM(..., endpoint)routes an admin-configured OpenAI-compatible endpoint first (services/llm-chat-target.ts).callOpenAIChatLLMreplacescallWorkersAILLM(Workers AI throughresolveCloudflareWorkersAiTarget,LlmUnavailableError). Anthropic headers go throughaiGatewayOnlyHeaders.agent-loop.ts: resolvesresolveOpenAICompatibleTarget(env, 'agent', model), and onLlmUnavailableErroremits a clear error event. It passesestimateMissingUsageandcostModelIdto accounting, and logs upstream errors with the sanitizedupstreamErrorLogFieldsinstead of a 500-char body slice.Agent Preflight (Required)
Classification
External References
N/A: no external API or library behaviour involved. TypeScript ES module re-exports (
export { … } from) and hoisted function declarations behave the same as the inline definitions for every consumer.Codebase Impact Analysis
Touched:
apps/api/src/services/tts.ts(+ newtts-config.ts,tts-text.ts),packages/ai-proxy/src/ai-token-budget.ts(+ newai-budget-settings.ts,ai-monthly-cost-cap.ts),apps/api/src/durable-objects/sam-session/agent-loop.ts(+ newagent-loop-llm.ts,agent-loop-streams.ts), task file. Consumers:routes/tts.ts; every importer of@simple-agent-manager/ai-proxybudget functions (AI proxy routes, usage routes, operations, platform trial, SamSession operator agent); SamSession and ProjectAgent DOs (runAgentLoop). None of them changed imports. No open PR touches these files (coordinator check, November 14).Documentation & Specs
N/A: no docs, rules or specs describe these modules' internal layout (searched
apps/www/src/content/docs,docs/,.claude/rules,apps/api/.claude,AGENTS.md,CLAUDE.md). The one hit,.claude/rules/18-file-size-limits.md, usestts.ts→tts-voices.tsonly as an illustrative split example, so it is left as is.Constitution & Risk Check
Principle X (simplicity): pure move into the integration branch's existing layout, no new abstraction. Principle XI: no values added or changed. Risk: TTS, AI budget gating and agent-loop paths. Mitigated by the mechanical proof, an unchanged full test suite with zero test edits, and live staging checks.
Head:
dc1e475e4cf940c7a2947b365e56d8fb51d2e3cb. Staging ran on7fc3cdf0b6948aa246e72bd6bb4bb4975d874ef8; the only commit after it touches the task file (git diff --stat 7fc3cdf0b dc1e475e4lists onlytasks/active/2026-11-14-l3-api-pure-splits.md).🤖 Generated with Claude Code