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
Apply stashed changes and cleanup
nirholase27dc2c5cf4d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bd0e9ce8b..27ace68cb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-19+- **Agent Studio** (`/agent-studio`) — Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.+- **Agent Studio — one place to build your whole agent, with a live avatar** — Agent Studio is the new home for authoring everything about your AI agent — its brain, memory, 3D body, money, and skills — side by side with a live avatar that updates the instant you make a change, no save button and no refresh. The same living avatar can now appear anywhere on the platform as a presence companion, reacting with real emotion to what's happening: it celebrates a filled trade, looks concerned when a position drops, and stays in sync with whatever you edit in the Studio. This release ships the Studio shell and the shared foundation the rest of the experience builds on. (`/agent-studio`) `[feature]`- **Agent wallet's full money loop is now verified end-to-end on devnet** — A re-runnable harness now exercises the entire agent-wallet lifecycle in one pass — create a wallet, fund it, trade and snipe pump.fun tokens, pay an x402 service, exit a graduated position, and withdraw — against real Solana devnet state. It runs simulate-first and reports each step as passed or honestly blocked on funding/credentials, never a fake result, so regressions in the seams between deposit, trading, sniping, payments, and withdrawal surface before they reach holders. The agent wallet hub's Snipe tab now opens the live Sniper dashboard directly instead of a placeholder. (`/agent-wallet`) `[infra]`- **Align a whole room of agents in one gesture** — When you place several agents around a room, their spacing is already exact for everyone — but the whole cluster can sit a few metres off where it really is, because phone GPS only knows the spot to within several metres. Now you can fix that in one move: open any of your room agents and tap “Align this room,” then drag to slide the entire group onto its true spot and twist with two fingers to rotate it — every agent moves together, keeping its layout intact, instead of nudging them one at a time. A live readout shows the move in honest metres and degrees, and the room is labelled with how tightly it's anchored so you know when it's worth aligning. Only the room's owner can move it. And if you arrive at a room someone placed without a compass that looks turned the wrong way, a one-tap “Align to your view” straightens it out for you. (`/irl`) `[improvement]`- **AR & half-body avatar export fixed for compressed models** — View-in-AR (USDZ for iOS Quick Look) and the half-body VR-seat export now work for avatars that ship with meshopt or Draco geometry compression. Previously these exports silently failed on compressed GLBs because the loader had no decoder registered; the pipeline now loads the meshopt and Draco decoders before parsing, so every avatar — including the compressed ones produced by the server-side bake — converts cleanly. (`/gallery`) `[fix]`diff --git a/data/changelog.json b/data/changelog.jsonindex bfb9a143a..df5a2ae62 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-19",+ "title": "Agent Studio — one place to build your whole agent, with a live avatar",+ "summary": "Agent Studio is the new home for authoring everything about your AI agent — its brain, memory, 3D body, money, and skills — side by side with a live avatar that updates the instant you make a change, no save button and no refresh. The same living avatar can now appear anywhere on the platform as a presence companion, reacting with real emotion to what's happening: it celebrates a filled trade, looks concerned when a position drops, and stays in sync with whatever you edit in the Studio. This release ships the Studio shell and the shared foundation the rest of the experience builds on.",+ "tags": [+ "feature"+ ],+ "link": "/agent-studio"+ },{"date": "2026-06-19","title": "Pay-per-call vanity wallets now do seed phrases and encrypted delivery",diff --git a/data/pages.json b/data/pages.jsonindex ab5183818..64d2e43f5 100644--- a/data/pages.json+++ b/data/pages.json@@ -167,6 +167,14 @@"changefreq": "weekly","added": "2026-06-05"},+ {+ "path": "/agent-studio",+ "title": "Agent Studio",+ "description": "Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.",+ "auth": "required",+ "indexable": false,+ "added": "2026-06-19"+ },{"path": "/app","title": "Viewer",diff --git a/examples/agent-presence.html b/examples/agent-presence.htmlnew file mode 100644index 000000000..32e8c53f5--- /dev/null+++ b/examples/agent-presence.html@@ -0,0 +1,174 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title><agent-presence> — standalone harness · three.ws</title>+ <meta name="robots" content="noindex" />+ <style>+ :root {+ color-scheme: dark;+ --bg: #0a0a0a;+ --panel: rgba(255, 255, 255, 0.04);+ --stroke: rgba(255, 255, 255, 0.12);+ --ink: #e8e8e8;+ --dim: #888;+ --accent: #8b5cf6;+ font-family: 'Inter', system-ui, sans-serif;+ }+ body {+ margin: 0;+ background: var(--bg);+ color: var(--ink);+ padding: 24px;+ line-height: 1.6;+ }+ h1 { font-size: 22px; margin: 0 0 4px; }+ p.sub { color: var(--dim); margin: 0 0 20px; font-size: 14px; }+ .controls {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ align-items: center;+ margin-bottom: 20px;+ padding: 14px;+ background: var(--panel);+ border: 1px solid var(--stroke);+ border-radius: 14px;+ }+ .controls label { font-size: 12px; color: var(--dim); }+ input[type='text'] {+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--stroke);+ color: var(--ink);+ border-radius: 8px;+ padding: 7px 10px;+ font-size: 13px;+ min-width: 280px;+ }+ button {+ appearance: none;+ cursor: pointer;+ border: 1px solid var(--stroke);+ background: rgba(255, 255, 255, 0.06);+ color: var(--ink);+ border-radius: 8px;+ padding: 7px 12px;+ font-size: 13px;+ font-weight: 600;+ transition: background 0.15s, transform 0.1s;+ }+ button:hover { background: rgba(255, 255, 255, 0.12); }+ button:active { transform: scale(0.96); }+ button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .group { display: inline-flex; gap: 6px; align-items: center; flex-wrap: wrap; }+ .group + .group { margin-left: 12px; padding-left: 12px; border-left: 1px solid var(--stroke); }+ #mount {+ border: 1px dashed var(--stroke);+ border-radius: 14px;+ background: radial-gradient(120% 80% at 50% 0%, rgba(139, 92, 246, 0.1), transparent 60%);+ overflow: hidden;+ transition: width 0.25s, height 0.25s;+ }+ #mount[data-mode='stage'] { width: 100%; height: 600px; }+ #mount[data-mode='companion'] { width: 360px; height: 460px; }+ #mount[data-mode='mini'] { width: 100%; height: 200px; border-style: solid; opacity: 0.5; }+ #mount[data-mode='mini']::after {+ content: 'mini mode renders as a fixed, draggable, bottom-right companion →';+ display: grid;+ place-items: center;+ height: 100%;+ color: var(--dim);+ font-size: 13px;+ }+ .hint { font-size: 12px; color: var(--dim); margin-top: 12px; }+ code { background: rgba(255, 255, 255, 0.08); padding: 1px 5px; border-radius: 4px; }+ </style>+ </head>+ <body>+ <h1><agent-presence> harness</h1>+ <p class="sub">+ Standalone test for the global presence element — all three modes + live market reactions, on real data.+ </p>++ <div class="controls">+ <div class="group">+ <label for="id-input">agent / avatar id</label>+ <input id="id-input" type="text" placeholder="paste an agent-id or avatar-id (blank = your signed-in agent)" />+ <button id="apply-id">Load</button>+ </div>+ <div class="group">+ <label>mode</label>+ <button data-mode="stage">stage</button>+ <button data-mode="companion">companion</button>+ <button data-mode="mini">mini</button>+ </div>+ <div class="group">+ <label>react</label>+ <button data-react="snipe:filled">snipe:filled 🎉</button>+ <button data-react="position:down">position:down 😟</button>+ <button data-react="price:up">price:up</button>+ <button data-react="alert">alert</button>+ </div>+ </div>++ <div id="mount" data-mode="stage">+ <agent-presence id="presence" data-mode="stage"></agent-presence>+ </div>++ <p class="hint">+ Reaction buttons call <code>element.reactTo({ type })</code> directly and also broadcast via+ <code>studio.emitMarket(...)</code>. Edit your agent in <code>/agent-studio</code> in another tab and watch+ this avatar update live (when using your signed-in agent).+ </p>++ <script type="module">+ import '../src/studio/agent-presence.js';+ import { studio } from '../src/studio/agent-studio-store.js';++ const mount = document.getElementById('mount');+ let el = document.getElementById('presence');++ // Apply id from query string for quick deep-links (?agent= / ?avatar=).+ const qs = new URLSearchParams(location.search);+ const qAgent = qs.get('agent');+ const qAvatar = qs.get('avatar');+ if (qAgent) el.setAttribute('data-agent-id', qAgent);+ if (qAvatar) el.setAttribute('data-avatar-id', qAvatar);++ function rebuild(attrs) {+ // Re-create the element so a fresh boot picks up the new source.+ const next = document.createElement('agent-presence');+ next.id = 'presence';+ next.setAttribute('data-mode', mount.dataset.mode);+ if (attrs?.agentId) next.setAttribute('data-agent-id', attrs.agentId);+ if (attrs?.avatarId) next.setAttribute('data-avatar-id', attrs.avatarId);+ el.remove();+ mount.appendChild(next);+ el = next;+ }++ document.getElementById('apply-id').addEventListener('click', () => {+ const v = document.getElementById('id-input').value.trim();+ // A UUID with a leading 'a'/agent heuristic isn't reliable; treat the+ // pasted id as an agent-id first (the element falls back to avatar lookup).+ rebuild(v ? { agentId: v } : {});+ });++ for (const b of document.querySelectorAll('[data-mode]')) {+ b.addEventListener('click', () => {+ mount.dataset.mode = b.dataset.mode;+ el.setAttribute('data-mode', b.dataset.mode);+ });+ }++ for (const b of document.querySelectorAll('[data-react]')) {+ b.addEventListener('click', () => {+ const evt = { type: b.dataset.react, mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' };+ el.reactTo(evt);+ studio.emitMarket(evt);+ });+ }+ </script>+ </body>+</html>diff --git a/pages/agent-studio.html b/pages/agent-studio.htmlnew file mode 100644index 000000000..fb16436f3--- /dev/null+++ b/pages/agent-studio.html@@ -0,0 +1,390 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>Agent Studio · three.ws</title>+ <meta name="theme-color" content="#000000" />+ <meta name="mobile-web-app-capable" content="yes" />+ <meta name="apple-mobile-web-app-capable" content="yes" />+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />+ <meta name="apple-mobile-web-app-title" content="three.ws" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <meta+ name="description"+ content="Agent Studio — author your AI agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit."+ />+ <meta name="robots" content="noindex" />++ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <link rel="stylesheet" href="/buttons.css" />++ <style>+ html,+ body {+ margin: 0;+ background: var(--bg-0, #0a0a0a);+ color: var(--ink, #e8e8e8);+ font-family: var(--font-body, 'Inter', system-ui, sans-serif);+ }+ #studio-root {+ min-height: calc(100vh - var(--header-h, 3.5rem));+ }++ /* ── Layout ──────────────────────────────────────────────────────── */+ .studio {+ display: grid;+ grid-template-columns: minmax(340px, 42%) 1fr;+ gap: var(--space-md, 1rem);+ padding: var(--space-md, 1rem);+ max-width: 1600px;+ margin: 0 auto;+ min-height: calc(100vh - var(--header-h, 3.5rem));+ box-sizing: border-box;+ }++ /* Persistent live avatar stage */+ .studio-stage {+ position: relative;+ border-radius: var(--radius-lg, 14px);+ background:+ radial-gradient(120% 80% at 50% 0%, rgba(139, 92, 246, 0.12), transparent 60%),+ var(--surface-glass, linear-gradient(180deg, rgba(20, 21, 28, 0.7), rgba(14, 15, 22, 0.5)));+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ overflow: hidden;+ min-height: clamp(420px, 70vh, 820px);+ box-shadow: var(--shadow-2);+ }+ .studio-stage agent-presence {+ position: absolute;+ inset: 0;+ }+ .studio-stage-hud {+ position: absolute;+ left: 14px;+ bottom: 14px;+ display: inline-flex;+ align-items: center;+ gap: 7px;+ padding: 5px 11px;+ border-radius: var(--radius-pill, 999px);+ background: rgba(0, 0, 0, 0.45);+ border: 1px solid var(--stroke);+ backdrop-filter: blur(var(--blur-sm, 8px));+ -webkit-backdrop-filter: blur(var(--blur-sm, 8px));+ font-size: var(--text-2xs, 0.6875rem);+ font-weight: var(--weight-semibold, 600);+ color: var(--ink-dim, #888);+ pointer-events: none;+ }+ .studio-live-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--success, #4ade80);+ box-shadow: 0 0 8px var(--success, #4ade80);+ animation: studio-pulse 2s ease-in-out infinite;+ }+ @keyframes studio-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.4; }+ }++ /* Editing surface */+ .studio-panel {+ display: flex;+ flex-direction: column;+ min-width: 0;+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ overflow: hidden;+ }++ .studio-identity {+ display: grid;+ grid-template-columns: 1fr auto;+ grid-template-areas: 'name save' 'tag tag';+ gap: 4px var(--space-sm, 0.618rem);+ padding: var(--space-md, 1rem) var(--space-lg, 1.618rem);+ border-bottom: 1px solid var(--stroke);+ }+ .studio-name {+ grid-area: name;+ font-family: var(--font-display);+ font-size: var(--text-xl, 1.618rem);+ font-weight: var(--weight-bold, 700);+ color: var(--ink-bright, #fff);+ background: transparent;+ border: 1px solid transparent;+ border-radius: var(--radius-sm, 6px);+ padding: 2px 6px;+ margin-left: -6px;+ transition: border-color var(--duration-fast, 140ms) var(--ease-standard), background var(--duration-fast) var(--ease-standard);+ }+ .studio-tagline {+ grid-area: tag;+ font-size: var(--text-ui, 0.875rem);+ color: var(--ink-dim, #888);+ background: transparent;+ border: 1px solid transparent;+ border-radius: var(--radius-sm, 6px);+ padding: 2px 6px;+ margin-left: -6px;+ }+ .studio-name:hover,+ .studio-tagline:hover {+ border-color: var(--stroke);+ }+ .studio-name:focus,+ .studio-tagline:focus {+ outline: none;+ border-color: var(--stroke-strong);+ background: var(--surface-2);+ }+ .studio-save {+ grid-area: save;+ align-self: center;+ font-size: var(--text-2xs, 0.6875rem);+ font-weight: var(--weight-semibold, 600);+ color: var(--ink-faint);+ transition: color var(--duration-fast) var(--ease-standard);+ }+ .studio-save[data-state='pending'] { color: var(--warn, #fbbf24); }+ .studio-save[data-state='saved'] { color: var(--success, #4ade80); }+ .studio-save[data-state='error'] { color: var(--danger, #f87171); }++ /* Tabs */+ .studio-tabs {+ display: flex;+ gap: 2px;+ padding: var(--space-sm, 0.618rem) var(--space-lg, 1.618rem) 0;+ border-bottom: 1px solid var(--stroke);+ overflow-x: auto;+ scrollbar-width: none;+ }+ .studio-tabs::-webkit-scrollbar { display: none; }+ .studio-tab {+ appearance: none;+ display: inline-flex;+ align-items: center;+ gap: 7px;+ white-space: nowrap;+ padding: 9px 14px;+ border: none;+ border-bottom: 2px solid transparent;+ margin-bottom: -1px;+ background: transparent;+ color: var(--ink-dim, #888);+ font-family: var(--font-body);+ font-size: var(--text-ui, 0.875rem);+ font-weight: var(--weight-semibold, 600);+ cursor: pointer;+ border-radius: var(--radius-sm) var(--radius-sm) 0 0;+ transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);+ }+ .studio-tab:hover { color: var(--ink, #e8e8e8); background: var(--surface-1); }+ .studio-tab[aria-selected='true'] {+ color: var(--ink-bright, #fff);+ border-bottom-color: var(--accent, #fff);+ }+ .studio-tab:focus-visible {+ outline: 2px solid var(--focus-ring-color, #fff);+ outline-offset: -2px;+ }+ .studio-tab-num {+ display: inline-grid;+ place-items: center;+ width: 16px;+ height: 16px;+ border-radius: var(--radius-sm, 6px);+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ font-size: 10px;+ font-weight: var(--weight-bold, 700);+ color: var(--ink-dim);+ }+ .studio-tab[aria-selected='true'] .studio-tab-num {+ background: var(--accent-soft);+ color: var(--ink-bright);+ }++ .studio-tabpanels {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ }+ .studio-tabpanel {+ padding: var(--space-lg, 1.618rem);+ animation: studio-fade var(--duration-base, 220ms) var(--ease-out);+ }+ .studio-tabpanel:focus-visible {+ outline: 2px solid var(--focus-ring-color, #fff);+ outline-offset: -4px;+ border-radius: var(--radius-md);+ }+ @keyframes studio-fade {+ from { opacity: 0; transform: translateY(6px); }+ to { opacity: 1; transform: none; }+ }++ /* Designed empty state (each tab) */+ .studio-empty {+ max-width: 380px;+ margin: clamp(24px, 8vh, 80px) auto;+ text-align: center;+ color: var(--ink-dim, #888);+ }+ .studio-empty-glyph {+ width: 52px;+ height: 52px;+ margin: 0 auto var(--space-md, 1rem);+ border-radius: var(--radius-lg, 14px);+ background:+ radial-gradient(circle at 30% 30%, rgba(139, 92, 246, 0.4), transparent 70%),+ var(--surface-2, rgba(255, 255, 255, 0.05));+ border: 1px solid var(--stroke);+ }+ .studio-empty h2 {+ margin: 0 0 6px;+ font-family: var(--font-display);+ font-size: var(--text-lg, 1.236rem);+ color: var(--ink-bright, #fff);+ }+ .studio-empty p {+ margin: 0 0 var(--space-md, 1rem);+ font-size: var(--text-md, 0.8125rem);+ line-height: var(--leading-normal, 1.618);+ }++ /* Buttons (shell-local; mirrors token vocabulary) */+ .studio-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 9px 18px;+ border-radius: var(--radius-pill, 999px);+ font-family: var(--font-body);+ font-size: var(--text-ui, 0.875rem);+ font-weight: var(--weight-semibold, 600);+ text-decoration: none;+ cursor: pointer;+ border: 1px solid transparent;+ transition: transform var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);+ }+ .studio-btn:active { transform: scale(0.97); }+ .studio-btn:focus-visible { outline: 2px solid var(--focus-ring-color, #fff); outline-offset: 2px; }+ .studio-btn-primary {+ background: var(--ink-bright, #fff);+ color: var(--bg-0, #0a0a0a);+ }+ .studio-btn-primary:hover { background: #e6e6e6; }+ .studio-btn-ghost {+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink, #e8e8e8);+ border-color: var(--stroke);+ margin-top: 8px;+ }+ .studio-btn-ghost:hover { background: var(--surface-3); }++ /* Gate / error / empty-agent */+ .studio-gate {+ display: grid;+ place-items: center;+ min-height: calc(100vh - var(--header-h, 3.5rem));+ padding: var(--space-lg);+ }+ .studio-gate-inner {+ max-width: 460px;+ text-align: center;+ }+ .studio-gate-glyph {+ font-size: 44px;+ margin-bottom: var(--space-md);+ opacity: 0.7;+ }+ .studio-gate h1 {+ font-family: var(--font-display);+ font-size: var(--text-2xl, 2.618rem);+ margin: 0 0 var(--space-sm);+ color: var(--ink-bright, #fff);+ }+ .studio-gate p {+ font-size: var(--text-base, 1rem);+ line-height: var(--leading-normal);+ color: var(--ink-dim);+ margin: 0 0 var(--space-lg);+ }+ .studio-gate .studio-btn { margin: 6px; }++ /* Loading skeleton */+ .studio-skeleton {+ display: grid;+ grid-template-columns: minmax(340px, 42%) 1fr;+ gap: var(--space-md);+ padding: var(--space-md);+ max-width: 1600px;+ margin: 0 auto;+ }+ .studio-skeleton > div {+ border-radius: var(--radius-lg, 14px);+ background: linear-gradient(110deg, rgba(255, 255, 255, 0.03) 30%, rgba(255, 255, 255, 0.07) 50%, rgba(255, 255, 255, 0.03) 70%);+ background-size: 220% 100%;+ animation: studio-shimmer 1.4s ease-in-out infinite;+ }+ .sk-stage { min-height: clamp(420px, 70vh, 820px); }+ .sk-panel { display: flex; flex-direction: column; gap: 12px; padding: 20px; background: none; animation: none; }+ .sk-tabs { height: 38px; }+ .sk-rows { display: flex; flex-direction: column; gap: 12px; }+ .sk-row { height: 54px; }+ @keyframes studio-shimmer { to { background-position: -220% 0; } }++ /* ── Responsive ───────────────────────────────────────────────────── */+ @media (max-width: 980px) {+ .studio,+ .studio-skeleton {+ grid-template-columns: 1fr;+ }+ .studio-stage {+ position: sticky;+ top: calc(var(--header-h, 3.5rem) + 8px);+ z-index: 5;+ min-height: clamp(220px, 34vh, 360px);+ }+ .sk-stage { min-height: 240px; }+ }+ @media (max-width: 420px) {+ .studio { padding: var(--space-sm); gap: var(--space-sm); }+ .studio-stage { min-height: 180px; }+ .studio-identity { padding: var(--space-sm) var(--space-md); }+ .studio-tabs { padding: var(--space-xs) var(--space-md) 0; }+ .studio-tabpanel { padding: var(--space-md); }+ .studio-name { font-size: var(--text-lg, 1.236rem); }+ }+ @media (min-width: 1441px) {+ .studio-stage { min-height: clamp(560px, 78vh, 900px); }+ }+ @media (prefers-reduced-motion: reduce) {+ .studio-skeleton > div,+ .studio-live-dot,+ .studio-tabpanel { animation: none; }+ }+ </style>+ </head>+ <body>+ <div id="nav-container"></div>+ <script src="/nav.js"></script>++ <main id="studio-root"></main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>++ <script type="module" src="/src/studio/studio-shell.js"></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex 7e4b01e91..a696068ef 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,31 @@{- "generated_at": "2026-06-19T10:48:07.066Z",+ "generated_at": "2026-06-19T11:34:06.212Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-19",+ "type": "launch",+ "title": "Agent Studio",+ "summary": "Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.",+ "link": "/agent-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Agent Studio — one place to build your whole agent, with a live avatar",+ "summary": "Agent Studio is the new home for authoring everything about your AI agent — its brain, memory, 3D body, money, and skills — side by side with a live avatar that updates the instant you make a change, no save button and no refresh. The same living avatar can now appear anywhere on the platform as a presence companion, reacting with real emotion to what's happening: it celebrates a filled trade, looks concerned when a position drops, and stays in sync with whatever you edit in the Studio. This release ships the Studio shell and the shared foundation the rest of the experience builds on.",+ "link": "/agent-studio",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex bb6fc0f2c..b8c24152f 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Agent Studio</title>+ <link>https://three.ws/agent-studio</link>+ <guid isPermaLink="false">2026-06-19:Agent Studio</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.</description>+ </item>+ <item>+ <title>Agent Studio — one place to build your whole agent, with a live avatar</title>+ <link>https://three.ws/agent-studio</link>+ <guid isPermaLink="false">2026-06-19:Agent Studio — one place to build your whole agent, with a live avatar</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Agent Studio is the new home for authoring everything about your AI agent — its brain, memory, 3D body, money, and skills — side by side with a live avatar that updates the instant you make a change, no save button and no refresh. The same living avatar can now appear anywhere on the platform as a presence companion, reacting with real emotion to what's happening: it celebrates a filled trade, looks concerned when a position drops, and stays in sync with whatever you edit in the Studio. This release ships the Studio shell and the shared foundation the rest of the experience builds on.</description>+ </item><item><title>Agent wallet's full money loop is now verified end-to-end on devnet</title><link>https://three.ws/agent-wallet</link>diff --git a/public/features.json b/public/features.jsonindex a372ba5d0..343e8005a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T10:48:07.052Z",+ "generated_at": "2026-06-19T11:34:06.197Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -202,6 +202,16 @@"tags": [],"showcase": false},+ {+ "path": "/agent-studio",+ "title": "Agent Studio",+ "description": "Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.",+ "added": "2026-06-19",+ "auth": "required",+ "indexable": false,+ "tags": [],+ "showcase": false+ },{"path": "/app","title": "Viewer",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 53d83b2ea..132632d56 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -126,6 +126,14 @@ URL: https://three.ws/create-agentStep-by-step wizard to create a 3D AI agent: name, 3D body, skills, personality, voice, and on-chain identity.+### Agent Studio++URL: https://three.ws/agent-studio+Auth: required (sign-in)+Indexable: no (excluded from sitemap)++Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.+### ViewerURL: https://three.ws/appdiff --git a/public/nav-data.js b/public/nav-data.jsindex bd804303d..7d0cc8c55 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -44,6 +44,12 @@ export const NAV_GROUPS = [badge: 'New',desc: 'Guided wizard: name, 3D body, skills, personality → ship it',},+ {+ title: 'Agent Studio',+ href: '/agent-studio',+ badge: 'New',+ desc: "Author brain, memory, body, money & skills with a live avatar",+ },{title: 'Selfie to avatar',href: '/create/selfie',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 7622606ac..5140d3f7b 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 174 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 175 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 174 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 175 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -209,7 +209,7 @@<section class="sm-section" id="build"><header>- <h2>Build<span class="sm-count" data-count>30</span></h2>+ <h2>Build<span class="sm-count" data-count>31</span></h2><p class="sm-section-desc">Create and customize an agent.</p></header><ul class="sm-list">@@ -234,6 +234,13 @@<span class="sm-desc">Step-by-step wizard to create a 3D AI agent: name, 3D body, skills, personality, voice, and on-chain identity.</span></a></li>+ <li>+ <a href="/agent-studio">+ <span class="sm-title">Agent Studio<span class="sm-badge sm-badge-auth">sign-in</span><span class="sm-badge sm-badge-internal">internal</span></span>+ <span class="sm-path">/agent-studio</span>+ <span class="sm-desc">Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.</span>+ </a>+ </li><li><a href="/app"><span class="sm-title">Viewer</span>diff --git a/public/studio.css b/public/studio.cssnew file mode 100644index 000000000..4f9301805--- /dev/null+++ b/public/studio.css@@ -0,0 +1,303 @@+/* Agent Studio — shell + Brain Studio (P0 shell · P1 brain)+ * Uses the platform design tokens (public/tokens.css). Dark-first; light theme+ * inherits via the token overrides. */++.studio {+ --studio-stage-w: clamp(320px, 34vw, 560px);+ --node-persona: #8b8bff;+ --node-model: #4fd1c5;+ --node-memory: #f6ad55;+ --node-skill: #b794f4;+ --node-market: #68d391;+ --node-output: #fc8181;+ position: relative;+ display: grid;+ grid-template-columns: var(--studio-stage-w) 1fr;+ gap: var(--space-sm);+ height: calc(100vh - var(--nav-h, 56px));+ padding: var(--space-sm);+ box-sizing: border-box;+ background: var(--bg-0);+ color: var(--ink);+}+.studio--stage-collapsed { grid-template-columns: 64px 1fr; }++/* ── Stage ─────────────────────────────────────────────────────────────── */+.studio__stage {+ position: relative;+ border-radius: var(--radius-lg);+ background:+ radial-gradient(120% 80% at 50% 0%, rgba(139, 139, 255, 0.10), transparent 60%),+ var(--surface-glass);+ border: 1px solid var(--surface-2);+ overflow: hidden;+ min-height: 0;+}+.studio__stage-frame { position: absolute; inset: 0; }+.studio__stage-frame agent-presence { display: block; width: 100%; height: 100%; }+.studio__stage-meta {+ position: absolute; left: var(--space-md); bottom: var(--space-md);+ pointer-events: none; text-shadow: 0 1px 8px rgba(0, 0, 0, 0.6);+}+.studio__stage-name { font-size: var(--text-lg); font-weight: var(--weight-semibold); }+.studio__stage-sub { font-size: var(--text-sm); color: var(--ink-dim); }+.studio__stage-collapse {+ position: absolute; top: var(--space-sm); right: var(--space-sm);+ width: 28px; height: 28px; border-radius: var(--radius-pill);+ border: 1px solid var(--surface-3); background: var(--surface-1); color: var(--ink);+ cursor: pointer; display: grid; place-items: center; transition: background .15s, transform .15s;+}+.studio__stage-collapse:hover { background: var(--surface-3); }+.studio--stage-collapsed .studio__stage-meta { display: none; }+.studio--stage-collapsed .studio__stage-collapse { transform: rotate(180deg); }++/* ── Panel + tabs ──────────────────────────────────────────────────────── */+.studio__panel { display: flex; flex-direction: column; min-width: 0; min-height: 0; }+.studio__tabs {+ display: flex; align-items: center; gap: var(--space-3xs);+ padding: var(--space-3xs); margin-bottom: var(--space-sm);+ background: var(--surface-1); border: 1px solid var(--surface-2); border-radius: var(--radius-pill);+}+.studio__tab {+ display: inline-flex; align-items: center; gap: var(--space-2xs);+ padding: var(--space-2xs) var(--space-md); border: 0; border-radius: var(--radius-pill);+ background: transparent; color: var(--ink-dim); font-size: var(--text-ui); font-weight: var(--weight-medium);+ cursor: pointer; transition: background .15s, color .15s; white-space: nowrap;+}+.studio__tab:hover { color: var(--ink); }+.studio__tab.is-active { background: var(--surface-3); color: var(--ink-bright); }+.studio__tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.studio__tab-key {+ display: inline-grid; place-items: center; width: 16px; height: 16px;+ font-size: var(--text-2xs); color: var(--ink-faint); border: 1px solid var(--surface-3); border-radius: 4px;+}+.studio__tab.is-active .studio__tab-key { color: var(--ink); }+.studio__save { margin-left: auto; padding-right: var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); min-height: 1em; }+.studio__save.is-saving { color: var(--node-memory); }+.studio__save.is-saved { color: var(--node-market); }+.studio__save.is-error { color: var(--node-output); }++.studio__tabpanels { flex: 1; min-height: 0; position: relative; }+.studio__tabpanel { position: absolute; inset: 0; overflow: auto; }+.studio__tabpanel:not(.is-active) { display: none; }+.studio__tabpanel:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }++/* ── Placeholder tabs (P2–P5 land here) ────────────────────────────────── */+.studio__placeholder {+ height: 100%; display: grid; place-content: center; justify-items: center; text-align: center;+ gap: var(--space-sm); padding: var(--space-xl); color: var(--ink-dim);+}+.studio__placeholder-glyph {+ width: 56px; height: 56px; border-radius: var(--radius-lg);+ background: var(--surface-2); border: 1px dashed var(--surface-3);+}+.studio__placeholder h2 { margin: 0; color: var(--ink); font-size: var(--text-xl); }+.studio__placeholder p { margin: 0; max-width: 42ch; }++/* ── Buttons ───────────────────────────────────────────────────────────── */+.studio__btn {+ display: inline-flex; align-items: center; gap: var(--space-2xs);+ padding: var(--space-2xs) var(--space-md); border-radius: var(--radius-md);+ border: 1px solid var(--surface-3); background: var(--surface-1); color: var(--ink);+ font-size: var(--text-sm); font-weight: var(--weight-medium); cursor: pointer; text-decoration: none;+ transition: background .15s, border-color .15s, transform .1s;+}+.studio__btn:hover { background: var(--surface-3); }+.studio__btn:active { transform: translateY(1px); }+.studio__btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.studio__btn-primary { background: var(--accent); color: var(--bg-0); border-color: var(--accent); }+.studio__btn-primary:hover { filter: brightness(1.08); background: var(--accent); }+.studio__btn:disabled { opacity: .5; cursor: not-allowed; }++/* ── Overlays (loading / onboard / error) ──────────────────────────────── */+.studio__overlay { position: absolute; inset: 0; z-index: 20; display: grid; place-items: center; background: var(--bg-0); }+.studio[data-state="ready"] .studio__overlay { display: none; }+.studio__cta { text-align: center; max-width: 44ch; padding: var(--space-xl); }+.studio__cta h1 { font-size: var(--text-xl); margin: 0 0 var(--space-sm); }+.studio__cta p { color: var(--ink-dim); margin: 0 0 var(--space-lg); }+.studio__skeleton { display: grid; grid-template-columns: var(--studio-stage-w) 1fr; gap: var(--space-sm); width: 100%; height: 100%; padding: var(--space-sm); box-sizing: border-box; }+.studio__skeleton-stage, .sk-bar, .sk-block { background: linear-gradient(90deg, var(--surface-1), var(--surface-3), var(--surface-1)); background-size: 200% 100%; animation: sk 1.4s linear infinite; border-radius: var(--radius-lg); }+.studio__skeleton-panel { display: flex; flex-direction: column; gap: var(--space-sm); }+.sk-bar { height: 44px; border-radius: var(--radius-pill); }+.sk-block { flex: 1; }+@keyframes sk { from { background-position: 200% 0; } to { background-position: -200% 0; } }++/* ════════════════════════ Brain Studio ════════════════════════ */+.brainstudio { height: 100%; display: flex; flex-direction: column; min-height: 0; }+.brainstudio__editor { display: flex; flex-direction: column; height: 100%; min-height: 0; }++/* Onboarding */+.brainstudio__onboard { height: 100%; display: grid; place-items: center; padding: var(--space-lg); }+.brainstudio__onboard-inner { max-width: 720px; text-align: center; }+.brainstudio__onboard h1 { font-size: var(--text-2xl); margin: 0 0 var(--space-xs); }+.brainstudio__onboard p { color: var(--ink-dim); margin: 0 0 var(--space-lg); }+.brainstudio__templates { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: var(--space-sm); margin-bottom: var(--space-lg); }+.brainstudio__tpl {+ text-align: left; padding: var(--space-md); border-radius: var(--radius-lg); cursor: pointer;+ border: 1px solid var(--surface-3); background: var(--surface-1); color: var(--ink);+ display: flex; flex-direction: column; gap: var(--space-2xs); transition: transform .12s, border-color .15s, background .15s;+}+.brainstudio__tpl:hover { transform: translateY(-2px); background: var(--surface-2); }+.brainstudio__tpl::before { content: ''; width: 26px; height: 4px; border-radius: 2px; background: var(--accent); }+.brainstudio__tpl--persona::before { background: var(--node-persona); }+.brainstudio__tpl--model::before { background: var(--node-model); }+.brainstudio__tpl--memory::before { background: var(--node-memory); }+.brainstudio__tpl--market::before { background: var(--node-market); }+.brainstudio__tpl-name { font-weight: var(--weight-semibold); }+.brainstudio__tpl-tag { font-size: var(--text-sm); color: var(--ink-dim); }++/* Toolbar */+.brainstudio__toolbar { display: flex; align-items: center; gap: var(--space-sm); margin-bottom: var(--space-sm); flex-wrap: wrap; }+.brainstudio__palette { display: flex; gap: var(--space-2xs); flex-wrap: wrap; }+.brainstudio__tools { margin-left: auto; display: flex; gap: var(--space-2xs); }+.brainstudio__chip {+ padding: var(--space-3xs) var(--space-sm); border-radius: var(--radius-pill); cursor: pointer;+ border: 1px solid var(--surface-3); background: var(--surface-1); color: var(--ink-dim);+ font-size: var(--text-sm); font-weight: var(--weight-medium); transition: color .15s, border-color .15s, background .15s;+}+.brainstudio__chip:hover { color: var(--ink); background: var(--surface-2); }+.brainstudio__chip--persona:hover { border-color: var(--node-persona); }+.brainstudio__chip--model:hover { border-color: var(--node-model); }+.brainstudio__chip--memory:hover { border-color: var(--node-memory); }+.brainstudio__chip--skill:hover { border-color: var(--node-skill); }+.brainstudio__chip--market:hover { border-color: var(--node-market); }+.brainstudio__chip--output:hover { border-color: var(--node-output); }++/* Main split: canvas + side */+.brainstudio__main { flex: 1; display: grid; grid-template-columns: 1fr minmax(280px, 360px); gap: var(--space-sm); min-height: 0; }+.brainstudio__canvas {+ position: relative; overflow: hidden; border-radius: var(--radius-lg);+ border: 1px solid var(--surface-2); background-color: var(--bg-1);+ background-image: radial-gradient(var(--surface-3) 1px, transparent 1px);+ background-size: 22px 22px; touch-action: none; cursor: grab;+}+.brainstudio__canvas.is-panning { cursor: grabbing; }+.brainstudio__side { display: flex; flex-direction: column; gap: var(--space-sm); min-height: 0; }++/* ── Graph (BrainGraphView) ─────────────────────────────────────────────── */+.bgraph { position: absolute; inset: 0; overflow: hidden; }+.bgraph__world { position: absolute; inset: 0; transform-origin: 0 0; }+.bgraph__edges { position: absolute; left: 0; top: 0; width: 8000px; height: 8000px; overflow: visible; pointer-events: none; }+.bgraph__nodes { position: absolute; inset: 0; }+.bgraph__hint { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); font-size: var(--text-sm); color: var(--ink-dim); background: var(--surface-1); padding: 2px 10px; border-radius: var(--radius-pill); pointer-events: none; }++.bedge { fill: none; stroke: var(--surface-3); stroke-width: 2; transition: stroke .2s; }+.bedge-hit { fill: none; stroke: transparent; stroke-width: 14; pointer-events: stroke; cursor: pointer; }+.bedge.is-active { stroke: var(--accent); stroke-width: 2.5; filter: drop-shadow(0 0 4px var(--accent)); }+.bedge--ghost { stroke: var(--accent); stroke-dasharray: 5 4; opacity: .7; }+.bedge.is-flow { stroke-dasharray: 7 6; animation: bflow .6s linear infinite; }+@keyframes bflow { to { stroke-dashoffset: -26; } }++.bnode {+ position: absolute; left: 0; top: 0; box-sizing: border-box;+ border-radius: var(--radius-md); border: 1px solid var(--surface-3);+ background: var(--surface-glass); backdrop-filter: blur(8px);+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35); user-select: none;+ transition: box-shadow .15s, border-color .15s;+}+.bnode.is-selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), 0 8px 28px rgba(0, 0, 0, 0.45); }+.bnode.is-active { border-color: var(--accent); }+.bnode.is-pulse { animation: bpulse .7s ease-out; }+@keyframes bpulse { 0% { box-shadow: 0 0 0 0 var(--accent); } 100% { box-shadow: 0 0 0 14px transparent; } }+.bnode.is-busy .bnode__head::after { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--node-memory); margin-left: auto; animation: bbusy .8s ease-in-out infinite; }+@keyframes bbusy { 0%, 100% { opacity: .3; } 50% { opacity: 1; } }++.bnode__head { display: flex; align-items: center; gap: var(--space-2xs); height: 34px; padding: 0 var(--space-sm); border-bottom: 1px solid var(--surface-2); cursor: grab; border-radius: var(--radius-md) var(--radius-md) 0 0; }+.bnode__head::before { content: ''; width: 8px; height: 8px; border-radius: 2px; background: var(--accent); }+.bnode--persona .bnode__head::before { background: var(--node-persona); }+.bnode--model .bnode__head::before { background: var(--node-model); }+.bnode--memory .bnode__head::before { background: var(--node-memory); }+.bnode--skill .bnode__head::before { background: var(--node-skill); }+.bnode--market .bnode__head::before { background: var(--node-market); }+.bnode--output .bnode__head::before { background: var(--node-output); }+.bnode__title { font-size: var(--text-sm); font-weight: var(--weight-semibold); }+.bnode__del { margin-left: auto; border: 0; background: transparent; color: var(--ink-faint); cursor: pointer; font-size: var(--text-base); line-height: 1; padding: 2px 4px; border-radius: 4px; }+.bnode__del:hover { color: var(--node-output); background: var(--surface-2); }+.bnode__summary { padding: var(--space-2xs) var(--space-sm); font-size: var(--text-sm); color: var(--ink-dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.bnode__ports { display: flex; justify-content: space-between; padding-bottom: var(--space-2xs); }+.bnode__col { display: flex; flex-direction: column; gap: 6px; }+.bport { display: flex; align-items: center; gap: 5px; height: 20px; font-size: var(--text-2xs); color: var(--ink-faint); cursor: crosshair; padding: 0 var(--space-2xs); }+.bport--out { flex-direction: row-reverse; }+.bport__dot { width: 11px; height: 11px; border-radius: 50%; background: var(--bg-1); border: 2px solid var(--ink-dim); transition: transform .1s, border-color .15s; }+.bport:hover .bport__dot { transform: scale(1.25); }+.bport--signal .bport__dot { border-color: var(--node-persona); }+.bport--context .bport__dot { border-color: var(--node-memory); }+.bport--tool .bport__dot { border-color: var(--node-skill); }+.bnode__stat { padding: 2px var(--space-sm) var(--space-2xs); font-size: var(--text-2xs); color: var(--node-model); }++/* ── Inspector ──────────────────────────────────────────────────────────── */+.brainstudio__inspector { background: var(--surface-1); border: 1px solid var(--surface-2); border-radius: var(--radius-lg); padding: var(--space-md); overflow: auto; max-height: 48%; }+.brainstudio__inspector-empty h3, .brainstudio__insp-head h3 { margin: 0 0 var(--space-2xs); font-size: var(--text-md); }+.brainstudio__inspector-empty p { margin: 0; color: var(--ink-dim); font-size: var(--text-sm); }+.brainstudio__insp-head { display: flex; align-items: center; gap: var(--space-2xs); margin-bottom: var(--space-sm); }+.brainstudio__insp-dot { width: 10px; height: 10px; border-radius: 3px; background: var(--accent); }+.brainstudio__insp-dot--persona { background: var(--node-persona); }+.brainstudio__insp-dot--model { background: var(--node-model); }+.brainstudio__insp-dot--memory { background: var(--node-memory); }+.brainstudio__insp-dot--skill { background: var(--node-skill); }+.brainstudio__insp-dot--market { background: var(--node-market); }+.brainstudio__insp-dot--output { background: var(--node-output); }+.brainstudio__fields { display: flex; flex-direction: column; gap: var(--space-sm); }+.brainstudio__field { display: flex; flex-direction: column; gap: var(--space-3xs); }+.brainstudio__field-label { font-size: var(--text-sm); color: var(--ink-dim); }+.brainstudio__input { width: 100%; box-sizing: border-box; padding: var(--space-2xs) var(--space-sm); background: var(--bg-1); color: var(--ink); border: 1px solid var(--surface-3); border-radius: var(--radius-md); font-size: var(--text-sm); font-family: inherit; }+.brainstudio__input:focus { outline: none; border-color: var(--accent); }+textarea.brainstudio__input { resize: vertical; }+.brainstudio__toggle { position: relative; display: inline-block; width: 38px; height: 22px; }+.brainstudio__toggle input { opacity: 0; width: 0; height: 0; }+.brainstudio__toggle span { position: absolute; inset: 0; background: var(--surface-3); border-radius: var(--radius-pill); transition: background .15s; cursor: pointer; }+.brainstudio__toggle span::before { content: ''; position: absolute; width: 16px; height: 16px; left: 3px; top: 3px; background: var(--ink); border-radius: 50%; transition: transform .15s; }+.brainstudio__toggle input:checked + span { background: var(--accent); }+.brainstudio__toggle input:checked + span::before { transform: translateX(16px); background: var(--bg-0); }+.brainstudio__toggle input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 2px; }++/* ── Test chat ──────────────────────────────────────────────────────────── */+.brainstudio__test { flex: 1; display: flex; flex-direction: column; min-height: 0; background: var(--surface-1); border: 1px solid var(--surface-2); border-radius: var(--radius-lg); overflow: hidden; }+.brainstudio__test-head { padding: var(--space-2xs) var(--space-md); border-bottom: 1px solid var(--surface-2); font-size: var(--text-sm); font-weight: var(--weight-semibold); }+.brainstudio__test-model { color: var(--ink-faint); font-weight: var(--weight-regular); }+.brainstudio__transcript { flex: 1; overflow: auto; padding: var(--space-sm); display: flex; flex-direction: column; gap: var(--space-sm); }+.brainstudio__msg { max-width: 90%; padding: var(--space-2xs) var(--space-sm); border-radius: var(--radius-md); font-size: var(--text-sm); white-space: pre-wrap; word-break: break-word; }+.brainstudio__msg--user { align-self: flex-end; background: var(--accent); color: var(--bg-0); }+.brainstudio__msg--agent { align-self: flex-start; background: var(--surface-3); color: var(--ink); }+.brainstudio__msg.is-error { background: rgba(252, 129, 129, 0.15); color: var(--node-output); }+.brainstudio__msg-stat { margin-top: 4px; font-size: var(--text-2xs); color: var(--ink-faint); }+.brainstudio__msg--user .brainstudio__msg-stat { display: none; }+.brainstudio__compose { display: flex; gap: var(--space-2xs); padding: var(--space-2xs); border-top: 1px solid var(--surface-2); }+.brainstudio__compose textarea { flex: 1; resize: none; padding: var(--space-2xs) var(--space-sm); background: var(--bg-1); color: var(--ink); border: 1px solid var(--surface-3); border-radius: var(--radius-md); font-family: inherit; font-size: var(--text-sm); }+.brainstudio__compose textarea:focus { outline: none; border-color: var(--accent); }++/* ── Modal (templates + behavior diff) ──────────────────────────────────── */+.brainstudio__modal { position: absolute; inset: 0; z-index: 30; display: grid; place-items: center; background: rgba(0, 0, 0, 0.55); padding: var(--space-md); }+.brainstudio__modal-card { width: min(720px, 100%); max-height: 86%; overflow: auto; background: var(--bg-1); border: 1px solid var(--surface-3); border-radius: var(--radius-lg); padding: var(--space-lg); }+.brainstudio__modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--space-2xs); }+.brainstudio__modal-head h2 { margin: 0; font-size: var(--text-lg); }+.brainstudio__modal-x { border: 0; background: transparent; color: var(--ink-dim); font-size: var(--text-xl); cursor: pointer; line-height: 1; }+.brainstudio__modal-sub { margin: 0 0 var(--space-md); color: var(--ink-dim); font-size: var(--text-sm); }+.brainstudio__behavior-meta { display: flex; flex-wrap: wrap; gap: var(--space-sm); margin-bottom: var(--space-md); font-size: var(--text-sm); color: var(--ink-dim); }+.brainstudio__behavior-meta b { color: var(--ink); font-weight: var(--weight-medium); }+.brainstudio__diff { white-space: pre-wrap; word-break: break-word; background: var(--bg-0); border: 1px solid var(--surface-2); border-radius: var(--radius-md); padding: var(--space-md); font-size: var(--text-sm); line-height: var(--leading-normal); max-height: 50vh; overflow: auto; }+.diff-add { color: var(--node-market); }+.diff-del { color: var(--node-output); text-decoration: line-through; opacity: .8; }+.diff-muted { color: var(--ink-faint); }++/* ── Responsive ─────────────────────────────────────────────────────────── */+@media (max-width: 1024px) {+ .brainstudio__main { grid-template-columns: 1fr; grid-template-rows: minmax(260px, 1fr) auto; }+ .brainstudio__side { flex-direction: row; }+ .brainstudio__inspector { max-height: none; flex: 1; }+ .brainstudio__test { flex: 1; }+}+@media (max-width: 900px) {+ .studio { grid-template-columns: 1fr; grid-template-rows: minmax(160px, 26vh) 1fr; height: auto; min-height: calc(100vh - var(--nav-h, 56px)); }+ .studio__skeleton { grid-template-columns: 1fr; grid-template-rows: 26vh 1fr; }+ .brainstudio__side { flex-direction: column; }+}+@media (max-width: 560px) {+ .studio__tab { padding: var(--space-2xs) var(--space-sm); }+ .studio__tab-key { display: none; }+}+@media (prefers-reduced-motion: reduce) {+ .bedge.is-flow { animation: none; }+ .bnode.is-pulse { animation: none; }+ .studio__skeleton-stage, .sk-bar, .sk-block { animation: none; }+}diff --git a/src/agent-identity.js b/src/agent-identity.jsindex 22b45062d..0e18993c2 100644--- a/src/agent-identity.js+++ b/src/agent-identity.js@@ -136,6 +136,25 @@ export class AgentIdentity {await this.save();}+ /**+ * Adopt an authoritative agent record returned by the backend WITHOUT issuing+ * another network call. Lets a caller that owns its own PUT (e.g. the Agent+ * Studio store, which needs optimistic updates + rollback + updated_at conflict+ * reconciliation that `save()` can't express) keep this identity + its+ * localStorage cache coherent with what the server stored. Returns the record.+ * @param {Object} apiRecord — a decorated agent record from /api/agents/:id+ */+ applyServerRecord(apiRecord) {+ if (!apiRecord) return this._record;+ this._record = _normalise(apiRecord);+ this._agentId = this._record.id;+ this._loaded = true;+ this._backendConfirmed = true;+ this._owned = apiRecord.is_owner === true || Boolean(apiRecord.user_id);+ this._persist();+ return this._record;+ }+// ── Wallet ────────────────────────────────────────────────────────────────async linkWallet(address, chainId) {diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.jsindex d6f2acf90..4dbd75341 100644--- a/src/agent-solana-wallet.js+++ b/src/agent-solana-wallet.js@@ -73,10 +73,15 @@ export async function provisionAgentSolanaWallet({};}+ // Provisioning/importing a keypair changes which keys control the agent's+ // funds — carry a single-use CSRF token (the server burns it on use).+ const provisionHeaders = body ? { 'Content-Type': 'application/json' } : {};+ const provisionToken = await consumeCsrfToken();+ if (provisionToken) provisionHeaders['x-csrf-token'] = provisionToken;const resp = await fetch(ENDPOINT(agentId), {method: 'POST',credentials: 'include',- headers: body ? { 'Content-Type': 'application/json' } : {},+ headers: provisionHeaders,body: body ? JSON.stringify(body) : undefined,signal,});@@ -91,7 +96,10 @@ export async function provisionAgentSolanaWallet({}export async function deleteAgentSolanaWallet(agentId) {- const resp = await fetch(ENDPOINT(agentId), { method: 'DELETE', credentials: 'include' });+ const delHeaders = {};+ const delToken = await consumeCsrfToken();+ if (delToken) delHeaders['x-csrf-token'] = delToken;+ const resp = await fetch(ENDPOINT(agentId), { method: 'DELETE', credentials: 'include', headers: delHeaders });if (!resp.ok) {const j = await resp.json().catch(() => ({}));throw new Error(j?.error?.message || `delete failed (${resp.status})`);diff --git a/src/agent-wallet-hub/tabs/vanity.js b/src/agent-wallet-hub/tabs/vanity.jsindex 9b6d44963..4ba0d01f7 100644--- a/src/agent-wallet-hub/tabs/vanity.js+++ b/src/agent-wallet-hub/tabs/vanity.js@@ -14,6 +14,7 @@*/import { registerWalletTab } from '../registry.js';+import { consumeCsrfToken } from '../../api.js';const MAX_CHARS = 3;const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]*$/;@@ -49,6 +50,12 @@ async function call(url, { method = 'GET', body = null } = {}) {opts.headers['content-type'] = 'application/json';opts.body = JSON.stringify(body);}+ // Grinding a vanity address swaps the keypair and sweeps funds — the POST is+ // state-changing, so carry a single-use CSRF token (server burns it on use).+ if (method !== 'GET') {+ const token = await consumeCsrfToken();+ if (token) opts.headers['x-csrf-token'] = token;+ }const r = await fetch(url, opts);let j = null;try { j = await r.json(); } catch { /* empty body */ }diff --git a/src/studio/agent-presence.js b/src/studio/agent-presence.jsnew file mode 100644index 000000000..6af4da290--- /dev/null+++ b/src/studio/agent-presence.js@@ -0,0 +1,575 @@+/**+ * ════════════════════════════════════════════════════════════════════════════+ * <agent-presence> — the user's live agent, rendered on every page (P0)+ * ════════════════════════════════════════════════════════════════════════════+ *+ * A framework-agnostic custom element that renders the caller's live 3D agent and+ * keeps it in lock-step with Agent Studio: edit a field anywhere (via the shared+ * `studio` store) and every <agent-presence> on the page updates instantly — no+ * save, no refresh. It also reacts to market/trade events with avatar emotion.+ *+ * <agent-presence data-mode="stage"></agent-presence> <!-- full studio stage -->+ * <agent-presence data-mode="companion"></agent-presence> <!-- sidebar size -->+ * <agent-presence data-mode="mini"></agent-presence> <!-- floating companion -->+ * <agent-presence data-agent-id="…"></agent-presence> <!-- pin a specific agent -->+ * <agent-presence data-avatar-id="…"></agent-presence> <!-- render a bare avatar -->+ *+ * It reuses the platform's renderer wholesale — `Viewer` (src/viewer.js) ++ * `AgentAvatar` (src/agent-avatar.js, emotion blend + idle loop + lip-sync) ++ * the singleton `protocol` (src/agent-protocol.js) — it does NOT fork rendering.+ *+ * Reactions (P4/P5 emit market events through `studio.emitMarket`):+ * element.reactTo({ type: 'snipe:filled' }) → celebration + cheer gesture+ * element.reactTo({ type: 'position:down' }) → concern + glance down+ * Default mappings ship below; pass any { type, ... } event.+ *+ * PERFORMANCE (this renders on every page, so it is built to disappear when idle):+ * • Heavy Three.js modules are lazy-imported on first reveal, never at parse.+ * • The Viewer only renders while on-screen AND the tab is visible — it owns an+ * IntersectionObserver + visibilitychange gate internally; we also defer boot+ * until first intersection so an off-screen companion costs nothing.+ * • DPR is capped (1.5 for mini/companion, 2 for the stage).+ * • mini mode is position:fixed/transform-only so it never reflows or janks scroll.+ */++import { studio } from './agent-studio-store.js';+import { log } from '../shared/log.js';++const MINI_POS_KEY = 'tws:presence:mini:pos';++// Market-event → reaction mapping. Each entry drives the existing emotion system+// (emote stimulus via the protocol bus) and, optionally, a one-shot gesture clip+// and a gaze direction. Tunable here; P4/P5 only need to emit the event types.+const REACTIONS = {+ 'snipe:filled': { emote: ['celebration', 0.95], gesture: 'celebrate', look: null },+ 'trade:filled': { emote: ['celebration', 0.8], gesture: 'celebrate', look: null },+ 'trade:buy': { emote: ['curiosity', 0.5], gesture: null, look: 'token' },+ 'trade:sell': { emote: ['patience', 0.4], gesture: null, look: 'token' },+ 'position:up': { emote: ['celebration', 0.7], gesture: null, look: 'up' },+ 'position:down': { emote: ['concern', 0.7], gesture: 'concern', look: 'down' },+ 'price:up': { emote: ['celebration', 0.4], gesture: null, look: null },+ 'price:down': { emote: ['concern', 0.4], gesture: null, look: null },+ 'snipe:failed': { emote: ['concern', 0.7], gesture: null, look: 'down' },+ 'trade:failed': { emote: ['empathy', 0.6], gesture: null, look: 'down' },+ 'alert': { emote: ['curiosity', 0.6], gesture: null, look: 'token' },+};+const DEFAULT_REACTION = { emote: ['curiosity', 0.4], gesture: null, look: null };++class AgentPresenceElement extends HTMLElement {+ static get observedAttributes() {+ return ['data-mode', 'data-agent-id', 'data-avatar-id'];+ }++ constructor() {+ super();+ this.attachShadow({ mode: 'open' });+ this._viewer = null;+ this._avatar = null;+ this._protocol = null;+ this._ACTION = null;+ this._booted = false;+ this._booting = false;+ this._disposed = false;+ this._currentAvatarId = undefined; // tracks body so we reload only on real change+ this._currentModelUrl = null;+ this._unsubStudio = null;+ this._unsubMarket = null;+ this._io = null;+ this._dragCleanup = null;+ this._reactQueue = [];+ }++ get mode() {+ return this.getAttribute('data-mode') || 'stage';+ }++ // ── Lifecycle ───────────────────────────────────────────────────────────────++ connectedCallback() {+ this._renderShell();+ // Defer the heavy boot until the element is actually on screen. For a+ // scrolled-away companion this means zero WebGL cost until it matters.+ if (typeof IntersectionObserver !== 'undefined') {+ this._io = new IntersectionObserver(+ (entries) => {+ if (entries.some((e) => e.isIntersecting)) {+ this._io.disconnect();+ this._io = null;+ this._boot();+ }+ },+ { rootMargin: '200px' },+ );+ this._io.observe(this);+ } else {+ this._boot();+ }+ }++ disconnectedCallback() {+ this._teardown();+ }++ attributeChangedCallback(name, oldVal, newVal) {+ if (oldVal === newVal) return;+ if (name === 'data-mode') {+ this._applyMode();+ } else if ((name === 'data-agent-id' || name === 'data-avatar-id') && this._booted) {+ this._refreshBody();+ }+ }++ // ── Boot ─────────────────────────────────────────────────────────────────++ async _boot() {+ if (this._booted || this._booting || this._disposed) return;+ this._booting = true;+ this._setStatus('loading');+ try {+ // Lazy-load the renderer + emotion layer + protocol bus together.+ const [{ Viewer }, { AgentAvatar }, protocolMod] = await Promise.all([+ import('../viewer.js'),+ import('../agent-avatar.js'),+ import('../agent-protocol.js'),+ ]);+ if (this._disposed) return;+ this._protocol = protocolMod.protocol;+ this._ACTION = protocolMod.ACTION_TYPES;++ const stageEl = this.shadowRoot.getElementById('stage');+ const dprCap = this.mode === 'stage' ? 2 : 1.5;+ this._viewer = new Viewer(stageEl, {+ kiosk: true,+ maxPixelRatio: dprCap,+ framing: this.mode === 'mini' ? 'portrait' : 'full',+ });+ this._viewer.state.transparentBg = true;+ this._viewer.updateBackground();++ const resolved = await this._resolveBody();+ if (this._disposed) return;++ if (!resolved) {+ this._handleNoBody();+ this._booted = true;+ this._booting = false;+ this._subscribe();+ return;+ }++ await this._loadModel(resolved, Viewer, AgentAvatar);+ this._booted = true;+ this._booting = false;+ this._setStatus('live');+ this._subscribe();+ // Replay any reactions that arrived during boot.+ const q = this._reactQueue;+ this._reactQueue = [];+ for (const evt of q) this.reactTo(evt);+ } catch (err) {+ log.warn('[agent-presence] boot failed', err);+ this._booting = false;+ this._setStatus('error');+ }+ }++ async _loadModel(modelUrl, Viewer, AgentAvatar) {+ await this._viewer.load(modelUrl, '', new Map());+ this._currentModelUrl = modelUrl;++ // Emotion + idle + lip-sync layer. AgentAvatar.attach() starts the procedural+ // idle loop and the per-frame empathy tick; we share the SINGLETON protocol so+ // reactTo() (and any other surface) can drive this avatar.+ const identity = studio.identity || { id: this.getAttribute('data-agent-id') || 'presence' };+ this._avatar = new AgentAvatar(this._viewer, this._protocol, identity);+ this._avatar.attach();++ // Best-effort baked idle so a rig with an "idle" clip loops it; the procedural+ // IdleAnimation inside AgentAvatar keeps a clip-less rig breathing regardless.+ try {+ const am = this._viewer.animationManager;+ if (am && (await am.ensureLoaded('idle'))) am.crossfadeTo('idle', 0.4);+ } catch {+ /* procedural idle covers it */+ }+ }++ // Resolve the GLB URL for the agent/avatar this presence should render.+ // Order: explicit data-avatar-id → studio agent's bound avatar → data-agent-id+ // → null (designed "no body" state). Never invents a fake body.+ async _resolveBody() {+ const { apiFetch } = await import('../api.js');++ const explicitAvatar = this.getAttribute('data-avatar-id');+ if (explicitAvatar) {+ this._currentAvatarId = explicitAvatar;+ return this._avatarUrl(explicitAvatar, apiFetch);+ }++ const explicitAgent = this.getAttribute('data-agent-id');+ if (explicitAgent) {+ return this._agentBodyUrl(explicitAgent, apiFetch);+ }++ // Default source: the Studio store's live agent.+ await studio.load();+ const agent = studio.agent;+ this._currentAvatarId = agent?.avatarId || null;+ if (agent?.avatarId) {+ const url = await this._avatarUrl(agent.avatarId, apiFetch);+ if (url) return url;+ }+ return null;+ }++ async _agentBodyUrl(agentId, apiFetch) {+ try {+ const res = await apiFetch(`/api/agents/${agentId}`, { allowAnonymous: true });+ if (!res.ok) return null;+ const { agent } = await res.json();+ this._currentAvatarId = agent?.avatar_id || null;+ if (agent?.avatar_model_url) return agent.avatar_model_url;+ if (agent?.avatar_id) return this._avatarUrl(agent.avatar_id, apiFetch);+ return null;+ } catch {+ return null;+ }+ }++ async _avatarUrl(avatarId, apiFetch) {+ try {+ const res = await apiFetch(`/api/avatars/${avatarId}`, { allowAnonymous: true });+ if (!res.ok) return null;+ const { avatar } = await res.json();+ return avatar?.url || avatar?.model_url || null;+ } catch {+ return null;+ }+ }++ // ── Reactivity: stay in sync with Studio edits ──────────────────────────────++ _subscribe() {+ // Only the default (store-backed) presence tracks the live store. An element+ // pinned to an explicit agent/avatar id renders that one statically, but still+ // listens for market events so it can react.+ if (this.getAttribute('data-agent-id') || this.getAttribute('data-avatar-id')) {+ this._unsubMarket = studio.onMarket((evt) => this.reactTo(evt));+ return;+ }+ this._unsubStudio = studio.subscribe((agent) => this._onStudioChange(agent));+ this._unsubMarket = studio.onMarket((evt) => this.reactTo(evt));+ }++ _onStudioChange(agent) {+ if (!agent) return;+ this._updateNameplate(agent.name);+ // Reload the body only when the bound avatar actually changes (covers both+ // patch({avatarId}) and preview({avatarId})). Other edits never touch the rig.+ if (agent.avatarId !== this._currentAvatarId) {+ this._currentAvatarId = agent.avatarId;+ this._refreshBody();+ }+ }++ async _refreshBody() {+ if (!this._viewer || this._disposed) return;+ const resolved = await this._resolveBody();+ if (this._disposed || !this._viewer) return;+ if (!resolved) {+ this._handleNoBody();+ return;+ }+ this.hidden = false;+ if (resolved === this._currentModelUrl) return;+ this._setStatus('loading');+ try {+ const { Viewer } = await import('../viewer.js');+ const { AgentAvatar } = await import('../agent-avatar.js');+ this._avatar?.detach();+ this._avatar = null;+ await this._loadModel(resolved, Viewer, AgentAvatar);+ this._setStatus('live');+ } catch (err) {+ log.warn('[agent-presence] body refresh failed', err);+ this._setStatus('error');+ }+ }++ // A bodiless agent: show the "give it a body" CTA only to the OWNER (the CTA+ // routes into the owner-gated Studio). For an anonymous visitor or a pinned+ // someone-else's agent there is nothing actionable, so hide rather than show a+ // dead-end CTA — a site-wide companion simply doesn't appear until there's a body.+ _handleNoBody() {+ const pinned = this.getAttribute('data-agent-id') || this.getAttribute('data-avatar-id');+ const owned = !pinned && studio.agent?.isOwner === true;+ if (owned) {+ this.hidden = false;+ this._setStatus('no-body');+ } else {+ this.hidden = true;+ }+ }++ // ── Reactions ────────────────────────────────────────────────────────────++ /**+ * Map a market/trade event to an avatar reaction. Public API — P4/P5 emit+ * events via studio.emitMarket and presence forwards them here; you can also+ * call element.reactTo({ type }) directly.+ * @param {{ type: string }} event+ */+ reactTo(event) {+ if (!event || typeof event !== 'object') return;+ if (!this._booted || !this._avatar || !this._protocol) {+ // Queue until the avatar is live so an early trade isn't dropped.+ if (this._reactQueue.length < 16) this._reactQueue.push(event);+ return;+ }+ const map = REACTIONS[event.type] || DEFAULT_REACTION;+ const [trigger, weight] = map.emote;+ this._protocol.emit({ type: this._ACTION.EMOTE, payload: { trigger, weight } });+ if (map.look) {+ this._protocol.emit({ type: this._ACTION.LOOK_AT, payload: { target: map.look } });+ }+ if (map.gesture) {+ try {+ this._avatar.playGesture(map.gesture);+ } catch {+ /* clip not on this rig — emotion still conveys it */+ }+ }+ }++ // ── Shell + modes + status ──────────────────────────────────────────────────++ _renderShell() {+ this.shadowRoot.innerHTML = `+ <style>+ :host { display: block; position: relative; }+ :host([hidden]) { display: none; }+ #stage { position: relative; width: 100%; height: 100%; min-height: inherit; }+ #stage canvas { display: block; width: 100% !important; height: 100% !important; }+ .status {+ position: absolute; inset: 0; display: none; place-items: center;+ text-align: center; padding: 16px; pointer-events: none;+ font: 500 13px/1.5 'Inter', system-ui, sans-serif; color: rgba(255,255,255,.65);+ }+ .status[data-show="1"] { display: grid; }+ .status .inner { pointer-events: auto; max-width: 240px; }+ .skeleton {+ position: absolute; inset: 0; border-radius: inherit;+ background: linear-gradient(110deg, rgba(255,255,255,.03) 30%, rgba(255,255,255,.07) 50%, rgba(255,255,255,.03) 70%);+ background-size: 220% 100%; animation: pres-shimmer 1.4s ease-in-out infinite;+ }+ @keyframes pres-shimmer { to { background-position: -220% 0; } }+ .cta {+ margin-top: 10px; display: inline-flex; appearance: none; cursor: pointer;+ padding: 7px 14px; border-radius: 999px; font: 600 12px 'Inter', system-ui, sans-serif;+ color: #fff; background: rgba(139,92,246,.18); border: 1px solid rgba(139,92,246,.5);+ text-decoration: none; transition: background .15s ease, transform .12s ease;+ }+ .cta:hover { background: rgba(139,92,246,.3); }+ .cta:active { transform: scale(.96); }+ .cta:focus-visible { outline: 2px solid rgba(139,92,246,.8); outline-offset: 2px; }+ .retry {+ margin-top: 10px; appearance: none; cursor: pointer; padding: 6px 12px; border-radius: 8px;+ font: 600 12px 'Inter', system-ui, sans-serif; color: #fff;+ background: rgba(255,255,255,.08); border: 1px solid rgba(255,255,255,.18);+ }+ .retry:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+ .nameplate {+ position: absolute; left: 50%; bottom: 8px; transform: translateX(-50%);+ font: 600 11px 'Inter', system-ui, sans-serif; color: rgba(255,255,255,.85);+ background: rgba(0,0,0,.45); padding: 3px 10px; border-radius: 999px;+ backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); pointer-events: none;+ max-width: 80%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ opacity: 0; transition: opacity .25s ease;+ }+ .nameplate[data-show="1"] { opacity: 1; }++ /* ── modes ───────────────────────────────────────────────────── */+ :host([data-mode="stage"]) { width: 100%; height: 100%; min-height: 360px; }+ :host([data-mode="companion"]) { width: 100%; height: 100%; min-height: 280px; }+ :host([data-mode="mini"]) {+ position: fixed; z-index: 2147483000; width: 132px; height: 168px;+ right: 18px; bottom: 18px; border-radius: 16px; overflow: hidden;+ background: linear-gradient(180deg, rgba(20,21,28,.7), rgba(14,15,22,.5));+ border: 1px solid rgba(255,255,255,.1);+ box-shadow: 0 8px 32px rgba(0,0,0,.5), 0 1px 4px rgba(0,0,0,.2);+ backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);+ transition: box-shadow .2s ease;+ will-change: transform;+ }+ :host([data-mode="mini"]:hover) { box-shadow: 0 12px 40px rgba(0,0,0,.6); }+ :host([data-mode="mini"]) .drag {+ position: absolute; top: 0; left: 0; right: 0; height: 22px; cursor: grab;+ display: flex; align-items: center; justify-content: center; z-index: 3;+ }+ :host([data-mode="mini"]) .drag::before {+ content: ''; width: 26px; height: 3px; border-radius: 3px; background: rgba(255,255,255,.25); margin-top: 6px;+ }+ :host([data-mode="mini"]) .drag.dragging { cursor: grabbing; }+ .drag { display: none; }+ @media (prefers-reduced-motion: reduce) {+ .skeleton { animation: none; }+ .cta, .nameplate, :host([data-mode="mini"]) { transition: none; }+ }+ </style>+ <div id="stage" role="img" aria-label="Live 3D agent avatar">+ <div class="drag" part="drag" aria-hidden="true"></div>+ <div class="skeleton" id="skel"></div>+ <div class="status" id="status"><div class="inner" id="status-inner"></div></div>+ <div class="nameplate" id="nameplate"></div>+ </div>+ `;+ this._applyMode();+ }++ _applyMode() {+ if (!this.shadowRoot) return;+ const drag = this.shadowRoot.querySelector('.drag');+ if (this.mode === 'mini') {+ this._restoreMiniPosition();+ this._enableDrag(drag);+ } else if (this._dragCleanup) {+ this._dragCleanup();+ this._dragCleanup = null;+ }+ }++ _setStatus(state) {+ const skel = this.shadowRoot?.getElementById('skel');+ const status = this.shadowRoot?.getElementById('status');+ const inner = this.shadowRoot?.getElementById('status-inner');+ if (!skel || !status || !inner) return;+ skel.style.display = state === 'loading' ? 'block' : 'none';+ if (state === 'live' || state === 'loading') {+ status.setAttribute('data-show', '0');+ return;+ }+ status.setAttribute('data-show', '1');+ if (state === 'no-body') {+ inner.innerHTML = `<div>No body yet</div><a class="cta" href="/agent-studio#body">Give it a body →</a>`;+ } else if (state === 'error') {+ inner.innerHTML = `<div>Couldn't load the avatar.</div><button class="retry" type="button">Try again</button>`;+ inner.querySelector('.retry')?.addEventListener('click', () => {+ this._setStatus('loading');+ this._refreshBody();+ });+ }+ }++ _updateNameplate(name) {+ const el = this.shadowRoot?.getElementById('nameplate');+ if (!el) return;+ if (this.mode === 'mini' || !name) {+ el.setAttribute('data-show', '0');+ return;+ }+ el.textContent = name;+ el.setAttribute('data-show', '1');+ }++ // ── mini drag + persisted position ──────────────────────────────────────────++ _enableDrag(handle) {+ if (!handle || this._dragCleanup) return;+ let startX = 0, startY = 0, originX = 0, originY = 0, dragging = false;+ const onDown = (e) => {+ dragging = true;+ handle.classList.add('dragging');+ const rect = this.getBoundingClientRect();+ originX = rect.left;+ originY = rect.top;+ startX = e.clientX;+ startY = e.clientY;+ this.style.right = 'auto';+ this.style.bottom = 'auto';+ this.style.left = originX + 'px';+ this.style.top = originY + 'px';+ handle.setPointerCapture?.(e.pointerId);+ e.preventDefault();+ };+ const onMove = (e) => {+ if (!dragging) return;+ const w = this.offsetWidth, h = this.offsetHeight;+ let nx = originX + (e.clientX - startX);+ let ny = originY + (e.clientY - startY);+ nx = Math.max(6, Math.min(window.innerWidth - w - 6, nx));+ ny = Math.max(6, Math.min(window.innerHeight - h - 6, ny));+ this.style.left = nx + 'px';+ this.style.top = ny + 'px';+ };+ const onUp = () => {+ if (!dragging) return;+ dragging = false;+ handle.classList.remove('dragging');+ this._saveMiniPosition();+ };+ handle.addEventListener('pointerdown', onDown);+ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ this._dragCleanup = () => {+ handle.removeEventListener('pointerdown', onDown);+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ };+ }++ _saveMiniPosition() {+ try {+ localStorage.setItem(+ MINI_POS_KEY,+ JSON.stringify({ left: this.style.left, top: this.style.top }),+ );+ } catch {+ /* storage disabled */+ }+ }++ _restoreMiniPosition() {+ try {+ const raw = localStorage.getItem(MINI_POS_KEY);+ if (!raw) return;+ const pos = JSON.parse(raw);+ if (pos?.left && pos?.top) {+ // Clamp to the current viewport in case it shrank since last save.+ const left = Math.max(6, Math.min(window.innerWidth - 138, parseFloat(pos.left)));+ const top = Math.max(6, Math.min(window.innerHeight - 174, parseFloat(pos.top)));+ this.style.right = 'auto';+ this.style.bottom = 'auto';+ this.style.left = left + 'px';+ this.style.top = top + 'px';+ }+ } catch {+ /* ignore corrupt position */+ }+ }++ // ── Teardown ─────────────────────────────────────────────────────────────++ _teardown() {+ this._disposed = true;+ this._io?.disconnect();+ this._io = null;+ this._unsubStudio?.();+ this._unsubMarket?.();+ this._dragCleanup?.();+ try {+ this._avatar?.detach();+ } catch {}+ try {+ this._viewer?.dispose();+ } catch {}+ this._avatar = null;+ this._viewer = null;+ }+}++if (typeof window !== 'undefined' && !customElements.get('agent-presence')) {+ customElements.define('agent-presence', AgentPresenceElement);+}++export { AgentPresenceElement };+export default AgentPresenceElement;diff --git a/src/studio/brain/brain-compile.js b/src/studio/brain/brain-compile.jsnew file mode 100644index 000000000..e487a282c--- /dev/null+++ b/src/studio/brain/brain-compile.js@@ -0,0 +1,142 @@+/**+ * Brain Studio — graph compiler (P1)+ * ==================================+ * Compiles the visual brain graph down to the artifacts the rest of the platform+ * consumes, so existing chat surfaces keep working without knowing the graph+ * exists:+ *+ * • personaPrompt — the real `agent_identities.persona_prompt` string that+ * api/chat.js reads. This is the lossy projection (text). The graph itself is+ * the lossless source of truth, stored verbatim at meta.studio.brain.+ * • provider / model / maxTokens — picked from the Model node, used by the test+ * harness and persisted for the widget brain config.+ * • memory — recall config from the Memory node, or null.+ * • skills — skill names wired as tools.+ * • marketRules — reasoning wiring for P4 execution.+ *+ * Compilation walks edges backwards from the Output node so only nodes that are+ * actually connected into the circuit contribute — an orphaned node is inert,+ * exactly as the visual wiring implies.+ */++import { NODE_TYPES } from './brain-nodes.js';++function indexGraph(graph) {+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));+ const incoming = new Map(); // nodeId → [{from, fromPort, toPort}]+ for (const e of graph.edges) {+ if (!incoming.has(e.to)) incoming.set(e.to, []);+ incoming.get(e.to).push(e);+ }+ return { byId, incoming };+}++// All nodes reachable (upstream) from the output node — the live circuit.+function reachableFromOutput(graph) {+ const { byId, incoming } = indexGraph(graph);+ const output = graph.nodes.find((n) => n.type === 'output');+ if (!output) return { nodes: graph.nodes, byId, incoming, output: null };+ const seen = new Set();+ const stack = [output.id];+ while (stack.length) {+ const id = stack.pop();+ if (seen.has(id)) continue;+ seen.add(id);+ for (const e of incoming.get(id) || []) stack.push(e.from);+ }+ return { nodes: graph.nodes.filter((n) => seen.has(n.id)), byId, incoming, output };+}++const RISK_LINE = {+ cautious: 'You are risk-averse: protect capital, prefer waiting to acting, and surface downside first.',+ balanced: 'You weigh upside and downside evenly and act with measured conviction.',+ aggressive: 'You are decisive and opportunistic: you move fast on conviction while staying honest about risk.',+};++/**+ * @param {object} graph normalized graph+ * @param {{ agentName?: string }} [opts]+ * @returns {{ personaPrompt:string, provider:string, model:string, maxTokens:number,+ * memory:object|null, skills:string[], marketRules:object[], greeting:string }}+ */+export function compileBrain(graph, { agentName = 'the agent' } = {}) {+ const { nodes } = reachableFromOutput(graph);+ const has = (type) => nodes.find((n) => n.type === type);++ const persona = has('persona')?.data || NODE_TYPES.persona.defaults;+ const modelNode = has('model')?.data || NODE_TYPES.model.defaults;+ const memoryNode = has('memory')?.data || null;+ const skills = nodes.filter((n) => n.type === 'skill' && n.data.skill).map((n) => ({ skill: n.data.skill, when: n.data.when }));+ const marketNodes = nodes.filter((n) => n.type === 'market');++ const lines = [];+ lines.push(`You are ${persona.role || 'an AI agent'}.`);+ if (persona.tone) lines.push(`Voice: ${persona.tone}.`);+ if (RISK_LINE[persona.risk]) lines.push(RISK_LINE[persona.risk]);+ if (persona.vocabulary?.length) lines.push(`Favor this vocabulary: ${persona.vocabulary.join(', ')}.`);+ if (persona.avoid?.length) lines.push(`Never say: ${persona.avoid.join(', ')}.`);++ if (memoryNode) {+ lines.push('');+ lines.push(`You have a memory. Before answering, recall the most relevant ${memoryNode.topK} memories (similarity ≥ ${memoryNode.minScore}) and weave them in naturally — never dump them verbatim.${memoryNode.write ? ' Remember durable new facts the user shares.' : ''}`);+ }++ if (skills.length) {+ lines.push('');+ lines.push('You can invoke these skills as tools:');+ for (const s of skills) lines.push(`- ${s.skill}${s.when ? ` — ${s.when}` : ''}`);+ }++ if (marketNodes.length) {+ lines.push('');+ lines.push('Market reasoning (operate only on the specific mint provided at runtime — never recommend any coin other than the platform token $THREE):');+ for (const m of marketNodes.map((n) => n.data)) {+ lines.push(`- If a tracked mint ${humanTrigger(m.trigger, m.level)}, ${humanAction(m.action)}.`);+ }+ }++ if (persona.greeting) {+ lines.push('');+ lines.push(`Open new conversations with something like: "${persona.greeting}"`);+ }++ return {+ personaPrompt: lines.join('\n').trim(),+ provider: modelNode.provider || 'claude-sonnet-4-6',+ model: modelNode.provider || 'claude-sonnet-4-6',+ maxTokens: clampInt(modelNode.maxTokens, 64, 16384, 1024),+ memory: memoryNode ? { topK: clampInt(memoryNode.topK, 1, 20, 4), minScore: clampNum(memoryNode.minScore, 0, 1, 0.75), write: !!memoryNode.write } : null,+ skills: skills.map((s) => s.skill),+ marketRules: marketNodes.map((n) => ({ ...n.data })),+ greeting: persona.greeting || '',+ output: has('output')?.data || NODE_TYPES.output.defaults,+ };+}++function humanTrigger(trigger, level) {+ switch (trigger) {+ case 'breaks-level': return `breaks the level ${level || '(set a level)'}`;+ case 'price-change': return `moves ${level || '(set a %)'}`;+ case 'volume-spike': return 'sees a volume spike';+ case 'new-launch': return 'is a fresh launch';+ default: return 'changes';+ }+}++function humanAction(action) {+ switch (action) {+ case 'propose-action': return 'reason about it and propose a concrete action with sizing and risk';+ case 'alert-only': return 'surface a concise alert and wait for the user';+ case 'ask-brain': return 'think it through out loud before deciding';+ default: return 'react';+ }+}++function clampInt(v, lo, hi, dflt) {+ const n = Math.round(Number(v));+ return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : dflt;+}+function clampNum(v, lo, hi, dflt) {+ const n = Number(v);+ return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : dflt;+}diff --git a/src/studio/brain/brain-graph.js b/src/studio/brain/brain-graph.jsnew file mode 100644index 000000000..05df4a3a6--- /dev/null+++ b/src/studio/brain/brain-graph.js@@ -0,0 +1,432 @@+/**+ * Brain Studio — visual node-graph editor (P1)+ * ============================================+ * A dependency-free node editor built on DOM nodes + an SVG edge layer inside a+ * pan/zoom world. We deliberately did NOT pull in Rete.js / litegraph / React+ * Flow: the main app is vanilla and we cannot add npm deps in this environment,+ * AND keeping the renderer ours means the saved format is ours (brain-nodes.js),+ * never a library's internal schema leaking into the DB — and the live "thinking"+ * animation can address our own nodes/edges directly. ~1 file, zero deps, full+ * control of the screenshot moment.+ *+ * Public API:+ * new BrainGraphView(host, { onChange, onSelect })+ * .load(graph) — render a normalized graph+ * .toGraph() — serialize current state+ * .addNode(type) — drop a node at viewport centre+ * .removeNode(id) / .removeEdge(id)+ * .select(id|null)+ * .fit() — frame all nodes+ * Active-path animation (driven by brain-runtime.js):+ * .setActive(nodeIds, edgeIds) / .pulseNode(id) / .flowEdge(id) / .clearActive()+ */++import { NODE_TYPES, canConnect, makeNode } from './brain-nodes.js';++const NODE_W = 208;+const HEADER_H = 34;+const PORT_ROW = 26;+const PORT_PAD = 10;++const escapeHtml = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++export class BrainGraphView {+ constructor(host, { onChange, onSelect } = {}) {+ this.host = host;+ this.onChange = onChange || (() => {});+ this.onSelect = onSelect || (() => {});+ this.nodes = [];+ this.edges = [];+ this.selectedId = null;+ this.scale = 1;+ this.tx = 0;+ this.ty = 0;+ this._nodeEls = new Map();+ this._linking = null; // { from, fromPort, kind, ghost }+ this._render();+ }++ _render() {+ this.host.classList.add('bgraph');+ this.host.innerHTML = `+ <div class="bgraph__world" id="bgWorld">+ <svg class="bgraph__edges" id="bgEdges" aria-hidden="true"></svg>+ <div class="bgraph__nodes" id="bgNodes"></div>+ </div>+ <div class="bgraph__hint" id="bgHint"></div>`;+ this.world = this.host.querySelector('#bgWorld');+ this.svg = this.host.querySelector('#bgEdges');+ this.nodesEl = this.host.querySelector('#bgNodes');+ this._bindCanvas();+ }++ // ── Load / serialize ──────────────────────────────────────────────────────++ load(graph) {+ this.nodes = graph.nodes.map((n) => ({ ...n, data: { ...n.data } }));+ this.edges = graph.edges.map((e) => ({ ...e }));+ this.selectedId = null;+ this._renderAll();+ // Frame the graph on first load so the user always sees their circuit.+ requestAnimationFrame(() => this.fit());+ }++ toGraph() {+ return {+ version: 1,+ nodes: this.nodes.map((n) => ({ id: n.id, type: n.type, x: Math.round(n.x), y: Math.round(n.y), data: { ...n.data } })),+ edges: this.edges.map((e) => ({ id: e.id, from: e.from, fromPort: e.fromPort, to: e.to, toPort: e.toPort })),+ };+ }++ _emitChange() { this.onChange(this.toGraph()); }++ // ── Geometry ────────────────────────────────────────────────────────────++ _nodeHeight(node) {+ const spec = NODE_TYPES[node.type];+ const rows = Math.max(spec.inputs.length, spec.outputs.length);+ return HEADER_H + Math.max(rows, 1) * PORT_ROW + PORT_PAD;+ }++ _portAnchor(node, portId, dir) {+ const spec = NODE_TYPES[node.type];+ const list = dir === 'out' ? spec.outputs : spec.inputs;+ const idx = list.findIndex((p) => p.id === portId);+ const y = node.y + HEADER_H + idx * PORT_ROW + PORT_ROW / 2 + PORT_PAD / 2;+ const x = dir === 'out' ? node.x + NODE_W : node.x;+ return { x, y };+ }++ // ── Full render ─────────────────────────────────────────────────────────++ _renderAll() {+ this.nodesEl.innerHTML = '';+ this._nodeEls.clear();+ for (const node of this.nodes) this._renderNode(node);+ this._renderEdges();+ this._applyTransform();+ }++ _renderNode(node) {+ const spec = NODE_TYPES[node.type];+ const el = document.createElement('div');+ el.className = `bnode bnode--${spec.accent}`;+ el.dataset.id = node.id;+ el.style.width = `${NODE_W}px`;+ el.style.height = `${this._nodeHeight(node)}px`;+ el.style.transform = `translate(${node.x}px, ${node.y}px)`;+ el.innerHTML = `+ <div class="bnode__head"><span class="bnode__title">${escapeHtml(spec.title)}</span>${spec.single ? '' : '<button class="bnode__del" title="Delete node" aria-label="Delete node">×</button>'}</div>+ <div class="bnode__summary">${escapeHtml(this._summary(node))}</div>+ <div class="bnode__ports">+ <div class="bnode__col bnode__col--in">${spec.inputs.map((p) => this._portHtml(p, 'in')).join('')}</div>+ <div class="bnode__col bnode__col--out">${spec.outputs.map((p) => this._portHtml(p, 'out')).join('')}</div>+ </div>`;+ this.nodesEl.appendChild(el);+ this._nodeEls.set(node.id, el);+ this._bindNode(el, node);+ }++ _portHtml(port, dir) {+ return `<span class="bport bport--${dir} bport--${port.kind}" data-port="${port.id}" data-dir="${dir}" data-kind="${port.kind}" title="${escapeHtml(port.label)} (${port.kind})"><i class="bport__dot"></i><span class="bport__label">${escapeHtml(port.label)}</span></span>`;+ }++ _summary(node) {+ const d = node.data;+ switch (node.type) {+ case 'persona': return d.role || 'identity';+ case 'model': return d.provider || 'pick a model';+ case 'memory': return `recall ${d.topK} · write ${d.write ? 'on' : 'off'}`;+ case 'skill': return d.skill || 'pick a skill';+ case 'market': return `${d.trigger}${d.level ? ` @ ${d.level}` : ''}`;+ case 'output': return [d.speak && 'speak', d.emotion && 'emote', d.lipsync && 'lip-sync'].filter(Boolean).join(' · ') || 'silent';+ default: return '';+ }+ }++ refreshNode(id) {+ const node = this.nodes.find((n) => n.id === id);+ const el = this._nodeEls.get(id);+ if (!node || !el) return;+ el.querySelector('.bnode__summary').textContent = this._summary(node);+ }++ _renderEdges() {+ const parts = [];+ for (const e of this.edges) {+ const fromNode = this.nodes.find((n) => n.id === e.from);+ const toNode = this.nodes.find((n) => n.id === e.to);+ if (!fromNode || !toNode) continue;+ const a = this._portAnchor(fromNode, e.fromPort, 'out');+ const b = this._portAnchor(toNode, e.toPort, 'in');+ parts.push(`<path class="bedge" data-id="${e.id}" d="${this._curve(a, b)}" />`);+ parts.push(`<path class="bedge-hit" data-id="${e.id}" d="${this._curve(a, b)}" />`);+ }+ this.svg.innerHTML = parts.join('');+ this.svg.querySelectorAll('.bedge-hit').forEach((p) => {+ p.addEventListener('click', (ev) => { ev.stopPropagation(); this.removeEdge(p.dataset.id); });+ });+ }++ _curve(a, b) {+ const dx = Math.max(40, Math.abs(b.x - a.x) * 0.5);+ return `M ${a.x} ${a.y} C ${a.x + dx} ${a.y}, ${b.x - dx} ${b.y}, ${b.x} ${b.y}`;+ }++ // ── Node interaction ──────────────────────────────────────────────────────++ _bindNode(el, node) {+ const head = el.querySelector('.bnode__head');+ head.addEventListener('pointerdown', (e) => this._startDrag(e, node, el));+ el.addEventListener('pointerdown', () => this.select(node.id));+ el.querySelector('.bnode__del')?.addEventListener('click', (e) => { e.stopPropagation(); this.removeNode(node.id); });+ el.querySelectorAll('.bport').forEach((portEl) => {+ portEl.addEventListener('pointerdown', (e) => {+ e.stopPropagation();+ if (portEl.dataset.dir === 'out') this._startLink(e, node, portEl);+ });+ portEl.addEventListener('pointerup', (e) => {+ if (portEl.dataset.dir === 'in') this._completeLink(e, node, portEl);+ });+ });+ }++ _startDrag(e, node, el) {+ e.preventDefault();+ const startX = e.clientX, startY = e.clientY;+ const ox = node.x, oy = node.y;+ const move = (ev) => {+ node.x = ox + (ev.clientX - startX) / this.scale;+ node.y = oy + (ev.clientY - startY) / this.scale;+ el.style.transform = `translate(${node.x}px, ${node.y}px)`;+ this._renderEdges();+ };+ const up = () => {+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ this._emitChange();+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ }++ _startLink(e, node, portEl) {+ e.preventDefault();+ const kind = portEl.dataset.kind;+ const a = this._portAnchor(node, portEl.dataset.port, 'out');+ const ghost = document.createElementNS('http://www.w3.org/2000/svg', 'path');+ ghost.setAttribute('class', 'bedge bedge--ghost');+ this.svg.appendChild(ghost);+ this._linking = { from: node.id, fromPort: portEl.dataset.port, kind, a, ghost };+ this.host.querySelector('#bgHint').textContent = `Connecting ${kind} — drop on a matching input`;+ const move = (ev) => {+ const pt = this._toWorld(ev.clientX, ev.clientY);+ ghost.setAttribute('d', this._curve(a, pt));+ };+ const up = (ev) => {+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ // If released over an input port, _completeLink already ran; clean up ghost.+ const target = document.elementFromPoint(ev.clientX, ev.clientY);+ const portTarget = target?.closest?.('.bport--in');+ if (portTarget) {+ const nodeEl = portTarget.closest('.bnode');+ this._tryConnect(nodeEl?.dataset.id, portTarget.dataset.port, portTarget.dataset.kind);+ }+ ghost.remove();+ this._linking = null;+ this.host.querySelector('#bgHint').textContent = '';+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ }++ _completeLink() { /* handled in _startLink's pointerup via elementFromPoint */ }++ _tryConnect(toId, toPort, toKind) {+ if (!this._linking || !toId) return;+ const { from, fromPort, kind } = this._linking;+ if (from === toId) return;+ if (!canConnect(kind, toKind)) {+ this.host.querySelector('#bgHint').textContent = `Can't connect ${kind} → ${toKind}`;+ setTimeout(() => { this.host.querySelector('#bgHint').textContent = ''; }, 1400);+ return;+ }+ // One edge per input port (latest wins) — keeps the circuit unambiguous.+ this.edges = this.edges.filter((e) => !(e.to === toId && e.toPort === toPort));+ const id = `e_${from}.${fromPort}-${toId}.${toPort}`;+ if (!this.edges.some((e) => e.id === id)) {+ this.edges.push({ id, from, fromPort, to: toId, toPort });+ this._renderEdges();+ this._emitChange();+ }+ }++ // ── Mutations ─────────────────────────────────────────────────────────────++ addNode(type) {+ const spec = NODE_TYPES[type];+ if (spec.single && this.nodes.some((n) => n.type === type)) {+ this.host.querySelector('#bgHint').textContent = `Only one ${spec.title} node allowed`;+ setTimeout(() => { this.host.querySelector('#bgHint').textContent = ''; }, 1400);+ return null;+ }+ // Drop at the centre of the current viewport, in world coords.+ const rect = this.host.getBoundingClientRect();+ const c = this._toWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);+ const node = makeNode(type, c.x - NODE_W / 2, c.y - 40);+ this.nodes.push(node);+ this._renderNode(node);+ this._applyTransform();+ this.select(node.id);+ this._emitChange();+ return node;+ }++ removeNode(id) {+ const node = this.nodes.find((n) => n.id === id);+ if (!node) return;+ if (NODE_TYPES[node.type].single) return; // persona/output are structural+ this.nodes = this.nodes.filter((n) => n.id !== id);+ this.edges = this.edges.filter((e) => e.from !== id && e.to !== id);+ this._nodeEls.get(id)?.remove();+ this._nodeEls.delete(id);+ if (this.selectedId === id) this.select(null);+ this._renderEdges();+ this._emitChange();+ }++ removeEdge(id) {+ this.edges = this.edges.filter((e) => e.id !== id);+ this._renderEdges();+ this._emitChange();+ }++ updateNodeData(id, patch) {+ const node = this.nodes.find((n) => n.id === id);+ if (!node) return;+ Object.assign(node.data, patch);+ this.refreshNode(id);+ this._emitChange();+ }++ select(id) {+ this.selectedId = id;+ for (const [nid, el] of this._nodeEls) el.classList.toggle('is-selected', nid === id);+ this.onSelect(id ? this.nodes.find((n) => n.id === id) : null);+ }++ // ── Pan / zoom ──────────────────────────────────────────────────────────++ _bindCanvas() {+ this.host.addEventListener('pointerdown', (e) => {+ if (e.target.closest('.bnode') || e.target.closest('.bport')) return;+ this.select(null);+ const sx = e.clientX, sy = e.clientY, otx = this.tx, oty = this.ty;+ this.host.classList.add('is-panning');+ const move = (ev) => { this.tx = otx + (ev.clientX - sx); this.ty = oty + (ev.clientY - sy); this._applyTransform(); };+ const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); this.host.classList.remove('is-panning'); };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ });+ this.host.addEventListener('wheel', (e) => {+ e.preventDefault();+ const rect = this.host.getBoundingClientRect();+ const mx = e.clientX - rect.left, my = e.clientY - rect.top;+ const before = this._toWorld(e.clientX, e.clientY);+ const factor = e.deltaY < 0 ? 1.1 : 1 / 1.1;+ this.scale = Math.max(0.3, Math.min(2, this.scale * factor));+ // keep the point under the cursor fixed+ this.tx = mx - before.x * this.scale;+ this.ty = my - before.y * this.scale;+ this._applyTransform();+ }, { passive: false });+ }++ _toWorld(clientX, clientY) {+ const rect = this.host.getBoundingClientRect();+ return { x: (clientX - rect.left - this.tx) / this.scale, y: (clientY - rect.top - this.ty) / this.scale };+ }++ _applyTransform() {+ this.world.style.transform = `translate(${this.tx}px, ${this.ty}px) scale(${this.scale})`;+ }++ fit() {+ if (!this.nodes.length) return;+ const xs = this.nodes.map((n) => n.x);+ const ys = this.nodes.map((n) => n.y);+ const minX = Math.min(...xs) - 40;+ const minY = Math.min(...ys) - 40;+ const maxX = Math.max(...this.nodes.map((n) => n.x + NODE_W)) + 40;+ const maxY = Math.max(...this.nodes.map((n) => n.y + this._nodeHeight(n))) + 40;+ const rect = this.host.getBoundingClientRect();+ if (!rect.width) return;+ this.scale = Math.max(0.4, Math.min(1.2, Math.min(rect.width / (maxX - minX), rect.height / (maxY - minY))));+ this.tx = (rect.width - (maxX - minX) * this.scale) / 2 - minX * this.scale;+ this.ty = (rect.height - (maxY - minY) * this.scale) / 2 - minY * this.scale;+ this._applyTransform();+ }++ // ── Active-path animation (the "watch it think" moment) ─────────────────────++ setActive(nodeIds = [], edgeIds = []) {+ const ns = new Set(nodeIds);+ for (const [id, el] of this._nodeEls) el.classList.toggle('is-active', ns.has(id));+ const es = new Set(edgeIds);+ this.svg.querySelectorAll('.bedge').forEach((p) => p.classList.toggle('is-active', es.has(p.dataset.id)));+ }++ pulseNode(id) {+ const el = this._nodeEls.get(id);+ if (!el) return;+ el.classList.remove('is-pulse');+ void el.offsetWidth; // restart animation+ el.classList.add('is-pulse');+ }++ flowEdge(id) {+ const p = this.svg.querySelector(`.bedge[data-id="${CSS.escape(id)}"]`);+ if (p) { p.classList.add('is-active', 'is-flow'); }+ }++ setNodeBusy(id, busy) {+ this._nodeEls.get(id)?.classList.toggle('is-busy', !!busy);+ }++ setNodeStat(id, text) {+ const el = this._nodeEls.get(id);+ if (!el) return;+ let stat = el.querySelector('.bnode__stat');+ if (!stat) {+ stat = document.createElement('div');+ stat.className = 'bnode__stat';+ el.appendChild(stat);+ }+ stat.textContent = text || '';+ stat.hidden = !text;+ }++ clearActive() {+ for (const el of this._nodeEls.values()) el.classList.remove('is-active', 'is-pulse', 'is-busy');+ this.svg.querySelectorAll('.bedge').forEach((p) => p.classList.remove('is-active', 'is-flow'));+ }++ // Find the live circuit (nodes + edges reachable upstream from output) — used to+ // pre-highlight the path the runtime will walk.+ circuit() {+ const incoming = new Map();+ for (const e of this.edges) { if (!incoming.has(e.to)) incoming.set(e.to, []); incoming.get(e.to).push(e); }+ const out = this.nodes.find((n) => n.type === 'output');+ if (!out) return { nodeIds: [], edgeIds: [] };+ const nodeIds = new Set(); const edgeIds = new Set(); const stack = [out.id];+ while (stack.length) {+ const id = stack.pop();+ if (nodeIds.has(id)) continue;+ nodeIds.add(id);+ for (const e of incoming.get(id) || []) { edgeIds.add(e.id); stack.push(e.from); }+ }+ return { nodeIds: [...nodeIds], edgeIds: [...edgeIds] };+ }+}diff --git a/src/studio/brain/brain-nodes.js b/src/studio/brain/brain-nodes.jsnew file mode 100644index 000000000..5c276a886--- /dev/null+++ b/src/studio/brain/brain-nodes.js@@ -0,0 +1,227 @@+/**+ * Brain Studio — node type registry + execution interface (P1)+ * ============================================================+ * The Brain graph is a small set of typed nodes wired into a circuit that IS the+ * agent's persona. This module defines every node type, its ports, its editable+ * fields, and the extension seam P4 (trading execution) binds to.+ *+ * Saved graph format (lives at meta.studio.brain — OUR schema, not a library's):+ *+ * {+ * version: 1,+ * nodes: [{ id, type, x, y, data: {…type-specific} }],+ * edges: [{ id, from, fromPort, to, toPort }],+ * compiled?: { personaPrompt, provider, model, ... } // last compile snapshot+ * }+ *+ * Ports carry a `kind` so the editor only allows sane connections:+ * 'signal' — control/flow (persona → model → output)+ * 'context' — text injected into the model's system prompt (memory, skills, market)+ * 'tool' — an invokable capability (skill, market reasoning) the brain may call+ *+ * ── Node execution interface (the contract P4 should target) ──────────────────+ * The Brain Studio's test harness (brain-runtime.js) executes the graph. Persona,+ * Model, Memory and Output have built-in runners here. Skill and Market/Reasoning+ * nodes define their INTERFACE here but defer EXECUTION to P4 via:+ *+ * import { registerNodeRunner } from './brain-nodes.js';+ * registerNodeRunner('market', async (node, ctx) => {+ * // ctx = { mint, brain, recall(query), emit(protocolAction), signal (AbortSignal),+ * // say(text), now }+ * // return { context?: string, tool?: {...}, fired?: boolean }+ * });+ *+ * Until P4 registers a runner, these nodes contribute their reasoning INSTRUCTIONS+ * to the system prompt (so the brain reasons about them in language) but perform no+ * side effects — never a mock, just language-level wiring awaiting execution.+ */++// Emotion vocabulary the Output node can drive (matches agent-avatar.js).+export const EMOTIONS = ['neutral', 'celebration', 'concern', 'curiosity', 'empathy', 'patience', 'uncertain'];++export const PORT_KINDS = { SIGNAL: 'signal', CONTEXT: 'context', TOOL: 'tool' };++// Each node type: ports, defaults, editor field schema, and an optional built-in+// runner. `accent` is a CSS token class suffix for the node header.+export const NODE_TYPES = {+ persona: {+ title: 'Persona',+ accent: 'persona',+ single: true, // only one allowed in a graph+ inputs: [],+ outputs: [{ id: 'identity', label: 'identity', kind: PORT_KINDS.SIGNAL }],+ defaults: {+ role: 'a sharp, helpful AI agent',+ tone: 'direct, warm, plain-spoken',+ risk: 'balanced',+ vocabulary: [],+ avoid: ['hype', 'buzzwords'],+ greeting: 'Hey — what are we working on?',+ },+ fields: [+ { key: 'role', label: 'Role', type: 'text', placeholder: 'a sharp crypto trading copilot' },+ { key: 'tone', label: 'Tone', type: 'text', placeholder: 'direct, a little sardonic' },+ { key: 'risk', label: 'Risk appetite', type: 'select', options: ['cautious', 'balanced', 'aggressive'] },+ { key: 'vocabulary', label: 'Vocabulary (favor)', type: 'tags' },+ { key: 'avoid', label: 'Avoid', type: 'tags' },+ { key: 'greeting', label: 'Greeting', type: 'textarea' },+ ],+ },++ model: {+ title: 'Model',+ accent: 'model',+ inputs: [+ { id: 'identity', label: 'identity', kind: PORT_KINDS.SIGNAL },+ { id: 'context', label: 'context', kind: PORT_KINDS.CONTEXT },+ { id: 'tools', label: 'tools', kind: PORT_KINDS.TOOL },+ ],+ outputs: [{ id: 'reply', label: 'reply', kind: PORT_KINDS.SIGNAL }],+ defaults: { provider: 'claude-sonnet-4-6', maxTokens: 1024 },+ fields: [+ { key: 'provider', label: 'Model', type: 'provider' }, // populated from /api/brain/chat (GET)+ { key: 'maxTokens', label: 'Max tokens', type: 'number', min: 64, max: 16384, step: 64 },+ ],+ },++ memory: {+ title: 'Memory',+ accent: 'memory',+ inputs: [{ id: 'query', label: 'query', kind: PORT_KINDS.SIGNAL }],+ outputs: [{ id: 'recall', label: 'recall', kind: PORT_KINDS.CONTEXT }],+ // Mirrors mem0 search() ergonomics + Letta tiered recall (topK / minScore).+ defaults: { topK: 4, minScore: 0.75, write: true },+ fields: [+ { key: 'topK', label: 'Recall top-K', type: 'number', min: 1, max: 20, step: 1 },+ { key: 'minScore', label: 'Min similarity', type: 'number', min: 0, max: 1, step: 0.05 },+ { key: 'write', label: 'Write new memories', type: 'toggle' },+ ],+ },++ skill: {+ title: 'Skill',+ accent: 'skill',+ inputs: [],+ outputs: [{ id: 'tool', label: 'tool', kind: PORT_KINDS.TOOL }],+ defaults: { skill: '', when: 'when the user asks for it' },+ fields: [+ { key: 'skill', label: 'Skill', type: 'skill' }, // populated from agent.skills[]+ { key: 'when', label: 'Invoke when', type: 'text' },+ ],+ },++ market: {+ title: 'Market signal',+ accent: 'market',+ inputs: [],+ outputs: [{ id: 'signal', label: 'signal', kind: PORT_KINDS.CONTEXT }],+ // Reasoning wiring only — execution is P4's. Operates on a runtime-supplied+ // mint (never a hardcoded coin; $THREE is the only coin the platform promotes).+ defaults: { trigger: 'breaks-level', level: '', action: 'propose-action' },+ fields: [+ { key: 'trigger', label: 'Trigger', type: 'select', options: ['breaks-level', 'price-change', 'volume-spike', 'new-launch'] },+ { key: 'level', label: 'Level / threshold', type: 'text', placeholder: 'e.g. 0.0042 or +15%' },+ { key: 'action', label: 'Then', type: 'select', options: ['propose-action', 'alert-only', 'ask-brain'] },+ ],+ },++ output: {+ title: 'Avatar output',+ accent: 'output',+ single: true,+ inputs: [{ id: 'reply', label: 'reply', kind: PORT_KINDS.SIGNAL }],+ outputs: [],+ defaults: { speak: true, emotion: true, lipsync: true },+ fields: [+ { key: 'speak', label: 'Speak reply', type: 'toggle' },+ { key: 'emotion', label: 'Emotional reactions', type: 'toggle' },+ { key: 'lipsync', label: 'Lip-sync', type: 'toggle' },+ ],+ },+};++// Connection rule: an output port may connect to an input port of the same kind.+export function canConnect(fromKind, toKind) {+ return fromKind === toKind;+}++// ── Execution runner registry (P4 extension point) ──────────────────────────+const RUNNERS = new Map();++/**+ * Register an execution runner for a node type (P4: 'market', and richer 'skill').+ * @param {string} type+ * @param {(node:object, ctx:object)=>Promise<{context?:string,tool?:object,fired?:boolean}>} fn+ */+export function registerNodeRunner(type, fn) {+ if (!NODE_TYPES[type]) throw new Error(`registerNodeRunner: unknown node type "${type}"`);+ RUNNERS.set(type, fn);+}++export function getNodeRunner(type) {+ return RUNNERS.get(type) || null;+}++// ── Graph construction helpers ──────────────────────────────────────────────++let _seq = 0;+export function nodeId(type) {+ _seq += 1;+ return `${type}_${Date.now().toString(36)}_${_seq}`;+}++export function makeNode(type, x, y, data = {}) {+ const spec = NODE_TYPES[type];+ if (!spec) throw new Error(`makeNode: unknown type ${type}`);+ return { id: nodeId(type), type, x, y, data: { ...structuredClone(spec.defaults), ...data } };+}++// A sensible starter circuit: Persona → Model → Avatar output, with Memory wired+// into the model's context. The user fleshes it out from here.+export function defaultGraph() {+ const persona = makeNode('persona', 80, 120);+ const memory = makeNode('memory', 80, 360);+ const model = makeNode('model', 440, 200);+ const output = makeNode('output', 800, 220);+ return {+ version: 1,+ nodes: [persona, memory, model, output],+ edges: [+ edge(persona, 'identity', model, 'identity'),+ edge(memory, 'recall', model, 'context'),+ edge(model, 'reply', output, 'reply'),+ ],+ };+}++export function edge(fromNode, fromPort, toNode, toPort) {+ return {+ id: `e_${fromNode.id}.${fromPort}-${toNode.id}.${toPort}`,+ from: fromNode.id,+ fromPort,+ to: toNode.id,+ toPort,+ };+}++// Validate + normalize a graph loaded from storage so a hand-edited or legacy bag+// can't crash the editor. Drops nodes of unknown type and edges to missing ports.+export function normalizeGraph(g) {+ if (!g || typeof g !== 'object' || !Array.isArray(g.nodes)) return defaultGraph();+ const nodes = g.nodes.filter((n) => n && NODE_TYPES[n.type]).map((n) => ({+ id: String(n.id),+ type: n.type,+ x: Number.isFinite(n.x) ? n.x : 100,+ y: Number.isFinite(n.y) ? n.y : 100,+ data: { ...structuredClone(NODE_TYPES[n.type].defaults), ...(n.data || {}) },+ }));+ const byId = new Map(nodes.map((n) => [n.id, n]));+ const portExists = (node, portId, dir) =>+ node && NODE_TYPES[node.type][dir].some((p) => p.id === portId);+ const edges = (Array.isArray(g.edges) ? g.edges : []).filter((e) =>+ e && byId.has(e.from) && byId.has(e.to) &&+ portExists(byId.get(e.from), e.fromPort, 'outputs') &&+ portExists(byId.get(e.to), e.toPort, 'inputs'),+ ).map((e) => ({ id: e.id || `e_${e.from}.${e.fromPort}-${e.to}.${e.toPort}`, from: e.from, fromPort: e.fromPort, to: e.to, toPort: e.toPort }));+ return { version: 1, nodes, edges, compiled: g.compiled || null };+}diff --git a/src/studio/brain/brain-runtime.js b/src/studio/brain/brain-runtime.jsnew file mode 100644index 000000000..77ca36c8c--- /dev/null+++ b/src/studio/brain/brain-runtime.js@@ -0,0 +1,247 @@+/**+ * Brain Studio — test-harness runtime (P1)+ * ========================================+ * Executes the live brain graph against the REAL multi-provider LLM proxy+ * (/api/brain/chat, SSE), recalls the agent's REAL memory, animates the active+ * path through the graph as it runs, and drives the live avatar via the shared+ * protocol bus. No fake responses, ever.+ *+ * Flow per message (mirrors the compiled circuit):+ * persona → (memory recall) → model (streamed) → output (avatar speak/emote)+ *+ * Node execution (skill / market) defers to P4-registered runners+ * (brain-nodes.js registerNodeRunner); absent a runner those nodes contribute+ * reasoning instructions to the system prompt (already baked by the compiler) and+ * perform no side effects.+ */++import { apiFetch } from '../../api.js';+import { protocol, ACTION_TYPES } from '../../agent-protocol.js';+import { getNodeRunner } from './brain-nodes.js';++export class BrainRuntime {+ /**+ * @param {object} o+ * @param {import('./brain-graph.js').BrainGraphView} o.graphView+ * @param {import('../agent-studio-store.js').default} o.studio+ * @param {() => object} o.getCompiled returns compileBrain() of the live graph+ * @param {() => object} o.getGraph returns the raw graph (node ids for animation)+ */+ constructor({ graphView, studio, getCompiled, getGraph }) {+ this.graphView = graphView;+ this.studio = studio;+ this.getCompiled = getCompiled;+ this.getGraph = getGraph;+ this._abort = null;+ }++ abort() {+ this._abort?.abort();+ this._abort = null;+ }++ /**+ * Run one turn.+ * @param {string} userText+ * @param {{ history?: Array<{role,content}>, onToken?:(t:string)=>void, onMeta?:(m)=>void }} opts+ * @returns {Promise<{ text:string, stats:object }>}+ */+ async run(userText, { history = [], onToken = () => {}, onMeta = () => {} } = {}) {+ const compiled = this.getCompiled();+ const gv = this.graphView;+ const graph = this.getGraph();+ const nodeOf = (type) => graph.nodes.find((n) => n.type === type);++ gv.clearActive();+ const circuit = gv.circuit();+ gv.setActive(circuit.nodeIds, circuit.edgeIds);++ // 1. Persona lights up first.+ const personaNode = nodeOf('persona');+ if (personaNode) gv.pulseNode(personaNode.id);++ let system = compiled.personaPrompt;++ // 2. Memory recall — real semantic search over the agent's memory.+ const memNode = nodeOf('memory');+ if (memNode && compiled.memory) {+ gv.setNodeBusy(memNode.id, true);+ gv.pulseNode(memNode.id);+ try {+ const recalled = await this._recall(userText, compiled.memory);+ if (recalled.length) {+ system += `\n\nRelevant memories:\n${recalled.map((m) => `- ${m}`).join('\n')}`;+ gv.setNodeStat(memNode.id, `${recalled.length} recalled`);+ this.studio.emitMarket?.({ type: 'memory:recalled', count: recalled.length });+ } else {+ gv.setNodeStat(memNode.id, 'no matches');+ }+ } catch (e) {+ gv.setNodeStat(memNode.id, 'recall failed');+ console.warn('[brain] memory recall failed', e);+ } finally {+ gv.setNodeBusy(memNode.id, false);+ }+ }++ // 3. Skill / market nodes — P4 runners if registered (reasoning-only otherwise).+ for (const node of graph.nodes.filter((n) => n.type === 'skill' || n.type === 'market')) {+ const runner = getNodeRunner(node.type);+ if (!runner) continue;+ gv.setNodeBusy(node.id, true);+ gv.pulseNode(node.id);+ try {+ const out = await runner(node, this._nodeContext(compiled));+ if (out?.context) system += `\n\n${out.context}`;+ } catch (e) {+ console.warn(`[brain] ${node.type} runner failed`, e);+ } finally {+ gv.setNodeBusy(node.id, false);+ }+ }++ // 4. Model — stream real tokens from the multi-provider proxy.+ const modelNode = nodeOf('model');+ if (modelNode) { gv.setNodeBusy(modelNode.id, true); gv.pulseNode(modelNode.id); }+ protocol.emit({ type: ACTION_TYPES.THINK, payload: { thought: 'reasoning…' } });+ this.studio.emitMarket?.({ type: 'brain:thinking' });++ const messages = [...history, { role: 'user', content: userText }].slice(-20);+ let text = '';+ const stats = {};+ try {+ await this._stream({+ provider: compiled.provider,+ system,+ messages,+ maxTokens: compiled.maxTokens,+ onMeta: (m) => { stats.label = m.label; stats.network = m.network; onMeta(m); },+ onFirst: (ms) => {+ stats.firstTokenMs = ms;+ if (modelNode) gv.setNodeStat(modelNode.id, `${ms}ms to first token`);+ },+ onToken: (t) => { text += t; onToken(t); },+ onDone: (d) => {+ stats.elapsedMs = d.elapsedMs;+ stats.firstTokenMs = d.firstTokenMs ?? stats.firstTokenMs;+ stats.usage = d.usage || null;+ if (modelNode) {+ const tok = d.usage?.outputTokens ? `${d.usage.outputTokens} tok` : '';+ const tps = d.usage?.outputTokens && d.elapsedMs ? ` · ${Math.round((d.usage.outputTokens / d.elapsedMs) * 1000)} tok/s` : '';+ gv.setNodeStat(modelNode.id, `${tok}${tps} · ${d.elapsedMs}ms`.trim());+ }+ },+ });+ } finally {+ if (modelNode) gv.setNodeBusy(modelNode.id, false);+ }++ // 5. Output — drive the live avatar.+ const outNode = nodeOf('output');+ if (outNode) {+ gv.pulseNode(outNode.id);+ const o = compiled.output || {};+ if (o.speak !== false && text) {+ protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text } });+ }+ if (o.emotion !== false) {+ this.studio.emitMarket?.({ type: 'brain:answered' });+ }+ }++ // 6. Memory write — persist the exchange when the node enables it.+ if (memNode && compiled.memory?.write && text) {+ this._remember(userText, text).catch((e) => console.warn('[brain] memory write failed', e));+ }++ return { text, stats };+ }++ // ── Memory (real, via the agent's AgentMemory) ──────────────────────────────++ async _recall(query, cfg) {+ const mem = this.studio.identity?.memory;+ if (!mem?.recall) return [];+ const results = await mem.recall(query, { limit: cfg.topK, minScore: cfg.minScore });+ return (results || []).map((m) => m.text || m.content || (typeof m === 'string' ? m : JSON.stringify(m))).filter(Boolean);+ }++ async _remember(userText, replyText) {+ const mem = this.studio.identity?.memory;+ if (!mem?.add) return;+ await mem.add({ type: 'conversation', text: `User: ${userText}\nAgent: ${replyText}`.slice(0, 1000), tags: ['studio', 'chat'] });+ }++ _nodeContext(compiled) {+ return {+ brain: compiled,+ mint: null, // runtime-supplied by P4; $THREE is the only coin the platform promotes+ recall: (q) => this._recall(q, compiled.memory || { topK: 4, minScore: 0.75 }),+ emit: (action) => protocol.emit(action),+ say: (t) => protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: t } }),+ signal: this._abort?.signal,+ now: Date.now(),+ };+ }++ // ── SSE stream from /api/brain/chat ─────────────────────────────────────────++ async _stream({ provider, system, messages, maxTokens, onMeta, onFirst, onToken, onDone }) {+ this._abort = new AbortController();+ const resp = await apiFetch('/api/brain/chat', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ provider, system, messages, maxTokens }),+ signal: this._abort.signal,+ });+ if (!resp.ok) {+ const detail = await resp.json().catch(() => ({}));+ throw new Error(detail?.error?.message || detail?.message || `chat ${resp.status}`);+ }+ const reader = resp.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ let event = null;+ let streamErr = null;++ // SSE frames are separated by a blank line. Each frame may carry an+ // `event:` line plus one or more `data:` lines; a data-only frame is a text+ // chunk (JSON-encoded string), matching the api/brain/chat.js protocol.+ const handleFrame = (frame) => {+ let evName = null;+ const dataLines = [];+ for (const line of frame.split('\n')) {+ if (line.startsWith('event:')) evName = line.slice(6).trim();+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));+ }+ if (!dataLines.length) return;+ const raw = dataLines.join('\n');+ if (raw === '[DONE]') return;+ let payload;+ try { payload = JSON.parse(raw); } catch { return; }+ switch (evName) {+ case 'meta': onMeta?.(payload); break;+ case 'first': onFirst?.(payload.firstTokenMs); break;+ case 'done': onDone?.(payload); break;+ case 'error': streamErr = new Error(payload.message || 'stream error'); break;+ case 'fallback': break; // advisory+ default: if (typeof payload === 'string') onToken?.(payload); break;+ }+ };++ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ let sep;+ while ((sep = buf.indexOf('\n\n')) !== -1) {+ const frame = buf.slice(0, sep);+ buf = buf.slice(sep + 2);+ if (frame.trim()) handleFrame(frame);+ }+ }+ if (buf.trim()) handleFrame(buf);+ this._abort = null;+ if (streamErr) throw streamErr;+ }+}diff --git a/src/studio/brain/brain-studio.js b/src/studio/brain/brain-studio.jsnew file mode 100644index 000000000..35f8138a2--- /dev/null+++ b/src/studio/brain/brain-studio.js@@ -0,0 +1,383 @@+/**+ * Brain Studio — controller (P1)+ * ==============================+ * The visible, programmable agent brain. Mounts into the studio shell's Brain tab+ * container and wires together:+ * • BrainGraphView — the visual node-graph editor+ * • compileBrain — graph → real persona_prompt + provider/tool config+ * • BrainRuntime — streaming test chat against the real LLM proxy + live+ * memory + active-path animation + avatar reactions+ * • TEMPLATES — forkable Sniper / Scalper / Researcher / Companion brains+ *+ * The graph is the persona. We persist the graph verbatim to meta.studio.brain+ * (lossless round-trip) AND the compiled persona to agent_identities.persona_prompt+ * (so /api/chat and every existing chat surface keep working), both through the+ * shared `studio` store (optimistic + debounced PUT).+ *+ * Mount: import { mountBrainStudio } from './brain/brain-studio.js';+ * mountBrainStudio(container, { studio });+ */++import { BrainGraphView } from './brain-graph.js';+import { compileBrain } from './brain-compile.js';+import { BrainRuntime } from './brain-runtime.js';+import { NODE_TYPES, normalizeGraph, defaultGraph } from './brain-nodes.js';+import { TEMPLATES } from './brain-templates.js';++const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));+const PALETTE = ['persona', 'model', 'memory', 'skill', 'market', 'output'];++export function mountBrainStudio(container, { studio }) {+ if (container.dataset.brainMounted) return;+ container.dataset.brainMounted = '1';+ return new BrainStudio(container, studio);+}++class BrainStudio {+ constructor(container, studio) {+ this.studio = studio;+ this.el = container;+ this.providers = [];+ this._saveTimer = null;+ this._history = [];+ this._savedPersona = studio.brain?.compiled?.personaPrompt || '';+ this._render();+ this._init();+ }++ async _init() {+ // Providers power the Model node's picker — real availability from the proxy.+ try {+ const resp = await fetch('/api/brain/chat', { credentials: 'include' });+ if (resp.ok) this.providers = (await resp.json()).providers || [];+ } catch { /* picker falls back to a static list of model ids */ }++ const stored = this.studio.brain?.graph;+ if (stored) {+ this._showEditor();+ this.graph.load(normalizeGraph(stored));+ } else {+ this._showOnboarding();+ }+ }++ // ── Layout ────────────────────────────────────────────────────────────────++ _render() {+ this.el.innerHTML = `+ <div class="brainstudio" data-view="onboard">+ <div class="brainstudio__onboard" id="bsOnboard">+ <div class="brainstudio__onboard-inner">+ <h1>Build your agent's mind</h1>+ <p>Wire persona, model, memory, skills and trading reasoning into a living circuit. Watch it light up as it thinks.</p>+ <div class="brainstudio__templates" id="bsTplGrid"></div>+ <button class="studio__btn studio__btn-primary" id="bsBlank">Start from blank</button>+ </div>+ </div>++ <div class="brainstudio__editor" id="bsEditor" hidden>+ <div class="brainstudio__toolbar">+ <div class="brainstudio__palette" id="bsPalette" role="toolbar" aria-label="Add node"></div>+ <div class="brainstudio__tools">+ <button class="studio__btn" id="bsFit" title="Frame the graph">Fit</button>+ <button class="studio__btn" id="bsDiff" title="See how this brain reads">Behavior</button>+ <button class="studio__btn" id="bsTpl" title="Fork a template">Templates</button>+ </div>+ </div>+ <div class="brainstudio__main">+ <div class="brainstudio__canvas" id="bsCanvas"></div>+ <aside class="brainstudio__side">+ <div class="brainstudio__inspector" id="bsInspector"></div>+ <div class="brainstudio__test" id="bsTest">+ <div class="brainstudio__test-head">Test chat <span class="brainstudio__test-model" id="bsTestModel"></span></div>+ <div class="brainstudio__transcript" id="bsTranscript"></div>+ <form class="brainstudio__compose" id="bsCompose">+ <textarea id="bsInput" rows="1" placeholder="Talk to your agent…" aria-label="Test message"></textarea>+ <button class="studio__btn studio__btn-primary" type="submit" id="bsSend">Run</button>+ </form>+ </div>+ </aside>+ </div>+ </div>++ <div class="brainstudio__modal" id="bsModal" hidden>+ <div class="brainstudio__modal-card" id="bsModalCard"></div>+ </div>+ </div>`;++ this.root = this.el.querySelector('.brainstudio');+ this._renderTemplateGrid(this.el.querySelector('#bsTplGrid'));+ this._renderPalette();+ this.el.querySelector('#bsBlank').addEventListener('click', () => this._start(defaultGraph()));+ this.el.querySelector('#bsFit').addEventListener('click', () => this.graph?.fit());+ this.el.querySelector('#bsDiff').addEventListener('click', () => this._showBehavior());+ this.el.querySelector('#bsTpl').addEventListener('click', () => this._showTemplateModal());+ this.el.querySelector('#bsCompose').addEventListener('submit', (e) => { e.preventDefault(); this._send(); });+ const input = this.el.querySelector('#bsInput');+ input.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); this._send(); } });+ input.addEventListener('input', () => { input.style.height = 'auto'; input.style.height = `${Math.min(120, input.scrollHeight)}px`; });+ this.el.querySelector('#bsModal').addEventListener('click', (e) => { if (e.target.id === 'bsModal') this._closeModal(); });+ }++ _renderPalette() {+ const pal = this.el.querySelector('#bsPalette');+ pal.innerHTML = PALETTE.map((t) => `<button class="brainstudio__chip brainstudio__chip--${NODE_TYPES[t].accent}" data-add="${t}" title="Add ${NODE_TYPES[t].title}">+ ${esc(NODE_TYPES[t].title)}</button>`).join('');+ pal.addEventListener('click', (e) => {+ const t = e.target.closest('[data-add]')?.dataset.add;+ if (t) this.graph?.addNode(t);+ });+ }++ _renderTemplateGrid(host) {+ host.innerHTML = TEMPLATES.map((t) => `+ <button class="brainstudio__tpl brainstudio__tpl--${t.accent}" data-tpl="${t.id}">+ <span class="brainstudio__tpl-name">${esc(t.name)}</span>+ <span class="brainstudio__tpl-tag">${esc(t.tagline)}</span>+ </button>`).join('');+ host.addEventListener('click', (e) => {+ const id = e.target.closest('[data-tpl]')?.dataset.tpl;+ const tpl = TEMPLATES.find((t) => t.id === id);+ if (tpl) this._start(tpl.make());+ });+ }++ // ── View states ────────────────────────────────────────────────────────++ _showOnboarding() { this.root.dataset.view = 'onboard'; this.el.querySelector('#bsOnboard').hidden = false; this.el.querySelector('#bsEditor').hidden = true; }++ _showEditor() {+ this.root.dataset.view = 'editor';+ this.el.querySelector('#bsOnboard').hidden = true;+ this.el.querySelector('#bsEditor').hidden = false;+ if (!this.graph) {+ this.graph = new BrainGraphView(this.el.querySelector('#bsCanvas'), {+ onChange: (g) => this._onGraphChange(g),+ onSelect: (n) => this._renderInspector(n),+ });+ this.runtime = new BrainRuntime({+ graphView: this.graph,+ studio: this.studio,+ getCompiled: () => compileBrain(this.graph.toGraph(), { agentName: this.studio.agent?.name }),+ getGraph: () => this.graph.toGraph(),+ });+ }+ }++ _start(graph) {+ this._showEditor();+ this.graph.load(normalizeGraph(graph));+ this._onGraphChange(this.graph.toGraph(), { immediate: true });+ this._renderInspector(null);+ }++ // ── Persistence ─────────────────────────────────────────────────────────++ _onGraphChange(graph, { immediate = false } = {}) {+ const compiled = compileBrain(graph, { agentName: this.studio.agent?.name });+ this._updateTestModelLabel(compiled);+ clearTimeout(this._saveTimer);+ const persist = () => {+ this.studio.patch({+ meta: { studio: { studio_version: 1, brain: { version: 1, graph, compiled: { personaPrompt: compiled.personaPrompt, provider: compiled.provider, model: compiled.model } } } },+ personaPrompt: compiled.personaPrompt,+ });+ };+ if (immediate) persist();+ else this._saveTimer = setTimeout(persist, 400);+ }++ // ── Inspector ─────────────────────────────────────────────────────────────++ _renderInspector(node) {+ const host = this.el.querySelector('#bsInspector');+ if (!node) {+ host.innerHTML = `<div class="brainstudio__inspector-empty"><h3>Inspector</h3><p>Select a node to edit it, or drag from a node's right-hand port to wire it into another.</p></div>`;+ return;+ }+ const spec = NODE_TYPES[node.type];+ host.innerHTML = `<div class="brainstudio__insp-head"><span class="brainstudio__insp-dot brainstudio__insp-dot--${spec.accent}"></span><h3>${esc(spec.title)}</h3></div>+ <div class="brainstudio__fields">${spec.fields.map((f) => this._fieldHtml(f, node.data[f.key])).join('')}</div>`;+ host.querySelectorAll('[data-field]').forEach((inp) => {+ const key = inp.dataset.field;+ const field = spec.fields.find((f) => f.key === key);+ const handler = () => this.graph.updateNodeData(node.id, { [key]: this._readField(field, inp) });+ inp.addEventListener(inp.tagName === 'SELECT' || inp.type === 'checkbox' ? 'change' : 'input', handler);+ });+ }++ _fieldHtml(field, value) {+ const id = `f_${field.key}`;+ const label = `<label class="brainstudio__field-label" for="${id}">${esc(field.label)}</label>`;+ let control = '';+ switch (field.type) {+ case 'textarea':+ control = `<textarea class="brainstudio__input" id="${id}" data-field="${field.key}" rows="2">${esc(value || '')}</textarea>`;+ break;+ case 'number':+ control = `<input class="brainstudio__input" id="${id}" data-field="${field.key}" type="number" min="${field.min ?? ''}" max="${field.max ?? ''}" step="${field.step ?? 1}" value="${esc(value ?? '')}" />`;+ break;+ case 'toggle':+ control = `<label class="brainstudio__toggle"><input id="${id}" data-field="${field.key}" type="checkbox" ${value ? 'checked' : ''} /><span></span></label>`;+ break;+ case 'select':+ control = `<select class="brainstudio__input" id="${id}" data-field="${field.key}">${field.options.map((o) => `<option value="${esc(o)}" ${o === value ? 'selected' : ''}>${esc(o)}</option>`).join('')}</select>`;+ break;+ case 'provider':+ control = this._providerSelect(id, field.key, value);+ break;+ case 'skill':+ control = this._skillSelect(id, field.key, value);+ break;+ case 'tags':+ control = `<input class="brainstudio__input" id="${id}" data-field="${field.key}" type="text" value="${esc((value || []).join(', '))}" placeholder="comma, separated" />`;+ break;+ default:+ control = `<input class="brainstudio__input" id="${id}" data-field="${field.key}" type="text" value="${esc(value ?? '')}" placeholder="${esc(field.placeholder || '')}" />`;+ }+ return `<div class="brainstudio__field">${label}${control}</div>`;+ }++ _providerSelect(id, key, value) {+ const list = this.providers.length ? this.providers : [{ key: value || 'claude-sonnet-4-6', label: value || 'Claude Sonnet 4.6', available: true, tier: '', network: '' }];+ const opts = list.map((p) => `<option value="${esc(p.key)}" ${p.key === value ? 'selected' : ''} ${p.available ? '' : 'disabled'}>${esc(p.label)}${p.available ? '' : ' (no key)'}${p.tier ? ` · ${esc(p.tier)}` : ''}</option>`).join('');+ return `<select class="brainstudio__input" id="${id}" data-field="${key}">${opts}</select>`;+ }++ _skillSelect(id, key, value) {+ const skills = this.studio.agent?.skills || [];+ if (!skills.length) return `<input class="brainstudio__input" id="${id}" data-field="${key}" type="text" value="${esc(value || '')}" placeholder="no skills enabled yet" />`;+ const opts = ['<option value="">— pick a skill —</option>', ...skills.map((s) => `<option value="${esc(s)}" ${s === value ? 'selected' : ''}>${esc(s)}</option>`)].join('');+ return `<select class="brainstudio__input" id="${id}" data-field="${key}">${opts}</select>`;+ }++ _readField(field, inp) {+ switch (field.type) {+ case 'number': return Number(inp.value);+ case 'toggle': return inp.checked;+ case 'tags': return inp.value.split(',').map((s) => s.trim()).filter(Boolean);+ default: return inp.value;+ }+ }++ // ── Test chat ───────────────────────────────────────────────────────────++ _updateTestModelLabel(compiled) {+ const el = this.el.querySelector('#bsTestModel');+ if (el) el.textContent = compiled.provider ? `· ${compiled.provider}` : '';+ }++ async _send() {+ const input = this.el.querySelector('#bsInput');+ const text = input.value.trim();+ if (!text || this._running) return;+ input.value = ''; input.style.height = 'auto';+ this._running = true;+ this.el.querySelector('#bsSend').disabled = true;++ this._appendMsg('user', text);+ const bubble = this._appendMsg('agent', '');+ const statEl = bubble.querySelector('.brainstudio__msg-stat');+ try {+ const { stats } = await this.runtime.run(text, {+ history: this._history,+ onToken: (t) => { bubble.querySelector('.brainstudio__msg-text').textContent += t; this._scrollTranscript(); },+ onMeta: (m) => { statEl.textContent = `${m.label}…`; },+ });+ const reply = bubble.querySelector('.brainstudio__msg-text').textContent;+ this._history.push({ role: 'user', content: text }, { role: 'assistant', content: reply });+ this._history = this._history.slice(-20);+ statEl.textContent = this._fmtStats(stats);+ } catch (err) {+ bubble.classList.add('is-error');+ bubble.querySelector('.brainstudio__msg-text').textContent = this._friendlyError(err);+ } finally {+ this._running = false;+ this.el.querySelector('#bsSend').disabled = false;+ this.graph.clearActive();+ }+ }++ _friendlyError(err) {+ const m = err?.message || 'stream error';+ if (/sign in/i.test(m)) return 'Sign in to use this model, or pick a free one in the Model node.';+ if (/rate|429|too many/i.test(m)) return 'Rate limited — slow down a moment and try again.';+ if (/not_configured|no api key/i.test(m)) return 'That model has no API key configured. Pick another in the Model node.';+ return `Couldn't reach the model: ${m}`;+ }++ _fmtStats(s) {+ const bits = [];+ if (s.label) bits.push(s.label);+ if (s.firstTokenMs != null) bits.push(`${s.firstTokenMs}ms first token`);+ if (s.usage?.outputTokens) bits.push(`${s.usage.outputTokens} tok`);+ if (s.elapsedMs) bits.push(`${(s.elapsedMs / 1000).toFixed(1)}s`);+ return bits.join(' · ');+ }++ _appendMsg(role, text) {+ const t = this.el.querySelector('#bsTranscript');+ const msg = document.createElement('div');+ msg.className = `brainstudio__msg brainstudio__msg--${role}`;+ msg.innerHTML = `<div class="brainstudio__msg-text"></div><div class="brainstudio__msg-stat"></div>`;+ msg.querySelector('.brainstudio__msg-text').textContent = text;+ t.appendChild(msg);+ this._scrollTranscript();+ return msg;+ }++ _scrollTranscript() {+ const t = this.el.querySelector('#bsTranscript');+ t.scrollTop = t.scrollHeight;+ }++ // ── Modals: templates + behavior diff ─────────────────────────────────────++ _showTemplateModal() {+ const card = this.el.querySelector('#bsModalCard');+ card.innerHTML = `<div class="brainstudio__modal-head"><h2>Fork a brain</h2><button class="brainstudio__modal-x" aria-label="Close">×</button></div>+ <p class="brainstudio__modal-sub">Replaces the current graph. Your current brain is saved until you save over it.</p>+ <div class="brainstudio__templates" id="bsModalTpl"></div>`;+ this._renderTemplateGrid(card.querySelector('#bsModalTpl'));+ card.querySelector('.brainstudio__modal-x').addEventListener('click', () => this._closeModal());+ card.querySelector('#bsModalTpl').addEventListener('click', () => this._closeModal());+ this.el.querySelector('#bsModal').hidden = false;+ }++ // Show how the current circuit compiles to behavior, and diff it against the+ // last-saved brain so a user sees exactly how an edit changes the agent.+ _showBehavior() {+ const current = compileBrain(this.graph.toGraph(), { agentName: this.studio.agent?.name });+ const prev = this._savedPersona;+ const card = this.el.querySelector('#bsModalCard');+ card.innerHTML = `<div class="brainstudio__modal-head"><h2>How this brain behaves</h2><button class="brainstudio__modal-x" aria-label="Close">×</button></div>+ <div class="brainstudio__behavior">+ <div class="brainstudio__behavior-meta">+ <span><b>Model</b> ${esc(current.provider)}</span>+ <span><b>Memory</b> ${current.memory ? `top-${current.memory.topK} @ ${current.memory.minScore}` : 'off'}</span>+ <span><b>Skills</b> ${current.skills.length || 'none'}</span>+ <span><b>Market rules</b> ${current.marketRules.length || 'none'}</span>+ </div>+ <h3>Compiled persona</h3>+ <pre class="brainstudio__diff">${this._diffHtml(prev, current.personaPrompt)}</pre>+ </div>`;+ card.querySelector('.brainstudio__modal-x').addEventListener('click', () => this._closeModal());+ this.el.querySelector('#bsModal').hidden = false;+ }++ // Minimal line-level diff: unchanged lines plain, added green, removed red.+ _diffHtml(prev, next) {+ const a = (prev || '').split('\n');+ const b = (next || '').split('\n');+ const aSet = new Set(a);+ const bSet = new Set(b);+ const out = [];+ for (const line of a) if (!bSet.has(line) && line.trim()) out.push(`<span class="diff-del">- ${esc(line)}</span>`);+ for (const line of b) out.push(bSet.has(line) && !aSet.has(line) ? `<span class="diff-add">+ ${esc(line)}</span>` : esc(line));+ return out.join('\n') || '<span class="diff-muted">(empty — wire a Persona node)</span>';+ }++ _closeModal() {+ this.el.querySelector('#bsModal').hidden = true;+ this._savedPersona = compileBrain(this.graph.toGraph(), { agentName: this.studio.agent?.name }).personaPrompt;+ }+}diff --git a/src/studio/brain/brain-templates.js b/src/studio/brain/brain-templates.jsnew file mode 100644index 000000000..6dee4f117--- /dev/null+++ b/src/studio/brain/brain-templates.js@@ -0,0 +1,82 @@+/**+ * Brain Studio — template gallery (P1)+ * ====================================+ * Forkable starting circuits. Each returns a fresh, normalized graph (new node+ * ids every time) so a user can fork, tweak, and save without colliding with the+ * template. These are the "screenshot moment" on-ramps: a user picks Sniper and+ * instantly has a wired mind they can run and watch think.+ */++import { makeNode, edge } from './brain-nodes.js';++function build(spec) {+ const nodes = spec.nodes.map((n) => makeNode(n.type, n.x, n.y, n.data || {}));+ const byKey = {};+ spec.nodes.forEach((n, i) => { if (n.key) byKey[n.key] = nodes[i]; });+ const edges = spec.edges.map(([fk, fp, tk, tp]) => edge(byKey[fk], fp, byKey[tk], tp));+ return { version: 1, nodes, edges };+}++export const TEMPLATES = [+ {+ id: 'sniper',+ name: 'Sniper',+ tagline: 'Fast, decisive on-chain trading copilot that watches levels and proposes action.',+ accent: 'market',+ make: () => build({+ nodes: [+ { key: 'p', type: 'persona', x: 60, y: 80, data: { role: 'a sharp on-chain trading copilot', tone: 'terse, decisive, numbers-first', risk: 'aggressive', avoid: ['hype', 'financial advice disclaimers'], greeting: 'Watching the tape. What are we hunting?' } },+ { key: 'mkt', type: 'market', x: 60, y: 300, data: { trigger: 'breaks-level', level: '', action: 'propose-action' } },+ { key: 'mem', type: 'memory', x: 60, y: 470, data: { topK: 5, minScore: 0.72, write: true } },+ { key: 'm', type: 'model', x: 430, y: 200, data: { provider: 'claude-sonnet-4-6', maxTokens: 800 } },+ { key: 'o', type: 'output', x: 800, y: 220, data: { speak: true, emotion: true, lipsync: true } },+ ],+ edges: [['p', 'identity', 'm', 'identity'], ['mkt', 'signal', 'm', 'context'], ['mem', 'recall', 'm', 'context'], ['m', 'reply', 'o', 'reply']],+ }),+ },+ {+ id: 'scalper',+ name: 'Scalper',+ tagline: 'High-frequency, low-latency reactor tuned for speed over verbosity.',+ accent: 'model',+ make: () => build({+ nodes: [+ { key: 'p', type: 'persona', x: 60, y: 100, data: { role: 'a high-frequency scalping assistant', tone: 'ultra-terse, signal-only', risk: 'balanced', avoid: ['filler', 'preamble'], greeting: 'Ready. Feed me ticks.' } },+ { key: 'mkt', type: 'market', x: 60, y: 320, data: { trigger: 'price-change', level: '+2%', action: 'alert-only' } },+ { key: 'm', type: 'model', x: 430, y: 200, data: { provider: 'claude-haiku-4-5', maxTokens: 400 } },+ { key: 'o', type: 'output', x: 800, y: 210, data: { speak: true, emotion: true, lipsync: false } },+ ],+ edges: [['p', 'identity', 'm', 'identity'], ['mkt', 'signal', 'm', 'context'], ['m', 'reply', 'o', 'reply']],+ }),+ },+ {+ id: 'researcher',+ name: 'Researcher',+ tagline: 'Deep, memory-rich analyst that reasons carefully and cites what it recalls.',+ accent: 'memory',+ make: () => build({+ nodes: [+ { key: 'p', type: 'persona', x: 60, y: 90, data: { role: 'a meticulous research analyst', tone: 'thorough, neutral, evidence-led', risk: 'cautious', vocabulary: ['evidence', 'tradeoff', 'hypothesis'], avoid: ['hype', 'certainty without basis'], greeting: 'What should we dig into?' } },+ { key: 'mem', type: 'memory', x: 60, y: 340, data: { topK: 8, minScore: 0.7, write: true } },+ { key: 'm', type: 'model', x: 430, y: 190, data: { provider: 'claude-opus-4-7', maxTokens: 2000 } },+ { key: 'o', type: 'output', x: 800, y: 210, data: { speak: true, emotion: true, lipsync: true } },+ ],+ edges: [['p', 'identity', 'm', 'identity'], ['mem', 'recall', 'm', 'context'], ['m', 'reply', 'o', 'reply']],+ }),+ },+ {+ id: 'companion',+ name: 'Companion',+ tagline: 'Warm, expressive conversational agent — memory on, full emotion + lip-sync.',+ accent: 'persona',+ make: () => build({+ nodes: [+ { key: 'p', type: 'persona', x: 60, y: 110, data: { role: 'a warm, witty companion', tone: 'friendly, playful, curious', risk: 'balanced', avoid: ['corporate-speak'], greeting: 'Hey! Good to see you. What\'s up?' } },+ { key: 'mem', type: 'memory', x: 60, y: 350, data: { topK: 6, minScore: 0.74, write: true } },+ { key: 'm', type: 'model', x: 430, y: 200, data: { provider: 'claude-sonnet-4-6', maxTokens: 1200 } },+ { key: 'o', type: 'output', x: 800, y: 220, data: { speak: true, emotion: true, lipsync: true } },+ ],+ edges: [['p', 'identity', 'm', 'identity'], ['mem', 'recall', 'm', 'context'], ['m', 'reply', 'o', 'reply']],+ }),+ },+];diff --git a/src/studio/studio-shell.js b/src/studio/studio-shell.jsnew file mode 100644index 000000000..7a3da5447--- /dev/null+++ b/src/studio/studio-shell.js@@ -0,0 +1,342 @@+/**+ * ════════════════════════════════════════════════════════════════════════════+ * Agent Studio — Shell (P0 foundation)+ * ════════════════════════════════════════════════════════════════════════════+ *+ * The skeleton + nervous system of /agent-studio: a persistent live avatar stage+ * (<agent-presence mode="stage">, reusing the platform renderer) beside a tabbed+ * editing surface — Brain · Memory · Body · Money · Skills. This file builds the+ * shell, the auth/loading/empty/error states, the identity header (a REAL control+ * that proves the live edit→PUT→avatar path), and exposes mount points the five+ * sub-studios fill.+ *+ * ── MOUNT POINTS FOR P1–P5 ───────────────────────────────────────────────────+ * Each tab is an empty <section data-studio-mount="<domain>"> with a designed+ * empty state inside a <div class="studio-empty">. To fill a tab, mount into its+ * container and remove/hide the empty state:+ *+ * import { studio } from '/src/studio/agent-studio-store.js';+ * const mount = document.querySelector('[data-studio-mount="brain"]');+ * mount.querySelector('.studio-empty')?.remove();+ * // …render your sub-studio into `mount`, reading studio.agent and calling+ * // studio.patch({ meta: { studio: { brain: {...} } } }) to persist.+ *+ * The shell also fires `studio-shell:ready` (CustomEvent, detail:{ studio, agent })+ * on `document` once the agent has loaded, so a sub-studio bundle can boot itself+ * without racing the shell.+ * ----------------------------------------------------------------------------+ */++import { studio } from './agent-studio-store.js';+import { getMe } from '../account.js';+import { log } from '../shared/log.js';+import './agent-presence.js'; // registers <agent-presence>++const TABS = [+ { key: 'brain', label: 'Brain', hint: "Model, provider, and the agent's reasoning graph." },+ { key: 'memory', label: 'Memory', hint: 'What the agent remembers, and for how long.' },+ { key: 'body', label: 'Body', hint: 'The 3D avatar, outfit, and animations.' },+ { key: 'money', label: 'Money', hint: 'Wallet, payouts, and per-call pricing.' },+ { key: 'skills', label: 'Skills', hint: 'Capabilities the agent can perform and sell.' },+];++const EMPTY_COPY = {+ brain: {+ title: 'Wire up a brain',+ body: 'Pick a model and shape how your agent thinks. The Brain studio mounts here.',+ },+ memory: {+ title: 'Give it a memory',+ body: 'Decide what your agent recalls across conversations. The Memory studio mounts here.',+ },+ body: {+ title: 'Choose a body',+ body: 'Attach a 3D avatar, dress it, and set its animations. The Body studio mounts here.',+ cta: { label: 'Create an avatar →', href: '/create' },+ },+ money: {+ title: 'Set up money',+ body: "Fund the agent's wallet and price its skills. The Money studio mounts here.",+ },+ skills: {+ title: 'Add skills',+ body: 'Turn on capabilities your agent can perform and monetize. The Skills studio mounts here.',+ },+};++class StudioShell {+ constructor(root) {+ this.root = root;+ this.activeTab = this._initialTab();+ this._unsub = null;+ }++ _initialTab() {+ const hash = (location.hash || '').replace('#', '');+ return TABS.some((t) => t.key === hash) ? hash : 'brain';+ }++ async boot() {+ this._renderLoading();++ // Auth gate — /agent-studio is owner-only (every agent has a wallet).+ let user;+ try {+ user = await getMe();+ } catch (err) {+ log.warn('[studio-shell] auth check failed', err);+ return this._renderError('We couldn’t verify your session.', () => this.boot());+ }+ if (!user) return this._renderAuthGate();++ // Load (auto-creates) the caller's agent through the shared store.+ try {+ const agent = await studio.load();+ if (!agent || !agent.id) return this._renderEmptyAgent();+ this._renderShell(agent);+ this._bind();+ document.dispatchEvent(+ new CustomEvent('studio-shell:ready', { detail: { studio, agent } }),+ );+ } catch (err) {+ log.warn('[studio-shell] agent load failed', err);+ this._renderError('We couldn’t load your agent.', () => this.boot());+ }+ }++ // ── States ─────────────────────────────────────────────────────────────────++ _renderLoading() {+ this.root.innerHTML = `+ <div class="studio-skeleton" aria-busy="true" aria-label="Loading Agent Studio">+ <div class="sk-stage"></div>+ <div class="sk-panel">+ <div class="sk-tabs"></div>+ <div class="sk-rows">${'<div class="sk-row"></div>'.repeat(4)}</div>+ </div>+ </div>`;+ }++ _renderAuthGate() {+ const next = encodeURIComponent('/agent-studio');+ this.root.innerHTML = `+ <div class="studio-gate" role="region" aria-label="Sign in required">+ <div class="studio-gate-inner">+ <div class="studio-gate-glyph" aria-hidden="true">◐</div>+ <h1>Agent Studio</h1>+ <p>Author your agent's brain, memory, body, money, and skills in one place — and watch it come alive everywhere on the platform.</p>+ <a class="studio-btn studio-btn-primary" href="/login?next=${next}">Sign in to start</a>+ <a class="studio-btn studio-btn-ghost" href="/start">New here? Create your first agent</a>+ </div>+ </div>`;+ }++ _renderEmptyAgent() {+ this.root.innerHTML = `+ <div class="studio-gate" role="region" aria-label="No agent yet">+ <div class="studio-gate-inner">+ <div class="studio-gate-glyph" aria-hidden="true">✦</div>+ <h1>Create your first agent</h1>+ <p>You don't have an agent yet. Spin one up and it'll open right here in the Studio.</p>+ <a class="studio-btn studio-btn-primary" href="/create-agent">Create an agent →</a>+ </div>+ </div>`;+ }++ _renderError(message, onRetry) {+ this.root.innerHTML = `+ <div class="studio-gate" role="alert">+ <div class="studio-gate-inner">+ <div class="studio-gate-glyph" aria-hidden="true">⚠</div>+ <h1>Something went wrong</h1>+ <p>${esc(message)}</p>+ <button class="studio-btn studio-btn-primary" type="button" id="studio-retry">Try again</button>+ </div>+ </div>`;+ this.root.querySelector('#studio-retry')?.addEventListener('click', onRetry);+ }++ // ── Shell ────────────────────────────────────────────────────────────────++ _renderShell(agent) {+ this.root.innerHTML = `+ <div class="studio">+ <aside class="studio-stage" aria-label="Live agent">+ <agent-presence data-mode="stage"></agent-presence>+ <div class="studio-stage-hud">+ <span class="studio-live-dot" aria-hidden="true"></span>+ <span class="studio-live-label">Live · updates everywhere as you edit</span>+ </div>+ </aside>++ <section class="studio-panel" aria-label="Agent editor">+ <header class="studio-identity">+ <input id="studio-name" class="studio-name" value="${esc(agent.name || '')}"+ maxlength="100" aria-label="Agent name" placeholder="Name your agent" />+ <input id="studio-tagline" class="studio-tagline" value="${esc(agent.description || '')}"+ maxlength="280" aria-label="Agent tagline" placeholder="Add a short tagline…" />+ <span class="studio-save" id="studio-save" aria-live="polite"></span>+ </header>++ <nav class="studio-tabs" role="tablist" aria-label="Editor sections">+ ${TABS.map(+ (t, i) => `+ <button role="tab" class="studio-tab" id="tab-${t.key}"+ data-tab="${t.key}" aria-controls="panel-${t.key}"+ aria-selected="false" tabindex="-1" title="${esc(t.hint)} (${i + 1})">+ <span class="studio-tab-num" aria-hidden="true">${i + 1}</span>${t.label}+ </button>`,+ ).join('')}+ </nav>++ <div class="studio-tabpanels">+ ${TABS.map(+ (t) => `+ <section role="tabpanel" id="panel-${t.key}" class="studio-tabpanel"+ data-studio-mount="${t.key}" aria-labelledby="tab-${t.key}" hidden tabindex="0">+ <div class="studio-empty">+ <div class="studio-empty-glyph" aria-hidden="true"></div>+ <h2>${esc(EMPTY_COPY[t.key].title)}</h2>+ <p>${esc(EMPTY_COPY[t.key].body)}</p>+ ${+ EMPTY_COPY[t.key].cta+ ? `<a class="studio-btn studio-btn-ghost" href="${EMPTY_COPY[t.key].cta.href}">${esc(EMPTY_COPY[t.key].cta.label)}</a>`+ : ''+ }+ </div>+ </section>`,+ ).join('')}+ </div>+ </section>+ </div>`;++ this._selectTab(this.activeTab, { focus: false });+ }++ _bind() {+ // Tabs: click + number keys + Esc + arrow nav.+ const tabs = [...this.root.querySelectorAll('.studio-tab')];+ tabs.forEach((tab) => {+ tab.addEventListener('click', () => this._selectTab(tab.dataset.tab));+ tab.addEventListener('keydown', (e) => this._onTabKeydown(e, tabs));+ });+ this._keyHandler = (e) => this._onGlobalKeydown(e);+ document.addEventListener('keydown', this._keyHandler);++ // Identity header → real live edits through the store. Typing the name+ // updates the avatar's nameplate (via subscribe) and debounce-PUTs.+ const nameEl = this.root.querySelector('#studio-name');+ const tagEl = this.root.querySelector('#studio-tagline');+ const saveEl = this.root.querySelector('#studio-save');++ // Save indicator. The store debounces (~600ms) then PUTs; it surfaces a+ // failure via the 'error' event but no explicit success signal, so we show+ // "Saving…" on edit and settle to "Saved" shortly after the write window+ // (unless an error fires first). Honest within a frame of the real write.+ const markSaving = () => {+ if (!saveEl) return;+ saveEl.textContent = 'Saving…';+ saveEl.dataset.state = 'pending';+ clearTimeout(this._saveTimer);+ this._saveTimer = setTimeout(() => {+ if (saveEl.dataset.state === 'pending') {+ saveEl.textContent = 'Saved';+ saveEl.dataset.state = 'saved';+ }+ }, 1100);+ };+ nameEl?.addEventListener('input', () => {+ studio.patch({ name: nameEl.value });+ markSaving();+ });+ tagEl?.addEventListener('input', () => {+ studio.patch({ description: tagEl.value });+ markSaving();+ });++ // Keep the header in sync if another surface edits the same agent.+ this._unsub = studio.subscribe((agent) => {+ if (!agent) return;+ if (nameEl && document.activeElement !== nameEl && nameEl.value !== (agent.name || '')) {+ nameEl.value = agent.name || '';+ }+ if (tagEl && document.activeElement !== tagEl && tagEl.value !== (agent.description || '')) {+ tagEl.value = agent.description || '';+ }+ });+ this._unsubErr = studio.on('error', () => {+ clearTimeout(this._saveTimer);+ if (saveEl) {+ saveEl.textContent = 'Save failed — retrying';+ saveEl.dataset.state = 'error';+ }+ });+ }++ _onTabKeydown(e, tabs) {+ const i = tabs.indexOf(e.currentTarget);+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {+ e.preventDefault();+ const next = tabs[(i + 1) % tabs.length];+ this._selectTab(next.dataset.tab);+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {+ e.preventDefault();+ const prev = tabs[(i - 1 + tabs.length) % tabs.length];+ this._selectTab(prev.dataset.tab);+ }+ }++ _onGlobalKeydown(e) {+ // Don't hijack typing in the identity fields or any future panel input.+ const t = e.target;+ const typing = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);+ if (e.key === 'Escape') {+ // Esc closes/blurs the active panel control and returns focus to its tab.+ if (typing) {+ t.blur();+ this.root.querySelector(`#tab-${this.activeTab}`)?.focus();+ e.preventDefault();+ }+ return;+ }+ if (typing) return;+ const n = Number(e.key);+ if (n >= 1 && n <= TABS.length) {+ e.preventDefault();+ this._selectTab(TABS[n - 1].key, { focus: true });+ }+ }++ _selectTab(key, { focus = true } = {}) {+ this.activeTab = key;+ for (const tab of this.root.querySelectorAll('.studio-tab')) {+ const on = tab.dataset.tab === key;+ tab.setAttribute('aria-selected', String(on));+ tab.tabIndex = on ? 0 : -1;+ if (on && focus) tab.focus();+ }+ for (const panel of this.root.querySelectorAll('.studio-tabpanel')) {+ panel.hidden = panel.dataset.studioMount !== key;+ }+ if (history.replaceState) history.replaceState(null, '', `#${key}`);+ }+}++function esc(s) {+ return String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function init() {+ const root = document.getElementById('studio-root');+ if (!root) return;+ new StudioShell(root).boot();+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', init);+} else {+ init();+}diff --git a/tests/agent-wallet-trade.test.js b/tests/agent-wallet-trade.test.jsindex 2f5b39b6b..01cf8ebd4 100644--- a/tests/agent-wallet-trade.test.js+++ b/tests/agent-wallet-trade.test.js@@ -31,6 +31,13 @@ vi.mock('../api/_lib/auth.js', () => ({extractBearer: vi.fn(() => null),}));+// CSRF enforcement is exercised by agent-identity-csrf.test.js; here we mock it+// through so these tests focus on trade guards, spend policy, and execution.+vi.mock('../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => true),+ issueCsrf: vi.fn(async () => ({ token: 'test-csrf', expiresIn: 3600 })),+}));+// ── db ──────────────────────────────────────────────────────────────────────const sqlState = { queue: [], calls: [] };vi.mock('../api/_lib/db.js', () => ({diff --git a/tests/agent-wallet-withdraw.test.js b/tests/agent-wallet-withdraw.test.jsindex af99d2c05..d9b4f8119 100644--- a/tests/agent-wallet-withdraw.test.js+++ b/tests/agent-wallet-withdraw.test.js@@ -26,6 +26,13 @@ vi.mock('../api/_lib/auth.js', () => ({extractBearer: vi.fn(() => null),}));+// CSRF enforcement is exercised by agent-identity-csrf.test.js; here we mock it+// through so these tests focus on withdraw validation, spend policy, and signing.+vi.mock('../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => true),+ issueCsrf: vi.fn(async () => ({ token: 'test-csrf', expiresIn: 3600 })),+}));+// ── db ──────────────────────────────────────────────────────────────────────const sqlState = { queue: [], calls: [] };vi.mock('../api/_lib/db.js', () => ({diff --git a/tests/solana-trade-guards.test.js b/tests/solana-trade-guards.test.jsindex 04f957580..4fe23377b 100644--- a/tests/solana-trade-guards.test.js+++ b/tests/solana-trade-guards.test.js@@ -32,6 +32,13 @@ vi.mock('../api/_lib/auth.js', () => ({extractBearer: vi.fn(() => null),}));+// CSRF enforcement is exercised by agent-identity-csrf.test.js; mock it through+// so these tests focus on the trade execution guard ladder.+vi.mock('../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => true),+ issueCsrf: vi.fn(async () => ({ token: 'test-csrf', expiresIn: 3600 })),+}));+vi.mock('../api/_lib/rate-limit.js', () => ({limits: { authIp: vi.fn(async () => ({ success: true })), walletRead: vi.fn(async () => ({ success: true })) },clientIp: () => '127.0.0.1',diff --git a/vercel.json b/vercel.jsonindex 9525dac7e..983db4485 100644--- a/vercel.json+++ b/vercel.json@@ -3345,6 +3345,14 @@"src": "/create-agent/","dest": "/create-agent.html"},+ {+ "src": "/agent-studio",+ "dest": "/agent-studio.html"+ },+ {+ "src": "/agent-studio/",+ "dest": "/agent-studio.html"+ },{"src": "/creating","dest": "/creating.html"