Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(design-agent): P0-B production wiring + P1 benchmark — BYOK adapter, API route, 22-brief fidelity harness

Ashiq Hussain Mir4239cae29650
diff --git a/.gitignore b/.gitignore
index 354d7ae..51c5432 100644
--- a/.gitignore
+++ b/.gitignore
@@ -90,3 +90,7 @@ mini-services/
/test-results/
/playwright-report/
core
+
+# design-agent acceptance/benchmark artifacts (kept in download/, not the repo)
+/scripts/designspec-agent/
+/scripts/designspec-browser-bundle.js
diff --git a/docs/DESIGN-AGENT-ACCEPTANCE-REPORT.md b/docs/DESIGN-AGENT-ACCEPTANCE-REPORT.md
new file mode 100644
index 0000000..df6aaec
--- /dev/null
+++ b/docs/DESIGN-AGENT-ACCEPTANCE-REPORT.md
@@ -0,0 +1,135 @@
+# DesignAgent — autonomous design pipeline acceptance report (24 Nov 2026)
+
+**Branch:** `feat/design-agent` (stacked on `feat/design-spec-foundation`, both updated
+against current main) · **Research:** `research/AUTONOMOUS-AGENT-RESEARCH.md`
+**What this is:** the Phase B design agent — a code-orchestrated autonomous pipeline
+over the DesignSpec engine, built from the patterns that production agent systems
+actually use (ReAct tool-registry discipline, the OpenAI Agents SDK "code
+orchestration + evaluator loop" guidance, and PosterGen's staged specialists with
+embedded design principles). The model plans and critiques; deterministic code runs
+everything else and judges the result.
+
+## The P0 items from the external review, closed
+
+1. **Visual verification is now an EXECUTION STAGE, not a side script.** After the
+ deterministic checks pass, the pipeline renders the pages through a
+ `DesignRenderer` seam, critiques the real pixels through a `critique` seam, and
+ can trigger one more revision round from P1/P2 findings — bounded, cycle-guarded,
+ cancellation-aware. The hierarchy is absolute: a critique-revision is only
+ accepted if it ALSO passes every deterministic check and actually reduces the
+ actionable finding count; otherwise the previous passing design is kept and the
+ outcome is disclosed ("checks outrank critique"). No renderer or vision seam →
+ `unavailable`, disclosed, never faked. Five unit tests cover the stage
+ deterministically (improved / verified / rejected-by-checks / unavailable /
+ unparseable-discarded).
+2. **A production BYOK adapter exists and is wired into the provider system.**
+ `src/lib/design-agent/byok-adapter.ts` builds the `DesignAgentModel` seam from
+ resolved `ProviderContext`s — the same BYOK resolution chain
+ (user providers → instance multi/db/env/file), the same SDK client, the same
+ JSON-mode-with-fallback call shape the shipped design-spec normalizer uses. The
+ route `POST /api/ai/design-agent` rides `withProvider`: admin kill switch
+ (`ai.features.designAgent`), same-origin abuse guard, per-feature rate limits,
+ session-BYOK resolution, request-abort cancellation through the pipeline's signal
+ seam, and the app's REAL vector export (`exportPageToSVG`) as the renderer.
+ Vision critique resolves from the user's vision slot when configured; without
+ it, visual verification is disclosed as unavailable. Adapter call shapes are
+ unit-tested with stub SDK clients.
+3. **The toolbox grew to the full declared vocabulary.** Every block kind now has a
+ dedicated deterministic builder: hero, feature-cards, stat-row (uniform value
+ baselines), mockup (4:3 visual frame), timeline (route line + stops), gallery
+ (2/3-up frames), footer (divider + sign-off). No kind falls back to a generic
+ stack.
+4. **The design-quality benchmark exists** (`scripts/designspec-agent-benchmark.ts`):
+ 22 diverse briefs (events, menus, retail, nonprofit, music, education, hiring,
+ real estate, wellness, launch, exhibition, market, fitness, conference, bakery,
+ marathon, theatre, health, café, demo day, cleanup, crafts) × the REAL pipeline,
+ measuring instruction fidelity the deterministic, non-fakeable way: exact texts,
+ seed-guaranteed colors, dimensions, brief→spec conformance, revision rounds,
+ model calls, wall time, honest-failure and cycle-guard counts.
+
+## The acceptance run (real model, real render, real VLM, in one loop)
+
+Brief: the 1080×1350 race poster — three verbatim lines (one with middle dots), two
+required hexes, a stats band and a framed photo area.
+
+```
+extract-brief (deterministic) PASS — 3 required texts, 2 required colors
+plan (GLM, round 1) brief-conformance FAIL — the model split
+ "12km · Dachigam Road · 26 Jan" across
+ three stat slots (engine checks GREEN;
+ only the agent layer can see this)
+feedback → revise (round 2) every required text/color/dimension carried;
+ all compile checks PASS
+render (pass 1) the real exportPageToSVG in real Chromium
+critique (VLM on the PNG) 6 issues, 4 actionable (P1/P2)
+visual-revision model revised from the findings; the new
+ spec ALSO passed every check → accepted
+verify (re-render + re-critique) 4 actionable remaining (was 4) → honestly
+ reported 'unverified', NOT 'improved'
+```
+
+5 model calls · 2 revision rounds · 36 s · outcome **passed**, with the visual
+verification result honestly reported as not-improved rather than faked. The
+critique's findings (band rhythm, secondary-text contrast at the WCAG floor,
+typographic pairing, margins) are recorded as the next-round engine roadmap —
+advisory, never overriding the checks.
+
+An earlier run the same day demonstrated the guard path instead: the model
+repeated its spec verbatim under feedback → cycle guard → `guard-cycled`, honest
+stop, evidence kept. Both paths are by design and tested.
+
+## What the evaluator loop caught (why the agent layer exists)
+
+The round-1 spec **passed every engine check** — the compiler validates spec→page
+fidelity, and the spec's own slots were internally consistent. What was wrong was
+brief→spec fidelity: the model had dropped (or split) a user-required line. The
+pipeline's `briefConformance()` check (required texts verbatim in slots, required
+hexes in seeds, exact dimensions) is the evaluator the engine cannot be, and the
+revision loop fixed it in one feedback round. The improved feedback now instructs
+precisely: ONE slot with the full exact string, never split.
+
+## The benchmark (22 briefs, real model)
+
+See `benchmark-report.md` in the run artifacts for the full table. Measured:
+pass rate, self-corrections-to-pass, honest failures, cycle guards, model calls
+per brief, revision rounds, wall time. Corpus scope, honestly: Latin-script briefs
+only — the engine's SVG export has no non-Latin font pipeline yet, and a
+multilingual brief would pass text-presence checks while rendering tofu, which the
+harness refuses to claim as fidelity. Multilingual fidelity lands with the font
+work + in-benchmark visual passes.
+
+## Guards and honesty (tested, not claimed)
+
+- **bounded revisions** (default 3, shared by check- and critique-origin rounds)
+- **cycle guard** — a model repeating its spec verbatim stops the loop honestly
+- **parse failures** recoverable against the prior spec, or fail honestly
+- **caller cancellation** (AbortSignal) honored before every model call
+- 22 design-agent unit tests (16 pipeline + 6 adapter) prove all of this
+ deterministically with scripted models; branch suite 1,647+ green, tsc + eslint
+ clean
+
+## Not exercised (no claims beyond it)
+
+- No in-app client panel for the new route yet (the route is the server contract;
+ the chat agent panel continues to serve interactive editing; a dedicated
+ generation panel is the next UI step).
+- Visual verification in the app route delivers the SVG as a data URL — providers
+ that cannot ingest SVG fail-closed to 'unavailable' (disclosed), and the
+ browser-rendered capture path (already shipped in the chat agent) remains the
+ richer production option for panel integration.
+- The benchmark measures instruction fidelity; aesthetic quality is judged by the
+ visual-verification loop, whose current verdict on the sample is honest and
+ mixed — the critique findings list is the engine's roadmap, not a score.
+
+## Reproduce
+
+```
+bun scripts/designspec-agent-run.ts run <promptFile> <outDir> --visual
+bun scripts/designspec-agent-benchmark.ts run <outRoot> <from> <to>
+bun scripts/designspec-agent-benchmark.ts aggregate <outRoot>
+```
+
+Artifacts in `download/designspec-agent/`: the rendered posters (PNG/SVG, both the
+pre- and post-revision renders), the final spec, compile + render checks, the full
+run report (stages, model calls, revisions, visual passes, VLM findings), and the
+benchmark report.
diff --git a/scripts/designspec-agent-benchmark.ts b/scripts/designspec-agent-benchmark.ts
new file mode 100644
index 0000000..7ffdf3a
--- /dev/null
+++ b/scripts/designspec-agent-benchmark.ts
@@ -0,0 +1,223 @@
+// ─────────────────────────────────────────────────────────────
+// DesignAgent benchmark (Phase B P1, 24 Nov 2026).
+//
+// 22 diverse briefs × the REAL pipeline (GLM planner via z-ai chat;
+// plan + brief-conformance + compile + bounded self-correction —
+// the visual stage is opt-in per run, not benchmarked here).
+//
+// Measured, per brief and aggregate:
+// · outcome (passed / failed-honestly / guard-cycled)
+// · instruction fidelity — the deterministic, non-fakeable kind:
+// exact texts (NFC-equal slots), required colors (seed
+// guarantee), dimensions, brief conformance
+// · revision rounds, model calls, elapsed ms, cycle guards
+// · engine warnings (density, fit)
+//
+// Corpus scope, honestly: Latin-script briefs only — the engine's
+// SVG export has no non-Latin font pipeline yet, and without the
+// visual loop in the benchmark a Devanagari/Arabic brief would
+// "pass" deterministically while rendering tofu. That combination
+// is exactly what this harness refuses to claim. Multilingual
+// fidelity lands with the font work + in-benchmark visual passes.
+//
+// Usage (run in chunks — each brief is ~2-4 model calls):
+// bun scripts/designspec-agent-benchmark.ts run <outRoot> <from> <to>
+// bun scripts/designspec-agent-benchmark.ts aggregate <outRoot>
+// ─────────────────────────────────────────────────────────────
+
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync } from 'node:fs'
+import path from 'node:path'
+import { runDesignAgent } from '@/lib/design-agent/pipeline'
+import type { DesignAgentModel } from '@/lib/design-agent/model'
+import { PLANNER_SYSTEM, planUserPrompt, revisionUserPrompt } from '@/lib/design-agent/prompts'
+
+const TMP = '/tmp/designspec-bench'
+
+/** CLI-backed planner call with 429 backoff (the shared sandbox CLI
+ * is rate-limited; a benchmark burst trips it — wait and retry
+ * instead of failing the brief). */
+function cliPlan(prompt: string, system: string): string {
+ const out = `${TMP}-chat.json`
+ const delays = [0, 30_000, 60_000, 90_000]
+ for (let attempt = 0; attempt < delays.length; attempt++) {
+ if (delays[attempt]) {
+ const until = Date.now() + delays[attempt]
+ while (Date.now() < until) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, Math.min(5_000, until - Date.now()))
+ }
+ try {
+ execFileSync('z-ai', ['chat', '-p', prompt, '-s', system, '-o', out], { stdio: ['ignore', 'ignore', 'ignore'] })
+ const reply = JSON.parse(readFileSync(out, 'utf-8')) as { choices?: { message?: { content?: string } }[] }
+ return reply.choices?.[0]?.message?.content ?? ''
+ } catch (err) {
+ const msg = String(err)
+ if (attempt === delays.length - 1) throw err
+ if (!msg.includes('429') && !msg.includes('Too many')) {
+ // non-rate errors (parse, network) still retry once, then bubble
+ if (attempt > 1) throw err
+ }
+ }
+ }
+ return ''
+}
+
+const cliModel: DesignAgentModel = {
+ plan: async (req) =>
+ cliPlan(
+ req.feedback ? revisionUserPrompt(req.feedback) : planUserPrompt(req.brief),
+ PLANNER_SYSTEM,
+ ),
+}
+
+/** 22 briefs — events, commerce, food, nonprofit, education, music,
+ * recruitment, real estate…; varying required-text counts, colors,
+ * formats and vocabulary demands (stats bands, timelines, mockups). */
+const BRIEFS: { id: string; prompt: string }[] = [
+ { id: 'b01-race', prompt: 'Create a poster for a mountain running event. The poster must show these exact lines: "Valley Runs 2026", "12km · Dachigam Road · 26 Jan", "Register Free". Use the colors #0D47A1 and #FF6F00 somewhere. Size 1080x1350. Include a stats band with runner numbers and a framed photo area. Energetic, bold, race-day feel.' },
+ { id: 'b02-menu', prompt: 'Design a dinner menu board. It must show exactly: "Kashmiri Wazwan Evening", "Rista · Rogan Josh · Gustaba", "Rs 1,200 per guest". Use #1B5E20 and #F9A825. Size 1080x1350. Warm, traditional, appetizing.' },
+ { id: 'b03-sale', prompt: 'Make a bold sale poster. Must show exactly: "Mega Winter Sale", "Up to 60% Off Everything", "This weekend only". Colors: #D32F2F and #212121. Size 1080x1080. Loud, retail, high-contrast.' },
+ { id: 'b04-nonprofit', prompt: 'Create a charity fundraiser poster. Must show exactly: "Books for Every Child", "₹500 sponsors a full school year", "Donate before 31 Dec". Use #00695C and #FFB300. Size 1080x1350. Hopeful, warm, trustworthy.' },
+ { id: 'b05-music', prompt: 'Design a music festival poster. Must show exactly: "Alpine Nights Festival", "12–14 June 2026", "Tickets from Rs 3,500". Colors #311B92 and #FF4081. Size 1080x1350. Dark, electric, nightlife energy.' },
+ { id: 'b06-education', prompt: 'Make a coding bootcamp poster. Must show exactly: "12-Week Full-Stack Bootcamp", "Batch starts 5 January", "Scholarships for 10 students". Use #1565C0 and #FFFFFF. Size 1080x1350. Modern, clean, career-focused.' },
+ { id: 'b07-recruit', prompt: 'Create a hiring poster. Must show exactly: "We are hiring Designers", "Apply by 15 Jan 2027", "Remote-friendly". Colors #37474F and #FF7043. Size 1080x1080. Professional, direct, confident.' },
+ { id: 'b08-realestate', prompt: 'Design an open-house poster. Must show exactly: "Open House Sunday", "11 AM – 4 PM · Gulmarg Residences", "RSVP 98x000 000". Use #4E342E and #FFCA28. Size 1080x1350. Elegant, premium, inviting.' },
+ { id: 'b09-yoga', prompt: 'Make a wellness retreat poster. Must show exactly: "Himalayan Yoga Retreat", "7 days of stillness", "From Rs 18,000". Colors #2E7D32 and #FFF8E1. Size 1080x1350. Calm, minimal, breathing room.' },
+ { id: 'b10-tech', prompt: 'Create a product-launch poster. Must show exactly: "Canvix 2.0 Launch Week", "One prompt, one professional design", "Try it free — 18 Feb". Use #0D47A1 and #FF6F00. Size 1200x628. Sharp, confident, modern.' },
+ { id: 'b11-exhibit', prompt: 'Design an art-exhibition poster. Must show exactly: "Threads of the Valley", "Contemporary Kashmiri Textiles", "4 Mar – 30 Apr 2026". Colors #4A148C and #FFD54F. Size 1080x1350. Refined, gallery-quiet.' },
+ { id: 'b12-farmers', prompt: 'Make a farmers-market poster. Must show exactly: "Saturday Farmers Market", "6 AM – 1 PM · Lal Chowk", "Fresh from the valley". Use #1B5E20 and #F9A825. Size 1080x1080. Friendly, earthy, hand-made warmth.' },
+ { id: 'b13-fitness', prompt: 'Create a gym-promotion poster. Must show exactly: "New Year, New You", "First month free", "Join before 10 Jan". Colors #B71C1C and #FFEB3B. Size 1080x1350. High-energy, motivational.' },
+ { id: 'b14-conference', prompt: 'Design a tech-conference poster. Must show exactly: "DevSrinagar 2026", "26–27 September · SKICC", "Early bird Rs 1,999". Use #004D40 and #FF6F00. Size 1080x1350. Serious, tech-forward, structured. Include a schedule timeline band.' },
+ { id: 'b15-bakery', prompt: 'Make a bakery poster. Must show exactly: "Saffron & Almond Bakes", "Order 48 hours ahead", "Call 95x000 000". Colors #5D4037 and #FFB300. Size 1080x1080. Cozy, artisanal, golden warmth.' },
+ { id: 'b16-marathon', prompt: 'Create a marathon poster. Must show exactly: "Srinagar Half Marathon", "21.0975 km · 2 Feb 2026", "Register at srinagarrun.in". Use #01579B and #FFC107. Size 1080x1350. Athletic, crisp, morning-light energy. Add a stats band with participant numbers.' },
+ { id: 'b17-theatre', prompt: 'Design a theatre poster. Must show exactly: "Bhand Pather: The Living Tradition", "8 PM nightly · Abhinav Theatre", "Tickets Rs 300". Colors #880E4F and #E0E0E0. Size 1080x1350. Dramatic, dark-stage contrast.' },
+ { id: 'b18-vaccination', prompt: 'Make a health-camp poster. Must show exactly: "Free Health Camp", "9 AM – 4 PM · Community Hall", "Bring your health card". Use #00695C and #FFFFFF. Size 800x2000. Clear, accessible, high-contrast, calm urgency.' },
+ { id: 'b19-coffee', prompt: 'Create a café poster. Must show exactly: "Pheran & Pour", "Kahwa served till dusk", "Open 8 AM daily". Colors #3E2723 and #FF8F00. Size 1080x1080. Warm, slow, aromatic mood.' },
+ { id: 'b20-startup', prompt: 'Design a demo-day poster. Must show exactly: "Demo Day Winter 2026", "10 startups, 5 minutes each", "Apply to pitch by 20 Dec". Use #1A237E and #FF5252. Size 1080x1350. Ventures, momentum, bold numerals.' },
+ { id: 'b21-cleanup', prompt: 'Make a lake-cleanup drive poster. Must show exactly: "Save Dal, One Sunday", "7 AM · Boulevard Road", "Volunteers get breakfast". Colors #0277BD and #AED581. Size 1080x1350. Community, fresh, hopeful. Include a stat row with last year\'s numbers.' },
+ { id: 'b22-crafts', prompt: 'Create a craft-workshop poster. Must show exactly: "Papier-Mâché Workshop", "Saturdays · 11 AM", "Materials included · Rs 800". Use #6A1B9A and #FFD600. Size 1080x1350. Artisanal, playful, colorful. Add a framed photo area for student work.' },
+]
+
+const phase = process.argv[2]
+const outRoot = process.argv[3]
+
+if (phase !== 'run' && phase !== 'aggregate') {
+ console.error('usage: bun scripts/designspec-agent-benchmark.ts run <outRoot> <from> <to> | aggregate <outRoot>')
+ process.exit(2)
+}
+
+if (phase === 'run') {
+ const from = Math.max(0, Number(process.argv[4] || 0))
+ const to = Math.min(BRIEFS.length, Number(process.argv[5] || BRIEFS.length))
+ mkdirSync(outRoot, { recursive: true })
+ const results: unknown[] = []
+ for (let i = from; i < to; i++) {
+ const brief = BRIEFS[i]
+ const outDir = path.join(outRoot, brief.id)
+ mkdirSync(outDir, { recursive: true })
+ writeFileSync(path.join(outDir, 'prompt.txt'), brief.prompt)
+ const started = Date.now()
+ let run
+ try {
+ run = await runDesignAgent({ prompt: brief.prompt, model: cliModel })
+ } catch (err) {
+ results.push({ id: brief.id, outcome: 'error', error: String(err) })
+ console.log(`${brief.id} ERROR ${String(err).slice(0, 80)}`)
+ continue
+ }
+ const elapsedMs = Date.now() - started
+ if (run.report.spec) writeFileSync(path.join(outDir, 'spec.json'), JSON.stringify(run.report.spec, null, 2))
+ if (run.pages) writeFileSync(path.join(outDir, 'pages.json'), JSON.stringify(run.pages, null, 2))
+ if (run.checks) writeFileSync(path.join(outDir, 'checks.json'), JSON.stringify(run.checks, null, 2))
+ const rec = {
+ id: brief.id,
+ outcome: run.outcome,
+ modelCalls: run.report.modelCalls,
+ revisionRounds: run.report.revisionRounds,
+ cycleGuard: run.report.cycleGuard,
+ briefConformanceFailures: run.briefConformance.length,
+ checks: run.checks ? { passed: run.checks.passed, failures: run.checks.failures.length } : null,
+ warnings: run.warnings.length,
+ elapsedMs,
+ }
+ writeFileSync(path.join(outDir, 'result.json'), JSON.stringify(rec, null, 2))
+ results.push(rec)
+ console.log(
+ `${brief.id} ${run.outcome.padEnd(15)} calls=${run.report.modelCalls} rev=${run.report.revisionRounds} ` +
+ `briefFails=${run.briefConformance.length} ${elapsedMs}ms`,
+ )
+ }
+ writeFileSync(path.join(outRoot, `chunk-${from}-${to}.json`), JSON.stringify(results, null, 2))
+ console.log(`chunk ${from}-${to} done: ${results.length} briefs`)
+ process.exit(0)
+}
+
+// ── aggregate ──
+const dirs = readdirSync(outRoot).filter((d) => d.startsWith('b') && d.length > 3 && existsSync(path.join(outRoot, d, 'result.json')))
+const rows = dirs
+ .map((d) => JSON.parse(readFileSync(path.join(outRoot, d, 'result.json'), 'utf-8')) as Record<string, number | string | boolean>)
+ .sort((a, b) => String(a.id).localeCompare(String(b.id)))
+
+const passed = rows.filter((r) => r.outcome === 'passed').length
+const honestFails = rows.filter((r) => r.outcome === 'failed-honestly').length
+const cycled = rows.filter((r) => r.outcome === 'guard-cycled').length
+const avg = (xs: number[]) => (xs.length ? Math.round(xs.reduce((a, b) => a + b, 0) / xs.length) : 0)
+
+const summary = {
+ briefs: rows.length,
+ passed,
+ failedHonestly: honestFails,
+ guardCycled: cycled,
+ passRate: rows.length ? Number((passed / rows.length).toFixed(3)) : 0,
+ avgModelCalls: avg(rows.map((r) => Number(r.modelCalls ?? 0))),
+ avgRevisionRounds: avg(rows.map((r) => Number(r.revisionRounds ?? 0))),
+ avgElapsedMs: avg(rows.map((r) => Number(r.elapsedMs ?? 0))),
+ totalModelCalls: rows.reduce((a, r) => a + Number(r.modelCalls ?? 0), 0),
+ // the self-correction story: runs that needed at least one revision
+ // and still finished passed
+ selfCorrectedToPass: rows.filter((r) => r.outcome === 'passed' && Number(r.revisionRounds ?? 0) > 0).length,
+}
+
+writeFileSync(path.join(outRoot, 'benchmark-report.json'), JSON.stringify({ summary, rows }, null, 2))
+
+const md = [
+ '# DesignAgent benchmark — instruction fidelity (24 Nov 2026)',
+ '',
+ `**${summary.briefs} diverse briefs · real GLM planner · deterministic evaluation.**`,
+ '',
+ `| metric | value |`,
+ `| --- | --- |`,
+ `| briefs run | ${summary.briefs} |`,
+ `| passed (all checks + brief conformance) | ${summary.passed} (${(summary.passRate * 100).toFixed(0)}%) |`,
+ `| failed honestly | ${summary.failedHonestly} |`,
+ `| cycle-guarded | ${summary.guardCycled} |`,
+ `| self-corrected to pass (≥1 revision, finished passed) | ${summary.selfCorrectedToPass} |`,
+ `| avg model calls per brief | ${summary.avgModelCalls} |`,
+ `| avg revision rounds | ${summary.avgRevisionRounds} |`,
+ `| avg wall time per brief | ${(summary.avgElapsedMs / 1000).toFixed(1)}s |`,
+ `| total model calls | ${summary.totalModelCalls} |`,
+ '',
+ 'Fidelity here is the deterministic, non-fakeable kind: exact texts',
+ '(NFC-equal slots, rendered through the real export pipeline in the',
+ 'single-brief acceptance runs), required colors via the seed',
+ 'guarantee, exact dimensions, and the brief→spec conformance check',
+ 'the agent layer owns. Aesthetic quality is judged separately by',
+ 'the visual-verification loop (advisory, VLM-on-the-real-render).',
+ '',
+ '## Per-brief outcomes',
+ '',
+ `| brief | outcome | calls | revisions | brief-fails | wall |`,
+ `| --- | --- | --- | --- | --- | --- |`,
+ ...rows.map(
+ (r) =>
+ `| ${r.id} | ${r.outcome} | ${r.modelCalls} | ${r.revisionRounds} | ${r.briefConformanceFailures} | ${(Number(r.elapsedMs) / 1000).toFixed(1)}s |`,
+ ),
+ '',
+ 'Corpus scope: Latin-script briefs only. Multilingual fidelity is',
+ 'scoped out until the font pipeline and in-benchmark visual passes',
+ 'exist — a Devanagari brief would pass text-presence checks while',
+ 'rendering tofu, which this harness refuses to claim as fidelity.',
+ '',
+].join('\n')
+writeFileSync(path.join(outRoot, 'benchmark-report.md'), md)
+console.log(`══ benchmark aggregate ══`)
+console.log(JSON.stringify(summary, null, 2))
diff --git a/src/app/api/ai/design-agent/route.ts b/src/app/api/ai/design-agent/route.ts
new file mode 100644
index 0000000..fdb3dbf
--- /dev/null
+++ b/src/app/api/ai/design-agent/route.ts
@@ -0,0 +1,110 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { withProvider, getClientForSlotForUser } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
+import { getSessionUser } from '@/lib/auth/session'
+import { runDesignAgent, type DesignRenderer } from '@/lib/design-agent/pipeline'
+import { byokDesignAgentModel } from '@/lib/design-agent/byok-adapter'
+import { exportPageToSVG } from '@/lib/svg-export'
+import type { PageData } from '@/lib/types'
+import type { DesignSpec } from '@/lib/design-spec/types'
+
+// ─────────────────────────────────────────────────────────────
+// POST /api/ai/design-agent — the autonomous design pipeline as a
+// production route (v0.30, DesignAgent Phase B P0-B).
+//
+// One prompt in, one verified design out:
+// extract-brief → plan (BYOK text provider) → parse → brief-
+// conformance + compile+check → bounded self-correction →
+// visual verification (render → BYOK vision critique → guarded
+// correction → re-verify) → editable pages + run report.
+//
+// Security/lifecycle: everything rides withProvider — the admin
+// kill switch (ai.features.designAgent), the same-origin abuse
+// guard, per-feature rate limits, and BYOK resolution (the
+// session user's own providers first, then the instance chain).
+// Request abort cancels the pipeline through its signal seam.
+//
+// The renderer is the app's REAL vector export (exportPageToSVG)
+// delivered as a data URL — providers that cannot ingest SVG
+// images fail-closed: the pipeline reports 'visual verification
+// unavailable' instead of pretending a review happened.
+// ─────────────────────────────────────────────────────────────
+
+export const runtime = 'nodejs'
+export const maxDuration = 120
+
+interface DesignAgentBody {
+ prompt?: string
+ /** opt out of the visual-verification stage (plan+check only) */
+ visual?: boolean
+ /** cap the revision rounds (1-3; default 3) */
+ maxRevisions?: number
+}
+
+const svgRenderer: DesignRenderer = {
+ render: async (pages: PageData[], spec: DesignSpec) => {
+ try {
+ const svg = exportPageToSVG(pages[0], spec.format.width, spec.format.height)
+ if (!svg) return null
+ const dataUrl = `data:image/svg+xml;base64,${Buffer.from(svg, 'utf-8').toString('base64')}`
+ return { image: dataUrl }
+ } catch {
+ return null
+ }
+ },
+}
+
+/** POST /api/ai/design-agent — one prompt → compiled, checked design. */
+async function __canvix_post(req: NextRequest) {
+ const body = (await req.json().catch(() => ({}))) as DesignAgentBody
+ const prompt = (body.prompt ?? '').trim().slice(0, 2000)
+ if (!prompt) return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })
+
+ const maxRevisions = Math.min(3, Math.max(1, Number(body.maxRevisions) || 3))
+
+ return withProvider('design-agent', req, { limit: 6, windowSec: 60 }, async (ctx) => {
+ // the vision seam is OPTIONAL: resolve it (user BYOK first), fall
+ // back to none — the pipeline discloses 'unavailable' honestly
+ let vision: Awaited<ReturnType<typeof getClientForSlotForUser>> = null
+ if (body.visual !== false) {
+ try {
+ const user = await getSessionUser(req)
+ vision = await getClientForSlotForUser('vision', user?.id ?? null)
+ } catch {
+ vision = null
+ }
+ }
+ const model = byokDesignAgentModel(ctx, vision)
+
+ const run = await runDesignAgent({
+ prompt,
+ model,
+ renderer: body.visual === false ? undefined : svgRenderer,
+ limits: { maxRevisions, maxVisualPasses: 1 },
+ // a LIVE view of the request's abort state — the pipeline
+ // re-reads it before every model call and stage
+ signal: {
+ get aborted() {
+ return req.signal.aborted
+ },
+ },
+ })
+
+ const status = run.outcome === 'passed' ? 200 : run.outcome === 'aborted' ? 499 : 422
+ return NextResponse.json(
+ {
+ outcome: run.outcome,
+ pages: run.pages ?? [],
+ checks: run.checks ?? null,
+ briefConformance: run.briefConformance,
+ warnings: run.warnings,
+ report: run.report,
+ },
+ { status },
+ )
+ })
+}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/ai/design-agent', __canvix_post)
diff --git a/src/lib/admin/config.ts b/src/lib/admin/config.ts
index 86d9228..5c82aeb 100644
--- a/src/lib/admin/config.ts
+++ b/src/lib/admin/config.ts
@@ -62,6 +62,10 @@ export const AI_FEATURES = [
'themeGeneration', // AI palette/font theme, applied design-wide
'altText', // accessibility alt text for images (vision slot)
'videoGeneration', // text-to-video via the video slot
+ // v0.30 (DesignAgent, Phase B):
+ 'designAgent', // autonomous one-prompt design generation: plan →
+ // compile → self-correct → visual verify (text slot plans; the
+ // vision slot powers the advisory critique when configured)
] as const
export type AiFeature = (typeof AI_FEATURES)[number]
@@ -130,6 +134,7 @@ export const DEFAULT_FEATURES: StoredFeatures = {
themeGeneration: true,
altText: true,
videoGeneration: true,
+ designAgent: true,
}
export const DEFAULT_SETTINGS: StoredSettings = {
diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.ts
index 397e494..b3480ac 100644
--- a/src/lib/ai/provider.ts
+++ b/src/lib/ai/provider.ts
@@ -276,6 +276,10 @@ const FEATURE_SLOTS: Record<string, AiSlot> = {
theme: 'text', // AI theme generation
'alt-text': 'vision', // image alt text (vision slot — image understanding)
video: 'video', // text-to-video generation
+ // v0.30 (DesignAgent, Phase B): the autonomous design pipeline
+ // plans on the text slot; its vision critique resolves separately
+ // inside the route (optional — disclosed as unavailable without it)
+ 'design-agent': 'text',
}
/** Async probe — does THIS slot have a provider behind it? */
@@ -610,6 +614,8 @@ const FEATURE_FLAGS: Record<string, AiFeature> = {
theme: 'themeGeneration',
'alt-text': 'altText',
video: 'videoGeneration',
+ // v0.30 (DesignAgent, Phase B):
+ 'design-agent': 'designAgent',
}
export const FEATURE_DISABLED = {
diff --git a/src/lib/design-agent/byok-adapter.test.ts b/src/lib/design-agent/byok-adapter.test.ts
new file mode 100644
index 0000000..fedde7a
--- /dev/null
+++ b/src/lib/design-agent/byok-adapter.test.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it } from 'vitest'
+import { byokDesignAgentModel } from './byok-adapter'
+import { PLANNER_SYSTEM, planUserPrompt, revisionUserPrompt, CRITIQUE_SYSTEM, critiqueUserPrompt } from './prompts'
+import type { ProviderContext } from '@/lib/ai/provider'
+import { extractBrief } from '@/lib/agent/brief'
+import type { RevisionFeedback } from './model'
+import type { DesignSpec } from '@/lib/design-spec/types'
+
+/**
+ * The BYOK adapter proven with STUB SDK clients — no network, no
+ * provider resolution. Asserts the call SHAPES (messages, JSON mode,
+ * fallback, vision) that the provider system will execute, and that
+ * the adapter composes with the pipeline's model seam.
+ */
+
+/** A stub SDK client that records every call. */
+function stubZai(planReplies: string[], visionReply = '', failJsonMode = false) {
+ const calls: { kind: 'chat' | 'vision'; args: Record<string, unknown> }[] = []
+ let planIdx = 0
+ return {
+ calls,
+ zai: {
+ chat: {
+ completions: {
+ create: async (args: Record<string, unknown>) => {
+ calls.push({ kind: 'chat', args })
+ if (failJsonMode && (args as { response_format?: unknown }).response_format) {
+ throw new Error('endpoint does not support json_object')
+ }
+ const reply = planReplies[Math.min(planIdx++, planReplies.length - 1)]
+ return { choices: [{ message: { content: reply } }] }
+ },
+ createVision: async (args: Record<string, unknown>) => {
+ calls.push({ kind: 'vision', args })
+ return { choices: [{ message: { content: visionReply } }] }
+ },
+ },
+ },
+ },
+ }
+}
+
+function ctxOf(zai: unknown, model?: string): ProviderContext {
+ return { zai: zai as ProviderContext['zai'], model, label: 'stub', source: 'user' }
+}
+
+const PROMPT = 'Create a poster. Must show "Launch Week 2026". Use #123456. Size 1080x1350.'
+
+describe('byokDesignAgentModel · the plan seam', () => {
+ it('sends the planner system + brief prompt with JSON mode and returns the model text', async () => {
+ const specReply = '{"version":"v2"}'
+ const { zai, calls } = stubZai([specReply])
+ const model = byokDesignAgentModel(ctxOf(zai, 'glm-4-plus'))
+ const brief = extractBrief(PROMPT)
+
+ const raw = await model.plan({ brief, toolbox: 'toolbox' })
+
+ expect(raw).toBe(specReply)
+ const chat = calls.find((c) => c.kind === 'chat')
+ expect(chat).toBeTruthy()
+ const messages = chat!.args.messages as { role: string; content: string }[]
+ expect(messages[0].role).toBe('system')
+ expect(messages[0].content).toContain(PLANNER_SYSTEM.slice(0, 40))
+ expect(messages[1].content).toContain('Launch Week 2026')
+ expect(chat!.args.model).toBe('glm-4-plus')
+ expect(chat!.args.response_format).toEqual({ type: 'json_object' })
+ })
+
+ it('a revision round sends the Reflexion-style feedback prompt', async () => {
+ const { zai, calls } = stubZai(['{"version":"v2"}'])
+ const model = byokDesignAgentModel(ctxOf(zai))
+ const brief = extractBrief(PROMPT)
+ const feedback: RevisionFeedback = {
+ round: 1,
+ failures: ['required text missing from the spec — add it as ONE user-required slot with exactly this text: "Launch Week 2026"'],
+ warnings: [],
+ priorSpec: { version: 'v2', name: 'x', format: { width: 1080, height: 1350 }, palette: { seeds: ['#123456'], mood: 'cool' }, typography: {}, blocks: [] } as unknown as DesignSpec,
+ origin: 'checks',
+ }
+
+ await model.plan({ brief, toolbox: 'toolbox', feedback })
+
+ const chat = calls.find((c) => c.kind === 'chat')!
+ const messages = chat.args.messages as { role: string; content: string }[]
+ expect(messages[1].content).toContain(revisionUserPrompt(feedback).slice(0, 30))
+ expect(messages[1].content).toContain('required text missing from the spec')
+ expect(messages[1].content).toContain('"version": "v2"') // the prior spec JSON rides along
+ })
+
+ it('falls back to plain completion when the endpoint rejects JSON mode', async () => {
+ const { zai, calls } = stubZai(['{"ok":true}'], '', true)
+ const model = byokDesignAgentModel(ctxOf(zai))
+
+ const raw = await model.plan({ brief: extractBrief(PROMPT), toolbox: 't' })
+
+ expect(raw).toBe('{"ok":true}')
+ // two chat calls: the failed JSON-mode one, then the fallback
+ const chatCalls = calls.filter((c) => c.kind === 'chat')
+ expect(chatCalls).toHaveLength(2)
+ expect(chatCalls[0].args.response_format).toEqual({ type: 'json_object' })
+ expect(chatCalls[1].args.response_format).toBeUndefined()
+ })
+})
+
+describe('byokDesignAgentModel · the critique seam', () => {
+ it('sends the calibrated critique system + image to the vision model', async () => {
+ const visionReply = '{"summary":"s","issues":[{"severity":"P2","issue":"gappy"}]}'
+ const { zai, calls } = stubZai(['{}'], visionReply)
+ const text = stubZai(['{}'])
+ const model = byokDesignAgentModel(ctxOf(text.zai), ctxOf(zai, 'glm-4.5v'))
+ const brief = extractBrief(PROMPT)
+
+ const raw = await model.critique!({ brief, image: 'data:image/svg+xml;base64,AAA' })
+
+ expect(raw).toBe(visionReply)
+ const vision = calls.find((c) => c.kind === 'vision')
+ expect(vision).toBeTruthy()
+ expect(vision!.args.model).toBe('glm-4.5v')
+ const messages = vision!.args.messages as { role: string; content: unknown }[]
+ expect(messages[0].content).toContain(CRITIQUE_SYSTEM.slice(0, 30))
+ const userContent = messages[1].content as { type: string; text?: string; image_url?: { url: string } }[]
+ expect(userContent[1].image_url?.url).toBe('data:image/svg+xml;base64,AAA')
+ expect(String(userContent[0].text)).toContain(critiqueUserPrompt(brief).slice(0, 20))
+ })
+
+ it('no vision context → no critique capability (the pipeline discloses unavailable)', async () => {
+ const { zai } = stubZai(['{}'])
+ const model = byokDesignAgentModel(ctxOf(zai), null)
+ expect(model.critique).toBeUndefined()
+ })
+
+ it('the vision model falls back to DEFAULT_VISION_MODEL when ctx has none', async () => {
+ const { zai, calls } = stubZai(['{}'], '{}')
+ const text = stubZai(['{}'])
+ const model = byokDesignAgentModel(ctxOf(text.zai), ctxOf(zai))
+ await model.critique!({ brief: extractBrief(PROMPT), image: 'x' })
+ expect(calls.find((c) => c.kind === 'vision')!.args.model).toBe('glm-4.5v')
+ })
+})
diff --git a/src/lib/design-agent/byok-adapter.ts b/src/lib/design-agent/byok-adapter.ts
new file mode 100644
index 0000000..5021ecd
--- /dev/null
+++ b/src/lib/design-agent/byok-adapter.ts
@@ -0,0 +1,101 @@
+// ─────────────────────────────────────────────────────────────
+// DesignAgent · the BYOK production adapter (Phase B P0-B).
+//
+// Bridges the pipeline's DesignAgentModel seam onto Canvix's
+// provider system (src/lib/ai/provider.ts): the same resolution
+// chain (user BYOK providers → instance multi/db/env/file), the
+// same SDK client, the same JSON-mode-with-fallback call shape the
+// shipped design-spec normalizer uses.
+//
+// · plan → text slot: chat.completions.create (json_object
+// response_format, plain-text fallback on error)
+// · critique → vision slot: chat.completions.createVision over the
+// rendered image (omitted entirely when no vision
+// provider exists — the pipeline then discloses
+// 'visual verification unavailable', fail-closed)
+//
+// The adapter is a PURE function of ProviderContext — unit tests
+// stub the SDK client, no network, no provider resolution.
+// ─────────────────────────────────────────────────────────────
+
+import { DEFAULT_VISION_MODEL, type ProviderContext } from '@/lib/ai/provider'
+import type { DesignAgentModel, PlanRequest, CritiqueRequest } from './model'
+import { PLANNER_SYSTEM, planUserPrompt, revisionUserPrompt, CRITIQUE_SYSTEM, critiqueUserPrompt } from './prompts'
+
+/** The SDK's chat completion type (loose — the shape we read). */
+interface CompletionLike {
+ choices?: { message?: { content?: string } }[]
+}
+
+/** Minimal SDK client surface the adapter consumes. */
+interface ZaiLike {
+ chat: {
+ completions: {
+ create: (args: Record<string, unknown>) => Promise<CompletionLike>
+ createVision: (args: Record<string, unknown>) => Promise<CompletionLike>
+ }
+ }
+}
+
+/**
+ * Build a DesignAgentModel from resolved provider contexts.
+ * `text` is required (the planner); `vision` is optional — without
+ * it the model has no critique capability and the pipeline reports
+ * visual verification as unavailable rather than skipping silently.
+ */
+export function byokDesignAgentModel(text: ProviderContext, vision?: ProviderContext | null): DesignAgentModel {
+ const textZai = text.zai as unknown as ZaiLike
+
+ /** one planner call: JSON mode first, plain fallback (the SDK's
+ * json_object support varies by endpoint — same recovery the
+ * design-spec normalizer uses) */
+ async function plan(req: PlanRequest): Promise<string> {
+ const system = PLANNER_SYSTEM
+ const user = req.feedback ? revisionUserPrompt(req.feedback) : planUserPrompt(req.brief)
+ const messages = [
+ { role: 'system', content: system },
+ { role: 'user', content: user },
+ ]
+ try {
+ const completion = (await textZai.chat.completions.create({
+ ...(text.model ? { model: text.model } : {}),
+ messages,
+ thinking: { type: 'disabled' },
+ response_format: { type: 'json_object' },
+ })) as CompletionLike
+ return completion.choices?.[0]?.message?.content ?? ''
+ } catch {
+ const completion = (await textZai.chat.completions.create({
+ ...(text.model ? { model: text.model } : {}),
+ messages,
+ thinking: { type: 'disabled' },
+ })) as CompletionLike
+ return completion.choices?.[0]?.message?.content ?? ''
+ }
+ }
+
+ const model: DesignAgentModel = { plan }
+
+ if (vision) {
+ const visionZai = vision.zai as unknown as ZaiLike
+ model.critique = async (req: CritiqueRequest): Promise<string> => {
+ const completion = (await visionZai.chat.completions.createVision({
+ model: vision.model ?? DEFAULT_VISION_MODEL,
+ messages: [
+ { role: 'system', content: CRITIQUE_SYSTEM },
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: critiqueUserPrompt(req.brief) },
+ { type: 'image_url', image_url: { url: req.image } },
+ ],
+ },
+ ],
+ thinking: { type: 'disabled' },
+ })) as CompletionLike
+ return completion.choices?.[0]?.message?.content ?? ''
+ }
+ }
+
+ return model
+}