import { anthropic as createAnthropicModel, completePrompt, ContentBlock } from '../models'; import { ToolDefinition, ToolHandler } from '../models/types'; import { parseChangeList, getTransformInstr } from '../service/transformPage'; import { Attachment, Builder, BuilderResult, CHANGE_OPS_SCHEMA, CHANGE_OPS_SCHEMA_NO_RANGED, ContextSection } from './types'; // --------------------------------------------------------------------------- // Builder options — passed from the route handler // --------------------------------------------------------------------------- export interface AnthropicBuilderOptions { apiKey?: string; model?: string; /** Optional wrapper applied to any internally-created model (e.g. for debug logging). */ wrapModel?: (model: completePrompt) => completePrompt; /** When true, this is the first edit to a saved page (v0→v1) — forces Opus + no ranged writes. */ isFirstEdit?: boolean; /** When true, retry the last edit — forces Opus + no ranged writes, skips classification. */ tryAgain?: boolean; /** Number of messages in the chat history (used for early-conversation bypass). */ historyLength?: number; /** Pre-computed classification result — skips re-classifying in the builder. */ preClassified?: ClassifyResult; } // --------------------------------------------------------------------------- // Request classification // --------------------------------------------------------------------------- export type Classification = 'question' | 'easy-change' | 'medium-change' | 'hard-change' | 're-write'; /** Sketches passed to the classifier so it can decide which sections to expand. */ export interface ClassifierSection { /** Section title (e.g. ""). */ title: string; /** Compact one-line summary the classifier reads. */ sketch: string; } export interface ClassifyResult { classification: Classification; /** When classification is "question", this contains the answer text. */ answer?: string; /** Section titles the classifier picked to render in full. Empty = render all sketches. */ expand: string[]; } const CLASSIFIER_SYSTEM_PROMPT = `You classify user messages for a web page builder and pick which context sections the builder needs. Default to a change request. Only classify as "question" when the user is purely asking for information with zero implication that anything should change. Step 1 — Is this a pure information question with zero change implication? Examples: "What color is the header?", "How many sections are there?", "What font is the title using?" Yes, and there is absolutely no suggestion that anything should change → "question" No → go to step 2. Step 2 — Classify complexity: "easy-change": Text edits, color/style tweaks, toggling visibility, adding/removing a single element, minor CSS changes. "medium-change": Modifying existing JS logic, updating event handlers, changing multiple related styles, adding a small feature to existing functionality, updating existing behavior. "hard-change": Complex new features, significant new JS, games, animations, restructuring layout, forms with validation, multi-step work. "re-write": Complete page overhaul, fundamental restructure, "start over", "rebuild", "redo the whole page". Step 3 — Which context sections does the model need to fulfill this request? Read the AVAILABLE_SECTIONS list in the user message — each line is ": " describing what's in the section. Return an "expand" array of section titles (matching exactly, including the angle brackets) the model needs in full. Include a title only if the page currently uses that feature OR the user's request will likely require it. Sections you don't expand will still be visible to the model as their sketch — so the model knows the section exists, just not the full content. Omit sections that are clearly unrelated to this request. Return only JSON. No other text. - Change: { "classification": "easy-change", "expand": [""] } - Question: { "classification": "question", "answer": "", "expand": [] }`; export async function classifyRequest( apiKey: string, pageHtml: string, userMessage: string, sections?: ClassifierSection[], ): Promise { try { const sonnet = createAnthropicModel({ apiKey, model: 'claude-sonnet-4-6' }); const sectionList = (sections ?? []) .map(s => `${s.title}: ${s.sketch}`) .join('\n'); const sectionsBlock = sectionList ? `\n\n\n${sectionList}` : ''; const result = await sonnet({ system: { role: 'system', content: CLASSIFIER_SYSTEM_PROMPT }, prompt: { role: 'user', content: `\n${pageHtml}\n\n\n${userMessage}${sectionsBlock}` }, jsonMode: true, }); if (!result.completed || !result.value) { return { classification: 'hard-change', expand: [] }; } const parsed = JSON.parse(result.value); const c = parsed.classification; const allowed = new Set((sections ?? []).map(s => s.title)); const expand = parseExpand(parsed.expand, allowed); if (c === 'question') { return { classification: 'question', answer: typeof parsed.answer === 'string' ? parsed.answer : '', expand }; } if (c === 'easy-change' || c === 'medium-change' || c === 'hard-change' || c === 're-write') { return { classification: c, expand }; } return { classification: 'hard-change', expand }; } catch { return { classification: 'hard-change', expand: [] }; } } /** * Validate the classifier's expand[] against the set of titles it was offered. * Unknown / non-string entries are dropped silently. */ function parseExpand(raw: unknown, allowed: Set): string[] { if (!Array.isArray(raw)) return []; const out: string[] = []; for (const item of raw) { if (typeof item === 'string' && allowed.has(item)) { out.push(item); } } return out; } // --------------------------------------------------------------------------- // Lightweight question heuristic — replaces Sonnet classifier for Q&A detection // --------------------------------------------------------------------------- const QUESTION_WORDS = /^(?:what|how|why|where|when|which|is|are|does|do|can|could|should|would|will)\b/i; const ACTION_VERBS = /\b(?:add|change|make|create|build|fix|update|remove|delete|move|replace|resize|rewrite|redo|redesign)\b/i; /** * Returns true when the message is very likely a pure information question * (no intent to modify the page). Used to bypass the full Sonnet classifier. */ export function isLikelyQuestion(message: string): boolean { const trimmed = message.trim(); if (!trimmed.endsWith('?')) return false; if (!QUESTION_WORDS.test(trimmed)) return false; if (ACTION_VERBS.test(trimmed)) return false; return true; } // --------------------------------------------------------------------------- // Anthropic builder factory // --------------------------------------------------------------------------- /** * Create an Anthropic-tuned builder. * * @param complete The completePrompt function (already configured with API key / model). * @param userInstructions Optional user-level instructions from settings. * @param productName Product name for branding in prompts (defaults to 'SynthOS'). * @param options Optional API key and model name for classifier routing. */ export function createAnthropicBuilder( complete: completePrompt, userInstructions?: string, productName?: string, options?: AnthropicBuilderOptions ): Builder { const name = productName ?? 'SynthOS'; return { async run(currentPage, additionalSections, userMessage, newBuild, attachments?, tools?, toolHandlers?, onToolCall?): Promise { try { const isOpus = options?.model?.startsWith('claude-opus-'); const noRanged = CHANGE_OPS_SCHEMA_NO_RANGED; // Non-Opus models or missing apiKey: existing behavior if (!isOpus || !options?.apiKey) { return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, undefined, tools, toolHandlers, onToolCall); } // Console errors bypass classification — always route to Opus with no ranged writes if (userMessage.includes('CONSOLE_ERRORS:')) { console.log('classifyRequest: console errors detected → routing to ' + options.model! + ' (no ranged)'); return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // New builds always use Opus with no ranged writes if (newBuild) { console.log('classifyRequest: new build → routing to ' + options.model! + ' (no ranged)'); return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // First edit to a saved page (v0→v1) — force Opus with no ranged writes if (options?.isFirstEdit) { console.log('classifyRequest: first edit (v0→v1) → routing to ' + options.model! + ' (no ranged)'); return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // Try again — force Opus with no ranged writes, skip classification if (options?.tryAgain) { console.log('classifyRequest: try again → routing to claude-opus-4-6 (no ranged)'); let opus: completePrompt = createAnthropicModel({ apiKey: options.apiKey!, model: 'claude-opus-4-6' }); if (options.wrapModel) opus = options.wrapModel(opus); return buildWithModel(opus, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // --- Opt-1: Smart classification bypass --- // Small pages (<5KB) — Opus cost delta is negligible; classifier cost exceeds savings if (currentPage.content.length < 5_000) { console.log('classifyRequest: small page (<5KB) → routing to ' + options.model! + ' (no ranged, bypass)'); return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // Image attachments — always structural changes; classifier can't inspect images if (attachments && attachments.length > 0) { console.log('classifyRequest: image attachments → routing to ' + options.model! + ' (no ranged, bypass)'); return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // Early conversations (history <= 2) — almost always builds/edits if (typeof options.historyLength === 'number' && options.historyLength <= 2) { console.log('classifyRequest: early conversation (history <= 2) → routing to ' + options.model! + ' (no ranged, bypass)'); return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // Keyword-based Q&A detection — lightweight heuristic replaces full-page Sonnet call if (isLikelyQuestion(userMessage)) { console.log('classifyRequest: likely question (heuristic) → routing to claude-sonnet-4-6 (Q&A, no page HTML)'); let sonnet: completePrompt = createAnthropicModel({ apiKey: options.apiKey, model: 'claude-sonnet-4-6' }); if (options.wrapModel) sonnet = options.wrapModel(sonnet); // Lightweight Q&A call — send only user message + page summary, not full HTML const pageTitle = currentPage.content.match(/]*>([^<]*)<\/title>/i)?.[1] ?? 'untitled'; const elementCount = (currentPage.content.match(/<[a-z]/gi) ?? []).length; const pageSummary = `Page: "${pageTitle}" (${elementCount} elements)`; const qaResult = await sonnet({ system: { role: 'system', content: 'You are a helpful assistant for a web page builder. Answer the user\'s question briefly and accurately based on the page summary provided.' }, prompt: { role: 'user', content: `${pageSummary}\n\n${userMessage}` }, }); if (qaResult.completed && qaResult.value) { return { kind: 'reply', text: qaResult.value }; } // Fallback to classifier if Q&A call fails } // Classify the request — use pre-computed result if available, otherwise call Sonnet const classifyResult = options.preClassified ?? await classifyRequest(options.apiKey, currentPage.content, userMessage); if (!options.preClassified) { console.log(`classifyRequest: "${classifyResult.classification}" → routing to ${routeLabel(classifyResult.classification, options.model!)}`); } // Questions — answer was already provided by the classifier if (classifyResult.classification === 'question') { return { kind: 'reply', text: classifyResult.answer ?? '' }; } // Easy changes use Sonnet with default schema (ranged allowed) if (classifyResult.classification === 'easy-change') { let sonnet: completePrompt = createAnthropicModel({ apiKey: options.apiKey, model: 'claude-sonnet-4-6' }); if (options.wrapModel) sonnet = options.wrapModel(sonnet); return buildWithModel(sonnet, currentPage, additionalSections, userMessage, userInstructions, name, attachments, undefined, tools, toolHandlers, onToolCall); } // Medium changes use Sonnet with no ranged writes if (classifyResult.classification === 'medium-change') { let sonnet: completePrompt = createAnthropicModel({ apiKey: options.apiKey, model: 'claude-sonnet-4-6' }); if (options.wrapModel) sonnet = options.wrapModel(sonnet); return buildWithModel(sonnet, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } // Hard changes and re-writes use Opus with no ranged writes return buildWithModel(complete, currentPage, additionalSections, userMessage, userInstructions, name, attachments, noRanged, tools, toolHandlers, onToolCall); } catch (err: unknown) { return { kind: 'error', error: err instanceof Error ? err : new Error(String(err)) }; } } }; } // --------------------------------------------------------------------------- // Build flow — shared prompt construction + model call + parsing // --------------------------------------------------------------------------- /** * Appended to when tools are bound so the model knows it may * fetch additional context on demand. */ export const TOOLS_INSTRUCTION_HINT = 'You may call the provided tools to load additional context only if you need it. You may call multiple tools in parallel in a single turn.'; export async function buildWithModel( model: completePrompt, currentPage: ContextSection, additionalSections: ContextSection[], userMessage: string, userInstructions: string | undefined, productName: string, attachments?: Attachment[], outputSchema?: Record, tools?: ToolDefinition[], toolHandlers?: Record, onToolCall?: (names: string[]) => void, ): Promise { // -- System message: all static content (cacheable) -- const systemParts: string[] = []; for (const section of additionalSections) { if (section.content) { systemParts.push(`${section.title}\n${section.content}`); } } const instructionParts: string[] = []; if (userInstructions?.trim()) { instructionParts.push(userInstructions); } for (const section of additionalSections) { if (section.instructions?.trim()) { instructionParts.push(section.instructions); } } instructionParts.push(getTransformInstr(productName)); if (tools && tools.length > 0) { instructionParts.push(TOOLS_INSTRUCTION_HINT); } const instructions = instructionParts.filter(s => s.trim() !== '').join('\n'); systemParts.push(`\n${instructions}`); const systemContent = systemParts.join('\n\n'); // -- User message: dynamic content only (current page + user message) -- const promptText = `${currentPage.title}\n${currentPage.content}\n\n\n${userMessage}`; // Build prompt content — multimodal when image attachments are present const imageAttachments = (attachments ?? []).filter(a => a.mediaType.startsWith('image/')); let promptContent: string | ContentBlock[]; if (imageAttachments.length > 0) { const blocks: ContentBlock[] = [{ type: 'text', text: promptText }]; for (const att of imageAttachments) { blocks.push({ type: 'image', mediaType: att.mediaType, data: att.data }); } promptContent = blocks; } else { promptContent = promptText; } // -- Call model -- const result = await model({ system: { role: 'system', content: systemContent }, prompt: { role: 'user', content: promptContent }, cacheSystem: true, outputSchema: outputSchema ?? CHANGE_OPS_SCHEMA, ...(tools && tools.length > 0 && { tools, toolHandlers: toolHandlers ?? {}, onToolCall }), }); if (!result.completed) { return { kind: 'error', error: result.error ?? new Error('Model call failed') }; } // -- Parse response -- return parseBuilderResponse(result.value!); } // --------------------------------------------------------------------------- // Route label for console logging // --------------------------------------------------------------------------- function routeLabel(classification: Classification, configuredModel: string): string { if (classification === 'question') return 'classifier (answered inline)'; if (classification === 'easy-change') return 'claude-sonnet-4-6'; if (classification === 'medium-change') return 'claude-sonnet-4-6 (no ranged)'; if (classification === 're-write') return configuredModel + ' (re-write)'; return configuredModel + ' (no ranged)'; } // --------------------------------------------------------------------------- // Response parsing — shared across builders // --------------------------------------------------------------------------- export function parseBuilderResponse(raw: string): BuilderResult { // Try parsing as a JSON object with a changes array + optional message try { const parsed = JSON.parse(raw); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { if (Array.isArray(parsed.changes)) { const message = typeof parsed.message === 'string' ? parsed.message : undefined; return { kind: 'transforms', changes: parsed.changes, message }; } if (parsed.kind === 'transforms' && Array.isArray(parsed.changes)) { return { kind: 'transforms', changes: parsed.changes }; } if (parsed.kind === 'reply' && typeof parsed.text === 'string') { return { kind: 'reply', text: parsed.text }; } } // Bare array — backward compat (no message field available) if (Array.isArray(parsed)) { return { kind: 'transforms', changes: parsed }; } } catch { // fall through to parseChangeList extraction } // Fall back to extracting a JSON array from the response text try { const changes = parseChangeList(raw); return { kind: 'transforms', changes }; } catch { return { kind: 'error', error: new Error('Failed to parse model response as JSON') }; } }