From 139dfe23d1ed3af322755a5f09609144dacf4e47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sat, 14 Nov 2026 14:37:56 +0000 Subject: [PATCH 1/6] task: add L3 API pure splits task file Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-14-l3-api-pure-splits.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 tasks/active/2026-11-14-l3-api-pure-splits.md diff --git a/tasks/active/2026-11-14-l3-api-pure-splits.md b/tasks/active/2026-11-14-l3-api-pure-splits.md new file mode 100644 index 0000000000..1c1a4aa32a --- /dev/null +++ b/tasks/active/2026-11-14-l3-api-pure-splits.md @@ -0,0 +1,53 @@ +# L3: API pure splits (tts, ai-token-budget, sam-session agent-loop) + +Self-host landing plan slice L3 (idea `01M72M9AEB933ZY8269D376DKC`, "LANDING PLAN (part 5 of 7)"). +Dispatched by coordinator task `01M7AF82KG9C78WAABTG3V1MN1`; this is the second dispatch (the first, +`01M7D749D4H9WPJCC4TWX1ZWG1`, failed at workspace build with no work done). Draft PR, coordinator merges. + +## Problem + +Three modules on main exceed the 500-line soft limit (rule 18). The integration branch +`sam/selfhost-pass-2` already split them; landing the same file layout on main now, as pure moves, +keeps the later self-host behaviour slices small. + +## Research findings + +- `apps/api/src/services/tts.ts`: 799 lines on main. Integration layout: `tts-config.ts` + (`TTSConfig`, `TTSEnvVars`, `getTTSConfig`, `retryWithBackoff`) and `tts-text.ts` + (`CLEANUP_INSTRUCTIONS`, `SUMMARY_INSTRUCTIONS`, `cleanTextForSpeech`, `summarizeTextForSpeech`, + `hasMarkdown`, `fallbackStripMarkdown`, `splitTextIntoChunks`); `tts.ts` re-exports them. + Integration-only behaviour to keep out: `SpeechAudioSource`, `isSpeechEndpoint`, speech-endpoint + synthesis (`./speech-endpoints`). +- `packages/ai-proxy/src/ai-token-budget.ts`: 660 lines on main. Integration layout: + `ai-budget-settings.ts` (`AiBudgetLimits`, `getAiBudgetLimits`, `buildBudgetSettingsKey`, + `get/save/deleteUserBudgetSettings`, `getAdminAiAllowance`, `validateBudgetUpdate`) and + `ai-monthly-cost-cap.ts` (`buildMonthlyCostCacheKey`, `getCachedMonthlyCost`, `checkMonthlyCostCap`). + Integration-only behaviour to keep out: `MONTHLY_COST_CAP_UNAVAILABLE_MESSAGE`, + `isMonthlyCostCapAvailable` gating, `MonthlyCostCapCheck`, `currentUtcMonthStart`, + `getLocalMonthlyAiCostUsd`, local cost metering (`getProviderUsage` cycle). +- `apps/api/src/durable-objects/sam-session/agent-loop.ts`: 676 lines on main. Integration layout: + `agent-loop-llm.ts` (`getAnthropicApiKey`, `DEFAULT_LLM_TIMEOUT_MS`, `callLLM`, `callAnthropicLLM`) + and `agent-loop-streams.ts` (`processAnthropicStream`, `processOpenAIStream`). Main's + `callWorkersAILLM` (private helper of `callLLM`) moves with `callLLM`; the integration branch + replaced it with `callOpenAIChatLLM` / `llm-chat-target` (new behaviour, kept out). +- gitlab split: obsolete (coordinator verified), not done. +- Model: PR #2714 (L2) pure-move proof and PR body. + +## Checklist + +- [ ] tts split reproduced on main's code, `tts.ts` re-exports every previous export +- [ ] ai-token-budget split reproduced, `ai-token-budget.ts` re-exports every previous export; package entry and apps/api shim unchanged in names +- [ ] agent-loop split reproduced; `agent-loop.ts` exports unchanged +- [ ] mechanical pure-move proof per split (symbol table + unmatched-lines lists) +- [ ] mock targets / import paths in tests updated only where needed, listed +- [ ] local gates: build order, typecheck, check:fast, api + ai-proxy unit tests, Workers tests touching these modules, file sizes, ast-checks, boundary rules +- [ ] reviews: architecture-reviewer, task-completion-validator, cloudflare-specialist (agent-loop runs inside SamSession/ProjectAgent DOs) +- [ ] staging: read-aloud audio, SAM agent chat, budget/usage page +- [ ] draft PR, CodeRabbit request via workflow dispatch, report to coordinator + +## Acceptance criteria + +- Every moved symbol's body is identical to main's (mechanical proof). +- Every previous import path and export name still resolves. +- Existing tests pass with at most import-path / mock-target edits. +- Staging read-aloud, SAM chat and budget page behave as before. From 637005252e5b855eef72106349a98f2c69783698 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sat, 14 Nov 2026 14:42:18 +0000 Subject: [PATCH 2/6] refactor(api): split tts.ts into tts-config and tts-text (L3, pure move) Co-Authored-By: Claude Opus 5.5 --- apps/api/src/services/tts-config.ts | 134 ++++++++++ apps/api/src/services/tts-text.ts | 273 ++++++++++++++++++++ apps/api/src/services/tts.ts | 383 +--------------------------- 3 files changed, 417 insertions(+), 373 deletions(-) create mode 100644 apps/api/src/services/tts-config.ts create mode 100644 apps/api/src/services/tts-text.ts diff --git a/apps/api/src/services/tts-config.ts b/apps/api/src/services/tts-config.ts new file mode 100644 index 0000000000..219a17b8d4 --- /dev/null +++ b/apps/api/src/services/tts-config.ts @@ -0,0 +1,134 @@ +/** + * TTS configuration (env → TTSConfig) and the retry helper shared by the TTS pipeline. + * Split from tts.ts by size; consumers import through tts.ts. + */ +import { + DEFAULT_TTS_CHUNK_SIZE, + DEFAULT_TTS_CLEANUP_MAX_TOKENS, + DEFAULT_TTS_CLEANUP_MODEL, + DEFAULT_TTS_CLEANUP_TIMEOUT_MS, + 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_BASE_DELAY_MS, + DEFAULT_TTS_SPEAKER, + DEFAULT_TTS_SUMMARY_THRESHOLD, + DEFAULT_TTS_TIMEOUT_MS, +} from '@simple-agent-manager/shared'; + +import { log } from '../lib/logger'; +import { parsePositiveInt } from '../lib/route-helpers'; + +// ─── Configuration ─────────────────────────────────────────────────────────── + +export interface TTSConfig { + model?: string; + speaker?: string; + encoding?: string; + cleanupModel?: string; + cleanupMaxTokens?: number; + maxTextLength?: number; + timeoutMs?: number; + cleanupTimeoutMs?: number; + r2Prefix?: string; + enabled?: boolean; + chunkSize?: number; + maxChunks?: number; + summaryThreshold?: number; + retryAttempts?: number; + retryBaseDelayMs?: number; +} + +export interface TTSEnvVars { + TTS_MODEL?: string; + TTS_SPEAKER?: string; + TTS_ENCODING?: string; + TTS_CLEANUP_MODEL?: string; + TTS_CLEANUP_MAX_TOKENS?: string; + TTS_MAX_TEXT_LENGTH?: string; + TTS_TIMEOUT_MS?: string; + TTS_CLEANUP_TIMEOUT_MS?: string; + TTS_R2_PREFIX?: string; + TTS_ENABLED?: string; + TTS_CHUNK_SIZE?: string; + TTS_MAX_CHUNKS?: string; + TTS_SUMMARY_THRESHOLD?: string; + TTS_RETRY_ATTEMPTS?: string; + TTS_RETRY_BASE_DELAY_MS?: string; +} + +export function getTTSConfig(env: TTSEnvVars): TTSConfig { + return { + model: env.TTS_MODEL || DEFAULT_TTS_MODEL, + speaker: env.TTS_SPEAKER || DEFAULT_TTS_SPEAKER, + encoding: env.TTS_ENCODING || DEFAULT_TTS_ENCODING, + cleanupModel: env.TTS_CLEANUP_MODEL || DEFAULT_TTS_CLEANUP_MODEL, + cleanupMaxTokens: parsePositiveInt(env.TTS_CLEANUP_MAX_TOKENS, DEFAULT_TTS_CLEANUP_MAX_TOKENS), + maxTextLength: parsePositiveInt(env.TTS_MAX_TEXT_LENGTH, DEFAULT_TTS_MAX_TEXT_LENGTH), + timeoutMs: parsePositiveInt(env.TTS_TIMEOUT_MS, DEFAULT_TTS_TIMEOUT_MS), + cleanupTimeoutMs: parsePositiveInt(env.TTS_CLEANUP_TIMEOUT_MS, DEFAULT_TTS_CLEANUP_TIMEOUT_MS), + r2Prefix: env.TTS_R2_PREFIX || DEFAULT_TTS_R2_PREFIX, + enabled: env.TTS_ENABLED !== 'false', + chunkSize: parsePositiveInt(env.TTS_CHUNK_SIZE, DEFAULT_TTS_CHUNK_SIZE), + maxChunks: parsePositiveInt(env.TTS_MAX_CHUNKS, DEFAULT_TTS_MAX_CHUNKS), + summaryThreshold: parsePositiveInt(env.TTS_SUMMARY_THRESHOLD, DEFAULT_TTS_SUMMARY_THRESHOLD), + retryAttempts: parsePositiveInt(env.TTS_RETRY_ATTEMPTS, DEFAULT_TTS_RETRY_ATTEMPTS), + retryBaseDelayMs: parsePositiveInt( + env.TTS_RETRY_BASE_DELAY_MS, + DEFAULT_TTS_RETRY_BASE_DELAY_MS + ), + }; +} + +// ─── Retry Utility ────────────────────────────────────────────────────────── + +/** + * Retry an async function with exponential backoff and jitter. + * Throws the last error if all attempts fail. + */ +export async function retryWithBackoff( + fn: () => Promise, + maxAttempts: number, + baseDelayMs: number, + label: string +): Promise { + let lastError: Error | undefined; + + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return await fn(); + } catch (err) { + lastError = err instanceof Error ? err : new Error(String(err)); + + if (attempt === maxAttempts) { + log.warn('tts.retry_exhausted', { + label, + attempts: maxAttempts, + error: lastError.message, + }); + throw lastError; + } + + // Exponential backoff: baseDelay * 2^(attempt-1) with ±25% jitter + const exponentialDelay = baseDelayMs * Math.pow(2, attempt - 1); + const jitter = exponentialDelay * 0.25 * (2 * Math.random() - 1); + const delay = Math.max(0, Math.round(exponentialDelay + jitter)); + + log.warn('tts.retry_attempt', { + label, + attempt, + maxAttempts, + error: lastError.message, + delayMs: delay, + }); + + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + + // Should never reach here, but TypeScript needs this + throw lastError ?? new Error('retryWithBackoff: no attempts made'); +} diff --git a/apps/api/src/services/tts-text.ts b/apps/api/src/services/tts-text.ts new file mode 100644 index 0000000000..41253f3588 --- /dev/null +++ b/apps/api/src/services/tts-text.ts @@ -0,0 +1,273 @@ +/** + * Text preparation for TTS: LLM markdown cleanup, LLM summary, regex fallback and chunking. + * Split from tts.ts by size; consumers import through tts.ts. + */ +import { + DEFAULT_TTS_CHUNK_SIZE, + DEFAULT_TTS_CLEANUP_MAX_TOKENS, + DEFAULT_TTS_CLEANUP_MODEL, + DEFAULT_TTS_CLEANUP_TIMEOUT_MS, + DEFAULT_TTS_RETRY_ATTEMPTS, + DEFAULT_TTS_RETRY_BASE_DELAY_MS, +} from '@simple-agent-manager/shared'; + +import { log } from '../lib/logger'; +import { retryWithBackoff, type TTSConfig } from './tts-config'; + +// ─── Markdown Cleanup ──────────────────────────────────────────────────────── + +const CLEANUP_INSTRUCTIONS = `You are a text preparation assistant for text-to-speech systems. Your job is to convert markdown-formatted text into natural spoken text. + +Rules: +- Output ONLY the cleaned text, nothing else +- Remove all markdown formatting (headers, bold, italic, code blocks, links, images, lists markers) +- Convert bullet points and numbered lists into natural flowing sentences +- Remove code blocks entirely — do not try to read code aloud +- Convert URLs and links into just the link text +- Expand common abbreviations if they would sound odd spoken (e.g., "e.g." → "for example") +- Keep the meaning and tone of the original text +- Do not add any commentary, explanation, or meta-text +- Output plain text only — no markdown, no HTML, no special formatting`; + +const SUMMARY_INSTRUCTIONS = `You are a text summarization assistant for text-to-speech systems. Your job is to create a concise spoken summary of long content. + +Rules: +- Output ONLY the summary text, nothing else +- Summarize the key points, findings, and conclusions +- Use natural spoken language — no markdown, no HTML, no special formatting +- Remove all code blocks, URLs, and technical formatting +- Keep the summary proportional: aim for roughly 10-20% of the original length +- Preserve the most important information and main arguments +- Use transitional phrases for natural flow when spoken aloud +- Do not add any commentary like "Here is a summary" — just provide the summary directly +- Do not add any meta-text or preamble`; + +/** + * Use an LLM to clean markdown/code from text, producing natural spoken text. + * Retries on failure before falling back to basic regex stripping. + */ +export async function cleanTextForSpeech( + text: string, + ai: Ai, + config: TTSConfig = {} +): Promise { + const cleanupModel = config.cleanupModel ?? DEFAULT_TTS_CLEANUP_MODEL; + const cleanupTimeoutMs = config.cleanupTimeoutMs ?? DEFAULT_TTS_CLEANUP_TIMEOUT_MS; + const cleanupMaxTokens = config.cleanupMaxTokens ?? DEFAULT_TTS_CLEANUP_MAX_TOKENS; + const retryAttempts = config.retryAttempts ?? DEFAULT_TTS_RETRY_ATTEMPTS; + const retryBaseDelayMs = config.retryBaseDelayMs ?? DEFAULT_TTS_RETRY_BASE_DELAY_MS; + + // If text has no markdown indicators, skip LLM cleanup + if (!hasMarkdown(text)) { + return text.trim(); + } + + try { + // Load speech dependencies on demand; construct the agent once before retrying. + const [{ Agent }, { createWorkersAI }] = await Promise.all([ + import('@mastra/core/agent'), + import('workers-ai-provider'), + ]); + const workersAi = createWorkersAI({ binding: ai }); + const model = workersAi(cleanupModel as Parameters[0]); + const agent = new Agent({ + id: 'tts-text-cleanup', + name: 'TTS Text Cleanup', + instructions: CLEANUP_INSTRUCTIONS, + model, + }); + + const cleaned = await retryWithBackoff( + async () => { + const result = await agent.generate(text, { + abortSignal: AbortSignal.timeout(cleanupTimeoutMs), + modelSettings: { + maxOutputTokens: cleanupMaxTokens, + }, + }); + + const resultText = result.text?.trim(); + if (!resultText) { + throw new Error('LLM returned empty cleanup result'); + } + return resultText; + }, + retryAttempts, + retryBaseDelayMs, + 'cleanup' + ); + + log.info('tts.cleanup_complete', { + inputLength: text.length, + outputLength: cleaned.length, + ratio: Math.round((cleaned.length / text.length) * 100), + cleanupModel, + cleanupMaxTokens, + }); + + return cleaned; + } catch (err) { + log.warn('tts.cleanup_failed', { + error: err instanceof Error ? err.message : String(err), + textLength: text.length, + cleanupModel, + }); + return fallbackStripMarkdown(text); + } +} + +/** + * Use an LLM to summarize long text for TTS. + * Retries on failure before falling back to truncation + regex stripping. + */ +export async function summarizeTextForSpeech( + text: string, + ai: Ai, + config: TTSConfig = {} +): Promise { + const cleanupModel = config.cleanupModel ?? DEFAULT_TTS_CLEANUP_MODEL; + const cleanupTimeoutMs = config.cleanupTimeoutMs ?? DEFAULT_TTS_CLEANUP_TIMEOUT_MS; + const cleanupMaxTokens = config.cleanupMaxTokens ?? DEFAULT_TTS_CLEANUP_MAX_TOKENS; + const retryAttempts = config.retryAttempts ?? DEFAULT_TTS_RETRY_ATTEMPTS; + const retryBaseDelayMs = config.retryBaseDelayMs ?? DEFAULT_TTS_RETRY_BASE_DELAY_MS; + + try { + // Load speech dependencies on demand; construct the agent once before retrying. + const [{ Agent }, { createWorkersAI }] = await Promise.all([ + import('@mastra/core/agent'), + import('workers-ai-provider'), + ]); + const workersAi = createWorkersAI({ binding: ai }); + const model = workersAi(cleanupModel as Parameters[0]); + const agent = new Agent({ + id: 'tts-text-summarize', + name: 'TTS Text Summarize', + instructions: SUMMARY_INSTRUCTIONS, + model, + }); + + const summary = await retryWithBackoff( + async () => { + const result = await agent.generate(text, { + abortSignal: AbortSignal.timeout(cleanupTimeoutMs), + modelSettings: { + maxOutputTokens: cleanupMaxTokens, + }, + }); + + const resultText = result.text?.trim(); + if (!resultText) { + throw new Error('LLM returned empty summary result'); + } + return resultText; + }, + retryAttempts, + retryBaseDelayMs, + 'summary' + ); + + log.info('tts.summary_complete', { + inputLength: text.length, + outputLength: summary.length, + ratio: Math.round((summary.length / text.length) * 100), + cleanupModel, + }); + + return summary; + } catch (err) { + log.warn('tts.summary_failed', { + error: err instanceof Error ? err.message : String(err), + textLength: text.length, + cleanupModel, + }); + const effectiveChunkSize = config.chunkSize ?? DEFAULT_TTS_CHUNK_SIZE; + return fallbackStripMarkdown(text.slice(0, effectiveChunkSize)); + } +} + +/** Quick check for common markdown patterns. */ +function hasMarkdown(text: string): boolean { + return /```|`[^`]+`|#{1,6}\s|[*_]{1,2}\S|\[.*\]\(.*\)|^\s*[-*+]\s|^\s*\d+\.\s/m.test(text); +} + +/** Regex-based markdown stripping fallback (less natural than LLM but works offline). */ +export function fallbackStripMarkdown(md: string): string { + return md + .replace(/```[\s\S]*?```/g, '') // fenced code blocks + .replace(/`([^`]+)`/g, '$1') // inline code + .replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images + .replace(/\[[^\]]*\]\(([^)]*)\)/g, '$1') // links → URL text + .replace(/#{1,6}\s+/g, '') // headings + .replace(/\*\*([^*]+)\*\*/g, '$1') // bold + .replace(/__([^_]+)__/g, '$1') // bold + .replace(/\*([^*]+)\*/g, '$1') // italic + .replace(/(?\s?/g, '$1') // blockquotes + .replace(/(^|\n)\s*[-*+]\s/g, '$1') // unordered list markers + .replace(/(^|\n)\s*\d+\.\s/g, '$1') // ordered list markers + .replace(/(^|\n)(---+|\*\*\*+|___+)\s*($|\n)/g, '$1') // horizontal rules + .replace(/\n{3,}/g, '\n\n') // collapse excess newlines + .trim(); +} + +// ─── Text Chunking ────────────────────────────────────────────────────────── + +/** + * Split text into chunks at sentence boundaries, respecting a max chunk size. + * Never splits mid-word. Falls back to word boundaries if no sentence boundary + * is found within the chunk limit. + */ +export function splitTextIntoChunks(text: string, maxChunkSize: number): string[] { + if (!text) { + return []; + } + + if (text.length <= maxChunkSize) { + return [text]; + } + + const chunks: string[] = []; + let remaining = text; + + while (remaining.length > 0) { + if (remaining.length <= maxChunkSize) { + chunks.push(remaining); + break; + } + + // Look for the last sentence boundary within the chunk limit + const window = remaining.slice(0, maxChunkSize); + let splitIndex = -1; + + // Try sentence boundaries: ". ", "! ", "? ", ".\n", "!\n", "?\n" + for (const sep of ['. ', '! ', '? ', '.\n', '!\n', '?\n']) { + const idx = window.lastIndexOf(sep); + if (idx > splitIndex) { + // Include the punctuation but not the space/newline after it + splitIndex = idx + 1; + } + } + + // Also try double newline (paragraph boundary) + const paraIdx = window.lastIndexOf('\n\n'); + if (paraIdx > splitIndex) { + splitIndex = paraIdx; + } + + // Fallback: split at last space (word boundary) + if (splitIndex <= 0) { + const spaceIdx = window.lastIndexOf(' '); + if (spaceIdx > 0) { + splitIndex = spaceIdx; + } else { + // No space found — force split at max chunk size + splitIndex = maxChunkSize; + } + } + + chunks.push(remaining.slice(0, splitIndex).trim()); + remaining = remaining.slice(splitIndex).trim(); + } + + return chunks.filter((c) => c.length > 0); +} diff --git a/apps/api/src/services/tts.ts b/apps/api/src/services/tts.ts index 3c1641c2c9..f7d4739546 100644 --- a/apps/api/src/services/tts.ts +++ b/apps/api/src/services/tts.ts @@ -20,9 +20,6 @@ import { DEFAULT_TTS_CHUNK_SIZE, - DEFAULT_TTS_CLEANUP_MAX_TOKENS, - DEFAULT_TTS_CLEANUP_MODEL, - DEFAULT_TTS_CLEANUP_TIMEOUT_MS, DEFAULT_TTS_ENCODING, DEFAULT_TTS_MAX_CHUNKS, DEFAULT_TTS_MAX_TEXT_LENGTH, @@ -36,376 +33,16 @@ import { } from '@simple-agent-manager/shared'; import { log } from '../lib/logger'; -import { parsePositiveInt } from '../lib/route-helpers'; - -// ─── Configuration ─────────────────────────────────────────────────────────── - -export interface TTSConfig { - model?: string; - speaker?: string; - encoding?: string; - cleanupModel?: string; - cleanupMaxTokens?: number; - maxTextLength?: number; - timeoutMs?: number; - cleanupTimeoutMs?: number; - r2Prefix?: string; - enabled?: boolean; - chunkSize?: number; - maxChunks?: number; - summaryThreshold?: number; - retryAttempts?: number; - retryBaseDelayMs?: number; -} - -export interface TTSEnvVars { - TTS_MODEL?: string; - TTS_SPEAKER?: string; - TTS_ENCODING?: string; - TTS_CLEANUP_MODEL?: string; - TTS_CLEANUP_MAX_TOKENS?: string; - TTS_MAX_TEXT_LENGTH?: string; - TTS_TIMEOUT_MS?: string; - TTS_CLEANUP_TIMEOUT_MS?: string; - TTS_R2_PREFIX?: string; - TTS_ENABLED?: string; - TTS_CHUNK_SIZE?: string; - TTS_MAX_CHUNKS?: string; - TTS_SUMMARY_THRESHOLD?: string; - TTS_RETRY_ATTEMPTS?: string; - TTS_RETRY_BASE_DELAY_MS?: string; -} - -export function getTTSConfig(env: TTSEnvVars): TTSConfig { - return { - model: env.TTS_MODEL || DEFAULT_TTS_MODEL, - speaker: env.TTS_SPEAKER || DEFAULT_TTS_SPEAKER, - encoding: env.TTS_ENCODING || DEFAULT_TTS_ENCODING, - cleanupModel: env.TTS_CLEANUP_MODEL || DEFAULT_TTS_CLEANUP_MODEL, - cleanupMaxTokens: parsePositiveInt(env.TTS_CLEANUP_MAX_TOKENS, DEFAULT_TTS_CLEANUP_MAX_TOKENS), - maxTextLength: parsePositiveInt(env.TTS_MAX_TEXT_LENGTH, DEFAULT_TTS_MAX_TEXT_LENGTH), - timeoutMs: parsePositiveInt(env.TTS_TIMEOUT_MS, DEFAULT_TTS_TIMEOUT_MS), - cleanupTimeoutMs: parsePositiveInt(env.TTS_CLEANUP_TIMEOUT_MS, DEFAULT_TTS_CLEANUP_TIMEOUT_MS), - r2Prefix: env.TTS_R2_PREFIX || DEFAULT_TTS_R2_PREFIX, - enabled: env.TTS_ENABLED !== 'false', - chunkSize: parsePositiveInt(env.TTS_CHUNK_SIZE, DEFAULT_TTS_CHUNK_SIZE), - maxChunks: parsePositiveInt(env.TTS_MAX_CHUNKS, DEFAULT_TTS_MAX_CHUNKS), - summaryThreshold: parsePositiveInt(env.TTS_SUMMARY_THRESHOLD, DEFAULT_TTS_SUMMARY_THRESHOLD), - retryAttempts: parsePositiveInt(env.TTS_RETRY_ATTEMPTS, DEFAULT_TTS_RETRY_ATTEMPTS), - retryBaseDelayMs: parsePositiveInt( - env.TTS_RETRY_BASE_DELAY_MS, - DEFAULT_TTS_RETRY_BASE_DELAY_MS - ), - }; -} - -// ─── Retry Utility ────────────────────────────────────────────────────────── - -/** - * Retry an async function with exponential backoff and jitter. - * Throws the last error if all attempts fail. - */ -export async function retryWithBackoff( - fn: () => Promise, - maxAttempts: number, - baseDelayMs: number, - label: string -): Promise { - let lastError: Error | undefined; - - for (let attempt = 1; attempt <= maxAttempts; attempt++) { - try { - return await fn(); - } catch (err) { - lastError = err instanceof Error ? err : new Error(String(err)); - - if (attempt === maxAttempts) { - log.warn('tts.retry_exhausted', { - label, - attempts: maxAttempts, - error: lastError.message, - }); - throw lastError; - } - - // Exponential backoff: baseDelay * 2^(attempt-1) with ±25% jitter - const exponentialDelay = baseDelayMs * Math.pow(2, attempt - 1); - const jitter = exponentialDelay * 0.25 * (2 * Math.random() - 1); - const delay = Math.max(0, Math.round(exponentialDelay + jitter)); - - log.warn('tts.retry_attempt', { - label, - attempt, - maxAttempts, - error: lastError.message, - delayMs: delay, - }); - - await new Promise((resolve) => setTimeout(resolve, delay)); - } - } - - // Should never reach here, but TypeScript needs this - throw lastError ?? new Error('retryWithBackoff: no attempts made'); -} - -// ─── Markdown Cleanup ──────────────────────────────────────────────────────── - -const CLEANUP_INSTRUCTIONS = `You are a text preparation assistant for text-to-speech systems. Your job is to convert markdown-formatted text into natural spoken text. - -Rules: -- Output ONLY the cleaned text, nothing else -- Remove all markdown formatting (headers, bold, italic, code blocks, links, images, lists markers) -- Convert bullet points and numbered lists into natural flowing sentences -- Remove code blocks entirely — do not try to read code aloud -- Convert URLs and links into just the link text -- Expand common abbreviations if they would sound odd spoken (e.g., "e.g." → "for example") -- Keep the meaning and tone of the original text -- Do not add any commentary, explanation, or meta-text -- Output plain text only — no markdown, no HTML, no special formatting`; - -const SUMMARY_INSTRUCTIONS = `You are a text summarization assistant for text-to-speech systems. Your job is to create a concise spoken summary of long content. - -Rules: -- Output ONLY the summary text, nothing else -- Summarize the key points, findings, and conclusions -- Use natural spoken language — no markdown, no HTML, no special formatting -- Remove all code blocks, URLs, and technical formatting -- Keep the summary proportional: aim for roughly 10-20% of the original length -- Preserve the most important information and main arguments -- Use transitional phrases for natural flow when spoken aloud -- Do not add any commentary like "Here is a summary" — just provide the summary directly -- Do not add any meta-text or preamble`; - -/** - * Use an LLM to clean markdown/code from text, producing natural spoken text. - * Retries on failure before falling back to basic regex stripping. - */ -export async function cleanTextForSpeech( - text: string, - ai: Ai, - config: TTSConfig = {} -): Promise { - const cleanupModel = config.cleanupModel ?? DEFAULT_TTS_CLEANUP_MODEL; - const cleanupTimeoutMs = config.cleanupTimeoutMs ?? DEFAULT_TTS_CLEANUP_TIMEOUT_MS; - const cleanupMaxTokens = config.cleanupMaxTokens ?? DEFAULT_TTS_CLEANUP_MAX_TOKENS; - const retryAttempts = config.retryAttempts ?? DEFAULT_TTS_RETRY_ATTEMPTS; - const retryBaseDelayMs = config.retryBaseDelayMs ?? DEFAULT_TTS_RETRY_BASE_DELAY_MS; - - // If text has no markdown indicators, skip LLM cleanup - if (!hasMarkdown(text)) { - return text.trim(); - } - - try { - // Load speech dependencies on demand; construct the agent once before retrying. - const [{ Agent }, { createWorkersAI }] = await Promise.all([ - import('@mastra/core/agent'), - import('workers-ai-provider'), - ]); - const workersAi = createWorkersAI({ binding: ai }); - const model = workersAi(cleanupModel as Parameters[0]); - const agent = new Agent({ - id: 'tts-text-cleanup', - name: 'TTS Text Cleanup', - instructions: CLEANUP_INSTRUCTIONS, - model, - }); - - const cleaned = await retryWithBackoff( - async () => { - const result = await agent.generate(text, { - abortSignal: AbortSignal.timeout(cleanupTimeoutMs), - modelSettings: { - maxOutputTokens: cleanupMaxTokens, - }, - }); - - const resultText = result.text?.trim(); - if (!resultText) { - throw new Error('LLM returned empty cleanup result'); - } - return resultText; - }, - retryAttempts, - retryBaseDelayMs, - 'cleanup' - ); - - log.info('tts.cleanup_complete', { - inputLength: text.length, - outputLength: cleaned.length, - ratio: Math.round((cleaned.length / text.length) * 100), - cleanupModel, - cleanupMaxTokens, - }); - - return cleaned; - } catch (err) { - log.warn('tts.cleanup_failed', { - error: err instanceof Error ? err.message : String(err), - textLength: text.length, - cleanupModel, - }); - return fallbackStripMarkdown(text); - } -} - -/** - * Use an LLM to summarize long text for TTS. - * Retries on failure before falling back to truncation + regex stripping. - */ -export async function summarizeTextForSpeech( - text: string, - ai: Ai, - config: TTSConfig = {} -): Promise { - const cleanupModel = config.cleanupModel ?? DEFAULT_TTS_CLEANUP_MODEL; - const cleanupTimeoutMs = config.cleanupTimeoutMs ?? DEFAULT_TTS_CLEANUP_TIMEOUT_MS; - const cleanupMaxTokens = config.cleanupMaxTokens ?? DEFAULT_TTS_CLEANUP_MAX_TOKENS; - const retryAttempts = config.retryAttempts ?? DEFAULT_TTS_RETRY_ATTEMPTS; - const retryBaseDelayMs = config.retryBaseDelayMs ?? DEFAULT_TTS_RETRY_BASE_DELAY_MS; - - try { - // Load speech dependencies on demand; construct the agent once before retrying. - const [{ Agent }, { createWorkersAI }] = await Promise.all([ - import('@mastra/core/agent'), - import('workers-ai-provider'), - ]); - const workersAi = createWorkersAI({ binding: ai }); - const model = workersAi(cleanupModel as Parameters[0]); - const agent = new Agent({ - id: 'tts-text-summarize', - name: 'TTS Text Summarize', - instructions: SUMMARY_INSTRUCTIONS, - model, - }); - - const summary = await retryWithBackoff( - async () => { - const result = await agent.generate(text, { - abortSignal: AbortSignal.timeout(cleanupTimeoutMs), - modelSettings: { - maxOutputTokens: cleanupMaxTokens, - }, - }); - - const resultText = result.text?.trim(); - if (!resultText) { - throw new Error('LLM returned empty summary result'); - } - return resultText; - }, - retryAttempts, - retryBaseDelayMs, - 'summary' - ); - - log.info('tts.summary_complete', { - inputLength: text.length, - outputLength: summary.length, - ratio: Math.round((summary.length / text.length) * 100), - cleanupModel, - }); - - return summary; - } catch (err) { - log.warn('tts.summary_failed', { - error: err instanceof Error ? err.message : String(err), - textLength: text.length, - cleanupModel, - }); - const effectiveChunkSize = config.chunkSize ?? DEFAULT_TTS_CHUNK_SIZE; - return fallbackStripMarkdown(text.slice(0, effectiveChunkSize)); - } -} - -/** Quick check for common markdown patterns. */ -function hasMarkdown(text: string): boolean { - return /```|`[^`]+`|#{1,6}\s|[*_]{1,2}\S|\[.*\]\(.*\)|^\s*[-*+]\s|^\s*\d+\.\s/m.test(text); -} - -/** Regex-based markdown stripping fallback (less natural than LLM but works offline). */ -export function fallbackStripMarkdown(md: string): string { - return md - .replace(/```[\s\S]*?```/g, '') // fenced code blocks - .replace(/`([^`]+)`/g, '$1') // inline code - .replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images - .replace(/\[[^\]]*\]\(([^)]*)\)/g, '$1') // links → URL text - .replace(/#{1,6}\s+/g, '') // headings - .replace(/\*\*([^*]+)\*\*/g, '$1') // bold - .replace(/__([^_]+)__/g, '$1') // bold - .replace(/\*([^*]+)\*/g, '$1') // italic - .replace(/(?\s?/g, '$1') // blockquotes - .replace(/(^|\n)\s*[-*+]\s/g, '$1') // unordered list markers - .replace(/(^|\n)\s*\d+\.\s/g, '$1') // ordered list markers - .replace(/(^|\n)(---+|\*\*\*+|___+)\s*($|\n)/g, '$1') // horizontal rules - .replace(/\n{3,}/g, '\n\n') // collapse excess newlines - .trim(); -} - -// ─── Text Chunking ────────────────────────────────────────────────────────── - -/** - * Split text into chunks at sentence boundaries, respecting a max chunk size. - * Never splits mid-word. Falls back to word boundaries if no sentence boundary - * is found within the chunk limit. - */ -export function splitTextIntoChunks(text: string, maxChunkSize: number): string[] { - if (!text) { - return []; - } - - if (text.length <= maxChunkSize) { - return [text]; - } - - const chunks: string[] = []; - let remaining = text; - - while (remaining.length > 0) { - if (remaining.length <= maxChunkSize) { - chunks.push(remaining); - break; - } - - // Look for the last sentence boundary within the chunk limit - const window = remaining.slice(0, maxChunkSize); - let splitIndex = -1; - - // Try sentence boundaries: ". ", "! ", "? ", ".\n", "!\n", "?\n" - for (const sep of ['. ', '! ', '? ', '.\n', '!\n', '?\n']) { - const idx = window.lastIndexOf(sep); - if (idx > splitIndex) { - // Include the punctuation but not the space/newline after it - splitIndex = idx + 1; - } - } - - // Also try double newline (paragraph boundary) - const paraIdx = window.lastIndexOf('\n\n'); - if (paraIdx > splitIndex) { - splitIndex = paraIdx; - } - - // Fallback: split at last space (word boundary) - if (splitIndex <= 0) { - const spaceIdx = window.lastIndexOf(' '); - if (spaceIdx > 0) { - splitIndex = spaceIdx; - } else { - // No space found — force split at max chunk size - splitIndex = maxChunkSize; - } - } - - chunks.push(remaining.slice(0, splitIndex).trim()); - remaining = remaining.slice(splitIndex).trim(); - } - - return chunks.filter((c) => c.length > 0); -} +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'; // ─── Audio Generation ──────────────────────────────────────────────────────── From d6c137c8a135b832e9c6b87b7ec4914b5ee63501 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sat, 14 Nov 2026 14:42:18 +0000 Subject: [PATCH 3/6] refactor(ai-proxy): split ai-token-budget into ai-budget-settings and ai-monthly-cost-cap (L3, pure move) Co-Authored-By: Claude Opus 5.5 --- packages/ai-proxy/src/ai-budget-settings.ts | 169 +++++++++++++ packages/ai-proxy/src/ai-monthly-cost-cap.ts | 62 +++++ packages/ai-proxy/src/ai-token-budget.ts | 236 ++----------------- 3 files changed, 250 insertions(+), 217 deletions(-) create mode 100644 packages/ai-proxy/src/ai-budget-settings.ts create mode 100644 packages/ai-proxy/src/ai-monthly-cost-cap.ts diff --git a/packages/ai-proxy/src/ai-budget-settings.ts b/packages/ai-proxy/src/ai-budget-settings.ts new file mode 100644 index 0000000000..5e3a53406e --- /dev/null +++ b/packages/ai-proxy/src/ai-budget-settings.ts @@ -0,0 +1,169 @@ +/** + * 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. + */ +import type { AdminAiAllowance, UserAiBudgetSettings } from '@simple-agent-manager/shared'; +import { + AI_ADMIN_ALLOWANCE_KV_PREFIX, + AI_BUDGET_SETTINGS_KV_PREFIX, + DEFAULT_AI_USAGE_ALERT_THRESHOLD_PERCENT, + DEFAULT_AI_USAGE_MAX_DAILY_TOKEN_LIMIT, + DEFAULT_AI_USAGE_MAX_MONTHLY_COST_CAP_USD, + DEFAULT_AI_USAGE_MIN_DAILY_TOKEN_LIMIT, + DEFAULT_AI_USAGE_MIN_MONTHLY_COST_CAP_USD, +} from '@simple-agent-manager/shared'; +import { expectJsonRecord } from '@simple-agent-manager/worker-core'; + +import type { AiProxyEnv } from './env'; + +export interface AiBudgetLimits { + maxDailyTokens: number; + minDailyTokens: number; + maxMonthlyCostCapUsd: number; + minMonthlyCostCapUsd: number; +} + +export function getAiBudgetLimits(env: AiProxyEnv): AiBudgetLimits { + return { + maxDailyTokens: + Number.parseInt(env.AI_USAGE_MAX_DAILY_TOKEN_LIMIT || '', 10) || + DEFAULT_AI_USAGE_MAX_DAILY_TOKEN_LIMIT, + minDailyTokens: + Number.parseInt(env.AI_USAGE_MIN_DAILY_TOKEN_LIMIT || '', 10) || + DEFAULT_AI_USAGE_MIN_DAILY_TOKEN_LIMIT, + maxMonthlyCostCapUsd: + Number(env.AI_USAGE_MAX_MONTHLY_COST_CAP_USD) || DEFAULT_AI_USAGE_MAX_MONTHLY_COST_CAP_USD, + minMonthlyCostCapUsd: + Number(env.AI_USAGE_MIN_MONTHLY_COST_CAP_USD) || DEFAULT_AI_USAGE_MIN_MONTHLY_COST_CAP_USD, + }; +} + +// ============================================================================= +// User Budget Settings (KV-stored) +// ============================================================================= + +/** Build the KV key for a user's budget settings. */ +export function buildBudgetSettingsKey(userId: string): string { + return `${AI_BUDGET_SETTINGS_KV_PREFIX}:${userId}`; +} + +/** Get a user's custom budget settings, or null if none set. */ +export async function getUserBudgetSettings( + kv: KVNamespace, + userId: string +): Promise { + const key = buildBudgetSettingsKey(userId); + return kv.get(key, 'json'); +} + +/** Save a user's budget settings. */ +export async function saveUserBudgetSettings( + kv: KVNamespace, + userId: string, + settings: UserAiBudgetSettings +): Promise { + const key = buildBudgetSettingsKey(userId); + await kv.put(key, JSON.stringify(settings)); +} + +/** Delete a user's custom budget settings (revert to platform defaults). */ +export async function deleteUserBudgetSettings(kv: KVNamespace, userId: string): Promise { + const key = buildBudgetSettingsKey(userId); + await kv.delete(key); +} + +/** Get a user's admin-managed AI allowance ceiling from KV. */ +export async function getAdminAiAllowance( + kv: KVNamespace, + userId: string +): Promise { + return kv.get(`${AI_ADMIN_ALLOWANCE_KV_PREFIX}:${userId}`, 'json'); +} + +/** + * Validate and normalize budget update request. Returns validated settings or throws. + * + * When `adminAllowance` is provided, the user's limits are capped at the + * admin-set ceiling instead of the platform maximum. + */ +export function validateBudgetUpdate( + body: unknown, + env: AiProxyEnv, + adminAllowance?: AdminAiAllowance | null +): UserAiBudgetSettings { + const request = expectJsonRecord(body, 'usage.ai.budget'); + const { + maxDailyTokens: platformMaxDailyTokens, + minDailyTokens, + maxMonthlyCostCapUsd: platformMaxMonthlyCap, + minMonthlyCostCapUsd: minMonthlyCap, + } = getAiBudgetLimits(env); + + // Admin ceilings take precedence over platform maximums when set + const maxDailyInputTokens = adminAllowance?.maxDailyInputTokens ?? platformMaxDailyTokens; + const maxDailyOutputTokens = adminAllowance?.maxDailyOutputTokens ?? platformMaxDailyTokens; + const maxMonthlyCap = adminAllowance?.maxMonthlyCostCapUsd ?? platformMaxMonthlyCap; + + const settings: UserAiBudgetSettings = { + dailyInputTokenLimit: null, + dailyOutputTokenLimit: null, + monthlyCostCapUsd: null, + alertThresholdPercent: DEFAULT_AI_USAGE_ALERT_THRESHOLD_PERCENT, + }; + + if (request.dailyInputTokenLimit !== undefined) { + if (request.dailyInputTokenLimit !== null) { + if ( + typeof request.dailyInputTokenLimit !== 'number' || + request.dailyInputTokenLimit < minDailyTokens || + request.dailyInputTokenLimit > maxDailyInputTokens + ) { + throw new Error( + `dailyInputTokenLimit must be between ${minDailyTokens} and ${maxDailyInputTokens}` + ); + } + settings.dailyInputTokenLimit = Math.floor(request.dailyInputTokenLimit); + } + } + + if (request.dailyOutputTokenLimit !== undefined) { + if (request.dailyOutputTokenLimit !== null) { + if ( + typeof request.dailyOutputTokenLimit !== 'number' || + request.dailyOutputTokenLimit < minDailyTokens || + request.dailyOutputTokenLimit > maxDailyOutputTokens + ) { + throw new Error( + `dailyOutputTokenLimit must be between ${minDailyTokens} and ${maxDailyOutputTokens}` + ); + } + settings.dailyOutputTokenLimit = Math.floor(request.dailyOutputTokenLimit); + } + } + + if (request.monthlyCostCapUsd !== undefined) { + if (request.monthlyCostCapUsd !== null) { + if ( + typeof request.monthlyCostCapUsd !== 'number' || + request.monthlyCostCapUsd < minMonthlyCap || + request.monthlyCostCapUsd > maxMonthlyCap + ) { + throw new Error(`monthlyCostCapUsd must be between ${minMonthlyCap} and ${maxMonthlyCap}`); + } + settings.monthlyCostCapUsd = Math.round(request.monthlyCostCapUsd * 100) / 100; + } + } + + if (request.alertThresholdPercent !== undefined) { + if ( + typeof request.alertThresholdPercent !== 'number' || + request.alertThresholdPercent < 1 || + request.alertThresholdPercent > 100 + ) { + throw new Error('alertThresholdPercent must be between 1 and 100'); + } + settings.alertThresholdPercent = Math.floor(request.alertThresholdPercent); + } + + return settings; +} diff --git a/packages/ai-proxy/src/ai-monthly-cost-cap.ts b/packages/ai-proxy/src/ai-monthly-cost-cap.ts new file mode 100644 index 0000000000..756338bce1 --- /dev/null +++ b/packages/ai-proxy/src/ai-monthly-cost-cap.ts @@ -0,0 +1,62 @@ +/** + * 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'; + +import { getUserBudgetSettings } from './ai-budget-settings'; + +// ============================================================================= +// Monthly Cost Cap Enforcement (KV-cached, written by cron) +// ============================================================================= + +/** Build the KV key for a user's cached monthly AI cost. */ +export function buildMonthlyCostCacheKey(userId: string): string { + const now = new Date(); + const monthKey = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}`; + return `${AI_MONTHLY_COST_CACHE_KV_PREFIX}:${userId}:${monthKey}`; +} + +/** Read a user's cached monthly AI cost from KV. Returns null if not cached yet. */ +export async function getCachedMonthlyCost( + kv: KVNamespace, + userId: string +): Promise { + const key = buildMonthlyCostCacheKey(userId); + const raw = await kv.get(key); + if (raw === null) return null; + const parsed = parseFloat(raw); + return Number.isNaN(parsed) ? null : parsed; +} + +/** + * Check whether a user is within their monthly cost cap. + * + * Reads from KV cache (written by hourly cron). If no cache exists, + * the check passes (fail-open) — the cron will populate it next run. + * + * Returns { allowed, costUsd, capUsd } where capUsd is null if no cap is set. + */ +export async function checkMonthlyCostCap( + kv: KVNamespace, + userId: string +): Promise<{ allowed: boolean; costUsd: number; capUsd: number | null }> { + const userSettings = await getUserBudgetSettings(kv, userId); + const capUsd = userSettings?.monthlyCostCapUsd ?? null; + + // No cap set — always allowed + if (capUsd === null || capUsd <= 0) { + return { allowed: true, costUsd: 0, capUsd }; + } + + const costUsd = await getCachedMonthlyCost(kv, userId); + + // No cache yet — fail-open until the hourly cron populates usage data. + // Window is at most 60 minutes after SAM mode activation or cap change. + // Acceptable risk: daily token budget (checked separately) still applies. + if (costUsd === null) { + return { allowed: true, costUsd: 0, capUsd }; + } + + return { allowed: costUsd < capUsd, costUsd, capUsd }; +} diff --git a/packages/ai-proxy/src/ai-token-budget.ts b/packages/ai-proxy/src/ai-token-budget.ts index bf5f4a4753..21eb04c2c9 100644 --- a/packages/ai-proxy/src/ai-token-budget.ts +++ b/packages/ai-proxy/src/ai-token-budget.ts @@ -7,25 +7,34 @@ * write updates are not atomic under concurrent requests. */ -import type { AdminAiAllowance, UserAiBudgetSettings } from '@simple-agent-manager/shared'; +import type { UserAiBudgetSettings } from '@simple-agent-manager/shared'; import { - AI_ADMIN_ALLOWANCE_KV_PREFIX, - AI_BUDGET_SETTINGS_KV_PREFIX, - AI_MONTHLY_COST_CACHE_KV_PREFIX, DEFAULT_AI_PROXY_DAILY_INPUT_TOKEN_LIMIT, DEFAULT_AI_PROXY_DAILY_OUTPUT_TOKEN_LIMIT, - DEFAULT_AI_USAGE_ALERT_THRESHOLD_PERCENT, DEFAULT_AI_USAGE_BUDGET_TTL_SECONDS, - DEFAULT_AI_USAGE_MAX_DAILY_TOKEN_LIMIT, - DEFAULT_AI_USAGE_MAX_MONTHLY_COST_CAP_USD, - DEFAULT_AI_USAGE_MIN_DAILY_TOKEN_LIMIT, - DEFAULT_AI_USAGE_MIN_MONTHLY_COST_CAP_USD, } from '@simple-agent-manager/shared'; import { log } from '@simple-agent-manager/worker-core'; -import { expectJsonRecord } from '@simple-agent-manager/worker-core'; +import { getUserBudgetSettings } from './ai-budget-settings'; +import { checkMonthlyCostCap } from './ai-monthly-cost-cap'; import type { AiProxyEnv } from './env'; +export { + type AiBudgetLimits, + buildBudgetSettingsKey, + deleteUserBudgetSettings, + getAdminAiAllowance, + getAiBudgetLimits, + getUserBudgetSettings, + saveUserBudgetSettings, + validateBudgetUpdate, +} from './ai-budget-settings'; +export { + buildMonthlyCostCacheKey, + checkMonthlyCostCap, + getCachedMonthlyCost, +} from './ai-monthly-cost-cap'; + export interface TokenBudget { inputTokens: number; outputTokens: number; @@ -63,13 +72,6 @@ interface AiTokenBudgetCounterStub extends DurableObjectStub { getProviderUsage(startDateKey: string): Promise; } -export interface AiBudgetLimits { - maxDailyTokens: number; - minDailyTokens: number; - maxMonthlyCostCapUsd: number; - minMonthlyCostCapUsd: number; -} - export interface PlatformDailyTokenLimits { dailyInputTokenLimit: number; dailyOutputTokenLimit: number; @@ -95,21 +97,6 @@ function getBudgetCounter(env: AiProxyEnv | undefined, userId: string) { ) as AiTokenBudgetCounterStub; } -export function getAiBudgetLimits(env: AiProxyEnv): AiBudgetLimits { - return { - maxDailyTokens: - Number.parseInt(env.AI_USAGE_MAX_DAILY_TOKEN_LIMIT || '', 10) || - DEFAULT_AI_USAGE_MAX_DAILY_TOKEN_LIMIT, - minDailyTokens: - Number.parseInt(env.AI_USAGE_MIN_DAILY_TOKEN_LIMIT || '', 10) || - DEFAULT_AI_USAGE_MIN_DAILY_TOKEN_LIMIT, - maxMonthlyCostCapUsd: - Number(env.AI_USAGE_MAX_MONTHLY_COST_CAP_USD) || DEFAULT_AI_USAGE_MAX_MONTHLY_COST_CAP_USD, - minMonthlyCostCapUsd: - Number(env.AI_USAGE_MIN_MONTHLY_COST_CAP_USD) || DEFAULT_AI_USAGE_MIN_MONTHLY_COST_CAP_USD, - }; -} - function parsePositiveIntegerEnv( value: string | undefined, name: string, @@ -241,136 +228,6 @@ export async function getFeatureTokenBudget( return { allowed: usedTokens < tokenLimit, usedTokens, tokenLimit }; } -// ============================================================================= -// User Budget Settings (KV-stored) -// ============================================================================= - -/** Build the KV key for a user's budget settings. */ -export function buildBudgetSettingsKey(userId: string): string { - return `${AI_BUDGET_SETTINGS_KV_PREFIX}:${userId}`; -} - -/** Get a user's custom budget settings, or null if none set. */ -export async function getUserBudgetSettings( - kv: KVNamespace, - userId: string -): Promise { - const key = buildBudgetSettingsKey(userId); - return kv.get(key, 'json'); -} - -/** Save a user's budget settings. */ -export async function saveUserBudgetSettings( - kv: KVNamespace, - userId: string, - settings: UserAiBudgetSettings -): Promise { - const key = buildBudgetSettingsKey(userId); - await kv.put(key, JSON.stringify(settings)); -} - -/** Delete a user's custom budget settings (revert to platform defaults). */ -export async function deleteUserBudgetSettings(kv: KVNamespace, userId: string): Promise { - const key = buildBudgetSettingsKey(userId); - await kv.delete(key); -} - -/** Get a user's admin-managed AI allowance ceiling from KV. */ -export async function getAdminAiAllowance( - kv: KVNamespace, - userId: string -): Promise { - return kv.get(`${AI_ADMIN_ALLOWANCE_KV_PREFIX}:${userId}`, 'json'); -} - -/** - * Validate and normalize budget update request. Returns validated settings or throws. - * - * When `adminAllowance` is provided, the user's limits are capped at the - * admin-set ceiling instead of the platform maximum. - */ -export function validateBudgetUpdate( - body: unknown, - env: AiProxyEnv, - adminAllowance?: AdminAiAllowance | null -): UserAiBudgetSettings { - const request = expectJsonRecord(body, 'usage.ai.budget'); - const { - maxDailyTokens: platformMaxDailyTokens, - minDailyTokens, - maxMonthlyCostCapUsd: platformMaxMonthlyCap, - minMonthlyCostCapUsd: minMonthlyCap, - } = getAiBudgetLimits(env); - - // Admin ceilings take precedence over platform maximums when set - const maxDailyInputTokens = adminAllowance?.maxDailyInputTokens ?? platformMaxDailyTokens; - const maxDailyOutputTokens = adminAllowance?.maxDailyOutputTokens ?? platformMaxDailyTokens; - const maxMonthlyCap = adminAllowance?.maxMonthlyCostCapUsd ?? platformMaxMonthlyCap; - - const settings: UserAiBudgetSettings = { - dailyInputTokenLimit: null, - dailyOutputTokenLimit: null, - monthlyCostCapUsd: null, - alertThresholdPercent: DEFAULT_AI_USAGE_ALERT_THRESHOLD_PERCENT, - }; - - if (request.dailyInputTokenLimit !== undefined) { - if (request.dailyInputTokenLimit !== null) { - if ( - typeof request.dailyInputTokenLimit !== 'number' || - request.dailyInputTokenLimit < minDailyTokens || - request.dailyInputTokenLimit > maxDailyInputTokens - ) { - throw new Error( - `dailyInputTokenLimit must be between ${minDailyTokens} and ${maxDailyInputTokens}` - ); - } - settings.dailyInputTokenLimit = Math.floor(request.dailyInputTokenLimit); - } - } - - if (request.dailyOutputTokenLimit !== undefined) { - if (request.dailyOutputTokenLimit !== null) { - if ( - typeof request.dailyOutputTokenLimit !== 'number' || - request.dailyOutputTokenLimit < minDailyTokens || - request.dailyOutputTokenLimit > maxDailyOutputTokens - ) { - throw new Error( - `dailyOutputTokenLimit must be between ${minDailyTokens} and ${maxDailyOutputTokens}` - ); - } - settings.dailyOutputTokenLimit = Math.floor(request.dailyOutputTokenLimit); - } - } - - if (request.monthlyCostCapUsd !== undefined) { - if (request.monthlyCostCapUsd !== null) { - if ( - typeof request.monthlyCostCapUsd !== 'number' || - request.monthlyCostCapUsd < minMonthlyCap || - request.monthlyCostCapUsd > maxMonthlyCap - ) { - throw new Error(`monthlyCostCapUsd must be between ${minMonthlyCap} and ${maxMonthlyCap}`); - } - settings.monthlyCostCapUsd = Math.round(request.monthlyCostCapUsd * 100) / 100; - } - } - - if (request.alertThresholdPercent !== undefined) { - if ( - typeof request.alertThresholdPercent !== 'number' || - request.alertThresholdPercent < 1 || - request.alertThresholdPercent > 100 - ) { - throw new Error('alertThresholdPercent must be between 1 and 100'); - } - settings.alertThresholdPercent = Math.floor(request.alertThresholdPercent); - } - - return settings; -} - /** * Resolve effective daily token limits: user-set → platform env → shared constant. */ @@ -572,61 +429,6 @@ function* eachUtcDate(startDate: Date, endDate: Date): Generator { } } -// ============================================================================= -// Monthly Cost Cap Enforcement (KV-cached, written by cron) -// ============================================================================= - -/** Build the KV key for a user's cached monthly AI cost. */ -export function buildMonthlyCostCacheKey(userId: string): string { - const now = new Date(); - const monthKey = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}`; - return `${AI_MONTHLY_COST_CACHE_KV_PREFIX}:${userId}:${monthKey}`; -} - -/** Read a user's cached monthly AI cost from KV. Returns null if not cached yet. */ -export async function getCachedMonthlyCost( - kv: KVNamespace, - userId: string -): Promise { - const key = buildMonthlyCostCacheKey(userId); - const raw = await kv.get(key); - if (raw === null) return null; - const parsed = parseFloat(raw); - return Number.isNaN(parsed) ? null : parsed; -} - -/** - * Check whether a user is within their monthly cost cap. - * - * Reads from KV cache (written by hourly cron). If no cache exists, - * the check passes (fail-open) — the cron will populate it next run. - * - * Returns { allowed, costUsd, capUsd } where capUsd is null if no cap is set. - */ -export async function checkMonthlyCostCap( - kv: KVNamespace, - userId: string -): Promise<{ allowed: boolean; costUsd: number; capUsd: number | null }> { - const userSettings = await getUserBudgetSettings(kv, userId); - const capUsd = userSettings?.monthlyCostCapUsd ?? null; - - // No cap set — always allowed - if (capUsd === null || capUsd <= 0) { - return { allowed: true, costUsd: 0, capUsd }; - } - - const costUsd = await getCachedMonthlyCost(kv, userId); - - // No cache yet — fail-open until the hourly cron populates usage data. - // Window is at most 60 minutes after SAM mode activation or cap change. - // Acceptable risk: daily token budget (checked separately) still applies. - if (costUsd === null) { - return { allowed: true, costUsd: 0, capUsd }; - } - - return { allowed: costUsd < capUsd, costUsd, capUsd }; -} - export type AiUsageGateResult = | { allowed: true } | { From 89429a7bca6106a441f7af7d65d91f335e440fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sat, 14 Nov 2026 14:42:18 +0000 Subject: [PATCH 4/6] refactor(api): split sam-session agent-loop into agent-loop-llm and agent-loop-streams (L3, pure move) Co-Authored-By: Claude Opus 5.5 --- .../sam-session/agent-loop-llm.ts | 197 +++++++++ .../sam-session/agent-loop-streams.ts | 230 ++++++++++ .../durable-objects/sam-session/agent-loop.ts | 409 +----------------- 3 files changed, 429 insertions(+), 407 deletions(-) create mode 100644 apps/api/src/durable-objects/sam-session/agent-loop-llm.ts create mode 100644 apps/api/src/durable-objects/sam-session/agent-loop-streams.ts diff --git a/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts new file mode 100644 index 0000000000..63b4be9ae2 --- /dev/null +++ b/apps/api/src/durable-objects/sam-session/agent-loop-llm.ts @@ -0,0 +1,197 @@ +/** + * 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 { Env } from '../../env'; +import { getCredentialEncryptionKey } from '../../lib/secrets'; +import { buildWorkersAIGatewayUrl } from '../../services/ai-proxy-shared'; +import { getPlatformAgentCredential } from '../../services/platform-credentials'; +import { + buildAnthropicGatewayUrl, + isAnthropicModel, + isWorkersAIModel, + type OpenAITool, + toOpenAITools, +} from './agent-loop-helpers'; +import type { OpenAIMessage } from './payload-size'; +import type { AnthropicToolDef } from './types'; + +async function getAnthropicApiKey(env: Env): Promise { + const { drizzle } = await import('drizzle-orm/d1'); + const db = drizzle(env.DATABASE); + const encryptionKey = getCredentialEncryptionKey(env); + const cred = await getPlatformAgentCredential(db, 'claude-code', encryptionKey); + if (!cred?.credential) { + throw new Error( + 'No Anthropic API key configured. An admin must add a Claude Code platform credential.' + ); + } + return cred.credential; +} + +/** Default fetch timeout for LLM calls (configurable via SAM_LLM_TIMEOUT_MS). */ +const DEFAULT_LLM_TIMEOUT_MS = 120_000; + +export async function callLLM( + env: Env, + config: SamConfig, + messages: OpenAIMessage[], + userId: string, + conversationId: string, + baseSystemPrompt: string, + tools: AnthropicToolDef[] +): Promise { + const model = config.model; + const systemPrompt = config.systemPromptAppend + ? `${baseSystemPrompt}\n\n${config.systemPromptAppend}` + : baseSystemPrompt; + + const openAITools = toOpenAITools(tools); + const aigMetadata = JSON.stringify({ + source: config.aigSource, + userId, + conversationId, + }); + + // Timeout to prevent hanging fetches inside DOs + const timeoutMs = + parseInt(String((env as unknown as Record).SAM_LLM_TIMEOUT_MS) || '', 10) || + DEFAULT_LLM_TIMEOUT_MS; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + + try { + if (isAnthropicModel(model)) { + return await callAnthropicLLM( + env, + model, + systemPrompt, + messages, + openAITools, + aigMetadata, + config.maxTokens, + controller.signal, + tools + ); + } else if (isWorkersAIModel(model)) { + return await callWorkersAILLM( + env, + model, + systemPrompt, + messages, + openAITools, + aigMetadata, + config.maxTokens, + controller.signal + ); + } else { + throw new Error(`Unknown model provider for model: ${model}`); + } + } finally { + clearTimeout(timer); + } +} + +/** Call Anthropic Messages API, translating from OpenAI format at the boundary. */ +async function callAnthropicLLM( + env: Env, + model: string, + systemPrompt: string, + messages: OpenAIMessage[], + _openAITools: OpenAITool[], + aigMetadata: string, + maxTokens: number, + signal: AbortSignal, + anthropicTools: AnthropicToolDef[] +): Promise { + const apiKey = await getAnthropicApiKey(env); + const url = buildAnthropicGatewayUrl(env); + + // Convert OpenAI messages to Anthropic format + const anthropicMessages = messages + .filter((m) => m.role !== 'system') + .map((m) => { + if (m.role === 'user') { + return { role: 'user' as const, content: m.content || '' }; + } else if (m.role === 'assistant') { + const content: Array> = []; + if (m.content) content.push({ type: 'text', text: m.content }); + if (m.tool_calls) { + for (const tc of m.tool_calls) { + let input: unknown = {}; + try { + input = JSON.parse(tc.function.arguments); + } catch { + /* empty */ + } + content.push({ type: 'tool_use', id: tc.id, name: tc.function.name, input }); + } + } + return { role: 'assistant' as const, content }; + } else if (m.role === 'tool') { + return { + role: 'user' as const, + content: [ + { type: 'tool_result', tool_use_id: m.tool_call_id || '', content: m.content || '' }, + ], + }; + } + return { role: 'user' as const, content: m.content || '' }; + }); + + return fetch(url, { + method: 'POST', + signal, + headers: { + 'x-api-key': apiKey, + 'anthropic-version': SAM_ANTHROPIC_VERSION, + 'content-type': 'application/json', + 'cf-aig-metadata': aigMetadata, + }, + body: JSON.stringify({ + model, + max_tokens: maxTokens, + system: systemPrompt, + messages: anthropicMessages, + tools: anthropicTools, + stream: true, + }), + }); +} + +/** Call Workers AI via AI Gateway (OpenAI-compatible). */ +async function callWorkersAILLM( + env: Env, + model: string, + systemPrompt: string, + messages: OpenAIMessage[], + openAITools: OpenAITool[], + aigMetadata: string, + maxTokens: number, + signal: AbortSignal +): Promise { + const url = buildWorkersAIGatewayUrl(env); + + const fullMessages: OpenAIMessage[] = [{ role: 'system', content: systemPrompt }, ...messages]; + + return fetch(url, { + method: 'POST', + signal, + headers: { + Authorization: `Bearer ${env.CF_API_TOKEN}`, + 'Content-Type': 'application/json', + 'cf-aig-metadata': aigMetadata, + }, + body: JSON.stringify({ + model, + max_tokens: maxTokens, + messages: fullMessages, + tools: openAITools.length > 0 ? openAITools : undefined, + stream: true, + }), + }); +} diff --git a/apps/api/src/durable-objects/sam-session/agent-loop-streams.ts b/apps/api/src/durable-objects/sam-session/agent-loop-streams.ts new file mode 100644 index 0000000000..f7bee21e47 --- /dev/null +++ b/apps/api/src/durable-objects/sam-session/agent-loop-streams.ts @@ -0,0 +1,230 @@ +/** + * 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 { expectJsonRecord } from '../../lib/runtime-validation'; +import { encodeSseEvent, parseToolInput } from './agent-loop-helpers'; +import type { CollectedToolCall } from './types'; + +/** + * Process an Anthropic SSE stream (native Anthropic event format). + * Writes SAM SSE events to the writer and collects tool calls. + */ +export async function processAnthropicStream( + response: Response, + writer: WritableStreamDefaultWriter +): Promise<{ textContent: string; toolCalls: CollectedToolCall[] }> { + if (!response.body) { + throw new Error('No response body from Anthropic'); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + let textContent = ''; + const toolCalls: CollectedToolCall[] = []; + + let currentToolId = ''; + let currentToolName = ''; + let currentToolInputJson = ''; + + let streamDone = false; + while (!streamDone) { + const { done, value } = await reader.read(); + if (done) { + streamDone = true; + break; + } + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + for (const line of lines) { + if (!line.startsWith('data: ')) continue; + const data = line.slice(6).trim(); + if (data === '[DONE]') continue; + + let event: Record; + try { + event = expectJsonRecord(JSON.parse(data), 'sam-session.anthropic_stream.event'); + } catch { + continue; + } + + const eventType = event.type as string; + + if (eventType === 'content_block_start') { + const block = expectJsonRecord( + event.content_block, + 'sam-session.anthropic_stream.content_block' + ); + if (block?.type === 'tool_use') { + currentToolId = typeof block.id === 'string' ? block.id : ''; + currentToolName = typeof block.name === 'string' ? block.name : ''; + currentToolInputJson = ''; + await writer.write( + encodeSseEvent({ + type: 'tool_start', + tool: currentToolName, + input: {}, + }) + ); + } + } else if (eventType === 'content_block_delta') { + const delta = expectJsonRecord(event.delta, 'sam-session.anthropic_stream.delta'); + if (delta?.type === 'text_delta') { + const text = typeof delta.text === 'string' ? delta.text : ''; + textContent += text; + await writer.write(encodeSseEvent({ type: 'text_delta', content: text })); + } else if (delta?.type === 'input_json_delta') { + currentToolInputJson += typeof delta.partial_json === 'string' ? delta.partial_json : ''; + } + } else if (eventType === 'content_block_stop') { + if (currentToolId) { + const input = parseToolInput( + currentToolInputJson, + 'sam-session.anthropic_stream.tool_input' + ); + toolCalls.push({ id: currentToolId, name: currentToolName, input }); + currentToolId = ''; + currentToolName = ''; + currentToolInputJson = ''; + } + } else if (eventType === 'error') { + const errorObj = expectJsonRecord(event.error ?? {}, 'sam-session.anthropic_stream.error'); + const message = + typeof errorObj.message === 'string' ? errorObj.message : 'Anthropic API error'; + await writer.write(encodeSseEvent({ type: 'error', message })); + } + } + } + + return { textContent, toolCalls }; +} + +/** + * Process an OpenAI-format SSE stream (Workers AI / OpenAI-compatible). + * Writes SAM SSE events to the writer and collects tool calls. + */ +export async function processOpenAIStream( + response: Response, + writer: WritableStreamDefaultWriter +): Promise<{ textContent: string; toolCalls: CollectedToolCall[] }> { + if (!response.body) { + throw new Error('No response body from LLM'); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + let textContent = ''; + const toolCalls: CollectedToolCall[] = []; + + const toolCallBuilders = new Map(); + + let streamDone = false; + while (!streamDone) { + const { done, value } = await reader.read(); + if (done) { + streamDone = true; + break; + } + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + for (const line of lines) { + if (!line.startsWith('data: ')) continue; + const data = line.slice(6).trim(); + if (data === '[DONE]') continue; + + let chunk: Record; + try { + chunk = expectJsonRecord(JSON.parse(data), 'sam-session.openai_stream.chunk'); + } catch { + continue; + } + + const choices = Array.isArray(chunk.choices) + ? chunk.choices.map((choice, index) => + expectJsonRecord(choice, `sam-session.openai_stream.choices[${index}]`) + ) + : undefined; + const firstChoice = choices?.[0]; + if (!firstChoice) continue; + + const delta = firstChoice.delta + ? expectJsonRecord(firstChoice.delta, 'sam-session.openai_stream.delta') + : undefined; + if (!delta) continue; + + // Text content + if (delta.content && typeof delta.content === 'string') { + textContent += delta.content; + await writer.write(encodeSseEvent({ type: 'text_delta', content: delta.content })); + } + + // Tool calls (streamed as deltas with index) + const deltaToolCalls = Array.isArray(delta.tool_calls) + ? delta.tool_calls.map((toolCall, index) => + expectJsonRecord(toolCall, `sam-session.openai_stream.tool_calls[${index}]`) + ) + : undefined; + if (deltaToolCalls) { + for (const dtc of deltaToolCalls) { + const index = typeof dtc.index === 'number' ? dtc.index : 0; + const fn = dtc.function + ? expectJsonRecord(dtc.function, 'sam-session.openai_stream.tool_call.function') + : undefined; + + let builder = toolCallBuilders.get(index); + if (!builder) { + const id = + typeof dtc.id === 'string' ? dtc.id : `call_${crypto.randomUUID().slice(0, 8)}`; + const name = typeof fn?.name === 'string' ? fn.name : ''; + builder = { id, name, args: '' }; + toolCallBuilders.set(index, builder); + if (name) { + await writer.write(encodeSseEvent({ type: 'tool_start', tool: name, input: {} })); + } + } + + if (fn?.name && typeof fn.name === 'string' && !builder.name) { + builder.name = fn.name; + await writer.write( + encodeSseEvent({ type: 'tool_start', tool: builder.name, input: {} }) + ); + } + if (fn?.arguments && typeof fn.arguments === 'string') { + builder.args += fn.arguments; + } + } + } + + // Finalize tool calls on finish_reason + const finishReason = + typeof firstChoice.finish_reason === 'string' ? firstChoice.finish_reason : undefined; + if (finishReason === 'tool_calls' || finishReason === 'stop') { + for (const [, builder] of toolCallBuilders) { + if (builder.name) { + const input = parseToolInput(builder.args, 'sam-session.openai_stream.tool_input'); + toolCalls.push({ id: builder.id, name: builder.name, input }); + } + } + toolCallBuilders.clear(); + } + } + } + + // Finalize remaining builders (stream ended without explicit finish_reason) + for (const [, builder] of toolCallBuilders) { + if (builder.name) { + const input = parseToolInput(builder.args, 'sam-session.openai_stream.remaining_tool_input'); + toolCalls.push({ id: builder.id, name: builder.name, input }); + } + } + + return { textContent, toolCalls }; +} diff --git a/apps/api/src/durable-objects/sam-session/agent-loop.ts b/apps/api/src/durable-objects/sam-session/agent-loop.ts index 1433e59b20..6aa29418c1 100644 --- a/apps/api/src/durable-objects/sam-session/agent-loop.ts +++ b/apps/api/src/durable-objects/sam-session/agent-loop.ts @@ -13,434 +13,29 @@ */ import { DEFAULT_SAM_MAX_REQUEST_BODY_BYTES_WORKERS_AI, - SAM_ANTHROPIC_VERSION, type SamConfig, } from '@simple-agent-manager/shared'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { expectJsonRecord } from '../../lib/runtime-validation'; -import { getCredentialEncryptionKey } from '../../lib/secrets'; -import { buildWorkersAIGatewayUrl } from '../../services/ai-proxy-shared'; import { checkAiUsageGate } from '../../services/ai-token-budget'; import { attachTokenUsageAccounting } from '../../services/ai-token-usage-accounting'; -import { getPlatformAgentCredential } from '../../services/platform-credentials'; import { - buildAnthropicGatewayUrl, encodeSseEvent, isAnthropicModel, isWorkersAIModel, - type OpenAITool, - parseToolInput, SAM_SYSTEM_PROMPT, toOpenAIMessages, - toOpenAITools, } from './agent-loop-helpers'; +import { callLLM } from './agent-loop-llm'; +import { processAnthropicStream, processOpenAIStream } from './agent-loop-streams'; import type { OpenAIMessage } from './payload-size'; import { estimateMessagesBytes, trimMessagesToFit, truncateToolResult } from './payload-size'; import type { AnthropicToolDef, CollectedToolCall, MessageRow, ToolContext } from './types'; export { SAM_SYSTEM_PROMPT }; -async function getAnthropicApiKey(env: Env): Promise { - const { drizzle } = await import('drizzle-orm/d1'); - const db = drizzle(env.DATABASE); - const encryptionKey = getCredentialEncryptionKey(env); - const cred = await getPlatformAgentCredential(db, 'claude-code', encryptionKey); - if (!cred?.credential) { - throw new Error( - 'No Anthropic API key configured. An admin must add a Claude Code platform credential.' - ); - } - return cred.credential; -} - -/** Default fetch timeout for LLM calls (configurable via SAM_LLM_TIMEOUT_MS). */ -const DEFAULT_LLM_TIMEOUT_MS = 120_000; - -async function callLLM( - env: Env, - config: SamConfig, - messages: OpenAIMessage[], - userId: string, - conversationId: string, - baseSystemPrompt: string, - tools: AnthropicToolDef[] -): Promise { - const model = config.model; - const systemPrompt = config.systemPromptAppend - ? `${baseSystemPrompt}\n\n${config.systemPromptAppend}` - : baseSystemPrompt; - - const openAITools = toOpenAITools(tools); - const aigMetadata = JSON.stringify({ - source: config.aigSource, - userId, - conversationId, - }); - - // Timeout to prevent hanging fetches inside DOs - const timeoutMs = - parseInt(String((env as unknown as Record).SAM_LLM_TIMEOUT_MS) || '', 10) || - DEFAULT_LLM_TIMEOUT_MS; - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), timeoutMs); - - try { - if (isAnthropicModel(model)) { - return await callAnthropicLLM( - env, - model, - systemPrompt, - messages, - openAITools, - aigMetadata, - config.maxTokens, - controller.signal, - tools - ); - } else if (isWorkersAIModel(model)) { - return await callWorkersAILLM( - env, - model, - systemPrompt, - messages, - openAITools, - aigMetadata, - config.maxTokens, - controller.signal - ); - } else { - throw new Error(`Unknown model provider for model: ${model}`); - } - } finally { - clearTimeout(timer); - } -} - -/** Call Anthropic Messages API, translating from OpenAI format at the boundary. */ -async function callAnthropicLLM( - env: Env, - model: string, - systemPrompt: string, - messages: OpenAIMessage[], - _openAITools: OpenAITool[], - aigMetadata: string, - maxTokens: number, - signal: AbortSignal, - anthropicTools: AnthropicToolDef[] -): Promise { - const apiKey = await getAnthropicApiKey(env); - const url = buildAnthropicGatewayUrl(env); - - // Convert OpenAI messages to Anthropic format - const anthropicMessages = messages - .filter((m) => m.role !== 'system') - .map((m) => { - if (m.role === 'user') { - return { role: 'user' as const, content: m.content || '' }; - } else if (m.role === 'assistant') { - const content: Array> = []; - if (m.content) content.push({ type: 'text', text: m.content }); - if (m.tool_calls) { - for (const tc of m.tool_calls) { - let input: unknown = {}; - try { - input = JSON.parse(tc.function.arguments); - } catch { - /* empty */ - } - content.push({ type: 'tool_use', id: tc.id, name: tc.function.name, input }); - } - } - return { role: 'assistant' as const, content }; - } else if (m.role === 'tool') { - return { - role: 'user' as const, - content: [ - { type: 'tool_result', tool_use_id: m.tool_call_id || '', content: m.content || '' }, - ], - }; - } - return { role: 'user' as const, content: m.content || '' }; - }); - - return fetch(url, { - method: 'POST', - signal, - headers: { - 'x-api-key': apiKey, - 'anthropic-version': SAM_ANTHROPIC_VERSION, - 'content-type': 'application/json', - 'cf-aig-metadata': aigMetadata, - }, - body: JSON.stringify({ - model, - max_tokens: maxTokens, - system: systemPrompt, - messages: anthropicMessages, - tools: anthropicTools, - stream: true, - }), - }); -} - -/** Call Workers AI via AI Gateway (OpenAI-compatible). */ -async function callWorkersAILLM( - env: Env, - model: string, - systemPrompt: string, - messages: OpenAIMessage[], - openAITools: OpenAITool[], - aigMetadata: string, - maxTokens: number, - signal: AbortSignal -): Promise { - const url = buildWorkersAIGatewayUrl(env); - - const fullMessages: OpenAIMessage[] = [{ role: 'system', content: systemPrompt }, ...messages]; - - return fetch(url, { - method: 'POST', - signal, - headers: { - Authorization: `Bearer ${env.CF_API_TOKEN}`, - 'Content-Type': 'application/json', - 'cf-aig-metadata': aigMetadata, - }, - body: JSON.stringify({ - model, - max_tokens: maxTokens, - messages: fullMessages, - tools: openAITools.length > 0 ? openAITools : undefined, - stream: true, - }), - }); -} - -/** - * Process an Anthropic SSE stream (native Anthropic event format). - * Writes SAM SSE events to the writer and collects tool calls. - */ -async function processAnthropicStream( - response: Response, - writer: WritableStreamDefaultWriter -): Promise<{ textContent: string; toolCalls: CollectedToolCall[] }> { - if (!response.body) { - throw new Error('No response body from Anthropic'); - } - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let textContent = ''; - const toolCalls: CollectedToolCall[] = []; - - let currentToolId = ''; - let currentToolName = ''; - let currentToolInputJson = ''; - - let streamDone = false; - while (!streamDone) { - const { done, value } = await reader.read(); - if (done) { - streamDone = true; - break; - } - - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split('\n'); - buffer = lines.pop() || ''; - - for (const line of lines) { - if (!line.startsWith('data: ')) continue; - const data = line.slice(6).trim(); - if (data === '[DONE]') continue; - - let event: Record; - try { - event = expectJsonRecord(JSON.parse(data), 'sam-session.anthropic_stream.event'); - } catch { - continue; - } - - const eventType = event.type as string; - - if (eventType === 'content_block_start') { - const block = expectJsonRecord( - event.content_block, - 'sam-session.anthropic_stream.content_block' - ); - if (block?.type === 'tool_use') { - currentToolId = typeof block.id === 'string' ? block.id : ''; - currentToolName = typeof block.name === 'string' ? block.name : ''; - currentToolInputJson = ''; - await writer.write( - encodeSseEvent({ - type: 'tool_start', - tool: currentToolName, - input: {}, - }) - ); - } - } else if (eventType === 'content_block_delta') { - const delta = expectJsonRecord(event.delta, 'sam-session.anthropic_stream.delta'); - if (delta?.type === 'text_delta') { - const text = typeof delta.text === 'string' ? delta.text : ''; - textContent += text; - await writer.write(encodeSseEvent({ type: 'text_delta', content: text })); - } else if (delta?.type === 'input_json_delta') { - currentToolInputJson += typeof delta.partial_json === 'string' ? delta.partial_json : ''; - } - } else if (eventType === 'content_block_stop') { - if (currentToolId) { - const input = parseToolInput( - currentToolInputJson, - 'sam-session.anthropic_stream.tool_input' - ); - toolCalls.push({ id: currentToolId, name: currentToolName, input }); - currentToolId = ''; - currentToolName = ''; - currentToolInputJson = ''; - } - } else if (eventType === 'error') { - const errorObj = expectJsonRecord(event.error ?? {}, 'sam-session.anthropic_stream.error'); - const message = - typeof errorObj.message === 'string' ? errorObj.message : 'Anthropic API error'; - await writer.write(encodeSseEvent({ type: 'error', message })); - } - } - } - - return { textContent, toolCalls }; -} - -/** - * Process an OpenAI-format SSE stream (Workers AI / OpenAI-compatible). - * Writes SAM SSE events to the writer and collects tool calls. - */ -async function processOpenAIStream( - response: Response, - writer: WritableStreamDefaultWriter -): Promise<{ textContent: string; toolCalls: CollectedToolCall[] }> { - if (!response.body) { - throw new Error('No response body from LLM'); - } - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let textContent = ''; - const toolCalls: CollectedToolCall[] = []; - - const toolCallBuilders = new Map(); - - let streamDone = false; - while (!streamDone) { - const { done, value } = await reader.read(); - if (done) { - streamDone = true; - break; - } - - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split('\n'); - buffer = lines.pop() || ''; - - for (const line of lines) { - if (!line.startsWith('data: ')) continue; - const data = line.slice(6).trim(); - if (data === '[DONE]') continue; - - let chunk: Record; - try { - chunk = expectJsonRecord(JSON.parse(data), 'sam-session.openai_stream.chunk'); - } catch { - continue; - } - - const choices = Array.isArray(chunk.choices) - ? chunk.choices.map((choice, index) => - expectJsonRecord(choice, `sam-session.openai_stream.choices[${index}]`) - ) - : undefined; - const firstChoice = choices?.[0]; - if (!firstChoice) continue; - - const delta = firstChoice.delta - ? expectJsonRecord(firstChoice.delta, 'sam-session.openai_stream.delta') - : undefined; - if (!delta) continue; - - // Text content - if (delta.content && typeof delta.content === 'string') { - textContent += delta.content; - await writer.write(encodeSseEvent({ type: 'text_delta', content: delta.content })); - } - - // Tool calls (streamed as deltas with index) - const deltaToolCalls = Array.isArray(delta.tool_calls) - ? delta.tool_calls.map((toolCall, index) => - expectJsonRecord(toolCall, `sam-session.openai_stream.tool_calls[${index}]`) - ) - : undefined; - if (deltaToolCalls) { - for (const dtc of deltaToolCalls) { - const index = typeof dtc.index === 'number' ? dtc.index : 0; - const fn = dtc.function - ? expectJsonRecord(dtc.function, 'sam-session.openai_stream.tool_call.function') - : undefined; - - let builder = toolCallBuilders.get(index); - if (!builder) { - const id = - typeof dtc.id === 'string' ? dtc.id : `call_${crypto.randomUUID().slice(0, 8)}`; - const name = typeof fn?.name === 'string' ? fn.name : ''; - builder = { id, name, args: '' }; - toolCallBuilders.set(index, builder); - if (name) { - await writer.write(encodeSseEvent({ type: 'tool_start', tool: name, input: {} })); - } - } - - if (fn?.name && typeof fn.name === 'string' && !builder.name) { - builder.name = fn.name; - await writer.write( - encodeSseEvent({ type: 'tool_start', tool: builder.name, input: {} }) - ); - } - if (fn?.arguments && typeof fn.arguments === 'string') { - builder.args += fn.arguments; - } - } - } - - // Finalize tool calls on finish_reason - const finishReason = - typeof firstChoice.finish_reason === 'string' ? firstChoice.finish_reason : undefined; - if (finishReason === 'tool_calls' || finishReason === 'stop') { - for (const [, builder] of toolCallBuilders) { - if (builder.name) { - const input = parseToolInput(builder.args, 'sam-session.openai_stream.tool_input'); - toolCalls.push({ id: builder.id, name: builder.name, input }); - } - } - toolCallBuilders.clear(); - } - } - } - - // Finalize remaining builders (stream ended without explicit finish_reason) - for (const [, builder] of toolCallBuilders) { - if (builder.name) { - const input = parseToolInput(builder.args, 'sam-session.openai_stream.remaining_tool_input'); - toolCalls.push({ id: builder.id, name: builder.name, input }); - } - } - - return { textContent, toolCalls }; -} - /** Configuration for a customized agent loop. */ export interface AgentLoopOptions { /** System prompt for the agent. */ From 7fc3cdf0b6948aa246e72bd6bb4bb4975d874ef8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sat, 14 Nov 2026 14:53:26 +0000 Subject: [PATCH 5/6] task: record L3 implementation and local gates Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-14-l3-api-pure-splits.md | 33 +++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/tasks/active/2026-11-14-l3-api-pure-splits.md b/tasks/active/2026-11-14-l3-api-pure-splits.md index 1c1a4aa32a..b329cb5967 100644 --- a/tasks/active/2026-11-14-l3-api-pure-splits.md +++ b/tasks/active/2026-11-14-l3-api-pure-splits.md @@ -35,12 +35,12 @@ keeps the later self-host behaviour slices small. ## Checklist -- [ ] tts split reproduced on main's code, `tts.ts` re-exports every previous export -- [ ] ai-token-budget split reproduced, `ai-token-budget.ts` re-exports every previous export; package entry and apps/api shim unchanged in names -- [ ] agent-loop split reproduced; `agent-loop.ts` exports unchanged -- [ ] mechanical pure-move proof per split (symbol table + unmatched-lines lists) -- [ ] mock targets / import paths in tests updated only where needed, listed -- [ ] local gates: build order, typecheck, check:fast, api + ai-proxy unit tests, Workers tests touching these modules, file sizes, ast-checks, boundary rules +- [x] tts split reproduced on main's code, `tts.ts` re-exports every previous export +- [x] ai-token-budget split reproduced, `ai-token-budget.ts` re-exports every previous export; package entry and apps/api shim unchanged in names +- [x] agent-loop split reproduced; `agent-loop.ts` exports unchanged +- [x] mechanical pure-move proof per split (symbol table + unmatched-lines lists) +- [x] mock targets / import paths in tests updated only where needed, listed +- [x] local gates: build order, typecheck, check:fast, api + ai-proxy unit tests, Workers tests touching these modules, file sizes, ast-checks, boundary rules - [ ] reviews: architecture-reviewer, task-completion-validator, cloudflare-specialist (agent-loop runs inside SamSession/ProjectAgent DOs) - [ ] staging: read-aloud audio, SAM agent chat, budget/usage page - [ ] draft PR, CodeRabbit request via workflow dispatch, report to coordinator @@ -51,3 +51,24 @@ keeps the later self-host behaviour slices small. - Every previous import path and export name still resolves. - Existing tests pass with at most import-path / mock-target edits. - Staging read-aloud, SAM chat and budget page behave as before. + +## Implementation notes + +- Splits generated mechanically from main's text (whole top-level statements with leading comments, + moved verbatim) by a scratch tool; imports and re-exports written by hand. +- Proof (scratch `verify.cjs`, compares against `git show origin/main`): tts 23/23, ai-token-budget + 38/38, agent-loop 9/9 identical; no new top-level statements; removed/added lines are only imports, + re-exports, header comments and the `export` keyword on `callLLM`, `processAnthropicStream`, + `processOpenAIStream`. Proven discriminating (one-word edit in a moved string → NO). +- Test edits: none needed. No mock target follows a moved symbol (every consumer still imports + through the original module). +- Local gates: build in order OK; typecheck api + ai-proxy OK; `pnpm check:fast` OK; ai-proxy 140/140; + apps/api full vitest 3,399 files / 15,177 tests, 15,173 passed, 4 skipped, 0 failed; Workers + project-agent-do 5/5, sam-runtime (sam-session-do, sam-grounding-runtime, sam-live-stream) 63/63; + `quality:file-sizes` pass (no exemption involved; tts 799→436, ai-token-budget 660→462, + agent-loop 676→271); `quality:ast-checks` 0 errors, 752 warnings, same as main (the 4 agent-loop + throw-without-log warnings moved with their code). +- Left out: gitlab split (obsolete per coordinator); `MONTHLY_COST_CAP_UNAVAILABLE_MESSAGE`, + `MonthlyCostCapCheck`, `currentUtcMonthStart`, `getLocalMonthlyAiCostUsd`, `SpeechAudioSource`, + `isSpeechEndpoint`, `callOpenAIChatLLM` (integration-only behaviour). Main's `callWorkersAILLM` + moved to agent-loop-llm.ts with `callLLM` (its only caller). From dc1e475e4cf940c7a2947b365e56d8fb51d2e3cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sat, 14 Nov 2026 15:43:30 +0000 Subject: [PATCH 6/6] task: record L3 staging verification Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-14-l3-api-pure-splits.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tasks/active/2026-11-14-l3-api-pure-splits.md b/tasks/active/2026-11-14-l3-api-pure-splits.md index b329cb5967..aa9359d6be 100644 --- a/tasks/active/2026-11-14-l3-api-pure-splits.md +++ b/tasks/active/2026-11-14-l3-api-pure-splits.md @@ -41,8 +41,8 @@ keeps the later self-host behaviour slices small. - [x] mechanical pure-move proof per split (symbol table + unmatched-lines lists) - [x] mock targets / import paths in tests updated only where needed, listed - [x] local gates: build order, typecheck, check:fast, api + ai-proxy unit tests, Workers tests touching these modules, file sizes, ast-checks, boundary rules -- [ ] reviews: architecture-reviewer, task-completion-validator, cloudflare-specialist (agent-loop runs inside SamSession/ProjectAgent DOs) -- [ ] staging: read-aloud audio, SAM agent chat, budget/usage page +- [x] reviews: architecture-reviewer, task-completion-validator, cloudflare-specialist (agent-loop runs inside SamSession/ProjectAgent DOs) +- [x] staging: read-aloud audio, SAM agent chat, budget/usage page - [ ] draft PR, CodeRabbit request via workflow dispatch, report to coordinator ## Acceptance criteria @@ -72,3 +72,9 @@ keeps the later self-host behaviour slices small. `MonthlyCostCapCheck`, `currentUtcMonthStart`, `getLocalMonthlyAiCostUsd`, `SpeechAudioSource`, `isSpeechEndpoint`, `callOpenAIChatLLM` (integration-only behaviour). Main's `callWorkersAILLM` moved to agent-loop-llm.ts with `callLLM` (its only caller). +- Staging (2026-11-14, head 7fc3cdf0b, Deploy Staging 43607690743): usage/budget APIs byte-identical + before/after; budget cap -5 → 400, 50 → 200, deleted back to baseline; Project Agent chat 200 with 3 + tool calls on Workers AI (processOpenAIStream path); read-aloud on a VM-runtime message → + synthesize 200 + audio/mpeg 840,960 B, player 0:03/2:20. `/sam` operator page not exercised (SAM + disabled for the shared smoke user; it does not use runAgentLoop). VM node deleted, D1 audit 0 live + nodes; staging FREE 15:43Z.