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 /api/anatomy to stream Claude-written machine specs, publish agent-written ones, and serve permalinks

nirholasc7bae14da960
diff --git a/api/_lib/anatomy/guide.js b/api/_lib/anatomy/guide.js
new file mode 100644
index 000000000..6509a9f5d
--- /dev/null
+++ b/api/_lib/anatomy/guide.js
@@ -0,0 +1,161 @@
+// The Anatomy spec authoring guide: the one document that teaches a model to
+// write a machine spec.
+//
+// Two consumers read it. The server writer (writer.js) sends it as the system
+// prompt when a visitor asks /anatomy for a machine, and
+// scripts/build-anatomy-skill.mjs copies it into the agent skill's
+// reference.md, so Claude Code writing a spec by hand follows exactly the
+// rules the server enforces. tests/anatomy-guide.test.js fails if the two drift.
+//
+// Every field named here exists in src/anatomy/spec.js; the guide test checks
+// that every shape, motion and effect type the normalizer accepts is
+// documented, and nothing undocumented is promised.
+
+export const SPEC_GUIDE = `# Anatomy spec reference
+
+An Anatomy spec is one JSON object that describes a machine as named parts, moving pieces, physical effects and a guided tour. The three.ws runtime renders it as an interactive isometric wireframe: people rotate it, explode it, cut it open, click parts to read about them and step through how it works.
+
+## Top level
+
+\`\`\`json
+{
+ "title": "A380-class turbofan",
+ "subtitle": "How a high-bypass engine turns kerosene into thrust",
+ "summary": "Two or three plain sentences: what the machine does and the one idea that makes it work.",
+ "parts": [],
+ "effects": [],
+ "flows": [],
+ "steps": [],
+ "view": { "speed": 1, "explode": 0, "section": "z" }
+}
+\`\`\`
+
+- \`title\` (max 80 chars), \`subtitle\` (max 140), \`summary\` (max 600; blank lines split paragraphs).
+- \`view.speed\` multiplies every motion (0 to 4, default 1). \`view.explode\` (0 to 1) opens with the parts pulled apart. \`view.section\` (\`"x"\`, \`"y"\` or \`"z"\`) opens with a cutaway along that axis, which removes the half nearest the viewer. Use a cutaway for anything whose interesting parts are inside a casing (engines, pumps, reactors, turbines).
+
+## Coordinates and units
+
+- Right handed, +Y up. One unit is whatever makes the machine about 4 to 12 units across. Keep every coordinate within ±500.
+- The camera looks from the +X, +Y, +Z corner, so put the most interesting face toward +X and +Z.
+- Rotations are Euler degrees \`[x, y, z]\`.
+- Every shape is built around its own centre. Shapes with an \`axis\` run along that axis (\`"x"\`, \`"y"\` or \`"z"\`, default \`"y"\`). A long horizontal machine (jet engine, locomotive, pump train) should run along \`"x"\`.
+
+## Parts
+
+\`\`\`json
+{
+ "id": "fan",
+ "name": "Fan",
+ "group": "Fan section",
+ "description": "What it is, what it does, and one concrete number when you know one.",
+ "parent": "low-shaft",
+ "shape": { "type": "rotor", "axis": "x", "blades": 24, "radius": 1.5, "hubRadius": 0.4, "chord": 0.45, "twist": 30, "pitch": 35 },
+ "position": [3, 0, 0],
+ "rotation": [0, 0, 0],
+ "scale": [1, 1, 1],
+ "color": "#4f8dff",
+ "style": "solid",
+ "glow": 0,
+ "repeat": { "count": 8, "axis": "x", "angle": 360 },
+ "motion": [{ "type": "spin", "axis": "x", "speed": 0.8 }],
+ "explode": [1.5, 0, 0],
+ "label": true
+}
+\`\`\`
+
+- \`id\`: short kebab-case, unique across parts, effects and flows. Steps and parents refer to it.
+- \`name\` (max 60), \`group\` (max 40; parts with the same group are listed together and share a colour when \`color\` is omitted), \`description\` (max 420; this is what people read when they click the part, so make it teach).
+- \`parent\`: id of another part. The child's position and rotation are relative to the parent, and the child inherits the parent's motion: put blades, discs and rods under the shaft that drives them so they turn together. A missing or circular parent is attached to the root.
+- \`position\`, \`rotation\`, \`scale\`: relative to the parent (or the world).
+- \`color\`: hex. Use a consistent palette: cool blues and greys for cold structure, warm oranges and reds for hot sections, greens for fluids or electrics. Omit to colour by group.
+- \`style\`: \`"solid"\` (default, shaded with hidden lines), \`"glass"\` (see-through shell; use for casings, nacelles, vessels), \`"ghost"\` (barely there; use for context like a fuselage stub), \`"wire"\` (lines only).
+- \`glow\`: 0 to 1, makes hot parts emit their own colour (combustors, turbine blades, filaments, reactor cores).
+- \`repeat\`: makes copies of the part and everything under it. Radial: \`{ "count": 8, "axis": "x", "angle": 360 }\` rotates each copy about the parent's axis through the parent's origin, so place the first copy off-axis (for example \`"position": [0, 1.2, 0]\`) and the copies ring around. A partial \`angle\` fans the copies across that arc. Linear: \`{ "count": 6, "offset": [0.5, 0, 0] }\` steps each copy by the offset. Max 96 copies.
+- \`explode\`: the direction and distance (in units, relative to the parent) this part moves when the viewer explodes the machine. Omit it and top-level parts fly outward from the centre automatically; children ride with their parent unless they set their own.
+- \`label\`: \`true\` pins a floating name label on the part. When no part sets it, the top-level parts are labelled. Label the 6 to 14 parts a newcomer must know; \`false\` hides a label.
+
+## Shapes
+
+Every \`shape\` has a \`type\`. Sizes are in units.
+
+| type | fields | use for |
+|---|---|---|
+| \`box\` | \`size [w,h,d]\`, \`radius\` (corner rounding) | frames, blocks, housings, plates |
+| \`cylinder\` | \`axis\`, \`radiusTop\`, \`radiusBottom\` (or \`radius\`), \`length\`, \`open\` | shafts, pistons, drums, tapered ducts (different radii) |
+| \`tube\` | \`axis\`, \`outerRadius\`, \`innerRadius\`, \`length\` | casings, liners, sleeves, bearings, cylinders with bores |
+| \`cone\` | \`axis\`, \`radius\`, \`length\` (tip toward +axis) | nose cones, spinners, nozzles, tips |
+| \`sphere\` | \`radius\`, \`hemisphere\`, \`axis\` | domes, balls, pressure vessels, cores |
+| \`capsule\` | \`axis\`, \`radius\`, \`length\` (overall) | tanks, rounded rods, fuel rods |
+| \`torus\` | \`axis\`, \`radius\`, \`tube\`, \`arc\` (degrees) | rings, seals, coils, tokamak vessels, manifolds |
+| \`gear\` | \`axis\`, \`teeth\`, \`radius\`, \`toothDepth\`, \`thickness\`, \`bore\` | spur gears, sprockets, escape wheels |
+| \`rotor\` | \`axis\`, \`blades\`, \`radius\`, \`hubRadius\`, \`chord\`, \`thickness\`, \`twist\`, \`pitch\`, \`hubLength\` | fans, compressor and turbine stages, propellers, impellers, wind turbine rotors |
+| \`lathe\` | \`axis\`, \`profile [[r, along], ...]\` | any turned part: nacelles, bells, nozzles, pistons with crowns, bottles. \`r\` is the radius at position \`along\` the axis |
+| \`extrude\` | \`axis\` (default \`"z"\`), \`points [[u, v], ...]\`, \`depth\` | flat plates of any outline: con-rod webs, brackets, cams, levers, anchors |
+| \`spring\` | \`axis\`, \`radius\`, \`wire\`, \`turns\`, \`length\` | coil springs, heating coils, windings |
+| \`pipe\` | \`path [[x,y,z], ...]\`, \`radius\`, \`closed\` | plumbing, fuel lines, cables, exhaust headers. Path points are in the part's own space |
+
+Shape tips:
+- A turbofan's nacelle, a rocket's bell and a reactor vessel are \`lathe\` profiles. Six to twelve profile points give a smooth, accurate silhouette. For a hollow shell, trace the outer surface out and back along the inner surface, the way a machinist would draw a half section.
+- A compressor or turbine is a stack of \`rotor\` stages, each a thin slice (small \`hubLength\`) at its own position, under the shaft that drives them. Real engines have many stages; draw enough (6 to 12) to read as a stack.
+- Stator vanes are a \`rotor\` with no motion and negative \`pitch\`, interleaved between rotor stages.
+- Gears that mesh must have the same tooth size: \`radius / teeth\` equal on both, and centres \`r1 + r2\` apart. Spin them in opposite directions at speeds inversely proportional to their tooth counts.
+
+## Motion
+
+\`motion\` is a list (max 3) applied in order. Children inherit it.
+
+- \`{ "type": "spin", "axis": "x", "speed": 0.5, "phase": 0 }\`: continuous rotation, \`speed\` in revolutions per second (negative reverses). Keep it readable: 0.2 to 2. Show relative speeds truthfully (an HP spool turns faster than an LP spool) but scale them down.
+- \`{ "type": "oscillate", "kind": "translate", "axis": "y", "amplitude": 0.3, "frequency": 1, "phase": 0 }\`: back and forth, amplitude in units. \`"kind": "rotate"\` rocks instead, amplitude in degrees (pendulums, pallets, valve rockers).
+- \`{ "type": "crank", "axis": "y", "radius": 0.4, "rod": 1.4, "speed": 1, "phase": 0 }\`: true slider-crank travel for pistons, between +radius and -radius about the part's position. Match \`speed\` to the crankshaft's spin, and give each cylinder its firing-order \`phase\` (degrees).
+- \`{ "type": "pulse", "amplitude": 0.06, "frequency": 1 }\`: breathing scale for hearts of the machine (a reactor core, a solenoid).
+
+## Effects
+
+Effects are the physics you can see. Each has an \`id\` and a \`type\`, and sits at \`position\` (relative to its \`parent\` part when given, so a flame inside a spinning part spins with it, and a repeated parent repeats its effects). Volumes grow from \`position\` along \`axis\` in \`direction\` (1 or -1).
+
+| type | fields | use for |
+|---|---|---|
+| \`flame\` | \`radius\` (base), \`radiusEnd\`, \`length\`, \`axis\`, \`direction\` | combustors, burners, candles, fireboxes |
+| \`exhaust\` | \`radius\`, \`radiusEnd\`, \`length\`, \`axis\`, \`direction\` | jet and rocket plumes, with shock diamonds |
+| \`plasma\` | \`radius\`, \`form\` (\`"sphere"\`, \`"torus"\` with \`radiusEnd\` as the tube, \`"column"\` with \`length\`) | fusion plasma, arcs in a lamp, stellar cores, ion drives |
+| \`water\` | \`radius\`, \`radiusEnd\`, \`length\` (a stream), or \`"form": "pool"\` with \`size [w,h,d]\` | jets, falling water, coolant pools, tanks |
+| \`smoke\` | \`radius\`, \`length\` (rise height), \`count\` | chimneys, exhaust stacks, burning fuel |
+| \`steam\` | \`radius\`, \`length\`, \`count\` | boilers, kettles, cooling towers, safety valves |
+| \`sparks\` | \`radius\`, \`length\`, \`count\` | spark plugs, grinders, welding, ignition |
+| \`electric\` | \`from [x,y,z]\`, \`to [x,y,z]\` | arcs, lightning, spark gaps, Tesla coils |
+| \`glow\` | \`radius\` | hot spots, lamps, LEDs, heat sources |
+
+All effects also take \`name\`, \`description\`, \`color\` and \`color2\` (hex; sensible defaults per type), \`intensity\` (0 to 3) and \`speed\` (0 to 10).
+
+## Flows
+
+Flows show something travelling through the machine: air, fuel, coolant, current, steam, exhaust. Particles stream along a smooth path over a dashed guide with direction arrows.
+
+\`\`\`json
+{ "id": "core-air", "name": "Core airflow", "description": "...", "path": [[4,0.3,0],[2,0.3,0],[0,0.2,0],[-2,0.3,0],[-4,0.2,0]], "color": "#3fa9ff", "speed": 0.3, "count": 40, "size": 1, "closed": false }
+\`\`\`
+
+- \`path\` is in world space (2 to 64 points). Route it through the real passages: between casing and core, around a loop, down a pipe.
+- \`speed\` is path lengths per second (0.1 to 0.6 reads well). \`closed: true\` for loops (refrigerant, coolant, a current in a circuit).
+- Use distinct colours per flow (cold air blue, hot gas orange, fuel amber, coolant cyan).
+
+## Steps (the tour)
+
+\`\`\`json
+{ "title": "Air comes in", "body": "Two to four sentences explaining this stage, with a real number when you know one.", "focus": ["fan", "inlet", "bypass-air"] }
+\`\`\`
+
+- 4 to 10 steps that follow the physics in order (intake to exhaust, fuel to power, input to output). The final step ties it together.
+- \`focus\` lists the part, effect and flow ids this step is about. The viewer fades everything else and frames these, so be selective. Parts under a focused part are included automatically.
+- \`body\` max 520 characters; blank lines split paragraphs.
+
+## Quality bar
+
+- Be accurate. Real proportions, real part names, real stage counts, real numbers in descriptions and steps (pressure ratios, temperatures, rpm, efficiencies). If you are unsure of a figure, describe the relationship instead of inventing a number.
+- Be complete. Every part a textbook cutaway would label should be there, typically 25 to 90 parts plus repeats. Moving parts move; hot parts glow; working fluids flow.
+- Build hierarchies. Rotating assemblies are one shaft part with blades, discs and hubs as children.
+- Make the motion tell the story: what spins, what reciprocates, what stays still, and the flows show where the energy goes.
+- Lay it out so it reads at a glance from the isometric corner; use \`glass\` casings and a \`view.section\` cutaway instead of hiding the interior.
+`;
+
+export const OUTPUT_RULES = `Return only the JSON object. No prose before or after it, no markdown fences, no comments, no trailing commas. Write the keys in this order so the viewer can draw the machine while you are still writing: title, subtitle, summary, view, parts, effects, flows, steps. Put parents before their children in the parts list.`;
diff --git a/api/_lib/anatomy/service.js b/api/_lib/anatomy/service.js
new file mode 100644
index 000000000..237706d2c
--- /dev/null
+++ b/api/_lib/anatomy/service.js
@@ -0,0 +1,184 @@
+// Anatomy service: the operations every transport shares.
+//
+// api/anatomy.js (the /anatomy page) and the anatomy_* MCP tools both call
+// these, so a machine written on the page and one published by an agent are
+// the same record with the same permalink.
+
+import { AnatomySpecError, extractSpecJson, normalizeSpec, specStats } from '../../../src/anatomy/spec.js';
+import { scanPartialSpec } from '../../../src/anatomy/stream.js';
+import { OUTPUT_RULES, SPEC_GUIDE } from './guide.js';
+import { streamSpec } from './writer.js';
+import { anatomyStoreEnabled, getDesign, newDesignId, saveDesign } from './store.js';
+
+const SITE = process.env.PUBLIC_BASE_URL || 'https://three.ws';
+export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+export const MAX_PROMPT_LEN = 600;
+export const MAX_SPEC_BYTES = 400_000;
+// A spec cut off by the token limit still carries every part that finished.
+// Past this many, the salvaged machine is worth showing rather than retrying.
+const SALVAGE_MIN_PARTS = 12;
+
+export class AnatomyError extends Error {
+ constructor(code, message, status = 400, detail = null) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ this.detail = detail;
+ }
+}
+
+export function designUrl(id) {
+ return `${SITE}/anatomy/${id}`;
+}
+
+export function publicDesign(design) {
+ return { ...design, url: design.id ? designUrl(design.id) : null };
+}
+
+export function cleanPrompt(raw) {
+ const prompt = String(raw ?? '')
+ .replace(/^\s*\/anatomy\s+/i, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, MAX_PROMPT_LEN);
+ if (prompt.length < 3) throw new AnatomyError('prompt_required', 'Describe the machine you want to see.', 400);
+ return prompt;
+}
+
+export function systemPrompt() {
+ return [
+ 'You are Anatomy, an engineer and illustrator who explains how machines work by building them as interactive 3D cutaways.',
+ 'Given a request, design the machine as an Anatomy spec: accurate geometry, the real moving parts in motion, the physics made visible with effects and flows, and a guided tour that teaches it step by step.',
+ 'Write for a curious, smart reader who is not an engineer: plain words, concrete numbers, no filler. Never use the em dash or en dash characters.',
+ SPEC_GUIDE,
+ OUTPUT_RULES,
+ ].join('\n\n');
+}
+
+function userMessage(prompt) {
+ return `Build this machine: ${prompt}\n\nIf the request names a specific real machine, model it on that machine. If it is vague, choose the most iconic real example and say which in the subtitle.`;
+}
+
+/**
+ * Turn model text into a normalized spec. Tries the whole document first,
+ * then salvages every complete element when the text was cut short.
+ * Returns { spec, warnings, salvaged } or throws AnatomySpecError.
+ */
+export function parseSpecText(text) {
+ const raw = extractSpecJson(text);
+ if (raw) return { ...normalizeSpec(raw), salvaged: false };
+ const partial = scanPartialSpec(text);
+ if (partial.parts.length >= SALVAGE_MIN_PARTS) {
+ const { spec, warnings } = normalizeSpec(partial);
+ return { spec, warnings: ['The model ran out of room; the machine shows every part it finished.', ...warnings], salvaged: true };
+ }
+ throw new AnatomySpecError(partial.parts.length ? `The spec was cut off after ${partial.parts.length} parts.` : 'The model did not return a JSON spec.');
+}
+
+function specSize(spec) {
+ return Buffer.byteLength(JSON.stringify(spec), 'utf8');
+}
+
+async function persist({ spec, prompt, source, model, user }) {
+ const design = {
+ id: newDesignId(),
+ title: spec.title,
+ subtitle: spec.subtitle,
+ prompt,
+ spec,
+ stats: specStats(spec),
+ source,
+ model,
+ userId: user?.id ?? null,
+ };
+ const saved = await saveDesign(design);
+ if (saved) return publicDesign(saved);
+ // Storage off or a failed write: the visitor still gets their machine, it
+ // just has no permalink. The page says so instead of showing a dead link.
+ const { userId: _omit, ...rest } = design;
+ return publicDesign({ ...rest, id: null, views: 0, creatorUsername: null, createdAt: new Date().toISOString() });
+}
+
+/**
+ * Write a machine with Claude, streaming it as it is written. Events:
+ * { type: 'stage', stage: 'writing' | 'repairing' | 'saving' }
+ * { type: 'delta', text } raw model text, to render progressively
+ * { type: 'reset' } discard the text so far (a rung died mid-way)
+ * Returns { design, warnings }.
+ */
+export async function generateDesign({ prompt, user = null, onEvent = () => {} }) {
+ const system = systemPrompt();
+ const messages = [{ role: 'user', content: userMessage(prompt) }];
+ const track = { userId: user?.id ?? null };
+
+ onEvent({ type: 'stage', stage: 'writing' });
+ let written = await streamSpec({
+ system,
+ messages,
+ track,
+ onDelta: (text) => onEvent({ type: 'delta', text }),
+ onReset: () => onEvent({ type: 'reset' }),
+ });
+
+ let parsed;
+ try {
+ parsed = parseSpecText(written.text);
+ } catch (err) {
+ // One repair round: show the model exactly what failed and ask for the
+ // whole object again. The client discards the first attempt.
+ onEvent({ type: 'stage', stage: 'repairing', reason: err.message });
+ onEvent({ type: 'reset' });
+ const truncated = written.stopReason === 'max_tokens' || written.stopReason === 'length';
+ const fix = truncated
+ ? 'Your answer was cut off before the JSON closed. Write the complete spec again, more compactly: fewer, well-chosen parts (use repeat and parent hierarchies instead of listing copies) and shorter descriptions, so it fits.'
+ : `Your answer could not be used: ${err.message} Write the complete spec again as one valid JSON object.`;
+ written = await streamSpec({
+ system,
+ messages: [...messages, { role: 'assistant', content: written.text.slice(0, 60_000) || '{}' }, { role: 'user', content: `${fix}\n\n${OUTPUT_RULES}` }],
+ track,
+ onDelta: (text) => onEvent({ type: 'delta', text }),
+ onReset: () => onEvent({ type: 'reset' }),
+ });
+ try {
+ parsed = parseSpecText(written.text);
+ } catch (again) {
+ throw new AnatomyError('spec_failed', 'The model could not produce a working machine for that. Try rephrasing it, or name a specific machine.', 502, again.message);
+ }
+ }
+
+ if (specSize(parsed.spec) > MAX_SPEC_BYTES) throw new AnatomyError('spec_too_large', 'That machine came out too large to save. Try a narrower request.', 422);
+ onEvent({ type: 'stage', stage: 'saving' });
+ const design = await persist({ spec: parsed.spec, prompt, source: 'generated', model: written.model ? `${written.provider}:${written.model}` : null, user });
+ return { design, warnings: parsed.warnings };
+}
+
+/**
+ * Save a spec an agent wrote itself (the anatomy skill, MCP). No model call.
+ * Returns { design, warnings }.
+ */
+export async function publishDesign({ spec: raw, prompt = null, user = null }) {
+ let input = raw;
+ if (typeof input === 'string') {
+ input = extractSpecJson(input);
+ if (!input) throw new AnatomyError('invalid_spec', 'spec must be a JSON object (or a string holding one).', 400);
+ }
+ let normalized;
+ try {
+ normalized = normalizeSpec(input);
+ } catch (err) {
+ throw new AnatomyError('invalid_spec', err.message, 400, err.warnings || null);
+ }
+ if (specSize(normalized.spec) > MAX_SPEC_BYTES) throw new AnatomyError('spec_too_large', `The spec is over ${MAX_SPEC_BYTES / 1000} KB after normalizing.`, 413);
+ if (!anatomyStoreEnabled()) throw new AnatomyError('storage_unavailable', 'Publishing needs the database, which is not configured on this deployment.', 503);
+ const cleanedPrompt = prompt ? String(prompt).replace(/\s+/g, ' ').trim().slice(0, MAX_PROMPT_LEN) || null : null;
+ const design = await persist({ spec: normalized.spec, prompt: cleanedPrompt, source: 'published', model: null, user });
+ if (!design.id) throw new AnatomyError('storage_unavailable', 'The design could not be saved right now. Try again.', 503);
+ return { design, warnings: normalized.warnings };
+}
+
+export async function loadDesign(id) {
+ if (!UUID_RE.test(String(id || ''))) throw new AnatomyError('invalid_id', 'Malformed design id.', 400);
+ const design = await getDesign(String(id));
+ if (!design) throw new AnatomyError('not_found', 'No machine with that id.', 404);
+ return publicDesign(design);
+}
diff --git a/api/_lib/anatomy/store.js b/api/_lib/anatomy/store.js
new file mode 100644
index 000000000..7c4ba6c2e
--- /dev/null
+++ b/api/_lib/anatomy/store.js
@@ -0,0 +1,135 @@
+// Anatomy persistence: one row per machine in `anatomy_designs`.
+//
+// A design is a normalized spec (src/anatomy/spec.js) plus where it came from:
+// written by Claude on /anatomy (`generated`), written by an agent through the
+// skill or MCP (`published`). The spec is the whole artifact, there are no
+// files, so a design renders from a single row.
+//
+// The table is created lazily, the same contract as the CAD Forge store:
+// without DATABASE_URL every read returns null/empty and every write null.
+
+import { randomUUID } from 'node:crypto';
+import { sql } from '../db.js';
+import { databaseConfigured } from '../env.js';
+import { recordDailyActivity, maybeAwardFirstCreation } from '../streaks.js';
+
+export function anatomyStoreEnabled() {
+ return databaseConfigured();
+}
+
+let _ensured = null;
+async function ensureTables() {
+ if (!anatomyStoreEnabled()) return false;
+ if (_ensured) return _ensured;
+ _ensured = (async () => {
+ await sql`
+ create table if not exists anatomy_designs (
+ id uuid primary key,
+ title text not null,
+ subtitle text,
+ prompt text,
+ spec jsonb not null,
+ stats jsonb not null,
+ source text not null default 'generated',
+ model text,
+ user_id uuid,
+ views bigint not null default 0,
+ created_at timestamptz not null default now()
+ )
+ `;
+ await sql`create index if not exists anatomy_designs_created_idx on anatomy_designs (created_at desc)`;
+ await sql`create index if not exists anatomy_designs_user_idx on anatomy_designs (user_id, created_at desc)`;
+ return true;
+ })().catch((err) => {
+ console.error('[anatomy-store] ensureTables failed:', err?.message);
+ _ensured = null;
+ return false;
+ });
+ return _ensured;
+}
+
+export function newDesignId() {
+ return randomUUID();
+}
+
+function toDesign(row, { withSpec = true } = {}) {
+ return {
+ id: row.id,
+ title: row.title,
+ subtitle: row.subtitle || '',
+ prompt: row.prompt || null,
+ ...(withSpec ? { spec: row.spec } : {}),
+ stats: row.stats,
+ source: row.source,
+ model: row.model || null,
+ views: Number(row.views) || 0,
+ creatorUsername: row.creator_username || null,
+ createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
+ };
+}
+
+/** Persist a design. Returns the stored design, or null when storage is off or the write failed. */
+export async function saveDesign(design) {
+ if (!(await ensureTables())) return null;
+ const createdAt = new Date().toISOString();
+ try {
+ await sql`
+ insert into anatomy_designs (id, title, subtitle, prompt, spec, stats, source, model, user_id, created_at)
+ values (
+ ${design.id}, ${design.title}, ${design.subtitle || null}, ${design.prompt || null},
+ ${JSON.stringify(design.spec)}::jsonb, ${JSON.stringify(design.stats)}::jsonb,
+ ${design.source}, ${design.model || null}, ${design.userId || null}, ${createdAt}
+ )
+ `;
+ } catch (err) {
+ console.error('[anatomy-store] saveDesign failed:', err?.message);
+ return null;
+ }
+ if (design.userId) {
+ recordDailyActivity(design.userId).catch(() => {});
+ maybeAwardFirstCreation(design.userId).catch(() => {});
+ }
+ const { userId: _omit, ...rest } = design;
+ return { ...rest, views: 0, creatorUsername: null, createdAt };
+}
+
+export async function getDesign(id) {
+ if (!id || !(await ensureTables())) return null;
+ try {
+ const rows = await sql`
+ select d.*, u.username as creator_username
+ from anatomy_designs d
+ left join users u on u.id = d.user_id and u.deleted_at is null
+ where d.id = ${id}
+ limit 1
+ `;
+ return rows[0] ? toDesign(rows[0]) : null;
+ } catch (err) {
+ console.error('[anatomy-store] getDesign failed:', err?.message);
+ return null;
+ }
+}
+
+export async function bumpViews(id) {
+ if (!(await ensureTables())) return;
+ sql`update anatomy_designs set views = views + 1 where id = ${id}`.catch(() => {});
+}
+
+/** Newest designs without their specs (gallery cards). */
+export async function listDesigns({ limit = 24, q } = {}) {
+ if (!(await ensureTables())) return [];
+ const lim = Math.min(60, Math.max(1, Number(limit) || 24));
+ const search = q ? `%${String(q).slice(0, 80).replace(/[%_\\]/g, (c) => `\\${c}`)}%` : null;
+ try {
+ const rows = search
+ ? await sql`select id, title, subtitle, prompt, stats, source, model, views, created_at
+ from anatomy_designs where title ilike ${search} or prompt ilike ${search} or subtitle ilike ${search}
+ order by created_at desc limit ${lim}`
+ : await sql`select id, title, subtitle, prompt, stats, source, model, views, created_at
+ from anatomy_designs order by created_at desc limit ${lim}`;
+ return rows.map((r) => toDesign(r, { withSpec: false }));
+ } catch (err) {
+ console.error('[anatomy-store] listDesigns failed:', err?.message);
+ return [];
+ }
+}
diff --git a/api/_lib/anatomy/writer.js b/api/_lib/anatomy/writer.js
new file mode 100644
index 000000000..b2559e77d
--- /dev/null
+++ b/api/_lib/anatomy/writer.js
@@ -0,0 +1,245 @@
+// Anatomy writer: streams a machine spec out of Claude.
+//
+// A good spec is 6 to 14K tokens of exact JSON (geometry, motion, physics and
+// a tour) and the visitor watches it assemble part by part, so every rung
+// 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)
+// 2. Claude on the Anthropic API, when a key is configured
+// 3. Claude through OpenRouter
+// 4. Kimi K3 on NVIDIA NIM (free)
+// 5. the platform's general chain, non-streaming, so a request is never
+// refused while any model answers
+//
+// A rung that fails before any text arrived is skipped silently. One that
+// fails part way through emits `reset` so the client clears the half-drawn
+// machine before the next rung starts over.
+
+import { llmComplete } from '../llm.js';
+import { recordEvent } from '../usage.js';
+
+export const ANATOMY_MODEL_DEFAULT = 'claude-opus-5';
+const FALLBACK_CLAUDE = 'claude-sonnet-5';
+const MAX_TOKENS = 16_000;
+
+export class AnatomyWriterError extends Error {
+ constructor(message, failures = []) {
+ super(message);
+ this.code = 'writer_unavailable';
+ this.failures = failures;
+ }
+}
+
+/** Parse an SSE body into { event, data } records. */
+export async function* sseRecords(body) {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ try {
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let idx;
+ while ((idx = buf.search(/\r?\n\r?\n/)) !== -1) {
+ const raw = buf.slice(0, idx);
+ buf = buf.slice(idx).replace(/^\r?\n\r?\n/, '');
+ let event = 'message';
+ const data = [];
+ for (const line of raw.split(/\r?\n/)) {
+ if (line.startsWith('event:')) event = line.slice(6).trim();
+ else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
+ }
+ if (data.length) yield { event, data: data.join('\n') };
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+/** Read an Anthropic Messages SSE stream. Returns { text, usage, stopReason }. */
+export async function readAnthropicStream(body, onDelta) {
+ let text = '';
+ const usage = { input: 0, output: 0 };
+ let stopReason = null;
+ for await (const { data } of sseRecords(body)) {
+ let msg;
+ try {
+ msg = JSON.parse(data);
+ } catch {
+ continue;
+ }
+ if (msg.type === 'message_start') usage.input = msg.message?.usage?.input_tokens || 0;
+ else if (msg.type === 'content_block_delta' && msg.delta?.type === 'text_delta') {
+ text += msg.delta.text;
+ onDelta(msg.delta.text);
+ } else if (msg.type === 'message_delta') {
+ usage.output = msg.usage?.output_tokens || usage.output;
+ stopReason = msg.delta?.stop_reason || stopReason;
+ } else if (msg.type === 'error') {
+ throw new Error(`stream error: ${msg.error?.message || 'unknown'}`);
+ }
+ }
+ return { text, usage, stopReason };
+}
+
+/** Read an OpenAI-style chat-completions SSE stream. */
+export async function readChatStream(body, onDelta) {
+ let text = '';
+ const usage = { input: 0, output: 0 };
+ let stopReason = null;
+ for await (const { data } of sseRecords(body)) {
+ if (data === '[DONE]') break;
+ let msg;
+ try {
+ msg = JSON.parse(data);
+ } catch {
+ continue;
+ }
+ if (msg.error) throw new Error(`stream error: ${msg.error.message || 'unknown'}`);
+ const choice = msg.choices?.[0];
+ const piece = choice?.delta?.content;
+ if (typeof piece === 'string' && piece) {
+ text += piece;
+ onDelta(piece);
+ }
+ if (choice?.finish_reason) stopReason = choice.finish_reason;
+ if (msg.usage) usage.input = msg.usage.prompt_tokens || usage.input;
+ if (msg.usage) usage.output = msg.usage.completion_tokens || usage.output;
+ }
+ return { text, usage, stopReason };
+}
+
+function anthropicBody(model, system, messages) {
+ return { model, max_tokens: MAX_TOKENS, temperature: 0.4, stream: true, system, messages };
+}
+
+export function writerRungs(env = process.env) {
+ const rungs = [];
+ const primary = env.ANATOMY_MODEL || ANATOMY_MODEL_DEFAULT;
+ if (env.GOOGLE_CLOUD_PROJECT) {
+ for (const model of [...new Set([primary, FALLBACK_CLAUDE])]) {
+ rungs.push({
+ provider: 'vertex',
+ model,
+ kind: 'anthropic',
+ open: async ({ system, messages, signal }) => {
+ const { vertexAnthropicMessages } = await import('../vertex-claude.js');
+ return vertexAnthropicMessages(anthropicBody(model, system, messages), { stream: true, signal });
+ },
+ });
+ }
+ }
+ if (env.ANTHROPIC_API_KEY) {
+ rungs.push({
+ provider: 'anthropic',
+ model: primary,
+ kind: 'anthropic',
+ open: ({ system, messages, signal, fetchImpl }) =>
+ fetchImpl('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: { 'x-api-key': env.ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },
+ body: JSON.stringify(anthropicBody(primary, system, messages)),
+ signal,
+ }),
+ });
+ }
+ const chat = (provider, url, key, model, extra = {}) => ({
+ provider,
+ model,
+ kind: 'chat',
+ open: ({ system, messages, signal, fetchImpl }) =>
+ fetchImpl(url, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json', ...extra.headers },
+ body: JSON.stringify({
+ model,
+ max_tokens: MAX_TOKENS,
+ temperature: 0.4,
+ stream: true,
+ messages: [{ role: 'system', content: system }, ...messages],
+ ...extra.body,
+ }),
+ signal,
+ }),
+ });
+ 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' },
+ }),
+ );
+ }
+ 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 } },
+ }),
+ );
+ }
+ return rungs;
+}
+
+/**
+ * Stream one completion through the ladder.
+ * messages Anthropic-shaped [{ role, content: string }]
+ * onDelta (text) => void for every streamed piece
+ * onReset () => void when a rung died after streaming some text
+ * Returns { text, provider, model, stopReason }.
+ */
+export async function streamSpec({ system, messages, onDelta = () => {}, onReset = () => {}, deadline = Date.now() + 420_000, track = {}, env = process.env, fetchImpl = fetch }) {
+ const failures = [];
+ for (const rung of writerRungs(env)) {
+ const remaining = deadline - Date.now();
+ if (remaining < 20_000) break;
+ const started = Date.now();
+ let streamed = false;
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), remaining);
+ try {
+ const res = await rung.open({ system, messages, signal: ctrl.signal, fetchImpl });
+ if (!res.ok || !res.body) {
+ const detail = await res.text().catch(() => '');
+ throw new Error(`${res.status} ${detail.slice(0, 160)}`);
+ }
+ const reader = rung.kind === 'anthropic' ? readAnthropicStream : readChatStream;
+ const out = await reader(res.body, (piece) => {
+ streamed = true;
+ onDelta(piece);
+ });
+ if (!out.text.trim()) throw new Error('empty completion');
+ recordEvent({
+ kind: 'llm',
+ provider: rung.provider,
+ model: rung.model,
+ inputTokens: out.usage.input,
+ outputTokens: out.usage.output,
+ latencyMs: Date.now() - started,
+ userId: track.userId ?? null,
+ tool: 'anatomy',
+ });
+ 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}`);
+ if (streamed) onReset();
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+ if (failures.length) console.warn('[anatomy-writer] streaming ladder exhausted:', failures.join(' | '));
+ const remaining = deadline - Date.now();
+ if (remaining < 15_000) throw new AnatomyWriterError('No model finished the machine in time. Try again.', failures);
+ try {
+ const user = messages.map((m) => `${m.role === 'assistant' ? 'Your previous answer' : 'Request'}:\n${m.content}`).join('\n\n');
+ const completion = await llmComplete({ system, user, maxTokens: MAX_TOKENS, timeoutMs: remaining, track: { tool: 'anatomy', ...track } });
+ const text = completion?.text || '';
+ if (!text.trim()) throw new Error('empty completion');
+ onDelta(text);
+ return { text, provider: completion.provider || null, model: completion.model || null, stopReason: null };
+ } catch (err) {
+ failures.push(`general: ${err?.message}`);
+ throw new AnatomyWriterError('Every model is unavailable right now. Try again in a minute.', failures);
+ }
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 238f1944b..14011d440 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1138,6 +1138,21 @@ export const limits = {
}).limit('global'),
cadRebuildIp: (ip) =>
getLimiter('cad:rebuild:ip', { limit: 90, window: '10 m', critical: true }).limit(ip),
+ // Anatomy (api/anatomy): one generation streams up to two long Claude
+ // completions (write plus one repair), so it is capped per IP with a global
+ // hourly breaker, critical so a Redis outage fails closed. Publishing a spec
+ // an agent wrote itself costs no model call, only a row, so it gets a looser
+ // bucket of its own.
+ anatomyIp: (ip) =>
+ getLimiter('anatomy:ip', { limit: 12, window: '10 m', critical: true }).limit(ip),
+ anatomyGlobal: () =>
+ getLimiter('anatomy:global', {
+ limit: Math.max(60, Number(process.env.ANATOMY_GLOBAL_HOURLY) || 400),
+ window: '1 h',
+ critical: true,
+ }).limit('global'),
+ anatomyPublishIp: (ip) =>
+ getLimiter('anatomy:publish:ip', { limit: 60, window: '10 m', critical: true }).limit(ip),
// Portal (api/portal): fetches a caller-supplied website once and builds a
// walkable world from it. The spend is other people's bandwidth rather than
// ours, which is exactly why it is capped: a build is one origin request plus
diff --git a/api/_lib/vertex-claude.js b/api/_lib/vertex-claude.js
index 8a108a393..e781027c3 100644
--- a/api/_lib/vertex-claude.js
+++ b/api/_lib/vertex-claude.js
@@ -123,7 +123,9 @@ export async function vertexRequestHeaders() {
// Issue an Anthropic Messages request against Vertex and return the raw Response
// (streaming or not), so callers can pass the SSE body through unchanged or read
// the JSON. `body` is a first-party-shaped Anthropic body including `model`.
-export async function vertexAnthropicMessages(body, { stream = false } = {}) {
+// An optional caller `signal` aborts the whole request, body included, for
+// callers that hold a deadline across a long stream.
+export async function vertexAnthropicMessages(body, { stream = false, signal = null } = {}) {
const url = vertexMessagesUrl(body.model, { stream });
const headers = await vertexRequestHeaders();
const headersCtrl = new AbortController();
@@ -133,7 +135,7 @@ export async function vertexAnthropicMessages(body, { stream = false } = {}) {
method: 'POST',
headers,
body: JSON.stringify(toVertexBody(body)),
- signal: headersCtrl.signal,
+ signal: signal ? AbortSignal.any([headersCtrl.signal, signal]) : headersCtrl.signal,
});
} finally {
clearTimeout(headersTimer);
diff --git a/api/anatomy.js b/api/anatomy.js
new file mode 100644
index 000000000..37a2f465b
--- /dev/null
+++ b/api/anatomy.js
@@ -0,0 +1,182 @@
+/**
+ * Anatomy: describe a machine in one line and get it back as an interactive
+ * isometric cutaway with moving parts, shader effects and a guided tour.
+ *
+ * POST /api/anatomy { action:'generate', prompt, stream? }
+ * Claude writes an Anatomy spec (src/anatomy/spec.js). stream:true
+ * answers text/event-stream so the page can draw the machine while it is
+ * written: `stage` { stage }, `delta` { text }, `reset` (discard the text
+ * so far), then one `done` { design, warnings } or `error`. Otherwise
+ * one JSON body { design, warnings }.
+ *
+ * POST /api/anatomy { action:'publish', spec, prompt? }
+ * Saves a spec an agent wrote itself (the anatomy skill, MCP) and
+ * returns its permalink. No model call. → { design, warnings }
+ *
+ * GET /api/anatomy?id=<uuid> → { design }
+ * GET /api/anatomy?list=recent[&q=][&limit=] → { designs }, newest first
+ *
+ * No mocks: when no model answers, the caller gets a designed 503, never a
+ * canned machine.
+ */
+
+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { getSessionUser } from './_lib/auth.js';
+import { AnatomyWriterError } from './_lib/anatomy/writer.js';
+import { anatomyStoreEnabled, bumpViews, listDesigns } from './_lib/anatomy/store.js';
+import { AnatomyError, MAX_SPEC_BYTES, cleanPrompt, generateDesign, loadDesign, publishDesign } from './_lib/anatomy/service.js';
+
+const KEEPALIVE_MS = 15_000;
+// Model text arrives a few tokens at a time; coalescing it keeps the event
+// count (and the page's re-render rate) sane without visible lag.
+const DELTA_FLUSH_MS = 60;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (req.method === 'GET') return handleGet(req, res);
+
+ const body = await readJson(req, MAX_SPEC_BYTES * 2).catch(() => null);
+ if (!body || typeof body !== 'object') {
+ return json(res, 400, { error: 'invalid_body', message: 'Send a JSON body.' });
+ }
+ if (body.action === 'generate') return handleGenerate(req, res, body);
+ if (body.action === 'publish') return handlePublish(req, res, body);
+ return json(res, 400, { error: 'unknown_action', message: 'action must be "generate" or "publish".' });
+});
+
+async function handleGet(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const id = url.searchParams.get('id');
+ const list = url.searchParams.get('list');
+
+ if (id) {
+ try {
+ const design = await loadDesign(id);
+ bumpViews(id);
+ return json(res, 200, { design }, { 'cache-control': 'public, max-age=15, s-maxage=60' });
+ } catch (err) {
+ return sendError(res, err, null);
+ }
+ }
+
+ if (list !== null) {
+ const designs = await listDesigns({
+ limit: Number(url.searchParams.get('limit')) || 24,
+ q: url.searchParams.get('q') || undefined,
+ });
+ return json(
+ res,
+ 200,
+ { designs, storage: anatomyStoreEnabled() },
+ { 'cache-control': 'public, max-age=20, s-maxage=60' },
+ );
+ }
+
+ return json(res, 400, { error: 'bad_request', message: 'Pass ?id= or ?list=.' });
+}
+
+function openStream(res) {
+ res.statusCode = 200;
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
+ res.setHeader('Cache-Control', 'no-cache, no-store');
+ res.setHeader('Connection', 'keep-alive');
+ res.setHeader('X-Accel-Buffering', 'no');
+ res.flushHeaders?.();
+ const write = (event, data) => {
+ if (res.writableEnded) return;
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ };
+ let pending = '';
+ let flushTimer = null;
+ const flush = () => {
+ clearTimeout(flushTimer);
+ flushTimer = null;
+ if (pending) write('delta', { text: pending });
+ pending = '';
+ };
+ const send = (event, data) => {
+ if (event === 'delta') {
+ pending += data.text;
+ flushTimer ??= setTimeout(flush, DELTA_FLUSH_MS);
+ return;
+ }
+ if (event === 'reset') pending = '';
+ flush();
+ write(event, data);
+ };
+ // Before the first token a long model call is silent; comments keep proxies
+ // from timing the idle connection out.
+ const keepalive = setInterval(() => {
+ if (!res.writableEnded) res.write(': keepalive\n\n');
+ }, KEEPALIVE_MS);
+ const close = () => {
+ flush();
+ clearInterval(keepalive);
+ if (!res.writableEnded) res.end();
+ };
+ return { send, close };
+}
+
+function sendError(res, err, stream) {
+ const known = err instanceof AnatomyError;
+ const writer = err instanceof AnatomyWriterError;
+ if (!known) console.error('[anatomy] request failed:', err?.message, writer ? err.failures : '');
+ const status = known ? err.status : writer ? 503 : 500;
+ const out = {
+ error: known || writer ? err.code : 'internal_error',
+ message: known || writer ? err.message : 'Something went wrong building this machine. Try again.',
+ ...(known && err.detail ? { detail: err.detail } : {}),
+ };
+ if (stream) {
+ stream.send('error', { status, ...out });
+ stream.close();
+ return;
+ }
+ return json(res, status, out);
+}
+
+async function handleGenerate(req, res, body) {
+ let prompt;
+ try {
+ prompt = cleanPrompt(body.prompt);
+ } catch (err) {
+ return sendError(res, err, null);
+ }
+
+ const rl = await limits.anatomyIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'Machine limit reached. Try again in a few minutes.');
+ const globalRl = await limits.anatomyGlobal();
+ if (!globalRl.success) return rateLimited(res, globalRl, 'Anatomy is at capacity. Try again shortly.');
+
+ const user = await getSessionUser(req).catch(() => null);
+ const stream = body.stream === true ? openStream(res) : null;
+ try {
+ const payload = await generateDesign({
+ prompt,
+ user,
+ onEvent: ({ type, ...data }) => stream?.send(type, data),
+ });
+ if (stream) {
+ stream.send('done', payload);
+ stream.close();
+ return;
+ }
+ return json(res, 201, payload);
+ } catch (err) {
+ return sendError(res, err, stream);
+ }
+}
+
+async function handlePublish(req, res, body) {
+ const rl = await limits.anatomyPublishIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'Publishing too fast. Give it a moment.');
+ const user = await getSessionUser(req).catch(() => null);
+ try {
+ const payload = await publishDesign({ spec: body.spec, prompt: body.prompt, user });
+ return json(res, 201, payload);
+ } catch (err) {
+ return sendError(res, err, null);
+ }
+}