import { spawn } from 'child_process'; import { ChangeOp, getTransformInstr } from '../service/transformPage'; import { parseBuilderResponse } from './anthropic'; import { Builder, BuilderResult, CHANGE_OPS_FORMAT_INSTRUCTION } from './types'; // --------------------------------------------------------------------------- // Options // --------------------------------------------------------------------------- export interface ClaudeCodeBuilderOptions { /** Model to pass as --model to the CLI. */ model?: string; /** Override path to the claude binary (defaults to 'claude' on PATH). */ commandPath?: string; /** Request timeout in milliseconds (default 120 000). */ timeout?: number; /** Additional CLI flags passed to every invocation. */ extraFlags?: string[]; } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- /** Strip ANSI escape codes from CLI output. */ function stripAnsi(text: string): string { // eslint-disable-next-line no-control-regex return text.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, ''); } /** * Spawn the Claude CLI with a prompt on stdin and capture stdout. * Returns the raw text output (ANSI-stripped). */ function runClaude( prompt: string, options: ClaudeCodeBuilderOptions ): Promise<{ stdout: string; stderr: string; exitCode: number }> { const cmd = options.commandPath ?? 'claude'; const args: string[] = ['-p', '--output-format', 'text']; if (options.model) { args.push('--model', options.model); } if (options.extraFlags) { args.push(...options.extraFlags); } const timeout = options.timeout ?? 120_000; return new Promise((resolve, reject) => { const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, FORCE_COLOR: '0', // suppress ANSI in captured output CLAUDECODE: undefined, // prevent recursive detection }, }); let stdout = ''; let stderr = ''; child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString(); }); child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString(); }); // EOF protection — swallow EPIPE if the child closes stdin early child.stdin.on('error', (err: NodeJS.ErrnoException) => { if (err.code !== 'EPIPE' && err.code !== 'EOF') throw err; }); // Timeout handling: SIGTERM → 5 s → SIGKILL const timer = setTimeout(() => { child.kill('SIGTERM'); setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); }, 5_000); }, timeout); child.on('close', (code) => { clearTimeout(timer); resolve({ stdout: stripAnsi(stdout), stderr: stripAnsi(stderr), exitCode: code ?? 1, }); }); child.on('error', (err) => { clearTimeout(timer); reject(err); }); // Pipe the prompt via stdin child.stdin.write(prompt, () => { child.stdin.end(); }); }); } // --------------------------------------------------------------------------- // Spawn + retry wrapper // --------------------------------------------------------------------------- /** * Execute the Claude CLI and return trimmed output. * Retries once on empty output with a simplified prompt prefix. */ async function executeWithRetry( prompt: string, options: ClaudeCodeBuilderOptions, ): Promise { const attempt = async (p: string): Promise => { const result = await runClaude(p, options); // Handle process-level failures if (result.exitCode !== 0 && !result.stdout.trim()) { if (result.stderr.includes('ENOENT') || result.stderr.includes('not found') || result.stderr.includes('not recognized')) { throw new Error( 'Claude CLI not found. Install it with: npm install -g @anthropic-ai/claude-code' ); } throw new Error(result.stderr || `Claude CLI exited with code ${result.exitCode}`); } return result.stdout.trim(); }; // First attempt const output = await attempt(prompt); if (output) return output; // Retry once with a nudge prepended to the prompt console.warn('[ClaudeCode] Empty response — retrying once'); const retryOutput = await attempt( 'IMPORTANT: You must produce output. Do not return an empty response.\n\n' + prompt ); if (retryOutput) return retryOutput; throw new Error('Claude CLI returned empty output after retry'); } // --------------------------------------------------------------------------- // Change-op validation // --------------------------------------------------------------------------- const VALID_OPS = new Set(['update', 'replace', 'delete', 'insert', 'style-element', 'search-replace', 'search-insert']); /** * Validate a single change operation against the expected schema. * Returns true if the op is structurally valid, false otherwise. */ function isValidChangeOp(op: unknown): op is ChangeOp { if (!op || typeof op !== 'object') return false; const o = op as Record; if (typeof o.op !== 'string' || !VALID_OPS.has(o.op)) return false; switch (o.op) { case 'update': case 'replace': return typeof o.nodeId === 'string' && typeof o.html === 'string'; case 'delete': return typeof o.nodeId === 'string'; case 'insert': return typeof o.parentId === 'string' && typeof o.position === 'string' && typeof o.html === 'string'; case 'style-element': return typeof o.nodeId === 'string' && typeof o.style === 'string'; case 'search-replace': return typeof o.nodeId === 'string' && typeof o.search === 'string' && typeof o.replace === 'string'; case 'search-insert': return typeof o.nodeId === 'string' && typeof o.after === 'string' && typeof o.content === 'string'; default: return false; } } /** * Filter a list of change ops, keeping only valid ones. * Logs warnings for any skipped ops. */ function filterValidOps(ops: unknown[]): ChangeOp[] { const valid: ChangeOp[] = []; for (let i = 0; i < ops.length; i++) { const op = ops[i]; if (isValidChangeOp(op)) { valid.push(op); } else { console.warn(`[ClaudeCode] Skipping invalid change op at index ${i}:`, JSON.stringify(ops[i])); } } return valid; } // --------------------------------------------------------------------------- // Chat mode heuristic // --------------------------------------------------------------------------- /** * Simple heuristic to detect chat/question messages. * Per spec: message ends with `?` and is under 100 characters. */ function isChatQuestion(message: string): boolean { const trimmed = message.trim(); return trimmed.length < 100 && trimmed.endsWith('?'); } // --------------------------------------------------------------------------- // Builder factory // --------------------------------------------------------------------------- export function createClaudeCodeBuilder( userInstructions?: string, productName?: string, options?: ClaudeCodeBuilderOptions, ): Builder { const name = productName ?? 'SynthOS'; const opts: ClaudeCodeBuilderOptions = options ?? {}; return { async run(currentPage, additionalSections, userMessage, newBuild, _attachments?): Promise { try { const chatMode = !newBuild && isChatQuestion(userMessage); let prompt: string; if (chatMode) { // -- Chat prompt: no change-ops, no node annotations -- const contextParts: string[] = [ `\n${currentPage.content}\n`, ]; for (const section of additionalSections) { if (section.content) { contextParts.push(`${section.title}\n${section.content}`); } } prompt = `You are ${name}, a helpful assistant. Answer the user's question about their page.\n\n` + contextParts.join('\n\n') + `\n\n\n${userMessage}\n`; } else { // -- Build/change prompt (same structure as before) -- const systemParts: string[] = [ `${currentPage.title}\n${currentPage.content}`, ]; for (const section of additionalSections) { if (section.content) { systemParts.push(`${section.title}\n${section.content}`); } } const systemContent = systemParts.join('\n\n'); 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(name)); instructionParts.push(CHANGE_OPS_FORMAT_INSTRUCTION); const instructions = instructionParts.filter(s => s.trim() !== '').join('\n'); prompt = `${systemContent}\n\n\n${userMessage}\n\n\n${instructions}`; } // -- Spawn claude CLI (with retry on empty output) -- const output = await executeWithRetry(prompt, opts); // Chat mode always returns a reply — skip change-ops parsing if (chatMode) { return { kind: 'reply', text: output }; } // Try to parse as builder response (JSON change ops or reply) const parsed = parseBuilderResponse(output); // Validate individual change ops — skip invalid ones if (parsed.kind === 'transforms') { const validated = filterValidOps(parsed.changes); if (validated.length === 0) { // All ops were invalid — treat the raw output as a text reply return { kind: 'reply', text: output }; } return { kind: 'transforms', changes: validated }; } return parsed; } catch (err: unknown) { // Spawn failure (e.g. ENOENT when claude is not on PATH) if (err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code === 'ENOENT') { return { kind: 'error', error: new Error( 'Claude CLI not found. Install it with: npm install -g @anthropic-ai/claude-code' ), }; } return { kind: 'error', error: err instanceof Error ? err : new Error(String(err)) }; } } }; }