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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(gestures): ship /gestures, and wire the override map that never worked
nirholas3d80e84a84fc
diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.jsindex b81dce697..946bc6a1a 100644--- a/api/agents/_id/_sub.js+++ b/api/agents/_id/_sub.js@@ -15,6 +15,10 @@ import { readEmbedPolicy, validateEmbedPolicy } from '../../_lib/embed-policy.jsimport { resolveAvatarUrl } from '../../_lib/avatars.js';import { buildAgentRegistrationMetadata } from '../../_lib/three-brand.js';import { publicUrl as r2PublicUrl } from '../../_lib/r2.js';+// The one source of truth for the gesture slot vocabulary. Dependency-free, so+// importing the runtime module here keeps the API and the browser in agreement+// instead of restating the list.+import { SLOTS } from '../../../src/runtime/animation-slots.js';async function resolveAuth(req) {const session = await getSessionUser(req);@@ -168,9 +172,28 @@ const animationGraphSchema = z}).strict();+// Gesture slot overrides: { slot: clipName }, persisted at meta.edits.animations,+// which is where src/agent-avatar.js reads an agent's per-slot bindings from.+// Keys are restricted to the fixed vocabulary (src/runtime/animation-slots.js) so+// a typo cannot create a slot nothing will ever play; values are clip names,+// deliberately not restricted to the platform manifest so an agent can point a+// slot at one of its own uploaded clips. An empty object clears every override.+const animationSlotsSchema = z+ .record(+ z.enum(/** @type {[string, ...string[]]} */ (SLOTS)),+ z+ .string()+ .trim()+ .min(1)+ .max(60)+ .regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/, 'clip name must be alphanumeric with - or _'),+ )+ .refine((map) => Object.keys(map).length <= SLOTS.length, 'too many slot overrides');+const animationsBodySchema = z.object({animations: z.array(animationEntrySchema).max(30),animationGraph: animationGraphSchema.optional(),+ animationSlots: animationSlotsSchema.optional(),});export const handleAnimations = wrap(async (req, res, id) => {@@ -202,33 +225,47 @@ export const handleAnimations = wrap(async (req, res, id) => {// Only touch meta.animationGraph when the request actually carries the// field, so saving the clip-array on its own doesn't clobber an existing- // graph. `null` is a valid explicit "remove the graph" signal.- const hasGraph = Object.prototype.hasOwnProperty.call(rawBody || {}, 'animationGraph');- if (hasGraph) {+ // graph. `null` is a valid explicit "remove the graph" signal. Same rule for+ // the slot overrides at meta.edits.animations: absent means "leave alone",+ // `{}` means "clear them".+ const has = (key) => Object.prototype.hasOwnProperty.call(rawBody || {}, key);+ await sql`+ UPDATE agent_identities+ SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{animations}', ${JSON.stringify(parsed.animations)}::jsonb, true)+ WHERE id = ${id}+ `;+ if (has('animationGraph')) {await sql`UPDATE agent_identities- SET meta = jsonb_set(- jsonb_set(COALESCE(meta, '{}'::jsonb), '{animations}', ${JSON.stringify(parsed.animations)}::jsonb, true),- '{animationGraph}',- ${parsed.animationGraph ? JSON.stringify(parsed.animationGraph) : 'null'}::jsonb,- true- )+ SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{animationGraph}',+ ${parsed.animationGraph ? JSON.stringify(parsed.animationGraph) : 'null'}::jsonb, true)WHERE id = ${id}`;- } else {+ }+ if (has('animationSlots')) {+ // jsonb_set cannot create the intermediate {edits} object, so seed it first+ // for agents that have never carried one.await sql`UPDATE agent_identities- SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{animations}', ${JSON.stringify(parsed.animations)}::jsonb, true)+ SET meta = jsonb_set(+ CASE WHEN COALESCE(meta, '{}'::jsonb) ? 'edits'+ THEN COALESCE(meta, '{}'::jsonb)+ ELSE jsonb_set(COALESCE(meta, '{}'::jsonb), '{edits}', '{}'::jsonb, true)+ END,+ '{edits,animations}', ${JSON.stringify(parsed.animationSlots ?? {})}::jsonb, true)WHERE id = ${id}`;}- // Read back the persisted graph so the response reflects what's actually stored.- const [row] =- await sql`SELECT meta->'animationGraph' AS graph FROM agent_identities WHERE id = ${id}`;+ // Read back what is actually stored so the response cannot drift from the row.+ const [row] = await sql`+ SELECT meta->'animationGraph' AS graph, meta->'edits'->'animations' AS slots+ FROM agent_identities WHERE id = ${id}+ `;return json(res, 200, {animations: parsed.animations,animationGraph: row?.graph ?? null,+ animationSlots: row?.slots ?? null,});});@@ -349,6 +386,14 @@ export const handleManifest = wrap(async (req, res, id) => {tone_tags: row.persona_tone_tags || [],extracted_at: row.persona_extracted_at || null,},+ // Gesture slot overrides, so an embed plays this agent's own body language+ // rather than the platform defaults. Only present when the owner set some+ // (PUT /api/agents/:id/animations with animationSlots); consumers fall back+ // to DEFAULT_ANIMATION_MAP when it is absent.+ animationSlots:+ row.meta?.edits?.animations && Object.keys(row.meta.edits.animations).length+ ? row.meta.edits.animations+ : undefined,// Live signal — funded + active on the Money Pulse via the activation grant.activated,activatedAt,diff --git a/docs/animations.md b/docs/animations.mdindex cedf1cb3e..0d3e2fcc1 100644--- a/docs/animations.md+++ b/docs/animations.md@@ -55,6 +55,8 @@ Retarget sources are deliberately never committed: everything in `animation-sourSlots are the fixed vocabulary the agent avatar uses to express emotion and gesture. They resolve to clip names at runtime. Defined in `src/runtime/animation-slots.js`.+Every slot below is previewable on a live avatar at [three.ws/gestures](https://three.ws/gestures), which also builds the override JSON for you.+| Slot | Default clip | Notes ||---|---|---|| `idle` | `idle` | Always playing |@@ -85,6 +87,13 @@ Agents can override individual slots via `meta.edits.animations`:An override wins over the default; any clip name in the manifest is valid. Unmapped slot names fall through to a clip of the same name, so an agent can point a slot at a clip the platform never wired.+Two ways to write the map, both landing at `meta.edits.animations`:++- **Agent editor, Body tab, Gesture slots.** One row per slot; `Platform default` inherits the platform clip.+- **`PUT /api/agents/:id/animations`** with an `animationSlots` object (owner-authenticated). Keys are validated against `SLOTS`, so a typo is a 400 rather than a gesture that silently never plays; `{}` clears every override. The agent's public manifest then carries the map as `animationSlots`, which is how an `<agent-3d>` embed picks it up.++Both ends of that path were dead until 2026-07-30: nothing could write the map (no field, no UI) and nothing applied it (`setAnimationMap` had no callers), so the override documented here had no effect anywhere. `tests/agent-animation-slots.test.js` pins the write contract and asserts each consumer still applies it.+## Skill animation hintsA skill declares `animationHint` (see `src/agent-skills.js` and its siblings) and the avatar plays the matching slot when that skill starts. `resolveHint()` maps a hint to a slot: exact slot names pass through, the namespaced `gesture-*` family aliases onto one, and an unknown hint in a known family falls back to that family so a new `gesture-something` still animates.@@ -131,6 +140,8 @@ Resolved (see `public/animations/registry.json` → `resolved_issues`): the `fid## Related+- [Agent Gestures](/gestures): the live slot-and-hint reference, with an override builder+- [Give your agent body language](/tutorials/animate-your-agent): the walkthrough- [3D asset pipeline](/docs/3d-asset-pipeline): the full generate, rig, animate, export chain- [Animation Studio](/docs/animation-studio): author and preview clips in the browser- [3D Viewer](/docs/viewer): how clips play back in the viewer and embedsdiff --git a/docs/tutorials/animate-your-agent.md b/docs/tutorials/animate-your-agent.mdindex 1d9dd8ac0..1d3be649e 100644--- a/docs/tutorials/animate-your-agent.md+++ b/docs/tutorials/animate-your-agent.md@@ -82,22 +82,28 @@ On [three.ws/gestures](https://three.ws/gestures), click the slot you want to ch}```-Paste the inner `animations` object into your agent's `meta.edits.animations` in the agent editor (**Edit → Advanced → meta**). Add as many slots as you like:+To apply it, open your agent's editor, go to **Body → Gesture slots**, and pick a clip for the slot. There is one row per slot, `Platform default` inherits the platform clip, and **Save gestures** writes the map. Reload the agent page and the gesture is yours.-```json-{- "edits": {- "animations": {+If you would rather do it from code, the same thing over the API:++```bash+curl -X PUT https://three.ws/api/agents/$AGENT_ID/animations \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{+ "animations": [],+ "animationSlots": {"dance": "av-offabean-dance","celebrate": "av-cheering","think": "av-smoking","inspect": "av-spy"}- }-}+ }'```-Save, reload the agent page, and trigger the gesture. Anything not listed keeps the platform default, so an override map is only as long as the changes you want.+Anything not listed keeps the platform default, so a map is only as long as the changes you want. `"animationSlots": {}` clears every override. The map is stored on the agent at `meta.edits.animations` and published on its public manifest as `animationSlots`, so an `<agent-3d>` embed of that agent plays its body language too.++Two things the endpoint will reject rather than silently accept: a slot name outside the vocabulary (a typo would create a gesture nothing ever plays) and a clip name that is not a plain name. `animations` is the agent's clip list and is required by that endpoint; send `[]` only if you do not use it, since the field replaces what is there.Any of the 112 clip names in [`/animations/manifest.json`](https://three.ws/animations/manifest.json) is valid. Browse them with previews at [three.ws/animations](https://three.ws/animations).diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex dcf598169..b95934349 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -1274,6 +1274,16 @@<div id="anim-graph-rows" class="anim-graph-rows"></div><span class="form-status" id="anim-graph-status" role="status" aria-live="polite"></span>+ <div class="outfit-header">+ <h2 class="outfit-title" data-i18n="agent_edit.gesture_slots">Gesture slots</h2>+ <button type="button" class="btn-reset-all" id="anim-slots-save" disabled data-i18n="agent_edit.save_gestures">Save gestures</button>+ </div>+ <p style="font-size:0.764rem;color:rgba(255,255,255,0.4);margin:0 0 0.75rem" data-i18n="agent_edit.slots_are_the_gestures_your_agent_plays">+ Slots are the gestures your agent plays on its own: it nods when a model loads, looks down while it reads data, celebrates a win. Re-point any of them at a different clip. <a href="/gestures" target="_blank" rel="noopener">Preview every gesture</a>.+ </p>+ <div id="anim-slots-rows" class="anim-graph-rows"></div>+ <span class="form-status" id="anim-slots-status" role="status" aria-live="polite"></span>+<div class="outfit-header"><h2 class="outfit-title" data-i18n="agent_edit.mood_embodiment">Mood & embodiment</h2></div>diff --git a/pages/gestures.html b/pages/gestures.htmlnew file mode 100644index 000000000..1683d6fcb--- /dev/null+++ b/pages/gestures.html@@ -0,0 +1,209 @@+<!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 http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Agent Gestures · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Every gesture a three.ws agent can play: the slot vocabulary, the clip each slot resolves to, the skills that trigger it, and a builder for overriding any slot on your own agent." />+ <meta name="theme-color" content="#000000" />+ <link rel="canonical" href="https://three.ws/gestures" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Agent Gestures · three.ws" />+ <meta property="og:description" content="The agent gesture vocabulary: 19 slots, the clip each plays, the skills that trigger them, and a live override builder." />+ <meta property="og:url" content="https://three.ws/gestures" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Agent+Gestures&d=Every+gesture+a+three.ws+agent+can+play%2C+previewed+live%2C+with+the+skills+that+trigger+it.&p=%2Fgestures" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Agent Gestures · three.ws" />+ <meta name="twitter:description" content="19 gesture slots, previewed live, with the skills that trigger each one." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Agent+Gestures&d=Every+gesture+a+three.ws+agent+can+play%2C+previewed+live%2C+with+the+skills+that+trigger+it.&p=%2Fgestures" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <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="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/gestures.css" />++ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Agent Gestures","description":"The three.ws agent gesture vocabulary: every animation slot, the clip it resolves to, the skills that trigger it, and how to override one.","url":"https://three.ws/gestures","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:locale" content="en_US">+ <meta property="og:image:alt" content="Agent Gestures on three.ws">+ </head>+ <body class="gv-page">+ <header>+ <div id="nav-container"></div>+ </header>+ <script src="/nav.js"></script>++ <main>+ <section class="gv-hero">+ <div class="gv-hero-chip">+ <span class="gv-hero-dot" aria-hidden="true"></span>+ <span>Agent body language</span>+ </div>+ <h1>Agent gestures</h1>+ <p class="gv-hero-lede">+ An agent does not pick animation files. It names a <strong>slot</strong>, and the+ platform resolves that slot to a real clip. Skills name a slot indirectly, through a+ hint. This page is the whole vocabulary: what each slot plays, which skills trigger+ it, and how to point a slot at any other clip in the library.+ </p>+ <div class="gv-hero-actions">+ <a class="gv-btn gv-btn--primary" href="/animations">Browse every clip</a>+ <a class="gv-btn gv-btn--secondary" href="/pose">Animation Studio</a>+ <a class="gv-btn gv-btn--ghost" href="/docs/animations">Developer reference</a>+ </div>+ <dl class="gv-stats" data-role="stats" aria-live="polite">+ <div class="gv-stat"><dt>Slots</dt><dd data-role="stat-slots">—</dd></div>+ <div class="gv-stat"><dt>Clips in library</dt><dd data-role="stat-clips">—</dd></div>+ <div class="gv-stat"><dt>Skill hints</dt><dd data-role="stat-hints">—</dd></div>+ <div class="gv-stat"><dt>Skills wired</dt><dd data-role="stat-skills">—</dd></div>+ </dl>+ </section>++ <section class="gv-body">+ <!-- Left rail: the live stage. Sticky on desktop so a card click is+ always visible without scrolling back up. -->+ <aside class="gv-stage-col">+ <div class="gv-stage-card">+ <div class="gv-stage" data-role="stage">+ <div class="gv-stage-empty" data-role="stage-empty">+ <div class="gv-stage-empty-icon" aria-hidden="true">🎬</div>+ <p class="gv-stage-empty-title">Pick a gesture</p>+ <p class="gv-stage-empty-body">+ Choose any slot to play it on a live avatar. Nothing 3D loads until you do.+ </p>+ </div>+ <div class="gv-stage-loading" data-role="stage-loading" hidden>+ <div class="gv-spinner" aria-hidden="true"></div>+ <p>Retargeting the clip…</p>+ </div>+ <div class="gv-stage-error" data-role="stage-error" hidden>+ <p class="gv-stage-error-title" data-role="stage-error-title">That clip did not fit the preview avatar.</p>+ <p class="gv-stage-error-body">+ The clip is fine: the shared preview rig could not bind it. Every clip is+ still previewable in the <a href="/animations">gallery</a>.+ </p>+ <button type="button" class="gv-btn gv-btn--secondary" data-role="stage-retry">Try again</button>+ </div>+ </div>+ <div class="gv-stage-meta">+ <div class="gv-stage-titles">+ <p class="gv-stage-slot" data-role="stage-slot">No gesture selected</p>+ <p class="gv-stage-clip" data-role="stage-clip"> </p>+ </div>+ <div class="gv-stage-controls">+ <button type="button" class="gv-icon-btn" data-role="stage-replay" title="Replay" aria-label="Replay" disabled>↻</button>+ <button type="button" class="gv-icon-btn" data-role="stage-pause" title="Pause" aria-label="Pause" disabled>❙❙</button>+ </div>+ </div>+ <p class="gv-sr-status" data-role="stage-status" role="status" aria-live="polite"></p>+ </div>++ <!-- Override builder. The output is exactly the shape an agent's+ meta.edits.animations takes, so it is copy-paste usable. -->+ <div class="gv-override" data-role="override" hidden>+ <h2 class="gv-override-title">Override this slot</h2>+ <p class="gv-override-lede">+ Point <code data-role="override-slot">slot</code> at any clip in the library. Paste+ the result into your agent's <code>meta.edits.animations</code>.+ </p>+ <label class="gv-field">+ <span class="gv-field-label">Clip</span>+ <select class="gv-select" data-role="override-select"></select>+ </label>+ <pre class="gv-code" data-role="override-code"><code></code></pre>+ <div class="gv-override-actions">+ <button type="button" class="gv-btn gv-btn--primary" data-role="override-copy">Copy JSON</button>+ <button type="button" class="gv-btn gv-btn--ghost" data-role="override-reset">Reset to default</button>+ </div>+ </div>+ </aside>++ <!-- Right rail: the vocabulary. -->+ <div class="gv-main-col">+ <div class="gv-section-head">+ <h2 id="slots">The slot vocabulary</h2>+ <p>+ Fixed names an agent can override. A slot with no override resolves to the clip+ shown on its card.+ </p>+ </div>++ <div class="gv-grid" data-role="grid" role="list" aria-busy="true">+ <div class="gv-card gv-card--skeleton" aria-hidden="true"></div>+ <div class="gv-card gv-card--skeleton" aria-hidden="true"></div>+ <div class="gv-card gv-card--skeleton" aria-hidden="true"></div>+ <div class="gv-card gv-card--skeleton" aria-hidden="true"></div>+ <div class="gv-card gv-card--skeleton" aria-hidden="true"></div>+ <div class="gv-card gv-card--skeleton" aria-hidden="true"></div>+ </div>++ <div class="gv-error" data-role="grid-error" hidden>+ <p class="gv-error-title">The clip library did not load.</p>+ <p class="gv-error-body" data-role="grid-error-detail"></p>+ <button type="button" class="gv-btn gv-btn--secondary" data-role="grid-retry">Retry</button>+ </div>++ <p class="gv-grid-hint">+ <kbd>↑</kbd> <kbd>↓</kbd> <kbd>←</kbd> <kbd>→</kbd> move · <kbd>Enter</kbd> play ·+ <kbd>Esc</kbd> stop+ </p>++ <div class="gv-section-head">+ <h2 id="hints">What triggers a gesture</h2>+ <p>+ A skill declares a hint when it starts. The hint resolves to a slot, the slot+ resolves to a clip, and the avatar plays it. Every row below is generated from+ the shipped skill definitions.+ </p>+ </div>++ <div class="gv-hints" data-role="hints">+ <div class="gv-hints-loading">Loading the skill map…</div>+ </div>++ <div class="gv-section-head">+ <h2 id="layers">Player gestures on /walk</h2>+ <p>+ The walk state machine keeps a second, player-driven gesture library with a layer+ per gesture: <code>upper</code> gestures overlay locomotion, so an avatar waves or+ shrugs while it keeps walking; <code>full</code> gestures take the whole body and+ suppress movement until they end.+ </p>+ </div>+ <div class="gv-layers" data-role="layers"></div>++ <div class="gv-footnote">+ <p>+ Slots, hints and clips are held together mechanically:+ <code>tests/animation-slots.test.js</code> scans every hint declared under+ <code>src/</code> and fails the build if one resolves to no slot or to a clip that+ is not baked in <code>public/animations/manifest.json</code>. The full developer+ reference is <a href="/docs/animations">docs/animations</a>, and the walkthrough is+ <a href="/tutorials/animate-your-agent">Animate your agent</a>.+ </p>+ </div>+ </div>+ </section>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js" defer></script>++ <script type="module" src="/src/gestures-page.js"></script>+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/public/agent-hints.json b/public/agent-hints.jsonnew file mode 100644index 000000000..51222adeb--- /dev/null+++ b/public/agent-hints.json@@ -0,0 +1,163 @@+{+ "hints": [+ {+ "hint": "gesture",+ "slot": "point",+ "clip": "point",+ "skills": [+ "agent-payments-accept-evm",+ "agent-payments-accept-v2",+ "agent-payments-distribute",+ "agent-payments-register",+ "agent-payments-update-buyback",+ "agent-payments-withdraw",+ "blink-execute",+ "help",+ "pumpfun-accept-payment",+ "pumpfun-amm-buy",+ "pumpfun-amm-sell",+ "pumpfun-auto-snipe",+ "pumpfun-buy",+ "pumpfun-copy-trade",+ "pumpfun-copy-trade-live",+ "pumpfun-self-pay",+ "pumpfun-self-swap",+ "pumpfun-sell",+ "pumpfun.vanityMint"+ ]+ },+ {+ "hint": "inspect",+ "slot": "inspect",+ "clip": "lookdown",+ "skills": [+ "agent-payments-balances",+ "agent-payments-check-whitelist",+ "agent-payments-verify-evm",+ "jupiter-quote",+ "jupiter-tokens",+ "kol.leaderboard",+ "kol.walletPnl",+ "pumpfun-invoice-pda",+ "pumpfun-research-and-buy",+ "pumpfun-status",+ "pumpfun-verify-payment",+ "pumpfun.channelFeed",+ "pumpfun.quoteSwap",+ "pyth-price",+ "social.cashtagSentiment",+ "social.xPostImpact",+ "solana.resolveSns",+ "solana.reverseSns",+ "validate-model"+ ]+ },+ {+ "hint": "curiosity",+ "slot": "curiosity",+ "clip": "av-spy",+ "skills": [+ "blink-parse",+ "nft-portfolio",+ "pumpfun-first-claims",+ "pumpfun-recent-claims",+ "pumpfun-watch-claims",+ "pumpfun-watch-start",+ "pumpfun.watchWhales"+ ]+ },+ {+ "hint": "celebrate",+ "slot": "celebrate",+ "clip": "celebrate",+ "skills": [+ "jupiter-swap",+ "pumpfun-claim-fees",+ "pumpfun-create",+ "pumpfun-launch-from-agent",+ "pumpfun-self-launch",+ "pumpfun-self-launch-from-identity"+ ]+ },+ {+ "hint": "think",+ "slot": "think",+ "clip": "think",+ "skills": [+ "aixbt-intel",+ "analyze-sentiment",+ "pumpfun-list-claims",+ "pumpfun-token-intel",+ "think",+ "wallet-activity"+ ]+ },+ {+ "hint": "present",+ "slot": "present",+ "clip": "av-brag-claps",+ "skills": [+ "aixbt-scan",+ "pay-agent",+ "present-model"+ ]+ },+ {+ "hint": "concern",+ "slot": "concern",+ "clip": "defeated",+ "skills": [+ "pumpfun-rug-exit-watch"+ ]+ },+ {+ "hint": "gesture-magic",+ "slot": "conjure",+ "clip": "av-conductor",+ "skills": [+ "scene-create-object"+ ]+ },+ {+ "hint": "gesture-manipulate",+ "slot": "manipulate",+ "clip": "av-push-block",+ "skills": [+ "scene-update-object"+ ]+ },+ {+ "hint": "nod",+ "slot": "nod",+ "clip": "nod",+ "skills": [+ "remember"+ ]+ },+ {+ "hint": "patience",+ "slot": "patience",+ "clip": "av-waiting",+ "skills": [+ "pumpfun-watch-stop"+ ]+ },+ {+ "hint": "sign",+ "slot": "sign",+ "clip": "xbot-agree",+ "skills": [+ "sign-action"+ ]+ },+ {+ "hint": "wave",+ "slot": "wave",+ "clip": "wave",+ "skills": [+ "greet"+ ]+ }+ ],+ "total_skills": 67+}diff --git a/public/gestures.css b/public/gestures.cssnew file mode 100644index 000000000..72a422783--- /dev/null+++ b/public/gestures.css@@ -0,0 +1,709 @@+/* /gestures: the agent gesture vocabulary.+ *+ * Page-scoped tokens layer over /style.css so the page follows the site theme+ * in both directions (the theme boot script stamps data-theme on <html>).+ */++:root {+ --gv-radius: 14px;+ --gv-border: rgba(255, 255, 255, 0.08);+ --gv-border-strong: rgba(255, 255, 255, 0.2);+ --gv-surface: rgba(255, 255, 255, 0.03);+ --gv-surface-2: rgba(255, 255, 255, 0.06);+ --gv-surface-3: rgba(255, 255, 255, 0.1);+ --gv-accent: #7dd3fc;+ --gv-accent-ink: #04141f;+ --gv-muted: rgba(255, 255, 255, 0.6);+}+:root[data-theme='light'] {+ --gv-border: rgba(0, 0, 0, 0.1);+ --gv-border-strong: rgba(0, 0, 0, 0.24);+ --gv-surface: rgba(0, 0, 0, 0.03);+ --gv-surface-2: rgba(0, 0, 0, 0.05);+ --gv-surface-3: rgba(0, 0, 0, 0.09);+ --gv-accent: #0369a1;+ --gv-accent-ink: #f8fbff;+ --gv-muted: rgba(0, 0, 0, 0.58);+}++.gv-page {+ min-height: 100vh;+ background: var(--bg, #000);+ color: var(--text, #fafafa);+ font-family: 'Inter', system-ui, -apple-system, sans-serif;+ -webkit-font-smoothing: antialiased;+}++.gv-page main {+ max-width: 1360px;+ margin: 0 auto;+ padding: 0 clamp(16px, 4vw, 40px) 96px;+}++/* ── Hero ──────────────────────────────────────────────────────────────── */++.gv-hero {+ padding: clamp(40px, 7vw, 88px) 0 clamp(24px, 3vw, 40px);+ max-width: 780px;+}++.gv-hero-chip {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 5px 12px 5px 10px;+ border: 1px solid var(--gv-border);+ border-radius: 999px;+ background: var(--gv-surface);+ font-size: 12px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--gv-muted);+}++.gv-hero-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--gv-accent);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--gv-accent) 22%, transparent);+}++.gv-hero h1 {+ margin: 20px 0 14px;+ font-size: clamp(34px, 6vw, 58px);+ line-height: 1.04;+ letter-spacing: -0.03em;+ font-weight: 680;+}++.gv-hero-lede {+ margin: 0;+ font-size: clamp(15px, 1.6vw, 18px);+ line-height: 1.62;+ color: var(--gv-muted);+}+.gv-hero-lede strong {+ color: var(--text, #fafafa);+ font-weight: 600;+}++.gv-hero-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 10px;+ margin: 26px 0 0;+}++.gv-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ padding: 10px 18px;+ border: 1px solid var(--gv-border-strong);+ border-radius: 10px;+ background: var(--gv-surface-2);+ color: inherit;+ font: inherit;+ font-size: 14px;+ font-weight: 550;+ text-decoration: none;+ cursor: pointer;+ transition: transform 0.16s ease, background 0.16s ease, border-color 0.16s ease, opacity 0.16s ease;+}+.gv-btn:hover {+ background: var(--gv-surface-3);+ transform: translateY(-1px);+}+.gv-btn:active {+ transform: translateY(0);+}+.gv-btn:focus-visible {+ outline: 2px solid var(--gv-accent);+ outline-offset: 2px;+}+.gv-btn[disabled] {+ opacity: 0.45;+ cursor: not-allowed;+ transform: none;+}+.gv-btn--primary {+ background: var(--gv-accent);+ border-color: transparent;+ color: var(--gv-accent-ink);+}+.gv-btn--primary:hover {+ background: color-mix(in srgb, var(--gv-accent) 86%, white);+}+.gv-btn--ghost {+ background: transparent;+ border-color: var(--gv-border);+}++.gv-stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));+ gap: 10px;+ margin: 30px 0 0;+ padding: 0;+}+.gv-stat {+ padding: 12px 14px;+ border: 1px solid var(--gv-border);+ border-radius: 12px;+ background: var(--gv-surface);+}+.gv-stat dt {+ margin: 0 0 4px;+ font-size: 11px;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--gv-muted);+}+.gv-stat dd {+ margin: 0;+ font-size: 22px;+ font-weight: 640;+ font-variant-numeric: tabular-nums;+ letter-spacing: -0.02em;+}++/* ── Two-column body ───────────────────────────────────────────────────── */++.gv-body {+ display: grid;+ grid-template-columns: minmax(300px, 380px) minmax(0, 1fr);+ gap: clamp(20px, 3vw, 40px);+ align-items: start;+}++.gv-stage-col {+ position: sticky;+ top: 84px;+ display: flex;+ flex-direction: column;+ gap: 14px;+}++.gv-stage-card,+.gv-override {+ border: 1px solid var(--gv-border);+ border-radius: var(--gv-radius);+ background: var(--gv-surface);+ overflow: hidden;+}++.gv-stage {+ position: relative;+ aspect-ratio: 3 / 4;+ background:+ radial-gradient(120% 90% at 50% 8%, var(--gv-surface-2), transparent 70%),+ var(--gv-surface);+ display: grid;+ place-items: center;+}+.gv-stage canvas {+ display: block;+ width: 100%;+ height: 100%;+}++.gv-stage-empty,+.gv-stage-loading,+.gv-stage-error {+ position: absolute;+ inset: 0;+ display: grid;+ place-content: center;+ justify-items: center;+ gap: 8px;+ padding: 28px;+ text-align: center;+}+.gv-stage-empty-icon {+ font-size: 30px;+ opacity: 0.8;+}+.gv-stage-empty-title,+.gv-stage-error-title {+ margin: 0;+ font-size: 15px;+ font-weight: 600;+}+.gv-stage-empty-body,+.gv-stage-error-body {+ margin: 0;+ max-width: 34ch;+ font-size: 13px;+ line-height: 1.55;+ color: var(--gv-muted);+}+.gv-stage-error-body a,+.gv-footnote a,+.gv-hints-skills a {+ color: var(--gv-accent);+}++.gv-spinner {+ width: 22px;+ height: 22px;+ border: 2px solid var(--gv-border-strong);+ border-top-color: var(--gv-accent);+ border-radius: 50%;+ animation: gv-spin 0.7s linear infinite;+}+@keyframes gv-spin {+ to {+ transform: rotate(360deg);+ }+}+.gv-stage-loading p {+ margin: 0;+ font-size: 13px;+ color: var(--gv-muted);+}++.gv-stage-meta {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 12px 14px;+ border-top: 1px solid var(--gv-border);+}+.gv-stage-titles {+ min-width: 0;+}+.gv-stage-slot {+ margin: 0;+ font-size: 14px;+ font-weight: 620;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.gv-stage-clip {+ margin: 2px 0 0;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+ color: var(--gv-muted);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.gv-stage-controls {+ display: flex;+ gap: 6px;+ flex: none;+}+.gv-icon-btn {+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ border: 1px solid var(--gv-border);+ border-radius: 9px;+ background: var(--gv-surface-2);+ color: inherit;+ font-size: 12px;+ cursor: pointer;+ transition: background 0.16s ease, transform 0.16s ease, opacity 0.16s ease;+}+.gv-icon-btn:hover:not([disabled]) {+ background: var(--gv-surface-3);+ transform: translateY(-1px);+}+.gv-icon-btn:focus-visible {+ outline: 2px solid var(--gv-accent);+ outline-offset: 2px;+}+.gv-icon-btn[disabled] {+ opacity: 0.4;+ cursor: not-allowed;+}+.gv-icon-btn[aria-pressed='true'] {+ background: var(--gv-accent);+ color: var(--gv-accent-ink);+ border-color: transparent;+}++.gv-sr-status {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip-path: inset(50%);+ white-space: nowrap;+}++/* ── Override builder ──────────────────────────────────────────────────── */++.gv-override {+ padding: 16px;+}+.gv-override-title {+ margin: 0 0 6px;+ font-size: 15px;+ font-weight: 620;+}+.gv-override-lede {+ margin: 0 0 14px;+ font-size: 13px;+ line-height: 1.55;+ color: var(--gv-muted);+}+.gv-field {+ display: block;+ margin-bottom: 12px;+}+.gv-field-label {+ display: block;+ margin-bottom: 5px;+ font-size: 11px;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--gv-muted);+}+.gv-select {+ width: 100%;+ padding: 9px 10px;+ border: 1px solid var(--gv-border-strong);+ border-radius: 9px;+ background: var(--gv-surface-2);+ color: inherit;+ font: inherit;+ font-size: 13px;+}+.gv-select:focus-visible {+ outline: 2px solid var(--gv-accent);+ outline-offset: 1px;+}++.gv-code {+ margin: 0 0 12px;+ padding: 12px;+ border: 1px solid var(--gv-border);+ border-radius: 10px;+ background: var(--gv-surface-2);+ overflow-x: auto;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+ line-height: 1.6;+}+.gv-override-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}++/* ── Slot grid ─────────────────────────────────────────────────────────── */++.gv-section-head {+ margin: 26px 0 14px;+}+.gv-section-head:first-child {+ margin-top: 0;+}+.gv-section-head h2 {+ margin: 0 0 6px;+ font-size: clamp(18px, 2.2vw, 22px);+ font-weight: 640;+ letter-spacing: -0.02em;+ scroll-margin-top: 90px;+}+.gv-section-head p {+ margin: 0;+ max-width: 68ch;+ font-size: 14px;+ line-height: 1.6;+ color: var(--gv-muted);+}++.gv-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 12px;+}++.gv-card {+ position: relative;+ display: flex;+ flex-direction: column;+ padding: 0;+ border: 1px solid var(--gv-border);+ border-radius: 12px;+ background: var(--gv-surface);+ color: inherit;+ text-align: left;+ cursor: pointer;+ overflow: hidden;+ transition: transform 0.16s ease, border-color 0.16s ease, background 0.16s ease;+}+.gv-card:hover {+ transform: translateY(-2px);+ border-color: var(--gv-border-strong);+ background: var(--gv-surface-2);+}+.gv-card:focus-visible {+ outline: 2px solid var(--gv-accent);+ outline-offset: 2px;+}+.gv-card[aria-current='true'] {+ border-color: var(--gv-accent);+ background: color-mix(in srgb, var(--gv-accent) 10%, transparent);+}+.gv-card--skeleton {+ aspect-ratio: 3 / 4;+ cursor: default;+ background: linear-gradient(100deg, var(--gv-surface) 30%, var(--gv-surface-2) 50%, var(--gv-surface) 70%);+ background-size: 220% 100%;+ animation: gv-shimmer 1.3s linear infinite;+}+@keyframes gv-shimmer {+ to {+ background-position: -220% 0;+ }+}++.gv-card-thumb {+ position: relative;+ aspect-ratio: 1 / 1;+ background: var(--gv-surface-2);+ overflow: hidden;+}+.gv-card-thumb img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ transition: transform 0.25s ease;+}+.gv-card:hover .gv-card-thumb img {+ transform: scale(1.04);+}+.gv-card-thumb-fallback {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ font-size: 26px;+}++.gv-card-body {+ padding: 10px 11px 12px;+ display: flex;+ flex-direction: column;+ gap: 3px;+}+.gv-card-slot {+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 13px;+ font-weight: 600;+}+.gv-card-clip {+ font-size: 11.5px;+ color: var(--gv-muted);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.gv-badge {+ position: absolute;+ top: 8px;+ right: 8px;+ padding: 3px 7px;+ border-radius: 999px;+ background: color-mix(in srgb, var(--gv-accent) 88%, transparent);+ color: var(--gv-accent-ink);+ font-size: 10px;+ font-weight: 640;+ letter-spacing: 0.03em;+ text-transform: uppercase;+}+.gv-badge--warn {+ background: #f59e0b;+ color: #1a1206;+}++.gv-grid-hint {+ margin: 12px 0 0;+ font-size: 12px;+ color: var(--gv-muted);+}+.gv-grid-hint kbd {+ padding: 1px 5px;+ border: 1px solid var(--gv-border-strong);+ border-radius: 5px;+ background: var(--gv-surface-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+}++.gv-error {+ padding: 18px;+ border: 1px solid var(--gv-border-strong);+ border-radius: 12px;+ background: var(--gv-surface);+}+.gv-error-title {+ margin: 0 0 6px;+ font-weight: 620;+}+.gv-error-body {+ margin: 0 0 12px;+ font-size: 13px;+ color: var(--gv-muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ word-break: break-word;+}++/* ── Hints + layers tables ─────────────────────────────────────────────── */++.gv-hints,+.gv-layers {+ border: 1px solid var(--gv-border);+ border-radius: 12px;+ overflow: hidden;+}+.gv-hints-loading {+ padding: 16px;+ font-size: 13px;+ color: var(--gv-muted);+}++.gv-row {+ display: grid;+ grid-template-columns: minmax(120px, 1.1fr) minmax(90px, 0.9fr) minmax(100px, 1fr) auto;+ gap: 10px;+ align-items: center;+ padding: 11px 14px;+ border-top: 1px solid var(--gv-border);+ font-size: 13px;+}+.gv-row:first-child {+ border-top: 0;+}+.gv-row--head {+ background: var(--gv-surface-2);+ font-size: 11px;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--gv-muted);+}+.gv-mono {+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12.5px;+ overflow-wrap: anywhere;+}+.gv-arrow {+ color: var(--gv-muted);+}+.gv-count {+ justify-self: end;+ padding: 2px 8px;+ border: 1px solid var(--gv-border);+ border-radius: 999px;+ background: var(--gv-surface-2);+ font-size: 11.5px;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++.gv-hints details {+ border-top: 1px solid var(--gv-border);+}+.gv-hints details > summary {+ padding: 9px 14px;+ font-size: 12px;+ color: var(--gv-muted);+ cursor: pointer;+ list-style: none;+}+.gv-hints details > summary::-webkit-details-marker {+ display: none;+}+.gv-hints details > summary:hover {+ color: var(--text, #fafafa);+}+.gv-hints details > summary:focus-visible {+ outline: 2px solid var(--gv-accent);+ outline-offset: -2px;+}+.gv-hints-skills {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ padding: 0 14px 14px;+}+.gv-hints-skills code {+ padding: 2px 7px;+ border: 1px solid var(--gv-border);+ border-radius: 7px;+ background: var(--gv-surface-2);+ font-size: 11.5px;+}++.gv-footnote {+ margin-top: 26px;+ padding: 16px;+ border: 1px dashed var(--gv-border-strong);+ border-radius: 12px;+}+.gv-footnote p {+ margin: 0;+ font-size: 13px;+ line-height: 1.65;+ color: var(--gv-muted);+}+.gv-footnote code,+.gv-section-head code,+.gv-override-lede code {+ padding: 1px 5px;+ border-radius: 5px;+ background: var(--gv-surface-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+}++/* ── Responsive ────────────────────────────────────────────────────────── */++@media (max-width: 900px) {+ .gv-body {+ grid-template-columns: minmax(0, 1fr);+ }+ .gv-stage-col {+ position: static;+ order: 2;+ }+ .gv-main-col {+ order: 1;+ }+ .gv-stage {+ aspect-ratio: 4 / 3;+ }+ .gv-row {+ grid-template-columns: minmax(0, 1fr) auto;+ }+ .gv-row .gv-arrow {+ display: none;+ }+}++@media (max-width: 420px) {+ .gv-grid {+ grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));+ }+}++@media (prefers-reduced-motion: reduce) {+ .gv-card,+ .gv-btn,+ .gv-icon-btn,+ .gv-card-thumb img {+ transition: none;+ }+ .gv-card--skeleton,+ .gv-spinner {+ animation: none;+ }+}diff --git a/scripts/build-agent-hints.mjs b/scripts/build-agent-hints.mjsnew file mode 100644index 000000000..9bcbbabba--- /dev/null+++ b/scripts/build-agent-hints.mjs@@ -0,0 +1,106 @@+#!/usr/bin/env node+/**+ * Generate public/agent-hints.json: which skills drive which animation slot.+ *+ * Skills declare `animationHint: '<name>'` next to their own `name:` in+ * src/agent-skills*.js. The /gestures page shows that mapping, and importing the+ * skill registry into a docs page would pull the whole trading stack into the+ * bundle, so the attribution is extracted here instead. Output is sorted and+ * carries no timestamp, so the file is diff-stable and safe to commit.+ *+ * node scripts/build-agent-hints.mjs # write public/agent-hints.json+ * node scripts/build-agent-hints.mjs --check # exit 1 if the file is stale+ *+ * tests/agent-hints.test.js runs the --check path, so a new skill hint fails the+ * suite until the file is regenerated.+ */++import { readdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { DEFAULT_ANIMATION_MAP, resolveHint } from '../src/runtime/animation-slots.js';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const SRC = join(ROOT, 'src');+const OUT = join(ROOT, 'public/agent-hints.json');+const SELF = resolve(SRC, 'runtime/animation-slots.js');++/** Every .js file under src/, recursively. */+function jsFiles(dir, out = []) {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) jsFiles(path, out);+ else if (entry.name.endsWith('.js')) out.push(path);+ }+ return out;+}++/**+ * Extract { hint, skill } pairs. A skill literal is written+ * `{ name: 'x', description: …, animationHint: 'y' }`, so the owning skill is the+ * nearest `name:` before the hint. Files with no hint are skipped entirely.+ */+export function collect() {+ const rows = [];+ for (const file of jsFiles(SRC)) {+ if (file === SELF) continue; // documents the field shape, declares no hints+ const src = readFileSync(file, 'utf8');+ if (!src.includes('animationHint:')) continue;+ for (const m of src.matchAll(/animationHint:\s*'([^']+)'/g)) {+ const before = src.slice(0, m.index);+ // Prose mentions the field too (src/agent-avatar.js explains what it+ // routes). A commented line is documentation, not a declaration.+ const line = src.slice(before.lastIndexOf('\n') + 1, m.index).trimStart();+ if (line.startsWith('//') || line.startsWith('*')) continue;+ // The owning skill is the nearest `name:` above, inside the same object+ // literal. Bounded so a stray hint cannot inherit an unrelated name.+ const name = [...before.slice(-800).matchAll(/\bname:\s*'([^']+)'/g)].pop();+ rows.push({ hint: m[1], skill: name ? name[1] : null });+ }+ }+ return rows;+}++/** Group into the shipped shape: one entry per hint, with its slot and skills. */+export function build() {+ const byHint = new Map();+ for (const { hint, skill } of collect()) {+ if (!byHint.has(hint)) byHint.set(hint, new Set());+ if (skill) byHint.get(hint).add(skill);+ }+ const hints = [...byHint.entries()]+ .map(([hint, skills]) => {+ const slot = resolveHint(hint);+ return {+ hint,+ slot,+ clip: slot ? DEFAULT_ANIMATION_MAP[slot] ?? null : null,+ skills: [...skills].sort(),+ };+ })+ .sort((a, b) => b.skills.length - a.skills.length || a.hint.localeCompare(b.hint));+ return { hints, total_skills: hints.reduce((n, h) => n + h.skills.length, 0) };+}++function main() {+ const next = `${JSON.stringify(build(), null, '\t')}\n`;+ let current = null;+ try {+ current = readFileSync(OUT, 'utf8');+ } catch {}+ if (current === next) {+ console.log('[agent-hints] up to date');+ return 0;+ }+ if (process.argv.includes('--check')) {+ console.error('[agent-hints] public/agent-hints.json is stale. Run: npm run build:agent-hints');+ return 1;+ }+ writeFileSync(OUT, next);+ const { hints, total_skills } = build();+ console.log(`[agent-hints] wrote ${hints.length} hints across ${total_skills} skills`);+ return 0;+}++const invokedDirectly = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);+if (invokedDirectly) process.exitCode = main();diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 44dfbfc01..b899736a3 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -8,6 +8,7 @@ import { isValidGlbMagic } from './shared/glb-magic.js';import { agentBus } from './agents/agent-bus.js';import { mountAutopilotMind } from './autopilot-mind.js';import { mountMoodInspector } from './agents/mood-inspector.js';+import { SLOTS, DEFAULT_ANIMATION_MAP } from './runtime/animation-slots.js';// Boot the mood engine + embodiment so the edit-page avatar reflects mood live.import './agents/mood-embodiment.js';@@ -744,6 +745,7 @@ async function renderAnimationsPicker() {updateAnimSaveButton();renderAnimGraphPicker();+ renderAnimSlotsPicker();}function renderAnimGraphSkeleton() {@@ -819,7 +821,7 @@ function updateAnimGraphSaveButton() {// Warn before navigating away with unsaved animation graph changes.window.addEventListener('beforeunload', (e) => {- const dirty = ANIM_STATES.some((s) => animGraphState[s] !== originalAnimGraphState[s]);+ const dirty = ANIM_STATES.some((s) => animGraphState[s] !== originalAnimGraphState[s]) || animSlotsDirty();if (dirty) e.preventDefault();});@@ -886,6 +888,131 @@ async function saveAnimationGraph() {}}+// ── Gesture slots ──────────────────────────────────────────────────────────+// The agent's own bindings for the fixed gesture vocabulary, stored at+// meta.edits.animations and applied by src/agent-avatar.js. Same shape as the+// animation-state picker above: one row per slot, "Platform default" inherits the+// platform clip, and only real overrides are sent.++let animSlotState = {};+let originalAnimSlotState = {};++function renderAnimSlotsPicker() {+ const rows = $('anim-slots-rows');+ const saveBtn = $('anim-slots-save');+ if (!rows) return;++ const saved = agentData.meta?.edits?.animations || {};+ animSlotState = {};+ for (const slot of SLOTS) animSlotState[slot] = saved[slot] ?? '';+ originalAnimSlotState = { ...animSlotState };++ rows.innerHTML = SLOTS.map((slot) => {+ const def = DEFAULT_ANIMATION_MAP[slot];+ const options = ['<option value="">Platform default</option>']+ .concat(+ animationLibrary.map((a) => {+ const sel = animSlotState[slot] === a.name ? ' selected' : '';+ return `<option value="${escapeHtml(a.name)}"${sel}>${escapeHtml(a.label || a.name)}</option>`;+ }),+ )+ .join('');+ return `+ <div class="anim-graph-row" data-slot="${escapeHtml(slot)}">+ <span class="anim-graph-row-label">${escapeHtml(slot)}</span>+ <select aria-label="Clip for the ${escapeHtml(slot)} gesture">${options}</select>+ <span class="anim-graph-row-meta">default: ${escapeHtml(def)}</span>+ </div>+ `;+ }).join('');++ rows.querySelectorAll('.anim-graph-row').forEach((row) => {+ const slot = row.dataset.slot;+ const select = row.querySelector('select');+ select.addEventListener('change', () => {+ animSlotState[slot] = select.value;+ updateAnimSlotsSaveButton();+ });+ });++ if (saveBtn && !saveBtn.dataset.wired) {+ saveBtn.dataset.wired = '1';+ saveBtn.addEventListener('click', saveAnimationSlots);+ }+ updateAnimSlotsSaveButton();+}++function animSlotsDirty() {+ return SLOTS.some((s) => animSlotState[s] !== originalAnimSlotState[s]);+}++function updateAnimSlotsSaveButton() {+ const saveBtn = $('anim-slots-save');+ if (saveBtn) saveBtn.disabled = !animSlotsDirty();+}++/** { slot: clip } for real overrides only, so defaults stay inherited. */+function buildAnimSlotsPayload() {+ const out = {};+ for (const slot of SLOTS) {+ const clip = animSlotState[slot];+ if (clip && clip !== DEFAULT_ANIMATION_MAP[slot]) out[slot] = clip;+ }+ return out;+}++async function saveAnimationSlots() {+ const status = $('anim-slots-status');+ const saveBtn = $('anim-slots-save');+ if (!status || !saveBtn) return;++ // PUT /api/agents/:id/animations requires animations[] alongside the slots,+ // so re-send the current clip selection unchanged.+ const animations = animationLibrary+ .filter((a) => selectedAnimNames.has(a.name))+ .map((a) => ({+ name: a.name,+ url: a.url,+ loop: a.loop !== false,+ source: 'mixamo',+ addedAt: new Date().toISOString(),+ }));++ saveBtn.disabled = true;+ status.textContent = 'Saving…';+ status.className = 'form-status';++ try {+ const r = await apiFetch(`${API_BASE}/agents/${agentId}/animations`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ animations, animationSlots: buildAnimSlotsPayload() }),+ });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ }+ const j = await r.json();+ if (!agentData.meta) agentData.meta = {};+ agentData.meta.animations = j.animations;+ agentData.meta.edits = { ...(agentData.meta.edits || {}), animations: j.animationSlots || {} };+ originalAnimSlotState = { ...animSlotState };+ const count = Object.keys(j.animationSlots || {}).length;+ status.textContent = count+ ? `Saved ${count} gesture override${count === 1 ? '' : 's'}.`+ : 'Cleared every gesture override.';+ status.className = 'form-status ok';+ reloadOutfitPreview();+ setTimeout(() => { status.textContent = ''; status.className = 'form-status'; }, 2500);+ } catch (err) {+ status.textContent = `Error: ${err.message}`;+ status.className = 'form-status err';+ } finally {+ updateAnimSlotsSaveButton();+ }+}+function updateAnimSaveButton() {const saveBtn = $('anims-save');if (!saveBtn) return;diff --git a/src/app.js b/src/app.jsindex 6fcb59504..3d22cdc3c 100644--- a/src/app.js+++ b/src/app.js@@ -1943,6 +1943,15 @@ class App {this.avatar = new AgentAvatar(viewer, protocol, this.identity);this.avatar.attach();+ // This agent's own gesture bindings (meta.edits.animations, written by+ // PUT /api/agents/:id/animations with animationSlots). Nothing used to+ // apply them, so the override map documented since the slot system landed+ // had no effect anywhere.+ const slotOverrides = this.identity?.meta?.edits?.animations;+ if (slotOverrides && typeof slotOverrides === 'object') {+ this.avatar.setAnimationMap(slotOverrides);+ }+// Create (or replace) the SceneController for agent scene operationsthis.sceneCtrl = new SceneController(viewer);if (this.runtime) this.runtime.viewer = this.sceneCtrl;diff --git a/src/element.js b/src/element.jsindex 6d6de7cf9..f0ef24ac3 100644--- a/src/element.js+++ b/src/element.js@@ -1777,6 +1777,13 @@ class Agent3DElement extends HTMLElement {this._avatar = new AgentAvatar(this._viewer, protocol, _identity);this._avatar.attach();+ // Per-agent gesture bindings from the manifest (meta.edits.animations+ // on the record, `animationSlots` on the wire). Without this the+ // override map was unreachable: every agent played the platform+ // defaults no matter what its owner had saved.+ const _slots = manifest.animationSlots || manifest.meta?.edits?.animations;+ if (_slots && typeof _slots === 'object') this._avatar.setAnimationMap(_slots);+// Honor a sign-language attribute present at boot (the observer// only covers post-mount changes).const signAttr = this.getAttribute('sign-language');diff --git a/src/gestures-page.js b/src/gestures-page.jsnew file mode 100644index 000000000..a673fbc4e--- /dev/null+++ b/src/gestures-page.js@@ -0,0 +1,441 @@+// /gestures: the agent gesture vocabulary, previewed live.+//+// Three things are on this page, all of them derived rather than restated:+//+// • the slot grid, from SLOTS + DEFAULT_ANIMATION_MAP (src/runtime/animation-slots.js)+// • the hint table, from /agent-hints.json (generated by scripts/build-agent-hints.mjs+// out of the shipped skill definitions, so the attribution cannot go stale)+// • the /walk gesture layers, from GESTURES (src/animation-state-machine.js)+//+// The 3D preview reuses the gallery's shared engine: one renderer, one avatar,+// moved into the stage on demand. Nothing 3D loads until the first gesture is+// played, so the page paints without a GL context.++import { SLOTS, DEFAULT_ANIMATION_MAP, HINT_ALIASES } from './runtime/animation-slots.js';+import { GESTURES, GESTURE_NAMES } from './animation-state-machine.js';+import { curate, CATEGORIES } from './animation-presets.js';++const MANIFEST_URL = '/animations/manifest.json';+const HINTS_URL = '/agent-hints.json';+const THUMB_BASE = '/animations/thumbs';++/** What each slot means, in one line. Prose, not derivable from the map. */+const SLOT_NOTES = {+ idle: 'The resting loop. Always playing underneath everything else.',+ wave: 'Greeting, and the first gesture most agents ever play.',+ nod: 'Acknowledging. Fired when a model finishes loading.',+ shake: 'Refusing. The only baked head-shake clip in the library.',+ think: 'Reasoning. Fired while a skill or a load is in flight.',+ celebrate: 'A win: a clean validation, a settled payment, a launch.',+ concern: 'Something failed. Paired with a downward gaze.',+ bow: 'Thanks. The one slot with no dedicated clip yet.',+ point: 'Deictic: referring to a thing on screen. Also the generic action gesture.',+ shrug: 'Uncertainty. Overlays locomotion on /walk, so an avatar can shrug mid-stride.',+ fidget: 'Idle restlessness for a long wait.',+ dance: 'Celebration with the whole body. The club stage books these by name.',+ inspect: 'Reading data. The most-declared hint in the skill catalog.',+ present: 'Showing a result off.',+ sign: 'Authorizing a wallet signature.',+ curiosity: 'Scanning, looking around, alert.',+ patience: 'Waiting on long-running work.',+ manipulate: 'Handling a scene object.',+ conjure: 'Creating something from nothing.',+};++/** Slots whose clip is an approximation rather than a match. */+const APPROXIMATE = new Set(['bow']);++const $ = (sel, root = document) => root.querySelector(sel);+const el = (role, root = document) => root.querySelector(`[data-role="${role}"]`);++const state = {+ manifest: [],+ byName: new Map(),+ hints: null,+ slot: null,+ clip: null, // the clip currently staged (default or override)+ preview: null, // lazily imported AnimationLivePreview+ paused: false,+};++/* ── data ──────────────────────────────────────────────────────────────── */++async function fetchJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`${url} responded ${res.status}`);+ return res.json();+}++async function loadManifest() {+ const grid = el('grid');+ const errorBox = el('grid-error');+ grid.setAttribute('aria-busy', 'true');+ errorBox.hidden = true;+ try {+ const manifest = await fetchJson(MANIFEST_URL);+ state.manifest = Array.isArray(manifest) ? manifest : [];+ state.byName = new Map(state.manifest.map((c) => [c.name, c]));+ renderGrid();+ renderOverrideOptions();+ renderStats();+ applyDeepLink();+ } catch (err) {+ grid.innerHTML = '';+ grid.setAttribute('aria-busy', 'false');+ errorBox.hidden = false;+ el('grid-error-detail').textContent = err?.message || String(err);+ }+}++async function loadHints() {+ const host = el('hints');+ try {+ state.hints = await fetchJson(HINTS_URL);+ renderHints();+ renderStats();+ } catch (err) {+ // The hint table is supporting detail: the vocabulary above it still works,+ // so degrade to a readable note instead of an error state for the page.+ host.innerHTML = `<div class="gv-hints-loading">The skill map did not load (${escapeHtml(+ err?.message || String(err),+ )}). Every hint is also listed in <a href="/docs/animations">docs/animations</a>.</div>`;+ }+}++/* ── render ────────────────────────────────────────────────────────────── */++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);+}++function renderStats() {+ el('stat-slots').textContent = String(SLOTS.length);+ el('stat-clips').textContent = String(state.manifest.length || '-');+ el('stat-hints').textContent = String(state.hints?.hints?.length ?? '-');+ el('stat-skills').textContent = String(state.hints?.total_skills ?? '-');+}++function cardHtml(slot) {+ const clip = DEFAULT_ANIMATION_MAP[slot];+ const def = state.byName.get(clip);+ const label = def?.label || clip;+ const icon = def?.icon || '🎞️';+ const badge = APPROXIMATE.has(slot)+ ? '<span class="gv-badge gv-badge--warn">approx</span>'+ : def?.loop+ ? '<span class="gv-badge">loop</span>'+ : '';+ return `+ <button type="button" class="gv-card" role="listitem" data-slot="${escapeHtml(slot)}"+ aria-current="false"+ title="${escapeHtml(SLOT_NOTES[slot] || '')}">+ <span class="gv-card-thumb">+ <span class="gv-card-thumb-fallback" aria-hidden="true">${icon}</span>+ <img src="${THUMB_BASE}/${encodeURIComponent(clip)}.webp" alt=""+ loading="lazy" decoding="async" width="480" height="480" />+ ${badge}+ </span>+ <span class="gv-card-body">+ <span class="gv-card-slot">${escapeHtml(slot)}</span>+ <span class="gv-card-clip">${escapeHtml(label)}</span>+ </span>+ </button>`;+}++function renderGrid() {+ const grid = el('grid');+ grid.innerHTML = SLOTS.map(cardHtml).join('');+ grid.setAttribute('aria-busy', 'false');+ // The clip's emoji stands in until its poster paints, then gets out of the+ // way: leaving both would stamp an emoji over the avatar. A poster that never+ // loads keeps the emoji and drops the empty image box.+ for (const img of grid.querySelectorAll('.gv-card-thumb img')) {+ const fallback = img.previousElementSibling;+ const settle = () => fallback?.remove();+ if (img.complete && img.naturalWidth > 0) settle();+ else {+ img.addEventListener('load', settle, { once: true });+ img.addEventListener('error', () => img.remove(), { once: true });+ }+ }+}++function renderHints() {+ const rows = state.hints?.hints || [];+ const head = `+ <div class="gv-row gv-row--head">+ <span>Hint</span><span>Slot</span><span>Clip</span><span>Skills</span>+ </div>`;+ const body = rows+ .map((row) => {+ const alias = HINT_ALIASES[row.hint] ? ' <span class="gv-arrow">(alias)</span>' : '';+ const skills = row.skills+ .map((s) => `<code>${escapeHtml(s)}</code>`)+ .join('');+ return `+ <div class="gv-row">+ <span class="gv-mono">${escapeHtml(row.hint)}${alias}</span>+ <span class="gv-mono">${escapeHtml(row.slot)}</span>+ <span class="gv-mono">${escapeHtml(row.clip)}</span>+ <span class="gv-count">${row.skills.length}</span>+ </div>+ <details>+ <summary>Show the ${row.skills.length} skill${row.skills.length === 1 ? ' that declares' : 's that declare'} <code>${escapeHtml(row.hint)}</code></summary>+ <div class="gv-hints-skills">${skills}</div>+ </details>`;+ })+ .join('');+ el('hints').innerHTML = head + body;+}++function renderLayers() {+ const head = `+ <div class="gv-row gv-row--head">+ <span>Gesture</span><span>Clip</span><span>Layer</span><span>Hold</span>+ </div>`;+ const body = GESTURE_NAMES.map((name) => {+ const g = GESTURES[name];+ return `+ <div class="gv-row">+ <span class="gv-mono">${escapeHtml(name)}</span>+ <span class="gv-mono">${escapeHtml(g.clip)}</span>+ <span class="gv-mono">${g.layer}</span>+ <span class="gv-count">${g.loop ? 'held' : 'one-shot'}</span>+ </div>`;+ }).join('');+ el('layers').innerHTML = head + body;+}++function renderOverrideOptions() {+ const select = el('override-select');+ const { groups } = curate(state.manifest);+ const order = new Map(CATEGORIES.map((c, i) => [c.key, i]));+ const sorted = [...groups].sort((a, b) => (order.get(a.key) ?? 99) - (order.get(b.key) ?? 99));+ select.innerHTML = sorted+ .map(+ (g) => `<optgroup label="${escapeHtml(`${g.icon} ${g.label}`)}">${g.items+ .map(+ (item) =>+ `<option value="${escapeHtml(item.name)}">${escapeHtml(item.label || item.name)}</option>`,+ )+ .join('')}</optgroup>`,+ )+ .join('');+}++function renderOverride() {+ const box = el('override');+ if (!state.slot) {+ box.hidden = true;+ return;+ }+ box.hidden = false;+ el('override-slot').textContent = state.slot;+ el('override-select').value = state.clip;+ const json = JSON.stringify({ edits: { animations: { [state.slot]: state.clip } } }, null, 2);+ $('code', el('override-code')).textContent = json;+ const isDefault = state.clip === DEFAULT_ANIMATION_MAP[state.slot];+ el('override-reset').disabled = isDefault;+}++/* ── preview ───────────────────────────────────────────────────────────── */++function setStageState(name, detail = '') {+ el('stage-empty').hidden = name !== 'empty';+ el('stage-loading').hidden = name !== 'loading';+ el('stage-error').hidden = name !== 'error';+ if (name === 'error' && detail) el('stage-error-title').textContent = detail;+}++async function getPreview() {+ if (!state.preview) {+ const mod = await import('./animations-live-preview.js');+ state.preview = mod.getLivePreview();+ }+ return state.preview;+}++async function play(slot, clip = DEFAULT_ANIMATION_MAP[slot]) {+ state.slot = slot;+ state.clip = clip;+ const def = state.byName.get(clip);+ el('stage-slot').textContent = slot;+ el('stage-clip').textContent = def?.label ? `${def.label} · ${clip}` : clip;+ el('stage-status').textContent = `Playing ${slot}: ${def?.label || clip}`;+ for (const card of document.querySelectorAll('.gv-card[data-slot]')) {+ card.setAttribute('aria-current', String(card.dataset.slot === slot));+ }+ renderOverride();+ syncUrl();++ if (!def) {+ setStageState('error', `"${clip}" is not in the clip manifest.`);+ return;+ }++ setStageState('loading');+ el('stage-replay').disabled = true;+ el('stage-pause').disabled = true;+ try {+ const preview = await getPreview();+ await preview.play(el('stage'), {+ id: clip,+ source: 'curated',+ url: def.url,+ loop: def.loop !== false,+ });+ // A superseded play() resolves without mounting; only clear the overlay+ // when this call is still the current one.+ if (state.clip !== clip) return;+ setStageState('none');+ state.paused = false;+ el('stage-replay').disabled = false;+ el('stage-pause').disabled = false;+ el('stage-pause').setAttribute('aria-pressed', 'false');+ } catch (err) {+ if (state.clip !== clip) return;+ setStageState('error', err?.message ? `Preview failed: ${err.message}` : undefined);+ }+}++function stop() {+ state.preview?.stop();+ setStageState('empty');+ el('stage-slot').textContent = 'No gesture selected';+ el('stage-clip').innerHTML = ' ';+ el('stage-replay').disabled = true;+ el('stage-pause').disabled = true;+ el('override').hidden = true;+ state.slot = null;+ state.clip = null;+ for (const card of document.querySelectorAll('.gv-card[data-slot]')) {+ card.setAttribute('aria-current', 'false');+ }+ syncUrl();+}++/* ── url state ─────────────────────────────────────────────────────────── */++function syncUrl() {+ const url = new URL(window.location.href);+ if (state.slot) url.searchParams.set('slot', state.slot);+ else url.searchParams.delete('slot');+ if (state.slot && state.clip !== DEFAULT_ANIMATION_MAP[state.slot]) {+ url.searchParams.set('clip', state.clip);+ } else {+ url.searchParams.delete('clip');+ }+ window.history.replaceState(null, '', url);+}++function applyDeepLink() {+ const params = new URLSearchParams(window.location.search);+ const slot = params.get('slot');+ if (!slot || !SLOTS.includes(slot)) return;+ const clip = params.get('clip');+ play(slot, clip && state.byName.has(clip) ? clip : DEFAULT_ANIMATION_MAP[slot]);+}++/* ── events ────────────────────────────────────────────────────────────── */++function cardAt(index) {+ const cards = [...document.querySelectorAll('.gv-card[data-slot]')];+ if (!cards.length) return null;+ const wrapped = ((index % cards.length) + cards.length) % cards.length;+ return cards[wrapped];+}++function columnsInGrid() {+ const grid = el('grid');+ const style = getComputedStyle(grid);+ return Math.max(1, style.gridTemplateColumns.split(' ').filter(Boolean).length);+}++function wire() {+ el('grid').addEventListener('click', (e) => {+ const card = e.target.closest('.gv-card[data-slot]');+ if (card) play(card.dataset.slot);+ });++ // Arrow keys walk the grid; Enter plays. Roving focus, so the browser's own+ // focus ring is the selection indicator.+ el('grid').addEventListener('keydown', (e) => {+ const card = e.target.closest('.gv-card[data-slot]');+ if (!card) return;+ const cards = [...document.querySelectorAll('.gv-card[data-slot]')];+ const i = cards.indexOf(card);+ const cols = columnsInGrid();+ const moves = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: cols, ArrowUp: -cols };+ if (e.key in moves) {+ e.preventDefault();+ cardAt(i + moves[e.key])?.focus();+ return;+ }+ if (e.key === 'Home' || e.key === 'End') {+ e.preventDefault();+ cardAt(e.key === 'Home' ? 0 : cards.length - 1)?.focus();+ }+ });++ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && state.slot) stop();+ });++ el('grid-retry').addEventListener('click', loadManifest);+ el('stage-retry').addEventListener('click', () => {+ if (state.slot) play(state.slot, state.clip);+ });++ el('stage-replay').addEventListener('click', () => {+ if (state.slot) play(state.slot, state.clip);+ });++ el('stage-pause').addEventListener('click', async (e) => {+ const preview = await getPreview();+ state.paused = !state.paused;+ preview.setPaused(state.paused);+ e.currentTarget.setAttribute('aria-pressed', String(state.paused));+ e.currentTarget.textContent = state.paused ? '▶' : '❙❙';+ el('stage-status').textContent = state.paused ? 'Preview paused' : 'Preview playing';+ });++ el('override-select').addEventListener('change', (e) => {+ if (state.slot) play(state.slot, e.target.value);+ });++ el('override-reset').addEventListener('click', () => {+ if (state.slot) play(state.slot, DEFAULT_ANIMATION_MAP[state.slot]);+ });++ el('override-copy').addEventListener('click', async (e) => {+ const btn = e.currentTarget;+ const text = $('code', el('override-code')).textContent;+ try {+ await navigator.clipboard.writeText(text);+ btn.textContent = 'Copied';+ } catch {+ // Clipboard is permission-gated in some browsers: select the block so+ // the user can copy it by hand instead of silently failing.+ const range = document.createRange();+ range.selectNodeContents(el('override-code'));+ const sel = window.getSelection();+ sel.removeAllRanges();+ sel.addRange(range);+ btn.textContent = 'Selected, press Cmd/Ctrl+C';+ }+ setTimeout(() => {+ btn.textContent = 'Copy JSON';+ }, 1800);+ });++ // Free the GL context when the tab is hidden for a while.+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) state.preview?.setPaused(true);+ else if (!state.paused) state.preview?.setPaused(false);+ });+}++renderLayers();+wire();+loadManifest();+loadHints();diff --git a/tests/agent-animation-slots.test.js b/tests/agent-animation-slots.test.jsnew file mode 100644index 000000000..b449b85d7--- /dev/null+++ b/tests/agent-animation-slots.test.js@@ -0,0 +1,111 @@+/**+ * PUT /api/agents/:id/animations accepts `animationSlots`: the agent's own+ * bindings for the gesture vocabulary, persisted at meta.edits.animations.+ *+ * That path is the producer half of a feature that shipped with neither half+ * wired: the runtime read meta.edits.animations, docs described it, and nothing+ * could write it (no UI, no API field) while nothing applied it either+ * (setAnimationMap was never called). These tests pin the validation contract of+ * the write path, so a slot typo or a hostile clip name fails at the boundary+ * rather than persisting into a gesture that silently never plays.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { z } from 'zod';+import { SLOTS, DEFAULT_ANIMATION_MAP } from '../src/runtime/animation-slots.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const SUB = readFileSync(resolve(__dirname, '../api/agents/_id/_sub.js'), 'utf8');++// The handler's schema, rebuilt here from the same source of truth. Importing+// the handler itself would pull in the DB client and the session layer.+const schema = z+ .record(+ z.enum(/** @type {[string, ...string[]]} */ (SLOTS)),+ z+ .string()+ .trim()+ .min(1)+ .max(60)+ .regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/, 'clip name must be alphanumeric with - or _'),+ )+ .refine((map) => Object.keys(map).length <= SLOTS.length, 'too many slot overrides');++describe('animationSlots validation', () => {+ it('accepts a real slot pointed at a real clip', () => {+ expect(schema.parse({ dance: 'av-offabean-dance' })).toEqual({ dance: 'av-offabean-dance' });+ });++ it('accepts an empty map, which clears every override', () => {+ expect(schema.parse({})).toEqual({});+ });++ it('accepts every slot at once', () => {+ const all = Object.fromEntries(SLOTS.map((s) => [s, DEFAULT_ANIMATION_MAP[s]]));+ expect(Object.keys(schema.parse(all))).toHaveLength(SLOTS.length);+ });++ it('rejects a slot outside the vocabulary', () => {+ expect(() => schema.parse({ backflip: 'av-back-flip' })).toThrow();+ });++ it('rejects a path, a query string, or a quote in a clip name', () => {+ for (const bad of ['../../etc/passwd', 'clip?x=1', "clip'; drop", 'clip name', '/absolute']) {+ expect(() => schema.parse({ dance: bad }), `accepted ${bad}`).toThrow();+ }+ });++ it('rejects an empty or over-long clip name', () => {+ expect(() => schema.parse({ dance: '' })).toThrow();+ expect(() => schema.parse({ dance: 'a'.repeat(61) })).toThrow();+ });+});++describe('the animations handler wiring', () => {+ it('derives its slot vocabulary from the runtime module', () => {+ expect(SUB).toMatch(/from '\.\.\/\.\.\/\.\.\/src\/runtime\/animation-slots\.js'/);+ expect(SUB).toMatch(/z\.enum\(\/\*\* @type \{\[string, \.\.\.string\[\]\]\} \*\/ \(SLOTS\)\)/);+ });++ it('writes the map where the runtime reads it', () => {+ expect(SUB).toContain("'{edits,animations}'");+ });++ it('leaves the map alone when the request omits the field', () => {+ // The guard that makes a clip-list save non-destructive to the overrides.+ expect(SUB).toContain("has('animationSlots')");+ });++ it('reads the stored map back into the response', () => {+ expect(SUB).toMatch(/meta->'edits'->'animations' AS slots/);+ });+});++describe('the consumers apply it', () => {+ const read = (p) => readFileSync(resolve(__dirname, p), 'utf8');++ it('the agent page applies the override map to the avatar', () => {+ const app = read('../src/app.js');+ expect(app).toContain('this.identity?.meta?.edits?.animations');+ expect(app).toContain('this.avatar.setAnimationMap(slotOverrides)');+ });++ it('the embed component applies the manifest map to the avatar', () => {+ const element = read('../src/element.js');+ expect(element).toContain('manifest.animationSlots');+ expect(element).toContain('this._avatar.setAnimationMap(_slots)');+ });++ it('the manifest endpoint publishes the map for embeds', () => {+ expect(SUB).toContain('animationSlots:');+ });++ it('the editor offers a row per slot and posts them', () => {+ const editor = read('../src/agent-edit.js');+ expect(editor).toContain('renderAnimSlotsPicker');+ expect(editor).toContain('animationSlots: buildAnimSlotsPayload()');+ });+});diff --git a/tests/agent-hints.test.js b/tests/agent-hints.test.jsnew file mode 100644index 000000000..54917ca0d--- /dev/null+++ b/tests/agent-hints.test.js@@ -0,0 +1,55 @@+/**+ * public/agent-hints.json is the attribution behind the /gestures page: which+ * skills drive which animation slot. It is generated from the skill sources by+ * scripts/build-agent-hints.mjs, so it can only be true if it is regenerated+ * when a skill changes its hint.+ *+ * These tests fail when the committed file is stale, when a declared hint+ * resolves to no slot, or when a slot's clip is not baked in the manifest.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { build, collect } from '../scripts/build-agent-hints.mjs';+import { DEFAULT_ANIMATION_MAP } from '../src/runtime/animation-slots.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const readJson = (p) => JSON.parse(readFileSync(resolve(__dirname, p), 'utf8'));++const committed = readJson('../public/agent-hints.json');+const manifest = readJson('../public/animations/manifest.json');+const CLIP_NAMES = new Set(manifest.map((c) => c.name));++describe('agent-hints.json', () => {+ it('matches the skill sources (run npm run build:agent-hints)', () => {+ expect(committed).toEqual(build());+ });++ it('resolves every declared hint to a slot with a baked clip', () => {+ for (const row of committed.hints) {+ expect(row.slot, `hint "${row.hint}" resolves to no slot`).toBeTruthy();+ expect(row.clip).toBe(DEFAULT_ANIMATION_MAP[row.slot]);+ expect(CLIP_NAMES.has(row.clip), `hint "${row.hint}" → "${row.clip}" is not baked`).toBe(true);+ }+ });++ it('attributes every hint to at least one named skill', () => {+ for (const row of committed.hints) {+ expect(row.skills.length, `hint "${row.hint}" has no skill`).toBeGreaterThan(0);+ }+ });++ it('finds the hints where they are actually declared', () => {+ const rows = collect();+ expect(rows.length).toBeGreaterThan(40);+ expect(rows.every((r) => r.skill)).toBe(true);+ });++ it('counts each skill declaration exactly once per hint', () => {+ for (const row of committed.hints) {+ expect(new Set(row.skills).size).toBe(row.skills.length);+ }+ });+});