Skip to content

refactor(api): split tts, ai-token-budget and agent-loop (L3, pure move) - #2733

Merged
simple-agent-manager[bot] merged 6 commits into
mainfrom
sam/task-l3-second-dispatch-g8a53v
Nov 14, 2026
Merged

simple-agent-manager[bot] merged 6 commits into
mainfrom
sam/task-l3-second-dispatch-g8a53v

Conversation

@simple-agent-manager

@simple-agent-manager simple-agent-manager Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

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 branch sam/selfhost-pass-2, so later slices apply as small diffs. Every moved body is main's current code, not the integration branch's.

Split Before After
apps/api/src/services/tts.ts 799 lines tts.ts 436, tts-config.ts 134 (TTSConfig, TTSEnvVars, getTTSConfig, retryWithBackoff), tts-text.ts 273 (LLM cleanup and summary prompts, cleanTextForSpeech, summarizeTextForSpeech, hasMarkdown, fallbackStripMarkdown, splitTextIntoChunks)
packages/ai-proxy/src/ai-token-budget.ts 660 lines ai-token-budget.ts 462, ai-budget-settings.ts 169 (AiBudgetLimits, getAiBudgetLimits, buildBudgetSettingsKey, get/save/deleteUserBudgetSettings, getAdminAiAllowance, validateBudgetUpdate), ai-monthly-cost-cap.ts 62 (buildMonthlyCostCacheKey, getCachedMonthlyCost, checkMonthlyCostCap)
apps/api/src/durable-objects/sam-session/agent-loop.ts 676 lines agent-loop.ts 271 (AgentLoopOptions, runAgentLoop), agent-loop-llm.ts 197 (getAnthropicApiKey, DEFAULT_LLM_TIMEOUT_MS, callLLM, callAnthropicLLM, callWorkersAILLM), agent-loop-streams.ts 230 (processAnthropicStream, processOpenAIStream)
  • Every previous import path keeps working: tts.ts and ai-token-budget.ts re-export everything they used to export; agent-loop.ts exports are unchanged. packages/ai-proxy/src/index.ts and the apps/api shim apps/api/src/services/ai-token-budget.ts are not touched and still export the same names through ./ai-token-budget.
  • The only edit inside a moved declaration: callLLM, processAnthropicStream and processOpenAIStream gained the export keyword, because agent-loop.ts now imports them. They are not re-exported, so the module's public surface is unchanged.
  • No import cycles: tts-text → tts-config; ai-monthly-cost-cap → ai-budget-settings; the original modules import the new ones, never the reverse.
  • All nine files are under 500 lines. None of the three originals was on the check-file-sizes.ts exemption list, so no exemption changes.

Left out, and why

  • gitlab → gitlab-access-token: obsolete. Main rewrote the token helpers and the integration branch deleted its file as stale (coordinator finding).
  • Integration-only symbols that do not exist on main stay out: SpeechAudioSource, isSpeechEndpoint (tts); MONTHLY_COST_CAP_UNAVAILABLE_MESSAGE, MonthlyCostCapCheck, currentUtcMonthStart, getLocalMonthlyAiCostUsd (budget); callOpenAIChatLLM (agent loop). Main's callWorkersAILLM moves to agent-loop-llm.ts with callLLM, its only caller (the integration branch replaced it with callOpenAIChatLLM).
  • Every new file still has coherent content, so no split was skipped.

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) parses git 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 leading export on the declaration line. It then diffs the line multisets old vs new.

  • tts: 23 of 23 identical. ai-token-budget: 38 of 38. agent-loop: 9 of 9. New top-level statements that are not on main: none.
  • Shown to discriminate: a one-word change inside a moved prompt string turned CLEANUP_INSTRUCTIONS and cleanTextForSpeech to NO. Changing null to 0 in getCachedMonthlyCost turned it to NO.
  • The removed and added line lists contain only import lines, re-export lines, header comments, and the three export keywords above. For example, SAM_ANTHROPIC_VERSION, and parseToolInput, were removed from one import list and re-added in a single-line import in the file their caller moved to.

tts

Symbol Old location New location Identical
TTSConfig tts.ts tts-config.ts yes
TTSEnvVars tts.ts tts-config.ts yes
getTTSConfig tts.ts tts-config.ts yes
retryWithBackoff tts.ts tts-config.ts yes
CLEANUP_INSTRUCTIONS tts.ts tts-text.ts yes
SUMMARY_INSTRUCTIONS tts.ts tts-text.ts yes
cleanTextForSpeech tts.ts tts-text.ts yes
summarizeTextForSpeech tts.ts tts-text.ts yes
hasMarkdown tts.ts tts-text.ts yes
fallbackStripMarkdown tts.ts tts-text.ts yes
splitTextIntoChunks tts.ts tts-text.ts yes
generateSpeechAudioChunk tts.ts tts.ts yes
generateSpeechAudio tts.ts tts.ts yes
concatenateArrayBuffers tts.ts tts.ts yes
buildR2Key tts.ts tts.ts yes
buildChunkR2Key tts.ts tts.ts yes
simpleHash tts.ts tts.ts yes
audioContentType tts.ts tts.ts yes
getAudioFromR2 tts.ts tts.ts yes
storeAudioInR2 tts.ts tts.ts yes
TTSMode tts.ts tts.ts yes
SynthesizeResult tts.ts tts.ts yes
synthesizeSpeech tts.ts tts.ts yes

Symbols: 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:

/**
/**
*/
*/
import {
import {
DEFAULT_TTS_CHUNK_SIZE,
DEFAULT_TTS_CHUNK_SIZE,
DEFAULT_TTS_ENCODING,
DEFAULT_TTS_MAX_CHUNKS,
DEFAULT_TTS_MAX_TEXT_LENGTH,
DEFAULT_TTS_MODEL,
DEFAULT_TTS_R2_PREFIX,
DEFAULT_TTS_RETRY_ATTEMPTS,
DEFAULT_TTS_RETRY_ATTEMPTS,
DEFAULT_TTS_RETRY_BASE_DELAY_MS,
DEFAULT_TTS_RETRY_BASE_DELAY_MS,
DEFAULT_TTS_SPEAKER,
DEFAULT_TTS_SUMMARY_THRESHOLD,
DEFAULT_TTS_TIMEOUT_MS,
} from '@simple-agent-manager/shared';
} from '@simple-agent-manager/shared';
import { log } from '../lib/logger';
import { log } from '../lib/logger';
import { retryWithBackoff, type TTSConfig } from './tts-config';
import { retryWithBackoff, type TTSConfig } from './tts-config';
import { cleanTextForSpeech, splitTextIntoChunks, summarizeTextForSpeech } from './tts-text';
export { getTTSConfig, retryWithBackoff, type TTSConfig, type TTSEnvVars } from './tts-config';
export {
cleanTextForSpeech,
fallbackStripMarkdown,
splitTextIntoChunks,
summarizeTextForSpeech,
} from './tts-text';
* TTS configuration (env → TTSConfig) and the retry helper shared by the TTS pipeline.
* Split from tts.ts by size; consumers import through tts.ts.
* Split from tts.ts by size; consumers import through tts.ts.
DEFAULT_TTS_CLEANUP_MAX_TOKENS,
DEFAULT_TTS_CLEANUP_MODEL,
DEFAULT_TTS_CLEANUP_TIMEOUT_MS,
* Text preparation for TTS: LLM markdown cleanup, LLM summary, regex fallback and chunking.

ai-token-budget

Symbol Old location New location Identical
TokenBudget ai-token-budget.ts ai-token-budget.ts yes
AiProviderUsageAttribution ai-token-budget.ts ai-token-budget.ts yes
AiProviderUsageEntry ai-token-budget.ts ai-token-budget.ts yes
AiTokenBudgetCounterStub ai-token-budget.ts ai-token-budget.ts yes
AiBudgetLimits ai-token-budget.ts ai-budget-settings.ts yes
PlatformDailyTokenLimits ai-token-budget.ts ai-token-budget.ts yes
buildBudgetDateKey ai-token-budget.ts ai-token-budget.ts yes
buildBudgetKey ai-token-budget.ts ai-token-budget.ts yes
getBudgetCounter ai-token-budget.ts ai-token-budget.ts yes
getAiBudgetLimits ai-token-budget.ts ai-budget-settings.ts yes
parsePositiveIntegerEnv ai-token-budget.ts ai-token-budget.ts yes
resolvePlatformDailyTokenLimits ai-token-budget.ts ai-token-budget.ts yes
getTokenUsage ai-token-budget.ts ai-token-budget.ts yes
FeatureTokenBudgetResult ai-token-budget.ts ai-token-budget.ts yes
buildFeatureBudgetKey ai-token-budget.ts ai-token-budget.ts yes
consumeFeatureTokenBudget ai-token-budget.ts ai-token-budget.ts yes
releaseFeatureTokenBudget ai-token-budget.ts ai-token-budget.ts yes
getFeatureTokenBudget ai-token-budget.ts ai-token-budget.ts yes
buildBudgetSettingsKey ai-token-budget.ts ai-budget-settings.ts yes
getUserBudgetSettings ai-token-budget.ts ai-budget-settings.ts yes
saveUserBudgetSettings ai-token-budget.ts ai-budget-settings.ts yes
deleteUserBudgetSettings ai-token-budget.ts ai-budget-settings.ts yes
getAdminAiAllowance ai-token-budget.ts ai-budget-settings.ts yes
validateBudgetUpdate ai-token-budget.ts ai-budget-settings.ts yes
resolveEffectiveLimits ai-token-budget.ts ai-token-budget.ts yes
checkTokenBudget ai-token-budget.ts ai-token-budget.ts yes
incrementTokenUsage ai-token-budget.ts ai-token-budget.ts yes
buildProviderUsageKey ai-token-budget.ts ai-token-budget.ts yes
incrementProviderUsage ai-token-budget.ts ai-token-budget.ts yes
getProviderUsage ai-token-budget.ts ai-token-budget.ts yes
providerUsageKey ai-token-budget.ts ai-token-budget.ts yes
mergeProviderUsageEntry ai-token-budget.ts ai-token-budget.ts yes
eachUtcDate ai-token-budget.ts ai-token-budget.ts yes
buildMonthlyCostCacheKey ai-token-budget.ts ai-monthly-cost-cap.ts yes
getCachedMonthlyCost ai-token-budget.ts ai-monthly-cost-cap.ts yes
checkMonthlyCostCap ai-token-budget.ts ai-monthly-cost-cap.ts yes
AiUsageGateResult ai-token-budget.ts ai-token-budget.ts yes
checkAiUsageGate ai-token-budget.ts ai-token-budget.ts yes

Symbols: 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:

AI_MONTHLY_COST_CACHE_KV_PREFIX,

Added:

/**
/**
*/
*/
import type { UserAiBudgetSettings } from '@simple-agent-manager/shared';
import {
} from '@simple-agent-manager/shared';
import { getUserBudgetSettings } from './ai-budget-settings';
import { getUserBudgetSettings } from './ai-budget-settings';
import { checkMonthlyCostCap } from './ai-monthly-cost-cap';
import type { AiProxyEnv } from './env';
export {
export {
type AiBudgetLimits,
buildBudgetSettingsKey,
deleteUserBudgetSettings,
getAdminAiAllowance,
getAiBudgetLimits,
getUserBudgetSettings,
saveUserBudgetSettings,
validateBudgetUpdate,
} from './ai-budget-settings';
buildMonthlyCostCacheKey,
checkMonthlyCostCap,
getCachedMonthlyCost,
} from './ai-monthly-cost-cap';
* AI budget limits and per-user budget settings (KV-stored), split out of ai-token-budget.ts
* (rule 18). ai-token-budget.ts re-exports everything here, so callers keep their imports.
* Monthly AI cost cap enforcement, split out of ai-token-budget.ts (rule 18).
* ai-token-budget.ts re-exports everything here, so callers keep their imports.
import { AI_MONTHLY_COST_CACHE_KV_PREFIX } from '@simple-agent-manager/shared';

sam-session agent-loop

Symbol Old location New location Identical
getAnthropicApiKey agent-loop.ts agent-loop-llm.ts yes
DEFAULT_LLM_TIMEOUT_MS agent-loop.ts agent-loop-llm.ts yes
callLLM agent-loop.ts agent-loop-llm.ts yes
callAnthropicLLM agent-loop.ts agent-loop-llm.ts yes
callWorkersAILLM agent-loop.ts agent-loop-llm.ts yes
processAnthropicStream agent-loop.ts agent-loop-streams.ts yes
processOpenAIStream agent-loop.ts agent-loop-streams.ts yes
AgentLoopOptions agent-loop.ts agent-loop.ts yes
runAgentLoop agent-loop.ts agent-loop.ts yes

Symbols: 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:

SAM_ANTHROPIC_VERSION,
parseToolInput,
async function callLLM(
async function processAnthropicStream(
async function processOpenAIStream(

Added:

/**
/**
*
*/
*/
import {
import type { Env } from '../../env';
import { expectJsonRecord } from '../../lib/runtime-validation';
isAnthropicModel,
isWorkersAIModel,
} from './agent-loop-helpers';
import { callLLM } from './agent-loop-llm';
import { processAnthropicStream, processOpenAIStream } from './agent-loop-streams';
import type { OpenAIMessage } from './payload-size';
* The model call for one agent-loop turn, split out of agent-loop.ts (rule 18).
* Route by model prefix: claude-* to Anthropic (translated at the boundary), @cf/* and @hf/* to
* Workers AI, both through AI Gateway.
import { SAM_ANTHROPIC_VERSION, type SamConfig } from '@simple-agent-manager/shared';
import type { AnthropicToolDef } from './types';
export async function callLLM(
* Model stream parsers for the agent loop, split out of agent-loop.ts (rule 18): each turns one
* upstream SSE stream into SAM SSE events on the writer and collects the turn's tool calls.
import { encodeSseEvent, parseToolInput } from './agent-loop-helpers';
import type { CollectedToolCall } from './types';
export async function processAnthropicStream(
export async function processOpenAIStream(

Validation

  • pnpm lint (via pnpm check:fast, exit 0; eslint boundary rules included)
  • pnpm typecheck (packages/ai-proxy and apps/api, after turbo run build --filter=@simple-agent-manager/api^... in dependency order)
  • pnpm test: full apps/api vitest, JSON reporter success: true: 3,399 files, 15,177 tests, 15,173 passed, 4 skipped, 0 failed. packages/ai-proxy: 9 files, 140/140.
  • Additional validation: Workers runtime project-agent-do 5/5; vitest.sam-runtime.config.ts (sam-session-do, sam-grounding-runtime, sam-live-stream) 63/63. quality:file-sizes pass. quality:ast-checks 0 errors, 752 warnings, identical to main: the four throw-without-log warnings that were in agent-loop.ts moved with their code to agent-loop-llm.ts and agent-loop-streams.ts.
  • N/A: no sweep, cron or alarm candidate selection changed

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-budget keep intercepting exactly as before.

Staging Verification (REQUIRED for all code changes — merge-blocking)

  • Staging deployment green: Deploy Staging 43607690743 succeeded, including smoke tests (15:23:31Z), for exact head 7fc3cdf0b6948aa246e72bd6bb4bb4975d874ef8. The Cloudflare deployments API shows sam-api-staging version 8ff3f517-0045-49b5-8ae4-c5bcad3bcb34 at 100%, annotated commit:7fc3cdf0b6948aa246e72bd6bb4bb4975d874ef8 (15:06:13Z).
  • Live app verified via Playwright: signed in to app.sammy.party as the staging smoke user (token-login against api.sammy.party, one login reused), desktop 1280x800.
  • Existing workflows confirmed working: project chat list and conversation, Project Agent page, settings usage APIs. No browser console errors were reported during the verification runs.
  • New feature/fix verified on staging: every moved path exercised, details below.
  • Infrastructure verification completed: N/A, no infra change. One real VM was still provisioned, used and deleted.
  • Mobile and desktop verification notes added for UI changes: N/A, no UI changes.

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/budget and /api/usage/quota were 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 at isCustom:false and 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 400 monthlyCostCapUsd must be between 0.01 and 10000 (validateBudgetUpdate).
  • {monthlyCostCapUsd:50} returned 200. GET then showed isCustom:true, cap 50 and monthlyCostPercent:0.1.
  • With the cap active, the agent turn below passed checkAiUsageGate → checkMonthlyCostCap.
  • DELETE returned 200. GET afterwards showed settings, isCustom and 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 calling runAgentLoop. Prompt: list recent tasks with the project tools, answer in two sentences.

  • POST /api/projects/<id>/agent/chat returned 200 on Workers AI @cf/zai-org/glm-5.3-flash (4 model requests: three tool rounds plus the answer). SSE events: conversation_started 1, tool_start 3, tool_result 3, text_delta 7, done 1, zero error events.
  • Rendered answer: "I found 20 tasks (the search tool's per-call maximum)… The newest one, last updated 2026-11-14 10:27 UTC, is 'Reply with exactly the word OK…'".

Read-aloud (tts.ts, tts-config.ts, tts-text.ts), on the VM runtime:

  • Setup: a conversation task with the Potato "Conversation profile" (Claude Code, default runtime), 01M7DANB7A96ZQN0WQB6VTANSB. It ran on node 01M7DANKDKB7921VR9CS6TQCH9 (runtime: vm, Hetzner cx33, created 15:26:29Z) and produced a ~2,600-character markdown answer with headings, a list and a code block.
  • Clicking Read aloud on that message sent POST /api/tts/synthesize, which returned 200 {"cached":false,"summarized":false}. Then GET /api/tts/audio/15ebb1cf-… returned 200 audio/mpeg, 840,960 bytes.
  • The global player was playing: pause control shown, 0:03 / 2:20. The fresh synthesis (not cached) ran the LLM markdown cleanup, the chunking and the retry wrapper.

SAM-mode note. The /sam page could not be used. GET /api/sam/settings returns {"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, not runAgentLoop. The legacy SamSession /chat relay is closed with 409, so runAgentLoop is 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 200 completed and removed the workspace (a later DELETE/GET of 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 was completed. 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/terminal untouched).

UI Screenshot Evidence

N/A: no UI changes.

End-to-End Verification (Required for multi-component changes)

  • Data flow traced. Read-aloud: 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 → checkMonthlyCostCap in ai-monthly-cost-cap.ts) → callLLM (agent-loop-llm.ts) → processAnthropicStream/processOpenAIStream (agent-loop-streams.ts). /sam turns: SamSession operator agent → checkAiUsageGate. Budget page: GET/PUT/DELETE /api/usage/ai/budget → getUserBudgetSettings/validateBudgetUpdate/saveUserBudgetSettings/deleteUserBudgetSettings (ai-budget-settings.ts).
  • Capability tests: the existing route- and DO-level suites above run unchanged through the original import paths.
  • Behaviour claims checked by running the mechanical comparison, not by reading.
  • Live staging run (see Staging Verification)

Data Flow Trace

See the first checkbox above. Unchanged from main; only the file boundaries moved.

Untested Gaps

  • /sam operator 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.
  • Staging's Project Agent ran on Workers AI (@cf/zai-org/glm-5.3-flash: 4 new requests in /api/usage/ai, 17 → 21, one per loop round), so callLLM → callWorkersAILLM → processOpenAIStream ran live. The Anthropic branch (callAnthropicLLM, processAnthropicStream) did not run on staging. Its moved bodies are proven identical and are covered by the unchanged sam-runtime Workers suite and the agent-loop unit tests.
  • The TTS summary path (texts above the summary threshold) was not triggered live; it is covered by the unchanged tts.test.ts suites.

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)

  • All local reviewers completed and findings addressed before merge
  • If any reviewer did NOT complete: needs-human-review label 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.
Reviewer Status Outcome
architecture-reviewer PASS Splits coherent, acyclic, no logic or signature changes, all export paths resolve (package entry, apps/api shim, internal/*), no integration-branch leakage, headers accurate. LOW: ai-token-budget.ts both imports and re-exports getUserBudgetSettings/checkMonthlyCostCap (needed, it uses them locally). No action.
cloudflare-specialist PASS No DO class, RPC, binding, wrangler.toml or entry change. New modules have no top-level side effects. Lazy import('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 from agent-loop.ts, as intended.
task-completion-validator PASS Reran the proof (70/70); export lists diffed main vs head; no test files changed; logs verified. LOW: moved code is covered indirectly through the original modules, which is adequate for a pure move. Staging plan sharpened, and followed: a long markdown read-aloud, a tool-call agent prompt, budget numbers compared before and after.

CodeRabbit Review Evidence (Required for agent-authored PRs)

  • CodeRabbit requested after local review, staging if applicable, and CI gates passed
  • Waited about 15 minutes
  • Either CodeRabbit reviewed and no CodeRabbit feedback is unresolved, or it did not review and the observed outcome is recorded below

CodeRabbit Notes

Requested at 2026-11-14 15:43:49Z through the trusted coderabbit-bot-review.yml workflow dispatch from main (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)

  • Scope: the PR stays a draft and is not merged by its author. The task file lives on this branch instead of a direct-to-main task commit.
  • Rationale: dispatch brief and Raphaël's rule of November 8, 2026: dispatched agents keep the PR a draft until the coordinator approves the exact head. Raphaël waived his own per-PR approval for pure reorganization on November 14, 2026 (chat a6bd681e-26f2-4ea3-9483-7188edcf27d7, message 01M7D5HFP5QSME6GJ08CFAF811), so the coordinator merges on its own review.
  • Expiration: when the coordinator approves and merges this head.

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, and synthesizeWithEndpoint from ./speech-endpoints. generateSpeechAudioChunk, generateSpeechAudio and synthesizeSpeech take SpeechAudioSource. The endpoint branch skips LLM cleanup, uses fallbackStripMarkdown, and truncates to chunkSize × (maxChunks − 1).
  • ai-budget-settings.ts: MONTHLY_COST_CAP_UNAVAILABLE_MESSAGE, and validateBudgetUpdate refuses a monthly cap when isMonthlyCostCapAvailable(env) is false.
  • ai-monthly-cost-cap.ts: checkMonthlyCostCap(kv, userId, env) returns MonthlyCostCapCheck with enforced. It adds local metering through getLocalMonthlyAiCostUsd (sums getProviderUsage from month start, which creates a cycle with ai-token-budget.ts) and fails closed on a read error. A gateway without the account API reports enforced: false.
  • ai-token-budget.ts: re-exports the symbols above, and checkAiUsageGate passes env to checkMonthlyCostCap. The package index.ts there also exports ai-cost-pricing, ai-gateway-availability and ai-model-usage, plus buildBudgetKey and estimateTokensFromText.
  • agent-loop-llm.ts: callLLM(..., endpoint) routes an admin-configured OpenAI-compatible endpoint first (services/llm-chat-target.ts). callOpenAIChatLLM replaces callWorkersAILLM (Workers AI through resolveCloudflareWorkersAiTarget, LlmUnavailableError). Anthropic headers go through aiGatewayOnlyHeaders.
  • agent-loop.ts: resolves resolveOpenAICompatibleTarget(env, 'agent', model), and on LlmUnavailableError emits a clear error event. It passes estimateMissingUsage and costModelId to accounting, and logs upstream errors with the sanitized upstreamErrorLogFields instead of a 500-char body slice.

Agent Preflight (Required)

  • Preflight completed before code changes

Classification

  • external-api-change
  • cross-component-change
  • business-logic-change
  • public-surface-change
  • docs-sync-change
  • security-sensitive-change
  • ui-change
  • infra-change

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 (+ new tts-config.ts, tts-text.ts), packages/ai-proxy/src/ai-token-budget.ts (+ new ai-budget-settings.ts, ai-monthly-cost-cap.ts), apps/api/src/durable-objects/sam-session/agent-loop.ts (+ new agent-loop-llm.ts, agent-loop-streams.ts), task file. Consumers: routes/tts.ts; every importer of @simple-agent-manager/ai-proxy budget 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, uses tts.ts → tts-voices.ts only 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 on 7fc3cdf0b6948aa246e72bd6bb4bb4975d874ef8; the only commit after it touches the task file (git diff --stat 7fc3cdf0b dc1e475e4 lists only tasks/active/2026-11-14-l3-api-pure-splits.md).

🤖 Generated with Claude Code

raphaeltm and others added 5 commits November 14, 2026 14:37
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>
@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are limited based on label configuration.

🏷️ Required labels (at least one): 1

  • coderabbit-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sonarqubecloud

Copy link
Copy Markdown

@simple-agent-manager

Copy link
Copy Markdown
Contributor Author

Coordinator review (self-host coordinator, task 01M7AF82KG9C78WAABTG3V1MN1)

Reviewed head dc1e475e4cf940c7a2947b365e56d8fb51d2e3cb (base a7d05239d). No findings. Approved; merging on coordinator review. Authority: Raphaël, November 14, 2026, chat session a6bd681e-26f2-4ea3-9483-7188edcf27d7, message 01M7D5HFP5QSME6GJ08CFAF811: slices that only reorganize code with identical behaviour do not need his approval.

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.

  • tts (tts.ts to tts.ts + tts-config.ts + tts-text.ts): 330 removed, all re-added. The only new lines are import and re-export name lists and comments.
  • ai-token-budget (packages/ai-proxy): 193 removed; the single line not re-added is an import name that moved with its user. New lines are import and re-export name lists and comments.
  • agent-loop: 369 removed; the five not re-added are two import names and the three function headers that gained the export keyword (callLLM, processAnthropicStream, processOpenAIStream). No logic line differs.
  • Outside the three splits the diff contains only the task file.

Main has moved since the base; its only change near these files is sam-session/tools/retry-subtask.ts, which this PR does not touch.

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 runAgentLoop, read-aloud audio on a VM-runtime message, cleanup) and the three specialist reviews. Not exercised live, as the author states: the Anthropic branch of the agent loop and the /sam page. CodeRabbit was requested and answered that it was rate limited.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant