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(choreography): routine format, runtime player, and authoring page
nirholas930d8df2c040
diff --git a/pages/choreograph.html b/pages/choreograph.htmlnew file mode 100644index 000000000..08c7497d3--- /dev/null+++ b/pages/choreograph.html@@ -0,0 +1,275 @@+<!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>Choreographer · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Compose a timed sequence of agent gestures on a timeline, preview the whole performance on a live 3D avatar, then save it to your agent and play it by name from any embed." />+ <meta name="theme-color" content="#000000" />+ <link rel="canonical" href="https://three.ws/choreograph" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Choreographer · three.ws" />+ <meta property="og:description" content="Compose agent gestures into a timed routine, preview it live in 3D, save it to your agent, and play it by name from any embed." />+ <meta property="og:url" content="https://three.ws/choreograph" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Choreographer&d=Compose+agent+gestures+into+a+timed+routine%2C+preview+it+live+in+3D%2C+then+play+it+by+name+from+any+embed.&p=%2Fchoreograph" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Choreographer · three.ws" />+ <meta name="twitter:description" content="A timeline for agent body language. Compose, preview in 3D, save to your agent, play it by name." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Choreographer&d=Compose+agent+gestures+into+a+timed+routine%2C+preview+it+live+in+3D%2C+then+play+it+by+name+from+any+embed.&p=%2Fchoreograph" />++ <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="/choreograph.css" />++ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"three.ws Choreographer","applicationCategory":"DesignApplication","operatingSystem":"Any","description":"Compose timed sequences of agent gestures on a timeline, preview them on a live 3D avatar, and save them to an agent as named routines playable from any embed.","url":"https://three.ws/choreograph","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"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="The three.ws gesture choreographer">+ </head>+ <body class="ch-page">+ <header>+ <div id="nav-container"></div>+ </header>+ <script src="/nav.js"></script>++ <main>+ <section class="ch-hero">+ <div class="ch-hero-chip">+ <span class="ch-hero-dot" aria-hidden="true"></span>+ <span>Agent body language</span>+ </div>+ <h1>Choreographer</h1>+ <p class="ch-hero-lede">+ One gesture is a beat. A <strong>routine</strong> is a performance: wave, then think,+ then present the thing you just made. Build one on the timeline, watch the whole thing+ on a live avatar, then save it to your agent and play it by name from any embed.+ </p>+ <div class="ch-hero-actions">+ <a class="ch-btn ch-btn--secondary" href="/gestures">The gesture vocabulary</a>+ <a class="ch-btn ch-btn--ghost" href="/animations">Browse every clip</a>+ <a class="ch-btn ch-btn--ghost" href="/docs/choreography">Developer reference</a>+ </div>+ </section>++ <section class="ch-body">+ <!-- Left rail: the stage and the transport. Sticky on desktop, so+ editing a step at the bottom of a long routine still shows the+ avatar performing it. -->+ <aside class="ch-stage-col">+ <div class="ch-stage-card">+ <div class="ch-stage" data-role="stage">+ <div class="ch-stage-empty" data-role="stage-empty">+ <div class="ch-stage-empty-icon" aria-hidden="true">🎬</div>+ <p class="ch-stage-empty-title">Nothing staged yet</p>+ <p class="ch-stage-empty-body">+ Start from a routine below, or add a gesture. Nothing 3D loads until you do.+ </p>+ </div>+ <div class="ch-stage-loading" data-role="stage-loading" hidden>+ <div class="ch-spinner" aria-hidden="true"></div>+ <p data-role="stage-loading-text">Retargeting the routine…</p>+ </div>+ <div class="ch-stage-error" data-role="stage-error" hidden>+ <p class="ch-stage-error-title" data-role="stage-error-title">That step did not fit the preview avatar.</p>+ <p class="ch-stage-error-body">+ The clip is fine: the shared preview rig could not bind it. Swap the step's clip,+ or preview it on its own in the <a href="/animations">gallery</a>.+ </p>+ <button type="button" class="ch-btn ch-btn--secondary" data-role="stage-retry">Try again</button>+ </div>+ <p class="ch-stage-badge" data-role="stage-badge" hidden></p>+ </div>++ <!-- Transport. The timeline is the primary control: its width is+ real time, so a long step looks long. -->+ <div class="ch-transport">+ <div class="ch-transport-row">+ <button type="button" class="ch-icon-btn ch-icon-btn--play" data-role="play" title="Play (Space)" aria-label="Play routine" disabled>▶</button>+ <button type="button" class="ch-icon-btn" data-role="restart" title="Restart (R)" aria-label="Restart routine" disabled>↻</button>+ <button type="button" class="ch-icon-btn" data-role="loop" title="Loop the routine" aria-label="Loop the routine" aria-pressed="false" disabled>⟲</button>+ <p class="ch-time"><span data-role="time">0.0</span>s <span class="ch-time-sep">/</span> <span data-role="duration">0.0</span>s</p>+ </div>++ <div+ class="ch-timeline"+ data-role="timeline"+ role="slider"+ tabindex="0"+ aria-label="Routine playhead"+ aria-valuemin="0"+ aria-valuenow="0"+ aria-valuemax="0"+ aria-valuetext="0 seconds"+ >+ <div class="ch-timeline-track" data-role="timeline-track"></div>+ <div class="ch-playhead" data-role="playhead" hidden></div>+ </div>+ <p class="ch-timeline-empty" data-role="timeline-empty">+ An empty timeline. Add a gesture and it appears here.+ </p>+ </div>+ <p class="ch-sr-status" data-role="stage-status" role="status" aria-live="polite"></p>+ </div>++ <div class="ch-shortcuts">+ <p>+ <kbd>Space</kbd> play/pause · <kbd>R</kbd> restart · <kbd>←</kbd> <kbd>→</kbd>+ scrub · <kbd>Esc</kbd> stop+ </p>+ </div>+ </aside>++ <!-- Right rail: composition. -->+ <div class="ch-main-col">+ <div class="ch-section-head">+ <h2 id="start">Start from a routine</h2>+ <p>+ Five performances built from the shipped slot vocabulary. Load one, then change+ anything: they are starting points, not templates you have to keep.+ </p>+ </div>+ <div class="ch-presets" data-role="presets" role="list"></div>++ <div class="ch-section-head ch-section-head--tight">+ <h2 id="routine">Your routine</h2>+ <p>+ Each row is one beat. Drag to reorder, set how long it holds, and point any step at+ a different clip. The stage follows every edit.+ </p>+ </div>++ <div class="ch-routine-bar">+ <label class="ch-field ch-field--grow">+ <span class="ch-field-label">Routine name</span>+ <input+ class="ch-input"+ data-role="name"+ type="text"+ maxlength="40"+ placeholder="Welcome"+ autocomplete="off"+ spellcheck="false"+ />+ </label>+ <p class="ch-routine-meta">+ <span data-role="step-count">0</span> steps ·+ <span data-role="meta-duration">0.0</span>s ·+ id <code data-role="routine-id">routine</code>+ </p>+ </div>++ <ol class="ch-steps" data-role="steps"></ol>++ <div class="ch-empty" data-role="steps-empty">+ <p class="ch-empty-title">No steps yet</p>+ <p class="ch-empty-body">+ Pick a gesture below to add the first beat, or load one of the routines above.+ </p>+ </div>++ <div class="ch-section-head ch-section-head--tight">+ <h2 id="palette">Add a gesture</h2>+ <p>+ The fixed slot vocabulary. A step names a slot, so a routine shared with another+ agent still plays that agent's own take on each gesture.+ </p>+ </div>+ <div class="ch-palette" data-role="palette" role="list"></div>++ <div class="ch-section-head ch-section-head--tight">+ <h2 id="ship">Ship it</h2>+ <p>+ Save the routine to an agent you own and it travels with that agent: the public+ manifest carries it, and any embed can play it by name.+ </p>+ </div>++ <div class="ch-ship">+ <div class="ch-save" data-role="save-panel" hidden>+ <label class="ch-field">+ <span class="ch-field-label">Save to</span>+ <select class="ch-select" data-role="agent-select"></select>+ </label>+ <div class="ch-actions">+ <button type="button" class="ch-btn ch-btn--primary" data-role="save">Save to agent</button>+ <button type="button" class="ch-btn ch-btn--ghost" data-role="share">Copy share link</button>+ </div>+ <p class="ch-save-status" data-role="save-status" role="status" aria-live="polite"></p>+ <div class="ch-saved" data-role="saved" hidden>+ <p class="ch-saved-title">Already on this agent</p>+ <div class="ch-saved-list" data-role="saved-list"></div>+ </div>+ </div>++ <div class="ch-save" data-role="save-signedout" hidden>+ <p class="ch-save-lede">+ Sign in to save this routine to an agent. Everything else on this page works+ without an account, and your routine is already in the URL.+ </p>+ <div class="ch-actions">+ <a class="ch-btn ch-btn--primary" href="/signin?next=/choreograph" data-role="signin">Sign in to save</a>+ <button type="button" class="ch-btn ch-btn--ghost" data-role="share-2">Copy share link</button>+ </div>+ </div>++ <details class="ch-export">+ <summary>Play it from your own site</summary>+ <p class="ch-export-lede">+ The routine below is live: paste it into any page that already renders an+ <code><agent-3d></code> embed.+ </p>+ <pre class="ch-code" data-role="embed-code"><code></code></pre>+ <div class="ch-actions">+ <button type="button" class="ch-btn ch-btn--secondary" data-role="copy-embed">Copy snippet</button>+ <a class="ch-btn ch-btn--ghost" href="/docs/choreography">Read the reference</a>+ </div>+ </details>++ <details class="ch-export">+ <summary>Show the JSON</summary>+ <p class="ch-export-lede">+ Exactly what gets stored at <code>meta.choreographies</code>, and exactly what+ <code>PUT /api/agents/:id/animations</code> accepts.+ </p>+ <pre class="ch-code" data-role="json-code"><code></code></pre>+ <div class="ch-actions">+ <button type="button" class="ch-btn ch-btn--secondary" data-role="copy-json">Copy JSON</button>+ </div>+ </details>+ </div>++ <div class="ch-footnote">+ <p>+ A routine is a list of slots and holds, not a list of animation files: the same+ routine looks different on an agent that has remapped its own gestures on+ <a href="/gestures">the vocabulary page</a>, which is the point. The wire format,+ the storage shape and the playback API are documented in+ <a href="/docs/choreography">docs/choreography</a>.+ </p>+ </div>+ </div>+ </section>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js" defer></script>++ <script type="module" src="/src/choreograph-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/choreograph.css b/public/choreograph.cssnew file mode 100644index 000000000..363377dfe--- /dev/null+++ b/public/choreograph.css@@ -0,0 +1,1039 @@+/* /choreograph: the gesture choreographer.+ *+ * 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>).+ * Deliberately shares the /gestures scale and radii — the two pages are one+ * surface split in half, and a user moving between them should not feel a seam.+ */++:root {+ --ch-radius: 14px;+ --ch-border: rgba(255, 255, 255, 0.08);+ --ch-border-strong: rgba(255, 255, 255, 0.2);+ --ch-surface: rgba(255, 255, 255, 0.03);+ --ch-surface-2: rgba(255, 255, 255, 0.06);+ --ch-surface-3: rgba(255, 255, 255, 0.1);+ --ch-accent: #7dd3fc;+ --ch-accent-ink: #04141f;+ --ch-muted: rgba(255, 255, 255, 0.6);+ --ch-ok: #4ade80;+ --ch-err: #f87171;+}+:root[data-theme='light'] {+ --ch-border: rgba(0, 0, 0, 0.1);+ --ch-border-strong: rgba(0, 0, 0, 0.24);+ --ch-surface: rgba(0, 0, 0, 0.03);+ --ch-surface-2: rgba(0, 0, 0, 0.05);+ --ch-surface-3: rgba(0, 0, 0, 0.09);+ --ch-accent: #0369a1;+ --ch-accent-ink: #f8fbff;+ --ch-muted: rgba(0, 0, 0, 0.58);+ --ch-ok: #15803d;+ --ch-err: #b91c1c;+}++.ch-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;+}++.ch-page main {+ max-width: 1360px;+ margin: 0 auto;+ padding: 0 clamp(16px, 4vw, 40px) 96px;+}++.ch-sr-only,+.ch-sr-status {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++/* ── Hero ──────────────────────────────────────────────────────────────── */++.ch-hero {+ padding: clamp(40px, 7vw, 88px) 0 clamp(20px, 3vw, 32px);+ max-width: 780px;+}+.ch-hero-chip {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 5px 12px 5px 10px;+ border: 1px solid var(--ch-border);+ border-radius: 999px;+ background: var(--ch-surface);+ font-size: 12px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--ch-muted);+}+.ch-hero-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--ch-accent);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--ch-accent) 22%, transparent);+}+.ch-hero h1 {+ margin: 18px 0 12px;+ font-size: clamp(34px, 6vw, 56px);+ line-height: 1.05;+ letter-spacing: -0.03em;+ font-weight: 680;+}+.ch-hero-lede {+ margin: 0 0 24px;+ font-size: clamp(15px, 1.6vw, 17px);+ line-height: 1.6;+ color: var(--ch-muted);+}+.ch-hero-lede strong {+ color: var(--text, #fafafa);+ font-weight: 600;+}+.ch-hero-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 10px;+}++/* ── Buttons ───────────────────────────────────────────────────────────── */++.ch-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ padding: 10px 18px;+ border: 1px solid var(--ch-border-strong);+ border-radius: 10px;+ background: var(--ch-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;+}+.ch-btn:hover {+ background: var(--ch-surface-3);+ transform: translateY(-1px);+}+.ch-btn:active {+ transform: translateY(0);+}+.ch-btn:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 2px;+}+.ch-btn[disabled] {+ opacity: 0.45;+ cursor: not-allowed;+ transform: none;+}+.ch-btn--primary {+ background: var(--ch-accent);+ border-color: var(--ch-accent);+ color: var(--ch-accent-ink);+}+.ch-btn--primary:hover {+ background: color-mix(in srgb, var(--ch-accent) 86%, white);+}+.ch-btn--ghost {+ background: transparent;+ border-color: var(--ch-border);+}++.ch-icon-btn {+ display: inline-grid;+ place-items: center;+ width: 38px;+ height: 38px;+ border: 1px solid var(--ch-border-strong);+ border-radius: 10px;+ background: var(--ch-surface-2);+ color: inherit;+ font-size: 14px;+ line-height: 1;+ cursor: pointer;+ transition:+ background 0.16s ease,+ border-color 0.16s ease,+ transform 0.16s ease,+ opacity 0.16s ease;+}+.ch-icon-btn:hover:not([disabled]) {+ background: var(--ch-surface-3);+ transform: translateY(-1px);+}+.ch-icon-btn:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 2px;+}+.ch-icon-btn[disabled] {+ opacity: 0.4;+ cursor: not-allowed;+}+.ch-icon-btn--play {+ background: var(--ch-accent);+ border-color: var(--ch-accent);+ color: var(--ch-accent-ink);+ font-size: 15px;+}+.ch-icon-btn--play:hover:not([disabled]) {+ background: color-mix(in srgb, var(--ch-accent) 86%, white);+}+.ch-icon-btn.is-on {+ border-color: var(--ch-accent);+ color: var(--ch-accent);+}+.ch-icon-btn--xs {+ width: 28px;+ height: 28px;+ border-radius: 8px;+ font-size: 12px;+}+.ch-icon-btn--danger:hover:not([disabled]) {+ border-color: var(--ch-err);+ color: var(--ch-err);+}++/* ── Layout ────────────────────────────────────────────────────────────── */++.ch-body {+ display: grid;+ grid-template-columns: minmax(300px, 380px) minmax(0, 1fr);+ gap: clamp(20px, 3vw, 36px);+ align-items: start;+}+@media (max-width: 940px) {+ .ch-body {+ grid-template-columns: 1fr;+ }+}++.ch-stage-col {+ position: sticky;+ top: 84px;+ display: grid;+ gap: 12px;+}+@media (max-width: 940px) {+ .ch-stage-col {+ position: static;+ }+}++/* ── Stage ─────────────────────────────────────────────────────────────── */++.ch-stage-card {+ border: 1px solid var(--ch-border);+ border-radius: var(--ch-radius);+ background: var(--ch-surface);+ overflow: hidden;+}+.ch-stage {+ position: relative;+ aspect-ratio: 3 / 4;+ background:+ radial-gradient(120% 90% at 50% 8%, var(--ch-surface-2), transparent 70%),+ var(--ch-surface);+ display: grid;+ place-items: center;+}+.ch-stage canvas {+ display: block;+ width: 100%;+ height: 100%;+}+.ch-stage-empty,+.ch-stage-loading,+.ch-stage-error {+ position: absolute;+ inset: 0;+ display: grid;+ place-content: center;+ justify-items: center;+ gap: 8px;+ padding: 24px;+ text-align: center;+}+.ch-stage-empty-icon {+ font-size: 34px;+ opacity: 0.75;+}+.ch-stage-empty-title,+.ch-stage-error-title {+ margin: 0;+ font-size: 15px;+ font-weight: 600;+}+.ch-stage-empty-body,+.ch-stage-error-body {+ margin: 0;+ max-width: 30ch;+ font-size: 13px;+ line-height: 1.55;+ color: var(--ch-muted);+}+.ch-stage-loading p {+ margin: 0;+ font-size: 13px;+ color: var(--ch-muted);+}+.ch-spinner {+ width: 26px;+ height: 26px;+ border: 2px solid var(--ch-border-strong);+ border-top-color: var(--ch-accent);+ border-radius: 50%;+ animation: ch-spin 0.8s linear infinite;+}+@keyframes ch-spin {+ to {+ transform: rotate(360deg);+ }+}+@media (prefers-reduced-motion: reduce) {+ .ch-spinner {+ animation-duration: 2.4s;+ }+}++.ch-stage-badge {+ position: absolute;+ left: 10px;+ bottom: 10px;+ margin: 0;+ padding: 5px 10px;+ border: 1px solid var(--ch-border);+ border-radius: 999px;+ background: color-mix(in srgb, var(--bg, #000) 62%, transparent);+ backdrop-filter: blur(8px);+ font-size: 11.5px;+ letter-spacing: 0.01em;+ color: var(--ch-muted);+ pointer-events: none;+}++/* ── Transport + timeline ──────────────────────────────────────────────── */++.ch-transport {+ padding: 12px 14px 14px;+ border-top: 1px solid var(--ch-border);+ display: grid;+ gap: 10px;+}+.ch-transport-row {+ display: flex;+ align-items: center;+ gap: 8px;+}+.ch-time {+ margin: 0 0 0 auto;+ font-size: 13px;+ font-variant-numeric: tabular-nums;+ color: var(--ch-muted);+}+.ch-time-sep {+ opacity: 0.5;+}++.ch-timeline {+ position: relative;+ height: 44px;+ border: 1px solid var(--ch-border);+ border-radius: 10px;+ background: var(--ch-surface-2);+ overflow: hidden;+ cursor: pointer;+ touch-action: none;+}+.ch-timeline:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 2px;+}+.ch-timeline-track {+ display: flex;+ height: 100%;+ width: 100%;+}+.ch-seg {+ position: relative;+ min-width: 0;+ height: 100%;+ padding: 0 4px;+ border: 0;+ border-right: 1px solid var(--ch-border);+ background: transparent;+ color: var(--ch-muted);+ font: inherit;+ font-size: 11px;+ display: grid;+ place-items: center;+ gap: 1px;+ cursor: pointer;+ overflow: hidden;+ transition:+ background 0.18s ease,+ color 0.18s ease;+}+.ch-seg:last-child {+ border-right: 0;+}+.ch-seg:hover {+ background: var(--ch-surface-3);+ color: var(--text, #fafafa);+}+.ch-seg:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: -2px;+}+.ch-seg.is-active {+ background: color-mix(in srgb, var(--ch-accent) 24%, transparent);+ color: var(--text, #fafafa);+}+.ch-seg-icon {+ font-size: 13px;+ line-height: 1;+}+.ch-seg-label {+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ letter-spacing: 0.01em;+}+.ch-playhead {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 2px;+ background: var(--ch-accent);+ box-shadow: 0 0 8px color-mix(in srgb, var(--ch-accent) 60%, transparent);+ pointer-events: none;+ transform: translateX(-1px);+}+.ch-playhead::before {+ content: '';+ position: absolute;+ top: -1px;+ left: 50%;+ width: 9px;+ height: 9px;+ border-radius: 50%;+ background: var(--ch-accent);+ transform: translateX(-50%);+}+.ch-timeline-empty {+ margin: 0;+ font-size: 12px;+ color: var(--ch-muted);+}++.ch-shortcuts p {+ margin: 0;+ font-size: 12px;+ color: var(--ch-muted);+}+.ch-shortcuts kbd {+ display: inline-block;+ padding: 1px 6px;+ border: 1px solid var(--ch-border-strong);+ border-bottom-width: 2px;+ border-radius: 5px;+ background: var(--ch-surface-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+}++/* ── Section heads ─────────────────────────────────────────────────────── */++.ch-section-head {+ margin: 0 0 14px;+}+.ch-section-head--tight {+ margin-top: 34px;+}+.ch-section-head h2 {+ margin: 0 0 6px;+ font-size: clamp(19px, 2.4vw, 23px);+ letter-spacing: -0.02em;+ font-weight: 640;+ scroll-margin-top: 84px;+}+.ch-section-head p {+ margin: 0;+ max-width: 68ch;+ font-size: 13.5px;+ line-height: 1.6;+ color: var(--ch-muted);+}++/* ── Presets ───────────────────────────────────────────────────────────── */++.ch-presets {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));+ gap: 10px;+}+.ch-preset {+ display: grid;+ gap: 7px;+ padding: 13px 14px;+ border: 1px solid var(--ch-border);+ border-radius: 12px;+ background: var(--ch-surface);+ color: inherit;+ font: inherit;+ text-align: left;+ cursor: pointer;+ transition:+ background 0.16s ease,+ border-color 0.16s ease,+ transform 0.16s ease;+}+.ch-preset:hover {+ background: var(--ch-surface-2);+ border-color: var(--ch-border-strong);+ transform: translateY(-1px);+}+.ch-preset:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 2px;+}+.ch-preset-head {+ display: flex;+ align-items: baseline;+ gap: 8px;+}+.ch-preset-name {+ font-size: 14.5px;+ font-weight: 620;+}+.ch-preset-time {+ margin-left: auto;+ font-size: 11.5px;+ font-variant-numeric: tabular-nums;+ color: var(--ch-muted);+}+.ch-preset-blurb {+ font-size: 12.5px;+ line-height: 1.5;+ color: var(--ch-muted);+}+.ch-preset-beats {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 5px;+ font-size: 11px;+ color: var(--ch-muted);+}+.ch-preset-beat {+ padding: 2px 7px;+ border: 1px solid var(--ch-border);+ border-radius: 999px;+ background: var(--ch-surface-2);+ white-space: nowrap;+}+.ch-preset-arrow {+ opacity: 0.5;+}++/* ── Routine bar ───────────────────────────────────────────────────────── */++.ch-routine-bar {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: 12px;+ margin-bottom: 12px;+}+.ch-field {+ display: grid;+ gap: 5px;+ min-width: 0;+}+.ch-field--grow {+ flex: 1 1 220px;+}+.ch-field-label {+ font-size: 11.5px;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--ch-muted);+}+.ch-input,+.ch-select {+ width: 100%;+ padding: 9px 10px;+ border: 1px solid var(--ch-border-strong);+ border-radius: 9px;+ background: var(--ch-surface-2);+ color: inherit;+ font: inherit;+ font-size: 13px;+}+.ch-input:focus-visible,+.ch-select:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 1px;+}+.ch-select--sm {+ padding: 6px 8px;+ font-size: 12px;+}+.ch-select--xs {+ padding: 5px 6px;+ font-size: 11.5px;+ width: auto;+}+.ch-routine-meta {+ margin: 0 0 9px;+ font-size: 12.5px;+ color: var(--ch-muted);+ font-variant-numeric: tabular-nums;+}+.ch-routine-meta code {+ padding: 1px 5px;+ border-radius: 5px;+ background: var(--ch-surface-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11.5px;+}++/* ── Steps ─────────────────────────────────────────────────────────────── */++.ch-steps {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: 8px;+}+.ch-step {+ display: grid;+ grid-template-columns: auto auto auto minmax(0, 1fr) auto auto;+ align-items: center;+ gap: 10px;+ padding: 9px 12px;+ border: 1px solid var(--ch-border);+ border-radius: 11px;+ background: var(--ch-surface);+ transition:+ border-color 0.16s ease,+ background 0.16s ease,+ opacity 0.16s ease;+}+.ch-step:hover {+ border-color: var(--ch-border-strong);+}+.ch-step.is-active {+ border-color: var(--ch-accent);+ background: color-mix(in srgb, var(--ch-accent) 10%, var(--ch-surface));+}+.ch-step.is-dragging {+ opacity: 0.45;+}+.ch-step.is-drop-target {+ border-color: var(--ch-accent);+ box-shadow: inset 0 2px 0 var(--ch-accent);+}+.ch-step-grip {+ color: var(--ch-muted);+ cursor: grab;+ font-size: 13px;+ line-height: 1;+ user-select: none;+}+.ch-step-grip:active {+ cursor: grabbing;+}+.ch-step-num {+ min-width: 18px;+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ color: var(--ch-muted);+ text-align: right;+}+.ch-step-icon {+ font-size: 17px;+ line-height: 1;+}+.ch-step-body {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px;+ min-width: 0;+}+.ch-step-slot {+ font-size: 13.5px;+ font-weight: 580;+ letter-spacing: -0.01em;+}+.ch-step-clip {+ min-width: 0;+ flex: 1 1 130px;+}+.ch-step-pin {+ padding: 1px 7px;+ border: 1px solid var(--ch-border);+ border-radius: 999px;+ background: var(--ch-surface-2);+ font-size: 10.5px;+ letter-spacing: 0.03em;+ text-transform: uppercase;+ color: var(--ch-muted);+}+.ch-step-timing {+ display: flex;+ align-items: center;+ gap: 8px;+}+.ch-step-hold {+ display: flex;+ align-items: center;+ gap: 7px;+}+.ch-range {+ width: 88px;+ accent-color: var(--ch-accent);+ cursor: pointer;+}+.ch-range:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 3px;+}+.ch-step-secs {+ min-width: 34px;+ font-size: 11.5px;+ font-variant-numeric: tabular-nums;+ color: var(--ch-muted);+}+.ch-step-actions {+ display: flex;+ gap: 4px;+}++@media (max-width: 720px) {+ .ch-step {+ grid-template-columns: auto auto minmax(0, 1fr) auto;+ row-gap: 8px;+ }+ .ch-step-grip {+ display: none;+ }+ .ch-step-timing {+ grid-column: 1 / -1;+ }+ .ch-range {+ width: 100%;+ flex: 1;+ }+ .ch-step-hold {+ flex: 1;+ }+}++.ch-empty {+ padding: 26px 20px;+ border: 1px dashed var(--ch-border-strong);+ border-radius: 12px;+ background: var(--ch-surface);+ text-align: center;+}+.ch-empty-title {+ margin: 0 0 5px;+ font-size: 14px;+ font-weight: 600;+}+.ch-empty-body {+ margin: 0;+ font-size: 13px;+ line-height: 1.55;+ color: var(--ch-muted);+}++/* ── Palette ───────────────────────────────────────────────────────────── */++.ch-palette {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(104px, 1fr));+ gap: 8px;+}+.ch-chip {+ position: relative;+ display: grid;+ gap: 6px;+ padding: 8px;+ border: 1px solid var(--ch-border);+ border-radius: 11px;+ background: var(--ch-surface);+ color: inherit;+ font: inherit;+ cursor: pointer;+ text-align: center;+ transition:+ background 0.16s ease,+ border-color 0.16s ease,+ transform 0.16s ease;+}+.ch-chip:hover {+ background: var(--ch-surface-2);+ border-color: var(--ch-accent);+ transform: translateY(-2px);+}+.ch-chip:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 2px;+}+.ch-chip-thumb {+ position: relative;+ display: grid;+ place-items: center;+ aspect-ratio: 1 / 1;+ border-radius: 8px;+ overflow: hidden;+ background: var(--ch-surface-2);+}+.ch-chip-thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}+.ch-chip-icon {+ position: absolute;+ font-size: 22px;+ opacity: 0.8;+}+.ch-chip-label {+ font-size: 12px;+ font-weight: 550;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.ch-chip-add {+ position: absolute;+ top: 6px;+ right: 6px;+ width: 20px;+ height: 20px;+ display: grid;+ place-items: center;+ border-radius: 50%;+ background: color-mix(in srgb, var(--bg, #000) 55%, transparent);+ backdrop-filter: blur(6px);+ font-size: 13px;+ line-height: 1;+ color: var(--ch-muted);+ opacity: 0;+ transition:+ opacity 0.16s ease,+ background 0.16s ease,+ color 0.16s ease;+}+.ch-chip:hover .ch-chip-add,+.ch-chip:focus-visible .ch-chip-add {+ opacity: 1;+ background: var(--ch-accent);+ color: var(--ch-accent-ink);+}++/* ── Ship ──────────────────────────────────────────────────────────────── */++.ch-ship {+ display: grid;+ gap: 12px;+}+.ch-save {+ display: grid;+ gap: 12px;+ padding: 15px 16px;+ border: 1px solid var(--ch-border);+ border-radius: 12px;+ background: var(--ch-surface);+}+.ch-save-lede {+ margin: 0;+ font-size: 13.5px;+ line-height: 1.6;+ color: var(--ch-muted);+}+.ch-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}+.ch-save-status {+ margin: 0;+ min-height: 1em;+ font-size: 12.5px;+ line-height: 1.5;+ color: var(--ch-muted);+}+.ch-save-status.is-ok {+ color: var(--ch-ok);+}+.ch-save-status.is-err {+ color: var(--ch-err);+}+.ch-save-status a,+.ch-save-status code {+ color: inherit;+}++.ch-saved {+ border-top: 1px solid var(--ch-border);+ padding-top: 12px;+}+.ch-saved-title {+ margin: 0 0 8px;+ font-size: 11.5px;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--ch-muted);+}+.ch-saved-list {+ display: flex;+ flex-wrap: wrap;+ gap: 7px;+}+.ch-saved-chip {+ display: grid;+ gap: 1px;+ padding: 7px 11px;+ border: 1px solid var(--ch-border-strong);+ border-radius: 9px;+ background: var(--ch-surface-2);+ color: inherit;+ font: inherit;+ text-align: left;+ cursor: pointer;+ transition:+ background 0.16s ease,+ border-color 0.16s ease;+}+.ch-saved-chip:hover {+ background: var(--ch-surface-3);+ border-color: var(--ch-accent);+}+.ch-saved-chip:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 2px;+}+.ch-saved-name {+ font-size: 13px;+ font-weight: 560;+}+.ch-saved-meta {+ font-size: 11px;+ color: var(--ch-muted);+ font-variant-numeric: tabular-nums;+}++.ch-export {+ border: 1px solid var(--ch-border);+ border-radius: 12px;+ background: var(--ch-surface);+ padding: 13px 16px;+}+.ch-export > summary {+ font-size: 13.5px;+ font-weight: 560;+ cursor: pointer;+ list-style: none;+}+.ch-export > summary::-webkit-details-marker {+ display: none;+}+.ch-export > summary::before {+ content: '▸ ';+ color: var(--ch-muted);+}+.ch-export[open] > summary::before {+ content: '▾ ';+}+.ch-export > summary:focus-visible {+ outline: 2px solid var(--ch-accent);+ outline-offset: 2px;+}+.ch-export-lede {+ margin: 10px 0;+ font-size: 12.5px;+ line-height: 1.6;+ color: var(--ch-muted);+}+.ch-export-lede code,+.ch-footnote code {+ padding: 1px 5px;+ border-radius: 5px;+ background: var(--ch-surface-2);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11.5px;+}+.ch-code {+ margin: 0 0 12px;+ padding: 12px;+ border: 1px solid var(--ch-border);+ border-radius: 10px;+ background: var(--ch-surface-2);+ overflow-x: auto;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+ line-height: 1.55;+ max-height: 320px;+}++.ch-footnote {+ margin-top: 34px;+ padding-top: 18px;+ border-top: 1px solid var(--ch-border);+}+.ch-footnote p {+ margin: 0;+ max-width: 72ch;+ font-size: 12.5px;+ line-height: 1.65;+ color: var(--ch-muted);+}+.ch-footnote a,+.ch-empty-body a {+ color: var(--ch-accent);+}++@media (prefers-reduced-motion: reduce) {+ .ch-btn,+ .ch-icon-btn,+ .ch-preset,+ .ch-chip,+ .ch-step,+ .ch-seg {+ transition: none;+ }+ .ch-btn:hover,+ .ch-icon-btn:hover,+ .ch-preset:hover,+ .ch-chip:hover {+ transform: none;+ }+}diff --git a/src/agent-avatar.js b/src/agent-avatar.jsindex cccaf9de8..071c9e039 100644--- a/src/agent-avatar.js+++ b/src/agent-avatar.js@@ -22,6 +22,7 @@import { ACTION_TYPES } from './agent-protocol.js';import { Vector3, Box3, MathUtils, PositionalAudio } from 'three';import { resolveSlot, resolveHint, DEFAULT_ANIMATION_MAP } from './runtime/animation-slots.js';+import { RoutinePlayer, normalizeRoutine, slugify } from './runtime/choreography.js';import { ElevenLabsTTS } from './runtime/speech.js';import { LipSyncAnalyser, VISEMES as LIPSYNC_VISEMES } from './lip-sync-analyser.js';import { resolveMorphTargets, MORPH_ALIASES, ARKIT_VISEMES } from './runtime/arkit52.js';@@ -211,6 +212,11 @@ export class AgentAvatar {this._animationMap = {};this._warnedSlots = new Set();+ // Named gesture routines (from meta.choreographies) and the one currently+ // performing, if any. Driven from the same frame hook as the emotion blend.+ this._routines = new Map();+ this._routinePlayer = null;+// Streak tracking for empathy injectionthis._errorStreak = 0;this._firstEncounter = true;@@ -331,6 +337,7 @@ export class AgentAvatar {detach() {clearTimeout(this._firstEncounterTimer);clearTimeout(this._playAmClipTimer);+ this.stopChoreography();if (this.viewer._afterAnimateHooks) {const idx = this.viewer._afterAnimateHooks.indexOf(this._tickBound);if (idx !== -1) this.viewer._afterAnimateHooks.splice(idx, 1);@@ -453,15 +460,105 @@ export class AgentAvatar {return resolveSlot(slot, this._animationMap);}+ // ── Choreography ──────────────────────────────────────────────────────────+ //+ // A routine is a named sequence of gesture slots with per-step timing+ // (src/runtime/choreography.js). The timing engine is shared with the+ // /choreograph studio, so what an owner composed there is frame-for-frame+ // what their agent performs here; this class only supplies the "play one+ // step" side effect and the frame deltas.++ /**+ * Register the agent's saved routines (manifest `choreographies`, stored at+ * meta.choreographies). Invalid entries are dropped rather than thrown: one+ * bad routine must not cost the agent the rest of its body language.+ * @param {Array} list+ */+ setChoreographies(list) {+ this._routines = new Map();+ for (const entry of Array.isArray(list) ? list : []) {+ try {+ const routine = normalizeRoutine(entry);+ this._routines.set(routine.id, routine);+ } catch (err) {+ log.warn(`[AgentAvatar] skipping invalid choreography: ${err.message}`);+ }+ }+ return this._routines.size;+ }++ /** The agent's registered routines, newest registration order. */+ getChoreographies() {+ return [...(this._routines?.values() ?? [])];+ }++ /**+ * Perform a routine: either one registered by id/name, or a literal routine+ * object (what a shared /choreograph link carries).+ *+ * @param {string|object} nameOrRoutine+ * @param {{loop?:boolean, onStep?:Function, onEnd?:Function}} [opts]+ * @returns {boolean} false when no such routine exists+ */+ playChoreography(nameOrRoutine, opts = {}) {+ let routine = null;+ if (typeof nameOrRoutine === 'string') {+ routine = this._routines?.get(slugify(nameOrRoutine)) ?? null;+ if (!routine) {+ log.warn(`[AgentAvatar] no choreography named "${nameOrRoutine}"`);+ return false;+ }+ } else {+ try {+ routine = normalizeRoutine(nameOrRoutine);+ } catch (err) {+ log.warn(`[AgentAvatar] invalid choreography: ${err.message}`);+ return false;+ }+ }++ this.stopChoreography();+ this._routinePlayer = new RoutinePlayer(routine, {+ loop: opts.loop ?? routine.loop,+ onStep: (step) => {+ // The step owns the stage for exactly its own span, so the one-shot+ // revert never fires mid-routine and steal the next step's crossfade.+ this._playSlot(step.slot, step.hold / (step.speed || 1), step.clip);+ opts.onStep?.(step);+ },+ onEnd: () => {+ this._routinePlayer = null;+ opts.onEnd?.();+ },+ });+ this._routinePlayer.start();+ return true;+ }++ /** Stop a routine mid-performance. The current gesture reverts as usual. */+ stopChoreography() {+ this._routinePlayer?.stop();+ this._routinePlayer = null;+ }++ /** True while a routine is performing. */+ get isPerforming() {+ return Boolean(this._routinePlayer?.playing);+ }+/*** Play a gesture by slot name, routing through the external animation manager.* Falls back to embedded clip search (_triggerOneShot) if the clip isn't in the library.* Warns once per missing clip name.* @param {string} slot — e.g. 'celebrate', 'think'* @param {number} [duration]+ * @param {string|null} [clipOverride] — play this exact clip instead of the+ * slot's resolved one. Used by choreography steps that pin a clip; the slot+ * is still what the fallbacks below key off, so a bad pin degrades to the+ * slot's default rather than to nothing.*/- _playSlot(slot, duration = 1.5) {- const clipName = this._resolveSlot(slot);+ _playSlot(slot, duration = 1.5, clipOverride = null) {+ const clipName = clipOverride || this._resolveSlot(slot);this._isPlayingOneShot = true;this._oneShotAction = slot;this._oneShotDuration = duration;@@ -837,8 +934,14 @@ export class AgentAvatar {}}- // Stage 3: Emotion-threshold gesture triggers (routed through slot map)- if (!this._isPlayingOneShot) {+ // Stage 2b: Advance a performing routine. Runs after the one-shot timer so+ // a step whose gesture just expired is replaced on the same frame.+ this._routinePlayer?.update(dt);++ // Stage 3: Emotion-threshold gesture triggers (routed through slot map).+ // A routine outranks them: an owner who composed a performance did not ask+ // for a stray celebrate to cut into it at the seam between two steps.+ if (!this._isPlayingOneShot && !this._routinePlayer) {const w = this._emotion;if (w.celebration > 0.6) {this._playSlot('celebrate', 2.0);diff --git a/src/animations-live-preview.js b/src/animations-live-preview.jsindex ff22dad5d..e3e3b67ad 100644--- a/src/animations-live-preview.js+++ b/src/animations-live-preview.js@@ -34,6 +34,7 @@ export class AnimationLivePreview {this._container = null;this._action = null;this._activeDef = null;+ this._fading = []; // crossfade sources awaiting retirementthis._raf = 0;this._lastT = 0;this._playToken = 0;@@ -208,19 +209,34 @@ export class AnimationLivePreview {// Frame the figure's full motion envelope: sample the clip at a few points,// union the bone boxes, and lock the camera for the whole loop so walks and// flips stay in frame without camera chase.+ //+ // Accepts several clips, which is what a choreography needs: framing each+ // step on its own would jog the camera at every cut, so a routine unions the+ // envelopes of all of its clips once and holds that frame for the whole+ // performance._frameCamera(bound) {const THREE = this._three;+ const clips = Array.isArray(bound) ? bound.filter(Boolean) : [bound];+ if (!clips.length) return;const box = new THREE.Box3();const v = new THREE.Vector3();- const probe = this._mixer.clipAction(bound);- probe.play();const samples = [0.05, 0.3, 0.55, 0.8];- for (const s of samples) {- this._mixer.setTime(bound.duration * s);- this._model.updateMatrixWorld(true);- for (const b of this._bones) box.expandByPoint(b.getWorldPosition(v));+ for (const clip of clips) {+ this._mixer.stopAllAction();+ const probe = this._mixer.clipAction(clip);+ probe.play();+ for (const s of samples) {+ this._mixer.setTime(clip.duration * s);+ this._model.updateMatrixWorld(true);+ for (const b of this._bones) box.expandByPoint(b.getWorldPosition(v));+ }+ probe.stop();}+ // Sampling drove the skeleton; put it back before the caller starts the+ // real action, so a clip that animates only the upper body does not+ // inherit a probe's legs.this._mixer.setTime(0);+ this._restoreRestPose();box.expandByVector(new THREE.Vector3(0.24, 0.15, 0.24));box.min.y = Math.min(box.min.y, 0);const center = box.getCenter(new THREE.Vector3());@@ -243,6 +259,16 @@ export class AnimationLivePreview {this._keyLight.target.updateMatrixWorld();}+ /** Stop every crossfade source whose fade has elapsed. */+ _retireFaded(incoming) {+ const now = performance.now();+ this._fading = this._fading.filter((entry) => {+ if (entry.action === incoming || now < entry.until) return true;+ entry.action.stop();+ return false;+ });+ }+_resizeToContainer() {if (!this._container || !this._renderer) return;const w = this._container.clientWidth || 300;@@ -266,14 +292,39 @@ export class AnimationLivePreview {this._renderer.render(this._scene, this._camera);};+ /**+ * Bind clips ahead of time. A choreography calls this once for its whole+ * step list so the first cut is not the first fetch: without it, step two+ * arrives mid-performance and the stage stutters exactly where the routine+ * was supposed to flow.+ *+ * Failures are swallowed per clip — one unbindable clip must not stop the+ * routine from being previewable — and reported by the resolved array's+ * `null` entries.+ *+ * @param {Array<{id:string, source:string, url?:string}>} defs+ * @returns {Promise<Array<object|null>>} bound clips, index-aligned with defs+ */+ async prepare(defs) {+ await this._boot();+ return Promise.all(+ (defs || []).map((def) => this._bindClip(def).catch(() => null)),+ );+ }+/*** Mount the shared canvas into `container` and play `def`'s clip.* Any previous preview stops. Resolves once playing; rejects on load or* retarget failure (the caller shows its fallback).*+ * `opts.crossfade` blends out of whatever is already playing instead of+ * hard-cutting, which is what turns a list of clips into a performance.+ * `opts.frameWith` locks the camera to the union of several clips' motion+ * envelopes, so it does not jog at every cut.+ ** @param {HTMLElement} container* @param {{id:string, source:string, url?:string, loop?:boolean}} def- * @param {{ speed?: number, onFrame?: (t:number,d:number)=>void }} [opts]+ * @param {{ speed?: number, crossfade?: number, frameWith?: Array, onFrame?: (t:number,d:number)=>void }} [opts]*/async play(container, def, opts = {}) {const token = ++this._playToken;@@ -281,36 +332,68 @@ export class AnimationLivePreview {const bound = await this._bindClip(def);if (token !== this._playToken) return; // superseded while loading- this.stop({ keepBoot: true });- this._container = container;- container.appendChild(this._renderer.domElement);- this._resizeToContainer();+ const THREE = this._three;+ // A crossfade is only possible into a stage that is already rendering this+ // clip's neighbour; anything else (first play, a different container) is a+ // cold start and takes the full reset path.+ const blending =+ opts.crossfade > 0 && this._action && this._container === container && this._raf;+ const previous = blending ? this._action : null;++ if (!blending) {+ this.stop({ keepBoot: true });+ this._container = container;+ container.appendChild(this._renderer.domElement);+ this._resizeToContainer();+ this._restoreRestPose();+ } else {+ // A pending one-shot replay belongs to the outgoing clip.+ this._mixer.removeEventListener?.('finished', this._replay);+ this._replay = null;+ }++ // Frame before the incoming action starts: sampling drives the skeleton,+ // and a routine frames once for all of its clips rather than per step.+ if (!blending || opts.frameWith) {+ this._frameCamera(opts.frameWith?.length ? opts.frameWith : bound);+ }- this._restoreRestPose();const action = this._mixer.clipAction(bound);- const THREE = this._three;+ action.reset();if (def.loop === false) {action.setLoop(THREE.LoopOnce, 0);action.clampWhenFinished = true;// One-shots replay on a beat so a hovering user sees the motion again.- this._mixer.removeEventListener?.('finished', this._replay);- this._replay = () => {- action.reset().play();- };- this._mixer.addEventListener('finished', this._replay);+ // A sequenced step does not: the routine decides when the next cut is.+ if (!opts.crossfade) {+ this._mixer.removeEventListener?.('finished', this._replay);+ this._replay = () => {+ action.reset().play();+ };+ this._mixer.addEventListener('finished', this._replay);+ }} else {action.setLoop(THREE.LoopRepeat, Infinity);}action.timeScale = opts.speed ?? 1;- action.play();+ if (previous && previous !== action) {+ action.play();+ previous.crossFadeTo(action, opts.crossfade, false);+ // A faded-out action keeps being evaluated at weight 0 forever unless it+ // is stopped. Over a looping routine that is a slow leak of frame time,+ // so retire each one as soon as its fade is spent.+ this._retireFaded(action);+ this._fading.push({ action: previous, until: performance.now() + opts.crossfade * 1000 });+ } else {+ action.setEffectiveWeight(1);+ action.play();+ }this._action = action;this._activeDef = def;this._paused = false;this._onFrame = opts.onFrame || null;- this._frameCamera(bound);this._lastT = performance.now();- cancelAnimationFrame(this._raf);- this._raf = requestAnimationFrame(this._loop);+ if (!this._raf) this._raf = requestAnimationFrame(this._loop);}/** Detach the canvas and halt rendering. Cheap — the engine stays warm. */@@ -325,6 +408,7 @@ export class AnimationLivePreview {if (this._mixer) this._mixer.stopAllAction();this._action = null;this._activeDef = null;+ this._fading = [];this._onFrame = null;if (this._renderer?.domElement?.parentNode) {this._renderer.domElement.parentNode.removeChild(this._renderer.domElement);diff --git a/src/choreograph-page.js b/src/choreograph-page.jsnew file mode 100644index 000000000..8c14ece52--- /dev/null+++ b/src/choreograph-page.js@@ -0,0 +1,984 @@+// /choreograph: compose agent gestures into a timed routine.+//+// The page owns editing and presentation only. Everything about what a routine+// *is* — validation, timing, the URL wire format, playback order — comes from+// src/runtime/choreography.js, the same module the agents API validates with+// and the avatar runtime performs with. That is what makes the preview here+// honest: the timeline is not an approximation of what the agent will do, it is+// driven by the identical player.+//+// The 3D stage reuses the gallery's shared engine (one renderer, one avatar,+// moved into the stage on demand) and nothing 3D loads until the first play.++import { SLOTS, DEFAULT_ANIMATION_MAP } from './runtime/animation-slots.js';+import {+ DEFAULT_HOLD,+ MAX_HOLD,+ MAX_STEPS,+ MIN_HOLD,+ PRESET_ROUTINES,+ RoutinePlayer,+ decodeRoutine,+ encodeRoutine,+ normalizeRoutine,+ resolveStepClip,+ routineDuration,+ slugify,+ stepOffsets,+} from './runtime/choreography.js';+import { curate, CATEGORIES } from './animation-presets.js';++const MANIFEST_URL = '/animations/manifest.json';+const THUMB_BASE = '/animations/thumbs';+/** Blend between steps. Long enough to read as a transition, short enough that+ * a 1s beat is still mostly the gesture itself. */+const CROSSFADE = 0.28;++/** One line per slot: what this beat reads as inside a performance. */+const SLOT_ICONS = {+ idle: '🧍',+ wave: '👋',+ nod: '🙂',+ shake: '🙅',+ think: '🤔',+ celebrate: '🎉',+ concern: '😟',+ bow: '🙇',+ point: '👉',+ shrug: '🤷',+ fidget: '😌',+ dance: '💃',+ inspect: '🔍',+ present: '🖐️',+ sign: '✍️',+ curiosity: '👀',+ patience: '⏳',+ manipulate: '📦',+ conjure: '✨',+};++const $ = (sel, root = document) => root.querySelector(sel);+const el = (role, root = document) => root.querySelector(`[data-role="${role}"]`);++const state = {+ manifest: [],+ byName: new Map(),+ /** Working routine: always normalized, always the source of truth. */+ name: 'Welcome',+ steps: [],+ loop: false,+ player: null,+ preview: null,+ raf: 0,+ lastT: 0,+ stagedClip: null, // clip currently mounted on the stage+ agents: null, // null = not fetched, [] = signed out or none+ dragIndex: -1,+};++/* ── helpers ───────────────────────────────────────────────────────────── */++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);+}++/** The working routine as the rest of the platform sees it, or null if empty. */+function currentRoutine() {+ if (!state.steps.length) return null;+ try {+ return normalizeRoutine({ name: state.name, steps: state.steps, loop: state.loop });+ } catch {+ return null;+ }+}++function clipLabel(clipName) {+ return state.byName.get(clipName)?.label || clipName;+}++function stepClip(step) {+ return resolveStepClip(step, null);+}++/* ── data ──────────────────────────────────────────────────────────────── */++async function loadManifest() {+ try {+ const res = await fetch(MANIFEST_URL, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`${MANIFEST_URL} responded ${res.status}`);+ const manifest = await res.json();+ state.manifest = Array.isArray(manifest) ? manifest : [];+ state.byName = new Map(state.manifest.map((c) => [c.name, c]));+ } catch (err) {+ // The clip library only supplies labels, posters and the per-step clip+ // picker. Composing, previewing and saving all work without it, so this+ // degrades to slot names rather than taking the page down.+ setStatus(`Clip labels unavailable (${err.message}). Slot names still work.`);+ }+ renderPalette();+ renderSteps();+}++/**+ * The signed-in user's agents. A 401 is the ordinary signed-out case, not an+ * error: the whole page works without an account.+ */+async function loadAgents() {+ try {+ const res = await fetch('/api/agents', {+ credentials: 'include',+ headers: { accept: 'application/json' },+ });+ state.agents = res.ok ? ((await res.json()).agents ?? []) : [];+ } catch {+ state.agents = [];+ }+ renderSave();+}++/* ── render: presets ───────────────────────────────────────────────────── */++function renderPresets() {+ el('presets').innerHTML = PRESET_ROUTINES.map((preset) => {+ const seconds = routineDuration(normalizeRoutine(preset));+ const beats = preset.steps+ .map((s) => `<span class="ch-preset-beat">${SLOT_ICONS[s.slot] || '🎞️'} ${escapeHtml(s.slot)}</span>`)+ .join('<span class="ch-preset-arrow" aria-hidden="true">→</span>');+ return `+ <button type="button" class="ch-preset" role="listitem" data-preset="${escapeHtml(preset.id)}">+ <span class="ch-preset-head">+ <span class="ch-preset-name">${escapeHtml(preset.name)}</span>+ <span class="ch-preset-time">${seconds}s${preset.loop ? ' · loops' : ''}</span>+ </span>+ <span class="ch-preset-blurb">${escapeHtml(preset.blurb)}</span>+ <span class="ch-preset-beats">${beats}</span>+ </button>`;+ }).join('');+}++/* ── render: palette ───────────────────────────────────────────────────── */++function renderPalette() {+ el('palette').innerHTML = SLOTS.map((slot) => {+ const clip = DEFAULT_ANIMATION_MAP[slot];+ return `+ <button type="button" class="ch-chip" role="listitem" data-slot="${escapeHtml(slot)}"+ title="Add ${escapeHtml(slot)} (${escapeHtml(clipLabel(clip))})">+ <span class="ch-chip-thumb">+ <span class="ch-chip-icon" aria-hidden="true">${SLOT_ICONS[slot] || '🎞️'}</span>+ <img src="${THUMB_BASE}/${encodeURIComponent(clip)}.webp" alt="" loading="lazy"+ decoding="async" width="160" height="160" />+ </span>+ <span class="ch-chip-label">${escapeHtml(slot)}</span>+ <span class="ch-chip-add" aria-hidden="true">+</span>+ </button>`;+ }).join('');+ // The emoji stands in until the poster paints, then gets out of the way.+ for (const img of el('palette').querySelectorAll('img')) {+ const icon = img.previousElementSibling;+ if (img.complete && img.naturalWidth > 0) icon?.remove();+ else {+ img.addEventListener('load', () => icon?.remove(), { once: true });+ img.addEventListener('error', () => img.remove(), { once: true });+ }+ }+}++/* ── render: steps ─────────────────────────────────────────────────────── */++let clipOptionsHtml = '';+function buildClipOptions() {+ if (clipOptionsHtml) return clipOptionsHtml;+ 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));+ clipOptionsHtml = 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('');+ return clipOptionsHtml;+}++function stepRowHtml(step, i) {+ const clip = stepClip(step);+ const isDefault = !step.clip;+ return `+ <li class="ch-step" data-index="${i}" draggable="true">+ <span class="ch-step-grip" aria-hidden="true" title="Drag to reorder">⠿</span>+ <span class="ch-step-num">${i + 1}</span>+ <span class="ch-step-icon" aria-hidden="true">${SLOT_ICONS[step.slot] || '🎞️'}</span>+ <span class="ch-step-body">+ <span class="ch-step-slot">${escapeHtml(step.slot)}</span>+ <label class="ch-step-clip">+ <span class="ch-sr-only">Clip for step ${i + 1}</span>+ <select class="ch-select ch-select--sm" data-act="clip" data-index="${i}">+ ${buildClipOptions()}+ </select>+ </label>+ ${isDefault ? '' : '<span class="ch-step-pin" title="This step pins a clip instead of following the agent\'s own mapping">pinned</span>'}+ </span>+ <span class="ch-step-timing">+ <label class="ch-step-hold">+ <span class="ch-sr-only">Hold for step ${i + 1}, in seconds</span>+ <input type="range" class="ch-range" data-act="hold" data-index="${i}"+ min="${MIN_HOLD}" max="${MAX_HOLD}" step="0.1" value="${step.hold}" />+ <output class="ch-step-secs">${step.hold.toFixed(1)}s</output>+ </label>+ <label class="ch-step-speed">+ <span class="ch-sr-only">Speed for step ${i + 1}</span>+ <select class="ch-select ch-select--xs" data-act="speed" data-index="${i}">+ ${[0.5, 0.75, 1, 1.25, 1.5, 2]+ .map(+ (s) =>+ `<option value="${s}"${s === step.speed ? ' selected' : ''}>${s}×</option>`,+ )+ .join('')}+ </select>+ </label>+ </span>+ <span class="ch-step-actions">+ <button type="button" class="ch-icon-btn ch-icon-btn--xs" data-act="up" data-index="${i}"+ title="Move up" aria-label="Move step ${i + 1} up"${i === 0 ? ' disabled' : ''}>↑</button>+ <button type="button" class="ch-icon-btn ch-icon-btn--xs" data-act="down" data-index="${i}"+ title="Move down" aria-label="Move step ${i + 1} down">↓</button>+ <button type="button" class="ch-icon-btn ch-icon-btn--xs ch-icon-btn--danger" data-act="remove"+ data-index="${i}" title="Remove" aria-label="Remove step ${i + 1}">✕</button>+ </span>+ <span class="ch-sr-only" data-role="step-clip-name">${escapeHtml(clipLabel(clip))}</span>+ </li>`;+}++function renderSteps() {+ const host = el('steps');+ const empty = el('steps-empty');+ host.innerHTML = state.steps.map(stepRowHtml).join('');+ host.hidden = !state.steps.length;+ empty.hidden = state.steps.length > 0;+ // Selects cannot carry their value through innerHTML, so set them after.+ for (const [i, step] of state.steps.entries()) {+ const select = host.querySelector(`select[data-act="clip"][data-index="${i}"]`);+ if (select) select.value = stepClip(step);+ }+ const last = host.querySelector('.ch-step:last-child [data-act="down"]');+ if (last) last.disabled = true;+ renderMeta();+ renderTimeline();+ renderExports();+}++function renderMeta() {+ const routine = currentRoutine();+ el('step-count').textContent = String(state.steps.length);+ const seconds = routine ? routineDuration(routine) : 0;+ el('meta-duration').textContent = seconds.toFixed(1);+ el('duration').textContent = seconds.toFixed(1);+ el('routine-id').textContent = slugify(state.name || 'routine');+ const hasSteps = state.steps.length > 0;+ for (const role of ['play', 'restart', 'loop']) el(role).disabled = !hasSteps;+ el('timeline-empty').hidden = hasSteps;+}++/* ── render: timeline ──────────────────────────────────────────────────── */++function renderTimeline() {+ const routine = currentRoutine();+ const track = el('timeline-track');+ const timeline = el('timeline');+ if (!routine) {+ track.innerHTML = '';+ el('playhead').hidden = true;+ timeline.setAttribute('aria-valuemax', '0');+ timeline.setAttribute('aria-valuenow', '0');+ timeline.setAttribute('aria-valuetext', 'Empty routine');+ return;+ }+ const total = routineDuration(routine) || 1;+ const active = state.player?.index ?? -1;+ track.innerHTML = routine.steps+ .map((step, i) => {+ const span = step.hold / (step.speed || 1);+ const pct = (span / total) * 100;+ return `+ <button type="button" class="ch-seg${i === active ? ' is-active' : ''}" style="width:${pct}%"+ data-seg="${i}" title="${escapeHtml(step.slot)} · ${span.toFixed(1)}s"+ aria-label="Jump to step ${i + 1}, ${escapeHtml(step.slot)}">+ <span class="ch-seg-icon" aria-hidden="true">${SLOT_ICONS[step.slot] || '🎞️'}</span>+ <span class="ch-seg-label">${escapeHtml(step.slot)}</span>+ </button>`;+ })+ .join('');+ timeline.setAttribute('aria-valuemax', String(total));+ renderPlayhead();+}++function renderPlayhead() {+ const head = el('playhead');+ const routine = currentRoutine();+ if (!routine || !state.player) {+ head.hidden = true;+ return;+ }+ const total = routineDuration(routine) || 1;+ const t = state.player.time;+ head.hidden = false;+ head.style.left = `${Math.min(100, (t / total) * 100)}%`;+ el('time').textContent = t.toFixed(1);+ const timeline = el('timeline');+ timeline.setAttribute('aria-valuenow', String(t));+ const step = routine.steps[state.player.index];+ timeline.setAttribute(+ 'aria-valuetext',+ step ? `${t.toFixed(1)} seconds, ${step.slot}` : `${t.toFixed(1)} seconds`,+ );+}++function highlightActive() {+ const active = state.player?.index ?? -1;+ for (const seg of el('timeline-track').querySelectorAll('.ch-seg')) {+ seg.classList.toggle('is-active', Number(seg.dataset.seg) === active);+ }+ for (const row of el('steps').querySelectorAll('.ch-step')) {+ row.classList.toggle('is-active', Number(row.dataset.index) === active);+ }+}++/* ── render: exports ───────────────────────────────────────────────────── */++function renderExports() {+ const routine = currentRoutine();+ const json = routine+ ? JSON.stringify({ choreographies: [routine] }, null, 2)+ : '// Add a step to see the payload.';+ $('code', el('json-code')).textContent = json;++ const id = routine?.id || 'routine';+ const snippet = routine+ ? `<agent-3d agent="YOUR_AGENT_ID"></agent-3d>\n\n<script type="module">\n const el = document.querySelector('agent-3d');\n // Saved on the agent, so it plays by name:\n el.playRoutine(${JSON.stringify(id)});\n<\/script>`+ : '// Add a step to see the snippet.';+ $('code', el('embed-code')).textContent = snippet;+ syncUrl();+}++function renderSave() {+ const panel = el('save-panel');+ const signedOut = el('save-signedout');+ const agents = state.agents;+ if (agents === null) {+ // Still loading: show neither rather than flashing "sign in" at someone+ // who is in fact signed in.+ panel.hidden = true;+ signedOut.hidden = true;+ return;+ }+ if (!agents.length) {+ panel.hidden = true;+ signedOut.hidden = false;+ return;+ }+ signedOut.hidden = true;+ panel.hidden = false;+ const select = el('agent-select');+ if (select.dataset.filled !== String(agents.length)) {+ select.dataset.filled = String(agents.length);+ select.innerHTML = agents+ .map((a) => `<option value="${escapeHtml(a.id)}">${escapeHtml(a.name || a.id)}</option>`)+ .join('');+ }+ renderSavedRoutines();+}++/** Routines already stored on the selected agent, each loadable in one click. */+function renderSavedRoutines() {+ const box = el('saved');+ const agent = (state.agents || []).find((a) => a.id === el('agent-select')?.value);+ const list = Array.isArray(agent?.meta?.choreographies) ? agent.meta.choreographies : [];+ if (!list.length) {+ box.hidden = true;+ return;+ }+ box.hidden = false;+ el('saved-list').innerHTML = list+ .map((r, i) => {+ let seconds = 0;+ try {+ seconds = routineDuration(normalizeRoutine(r));+ } catch {+ return '';+ }+ return `+ <button type="button" class="ch-saved-chip" data-saved="${i}">+ <span class="ch-saved-name">${escapeHtml(r.name || r.id)}</span>+ <span class="ch-saved-meta">${r.steps?.length || 0} steps · ${seconds}s</span>+ </button>`;+ })+ .join('');+}++/* ── editing ───────────────────────────────────────────────────────────── */++/** Every mutation funnels through here so the URL, exports and stage agree. */+function commit({ restage = true } = {}) {+ renderSteps();+ if (restage) restageIfPlaying();+ highlightActive();+}++function addStep(slot) {+ if (state.steps.length >= MAX_STEPS) {+ setStatus(`A routine holds at most ${MAX_STEPS} steps.`);+ return;+ }+ state.steps.push({ slot, clip: null, hold: DEFAULT_HOLD, speed: 1 });+ commit({ restage: false });+ // Adding a step should show you the step you just added, not restart the+ // routine from the top.+ playFrom(state.steps.length - 1);+ setStatus(`Added ${slot}. ${state.steps.length} steps.`);+}++function removeStep(i) {+ const [removed] = state.steps.splice(i, 1);+ if (!state.steps.length) stopPlayback();+ commit();+ setStatus(`Removed ${removed?.slot ?? 'step'}.`);+}++function moveStep(from, to) {+ if (to < 0 || to >= state.steps.length) return;+ const [step] = state.steps.splice(from, 1);+ state.steps.splice(to, 0, step);+ commit();+ setStatus(`Moved ${step.slot} to position ${to + 1}.`);+ // Keep the keyboard on the button the user just pressed.+ el('steps')+ .querySelector(`.ch-step[data-index="${to}"] [data-act="${to > from ? 'down' : 'up'}"]`)+ ?.focus();+}++/* ── playback ──────────────────────────────────────────────────────────── */++function setStatus(text) {+ el('stage-status').textContent = text;+}++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;+}++/** Manifest def for a step's clip, or null when the clip is not in the library. */+function defFor(step) {+ const clip = stepClip(step);+ const def = state.byName.get(clip);+ return def ? { id: clip, source: 'curated', url: def.url, loop: def.loop !== false } : null;+}++/**+ * Mount a step on the stage. Steps after the first crossfade into place, and+ * the camera is framed once for the whole routine so it does not jog at cuts.+ */+async function stageStep(step, { crossfade = true } = {}) {+ const def = defFor(step);+ if (!def) {+ setStageState('error', `"${stepClip(step)}" is not in the clip manifest.`);+ return;+ }+ const preview = await getPreview();+ const bounds = state.boundClips || [];+ try {+ await preview.play(el('stage'), def, {+ speed: step.speed,+ crossfade: crossfade && state.stagedClip ? CROSSFADE : 0,+ frameWith: bounds.filter(Boolean),+ });+ state.stagedClip = def.id;+ setStageState('none');+ el('stage-badge').hidden = false;+ el('stage-badge').textContent = `${step.slot} · ${clipLabel(def.id)}`;+ } catch (err) {+ setStageState('error', err?.message ? `Preview failed: ${err.message}` : undefined);+ }+}++/** Bind every clip in the routine up front so no cut waits on a fetch. */+async function prepareClips(routine) {+ const preview = await getPreview();+ const defs = routine.steps.map(defFor).filter(Boolean);+ state.boundClips = await preview.prepare(defs);+}++async function startPlayback(fromIndex = 0) {+ const routine = currentRoutine();+ if (!routine) return;++ stopRaf();+ el('stage-loading-text').textContent =+ state.stagedClip ? 'Cueing the routine…' : 'Retargeting the routine…';+ if (!state.stagedClip) setStageState('loading');++ await prepareClips(routine);++ state.player = new RoutinePlayer(routine, {+ loop: state.loop,+ onStep: (step) => {+ stageStep(step);+ highlightActive();+ renderTimeline();+ },+ onTick: () => renderPlayhead(),+ onEnd: () => {+ setPlayButton(false);+ setStatus('Routine finished.');+ renderPlayhead();+ },+ });+ state.player.start();+ if (fromIndex > 0) state.player.seek(stepOffsets(routine)[fromIndex] ?? 0);+ setPlayButton(true);+ startRaf();+ setStatus(`Playing ${routine.name}, ${routine.steps.length} steps.`);+}++function playFrom(index) {+ startPlayback(index);+}++function stopPlayback() {+ stopRaf();+ state.player = null;+ state.stagedClip = null;+ state.preview?.stop();+ setPlayButton(false);+ setStageState('empty');+ el('stage-badge').hidden = true;+ el('playhead').hidden = true;+ el('time').textContent = '0.0';+ highlightActive();+}++/** Re-cue the stage after an edit, but only if something was already playing. */+function restageIfPlaying() {+ if (!state.player) return;+ const wasPlaying = state.player.playing;+ const at = state.player.time;+ const routine = currentRoutine();+ if (!routine) {+ stopPlayback();+ return;+ }+ startPlayback(0).then(() => {+ if (!state.player) return;+ state.player.seek(Math.min(at, routineDuration(routine)));+ if (!wasPlaying) {+ state.player.pause();+ setPlayButton(false);+ }+ renderPlayhead();+ });+}++function setPlayButton(playing) {+ const btn = el('play');+ btn.textContent = playing ? '❙❙' : '▶';+ btn.setAttribute('aria-label', playing ? 'Pause routine' : 'Play routine');+ btn.title = playing ? 'Pause (Space)' : 'Play (Space)';+}++function startRaf() {+ stopRaf();+ state.lastT = performance.now();+ const tick = () => {+ state.raf = requestAnimationFrame(tick);+ const now = performance.now();+ const dt = Math.min(0.1, (now - state.lastT) / 1000);+ state.lastT = now;+ state.player?.update(dt);+ };+ state.raf = requestAnimationFrame(tick);+}++function stopRaf() {+ cancelAnimationFrame(state.raf);+ state.raf = 0;+}++function togglePlay() {+ if (!state.steps.length) return;+ if (!state.player) {+ startPlayback(0);+ return;+ }+ if (state.player.playing) {+ state.player.pause();+ state.preview?.setPaused(true);+ setPlayButton(false);+ setStatus('Paused.');+ } else {+ // A player parked at the very end restarts rather than sitting still.+ if (state.player.time >= state.player.duration) state.player.start();+ else state.player.resume();+ state.preview?.setPaused(false);+ setPlayButton(true);+ setStatus('Playing.');+ }+}++function scrubTo(seconds) {+ const routine = currentRoutine();+ if (!routine) return;+ if (!state.player) {+ startPlayback(0).then(() => {+ state.player?.seek(seconds);+ state.player?.pause();+ setPlayButton(false);+ renderPlayhead();+ });+ return;+ }+ state.player.seek(seconds);+ renderPlayhead();+ highlightActive();+}++/* ── url state ─────────────────────────────────────────────────────────── */++function syncUrl() {+ const routine = currentRoutine();+ const url = new URL(window.location.href);+ if (routine) url.searchParams.set('r', encodeRoutine(routine));+ else url.searchParams.delete('r');+ window.history.replaceState(null, '', url);+}++function loadRoutine(routine, { announce = true } = {}) {+ const normalized = normalizeRoutine(routine);+ state.name = normalized.name;+ state.steps = normalized.steps.map((s) => ({ ...s }));+ state.loop = normalized.loop;+ el('name').value = state.name;+ el('loop').setAttribute('aria-pressed', String(state.loop));+ el('loop').classList.toggle('is-on', state.loop);+ commit({ restage: false });+ if (announce) setStatus(`Loaded ${normalized.name}: ${normalized.steps.length} steps.`);+}++/**+ * Load the routine in `?r=`, if there is one.+ * @returns {string|null} an error to show the user, or null when there was+ * nothing to load or it loaded cleanly. Returning the message rather than+ * announcing it lets the caller decide the final wording: a bad link falls+ * back to a preset, and "could not read your link" plus "here is a starting+ * point instead" belong in one sentence, not two that overwrite each other.+ */+function applyDeepLink() {+ const encoded = new URLSearchParams(window.location.search).get('r');+ if (!encoded) return null;+ try {+ loadRoutine(decodeRoutine(encoded), { announce: false });+ setStatus(`Loaded a shared routine: ${state.name}.`);+ state.loadedFromLink = true;+ return null;+ } catch (err) {+ return err.message;+ }+}++/* ── saving ────────────────────────────────────────────────────────────── */++async function copy(text, btn, label = 'Copy') {+ try {+ await navigator.clipboard.writeText(text);+ btn.textContent = 'Copied';+ } catch {+ btn.textContent = 'Copy blocked, select it by hand';+ }+ setTimeout(() => {+ btn.textContent = label;+ }, 1800);+}++async function saveToAgent() {+ const routine = currentRoutine();+ if (!routine) return;+ const btn = el('save');+ const status = el('save-status');+ const agentId = el('agent-select').value;+ const agent = (state.agents || []).find((a) => a.id === agentId);+ if (!agentId) return;++ // Merge by id: saving "welcome" twice replaces it rather than stacking a+ // second copy the owner would have to hunt down and delete.+ const existing = Array.isArray(agent?.meta?.choreographies) ? agent.meta.choreographies : [];+ const merged = existing.filter((r) => slugify(r?.id || r?.name || '') !== routine.id);+ merged.push(routine);++ btn.disabled = true;+ status.textContent = 'Saving…';+ status.className = 'ch-save-status';+ try {+ const { apiFetch } = await import('./api.js');+ const res = await apiFetch(`/api/agents/${agentId}/animations`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ choreographies: merged }),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error_description || body.error || `HTTP ${res.status}`);+ }+ const saved = await res.json();+ // Keep the local copy in step so a second save merges against the truth.+ if (agent) {+ agent.meta = { ...(agent.meta || {}), choreographies: saved.choreographies || [] };+ }+ const count = (saved.choreographies || []).length;+ status.innerHTML = `Saved as <code>${escapeHtml(routine.id)}</code>. <a href="/a/${escapeHtml(+ agentId,+ )}">Open ${escapeHtml(agent?.name || 'the agent')}</a> · ${count} routine${+ count === 1 ? '' : 's'+ } in total.`;+ status.className = 'ch-save-status is-ok';+ renderSavedRoutines();+ } catch (err) {+ status.textContent = `Could not save: ${err.message}`;+ status.className = 'ch-save-status is-err';+ } finally {+ btn.disabled = false;+ }+}++/* ── events ────────────────────────────────────────────────────────────── */++function wire() {+ el('presets').addEventListener('click', (e) => {+ const btn = e.target.closest('[data-preset]');+ if (!btn) return;+ const preset = PRESET_ROUTINES.find((p) => p.id === btn.dataset.preset);+ if (!preset) return;+ loadRoutine(preset);+ startPlayback(0);+ });++ el('palette').addEventListener('click', (e) => {+ const chip = e.target.closest('[data-slot]');+ if (chip) addStep(chip.dataset.slot);+ });++ el('name').addEventListener('input', (e) => {+ state.name = e.target.value.slice(0, 40);+ renderMeta();+ renderExports();+ });++ // Step edits. One delegated listener for the whole list: rows are re-rendered+ // on every change, so per-row listeners would leak with each edit.+ const steps = el('steps');+ steps.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-act]');+ if (!btn) return;+ const i = Number(btn.dataset.index);+ if (btn.dataset.act === 'remove') removeStep(i);+ else if (btn.dataset.act === 'up') moveStep(i, i - 1);+ else if (btn.dataset.act === 'down') moveStep(i, i + 1);+ });++ steps.addEventListener('input', (e) => {+ const input = e.target.closest('[data-act="hold"]');+ if (!input) return;+ const i = Number(input.dataset.index);+ state.steps[i].hold = Number(input.value);+ // Live feedback while dragging, without re-rendering the row under the+ // pointer (which would drop the drag).+ input.parentElement.querySelector('.ch-step-secs').textContent =+ `${state.steps[i].hold.toFixed(1)}s`;+ renderMeta();+ renderTimeline();+ renderExports();+ });++ steps.addEventListener('change', (e) => {+ const control = e.target.closest('[data-act]');+ if (!control) return;+ const i = Number(control.dataset.index);+ if (control.dataset.act === 'clip') {+ const picked = control.value;+ state.steps[i].clip = picked === DEFAULT_ANIMATION_MAP[state.steps[i].slot] ? null : picked;+ commit();+ playFrom(i);+ } else if (control.dataset.act === 'speed') {+ state.steps[i].speed = Number(control.value);+ commit();+ } else if (control.dataset.act === 'hold') {+ commit();+ }+ });++ // Drag to reorder. The keyboard equivalent is the ↑/↓ buttons on every row,+ // so reordering never requires a pointer.+ steps.addEventListener('dragstart', (e) => {+ const row = e.target.closest('.ch-step');+ if (!row) return;+ state.dragIndex = Number(row.dataset.index);+ row.classList.add('is-dragging');+ e.dataTransfer.effectAllowed = 'move';+ // Firefox refuses to start a drag without payload.+ e.dataTransfer.setData('text/plain', String(state.dragIndex));+ });+ steps.addEventListener('dragover', (e) => {+ const row = e.target.closest('.ch-step');+ if (!row || state.dragIndex < 0) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = 'move';+ for (const r of steps.querySelectorAll('.ch-step')) r.classList.remove('is-drop-target');+ row.classList.add('is-drop-target');+ });+ steps.addEventListener('drop', (e) => {+ const row = e.target.closest('.ch-step');+ if (!row || state.dragIndex < 0) return;+ e.preventDefault();+ const to = Number(row.dataset.index);+ if (to !== state.dragIndex) moveStep(state.dragIndex, to);+ state.dragIndex = -1;+ });+ steps.addEventListener('dragend', () => {+ state.dragIndex = -1;+ for (const r of steps.querySelectorAll('.ch-step')) {+ r.classList.remove('is-dragging', 'is-drop-target');+ }+ });++ el('play').addEventListener('click', togglePlay);+ el('restart').addEventListener('click', () => startPlayback(0));+ el('loop').addEventListener('click', (e) => {+ state.loop = !state.loop;+ e.currentTarget.setAttribute('aria-pressed', String(state.loop));+ e.currentTarget.classList.toggle('is-on', state.loop);+ if (state.player) state.player.loop = state.loop;+ renderExports();+ setStatus(state.loop ? 'Looping.' : 'Playing once.');+ });+ el('stage-retry').addEventListener('click', () => startPlayback(0));++ // The timeline is both a scrubber and a step picker: clicking a segment jumps+ // to that beat, dragging anywhere scrubs.+ const timeline = el('timeline');+ const seek = (clientX) => {+ const routine = currentRoutine();+ if (!routine) return;+ const rect = timeline.getBoundingClientRect();+ const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));+ scrubTo(ratio * routineDuration(routine));+ };+ timeline.addEventListener('pointerdown', (e) => {+ timeline.setPointerCapture(e.pointerId);+ timeline.dataset.scrubbing = '1';+ seek(e.clientX);+ });+ timeline.addEventListener('pointermove', (e) => {+ if (timeline.dataset.scrubbing) seek(e.clientX);+ });+ const endScrub = (e) => {+ delete timeline.dataset.scrubbing;+ if (e.pointerId != null && timeline.hasPointerCapture?.(e.pointerId)) {+ timeline.releasePointerCapture(e.pointerId);+ }+ };+ timeline.addEventListener('pointerup', endScrub);+ timeline.addEventListener('pointercancel', endScrub);+ timeline.addEventListener('keydown', (e) => {+ const routine = currentRoutine();+ if (!routine) return;+ const total = routineDuration(routine);+ const at = state.player?.time ?? 0;+ const moves = { ArrowLeft: -0.25, ArrowRight: 0.25, Home: -total, End: total };+ if (!(e.key in moves)) return;+ e.preventDefault();+ scrubTo(Math.min(total, Math.max(0, e.key === 'Home' ? 0 : e.key === 'End' ? total : at + moves[e.key])));+ });++ el('save').addEventListener('click', saveToAgent);+ el('agent-select').addEventListener('change', renderSavedRoutines);+ el('saved-list').addEventListener('click', (e) => {+ const chip = e.target.closest('[data-saved]');+ if (!chip) return;+ const agent = (state.agents || []).find((a) => a.id === el('agent-select').value);+ const routine = agent?.meta?.choreographies?.[Number(chip.dataset.saved)];+ if (!routine) return;+ try {+ loadRoutine(routine);+ startPlayback(0);+ } catch (err) {+ setStatus(`That saved routine could not be loaded (${err.message}).`);+ }+ });++ const shareLink = (e) => {+ syncUrl();+ copy(window.location.href, e.currentTarget, 'Copy share link');+ };+ el('share').addEventListener('click', shareLink);+ el('share-2').addEventListener('click', shareLink);+ el('copy-json').addEventListener('click', (e) =>+ copy($('code', el('json-code')).textContent, e.currentTarget, 'Copy JSON'),+ );+ el('copy-embed').addEventListener('click', (e) =>+ copy($('code', el('embed-code')).textContent, e.currentTarget, 'Copy snippet'),+ );++ document.addEventListener('keydown', (e) => {+ // Never steal a key from a field the user is typing in.+ const tag = e.target.tagName;+ if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return;+ if (e.key === ' ' && state.steps.length) {+ e.preventDefault();+ togglePlay();+ } else if (e.key === 'r' || e.key === 'R') {+ if (state.steps.length) startPlayback(0);+ } else if (e.key === 'Escape' && state.player) {+ stopPlayback();+ setStatus('Stopped.');+ }+ });++ // Stop burning frames on a hidden tab without stomping a deliberate pause.+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) {+ stopRaf();+ state.preview?.setPaused(true);+ } else if (state.player?.playing) {+ state.preview?.setPaused(false);+ startRaf();+ }+ });+}++/* ── boot ──────────────────────────────────────────────────────────────── */++renderPresets();+wire();+loadManifest();+loadAgents();+if (!applyDeepLink()) {+ // An empty timeline is the hardest screen to start on, so the page opens on a+ // real routine. Nothing 3D loads until the user presses play.+ loadRoutine(PRESET_ROUTINES[0], { announce: false });+ setStatus('Loaded the Welcome routine. Press play, or change any step.');+}diff --git a/src/element.js b/src/element.jsindex f0ef24ac3..dbd57aefc 100644--- a/src/element.js+++ b/src/element.js@@ -1784,6 +1784,13 @@ class Agent3DElement extends HTMLElement {const _slots = manifest.animationSlots || manifest.meta?.edits?.animations;if (_slots && typeof _slots === 'object') this._avatar.setAnimationMap(_slots);+ // Saved gesture routines, same path: on the wire as `choreographies`,+ // on the record at meta.choreographies. Registering them here is what+ // makes `el.playRoutine('welcome')` resolve by name.+ const _routines = manifest.choreographies || manifest.meta?.choreographies;+ if (Array.isArray(_routines)) this._avatar.setChoreographies(_routines);+ this._applyPendingRoutine();+// Honor a sign-language attribute present at boot (the observer// only covers post-mount changes).const signAttr = this.getAttribute('sign-language');@@ -3250,6 +3257,50 @@ class Agent3DElement extends HTMLElement {return true;}+ /**+ * Perform a gesture routine: a named sequence of gestures with per-step+ * timing, composed at three.ws/choreograph. Pass the routine's id to play one+ * the agent has saved, or a routine object to play one the host page owns.+ *+ * el.playRoutine('welcome');+ * el.playRoutine({ name: 'Hi', steps: [{ slot: 'wave', hold: 2 }] });+ *+ * Queued until the empathy layer attaches, so it lands when called during+ * boot rather than being dropped.+ * @param {string|object} nameOrRoutine+ * @param {{loop?:boolean}} [opts]+ * @returns {boolean} false when the named routine does not exist+ */+ playRoutine(nameOrRoutine, opts = {}) {+ if (!this._avatar) {+ this._pendingRoutine = { nameOrRoutine, opts };+ // A routine requested before boot is a real request, not a no-op: report+ // success and let `_applyPendingRoutine` deliver it.+ this._waitForReady().then(() => this._applyPendingRoutine());+ return true;+ }+ return this._avatar.playChoreography(nameOrRoutine, opts);+ }++ /** Stop a performing routine. */+ stopRoutine() {+ this._pendingRoutine = null;+ this._avatar?.stopChoreography();+ return true;+ }++ /** The routines this agent has saved, as normalized routine objects. */+ getRoutines() {+ return this._avatar?.getChoreographies() ?? [];+ }++ _applyPendingRoutine() {+ const pending = this._pendingRoutine;+ if (!pending || !this._avatar) return;+ this._pendingRoutine = null;+ this._avatar.playChoreography(pending.nameOrRoutine, pending.opts);+ }+_waitForReady() {if (this._mounted) return Promise.resolve();return new Promise((resolve) => {diff --git a/src/runtime/choreography.js b/src/runtime/choreography.jsnew file mode 100644index 000000000..e28f51d84--- /dev/null+++ b/src/runtime/choreography.js@@ -0,0 +1,452 @@+// Agent choreography: a named, timed sequence of gesture slots.+//+// A gesture on its own is a single beat. A routine is a performance: wave, then+// nod, then present the thing you just made. Every surface that can play one+// gesture can play a routine, so this module is the one place the shape, the+// timing and the wire format live:+//+// • the /choreograph studio composes and previews routines+// • PUT /api/agents/:id/animations persists them at meta.choreographies+// • the public agent manifest ships them to embeds+// • AgentAvatar.playChoreography() and <agent-3d>.playRoutine() play them+//+// Deliberately dependency-free (no Three.js, no DOM, no fetch) for the same+// reason animation-slots.js is: the API imports it to validate what it stores,+// so the browser and the server can never disagree about what a routine is.+// Playback side effects are delivered through callbacks the caller supplies.++import { SLOTS, DEFAULT_ANIMATION_MAP, resolveSlot } from './animation-slots.js';++/** Hard bounds. The API enforces these too, by importing them from here. */+export const MAX_STEPS = 24;+export const MAX_ROUTINES = 12;+export const MAX_NAME_LENGTH = 40;+/** A hold shorter than this is a flicker, not a gesture. */+export const MIN_HOLD = 0.2;+export const MAX_HOLD = 20;+export const MIN_SPEED = 0.25;+export const MAX_SPEED = 3;+/** Used when a step omits its hold, and by the studio when adding a step. */+export const DEFAULT_HOLD = 1.6;++const SLOT_SET = new Set(SLOTS);+const CLIP_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;++const clamp = (n, min, max) => Math.min(max, Math.max(min, n));++/** Round to 2dp so encode/decode round-trips exactly and JSON stays readable. */+const round2 = (n) => Math.round(n * 100) / 100;++/**+ * URL/id-safe slug for a routine name. Falls back to `routine` for names made+ * entirely of punctuation, so every routine is addressable by id.+ * @param {string} name+ * @returns {string}+ */+export function slugify(name) {+ const slug = String(name || '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, MAX_NAME_LENGTH);+ return slug || 'routine';+}++/**+ * Coerce one step into the canonical shape, or throw with a reason a user can+ * act on. `clip` is optional: absent means "whatever this slot resolves to for+ * the agent playing it", which is what keeps a shared routine looking right on+ * an agent that has remapped its own gestures.+ *+ * @param {{slot:string, clip?:string|null, hold?:number, speed?:number}} input+ * @returns {{slot:string, clip:string|null, hold:number, speed:number}}+ */+export function normalizeStep(input) {+ if (!input || typeof input !== 'object') throw new Error('step must be an object');+ const slot = String(input.slot || '').trim();+ if (!SLOT_SET.has(slot)) throw new Error(`unknown gesture slot "${slot}"`);++ let clip = input.clip == null ? null : String(input.clip).trim();+ if (clip === '') clip = null;+ if (clip && !CLIP_RE.test(clip)) throw new Error(`invalid clip name "${clip}"`);+ if (clip && clip.length > 60) throw new Error(`clip name "${clip}" is too long`);+ // A clip equal to the platform default carries no information and would+ // pin the step to today's mapping; drop it so the slot stays the contract.+ if (clip && clip === DEFAULT_ANIMATION_MAP[slot]) clip = null;++ const holdRaw = input.hold == null ? DEFAULT_HOLD : Number(input.hold);+ if (!Number.isFinite(holdRaw)) throw new Error('hold must be a number');+ const speedRaw = input.speed == null ? 1 : Number(input.speed);+ if (!Number.isFinite(speedRaw)) throw new Error('speed must be a number');++ return {+ slot,+ clip,+ hold: round2(clamp(holdRaw, MIN_HOLD, MAX_HOLD)),+ speed: round2(clamp(speedRaw, MIN_SPEED, MAX_SPEED)),+ };+}++/**+ * Coerce a whole routine, or throw. The returned object is exactly what gets+ * stored, encoded and played: no other shape is valid anywhere downstream.+ *+ * @param {{id?:string, name?:string, steps:Array, loop?:boolean}} input+ * @returns {{id:string, name:string, steps:Array<{slot:string,clip:string|null,hold:number,speed:number}>, loop:boolean}}+ */+export function normalizeRoutine(input) {+ if (!input || typeof input !== 'object') throw new Error('routine must be an object');+ const steps = Array.isArray(input.steps) ? input.steps : [];+ if (!steps.length) throw new Error('a routine needs at least one step');+ if (steps.length > MAX_STEPS) throw new Error(`a routine can hold at most ${MAX_STEPS} steps`);++ const name = String(input.name ?? '').trim().slice(0, MAX_NAME_LENGTH) || 'Routine';+ const id = slugify(input.id || name);+ return {+ id,+ name,+ steps: steps.map(normalizeStep),+ loop: input.loop === true,+ };+}++/**+ * Normalize a list of routines and reject duplicate ids, which would make+ * `playRoutine('welcome')` ambiguous.+ * @param {Array} input+ */+export function normalizeRoutines(input) {+ const list = Array.isArray(input) ? input : [];+ if (list.length > MAX_ROUTINES) throw new Error(`at most ${MAX_ROUTINES} routines`);+ const out = list.map(normalizeRoutine);+ const seen = new Set();+ for (const r of out) {+ if (seen.has(r.id)) throw new Error(`two routines share the id "${r.id}"`);+ seen.add(r.id);+ }+ return out;+}++/**+ * Wall-clock length of a routine in seconds. Speed scales a step's hold: a+ * gesture played at 2x occupies half the time on the timeline, which is what+ * makes the studio's playhead agree with what the eye sees.+ * @param {{steps:Array<{hold:number,speed:number}>}} routine+ */+export function routineDuration(routine) {+ return round2(+ (routine?.steps || []).reduce((sum, s) => sum + s.hold / (s.speed || 1), 0),+ );+}++/**+ * Start time of each step, in seconds. Index-aligned with `routine.steps`.+ * @param {{steps:Array<{hold:number,speed:number}>}} routine+ * @returns {number[]}+ */+export function stepOffsets(routine) {+ const offsets = [];+ let t = 0;+ for (const s of routine?.steps || []) {+ offsets.push(round2(t));+ t += s.hold / (s.speed || 1);+ }+ return offsets;+}++/**+ * Which step is on screen at time `t`. Returns null for an empty routine or a+ * time past the end. The final step owns the closing instant so a playhead+ * parked at the very end still highlights something.+ *+ * @param {{steps:Array}} routine+ * @param {number} t seconds+ * @returns {{index:number, step:object, start:number, end:number}|null}+ */+export function stepAtTime(routine, t) {+ const steps = routine?.steps || [];+ if (!steps.length) return null;+ const time = Math.max(0, Number(t) || 0);+ let start = 0;+ for (let i = 0; i < steps.length; i++) {+ const span = steps[i].hold / (steps[i].speed || 1);+ const end = start + span;+ if (time < end || i === steps.length - 1) {+ if (time > end && i === steps.length - 1) return null;+ return { index: i, step: steps[i], start: round2(start), end: round2(end) };+ }+ start = end;+ }+ return null;+}++/**+ * The clip a step actually plays on a given agent: an explicit per-step clip+ * wins, then the agent's own slot override, then the platform default.+ * @param {{slot:string, clip?:string|null}} step+ * @param {Object|null} [overrideMap] agent's meta.edits.animations+ */+export function resolveStepClip(step, overrideMap) {+ return step?.clip || resolveSlot(step?.slot, overrideMap);+}++/* ── wire format ───────────────────────────────────────────────────────────+ *+ * Routines travel in URLs (share a routine without an account) so the encoding+ * is compact and legible rather than base64: a person can read a shared link+ * and see what it will do before clicking it.+ *+ * Name|wave:1.6,nod:1,present:2.2*0.8,dance:3@rumba+ *+ * step := slot ':' hold [ '*' speed ] [ '@' clip ]+ */++/** @param {{slot:string,clip:string|null,hold:number,speed:number}} step */+function encodeStep(step) {+ let out = `${step.slot}:${step.hold}`;+ if (step.speed !== 1) out += `*${step.speed}`;+ if (step.clip) out += `@${step.clip}`;+ return out;+}++function decodeStep(text) {+ const raw = String(text || '').trim();+ if (!raw) throw new Error('empty step');+ let rest = raw;+ let clip = null;+ const at = rest.indexOf('@');+ if (at >= 0) {+ clip = rest.slice(at + 1);+ rest = rest.slice(0, at);+ }+ let speed = 1;+ const star = rest.indexOf('*');+ if (star >= 0) {+ speed = Number(rest.slice(star + 1));+ rest = rest.slice(0, star);+ }+ const colon = rest.indexOf(':');+ const slot = colon >= 0 ? rest.slice(0, colon) : rest;+ const hold = colon >= 0 ? Number(rest.slice(colon + 1)) : DEFAULT_HOLD;+ return normalizeStep({ slot, clip, hold, speed });+}++/**+ * Compact, URL-safe text for a routine. The name is percent-encoded so it can+ * carry spaces and punctuation without colliding with the separators.+ * @param {{name:string, steps:Array, loop?:boolean}} routine+ */+export function encodeRoutine(routine) {+ const r = normalizeRoutine(routine);+ const steps = r.steps.map(encodeStep).join(',');+ return `${encodeURIComponent(r.name)}${r.loop ? '~loop' : ''}|${steps}`;+}++/**+ * Parse what `encodeRoutine` produced. Throws on anything malformed rather+ * than silently dropping steps: a half-decoded routine is worse than an error+ * the page can show.+ * @param {string} text+ */+export function decodeRoutine(text) {+ const raw = String(text || '').trim();+ if (!raw) throw new Error('nothing to decode');+ const bar = raw.indexOf('|');+ // A bare step list (no name) is accepted: it is what a hand-written link+ // looks like, and the name is cosmetic.+ let namePart = bar >= 0 ? raw.slice(0, bar) : '';+ const stepsPart = bar >= 0 ? raw.slice(bar + 1) : raw;+ let loop = false;+ if (namePart.endsWith('~loop')) {+ loop = true;+ namePart = namePart.slice(0, -5);+ }+ let name = 'Routine';+ try {+ name = decodeURIComponent(namePart) || 'Routine';+ } catch {+ name = namePart || 'Routine';+ }+ const steps = stepsPart+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ .map(decodeStep);+ return normalizeRoutine({ name, steps, loop });+}++/* ── starting points ───────────────────────────────────────────────────── */++/**+ * Routines the studio offers as a first move. Every one is a real sequence of+ * shipped slots, chosen because it reads as a recognisable performance rather+ * than a list of gestures: an empty timeline is the hardest screen to start on.+ */+export const PRESET_ROUTINES = Object.freeze([+ {+ id: 'welcome',+ name: 'Welcome',+ blurb: 'The greeting an agent plays the first time someone lands on it.',+ steps: [+ { slot: 'wave', hold: 2 },+ { slot: 'nod', hold: 1.2 },+ { slot: 'idle', hold: 1.6 },+ ],+ },+ {+ id: 'pitch',+ name: 'The pitch',+ blurb: 'Think, point at the thing, then show it off. Demo body language.',+ steps: [+ { slot: 'think', hold: 2.4 },+ { slot: 'point', hold: 1.4 },+ { slot: 'present', hold: 2.6 },+ { slot: 'idle', hold: 1.2 },+ ],+ },+ {+ id: 'shipped',+ name: 'Shipped it',+ blurb: 'A win: sign, celebrate, dance. What a settled payment should look like.',+ steps: [+ { slot: 'sign', hold: 1.6 },+ { slot: 'celebrate', hold: 2 },+ { slot: 'dance', hold: 3.2 },+ ],+ },+ {+ id: 'bad-news',+ name: 'Bad news',+ blurb: 'The honest version: inspect, concern, shrug. Failures deserve a face too.',+ steps: [+ { slot: 'inspect', hold: 2 },+ { slot: 'concern', hold: 2.2 },+ { slot: 'shrug', hold: 1.6 },+ ],+ },+ {+ id: 'waiting',+ name: 'Long wait',+ blurb: 'For work that takes a while. Loops without looking frozen.',+ loop: true,+ steps: [+ { slot: 'patience', hold: 3 },+ { slot: 'fidget', hold: 2.4 },+ { slot: 'curiosity', hold: 2 },+ ],+ },+]);++/* ── playback ──────────────────────────────────────────────────────────── */++/**+ * Timing engine for a routine. Deliberately has no clock of its own: the caller+ * advances it with `update(dt)` from whatever loop it already runs (rAF in the+ * studio, a frame hook on the avatar). That keeps playback exact under a paused+ * tab, a scrubbed playhead and a unit test with synthetic deltas alike.+ *+ * Callbacks:+ * onStep(step, index, routine) — a new step became current (also on seek)+ * onTick(time, duration) — every update while playing+ * onEnd() — the routine finished (never fires when looping)+ */+export class RoutinePlayer {+ /**+ * @param {object} routine normalized routine+ * @param {{onStep?:Function, onTick?:Function, onEnd?:Function, loop?:boolean}} [handlers]+ */+ constructor(routine, handlers = {}) {+ this.routine = normalizeRoutine(routine);+ this.duration = routineDuration(this.routine);+ this.loop = handlers.loop ?? this.routine.loop;+ this._onStep = handlers.onStep || null;+ this._onTick = handlers.onTick || null;+ this._onEnd = handlers.onEnd || null;+ this._time = 0;+ this._index = -1;+ this._playing = false;+ }++ get time() {+ return round2(this._time);+ }+ get index() {+ return this._index;+ }+ get playing() {+ return this._playing;+ }++ /** Start (or restart) from the top. Fires the first step immediately. */+ start() {+ this._time = 0;+ this._index = -1;+ this._playing = true;+ this._syncStep();+ return this;+ }++ pause() {+ this._playing = false;+ return this;+ }++ resume() {+ if (this._index >= 0) this._playing = true;+ return this;+ }++ stop() {+ this._playing = false;+ this._time = 0;+ this._index = -1;+ return this;+ }++ /**+ * Move the playhead. Re-fires onStep when it lands on a different step, so+ * scrubbing the studio timeline updates the 3D stage.+ * @param {number} t seconds+ */+ seek(t) {+ this._time = clamp(Number(t) || 0, 0, this.duration);+ this._syncStep();+ return this;+ }++ /**+ * Advance by `dt` seconds. Safe to call while paused (does nothing) and with+ * a large dt after a background tab: the routine catches up rather than+ * playing every intervening step.+ * @param {number} dt+ */+ update(dt) {+ if (!this._playing) return;+ const step = Number(dt);+ if (!Number.isFinite(step) || step <= 0) return;+ this._time += step;+ if (this._time >= this.duration) {+ if (this.loop && this.duration > 0) {+ this._time %= this.duration;+ } else {+ this._time = this.duration;+ this._playing = false;+ this._syncStep();+ this._onTick?.(this.time, this.duration);+ this._onEnd?.();+ return;+ }+ }+ this._syncStep();+ this._onTick?.(this.time, this.duration);+ }++ _syncStep() {+ const at = stepAtTime(this.routine, this._time);+ const index = at ? at.index : this.routine.steps.length - 1;+ if (index !== this._index) {+ this._index = index;+ this._onStep?.(this.routine.steps[index], index, this.routine);+ }+ }+}diff --git a/tests/choreography.test.js b/tests/choreography.test.jsnew file mode 100644index 000000000..e48967564--- /dev/null+++ b/tests/choreography.test.js@@ -0,0 +1,366 @@+/**+ * Contract tests for agent choreography (src/runtime/choreography.js).+ *+ * The module is the single definition of what a routine is: the /choreograph+ * studio, the agents API, the public manifest and the avatar runtime all agree+ * only because they import it. So the things pinned here are the things that+ * would let those four drift apart:+ *+ * 1. normalization is total — anything that survives it is storable, encodable+ * and playable, and anything that would not be is rejected with a reason.+ * 2. the URL wire format round-trips exactly, including the lossy-looking bits+ * (speed, per-step clip, loop flag, a name with punctuation in it).+ * 3. timeline math (duration, offsets, stepAtTime) is consistent with itself,+ * because the studio's playhead and the avatar's playback read it+ * independently and any disagreement shows up as a visibly wrong preview.+ * 4. RoutinePlayer fires each step exactly once per pass, survives a huge dt+ * (backgrounded tab) and ends or loops as declared.+ * 5. every shipped preset is a valid routine over real slots.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import {+ MAX_STEPS,+ MAX_ROUTINES,+ MIN_HOLD,+ MAX_HOLD,+ MIN_SPEED,+ MAX_SPEED,+ DEFAULT_HOLD,+ PRESET_ROUTINES,+ RoutinePlayer,+ decodeRoutine,+ encodeRoutine,+ normalizeRoutine,+ normalizeRoutines,+ normalizeStep,+ resolveStepClip,+ routineDuration,+ slugify,+ stepAtTime,+ stepOffsets,+} from '../src/runtime/choreography.js';+import { SLOTS, DEFAULT_ANIMATION_MAP } from '../src/runtime/animation-slots.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const CLIP_NAMES = new Set(+ JSON.parse(+ readFileSync(resolve(__dirname, '../public/animations/manifest.json'), 'utf8'),+ ).map((c) => c.name),+);++const routine = (steps, extra = {}) => normalizeRoutine({ name: 'T', steps, ...extra });++describe('normalizeStep', () => {+ it('fills in the defaults a hand-written step omits', () => {+ expect(normalizeStep({ slot: 'wave' })).toEqual({+ slot: 'wave',+ clip: null,+ hold: DEFAULT_HOLD,+ speed: 1,+ });+ });++ it('rejects a slot outside the fixed vocabulary', () => {+ expect(() => normalizeStep({ slot: 'moonwalk' })).toThrow(/unknown gesture slot/);+ expect(() => normalizeStep({ slot: '' })).toThrow(/unknown gesture slot/);+ });++ it('rejects a clip name that could not be a clip', () => {+ expect(() => normalizeStep({ slot: 'wave', clip: '../etc/passwd' })).toThrow(+ /invalid clip name/,+ );+ expect(() => normalizeStep({ slot: 'wave', clip: 'a'.repeat(61) })).toThrow(/too long/);+ });++ it('drops a clip that merely restates the platform default', () => {+ // Pinning the default into the step would freeze it against today's map+ // and stop the agent's own override from applying.+ const step = normalizeStep({ slot: 'wave', clip: DEFAULT_ANIMATION_MAP.wave });+ expect(step.clip).toBeNull();+ });++ it('keeps a clip that genuinely overrides the slot', () => {+ expect(normalizeStep({ slot: 'dance', clip: 'thriller' }).clip).toBe('thriller');+ });++ it('clamps hold and speed into playable bounds', () => {+ expect(normalizeStep({ slot: 'wave', hold: 0 }).hold).toBe(MIN_HOLD);+ expect(normalizeStep({ slot: 'wave', hold: 9999 }).hold).toBe(MAX_HOLD);+ expect(normalizeStep({ slot: 'wave', speed: 0 }).speed).toBe(MIN_SPEED);+ expect(normalizeStep({ slot: 'wave', speed: 99 }).speed).toBe(MAX_SPEED);+ });++ it('rejects non-numeric timing rather than coercing it to NaN', () => {+ expect(() => normalizeStep({ slot: 'wave', hold: 'soon' })).toThrow(/hold must be a number/);+ expect(() => normalizeStep({ slot: 'wave', speed: 'fast' })).toThrow(+ /speed must be a number/,+ );+ });+});++describe('normalizeRoutine', () => {+ it('derives an id from the name', () => {+ expect(normalizeRoutine({ name: 'Ship It!', steps: [{ slot: 'wave' }] }).id).toBe('ship-it');+ });++ it('always produces an addressable id', () => {+ expect(slugify('!!!')).toBe('routine');+ expect(slugify('')).toBe('routine');+ });++ it('requires at least one step', () => {+ expect(() => normalizeRoutine({ name: 'Empty', steps: [] })).toThrow(/at least one step/);+ });++ it('caps the step count', () => {+ const steps = Array.from({ length: MAX_STEPS + 1 }, () => ({ slot: 'wave' }));+ expect(() => normalizeRoutine({ name: 'Long', steps })).toThrow(/at most/);+ });++ it('rejects duplicate ids across a routine list', () => {+ const one = { name: 'Welcome', steps: [{ slot: 'wave' }] };+ expect(() => normalizeRoutines([one, { ...one }])).toThrow(/share the id/);+ });++ it('caps the routine count', () => {+ const list = Array.from({ length: MAX_ROUTINES + 1 }, (_, i) => ({+ name: `R${i}`,+ steps: [{ slot: 'wave' }],+ }));+ expect(() => normalizeRoutines(list)).toThrow(/at most/);+ });+});++describe('timeline math', () => {+ it('sums holds, scaled by speed', () => {+ const r = routine([+ { slot: 'wave', hold: 2 },+ { slot: 'nod', hold: 2, speed: 2 },+ ]);+ expect(routineDuration(r)).toBe(3);+ });++ it('offsets are the running sum of the scaled holds', () => {+ const r = routine([+ { slot: 'wave', hold: 1 },+ { slot: 'nod', hold: 2 },+ { slot: 'bow', hold: 0.5 },+ ]);+ expect(stepOffsets(r)).toEqual([0, 1, 3]);+ expect(routineDuration(r)).toBe(3.5);+ });++ it('stepAtTime agrees with stepOffsets at every boundary', () => {+ const r = routine([+ { slot: 'wave', hold: 1 },+ { slot: 'nod', hold: 2 },+ { slot: 'bow', hold: 0.5 },+ ]);+ stepOffsets(r).forEach((start, i) => {+ expect(stepAtTime(r, start + 0.01).index).toBe(i);+ });+ });++ it('holds the last step at the closing instant and returns null past the end', () => {+ const r = routine([+ { slot: 'wave', hold: 1 },+ { slot: 'nod', hold: 1 },+ ]);+ expect(stepAtTime(r, 2).index).toBe(1);+ expect(stepAtTime(r, 5)).toBeNull();+ });++ it('treats a negative playhead as the start', () => {+ const r = routine([{ slot: 'wave', hold: 1 }]);+ expect(stepAtTime(r, -3).index).toBe(0);+ });+});++describe('resolveStepClip', () => {+ const step = { slot: 'dance', clip: null };++ it('falls back to the platform default', () => {+ expect(resolveStepClip(step, null)).toBe(DEFAULT_ANIMATION_MAP.dance);+ });++ it("uses the agent's own slot override when the step does not name a clip", () => {+ expect(resolveStepClip(step, { dance: 'thriller' })).toBe('thriller');+ });++ it('lets an explicit per-step clip win over the agent override', () => {+ expect(resolveStepClip({ slot: 'dance', clip: 'rumba' }, { dance: 'thriller' })).toBe(+ 'rumba',+ );+ });+});++describe('wire format', () => {+ it('round-trips a routine that uses every optional field', () => {+ const original = routine(+ [+ { slot: 'wave', hold: 1.6 },+ { slot: 'dance', hold: 3, speed: 0.5, clip: 'rumba' },+ ],+ { name: 'Hello, world (v2)', loop: true },+ );+ const decoded = decodeRoutine(encodeRoutine(original));+ expect(decoded).toEqual(original);+ });++ it('stays legible rather than base64', () => {+ const encoded = encodeRoutine(routine([{ slot: 'wave', hold: 2 }], { name: 'Hi' }));+ expect(encoded).toBe('Hi|wave:2');+ });++ it('accepts a hand-written step list with no name', () => {+ const decoded = decodeRoutine('wave:1,nod:2');+ expect(decoded.steps.map((s) => s.slot)).toEqual(['wave', 'nod']);+ expect(decoded.name).toBe('Routine');+ });++ it('throws on a malformed routine instead of silently dropping steps', () => {+ expect(() => decodeRoutine('wave:1,notaslot:2')).toThrow(/unknown gesture slot/);+ expect(() => decodeRoutine('')).toThrow(/nothing to decode/);+ });++ it('survives a name that contains the separators', () => {+ const decoded = decodeRoutine(encodeRoutine(routine([{ slot: 'wave' }], { name: 'a|b,c:d' })));+ expect(decoded.name).toBe('a|b,c:d');+ });+});++describe('RoutinePlayer', () => {+ const build = (extra = {}) => {+ const seen = [];+ const player = new RoutinePlayer(+ routine([+ { slot: 'wave', hold: 1 },+ { slot: 'nod', hold: 1 },+ { slot: 'bow', hold: 1 },+ ], extra.routine),+ { onStep: (_s, i) => seen.push(i), onEnd: () => seen.push('end'), ...extra.handlers },+ );+ return { player, seen };+ };++ it('fires the first step on start, before any time passes', () => {+ const { player, seen } = build();+ player.start();+ expect(seen).toEqual([0]);+ expect(player.time).toBe(0);+ });++ it('fires each step exactly once, in order, then ends', () => {+ const { player, seen } = build();+ player.start();+ for (let i = 0; i < 40; i++) player.update(0.1);+ expect(seen).toEqual([0, 1, 2, 'end']);+ expect(player.playing).toBe(false);+ expect(player.time).toBe(3);+ });++ it('does not advance while paused', () => {+ const { player } = build();+ player.start().pause();+ player.update(10);+ expect(player.time).toBe(0);+ });++ it('catches up rather than replaying every step after a background tab', () => {+ const { player, seen } = build();+ player.start();+ player.update(2.5);+ expect(seen).toEqual([0, 2]);+ });++ it('loops without ever firing onEnd', () => {+ const { player, seen } = build({ handlers: { loop: true } });+ player.start();+ for (let i = 0; i < 70; i++) player.update(0.1);+ expect(seen).not.toContain('end');+ expect(player.playing).toBe(true);+ // Two full passes: three steps, then the same three again.+ expect(seen.slice(0, 6)).toEqual([0, 1, 2, 0, 1, 2]);+ });++ it('honors loop declared on the routine itself', () => {+ const { player } = build({ routine: { loop: true } });+ player.start();+ for (let i = 0; i < 50; i++) player.update(0.1);+ expect(player.playing).toBe(true);+ });++ it('re-fires the step when the playhead is scrubbed', () => {+ const { player, seen } = build();+ player.start();+ player.seek(2.2);+ expect(seen).toEqual([0, 2]);+ player.seek(0.1);+ expect(seen).toEqual([0, 2, 0]);+ });++ it('clamps a seek past the end to the end', () => {+ const { player } = build();+ player.start().seek(99);+ expect(player.time).toBe(3);+ });++ it('ignores a zero or negative delta', () => {+ const { player } = build();+ player.start();+ player.update(0);+ player.update(-1);+ player.update(NaN);+ expect(player.time).toBe(0);+ });++ it('reports progress through onTick', () => {+ const ticks = [];+ const player = new RoutinePlayer(routine([{ slot: 'wave', hold: 1 }]), {+ onTick: (t, d) => ticks.push([t, d]),+ });+ player.start();+ player.update(0.5);+ expect(ticks).toEqual([[0.5, 1]]);+ });+});++describe('shipped presets', () => {+ it('every preset is a valid routine over real slots and baked clips', () => {+ for (const preset of PRESET_ROUTINES) {+ const r = normalizeRoutine(preset);+ expect(r.steps.length).toBeGreaterThan(0);+ for (const step of r.steps) {+ expect(SLOTS).toContain(step.slot);+ expect(CLIP_NAMES.has(resolveStepClip(step, null))).toBe(true);+ }+ }+ });++ it('preset ids are unique and stable, so a shared link keeps resolving', () => {+ const ids = PRESET_ROUTINES.map((p) => p.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const preset of PRESET_ROUTINES) {+ expect(normalizeRoutine(preset).id).toBe(preset.id);+ }+ });++ it('every preset explains itself', () => {+ for (const preset of PRESET_ROUTINES) {+ expect(preset.blurb.length).toBeGreaterThan(20);+ }+ });++ it('presets fit inside the storable bounds', () => {+ expect(PRESET_ROUTINES.length).toBeLessThanOrEqual(MAX_ROUTINES);+ for (const preset of PRESET_ROUTINES) {+ expect(routineDuration(normalizeRoutine(preset))).toBeLessThanOrEqual(+ MAX_STEPS * MAX_HOLD,+ );+ }+ });+});