// Local UI for running a design prompt through a coding agent and previewing each direction. // npm start (reads ANTHROPIC_API_KEY from .env) import { spawn, type ChildProcess } from 'node:child_process'; import { createServer, type ServerResponse } from 'node:http'; import { appendFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { createInterface } from 'node:readline'; import { extname, join, normalize, resolve } from 'node:path'; const ROOT = resolve(import.meta.dirname, '..'); const RUNS = join(ROOT, 'runs'); const PORT = Number(process.env.PORT ?? 4321); const ORIGIN = `http://localhost:${PORT}`; const MODEL = 'claude-opus-5-5'; const EFFORT = 'high'; const PUBLIC_URL = 'https://pub-cdd85b5c268446a6b5c5838f5fccf28c.r2.dev'; // A fresh Claude Code config dir keeps the user's memory, plugins, MCP servers and settings out of runs. const AGENT_CONFIG = join(ROOT, '.agent-config'); const RESERVED = new Set(['content', 'inspo']); const CHIPS = [ 'in bauhaus style', 'featuring gridlines', '90s tech vibes', 'swiss typographic poster', 'brutalist web', 'y2k chrome and gloss', 'editorial magazine spreads', 'CRT terminal', 'risograph print texture', 'WebGL shader backgrounds', 'scroll-driven animation', 'kinetic typography', 'isometric 3D', 'zine collage', 'museum placard minimalism', 'dense information design', ]; type Inspo = { id: string; name: string; url: string }; function config(ref: string) { const dir = join(ROOT, 'ref', ref); return { ref, model: MODEL, effort: EFFORT, prompt: readFileSync(join(dir, 'prompt.md'), 'utf8'), inspo: JSON.parse(readFileSync(join(dir, 'inspo.json'), 'utf8')) as Inspo[], chips: CHIPS, }; } // --- runs --------------------------------------------------------------------- type Run = { meta: any; dir: string; events: object[]; clients: Set; child?: ChildProcess; seen: Map; // direction folder -> index.html mtime watcher?: NodeJS.Timeout; }; const live = new Map(); function emit(run: Run, event: object) { run.events.push(event); for (const res of run.clients) res.write(`data: ${JSON.stringify(event)}\n\n`); } const saveMeta = (run: Run) => writeFileSync(join(run.dir, 'meta.json'), JSON.stringify(run.meta, null, 2)); function directions(dir: string) { return readdirSync(dir, { withFileTypes: true }) .filter(d => d.isDirectory() && !RESERVED.has(d.name) && !d.name.startsWith('.') && existsSync(join(dir, d.name, 'index.html'))) .map(d => ({ name: d.name, mtime: statSync(join(dir, d.name, 'index.html')).mtimeMs })) .sort((a, b) => a.mtime - b.mtime); } function scanDirections(run: Run) { for (const d of directions(run.dir)) { const before = run.seen.get(d.name); if (before === d.mtime) continue; run.seen.set(d.name, d.mtime); emit(run, { type: before === undefined ? 'direction' : 'updated', name: d.name, url: `/runs/${run.meta.id}/${d.name}/index.html`, mtime: d.mtime }); } } /** One-line summary of what the agent is doing, for the status line and log. */ function describe(block: any): string | null { if (block.type === 'text') return block.text.trim() || null; if (block.type !== 'tool_use') return null; const i = block.input ?? {}; const target = i.file_path ?? i.url ?? i.query ?? i.description ?? i.command ?? i.pattern ?? ''; return `${block.name} ${String(target).replace(/\s+/g, ' ').slice(0, 160)}`.trim(); } async function startRun(body: { ref: string; prompt: string; images: string[] }) { const id = `${new Date().toISOString().replace(/[:.]/g, '-')}-${MODEL}`; const dir = join(RUNS, id); mkdirSync(join(dir, 'inspo'), { recursive: true }); // Workspace: posts (with public image URLs) + the selected inspo images. mkdirSync(join(dir, 'content')); cpSync(join(ROOT, 'base/posts.remote.json'), join(dir, 'content/posts.json')); cpSync(join(ROOT, 'base/posts'), join(dir, 'content/posts'), { recursive: true }); for (const f of readdirSync(join(dir, 'content/posts'))) { const p = join(dir, 'content/posts', f); writeFileSync(p, readFileSync(p, 'utf8').replaceAll('](media/', `](${PUBLIC_URL}/base/media/`)); } const inspo = config(body.ref).inspo.filter(i => body.images.includes(i.url)); await Promise.all(inspo.map(async i => { const res = await fetch(i.url); writeFileSync(join(dir, 'inspo', `${i.id}.jpg`), Buffer.from(await res.arrayBuffer())); })); writeFileSync(join(dir, 'brief.md'), body.prompt); const run: Run = { meta: { id, ref: body.ref, model: MODEL, effort: EFFORT, harness: 'claude-code', prompt: body.prompt, images: body.images, startedAt: new Date().toISOString() }, dir, events: [], clients: new Set(), seen: new Map(), }; live.set(id, run); saveMeta(run); emit(run, { type: 'run', id }); const system = readFileSync(join(ROOT, 'app/system.md'), 'utf8') .replaceAll('{{RUN_URL}}', `${ORIGIN}/runs/${id}`) .replaceAll('{{SCREENSHOT}}', join(ROOT, 'app/screenshot.mjs')); mkdirSync(AGENT_CONFIG, { recursive: true }); const child = spawn('claude', [ '-p', body.prompt, '--append-system-prompt', system, '--model', MODEL, '--effort', EFFORT, '--dangerously-skip-permissions', '--strict-mcp-config', '--output-format', 'stream-json', '--verbose', ], { cwd: dir, env: { ...process.env, CLAUDE_CONFIG_DIR: AGENT_CONFIG }, stdio: ['ignore', 'pipe', 'pipe'], }); run.child = child; run.watcher = setInterval(() => scanDirections(run), 1500); createInterface({ input: child.stdout! }).on('line', line => { appendFileSync(join(dir, 'events.jsonl'), line + '\n'); let ev: any; try { ev = JSON.parse(line); } catch { return; } if (ev.type === 'assistant') { for (const block of ev.message?.content ?? []) { const text = describe(block); if (text) emit(run, { type: 'activity', kind: block.type === 'text' ? 'say' : 'tool', text }); } } else if (ev.type === 'result') { Object.assign(run.meta, { cost: ev.total_cost_usd, durationMs: ev.duration_ms, turns: ev.num_turns, usage: ev.usage, notes: ev.result, isError: ev.is_error }); } }); let stderr = ''; child.stderr!.on('data', d => { stderr += d; }); child.on('close', code => { clearInterval(run.watcher); scanDirections(run); Object.assign(run.meta, { finishedAt: new Date().toISOString(), exitCode: code, directions: directions(dir).map(d => d.name), ...(code !== 0 && !run.meta.stopped ? { error: stderr.trim().slice(-2000) || `exited with ${code}` } : {}), }); saveMeta(run); emit(run, { type: 'end', meta: run.meta }); for (const res of run.clients) res.end(); live.delete(id); }); return id; } function attach(id: string, res: ServerResponse) { const run = live.get(id); res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' }); if (!run) { // Finished run: replay its final state. const meta = JSON.parse(readFileSync(join(RUNS, id, 'meta.json'), 'utf8')); for (const name of meta.directions ?? []) res.write(`data: ${JSON.stringify({ type: 'direction', name, url: `/runs/${id}/${name}/index.html` })}\n\n`); res.end(`data: ${JSON.stringify({ type: 'end', meta })}\n\n`); return; } for (const ev of run.events) res.write(`data: ${JSON.stringify(ev)}\n\n`); run.clients.add(res); res.on('close', () => run.clients.delete(res)); } function listRuns() { if (!existsSync(RUNS)) return []; return readdirSync(RUNS).sort().reverse() .filter(id => existsSync(join(RUNS, id, 'meta.json'))) .map(id => ({ ...JSON.parse(readFileSync(join(RUNS, id, 'meta.json'), 'utf8')), live: live.has(id) })); } // --- http ----------------------------------------------------------------------- const MIME: Record = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.md': 'text/plain; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.mp4': 'video/mp4', }; function serveFile(res: ServerResponse, base: string, rel: string) { let file = normalize(join(base, rel)); if (!file.startsWith(base)) { res.writeHead(403).end(); return; } if (existsSync(file) && statSync(file).isDirectory()) file = join(file, 'index.html'); if (!existsSync(file)) { res.writeHead(404).end('not found'); return; } // Previews run in null-origin sandboxed iframes, so their fetches are cross-origin. res.writeHead(200, { 'content-type': MIME[extname(file)] ?? 'application/octet-stream', 'access-control-allow-origin': '*', 'cache-control': 'no-store' }) .end(readFileSync(file)); } createServer(async (req, res) => { const url = new URL(req.url!, ORIGIN); const json = (data: unknown) => res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(data)); try { if (url.pathname === '/api/config') return json(config(url.searchParams.get('ref') ?? '1')); if (url.pathname === '/api/runs') return json(listRuns()); if (url.pathname === '/api/events') return attach(url.searchParams.get('id')!, res); if (url.pathname === '/api/run' && req.method === 'POST') { let raw = ''; for await (const chunk of req) raw += chunk; return json({ id: await startRun(JSON.parse(raw)) }); } if (url.pathname === '/api/stop' && req.method === 'POST') { const run = live.get(url.searchParams.get('id')!); if (run) { run.meta.stopped = true; run.child?.kill('SIGTERM'); } return json({ ok: !!run }); } if (url.pathname.startsWith('/runs/')) return serveFile(res, RUNS, decodeURIComponent(url.pathname.slice('/runs/'.length))); return serveFile(res, join(ROOT, 'app/public'), url.pathname === '/' ? 'index.html' : url.pathname.slice(1)); } catch (err) { console.error(err); res.writeHead(500).end(String(err)); } }).listen(PORT, () => console.log(`stylize on ${ORIGIN}`)); process.on('SIGINT', () => { for (const run of live.values()) run.child?.kill('SIGTERM'); process.exit(); });