Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(anatomy): add the /anatomy page and API client, and rewrite the spec writer

nirholasbe74e5995249
diff --git a/api/_lib/anatomy/writer.js b/api/_lib/anatomy/writer.js
index b2559e77d..feb6ff63f 100644
--- a/api/_lib/anatomy/writer.js
+++ b/api/_lib/anatomy/writer.js
@@ -5,10 +5,10 @@
// streams and forwards text deltas as they arrive. Order is quality first,
// the same chain the editorial writer uses (api/_lib/x-content/llm.js):
//
-// 1. Claude on Vertex AI (Google credits, pre-approved in the operating rules)
+// 1. Claude on Vertex AI (Google credits), when the project is entitled
// 2. Claude on the Anthropic API, when a key is configured
// 3. Claude through OpenRouter
-// 4. Kimi K3 on NVIDIA NIM (free)
+// 4. Kimi K3, then Nemotron Ultra and Super, on NVIDIA NIM (free)
// 5. the platform's general chain, non-streaming, so a request is never
// refused while any model answers
//
@@ -22,6 +22,20 @@ import { recordEvent } from '../usage.js';
export const ANATOMY_MODEL_DEFAULT = 'claude-opus-5';
const FALLBACK_CLAUDE = 'claude-sonnet-5';
const MAX_TOKENS = 16_000;
+// A healthy host starts streaming within seconds even on the long system
+// prompt. One that has not by now is queued or stalled, and waiting longer
+// would spend the whole request on it, so the ladder moves on.
+const FIRST_TOKEN_MS = 45_000;
+// Degenerate sampling (one token repeated forever) is a real failure mode of
+// some hosted models under load. It never becomes JSON, so it is cut off early.
+const DEGENERATE_WINDOW = 240;
+
+/** True when the tail of the text is one or two characters repeated. */
+export function isDegenerate(text) {
+ if (text.length < DEGENERATE_WINDOW + 60) return false;
+ const tail = text.slice(-DEGENERATE_WINDOW).replace(/\s+/g, '');
+ return tail.length > 0 && new Set(tail).size <= 2;
+}
export class AnatomyWriterError extends Error {
constructor(message, failures = []) {
@@ -119,7 +133,10 @@ function anthropicBody(model, system, messages) {
export function writerRungs(env = process.env) {
const rungs = [];
const primary = env.ANATOMY_MODEL || ANATOMY_MODEL_DEFAULT;
- if (env.GOOGLE_CLOUD_PROJECT) {
+ // Vertex Claude needs Model Garden entitlement as well as a project; the
+ // shared VERTEX_CLAUDE_ENABLED flag (docs/ops/llm-lanes.md) says whether the
+ // project has it, so an unentitled deployment never spends a round trip here.
+ if (env.GOOGLE_CLOUD_PROJECT && (env.VERTEX_CLAUDE_ENABLED === '1' || env.VERTEX_CLAUDE_ENABLED === 'true')) {
for (const model of [...new Set([primary, FALLBACK_CLAUDE])]) {
rungs.push({
provider: 'vertex',
@@ -166,18 +183,24 @@ export function writerRungs(env = process.env) {
}),
});
if (env.OPENROUTER_API_KEY) {
- rungs.push(
- chat('openrouter', 'https://openrouter.ai/api/v1/chat/completions', env.OPENROUTER_API_KEY, `anthropic/${primary}`, {
- headers: { 'http-referer': 'https://three.ws', 'x-title': 'three.ws Anatomy' },
- }),
- );
+ for (const model of [...new Set([primary, FALLBACK_CLAUDE])]) {
+ rungs.push(
+ chat('openrouter', 'https://openrouter.ai/api/v1/chat/completions', env.OPENROUTER_API_KEY, `anthropic/${model}`, {
+ headers: { 'http-referer': 'https://three.ws', 'x-title': 'three.ws Anatomy' },
+ }),
+ );
+ }
}
if (env.NVIDIA_API_KEY) {
- rungs.push(
- chat('nvidia', 'https://integrate.api.nvidia.com/v1/chat/completions', env.NVIDIA_API_KEY, 'moonshotai/kimi-k3', {
- body: { chat_template_kwargs: { thinking: false, enable_thinking: false } },
- }),
- );
+ // Three separate NIM functions on one key: Kimi writes the best specs,
+ // the Nemotron pair answers when Kimi's host is queued or stalled.
+ for (const model of ['moonshotai/kimi-k3', 'nvidia/nemotron-3-ultra-550b-a55b', 'nvidia/nemotron-3-super-120b-a12b']) {
+ rungs.push(
+ chat('nvidia', 'https://integrate.api.nvidia.com/v1/chat/completions', env.NVIDIA_API_KEY, model, {
+ body: { chat_template_kwargs: { thinking: false, enable_thinking: false } },
+ }),
+ );
+ }
}
return rungs;
}
@@ -196,8 +219,15 @@ export async function streamSpec({ system, messages, onDelta = () => {}, onReset
if (remaining < 20_000) break;
const started = Date.now();
let streamed = false;
+ let soFar = '';
+ let why = null;
const ctrl = new AbortController();
- const timer = setTimeout(() => ctrl.abort(), remaining);
+ const abort = (reason) => {
+ why ??= reason;
+ ctrl.abort();
+ };
+ const timer = setTimeout(() => abort('timed out'), remaining);
+ const firstToken = setTimeout(() => abort(`no output in ${FIRST_TOKEN_MS / 1000}s`), Math.min(FIRST_TOKEN_MS, remaining));
try {
const res = await rung.open({ system, messages, signal: ctrl.signal, fetchImpl });
if (!res.ok || !res.body) {
@@ -206,7 +236,13 @@ export async function streamSpec({ system, messages, onDelta = () => {}, onReset
}
const reader = rung.kind === 'anthropic' ? readAnthropicStream : readChatStream;
const out = await reader(res.body, (piece) => {
+ if (!streamed) clearTimeout(firstToken);
streamed = true;
+ soFar += piece;
+ if (isDegenerate(soFar)) {
+ abort('degenerate output');
+ throw new Error('degenerate output');
+ }
onDelta(piece);
});
if (!out.text.trim()) throw new Error('empty completion');
@@ -222,10 +258,11 @@ export async function streamSpec({ system, messages, onDelta = () => {}, onReset
});
return { text: out.text, provider: rung.provider, model: rung.model, stopReason: out.stopReason };
} catch (err) {
- failures.push(`${rung.provider}:${rung.model}: ${err?.name === 'AbortError' ? 'timed out' : err?.message}`);
+ failures.push(`${rung.provider}:${rung.model}: ${why || (err?.name === 'AbortError' ? 'timed out' : err?.message)}`);
if (streamed) onReset();
} finally {
clearTimeout(timer);
+ clearTimeout(firstToken);
}
}
if (failures.length) console.warn('[anatomy-writer] streaming ladder exhausted:', failures.join(' | '));
diff --git a/pages/anatomy.html b/pages/anatomy.html
new file mode 100644
index 000000000..bf86341c6
--- /dev/null
+++ b/pages/anatomy.html
@@ -0,0 +1,128 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Anatomy · See how any machine works · three.ws</title>
+ <meta name="description" content="Describe a machine in one line and Claude builds it as an interactive isometric cutaway: real moving parts, fire, water and plasma shaders, an exploded view, a section cut and a guided tour." />
+ <link rel="canonical" href="https://three.ws/anatomy" />
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Anatomy · three.ws" />
+ <meta property="og:description" content="One line in, a working machine out: rotate it, cut it open, explode it and follow the physics step by step." />
+ <meta property="og:url" content="https://three.ws/anatomy" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Anatomy&amp;d=Describe+a+machine+in+one+line+and+watch+it+work%3A+moving+parts%2C+shaders+and+a+guided+tour.&amp;p=%2Fanatomy" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Anatomy · three.ws" />
+ <meta name="twitter:description" content="One line in, a working machine out: rotate it, cut it open, explode it and follow the physics step by step." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Anatomy&amp;d=Describe+a+machine+in+one+line+and+watch+it+work%3A+moving+parts%2C+shaders+and+a+guided+tour.&amp;p=%2Fanatomy" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:image:alt" content="Anatomy, three.ws" />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+ <link rel="stylesheet" href="/src/anatomy/anatomy.css" />
+ <link rel="stylesheet" href="/src/anatomy/page.css" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Anatomy","applicationCategory":"EducationalApplication","operatingSystem":"Any","description":"Describe a machine in one line and get an interactive isometric cutaway with real moving parts, shader effects and a guided tour.","url":"https://three.ws/anatomy","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}}]}</script>
+</head>
+<body class="anp-body">
+ <header class="site-header"><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="anp">
+ <!-- /anatomy: describe a machine, browse what others built -->
+ <section id="anpHome" class="anp-home" aria-labelledby="anpHeroTitle">
+ <div class="anp-hero">
+ <p class="anp-eyebrow"><span class="anp-eyebrow__mark" aria-hidden="true"></span>Anatomy</p>
+ <h1 id="anpHeroTitle">Describe a machine. Watch it work.</h1>
+ <p class="anp-lede">One line becomes an interactive isometric cutaway: the real moving parts in motion, fire, water and plasma rendered with live shaders, and a guided tour of the physics. Rotate it, cut it open, pull it apart.</p>
+
+ <form id="anpForm" class="anp-form" autocomplete="off">
+ <label for="anpPrompt" class="anp-sr">Describe the machine</label>
+ <textarea id="anpPrompt" rows="2" maxlength="600" placeholder="How a big airliner turbofan like the A380's makes thrust"></textarea>
+ <div class="anp-form__foot">
+ <span class="anp-hint">Name a machine and what you want to understand. <kbd>Ctrl</kbd> <kbd>Enter</kbd> to build.</span>
+ <button id="anpSubmit" type="submit" class="anp-btn anp-btn--primary">
+ <span class="anp-btn__label">Build it</span>
+ <span class="anp-btn__spinner" aria-hidden="true"></span>
+ </button>
+ </div>
+ </form>
+ <p id="anpFormError" class="anp-notice anp-notice--error" role="alert" hidden></p>
+ <div id="anpExamples" class="anp-chips" aria-label="Example machines"></div>
+
+ <ul class="anp-proof" aria-label="What you get">
+ <li><strong>Real motion</strong><span>Fans spin, pistons ride their cranks and valves open in time, each part moving on its own.</span></li>
+ <li><strong>Physics you can see</strong><span>Combustion, coolant, plasma and airflow drawn with WebGL shaders and animated flow paths.</span></li>
+ <li><strong>Take it apart</strong><span>Explode the assembly, slice a section, x-ray the casing, or follow the tour step by step.</span></li>
+ </ul>
+ </div>
+
+ <section class="anp-gallery" aria-labelledby="anpGalleryTitle">
+ <div class="anp-gallery__head">
+ <h2 id="anpGalleryTitle">Recently built</h2>
+ <form id="anpSearch" class="anp-search" role="search">
+ <label for="anpSearchInput" class="anp-sr">Search machines</label>
+ <input id="anpSearchInput" type="search" placeholder="Search machines" maxlength="80" />
+ </form>
+ </div>
+ <div id="anpGallery" class="anp-grid" aria-live="polite"></div>
+ <div id="anpGalleryStatus" class="anp-empty" hidden></div>
+ </section>
+
+ <section class="anp-agent" aria-labelledby="anpAgentTitle">
+ <div>
+ <h2 id="anpAgentTitle">Use it from your agent</h2>
+ <p>Anatomy ships as an open-source agent skill. Claude Code writes the spec itself, publishes it here and hands you the link. Type <code>/anatomy</code> followed by any machine.</p>
+ </div>
+ <pre class="anp-code"><code>cp -r .agents/skills/anatomy ~/your-project/.claude/skills/
+
+/anatomy explain how a big airliner turbofan engine like the A380's makes thrust, interactive</code></pre>
+ <p class="anp-agent__links"><a class="anp-link" href="https://github.com/nirholas/three.ws/tree/main/.agents/skills/anatomy" rel="noopener" target="_blank">The skill on GitHub</a><a class="anp-link" href="/docs/anatomy">Spec reference and API</a></p>
+ </section>
+ </section>
+
+ <!-- /anatomy/:id and a machine being written -->
+ <section id="anpDesign" class="anp-design" hidden aria-labelledby="anpTitle">
+ <header class="anp-bar">
+ <a class="anp-back" href="/anatomy" aria-label="All machines">
+ <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path d="M15 18l-6-6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ <span>Anatomy</span>
+ </a>
+ <div class="anp-bar__title">
+ <h1 id="anpTitle" class="anp-title"></h1>
+ <p id="anpSubtitle" class="anp-subtitle"></p>
+ </div>
+ <div id="anpStatus" class="anp-status" role="status" aria-live="polite" hidden>
+ <span class="anp-status__dot" aria-hidden="true"></span>
+ <span id="anpStatusText"></span>
+ </div>
+ <div class="anp-bar__actions">
+ <button id="anpCopyLink" type="button" class="anp-btn anp-btn--ghost" hidden>Copy link</button>
+ <button id="anpCopySpec" type="button" class="anp-btn anp-btn--ghost" hidden>Copy spec</button>
+ <a id="anpNew" class="anp-btn" href="/anatomy">New machine</a>
+ </div>
+ </header>
+ <p id="anpAsked" class="anp-asked" hidden></p>
+ <p id="anpWarn" class="anp-notice" hidden></p>
+ <div id="anpStage" class="anp-stage">
+ <div id="anpSkeleton" class="anp-skeleton" hidden>
+ <div class="anp-skeleton__iso" aria-hidden="true"><span></span><span></span><span></span></div>
+ <p id="anpSkeletonText">Claude is designing the machine. Parts appear here as they are written.</p>
+ </div>
+ </div>
+ <div id="anpDesignError" class="anp-empty anp-empty--page" hidden></div>
+ </section>
+ <div id="anpToast" class="anp-toast" role="status" aria-live="polite" hidden></div>
+ </main>
+
+ <script type="module" src="/src/anatomy/page.js"></script>
+</body>
+</html>
diff --git a/src/anatomy/api.js b/src/anatomy/api.js
new file mode 100644
index 000000000..40e776581
--- /dev/null
+++ b/src/anatomy/api.js
@@ -0,0 +1,83 @@
+// Anatomy page: the client side of /api/anatomy.
+
+export class AnatomyApiError extends Error {
+ constructor(status, body) {
+ super(body?.message || `Request failed (${status})`);
+ this.status = status;
+ this.code = body?.error || 'request_failed';
+ this.body = body || {};
+ }
+}
+
+async function readJsonResponse(res) {
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new AnatomyApiError(res.status, body);
+ return body;
+}
+
+export async function fetchDesign(id) {
+ return readJsonResponse(await fetch(`/api/anatomy?${new URLSearchParams({ id })}`));
+}
+
+export async function fetchGallery({ limit = 24, q = '' } = {}) {
+ const qs = new URLSearchParams({ list: 'recent', limit: String(limit) });
+ if (q) qs.set('q', q);
+ return readJsonResponse(await fetch(`/api/anatomy?${qs}`));
+}
+
+/**
+ * Generate a machine, streaming the spec as Claude writes it.
+ * onStage(stage) 'writing' | 'repairing' | 'saving'
+ * onText(text) the full spec text so far (after any reset)
+ * Resolves with { design, warnings }; rejects with AnatomyApiError.
+ */
+export async function generateDesign({ prompt, onStage = () => {}, onText = () => {}, signal } = {}) {
+ const res = await fetch('/api/anatomy', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
+ body: JSON.stringify({ action: 'generate', prompt, stream: true }),
+ signal,
+ });
+ const type = res.headers.get('content-type') || '';
+ if (!type.includes('text/event-stream')) return readJsonResponse(res);
+
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let text = '';
+ let result = null;
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let idx;
+ while ((idx = buffer.indexOf('\n\n')) !== -1) {
+ const record = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 2);
+ let event = 'message';
+ let data = '';
+ for (const line of record.split('\n')) {
+ if (line.startsWith('event:')) event = line.slice(6).trim();
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
+ }
+ if (!data) continue;
+ let payload;
+ try {
+ payload = JSON.parse(data);
+ } catch {
+ continue;
+ }
+ if (event === 'delta') {
+ text += payload.text || '';
+ onText(text);
+ } else if (event === 'reset') {
+ text = '';
+ onText(text);
+ } else if (event === 'stage') onStage(payload.stage);
+ else if (event === 'done') result = payload;
+ else if (event === 'error') throw new AnatomyApiError(payload.status || 500, payload);
+ }
+ }
+ if (!result) throw new AnatomyApiError(502, { error: 'stream_ended', message: 'The connection closed before the machine finished. Try again.' });
+ return result;
+}
diff --git a/src/anatomy/page.css b/src/anatomy/page.css
new file mode 100644
index 000000000..6dba78edb
--- /dev/null
+++ b/src/anatomy/page.css
@@ -0,0 +1,756 @@
+/* Anatomy page (/anatomy, /anatomy/:id). Tokens from DESIGN-TOKENS.md; the
+ explorer itself is styled by anatomy.css. */
+
+.anp-body {
+ background: var(--bg-0);
+ color: var(--ink);
+ --anp-accent: #ff8a3d;
+ --anp-cyan: #4fd1ff;
+}
+
+.anp {
+ width: 100%;
+ box-sizing: border-box;
+ max-width: 1440px;
+ margin: 0 auto;
+ padding: var(--space-lg, 24px) var(--space-md, 16px) var(--space-2xl, 64px);
+}
+
+.anp-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+}
+
+/* ── hero + form ─────────────────────────────────────────────────────────── */
+
+.anp-hero {
+ max-width: 880px;
+ margin: var(--space-xl, 40px) auto var(--space-2xl, 56px);
+ text-align: center;
+}
+
+.anp-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ font-family: var(--font-mono);
+ font-size: 12px;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ margin: 0 0 var(--space-sm, 12px);
+}
+
+.anp-eyebrow__mark {
+ width: 14px;
+ height: 14px;
+ border: 1.5px solid var(--anp-cyan);
+ transform: rotate(30deg) skewX(-30deg) scaleY(0.86);
+ background: linear-gradient(90deg, transparent 40%, color-mix(in srgb, var(--anp-accent) 70%, transparent) 40% 60%, transparent 60%);
+}
+
+.anp-hero h1 {
+ font-family: var(--font-display);
+ font-size: clamp(32px, 5.4vw, 58px);
+ line-height: 1.05;
+ letter-spacing: -0.02em;
+ color: var(--ink-bright, var(--ink));
+ margin: 0 0 var(--space-md, 16px);
+}
+
+.anp-lede {
+ font-size: 17px;
+ line-height: 1.55;
+ color: var(--ink-dim);
+ max-width: 700px;
+ margin: 0 auto var(--space-lg, 28px);
+}
+
+.anp-form {
+ text-align: left;
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-1);
+ border-radius: var(--radius-lg, 14px);
+ padding: var(--space-sm, 12px);
+ transition: border-color 0.2s ease, box-shadow 0.2s ease;
+}
+
+.anp-form:focus-within {
+ border-color: var(--anp-cyan);
+ box-shadow: 0 0 0 4px color-mix(in srgb, var(--anp-cyan) 16%, transparent);
+}
+
+.anp-form textarea {
+ width: 100%;
+ box-sizing: border-box;
+ resize: vertical;
+ min-height: 64px;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--ink);
+ font: 16px/1.5 var(--font-body);
+ padding: 6px 8px;
+}
+
+.anp-form__foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm, 12px);
+ padding-top: 6px;
+}
+
+.anp-hint {
+ font-size: 13px;
+ color: var(--ink-faint);
+}
+
+.anp-hint kbd {
+ font-family: var(--font-mono);
+ font-size: 11px;
+ border: 1px solid var(--stroke);
+ border-radius: 4px;
+ padding: 1px 5px;
+}
+
+.anp-notice {
+ margin: var(--space-sm, 12px) 0 0;
+ padding: 10px 14px;
+ border-radius: var(--radius-md, 10px);
+ border: 1px solid color-mix(in srgb, var(--warn) 45%, transparent);
+ color: var(--warn);
+ font-size: 14px;
+ text-align: left;
+}
+
+.anp-notice--error {
+ border-color: color-mix(in srgb, var(--danger, #ef4444) 50%, transparent);
+ color: var(--danger, #ef4444);
+}
+
+.anp-chips {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 8px;
+ margin: var(--space-md, 16px) 0 0;
+}
+
+.anp-chip {
+ border: 1px solid var(--stroke);
+ background: transparent;
+ color: var(--ink-dim);
+ border-radius: var(--radius-pill, 999px);
+ padding: 7px 13px;
+ font: 13px var(--font-body);
+ cursor: pointer;
+ transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease, transform 0.15s ease;
+}
+
+.anp-chip:hover:not(:disabled) {
+ color: var(--ink);
+ border-color: var(--stroke-strong);
+ background: var(--surface-1);
+}
+
+.anp-chip:active:not(:disabled) {
+ transform: scale(0.97);
+}
+
+.anp-chip:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.anp-proof {
+ list-style: none;
+ padding: 0;
+ margin: var(--space-xl, 40px) 0 0;
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: var(--space-md, 16px);
+ text-align: left;
+}
+
+.anp-proof li {
+ border-top: 1px solid var(--stroke);
+ padding-top: var(--space-sm, 12px);
+ display: grid;
+ gap: 4px;
+}
+
+.anp-proof strong {
+ font-family: var(--font-display);
+ color: var(--ink-bright, var(--ink));
+}
+
+.anp-proof span {
+ color: var(--ink-dim);
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+/* ── buttons ─────────────────────────────────────────────────────────────── */
+
+.anp-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 38px;
+ padding: 0 16px;
+ border-radius: var(--radius-md, 10px);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-2);
+ color: var(--ink);
+ font: 600 14px var(--font-body);
+ text-decoration: none;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.12s ease, opacity 0.15s ease;
+}
+
+.anp-btn:hover {
+ background: var(--surface-3);
+}
+
+.anp-btn:active {
+ transform: translateY(1px);
+}
+
+.anp-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.anp-btn--primary {
+ background: var(--ink-bright, #fff);
+ color: var(--bg-0);
+ border-color: transparent;
+}
+
+.anp-btn--primary:hover {
+ background: var(--ink);
+}
+
+.anp-btn--ghost {
+ background: transparent;
+}
+
+.anp-btn__spinner {
+ display: none;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ border: 2px solid currentColor;
+ border-right-color: transparent;
+ animation: anp-spin 0.8s linear infinite;
+}
+
+.anp-btn.is-busy .anp-btn__spinner {
+ display: inline-block;
+}
+
+.anp-link {
+ color: var(--ink);
+ text-decoration: underline;
+ text-decoration-color: var(--stroke-strong);
+ text-underline-offset: 3px;
+}
+
+.anp-link:hover {
+ text-decoration-color: currentColor;
+}
+
+.anp-btn:focus-visible,
+.anp-chip:focus-visible,
+.anp-link:focus-visible,
+.anp-card:focus-visible,
+.anp-back:focus-visible,
+.anp-search input:focus-visible {
+ outline: 2px solid var(--anp-cyan);
+ outline-offset: 2px;
+}
+
+@keyframes anp-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+/* ── gallery ─────────────────────────────────────────────────────────────── */
+
+.anp-gallery {
+ margin: 0 0 var(--space-2xl, 56px);
+}
+
+.anp-gallery__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-md, 16px);
+ margin-bottom: var(--space-md, 16px);
+}
+
+.anp-gallery__head h2,
+.anp-agent h2 {
+ font-family: var(--font-display);
+ font-size: 22px;
+ margin: 0;
+ color: var(--ink-bright, var(--ink));
+}
+
+.anp-search input {
+ width: min(260px, 50vw);
+ min-height: 36px;
+ box-sizing: border-box;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1);
+ color: var(--ink);
+ font: 14px var(--font-body);
+ padding: 0 12px;
+}
+
+.anp-search input:hover {
+ border-color: var(--stroke-strong);
+}
+
+.anp-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: var(--space-md, 16px);
+}
+
+.anp-card {
+ position: relative;
+ display: grid;
+ align-content: start;
+ gap: 6px;
+ min-height: 168px;
+ padding: 18px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg, 14px);
+ background:
+ linear-gradient(color-mix(in srgb, var(--anp-cyan) 5%, transparent) 1px, transparent 1px) 0 0 / 22px 22px,
+ linear-gradient(90deg, color-mix(in srgb, var(--anp-cyan) 5%, transparent) 1px, transparent 1px) 0 0 / 22px 22px,
+ var(--surface-1);
+ color: var(--ink);
+ text-decoration: none;
+ overflow: hidden;
+ transition: border-color 0.15s ease, transform 0.15s ease, background-color 0.15s ease;
+}
+
+.anp-card:hover {
+ border-color: var(--stroke-strong);
+ transform: translateY(-2px);
+}
+
+.anp-card:active {
+ transform: translateY(0);
+}
+
+.anp-card__glyph {
+ position: relative;
+ width: 34px;
+ height: 34px;
+ margin-bottom: 6px;
+}
+
+.anp-card__glyph span {
+ position: absolute;
+ inset: 0;
+ border: 1.5px solid var(--anp-cyan);
+ transform: rotate(30deg) skewX(-30deg) scaleY(0.86);
+ opacity: 0.85;
+}
+
+.anp-card__glyph span:nth-child(2) {
+ inset: 7px;
+ border-color: var(--anp-accent);
+}
+
+.anp-card__glyph span:nth-child(3) {
+ inset: 14px;
+ background: var(--anp-accent);
+ border: 0;
+}
+
+.anp-card:hover .anp-card__glyph span:nth-child(2) {
+ animation: anp-spin 3s linear infinite;
+}
+
+.anp-card__title {
+ font-family: var(--font-display);
+ font-size: 17px;
+ font-weight: 600;
+ color: var(--ink-bright, var(--ink));
+ overflow-wrap: anywhere;
+}
+
+.anp-card__subtitle {
+ font-size: 13px;
+ line-height: 1.45;
+ color: var(--ink-dim);
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.anp-card__facts {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 4px;
+}
+
+.anp-card__facts span {
+ font: 11px var(--font-mono);
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 2px 8px;
+}
+
+.anp-card__meta {
+ font-size: 12px;
+ color: var(--ink-faint);
+ margin-top: auto;
+}
+
+.anp-card--skeleton {
+ pointer-events: none;
+}
+
+.anp-card--skeleton span {
+ display: block;
+ height: 12px;
+ border-radius: 6px;
+ background: var(--surface-2);
+ animation: anp-pulse 1.4s ease-in-out infinite;
+}
+
+.anp-card--skeleton span:first-child {
+ width: 34px;
+ height: 34px;
+ margin-bottom: 8px;
+}
+
+.anp-card--skeleton span:nth-child(2) {
+ width: 70%;
+ height: 16px;
+}
+
+.anp-card--skeleton span:nth-child(3) {
+ width: 90%;
+}
+
+@keyframes anp-pulse {
+ 50% {
+ opacity: 0.45;
+ }
+}
+
+.anp-empty {
+ display: grid;
+ justify-items: center;
+ gap: 8px;
+ text-align: center;
+ padding: var(--space-xl, 40px) var(--space-md, 16px);
+ border: 1px dashed var(--stroke);
+ border-radius: var(--radius-lg, 14px);
+ color: var(--ink-dim);
+}
+
+.anp-empty strong {
+ color: var(--ink-bright, var(--ink));
+ font-size: 16px;
+}
+
+.anp-empty--page {
+ margin-top: var(--space-xl, 40px);
+ min-height: 260px;
+ align-content: center;
+}
+
+.anp-empty__actions {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 8px;
+ margin-top: 8px;
+}
+
+/* ── agent skill ─────────────────────────────────────────────────────────── */
+
+.anp-agent {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.3fr);
+ gap: var(--space-lg, 24px);
+ align-items: start;
+ padding: var(--space-lg, 24px);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg, 14px);
+ background: var(--surface-1);
+}
+
+.anp-agent p {
+ color: var(--ink-dim);
+ line-height: 1.55;
+ margin: 8px 0 0;
+}
+
+.anp-agent code,
+.anp-asked q {
+ font-family: var(--font-mono);
+ font-size: 0.92em;
+}
+
+.anp-code {
+ margin: 0;
+ padding: 14px 16px;
+ border-radius: var(--radius-md, 10px);
+ background: var(--bg-0);
+ border: 1px solid var(--stroke);
+ color: var(--ink);
+ font: 13px/1.6 var(--font-mono);
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+
+.anp-agent__links {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 18px;
+}
+
+/* ── design view ─────────────────────────────────────────────────────────── */
+
+.anp-design {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.anp-bar {
+ display: flex;
+ align-items: center;
+ gap: var(--space-md, 16px);
+ flex-wrap: wrap;
+}
+
+.anp-back {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--ink-dim);
+ text-decoration: none;
+ font-size: 14px;
+ border-radius: 8px;
+ padding: 4px 6px 4px 2px;
+}
+
+.anp-back:hover {
+ color: var(--ink);
+ background: var(--surface-1);
+}
+
+.anp-bar__title {
+ flex: 1 1 280px;
+ min-width: 0;
+}
+
+.anp-title {
+ font-family: var(--font-display);
+ font-size: clamp(20px, 2.4vw, 28px);
+ line-height: 1.15;
+ margin: 0;
+ color: var(--ink-bright, var(--ink));
+ overflow-wrap: anywhere;
+}
+
+.anp-subtitle {
+ margin: 2px 0 0;
+ color: var(--ink-dim);
+ font-size: 14px;
+}
+
+.anp-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ font: 12px var(--font-mono);
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 5px 12px;
+}
+
+.anp-status__dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--anp-accent);
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--anp-accent) 60%, transparent);
+ animation: anp-ping 1.4s ease-out infinite;
+}
+
+@keyframes anp-ping {
+ to {
+ box-shadow: 0 0 0 8px transparent;
+ }
+}
+
+.anp-bar__actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.anp-asked {
+ margin: 0;
+ font-size: 13px;
+ color: var(--ink-faint);
+}
+
+.anp-asked span {
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ font-size: 11px;
+}
+
+.anp-asked q {
+ color: var(--ink-dim);
+}
+
+.anp-design .anp-notice {
+ margin: 0;
+}
+
+.anp-stage {
+ position: relative;
+ height: calc(100vh - 210px);
+ height: calc(100dvh - 210px);
+ min-height: 480px;
+ border-radius: var(--radius-lg, 14px);
+ overflow: hidden;
+ border: 1px solid var(--stroke);
+}
+
+.anp-skeleton {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ display: grid;
+ place-content: center;
+ justify-items: center;
+ gap: 18px;
+ text-align: center;
+ color: var(--ink-dim);
+ background: var(--bg-0);
+ padding: 24px;
+}
+
+.anp-skeleton p {
+ margin: 0;
+ max-width: 360px;
+ line-height: 1.5;
+}
+
+.anp-skeleton__iso {
+ position: relative;
+ width: 96px;
+ height: 96px;
+}
+
+.anp-skeleton__iso span {
+ position: absolute;
+ inset: 0;
+ border: 1.5px solid var(--anp-cyan);
+ transform: rotate(30deg) skewX(-30deg) scaleY(0.86);
+ animation: anp-build 2.4s ease-in-out infinite;
+}
+
+.anp-skeleton__iso span:nth-child(2) {
+ inset: 18px;
+ border-color: var(--anp-accent);
+ animation-delay: 0.3s;
+}
+
+.anp-skeleton__iso span:nth-child(3) {
+ inset: 36px;
+ animation-delay: 0.6s;
+}
+
+@keyframes anp-build {
+ 0%,
+ 100% {
+ opacity: 0.25;
+ translate: 0 6px;
+ }
+ 50% {
+ opacity: 1;
+ translate: 0 -6px;
+ }
+}
+
+.anp-toast {
+ position: fixed;
+ left: 50%;
+ bottom: 24px;
+ transform: translateX(-50%);
+ z-index: 50;
+ background: var(--ink-bright, #fff);
+ color: var(--bg-0);
+ padding: 10px 16px;
+ border-radius: 10px;
+ font-size: 14px;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
+}
+
+/* ── responsive ──────────────────────────────────────────────────────────── */
+
+@media (max-width: 760px) {
+ .anp-proof,
+ .anp-agent {
+ grid-template-columns: 1fr;
+ }
+ .anp-hint {
+ display: none;
+ }
+ .anp-gallery__head {
+ flex-wrap: wrap;
+ }
+ .anp-search,
+ .anp-search input {
+ width: 100%;
+ }
+ .anp-stage {
+ height: calc(100dvh - 170px);
+ min-height: 420px;
+ border-radius: 10px;
+ }
+ .anp-bar__actions {
+ width: 100%;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .anp-skeleton__iso span,
+ .anp-status__dot,
+ .anp-card:hover .anp-card__glyph span:nth-child(2),
+ .anp-card--skeleton span,
+ .anp-btn__spinner {
+ animation: none;
+ }
+ .anp-card:hover {
+ transform: none;
+ }
+}
diff --git a/src/anatomy/page.js b/src/anatomy/page.js
new file mode 100644
index 000000000..4b358b52d
--- /dev/null
+++ b/src/anatomy/page.js
@@ -0,0 +1,409 @@
+// Anatomy page controller: /anatomy (describe + gallery) and /anatomy/:id
+// (one machine). A new machine is drawn while Claude writes it: every part
+// that finishes streaming is added to the explorer immediately.
+
+import { AnatomyApiError, fetchDesign, fetchGallery, generateDesign } from './api.js';
+import { mountAnatomy } from './runtime.js';
+import { scanPartialSpec } from './stream.js';
+
+const EXAMPLES = [
+ 'How a big airliner turbofan like the A380\'s makes thrust',
+ 'A V8 engine: pistons, crankshaft, cams and valves in time',
+ 'The escapement and balance wheel inside a mechanical watch',
+ 'A pressurized water reactor, from core to turbine',
+ 'A tokamak fusion reactor confining plasma with magnets',
+ 'A steam locomotive: firebox, boiler, cylinders and drive rods',
+ 'A Stirling engine running on a candle',
+ 'A liquid rocket engine with its turbopump',
+ 'A wind turbine nacelle: rotor, gearbox and generator',
+ 'A centrifugal water pump',
+];
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const STAGE_TEXT = {
+ writing: 'Claude is writing the machine',
+ repairing: 'Fixing the spec',
+ saving: 'Saving',
+};
+
+const $ = (sel) => document.querySelector(sel);
+
+const state = {
+ app: null,
+ design: null,
+ busy: false,
+ abort: null,
+ galleryQuery: '',
+ galleryToken: 0,
+};
+
+function el(tag, attrs = {}, ...children) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v === true ? '' : String(v));
+ }
+ for (const child of children.flat()) {
+ if (child == null || child === false) continue;
+ node.append(child instanceof Node ? child : document.createTextNode(String(child)));
+ }
+ return node;
+}
+
+let toastTimer = 0;
+function toast(message) {
+ const node = $('#anpToast');
+ node.textContent = message;
+ node.hidden = false;
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => (node.hidden = true), 2600);
+}
+
+function plural(n, word) {
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
+}
+
+function relativeTime(iso) {
+ const t = Date.parse(iso);
+ if (!Number.isFinite(t)) return '';
+ const s = Math.max(1, Math.round((Date.now() - t) / 1000));
+ if (s < 60) return 'just now';
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.round(m / 60);
+ if (h < 48) return `${h}h ago`;
+ return new Date(t).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+async function copyText(text, done) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast(done);
+ } catch {
+ toast('Copy failed. Your browser blocked clipboard access.');
+ }
+}
+
+// ── routing ─────────────────────────────────────────────────────────────────
+
+function routeId() {
+ const m = location.pathname.match(/^\/anatomy\/([^/]+)\/?$/);
+ return m ? m[1] : null;
+}
+
+function navigate(path) {
+ history.pushState(null, '', path);
+ route();
+}
+
+function route() {
+ const id = routeId();
+ if (id) return openDesign(id);
+ showHome();
+}
+
+function teardownExplorer() {
+ state.abort?.abort();
+ state.abort = null;
+ state.app?.dispose();
+ state.app = null;
+ state.design = null;
+}
+
+// ── home ────────────────────────────────────────────────────────────────────
+
+function showHome() {
+ teardownExplorer();
+ setBusy(false);
+ $('#anpDesign').hidden = true;
+ $('#anpHome').hidden = false;
+ document.title = 'Anatomy · See how any machine works · three.ws';
+ const prefill = new URLSearchParams(location.search).get('prompt');
+ if (prefill && !$('#anpPrompt').value) $('#anpPrompt').value = prefill.slice(0, 600);
+ loadGallery();
+}
+
+function renderExamples() {
+ const host = $('#anpExamples');
+ host.replaceChildren(
+ ...EXAMPLES.map((text) =>
+ el('button', {
+ type: 'button',
+ class: 'anp-chip',
+ text,
+ onclick: () => {
+ $('#anpPrompt').value = text;
+ startGenerate(text);
+ },
+ }),
+ ),
+ );
+}
+
+function setBusy(busy) {
+ state.busy = busy;
+ const btn = $('#anpSubmit');
+ btn.disabled = busy;
+ btn.classList.toggle('is-busy', busy);
+ for (const chip of document.querySelectorAll('.anp-chip')) chip.disabled = busy;
+}
+
+function galleryCard(d) {
+ const s = d.stats || {};
+ const facts = [plural(s.instances || s.parts || 0, 'part'), s.moving ? `${s.moving} moving` : null, s.effects ? plural(s.effects, 'effect') : null].filter(Boolean);
+ return el(
+ 'a',
+ { class: 'anp-card', href: `/anatomy/${d.id}`, onclick: (e) => onInternalLink(e, `/anatomy/${d.id}`) },
+ el('span', { class: 'anp-card__glyph', 'aria-hidden': 'true' }, el('span'), el('span'), el('span')),
+ el('span', { class: 'anp-card__title', text: d.title }),
+ d.subtitle ? el('span', { class: 'anp-card__subtitle', text: d.subtitle }) : null,
+ el('span', { class: 'anp-card__facts' }, ...facts.map((f) => el('span', { text: f }))),
+ el('span', { class: 'anp-card__meta', text: [relativeTime(d.createdAt), d.views ? plural(d.views, 'view') : null].filter(Boolean).join(' · ') }),
+ );
+}
+
+async function loadGallery() {
+ const token = ++state.galleryToken;
+ const grid = $('#anpGallery');
+ const status = $('#anpGalleryStatus');
+ status.hidden = true;
+ grid.setAttribute('aria-busy', 'true');
+ grid.replaceChildren(...Array.from({ length: 6 }, () => el('div', { class: 'anp-card anp-card--skeleton', 'aria-hidden': 'true' }, el('span'), el('span'), el('span'))));
+ try {
+ const { designs, storage } = await fetchGallery({ q: state.galleryQuery });
+ if (token !== state.galleryToken) return;
+ grid.replaceChildren(...designs.map(galleryCard));
+ if (!designs.length) {
+ status.hidden = false;
+ status.replaceChildren(
+ el('strong', { text: state.galleryQuery ? `Nothing matches "${state.galleryQuery}" yet.` : storage === false ? 'Saved machines are not available on this deployment.' : 'No machines yet.' }),
+ el('span', { text: state.galleryQuery ? 'Build it: type it into the box above.' : 'Pick an example above to build the first one.' }),
+ );
+ }
+ } catch (err) {
+ if (token !== state.galleryToken) return;
+ grid.replaceChildren();
+ status.hidden = false;
+ status.replaceChildren(
+ el('strong', { text: 'The gallery did not load.' }),
+ el('span', { text: err.message || 'Check your connection.' }),
+ el('button', { type: 'button', class: 'anp-btn', text: 'Try again', onclick: loadGallery }),
+ );
+ } finally {
+ if (token === state.galleryToken) grid.removeAttribute('aria-busy');
+ }
+}
+
+function onInternalLink(e, path) {
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
+ e.preventDefault();
+ navigate(path);
+}
+
+// ── design view ─────────────────────────────────────────────────────────────
+
+function showDesignShell() {
+ $('#anpHome').hidden = true;
+ $('#anpDesign').hidden = false;
+ $('#anpDesignError').hidden = true;
+ $('#anpStage').hidden = false;
+ $('#anpWarn').hidden = true;
+ $('#anpCopyLink').hidden = true;
+ $('#anpCopySpec').hidden = true;
+ window.scrollTo(0, 0);
+}
+
+function setHeader(title, subtitle, prompt) {
+ $('#anpTitle').textContent = title || 'New machine';
+ $('#anpSubtitle').textContent = subtitle || '';
+ $('#anpSubtitle').hidden = !subtitle;
+ const asked = $('#anpAsked');
+ asked.hidden = !prompt;
+ if (prompt) asked.replaceChildren(el('span', { text: 'Asked for' }), ' ', el('q', { text: prompt }));
+ document.title = `${title || 'New machine'} · Anatomy · three.ws`;
+}
+
+function setStatus(text) {
+ const node = $('#anpStatus');
+ node.hidden = !text;
+ $('#anpStatusText').textContent = text || '';
+}
+
+function ensureExplorer() {
+ if (state.app) return state.app;
+ const stage = $('#anpStage');
+ state.app = mountAnatomy(stage, null, { theme: 'auto' });
+ return state.app;
+}
+
+function showDesignError(err, { retry } = {}) {
+ setStatus('');
+ state.app?.dispose();
+ state.app = null;
+ $('#anpStage').hidden = true;
+ $('#anpSkeleton').hidden = true;
+ const box = $('#anpDesignError');
+ box.hidden = false;
+ const notFound = err instanceof AnatomyApiError && err.status === 404;
+ box.replaceChildren(
+ el('strong', { text: notFound ? 'This machine does not exist.' : 'That did not work.' }),
+ el('span', { text: notFound ? 'The link may be mistyped, or the machine was never saved.' : err.message || 'Something went wrong.' }),
+ el(
+ 'div',
+ { class: 'anp-empty__actions' },
+ retry ? el('button', { type: 'button', class: 'anp-btn anp-btn--primary', text: 'Try again', onclick: retry }) : null,
+ el('a', { class: 'anp-btn', href: '/anatomy', text: 'Back to Anatomy', onclick: (e) => onInternalLink(e, '/anatomy') }),
+ ),
+ );
+}
+
+function showDesign(design, warnings = []) {
+ state.design = design;
+ setHeader(design.title, design.subtitle, design.prompt);
+ setStatus('');
+ $('#anpSkeleton').hidden = true;
+ const app = ensureExplorer();
+ app.update(design.spec);
+ $('#anpCopySpec').hidden = false;
+ $('#anpCopyLink').hidden = !design.url;
+ const notes = [];
+ if (!design.id) notes.push('Saving is unavailable right now, so this machine has no shareable link. Copy the spec to keep it.');
+ if (warnings.some((w) => /ran out of room/.test(w))) notes.push('Claude ran out of room on this one, so a few parts may be missing.');
+ $('#anpWarn').hidden = !notes.length;
+ $('#anpWarn').textContent = notes.join(' ');
+ app.root.focus({ preventScroll: true });
+}
+
+async function openDesign(id) {
+ teardownExplorer();
+ showDesignShell();
+ if (!UUID_RE.test(id)) return showDesignError(new AnatomyApiError(404, {}));
+ setHeader('Loading machine', '', null);
+ $('#anpSkeleton').hidden = false;
+ $('#anpSkeletonText').textContent = 'Loading the machine.';
+ try {
+ const { design } = await fetchDesign(id);
+ if (routeId() !== id) return;
+ showDesign(design);
+ } catch (err) {
+ if (routeId() !== id) return;
+ showDesignError(err, { retry: () => openDesign(id) });
+ }
+}
+
+async function startGenerate(promptIn) {
+ const prompt = String(promptIn || '').trim();
+ const formError = $('#anpFormError');
+ formError.hidden = true;
+ if (prompt.length < 3) {
+ formError.textContent = 'Describe the machine you want to see, for example "a jet engine".';
+ formError.hidden = false;
+ $('#anpPrompt').focus();
+ return;
+ }
+ if (state.busy) return;
+
+ teardownExplorer();
+ setBusy(true);
+ history.pushState(null, '', '/anatomy');
+ showDesignShell();
+ setHeader('New machine', '', prompt);
+ $('#anpSkeleton').hidden = false;
+ $('#anpSkeletonText').textContent = 'Claude is designing the machine. Parts appear here as they are written.';
+ setStatus(STAGE_TEXT.writing);
+
+ const ctrl = new AbortController();
+ state.abort = ctrl;
+ let lastCounts = '';
+ let pendingText = null;
+ let raf = 0;
+ let stage = 'writing';
+
+ const render = () => {
+ raf = 0;
+ if (ctrl.signal.aborted || pendingText == null) return;
+ const partial = scanPartialSpec(pendingText);
+ const counts = `${partial.parts.length}/${partial.effects.length}/${partial.flows.length}/${partial.steps.length}/${partial.title || ''}`;
+ if (counts === lastCounts) return;
+ lastCounts = counts;
+ if (partial.title) setHeader(partial.title, partial.subtitle, prompt);
+ if (partial.parts.length) {
+ $('#anpSkeleton').hidden = true;
+ ensureExplorer().update(partial, { progressive: true });
+ }
+ const bits = [partial.parts.length ? plural(partial.parts.length, 'part') : null, partial.effects.length ? plural(partial.effects.length, 'effect') : null, partial.steps.length ? plural(partial.steps.length, 'tour step') : null].filter(Boolean);
+ setStatus(`${STAGE_TEXT[stage] || STAGE_TEXT.writing}${bits.length ? ` · ${bits.join(', ')}` : ''}`);
+ };
+
+ try {
+ const result = await generateDesign({
+ prompt,
+ signal: ctrl.signal,
+ onStage: (s) => {
+ stage = s;
+ setStatus(STAGE_TEXT[s] || STAGE_TEXT.writing);
+ },
+ onText: (text) => {
+ pendingText = text;
+ if (!text) {
+ lastCounts = '';
+ return;
+ }
+ raf ||= requestAnimationFrame(render);
+ },
+ });
+ if (ctrl.signal.aborted) return;
+ cancelAnimationFrame(raf);
+ const { design, warnings } = result;
+ if (design.id) history.replaceState(null, '', `/anatomy/${design.id}`);
+ showDesign(design, warnings || []);
+ $('#anpPrompt').value = '';
+ } catch (err) {
+ if (ctrl.signal.aborted || err?.name === 'AbortError') return;
+ cancelAnimationFrame(raf);
+ const msg = err instanceof AnatomyApiError && err.status === 429 ? err.message || 'You are building machines quickly. Try again in a few minutes.' : err.message;
+ showDesignError(new Error(msg), { retry: err?.status === 429 ? null : () => startGenerate(prompt) });
+ } finally {
+ if (state.abort === ctrl) state.abort = null;
+ setBusy(false);
+ }
+}
+
+// ── wiring ──────────────────────────────────────────────────────────────────
+
+function init() {
+ renderExamples();
+ const form = $('#anpForm');
+ const input = $('#anpPrompt');
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ startGenerate(input.value);
+ });
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ startGenerate(input.value);
+ }
+ });
+ let searchTimer = 0;
+ $('#anpSearchInput').addEventListener('input', (e) => {
+ clearTimeout(searchTimer);
+ searchTimer = setTimeout(() => {
+ state.galleryQuery = e.target.value.trim();
+ loadGallery();
+ }, 250);
+ });
+ $('#anpSearch').addEventListener('submit', (e) => e.preventDefault());
+ $('#anpCopyLink').addEventListener('click', () => state.design?.url && copyText(state.design.url, 'Link copied'));
+ $('#anpCopySpec').addEventListener('click', () => state.app && copyText(JSON.stringify(state.app.spec, null, 2), 'Spec copied as JSON'));
+ for (const link of [$('#anpNew'), document.querySelector('.anp-back')]) {
+ link.addEventListener('click', (e) => onInternalLink(e, '/anatomy'));
+ }
+ window.addEventListener('popstate', route);
+ route();
+}
+
+init();