/** * `/api/agent` — the thin LLM proxy for the live Code Mode agent (§12). * * The browser runs the agent loop and executes `execute_typescript` locally * (QuickJS WASM isolate → workbook tools). This route only runs the Anthropic * completion so `ANTHROPIC_API_KEY` stays server-side. `execute_typescript` is a * client-declared tool, so `mergeAgentTools([], params.tools)` delegates its * execution to the browser; the server just streams the model's turns. */ import { createFileRoute } from '@tanstack/react-router' import { chat, chatParamsFromRequestBody, maxIterations, mergeAgentTools, toServerSentEventsResponse, } from '@tanstack/ai' import { anthropicText } from '@tanstack/ai-anthropic' const AGENT_SYSTEM_PROMPT = `You are a spreadsheet-building agent. You operate a headless spreadsheet by writing TypeScript in the \`execute_typescript\` tool; the code calls the \`external_*\` functions to build and inspect the sheet. Keep prose brief between code steps. Work on sheet "s1". Use this EXACT layout (A1 addresses) so the dashboard can find the cells: Header row (row 1): A1 Category, B1 Anchor, C1 Actual, D1 Lower, E1 Upper, F1 Status Category rows (2–6), as raw inputs — column A name, B anchor, C actual: Cloud 20 / 21, Software 8 / 8, Contractors 30 / 28, Travel 5 / 4, Marketing 12 / 10 Guardrail + status formulas for each category row r (2–6): D{r} = =B{r}*0.8 (lower band) E{r} = =B{r}*1.2 (upper band) F{r} = =IF(C{r}>E{r},"OVER",IF(C{r} { const abortController = new AbortController() let params try { params = await chatParamsFromRequestBody(await request.json()) } catch (error) { return new Response( error instanceof Error ? error.message : 'Bad request', { status: 400 }, ) } const codeModeSystemPrompt = typeof params.forwardedProps.codeModeSystemPrompt === 'string' ? params.forwardedProps.codeModeSystemPrompt : '' const adapter = anthropicText('claude-sonnet-4-6') try { const stream = chat({ threadId: params.threadId, runId: params.runId, adapter, messages: params.messages, // execute_typescript arrives as a client-declared tool → client-executed. tools: mergeAgentTools([], params.tools), systemPrompts: [AGENT_SYSTEM_PROMPT, codeModeSystemPrompt], agentLoopStrategy: maxIterations(12), abortController, modelOptions: { max_tokens: 8192 }, }) return toServerSentEventsResponse(stream, { abortController }) } catch (error: unknown) { if ( (error instanceof Error && error.name === 'AbortError') || abortController.signal.aborted ) { return new Response(null, { status: 499 }) } console.error('[api/agent]', error) return new Response( JSON.stringify({ error: error instanceof Error ? error.message : 'error', }), { status: 500, headers: { 'Content-Type': 'application/json' } }, ) } }, }, }, })