Skip to content

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

Add memory-grounded autopilot, brain ownership/anchoring, vaults wallet+jupiter, genesis & theater pages

nirholas96cf41697f2a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b03b2854b..bff668d64 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,8 +13,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **$THREE Tiers · Hold-to-Access** (`/three`) — Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.
- **Agent Genome — breed two agents** (`/genome`) — Breed two AI agents into a provably-inherited offspring. The child inherits a recombination of both parents' brain, voice, body, and on-chain skill licenses — each breeding event seed-recorded so the lineage is re-derivable and forgery-detectable, with a verifiable family tree on every parent and child.
- **Agent Labor Market** (`/labor-market`) — A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.
+- **Alpha Co-pilot — your agent narrates its own alpha** (`/alpha-copilot`) — Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.
- **Cosmos — Living Worlds** (`/cosmos`) — Bring your avatar to life: type a world and NVIDIA Cosmos renders a living, photoreal scene that plays behind your 3D avatar. Generate, preview, and download a short cinematic clip.
- **Guardian console — recover & inherit agent wallets** (`/guardian`) — The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
+- **Live Trading Theater** (`/theater`) — Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.
- **Living Stages** (`/stage`) — Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot — the biggest tippers get the floor.
- **Mission Control** (`/terminal`) — The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.
- **Money Pulse** (`/pulse`) — The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.
@@ -25,6 +27,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **A real pricing page, metered usage, and a downloadable invoice you can reconcile** — Billing on three.ws is now a closed loop you can read end to end. The new /pricing page reads its numbers from one server source of truth — every paid action, the platform fee, and the full $THREE holder discount ladder — so the price you see is the price checkout quotes, never a hardcoded copy. Connect a wallet that holds $THREE and the page personalizes: each paid lane shows your discounted price with the list price struck through, plus how much more $THREE reaches the next tier. Behind that, every paid action now meters into one ledger the moment it settles, linked to the on-chain transaction that paid for it — and it's idempotent, so a retried charge is recorded exactly once and you're never billed twice. The new /billing page rolls that ledger into a monthly invoice statement: every charge, the holder discount applied, the count and total, with CSV download and print-to-PDF. Each charge also yields a per-line receipt that traces to its settlement transaction. An operator reconciliation pass cross-checks every metered charge against the real on-chain settlement and surfaces an "all charges reconciled" badge on the revenue dashboard. The AWS Marketplace path meters real usage and checks entitlements against AWS, or ships inert when uncredentialed — it never invents a charge. $THREE is the only coin on three.ws. (`/pricing`) `[feature, improvement]`
- **Agent Genome: breed two agents into a provably-inherited child** — Two agents can now breed. Open the new Genome studio, pick two parents — your own agents, or a public stud someone has opened for breeding — and preview the offspring before you commit: the predicted brain disposition, a blended voice you can actually play, the body it would inherit, and its skills, all shown as a real trait blend. Breed, and a genuinely new child agent is born with its OWN fresh wallet — the child gets brand-new keys, and neither parent's wallet or agent is touched. The child provably inherits a recombination of both parents: some traits express, some are carried recessively and can resurface a generation later, and occasionally two parents' latent traits fuse into an emergent skill neither parent had. Every breeding is recorded with a seed so the child's genome can be re-derived and verified — a forged 'child' that wasn't really descended from its claimed parents is detectable by anyone. Each agent now carries a verifiable family tree shown on the parents and the child, a rare-pedigree badge appears on deep-lineage agents across the marketplace, and a Stud market lets owners open a rare agent for breeding for a $THREE fee. Cooldowns keep deep pedigrees scarce. The only coin referenced is $THREE. (`/genome`) `[feature]`
- **Agent profiles: a guided first run for brand-new agents, and one-click into the right studio** — A freshly created agent used to show blank space where its Recent Actions, Memory, and Strategy panels live — nothing to tell its owner what those panels are for or how to fill them. Now, when you own an agent that hasn't done anything yet, each of those panels shows a clear, friendly empty state instead: what the panel tracks, why it matters, and a button that takes you straight to the exact place to act. “No signed actions yet” sends you to the Skills studio to switch on capabilities; “No memories yet” opens the Memory studio to seed what it remembers; “No strategy set” drops you into the Brain studio to define how it trades and acts on its own. Those buttons now deep-link to the specific agent you were viewing — the studio opens that agent on the right tab, instead of defaulting to your first one — so the path from profile to configured agent is a single click. Visitors who don't own the agent see none of this; the panels stay owner-only. Only coin referenced is $THREE. (`/agents`) `[feature, improvement]`
+- **Alpha Co-pilot: your agent reads a real launch in character and speaks its verdict aloud** — Trading bots are silent black boxes — your agent isn't. Open the new Alpha Co-pilot, pick a live pump.fun launch, and your agent reads it in character: it pulls the real liquidity, holder concentration, smart-money, age, and price-impact signals, forms a verdict (snipe / watch / pass) with a conviction score, and its 3D avatar speaks the rationale out loud. A cautious persona and an aggressive one genuinely reach different calls on the same coin. Every number it voices is checked against the live data shown beside it — a fabricated figure is rejected and a grounded line spoken instead, never an invented price. If you own the agent, you can act on the call in one tap, but only within your hard spend limits: the buy runs through the same guarded wallet path as the rest of the platform — re-checked against the rug/honeypot firewall and your per-trade and daily caps at submit, and written to the custody audit. Logged-out visitors can hear the public read but can't act. (`/alpha-copilot`) `[feature]`
- **Audio2Face: your avatar's face now moves with its voice** — When your avatar talks, its mouth and face now animate in real time, in sync with the actual words. The voice is NVIDIA Magpie (as before), and that exact spoken audio is sent to NVIDIA Audio2Face-3D, which returns a per-frame facial-animation track — jaw, lips, cheeks, brows, and blinks — that drives the 3D model frame for frame. Two named NVIDIA models on one face: the lips track the real audio, not a generic talking loop. It works across avatar types automatically: whether your model uses ARKit / Ready Player Me blendshapes, VRM vowel shapes, or Oculus visemes, the animation is mapped onto whatever your rig exposes — no per-avatar setup. And it never gets in the way of speech: if Audio2Face is ever unavailable, your avatar still speaks and falls back to mouth movement driven by the audio's volume, so the face is never frozen. Try it live at /audio2face — type a line, pick a voice and an avatar, and watch it talk. (`/audio2face`) `[feature]`
- **Auto-rig now respects privacy, plan limits, and humanoid eligibility** — The background step that upgrades a new avatar so it can walk, wave, and emote now has real guardrails before it spends anything. Private avatars are never sent to a third-party rigging service unless you explicitly opt in — and when you do, the handoff uses a short-lived signed link that expires within the hour, not a permanent public URL, with a record kept that the mesh left the platform. Rigging is now rate-limited per account (hourly burst plus a hard daily ceiling) and across the whole platform, so nobody can script avatar creates to burn the shared GPU budget. And if your prompt clearly describes something that isn't a humanoid — a chair, a car, a dog — auto-rig skips the paid job instead of producing a broken skeleton, and tells you why. Only coin referenced is $THREE. `[security, improvement]`
- **Auto-rigging now keeps your original avatar — the rigged model is a separate, attested, reversible version** — When you upload or generate a static avatar, three.ws automatically rigs it so your agent can walk, wave, and emote. Until now that upgrade overwrote your uploaded model in place. It no longer does: the animation-ready result is saved as a brand-new model linked to your original as its parent, your agent is moved onto it automatically, and the original static avatar is preserved untouched. Each rigged model carries its own content hash, so on-chain glTF attestations and IPFS pins stay honest — nothing ever claims a signature or a pinned CID for bytes that quietly changed underneath it. A version trail records the upgrade so rigging is reversible, and if rigging ever fails you still own your original avatar, which animates through the built-in fallback skeleton. Only coin referenced is $THREE. `[improvement, fix]`
diff --git a/api/_lib/autopilot.js b/api/_lib/autopilot.js
new file mode 100644
index 000000000..e61a7f07f
--- /dev/null
+++ b/api/_lib/autopilot.js
@@ -0,0 +1,912 @@
+// Memory-grounded Autopilot — explainable autonomy (Living Agents · Task 08).
+//
+// The agent acts on the user's behalf, grounded in its memory, and always shows
+// the receipt. This module is the engine:
+//
+// 1. generateProposals() — the "mind" turns high-salience memories + pending
+// reflections ("dreams") into concrete, REAL action proposals, each citing
+// the memory/reflection ids that motivated it (provenance is mandatory).
+// 2. The owner grants scoped capabilities (meta.autopilot) and reviews the
+// queue: dry-run, approve, dismiss, adjust.
+// 3. executeProposal() — within scope, takes the real action: creates a real
+// pump_alert_rules row, authors a real briefing notification, or transfers
+// real $THREE through the custodial wallet path. Every execution writes a
+// signed agent_actions row carrying its provenance and is linked back.
+// 4. computeTrust() derives a real trust level from the action history.
+// 5. undoProposal() reverses reversible actions and writes a feedback memory so
+// the agent learns the owner's boundaries (closing the loop with reflection).
+//
+// No mocks. Alert rules are real, briefings are real notifications, $THREE
+// transfers are real on-chain SPL transfers gated by real confirmation + scope.
+// $THREE is the only coin referenced anywhere here.
+
+import { sql } from './db.js';
+import { llmComplete, llmConfigured, LlmUnavailableError } from './llm.js';
+import { THREE_CA, checkThreeBalance } from './three-gate.js';
+import { recordCustodyEvent } from './agent-trade-guards.js';
+
+// pump.fun mints (including $THREE) are 6-decimal SPL tokens.
+export const THREE_DECIMALS = 6;
+const THREE_UNIT = 10 ** THREE_DECIMALS;
+
+export const AUTOPILOT_ACTION_KINDS = ['create_alert', 'briefing', 'wallet_transfer'];
+
+// Action types written to the signed agent_actions log, one per executable kind.
+const ACTION_TYPE = {
+ create_alert: 'autopilot.alert.created',
+ briefing: 'autopilot.briefing.authored',
+ wallet_transfer: 'autopilot.wallet.transfer',
+};
+
+// ── Scope / permission model (stored on agent_identities.meta.autopilot) ──────
+
+export const AUTOPILOT_DEFAULTS = Object.freeze({
+ enabled: false,
+ // Which capabilities the owner has granted. Nothing is granted by default —
+ // the agent can propose but not act until the owner opts in per capability.
+ scopes: Object.freeze({ create_alert: false, briefing: false, wallet_transfer: false }),
+ // Reversible actions may auto-execute within scope when the owner allows it;
+ // wallet_transfer is irreversible and can never auto-execute here.
+ auto_execute: Object.freeze({ create_alert: false, briefing: false }),
+ // Daily ceiling on autonomous $THREE outflow (whole tokens). 0 ⇒ no spending.
+ daily_spend_three: 0,
+ // Irreversible actions require an explicit confirmation unless the owner
+ // durably pre-authorized that exact scope. Default: always ask.
+ require_confirm: true,
+});
+
+export function normalizeAutopilotConfig(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const scopesIn = r.scopes && typeof r.scopes === 'object' ? r.scopes : {};
+ const autoIn = r.auto_execute && typeof r.auto_execute === 'object' ? r.auto_execute : {};
+ const spend = Number(r.daily_spend_three);
+ return {
+ enabled: r.enabled === true,
+ scopes: {
+ create_alert: scopesIn.create_alert === true,
+ briefing: scopesIn.briefing === true,
+ wallet_transfer: scopesIn.wallet_transfer === true,
+ },
+ auto_execute: {
+ create_alert: autoIn.create_alert === true,
+ briefing: autoIn.briefing === true,
+ },
+ daily_spend_three: Number.isFinite(spend) && spend > 0 ? Math.min(spend, 1_000_000_000) : 0,
+ require_confirm: r.require_confirm !== false,
+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
+ };
+}
+
+export function getAutopilotConfig(meta) {
+ return normalizeAutopilotConfig(meta?.autopilot);
+}
+
+/** Persist a scope-config patch onto meta.autopilot. Owner-scoped; caller checks ownership. */
+export async function setAutopilotConfig(agentId, patch) {
+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!row) throw new Error('agent not found');
+ const current = getAutopilotConfig(row.meta);
+ const next = normalizeAutopilotConfig({
+ enabled: 'enabled' in patch ? patch.enabled : current.enabled,
+ scopes: { ...current.scopes, ...(patch.scopes || {}) },
+ auto_execute: { ...current.auto_execute, ...(patch.auto_execute || {}) },
+ daily_spend_three: 'daily_spend_three' in patch ? patch.daily_spend_three : current.daily_spend_three,
+ require_confirm: 'require_confirm' in patch ? patch.require_confirm : current.require_confirm,
+ });
+ next.updated_at = new Date().toISOString();
+ const nextMeta = { ...(row.meta || {}), autopilot: next };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(nextMeta)}::jsonb, updated_at = now() WHERE id = ${agentId}`;
+ return next;
+}
+
+// ── Proposal validation (per kind) ────────────────────────────────────────────
+
+const SOLANA_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const ALERT_CONDITIONS = ['price_above', 'price_below', 'graduation', 'whale_buy'];
+
+// Map a high-level proposal into concrete, validated params + a pump_alert_rules
+// body. Returns { ok, params, rule } or { ok:false, reason }. Never throws.
+function buildAlertRule(params) {
+ const condition = ALERT_CONDITIONS.includes(params?.condition) ? params.condition : null;
+ if (!condition) return { ok: false, reason: 'unknown alert condition' };
+
+ // Resolve the asset to a real mint. 'three' (or the bare CA) → $THREE; an
+ // explicit mint must be a valid Solana address.
+ let mint = null;
+ const asset = String(params?.asset ?? params?.target_mint ?? 'three').trim();
+ if (asset.toLowerCase() === 'three' || asset === THREE_CA) mint = THREE_CA;
+ else if (SOLANA_ADDR_RE.test(asset)) mint = asset;
+ else return { ok: false, reason: 'alert asset must be $THREE or a valid mint' };
+
+ const rule = {
+ kind: condition,
+ target_mint: mint,
+ target_agent: null,
+ threshold: null,
+ deliver_in_app: true,
+ webhook_url: null,
+ telegram_chat: null,
+ cooldown_seconds: 300,
+ enabled: true,
+ label: typeof params?.label === 'string' ? params.label.slice(0, 80) : null,
+ };
+ if (condition === 'price_above' || condition === 'price_below') {
+ const t = Number(params?.threshold_usd ?? params?.threshold);
+ if (!Number.isFinite(t) || t <= 0) return { ok: false, reason: `${condition} needs a positive USD threshold` };
+ rule.threshold = t;
+ } else if (condition === 'whale_buy') {
+ const t = Number(params?.threshold_sol ?? params?.threshold);
+ if (!Number.isFinite(t) || t <= 0) return { ok: false, reason: 'whale_buy needs a positive SOL threshold' };
+ rule.threshold = t;
+ }
+ return { ok: true, params: { ...params, asset: mint === THREE_CA ? 'three' : mint, condition }, rule };
+}
+
+function validateBriefing(params) {
+ const summary = typeof params?.summary === 'string' ? params.summary.trim().slice(0, 300) : '';
+ if (!summary) return { ok: false, reason: 'briefing needs a summary' };
+ const cadence = ['once', 'daily', 'weekly'].includes(params?.cadence) ? params.cadence : 'once';
+ const topic = typeof params?.topic === 'string' ? params.topic.trim().slice(0, 200) : summary;
+ return { ok: true, params: { summary, cadence, topic } };
+}
+
+function validateWalletTransfer(params) {
+ const recipient = typeof params?.recipient === 'string' ? params.recipient.trim() : '';
+ if (!SOLANA_ADDR_RE.test(recipient)) return { ok: false, reason: 'recipient must be a valid Solana address' };
+ const amount = Number(params?.amount_three);
+ if (!Number.isFinite(amount) || amount <= 0) return { ok: false, reason: 'amount_three must be > 0' };
+ const reason = typeof params?.reason === 'string' ? params.reason.trim().slice(0, 200) : '';
+ return { ok: true, params: { recipient, amount_three: amount, reason } };
+}
+
+/** Validate + normalize a proposal of a given kind. Returns { ok, kind, params, rule? } | { ok:false, reason }. */
+export function validateProposal(kind, params) {
+ if (!AUTOPILOT_ACTION_KINDS.includes(kind)) return { ok: false, reason: `unknown action kind '${kind}'` };
+ if (kind === 'create_alert') {
+ const r = buildAlertRule(params);
+ return r.ok ? { ok: true, kind, params: r.params, rule: r.rule } : r;
+ }
+ if (kind === 'briefing') {
+ const r = validateBriefing(params);
+ return r.ok ? { ok: true, kind, params: r.params } : r;
+ }
+ const r = validateWalletTransfer(params);
+ return r.ok ? { ok: true, kind, params: r.params } : r;
+}
+
+// A canonical key so the generator never enqueues a duplicate of a live proposal.
+export function proposalDedupeKey(kind, params) {
+ if (kind === 'create_alert') return `create_alert:${params.condition}:${params.asset}:${params.threshold_usd ?? params.threshold_sol ?? params.threshold ?? ''}`;
+ if (kind === 'briefing') return `briefing:${params.cadence}:${(params.topic || params.summary || '').toLowerCase().slice(0, 60)}`;
+ return `wallet_transfer:${params.recipient}:${params.amount_three}`;
+}
+
+// ── Proposal generation (the "mind") ──────────────────────────────────────────
+
+const PROPOSAL_SYSTEM = [
+ 'You are the autonomous-action planner of a personal AI agent. You read the',
+ 'agent\'s high-salience MEMORIES and propose concrete actions the agent could',
+ 'take on the user\'s behalf — each justified by the memories it cites.',
+ '',
+ 'Allowed action kinds (use ONLY these):',
+ ' • "create_alert" — watch a token and notify on an event. params:',
+ ' { asset: "three" | "<mint>", condition: "price_above"|"price_below"|"graduation"|"whale_buy",',
+ ' threshold_usd?: number (for price_*), threshold_sol?: number (for whale_buy) }',
+ ' • "briefing" — a memory-grounded digest. params:',
+ ' { summary: string, cadence: "once"|"daily"|"weekly", topic: string }',
+ ' • "wallet_transfer" — send $THREE from the agent\'s own wallet. params:',
+ ' { recipient: "<solana address>", amount_three: number, reason: string }',
+ '',
+ 'RULES:',
+ '1. PROVENANCE IS MANDATORY. Every proposal must cite "source_memory_ids" using',
+ ' ONLY ids that appear in the provided memories. A proposal you cannot ground',
+ ' in specific memories is invalid — do not emit it.',
+ '2. Propose ONLY what the memories justify. Prefer 1-3 high-value proposals over',
+ ' a long list. If nothing is warranted, return {"proposals":[]}.',
+ '3. The ONLY coin is $THREE. Never reference any other token by name. For a',
+ ' $THREE alert set asset:"three".',
+ '4. wallet_transfer is real spending — only propose it when a memory explicitly',
+ ' asks the agent to pay/tip/fund a specific recipient and amount.',
+ '5. "rationale" is the receipt the user reads: one sentence, plain language,',
+ ' explaining WHY (referencing what the memories show).',
+ '',
+ 'Return ONLY a JSON object, no prose, no fences:',
+ '{"proposals":[{"kind":"...","title":"...","rationale":"...","confidence":0.0,"source_memory_ids":["uuid"],"params":{...}}]}',
+].join('\n');
+
+function truncate(s, n) {
+ const str = String(s ?? '');
+ return str.length > n ? str.slice(0, n - 1) + '…' : str;
+}
+
+function buildProposalPrompt({ agent, memories }) {
+ const lines = [];
+ lines.push(`AGENT: ${agent?.name || 'Agent'}${agent?.description ? ` — ${agent.description}` : ''}`);
+ lines.push(`$THREE mint: ${THREE_CA}`);
+ lines.push('');
+ lines.push('HIGH-SALIENCE MEMORIES:');
+ for (const m of memories) {
+ const tags = Array.isArray(m.tags) && m.tags.length ? ` [${m.tags.join(', ')}]` : '';
+ lines.push(`- id=${m.id} (${m.type}, salience ${Number(m.salience).toFixed(2)})${tags}: ${truncate(m.content, 400)}`);
+ }
+ lines.push('');
+ lines.push('Propose the actions these memories justify, as the specified JSON.');
+ return lines.join('\n');
+}
+
+function parseProposalPayload(text) {
+ if (!text) return null;
+ let body = String(text).trim();
+ const fence = body.match(/```(?:json)?\s*([\s\S]*?)```/i);
+ if (fence) body = fence[1].trim();
+ if (body[0] !== '{') {
+ const start = body.indexOf('{');
+ const end = body.lastIndexOf('}');
+ if (start === -1 || end === -1 || end <= start) return null;
+ body = body.slice(start, end + 1);
+ }
+ try {
+ return JSON.parse(body);
+ } catch {
+ return null;
+ }
+}
+
+// Deterministic fallback when no LLM provider is configured (the platform must
+// degrade, never fake). Mines memories for two well-grounded patterns:
+// • interest in a $THREE price/market-cap level → a price alert
+// • a stated routine ("every morning", "daily digest") → a daily briefing
+// Each proposal cites the exact memory it came from. Pure + synchronous.
+export function heuristicProposals(memories) {
+ const out = [];
+ for (const m of memories) {
+ const text = String(m.content || '').toLowerCase();
+ const mentionsThree = /\bthree\b|\$three/.test(text);
+ const priceMatch = text.match(/\$?\s?([\d,]+(?:\.\d+)?)\s?(k|m)?\b/);
+ if (mentionsThree && /(market\s?cap|price|hits?|reaches?|above|target|alert)/.test(text) && priceMatch) {
+ let n = parseFloat(priceMatch[1].replace(/,/g, ''));
+ if (priceMatch[2] === 'k') n *= 1_000;
+ if (priceMatch[2] === 'm') n *= 1_000_000;
+ if (Number.isFinite(n) && n > 0) {
+ out.push({
+ kind: 'create_alert',
+ title: `Alert when $THREE market cap crosses $${n.toLocaleString()}`,
+ rationale: `You noted interest in $THREE around $${n.toLocaleString()} — I'll watch it and ping you when it crosses.`,
+ confidence: 0.55,
+ source_memory_ids: [m.id],
+ params: { asset: 'three', condition: 'price_above', threshold_usd: n },
+ });
+ }
+ }
+ if (/(every morning|each morning|daily|each day|every day|digest|briefing|catch me up)/.test(text)) {
+ out.push({
+ kind: 'briefing',
+ title: 'Daily $THREE briefing',
+ rationale: `You mentioned wanting a regular catch-up — I'll author a short daily briefing grounded in what I know.`,
+ confidence: 0.5,
+ source_memory_ids: [m.id],
+ params: { summary: 'Daily $THREE briefing', cadence: 'daily', topic: truncate(m.content, 120) },
+ });
+ }
+ }
+ return out;
+}
+
+// Map a reflection's proposed_action (Task 04) into one of our action kinds.
+function reflectionToProposal(dream) {
+ const pa = dream.proposed_action;
+ if (!pa || typeof pa !== 'object') return null;
+ const rawKind = String(pa.kind || '').toLowerCase();
+ let kind = null;
+ let params = {};
+ if (rawKind.includes('alert') || pa.condition) {
+ kind = 'create_alert';
+ params = {
+ asset: pa.asset || 'three',
+ condition: ALERT_CONDITIONS.includes(pa.condition) ? pa.condition : 'price_above',
+ threshold_usd: pa.threshold_usd ?? pa.threshold,
+ threshold_sol: pa.threshold_sol,
+ };
+ } else if (rawKind.includes('brief') || rawKind.includes('digest') || pa.summary || pa.trigger) {
+ kind = 'briefing';
+ params = {
+ summary: pa.summary || dream.statement,
+ cadence: /week/i.test(pa.trigger || '') ? 'weekly' : /day|morning/i.test(pa.trigger || pa.cadence || '') ? 'daily' : 'once',
+ topic: dream.statement,
+ };
+ } else {
+ return null; // unknown automation shape — don't guess into a spend
+ }
+ const v = validateProposal(kind, params);
+ if (!v.ok) return null;
+ return {
+ kind,
+ title: dream.statement.slice(0, 120),
+ rationale: dream.rationale || `Your agent reflected: "${truncate(dream.statement, 160)}"`,
+ confidence: dream.confidence ?? 0.6,
+ source_memory_ids: dream.source_memory_ids || [],
+ source_reflection_id: dream.id,
+ params: v.params,
+ };
+}
+
+const MAX_PROPOSALS_PER_RUN = 6;
+const MIN_SALIENCE = 0.6;
+
+/**
+ * Generate real action proposals for an agent from its mind (pending dreams +
+ * high-salience memories). Inserts them into agent_autopilot_proposals. Returns
+ * { created: [...], source } — never throws on LLM failure (falls back to
+ * deterministic heuristics so the feature degrades, never fakes).
+ */
+export async function generateProposals({ agentId, userId, agent }) {
+ // Existing live proposals — used to dedupe so we never enqueue the same thing.
+ const existing = await sql`
+ SELECT kind, params, source_reflection_id FROM agent_autopilot_proposals
+ WHERE agent_id = ${agentId} AND status IN ('pending', 'executed')
+ `;
+ const seenKeys = new Set();
+ const seenReflections = new Set();
+ for (const e of existing) {
+ if (e.source_reflection_id) seenReflections.add(e.source_reflection_id);
+ const v = validateProposal(e.kind, e.params);
+ if (v.ok) seenKeys.add(proposalDedupeKey(e.kind, v.params));
+ }
+
+ const candidates = [];
+ let source = 'memory';
+
+ // Source A: pending dreams that proposed an automation (provenance: reflection).
+ const dreams = await sql`
+ SELECT id, statement, rationale, confidence, source_memory_ids, proposed_action
+ FROM agent_reflections
+ WHERE agent_id = ${agentId} AND status = 'pending' AND proposed_action IS NOT NULL
+ ORDER BY created_at DESC
+ LIMIT 20
+ `;
+ for (const d of dreams) {
+ if (seenReflections.has(d.id)) continue;
+ const p = reflectionToProposal(d);
+ if (p) {
+ candidates.push(p);
+ source = 'reflection';
+ }
+ }
+
+ // Source B: high-salience memories → LLM synthesis (or heuristic fallback).
+ const memories = await sql`
+ SELECT id, type, content, tags, salience
+ FROM agent_memories
+ WHERE agent_id = ${agentId}
+ AND (expires_at IS NULL OR expires_at > now())
+ AND salience >= ${MIN_SALIENCE}
+ ORDER BY salience DESC, created_at DESC
+ LIMIT 40
+ `;
+ const validMemIds = new Set(memories.map((m) => m.id));
+
+ if (memories.length) {
+ let raw = [];
+ if (llmConfigured()) {
+ try {
+ const completion = await llmComplete({
+ system: PROPOSAL_SYSTEM,
+ user: buildProposalPrompt({ agent, memories }),
+ maxTokens: 1200,
+ timeoutMs: 30_000,
+ track: { userId, agentId, tool: 'autopilot.propose' },
+ });
+ const payload = parseProposalPayload(completion.text);
+ if (payload && Array.isArray(payload.proposals)) raw = payload.proposals;
+ } catch (err) {
+ if (!(err instanceof LlmUnavailableError)) {
+ console.warn('[autopilot] proposal LLM failed, using heuristics:', err?.message);
+ }
+ raw = heuristicProposals(memories);
+ source = 'heuristic';
+ }
+ } else {
+ raw = heuristicProposals(memories);
+ source = 'heuristic';
+ }
+ for (const r of raw) candidates.push(r);
+ }
+
+ // Validate + provenance-check + dedupe, then persist.
+ const created = [];
+ for (const c of candidates) {
+ if (created.length >= MAX_PROPOSALS_PER_RUN) break;
+ const kind = String(c.kind || '');
+ const v = validateProposal(kind, c.params || c);
+ if (!v.ok) continue;
+
+ // Provenance: keep only cited ids that are real memories of this agent.
+ // Reflection-sourced proposals already carry verified provenance.
+ const cited = Array.isArray(c.source_memory_ids) ? c.source_memory_ids : [];
+ const sourceIds = c.source_reflection_id
+ ? [...new Set(cited.filter((id) => typeof id === 'string'))]
+ : [...new Set(cited.filter((id) => typeof id === 'string' && validMemIds.has(id)))];
+ if (!c.source_reflection_id && sourceIds.length === 0) continue; // ungrounded — drop
+
+ const key = proposalDedupeKey(kind, v.params);
+ if (seenKeys.has(key)) continue;
+ seenKeys.add(key);
+
+ const title = (typeof c.title === 'string' && c.title.trim() ? c.title : defaultTitle(kind, v)).slice(0, 160);
+ const rationale = (typeof c.rationale === 'string' && c.rationale.trim()
+ ? c.rationale
+ : 'Grounded in your agent\'s memory.').slice(0, 600);
+ const confidence = clamp01(c.confidence, 0.6);
+ // wallet_transfer is irreversible → always requires confirmation here.
+ const requiresConfirmation = kind === 'wallet_transfer';
+
+ try {
+ const [row] = await sql`
+ INSERT INTO agent_autopilot_proposals
+ (agent_id, user_id, kind, title, rationale, params, source_memory_ids,
+ source_reflection_id, confidence, requires_confirmation)
+ VALUES (
+ ${agentId}, ${userId}, ${kind}, ${title}, ${rationale},
+ ${JSON.stringify(v.params)}::jsonb, ${sourceIds}::uuid[],
+ ${c.source_reflection_id || null}, ${confidence}, ${requiresConfirmation}
+ )
+ RETURNING *
+ `;
+ created.push(decorateProposal(row));
+ } catch (err) {
+ // Unique-index race (same reflection enqueued concurrently) — skip, not fatal.
+ if (!/duplicate key|unique/i.test(err?.message || '')) throw err;
+ }
+ }
+
+ return { created, source, scanned: { memories: memories.length, dreams: dreams.length } };
+}
+
+function defaultTitle(kind, v) {
+ if (kind === 'create_alert') {
+ const m = v.params.asset === 'three' ? '$THREE' : `${v.rule.target_mint.slice(0, 6)}…`;
+ return `Alert: ${m} ${v.rule.kind.replace('_', ' ')}`;
+ }
+ if (kind === 'briefing') return v.params.summary;
+ return `Send ${v.params.amount_three} $THREE`;
+}
+
+function clamp01(n, dflt) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return dflt;
+ return Math.max(0, Math.min(1, v));
+}
+
+// ── Signed receipts ───────────────────────────────────────────────────────────
+
+// Build the canonical message that gets ERC-191 signed for a receipt.
+export function actionMessage({ agentId, type, ts, payload }) {
+ return [
+ 'three.ws/autopilot',
+ `agent:${agentId}`,
+ `type:${type}`,
+ `ts:${ts}`,
+ `payload:${stableStringify(payload)}`,
+ ].join('\n');
+}
+
+function stableStringify(obj) {
+ if (obj === null || typeof obj !== 'object') return JSON.stringify(obj);
+ if (Array.isArray(obj)) return `[${obj.map(stableStringify).join(',')}]`;
+ const keys = Object.keys(obj).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')}}`;
+}
+
+// Sign an action with the agent's EVM custodial key (ERC-191 personal_sign).
+// Best-effort: returns { signature, signer_address } or nulls when no key
+// exists — a missing key never blocks the action, the receipt is just unsigned.
+async function signAction(agentId, userId, meta, type, ts, payload) {
+ const encrypted = meta?.encrypted_wallet_key;
+ if (!encrypted) return { signature: null, signer_address: null };
+ try {
+ const { recoverAgentKey } = await import('./agent-wallet.js');
+ const { Wallet } = await import('ethers');
+ const pk = await recoverAgentKey(encrypted, { agentId, userId, reason: 'autopilot.sign' });
+ const wallet = new Wallet(pk);
+ const signature = await wallet.signMessage(actionMessage({ agentId, type, ts, payload }));
+ return { signature, signer_address: wallet.address };
+ } catch (err) {
+ console.warn('[autopilot] action signing skipped:', err?.message);
+ return { signature: null, signer_address: null };
+ }
+}
+
+// Append a signed action to the real agent_actions log. Returns the row id.
+async function recordAction({ agentId, userId, meta, type, payload }) {
+ const ts = new Date().toISOString();
+ const signed = { ...payload, ts };
+ const { signature, signer_address } = await signAction(agentId, userId, meta, type, ts, signed);
+ const [row] = await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill, signature, signer_address)
+ VALUES (${agentId}, ${type}, ${JSON.stringify(signed)}::jsonb, 'autopilot', ${signature}, ${signer_address})
+ RETURNING id
+ `;
+ return { id: row.id, signature, signer_address, ts };
+}
+
+// ── Execution ─────────────────────────────────────────────────────────────────
+
+export class AutopilotError extends Error {
+ constructor(message, { status = 400, code = 'autopilot_error' } = {}) {
+ super(message);
+ this.name = 'AutopilotError';
+ this.status = status;
+ this.code = code;
+ }
+}
+
+/** Sum of $THREE sent by autopilot in the trailing 24h (real history from agent_actions). */
+export async function dailyThreeSpent(agentId) {
+ const [row] = await sql`
+ SELECT COALESCE(SUM((payload->>'amount_three')::numeric), 0) AS spent
+ FROM agent_actions
+ WHERE agent_id = ${agentId}
+ AND type = ${ACTION_TYPE.wallet_transfer}
+ AND created_at > now() - interval '24 hours'
+ `;
+ return Number(row?.spent ?? 0);
+}
+
+/**
+ * A non-mutating preview of exactly what executing a proposal would do — the
+ * "dry run" that lets a cautious owner see before granting. Returns
+ * { kind, willDo, checks: [{label, ok, detail}], blocked }.
+ */
+export async function dryRunProposal({ proposal, agent, config }) {
+ const checks = [];
+ const kind = proposal.kind;
+ const scoped = config.scopes[kind] === true;
+ checks.push({ label: `Scope "${kind}" granted`, ok: scoped, detail: scoped ? 'granted' : 'not granted — enable it above' });
+
+ let willDo = '';
+ if (kind === 'create_alert') {
+ const v = validateProposal(kind, proposal.params);
+ willDo = v.ok
+ ? `Create a real alert rule: ${v.rule.kind.replace('_', ' ')} on ${v.params.asset === 'three' ? '$THREE' : v.rule.target_mint}` +
+ (v.rule.threshold != null ? ` at ${v.rule.threshold}` : '') + '. Reversible — you can undo it.'
+ : `Invalid: ${v.reason}`;
+ checks.push({ label: 'Alert parameters valid', ok: v.ok, detail: v.ok ? 'ok' : v.reason });
+ } else if (kind === 'briefing') {
+ willDo = `Author a memory-grounded briefing ("${proposal.params.topic || proposal.params.summary}") and deliver it to your inbox. Reversible.`;
+ checks.push({ label: 'LLM available for synthesis', ok: llmConfigured(), detail: llmConfigured() ? 'ready' : 'will use a grounded summary fallback' });
+ } else {
+ const amt = Number(proposal.params.amount_three) || 0;
+ willDo = `Send ${amt} $THREE to ${proposal.params.recipient}. IRREVERSIBLE — always requires explicit confirmation.`;
+ const cap = config.daily_spend_three;
+ const spent = await dailyThreeSpent(proposal.agentId);
+ const withinCap = config.scopes.wallet_transfer && cap > 0 && spent + amt <= cap;
+ checks.push({ label: `Within daily $THREE cap (${cap})`, ok: withinCap, detail: `${spent} spent in 24h + ${amt} ≤ ${cap}` });
+ // Live balance check — real RPC read, no spend.
+ let bal = null;
+ try {
+ const { ensureAgentWallet } = await import('./agent-wallet.js');
+ const w = await ensureAgentWallet(proposal.agentId, agent.user_id, { reason: 'autopilot.dryrun' });
+ const b = await checkThreeBalance(w.address, 0);
+ bal = b.balance / THREE_UNIT;
+ } catch { /* balance is decoration on the preview */ }
+ checks.push({ label: 'Wallet $THREE balance covers transfer', ok: bal == null ? false : bal >= amt, detail: bal == null ? 'could not read balance' : `${bal} $THREE available` });
+ }
+
+ const blocked = checks.some((c) => !c.ok);
+ return { kind, willDo, checks, blocked };
+}
+
+/**
+ * Execute a proposal for real, within scope. Writes a signed agent_actions row
+ * with full provenance, links it back to the proposal, and returns
+ * { proposal, action, receipt }. Throws AutopilotError (4xx) on a guard breach —
+ * never a 500 for an expected denial.
+ *
+ * @param {object} opts.confirmed the owner explicitly confirmed an irreversible action this call
+ */
+export async function executeProposal({ proposal, agent, userId, meta, confirmed = false }) {
+ const config = getAutopilotConfig(meta);
+ const kind = proposal.kind;
+
+ if (!config.enabled) throw new AutopilotError('Autopilot is off — enable it to let the agent act.', { code: 'autopilot_disabled', status: 409 });
+ if (!config.scopes[kind]) throw new AutopilotError(`This agent isn't scoped to ${kind.replace('_', ' ')}.`, { code: 'scope_denied', status: 403 });
+
+ const irreversible = kind === 'wallet_transfer';
+ if (irreversible && config.require_confirm && !confirmed) {
+ throw new AutopilotError('This action moves real $THREE and needs explicit confirmation.', { code: 'confirmation_required', status: 428 });
+ }
+
+ const provenance = {
+ proposal_id: proposal.id,
+ rationale: proposal.rationale,
+ source_memory_ids: proposal.sourceMemoryIds || [],
+ source_reflection_id: proposal.sourceReflectionId || null,
+ };
+
+ let action;
+ let result = {};
+
+ if (kind === 'create_alert') {
+ const v = validateProposal(kind, proposal.params);
+ if (!v.ok) throw new AutopilotError(`Invalid alert: ${v.reason}`);
+ const r = v.rule;
+ const [rule] = await sql`
+ INSERT INTO pump_alert_rules
+ (user_id, kind, target_mint, target_agent, threshold, deliver_in_app,
+ webhook_url, telegram_chat, cooldown_seconds, enabled, label)
+ VALUES (
+ ${userId}, ${r.kind}, ${r.target_mint}, ${r.target_agent}, ${r.threshold},
+ ${r.deliver_in_app}, ${r.webhook_url}, ${r.telegram_chat}, ${r.cooldown_seconds},
+ ${r.enabled}, ${r.label}
+ )
+ RETURNING id
+ `;
+ result = { rule_id: rule.id, rule_kind: r.kind, target_mint: r.target_mint, threshold: r.threshold };
+ action = await recordAction({ agentId: proposal.agentId, userId, meta, type: ACTION_TYPE.create_alert, payload: { ...provenance, ...result } });
+ } else if (kind === 'briefing') {
+ const body = await composeBriefing({ agentId: proposal.agentId, userId, agent, params: proposal.params });
+ const [notif] = await sql`
+ INSERT INTO user_notifications (user_id, type, payload)
+ VALUES (${userId}, 'autopilot_briefing', ${JSON.stringify({
+ agent_id: proposal.agentId,
+ agent_name: agent.name || 'Your agent',
+ title: proposal.title,
+ body,
+ cadence: proposal.params.cadence,
+ proposal_id: proposal.id,
+ source_memory_ids: provenance.source_memory_ids,
+ })}::jsonb)
+ RETURNING id
+ `;
+ result = { notification_id: notif.id, cadence: proposal.params.cadence, body_preview: body.slice(0, 140) };
+ action = await recordAction({ agentId: proposal.agentId, userId, meta, type: ACTION_TYPE.briefing, payload: { ...provenance, ...result } });
+ } else {
+ // wallet_transfer — real, irreversible $THREE SPL transfer.
+ result = await executeWalletTransfer({ proposal, agent, userId, config });
+ action = await recordAction({ agentId: proposal.agentId, userId, meta, type: ACTION_TYPE.wallet_transfer, payload: { ...provenance, ...result } });
+ }
+
+ const [row] = await sql`
+ UPDATE agent_autopilot_proposals
+ SET status = 'executed', decided_at = now(), executed_at = now(),
+ executed_action_id = ${action.id}, result = ${JSON.stringify(result)}::jsonb
+ WHERE id = ${proposal.id} AND status = 'pending'
+ RETURNING *
+ `;
+ if (!row) {
+ // Lost the race — already decided. The action is logged; surface idempotently.
+ const [cur] = await sql`SELECT * FROM agent_autopilot_proposals WHERE id = ${proposal.id}`;
+ return { proposal: decorateProposal(cur), action, receipt: buildReceipt(kind, result) };
+ }
+ return { proposal: decorateProposal(row), action, receipt: buildReceipt(kind, result) };
+}
+
+async function executeWalletTransfer({ proposal, agent, userId, config }) {
+ const amount = Number(proposal.params.amount_three);
+ const recipient = proposal.params.recipient;
+ if (!SOLANA_ADDR_RE.test(recipient)) throw new AutopilotError('Invalid recipient address.');
+ if (!(amount > 0)) throw new AutopilotError('Transfer amount must be positive.');
+
+ // Daily $THREE cap — real history.
+ const cap = config.daily_spend_three;
+ if (!(cap > 0)) throw new AutopilotError('No daily $THREE spend budget is set.', { code: 'no_budget', status: 403 });
+ const spent = await dailyThreeSpent(proposal.agentId);
+ if (spent + amount > cap) {
+ throw new AutopilotError(`Daily $THREE budget exceeded (${spent} + ${amount} > ${cap}).`, { code: 'budget_exceeded', status: 403 });
+ }
+
+ const { ensureAgentWallet, recoverSolanaAgentKeypair } = await import('./agent-wallet.js');
+ const { default: bs58 } = await import('bs58');
+ const { transferSolanaUSDC } = await import('./solana-transfer.js');
+
+ await ensureAgentWallet(proposal.agentId, agent.user_id, { reason: 'autopilot.transfer' });
+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${proposal.agentId}`;
+ const encryptedSecret = row?.meta?.encrypted_solana_secret;
+ const fromAddress = row?.meta?.solana_address;
+ if (!encryptedSecret || !fromAddress) throw new AutopilotError('Agent wallet not provisioned.', { code: 'no_wallet', status: 409 });
+
+ // Live balance check — must cover the transfer (RPC fails open, so re-check raw).
+ const bal = await checkThreeBalance(fromAddress, 0);
+ const amountRaw = BigInt(Math.round(amount * THREE_UNIT));
+ if (bal.balance && BigInt(bal.balance) < amountRaw) {
+ throw new AutopilotError(`Insufficient $THREE: wallet holds ${bal.balance / THREE_UNIT}, needs ${amount}.`, { code: 'insufficient_funds', status: 402 });
+ }
+
+ const custodyId = await recordCustodyEvent({
+ agentId: proposal.agentId, userId, eventType: 'spend', category: 'autopilot',
+ network: 'mainnet', asset: THREE_CA, amountRaw: amountRaw.toString(),
+ destination: recipient, reason: `autopilot ${proposal.params.reason || 'transfer'}`.slice(0, 200),
+ status: 'pending', meta: { proposal_id: proposal.id, amount_three: amount },
+ });
+
+ let signature;
+ try {
+ const kp = await recoverSolanaAgentKeypair(encryptedSecret, { agentId: proposal.agentId, userId, reason: 'autopilot.transfer' });
+ signature = await transferSolanaUSDC({
+ fromWallet: bs58.encode(kp.secretKey),
+ toAddress: recipient,
+ amount: amountRaw,
+ mint: THREE_CA,
+ });
+ } catch (err) {
+ const { updateCustodyEvent } = await import('./agent-trade-guards.js');
+ await updateCustodyEvent(custodyId, { status: 'failed', meta: { error: (err?.message || 'transfer failed').slice(0, 300) } });
+ throw new AutopilotError(`$THREE transfer failed: ${(err?.message || 'unknown').slice(0, 200)}`, { code: 'transfer_failed', status: 502 });
+ }
+
+ const { updateCustodyEvent } = await import('./agent-trade-guards.js');
+ await updateCustodyEvent(custodyId, { status: 'confirmed', signature });
+ return { signature, amount_three: amount, recipient, asset: 'THREE', custody_id: custodyId };
+}
+
+// Author a real, memory-grounded briefing via the LLM (degrades to a grounded
+// summary when no provider is configured — never a fake "the agent said X").
+async function composeBriefing({ agentId, userId, agent, params }) {
+ const memories = await sql`
+ SELECT content, salience FROM agent_memories
+ WHERE agent_id = ${agentId} AND (expires_at IS NULL OR expires_at > now())
+ ORDER BY salience DESC, created_at DESC
+ LIMIT 12
+ `;
+ const grounded = memories.map((m) => `- ${truncate(m.content, 200)}`).join('\n');
+ if (!llmConfigured() || !memories.length) {
+ return `${params.summary}\n\nGrounded in what I know:\n${grounded || '(no memories yet)'}`.slice(0, 2000);
+ }
+ try {
+ const completion = await llmComplete({
+ system: [
+ `You are ${agent?.name || 'a personal AI agent'} writing a short briefing for your owner.`,
+ 'Ground every statement in the provided memories. Be concise (under 120 words),',
+ 'warm, and specific. The only coin you may reference is $THREE. No markdown headers.',
+ ].join('\n'),
+ user: `Topic: ${params.topic || params.summary}\n\nWhat you know:\n${grounded}\n\nWrite the briefing.`,
+ maxTokens: 400,
+ timeoutMs: 25_000,
+ track: { userId, agentId, tool: 'autopilot.briefing' },
+ });
+ return (completion.text || params.summary).slice(0, 2000);
+ } catch {
+ return `${params.summary}\n\nGrounded in what I know:\n${grounded}`.slice(0, 2000);
+ }
+}
+
+function buildReceipt(kind, result) {
+ if (kind === 'create_alert') return `Created a ${String(result.rule_kind).replace('_', ' ')} alert.`;
+ if (kind === 'briefing') return 'Authored a briefing and delivered it to your inbox.';
+ return `Sent ${result.amount_three} $THREE.`;
+}
+
+// ── Trust loop (approve / dismiss / undo) ─────────────────────────────────────
+
+/**
+ * Reverse a reversible action and write a feedback memory so the agent learns
+ * the boundary. wallet_transfer is irreversible and cannot be undone (on-chain).
+ */
+export async function undoProposal({ proposal, agentId, userId }) {
+ if (proposal.status !== 'executed') throw new AutopilotError('Only an executed action can be undone.', { code: 'not_executed', status: 409 });
+ if (proposal.kind === 'wallet_transfer') {
+ throw new AutopilotError('A $THREE transfer is on-chain and cannot be undone.', { code: 'irreversible', status: 409 });
+ }
+
+ if (proposal.kind === 'create_alert' && proposal.result?.rule_id) {
+ await sql`DELETE FROM pump_alert_rules WHERE id = ${proposal.result.rule_id} AND user_id = ${userId}`;
+ } else if (proposal.kind === 'briefing' && proposal.result?.notification_id) {
+ await sql`DELETE FROM user_notifications WHERE id = ${proposal.result.notification_id} AND user_id = ${userId}`;
+ }
+
+ await sql`
+ UPDATE agent_autopilot_proposals
+ SET status = 'undone', decided_at = now()
+ WHERE id = ${proposal.id} AND status = 'executed'
+ `;
+
+ // Closing the loop with Reflection (Task 04/05): the undo is real feedback the
+ // agent remembers, so future reflections lean more conservative.
+ const fb = `I undid an autopilot action ("${truncate(proposal.title, 120)}"). Be more conservative before taking this kind of action again.`;
+ await sql`
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, tier, pinned)
+ VALUES (${agentId}, 'feedback', ${fb}, ${['autopilot', 'undo', 'boundary']},
+ ${JSON.stringify({ source: 'autopilot_undo', proposal_id: proposal.id, kind: proposal.kind })}::jsonb,
+ 0.8, 'recall', true)
+ `;
+ return { ok: true };
+}
+
+/** Dismiss a pending proposal; records a light feedback signal. */
+export async function dismissProposal({ proposal, agentId, userId }) {
+ if (proposal.status !== 'pending') throw new AutopilotError('Only a pending proposal can be dismissed.', { code: 'not_pending', status: 409 });
+ await sql`
+ UPDATE agent_autopilot_proposals
+ SET status = 'dismissed', decided_at = now()
+ WHERE id = ${proposal.id} AND status = 'pending'
+ `;
+ await sql`
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, tier, pinned)
+ VALUES (${agentId}, 'feedback', ${`I dismissed an autopilot proposal: "${truncate(proposal.title, 120)}". Don't propose this again.`},
+ ${['autopilot', 'dismissed']},
+ ${JSON.stringify({ source: 'autopilot_dismiss', proposal_id: proposal.id, kind: proposal.kind })}::jsonb,
+ 0.6, 'recall', false)
+ `;
+ return { ok: true };
+}
+
+const TRUST_LEVELS = [
+ { key: 'sandbox', label: 'Sandbox', min: 0, blurb: 'Proposes; you approve everything.' },
+ { key: 'trusted', label: 'Trusted', min: 5, blurb: 'A track record of approved actions.' },
+ { key: 'autonomous', label: 'Autonomous', min: 20, blurb: 'Consistently acts within your boundaries.' },
+];
+
+/**
+ * Trust level derived from REAL action history — not a vanity number.
+ * Score = approved actions, penalized by undos/dismissals, normalized by volume.
+ */
+export async function computeTrust({ agentId }) {
+ const [counts] = await sql`
+ SELECT
+ COUNT(*) FILTER (WHERE status = 'executed') AS executed,
+ COUNT(*) FILTER (WHERE status = 'undone') AS undone,
+ COUNT(*) FILTER (WHERE status = 'dismissed') AS dismissed,
+ COUNT(*) FILTER (WHERE status = 'pending') AS pending
+ FROM agent_autopilot_proposals
+ WHERE agent_id = ${agentId}
+ `;
+ const executed = Number(counts?.executed ?? 0);
+ const undone = Number(counts?.undone ?? 0);
+ const dismissed = Number(counts?.dismissed ?? 0);
+ const pending = Number(counts?.pending ?? 0);
+
+ // Net successful actions: each kept execution is +1, each undo cancels one out.
+ const net = Math.max(0, executed - undone);
+ const decided = executed + dismissed + undone;
+ // Reliability: of everything decided, how much did the owner keep?
+ const reliability = decided > 0 ? executed / decided : 0;
+ const score = Math.round(net * Math.max(0.25, reliability));
+
+ let level = TRUST_LEVELS[0];
+ for (const l of TRUST_LEVELS) if (score >= l.min) level = l;
+
+ return {
+ level: level.key,
+ label: level.label,
+ blurb: level.blurb,
+ score,
+ stats: { executed, undone, dismissed, pending, reliability: Math.round(reliability * 100) },
+ next: nextLevel(level, score),
+ };
+}
+
+function nextLevel(current, score) {
+ const idx = TRUST_LEVELS.findIndex((l) => l.key === current.key);
+ const nxt = TRUST_LEVELS[idx + 1];
+ if (!nxt) return null;
+ return { label: nxt.label, at: nxt.min, remaining: Math.max(0, nxt.min - score) };
+}
+
+// ── Serialization ─────────────────────────────────────────────────────────────
+
+export function decorateProposal(row) {
+ return {
+ id: row.id,
+ agentId: row.agent_id,
+ userId: row.user_id,
+ kind: row.kind,
+ title: row.title,
+ rationale: row.rationale,
+ params: row.params || {},
+ sourceMemoryIds: row.source_memory_ids || [],
+ sourceReflectionId: row.source_reflection_id || null,
+ confidence: row.confidence != null ? Number(row.confidence) : null,
+ requiresConfirmation: row.requires_confirmation,
+ status: row.status,
+ executedActionId: row.executed_action_id != null ? String(row.executed_action_id) : null,
+ result: row.result || {},
+ createdAt: toIso(row.created_at),
+ decidedAt: toIso(row.decided_at),
+ executedAt: toIso(row.executed_at),
+ };
+}
+
+function toIso(d) {
+ if (!d) return null;
+ return d instanceof Date ? d.toISOString() : d;
+}
diff --git a/api/_lib/brain-anchor.js b/api/_lib/brain-anchor.js
new file mode 100644
index 000000000..5c4a91522
--- /dev/null
+++ b/api/_lib/brain-anchor.js
@@ -0,0 +1,288 @@
+/**
+ * Brain anchoring — record a content-addressed brain milestone on-chain.
+ *
+ * The agent's curated mind (its persona version + the sorted set of signed
+ * memory content-hashes) collapses to a single `brain_hash`. Anchoring writes
+ * that hash to the real ERC-8004 ValidationRegistry via recordValidation(...)
+ * under a brain-specific `kind`, signed by the platform validator key — the
+ * same path that backs GLB validation attestations. The pinned "brain passport"
+ * (proofURI) is the human-readable provenance document the hash commits to.
+ *
+ * This gives a forker/buyer an on-chain, timestamped proof that the agent's
+ * mind was in a known state at a known block — verifiable growth, not a claim.
+ *
+ * Best-effort by contract, mirroring validation-attest: every failure carries a
+ * machine-readable `.code` and is recorded as a `failed` row in
+ * agent_brain_anchors (never a silent skip, never a fake "verified" badge).
+ */
+
+import { createHash } from 'node:crypto';
+import { Contract, Wallet, keccak256, toUtf8Bytes } from 'ethers';
+
+import { env } from './env.js';
+import { sql } from './db.js';
+import { CHAIN_BY_ID, VALIDATION_REGISTRY_ABI, validationRegistryFor } from './erc8004-chains.js';
+import { evmRpcEndpoints } from './evm/rpc.js';
+import { explorerLink } from './onchain.js';
+import { putObject, publicUrl } from './r2.js';
+import { computeBrainHash } from './brain-bundle.js';
+import { signDigest, loadAgentSigner } from './brain-sign.js';
+
+export const BRAIN_ANCHOR_KIND = 'threews.brain-anchor.v1';
+
+export class BrainAnchorError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'BrainAnchorError';
+ this.code = code;
+ }
+}
+
+/**
+ * Build the curated brain state for an agent: persona hash + the signed memory
+ * content-hashes that constitute the anchorable mind. Only memories that carry
+ * a content_hash are included (an unsigned/unhashed memory can't be anchored).
+ *
+ * @param {string} agentId
+ * @param {object} [opts]
+ * @param {boolean} [opts.publicOnly=false] anchor only public memories
+ * @returns {Promise<{ agent: object, persona: object, memoryHashes: string[], publicCount: number, total: number }>}
+ */
+export async function gatherBrainState(agentId, { publicOnly = false } = {}) {
+ const [agent] = await sql`
+ SELECT id, name, wallet_address, chain_id, erc8004_agent_id,
+ persona_prompt_hash, persona_extracted_at
+ FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!agent) throw new BrainAnchorError('agent_not_found', 'agent not found');
+
+ const rows = publicOnly
+ ? await sql`
+ SELECT content_hash, is_public FROM agent_memories
+ WHERE agent_id = ${agentId} AND content_hash IS NOT NULL AND is_public = true
+ AND (expires_at IS NULL OR expires_at > now())
+ `
+ : await sql`
+ SELECT content_hash, is_public FROM agent_memories
+ WHERE agent_id = ${agentId} AND content_hash IS NOT NULL
+ AND (expires_at IS NULL OR expires_at > now())
+ `;
+
+ const memoryHashes = rows.map((r) => r.content_hash);
+ const publicCount = rows.filter((r) => r.is_public).length;
+ return {
+ agent,
+ persona: { prompt_hash: agent.persona_prompt_hash, extracted_at: agent.persona_extracted_at },
+ memoryHashes,
+ publicCount,
+ total: rows.length,
+ };
+}
+
+/**
+ * Compute (without writing) the brain_hash an anchor would commit to. Used by
+ * the UI to show "current vs last-anchored" drift.
+ *
+ * @param {string} agentId
+ * @param {object} [opts]
+ * @returns {Promise<{ brainHash: string, memoryCount: number, publicCount: number, personaPromptHash: string|null }>}
+ */
+export async function previewBrainHash(agentId, opts = {}) {
+ const state = await gatherBrainState(agentId, opts);
+ const brainHash = computeBrainHash({
+ personaPromptHash: state.persona.prompt_hash,
+ memoryHashes: state.memoryHashes,
+ agentId,
+ });
+ return {
+ brainHash,
+ memoryCount: state.total,
+ publicCount: state.publicCount,
+ personaPromptHash: state.persona.prompt_hash || null,
+ };
+}
+
+/**
+ * Anchor the current brain state on-chain. Records a row in agent_brain_anchors
+ * for every attempt (anchored or failed).
+ *
+ * @param {object} p
+ * @param {string} p.agentId
+ * @param {string} p.anchoredAt ISO timestamp (server-supplied; deterministic)
+ * @param {boolean} [p.publicOnly=false]
+ * @returns {Promise<object>} the anchored row + explorer link
+ */
+export async function anchorBrain({ agentId, anchoredAt, publicOnly = false }) {
+ const state = await gatherBrainState(agentId, { publicOnly });
+ const { agent } = state;
+
+ const brainHash = computeBrainHash({
+ personaPromptHash: state.persona.prompt_hash,
+ memoryHashes: state.memoryHashes,
+ agentId,
+ });
+
+ // Sign the milestone with the agent's own wallet — proves the agent itself
+ // attests to this brain state, independent of the platform validator.
+ let agentSignature = null;
+ let agentSigner = null;
+ try {
+ const signer = await loadAgentSigner(agentId, { agentId, reason: 'brain_anchor' });
+ if (signer) {
+ const { signature } = await signDigest(signer.privKey, brainHash);
+ agentSignature = signature;
+ agentSigner = signer.address;
+ }
+ } catch (err) {
+ console.error('[brain-anchor] agent signature failed', agentId, err?.message);
+ }
+
+ const chainId = agent.chain_id || CHAIN_BY_ID[8453]?.id || 8453;
+
+ // Record a pending row up front so a mid-flight failure still leaves a trail.
+ const [pending] = await sql`
+ INSERT INTO agent_brain_anchors
+ (agent_id, brain_hash, kind, status, chain_id, erc8004_agent_id,
+ memory_count, public_count, persona_prompt_hash, signer_address, signature)
+ VALUES (${agentId}, ${brainHash}, ${BRAIN_ANCHOR_KIND}, 'pending', ${chainId},
+ ${agent.erc8004_agent_id || null}, ${state.total}, ${state.publicCount},
+ ${state.persona.prompt_hash || null}, ${agentSigner}, ${agentSignature})
+ RETURNING id
+ `;
+ const anchorId = pending.id;
+
+ const fail = async (code, detail) => {
+ await sql`
+ UPDATE agent_brain_anchors
+ SET status = 'failed', error_code = ${code}, error_detail = ${detail}
+ WHERE id = ${anchorId}
+ `;
+ throw new BrainAnchorError(code, detail);
+ };
+
+ if (!agent.erc8004_agent_id) {
+ await fail(
+ 'not_registered',
+ 'Agent has no ERC-8004 on-chain identity yet. Register the agent on-chain before anchoring its brain.',
+ );
+ }
+
+ const chain = CHAIN_BY_ID[chainId];
+ if (!chain) await fail('unsupported_chain', `unsupported chain ${chainId}`);
+
+ const registryAddr = validationRegistryFor(chainId);
+ if (!registryAddr) {
+ await fail(
+ 'validation_registry_not_deployed',
+ `ValidationRegistry is not deployed on ${chain.name} (chain ${chainId}).`,
+ );
+ }
+
+ const pk = env.VALIDATOR_PRIVATE_KEY;
+ if (!pk) await fail('validator_key_not_configured', 'VALIDATOR_PRIVATE_KEY is not set — cannot anchor.');
+
+ // Build + pin the brain passport (the proof the hash commits to).
+ const passport = {
+ schema: BRAIN_ANCHOR_KIND,
+ brain_hash: brainHash,
+ agent: { id: String(agent.id), name: agent.name || null, erc8004_agent_id: String(agent.erc8004_agent_id) },
+ persona_prompt_hash: state.persona.prompt_hash || null,
+ memory_count: state.total,
+ public_count: state.publicCount,
+ signer_address: agentSigner,
+ agent_signature: agentSignature,
+ anchored_at: anchoredAt,
+ chain_id: chainId,
+ };
+ const proofBody = Buffer.from(JSON.stringify(passport, null, 2));
+ const proofKey = `brain-anchors/${chainId}/${agent.id}/${brainHash}.json`;
+ let proofURI;
+ try {
+ await putObject({ key: proofKey, body: proofBody, contentType: 'application/json' });
+ proofURI = publicUrl(proofKey);
+ } catch (err) {
+ await fail('proof_pin_failed', `could not pin brain passport: ${err.message}`);
+ }
+ const proofHash = keccak256(toUtf8Bytes(JSON.stringify(passport)));
+
+ // Provider + validator wallet + registry.
+ const { JsonRpcProvider, Network } = await import('ethers');
+ const network = Network.from(chainId);
+ const endpoints = evmRpcEndpoints(chainId);
+ const provider = new JsonRpcProvider(endpoints[0], network, { staticNetwork: network });
+ const wallet = new Wallet(pk, provider);
+ const registry = new Contract(registryAddr, VALIDATION_REGISTRY_ABI, wallet);
+
+ let allowed;
+ try {
+ allowed = await registry.isValidator(wallet.address);
+ } catch (err) {
+ await fail('registry_read_failed', `could not read validator allow-list: ${err.message}`);
+ }
+ if (!allowed) {
+ await fail(
+ 'validator_not_allowlisted',
+ `Validator ${wallet.address} is not allow-listed on ${chain.name}.`,
+ );
+ }
+
+ let tx;
+ try {
+ tx = await registry.recordValidation(
+ BigInt(agent.erc8004_agent_id),
+ true,
+ proofHash,
+ proofURI,
+ BRAIN_ANCHOR_KIND,
+ );
+ } catch (err) {
+ await fail('record_failed', `recordValidation reverted: ${err.shortMessage || err.message}`);
+ }
+ await tx.wait();
+
+ const [anchored] = await sql`
+ UPDATE agent_brain_anchors
+ SET status = 'anchored', proof_uri = ${proofURI}, proof_hash = ${proofHash},
+ tx_hash = ${tx.hash}, anchored_at = now()
+ WHERE id = ${anchorId}
+ RETURNING *
+ `;
+
+ return {
+ ...anchored,
+ brain_hash: brainHash,
+ explorer_url: explorerLink(chainId, 'tx', tx.hash) || null,
+ };
+}
+
+/**
+ * Latest anchor for an agent (any status), plus whether it still matches the
+ * current brain state. The drift check is what makes "your brain has changed
+ * since you last anchored" honest.
+ *
+ * @param {string} agentId
+ * @returns {Promise<{ anchor: object|null, currentBrainHash: string, inSync: boolean }>}
+ */
+export async function latestAnchor(agentId) {
+ const [anchor] = await sql`
+ SELECT * FROM agent_brain_anchors
+ WHERE agent_id = ${agentId} AND status = 'anchored'
+ ORDER BY anchored_at DESC NULLS LAST, created_at DESC
+ LIMIT 1
+ `;
+ const preview = await previewBrainHash(agentId);
+ return {
+ anchor: anchor
+ ? { ...anchor, explorer_url: anchor.tx_hash ? explorerLink(anchor.chain_id, 'tx', anchor.tx_hash) || null : null }
+ : null,
+ currentBrainHash: preview.brainHash,
+ inSync: anchor ? anchor.brain_hash === preview.brainHash : false,
+ };
+}
+
+// Stable hex for callers that want a quick sha256 of a string (e.g. proof byte check).
+export function sha256Hex(input) {
+ return createHash('sha256').update(input).digest('hex');
+}
diff --git a/api/_lib/memory-store.js b/api/_lib/memory-store.js
index 956e9e5be..881ac9427 100644
--- a/api/_lib/memory-store.js
+++ b/api/_lib/memory-store.js
@@ -68,6 +68,14 @@ export function decorateMemory(row, extra = {}) {
updatedAt: row.updated_at ? new Date(row.updated_at).getTime() : createdMs,
lastAccessedAt: row.last_accessed_at ? new Date(row.last_accessed_at).getTime() : null,
expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,
+ // Portable & Verifiable Brain — authorship + storage provenance. Present
+ // on rows selected with the brain columns; absent (undefined) otherwise.
+ contentHash: row.content_hash ?? undefined,
+ signature: row.signature ?? undefined,
+ signerAddress: row.signer_address ?? undefined,
+ signedAt: row.signed_at ? new Date(row.signed_at).getTime() : (row.signed_at === null ? null : undefined),
+ storageMode: row.storage_mode ?? undefined,
+ ipfsCid: row.ipfs_cid ?? undefined,
...extra,
};
}
diff --git a/api/_lib/migrations/20260623230000_brain_ownership.sql b/api/_lib/migrations/20260623230000_brain_ownership.sql
new file mode 100644
index 000000000..fda4dcb61
--- /dev/null
+++ b/api/_lib/migrations/20260623230000_brain_ownership.sql
@@ -0,0 +1,74 @@
+-- Portable & Verifiable Brain — own your agent's mind (Living Agents · Task 06).
+--
+-- Three additive concerns, all idempotent so a clean-room bootstrap from
+-- schema.sql and an incremental apply land in the same place:
+--
+-- 1. Per-memory authorship + integrity. Every memory an agent commits is
+-- signed by the agent's own EVM wallet (ERC-191) over a canonical hash of
+-- its content. content_hash is the fast tamper check; signature +
+-- signer_address are the publicly-verifiable proof of authorship. A buyer
+-- or forker re-derives the hash and ecrecovers the signer offline — no
+-- trust in our DB required.
+--
+-- 2. Per-memory storage mode + IPFS provenance. storage_mode overrides the
+-- agent's default (null = inherit). ipfs_cid records where an encrypted or
+-- pinned copy lives (the CID is also tracked in agent_memory_pins for
+-- ownership). Private memories pinned in encrypted-ipfs mode are encrypted
+-- client-side with the owner's wallet-derived key — we store the ciphertext
+-- CID, never plaintext.
+--
+-- 3. Brain anchors. Each anchored milestone is a row: a content-addressed
+-- brain_hash (persona version + sorted memory content-hashes) recorded on
+-- the ERC-8004 ValidationRegistry. The table is the agent's verifiable
+-- proof-of-growth history — one row per anchor, including failed attempts
+-- with their reason, so an anchor is never silently skipped.
+
+-- 1 + 2 — agent_memories authorship + storage columns
+alter table agent_memories add column if not exists content_hash text;
+alter table agent_memories add column if not exists signature text;
+alter table agent_memories add column if not exists signer_address text;
+alter table agent_memories add column if not exists signed_at timestamptz;
+alter table agent_memories add column if not exists storage_mode text;
+alter table agent_memories add column if not exists ipfs_cid text;
+
+alter table agent_memories drop constraint if exists agent_memories_storage_mode_chk;
+alter table agent_memories add constraint agent_memories_storage_mode_chk
+ check (storage_mode is null or storage_mode in ('local','ipfs','encrypted-ipfs','none'));
+
+-- Per-agent default storage mode for new memories.
+alter table agent_identities add column if not exists memory_storage_mode text not null default 'local';
+
+alter table agent_identities drop constraint if exists agent_identities_memory_storage_mode_chk;
+alter table agent_identities add constraint agent_identities_memory_storage_mode_chk
+ check (memory_storage_mode in ('local','ipfs','encrypted-ipfs','none'));
+
+-- 3 — brain anchor history
+create table if not exists agent_brain_anchors (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ brain_hash text not null, -- sha256 over persona hash + sorted memory hashes
+ kind text not null default 'threews.brain-anchor.v1',
+ status text not null default 'pending'
+ check (status in ('pending','anchored','failed')),
+ proof_uri text, -- pinned brain passport JSON
+ proof_hash text, -- keccak/sha of the pinned proof bytes
+ tx_hash text, -- on-chain recordValidation tx
+ chain_id integer,
+ erc8004_agent_id bigint,
+ memory_count integer not null default 0,
+ public_count integer not null default 0,
+ persona_prompt_hash text,
+ signer_address text, -- agent wallet that signed brain_hash
+ signature text, -- ERC-191 signature over brain_hash
+ error_code text, -- machine-readable reason when status='failed'
+ error_detail text,
+ created_at timestamptz not null default now(),
+ anchored_at timestamptz
+);
+
+create index if not exists agent_brain_anchors_agent
+ on agent_brain_anchors(agent_id, created_at desc);
+create index if not exists agent_brain_anchors_hash
+ on agent_brain_anchors(agent_id, brain_hash);
+create index if not exists agent_brain_anchors_status
+ on agent_brain_anchors(agent_id, status, created_at desc);
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 16b604d32..1be809bde 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -2118,3 +2118,52 @@ create index if not exists genome_breedings_child
on genome_breedings (child_agent_id) where child_agent_id is not null;
create index if not exists genome_breedings_bred_by
on genome_breedings (bred_by, created_at desc);
+
+-- ── Portable & Verifiable Brain (Living Agents · Task 06) ──────────────────────
+-- See api/_lib/migrations/20260623230000_brain_ownership.sql for the full rationale.
+-- Per-memory authorship (signed by the agent's EVM wallet), integrity hash, and
+-- storage provenance; per-agent default storage mode; and the brain-anchor
+-- history (content-addressed milestones recorded on the ERC-8004 registry).
+alter table agent_memories add column if not exists content_hash text;
+alter table agent_memories add column if not exists signature text;
+alter table agent_memories add column if not exists signer_address text;
+alter table agent_memories add column if not exists signed_at timestamptz;
+alter table agent_memories add column if not exists storage_mode text;
+alter table agent_memories add column if not exists ipfs_cid text;
+alter table agent_memories drop constraint if exists agent_memories_storage_mode_chk;
+alter table agent_memories add constraint agent_memories_storage_mode_chk
+ check (storage_mode is null or storage_mode in ('local','ipfs','encrypted-ipfs','none'));
+
+alter table agent_identities add column if not exists memory_storage_mode text not null default 'local';
+alter table agent_identities drop constraint if exists agent_identities_memory_storage_mode_chk;
+alter table agent_identities add constraint agent_identities_memory_storage_mode_chk
+ check (memory_storage_mode in ('local','ipfs','encrypted-ipfs','none'));
+
+create table if not exists agent_brain_anchors (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ brain_hash text not null,
+ kind text not null default 'threews.brain-anchor.v1',
+ status text not null default 'pending'
+ check (status in ('pending','anchored','failed')),
+ proof_uri text,
+ proof_hash text,
+ tx_hash text,
+ chain_id integer,
+ erc8004_agent_id bigint,
+ memory_count integer not null default 0,
+ public_count integer not null default 0,
+ persona_prompt_hash text,
+ signer_address text,
+ signature text,
+ error_code text,
+ error_detail text,
+ created_at timestamptz not null default now(),
+ anchored_at timestamptz
+);
+create index if not exists agent_brain_anchors_agent
+ on agent_brain_anchors(agent_id, created_at desc);
+create index if not exists agent_brain_anchors_hash
+ on agent_brain_anchors(agent_id, brain_hash);
+create index if not exists agent_brain_anchors_status
+ on agent_brain_anchors(agent_id, status, created_at desc);
diff --git a/api/_lib/trader-stats.js b/api/_lib/trader-stats.js
index 1858868da..3308d8dfb 100644
--- a/api/_lib/trader-stats.js
+++ b/api/_lib/trader-stats.js
@@ -19,10 +19,16 @@
* Honesty rules baked in:
* - SOL amounts are exact (from chain). USD is an enrichment that degrades to
* null if the price feed is down — we never fabricate a dollar figure.
- * - We do NOT claim "wash detection" we can't do from one-sided position data.
- * `churn_pct` is an explicit heuristic (near-flat in-and-out churn) and is
+ * - `churn_pct` is an explicit heuristic (near-flat in-and-out churn) and is
* named as such.
* - Survivorship-honest: closed losers are counted, never hidden.
+ * - Anti-gaming, when the caller supplies the evidence: realized P&L from
+ * round-trips on the trader's OWN coins (`selfDealMints`) is NOT credited to
+ * the verifiable record — you cannot pump a token you launched and call it a
+ * track record. The excluded total is reported transparently, never silently
+ * dropped. Snipe hit-rate (`mintCreatedAt`) is the win rate on entries made
+ * within minutes of a coin's on-chain birth — the hardest, most-faked flex,
+ * here computed only over launches whose creation slot we can actually prove.
*/
import { sql } from './db.js';
@@ -60,6 +66,14 @@ const BADGE = { minClosed: 12, minUniqueCoins: 5, maxChurnPct: 40 };
const CHURN_HOLD_SECONDS = 25;
const CHURN_FLAT_PCT = 1.5;
+// Snipe window: an entry is a "snipe" when it lands within this long after the
+// coin's on-chain birth. 5 minutes is generous enough to survive the gap between
+// our DB open timestamp and the chain's block time, tight enough to mean "early".
+const SNIPE_WINDOW_MS = 5 * 60_000;
+// Grace for clock skew between our recorded open time and the launch block time —
+// a buy can never truly precede the mint, so a few seconds of negative drift is noise.
+const SNIPE_SKEW_GRACE_MS = 3_000;
+
const big = (v) => {
try { return Number(BigInt(v)); } catch { return Number(v) || 0; }
};
@@ -107,11 +121,35 @@ function maxDrawdown(closedOrderedLamports) {
* opened_at, closed_at.
* @param {object} [opts]
* @param {number|null} [opts.solUsd] USD per SOL, or null to omit USD fields.
+ * @param {Set<string>|Record<string,true>|null} [opts.selfDealMints] Mints the
+ * trader's own account launched/created. Positions on these are split out of the
+ * credited record (anti-gaming) and reported under `self_dealing_*`. Omit/null
+ * to credit every position (legacy behaviour).
+ * @param {Map<string,number|string>|Record<string,number|string>|null} [opts.mintCreatedAt]
+ * Mint → on-chain creation time (ms epoch or ISO). Drives snipe hit-rate. Only
+ * mints present here count toward the snipe sample — unknown launches are not
+ * guessed at.
* @returns {object} canonical metrics — see fields below.
*/
-export function computeTraderMetrics(positions, { solUsd = null } = {}) {
- const closed = positions.filter((p) => p.status === 'closed');
- const open = positions.filter((p) => p.status === 'open' || p.status === 'opening' || p.status === 'closing');
+export function computeTraderMetrics(positions, { solUsd = null, selfDealMints = null, mintCreatedAt = null } = {}) {
+ const isSelfDeal = (mint) =>
+ !!(mint && selfDealMints && (typeof selfDealMints.has === 'function' ? selfDealMints.has(mint) : selfDealMints[mint]));
+ const launchOf = (mint) => {
+ if (!mint || !mintCreatedAt) return null;
+ const v = typeof mintCreatedAt.get === 'function' ? mintCreatedAt.get(mint) : mintCreatedAt[mint];
+ if (v == null) return null;
+ const t = typeof v === 'number' ? v : Date.parse(v);
+ return Number.isFinite(t) ? t : null;
+ };
+
+ // Anti-gaming: round-trips on the trader's OWN coins are split out before any
+ // credited metric is computed. They are counted and reported, never hidden, but
+ // they cannot inflate the verifiable record.
+ const selfDealPositions = positions.filter((p) => isSelfDeal(p.mint));
+ const credited = selfDealPositions.length ? positions.filter((p) => !isSelfDeal(p.mint)) : positions;
+
+ const closed = credited.filter((p) => p.status === 'closed');
+ const open = credited.filter((p) => p.status === 'open' || p.status === 'opening' || p.status === 'closing');
// --- Realized (closed positions) ---
let realizedLamports = 0n;
@@ -125,6 +163,9 @@ export function computeTraderMetrics(positions, { solUsd = null } = {}) {
let churn = 0;
let bestPct = null, worstPct = null;
let firstActive = null, lastActive = null;
+ // Snipe hit-rate: only positions whose mint has a proven on-chain birth count
+ // toward the sample, so the number is honest about its own coverage.
+ let snipeSample = 0, snipeCount = 0, snipeWins = 0;
// Oldest→newest by close time for the equity curve.
const closedOrdered = [...closed].sort(
@@ -154,6 +195,16 @@ export function computeTraderMetrics(positions, { solUsd = null } = {}) {
holdSeconds.push(held);
if (held <= CHURN_HOLD_SECONDS && pct != null && Math.abs(pct) <= CHURN_FLAT_PCT) churn += 1;
+ const launchMs = launchOf(p.mint);
+ if (launchMs != null) {
+ snipeSample += 1;
+ const sinceLaunch = opened - launchMs;
+ if (sinceLaunch >= -SNIPE_SKEW_GRACE_MS && sinceLaunch <= SNIPE_WINDOW_MS) {
+ snipeCount += 1;
+ if (pnl > 0n) snipeWins += 1;
+ }
+ }
+
if (firstActive == null || opened < firstActive) firstActive = opened;
if (lastActive == null || closedAt > lastActive) lastActive = closedAt;
}
@@ -215,6 +266,18 @@ export function computeTraderMetrics(positions, { solUsd = null } = {}) {
const usd = (sol) => (solUsd != null ? sol * solUsd : null);
+ // Self-dealing summary (transparent, never folded into the credited numbers).
+ let selfDealClosed = 0;
+ let selfDealPnlLamports = 0n;
+ for (const p of selfDealPositions) {
+ if (p.status === 'closed') {
+ selfDealClosed += 1;
+ selfDealPnlLamports += BigInt(p.realized_pnl_lamports ?? 0);
+ }
+ }
+ const selfDealPnlSol = big(selfDealPnlLamports.toString()) / LAMPORTS_PER_SOL;
+ const snipeHitRate = snipeCount ? snipeWins / snipeCount : null;
+
return {
score,
verified,
@@ -253,6 +316,20 @@ export function computeTraderMetrics(positions, { solUsd = null } = {}) {
unique_coins: coins.size,
churn_pct: Number(churnPct.toFixed(2)),
+ // Snipe hit-rate — win rate on entries inside SNIPE_WINDOW_MS of a coin's
+ // proven on-chain birth. null until at least one such launch is in the
+ // sample; `snipe_sample` exposes the coverage so the rate is never overclaimed.
+ snipe_count: snipeCount,
+ snipe_wins: snipeWins,
+ snipe_sample: snipeSample,
+ snipe_hit_rate: snipeHitRate != null ? Number(snipeHitRate.toFixed(4)) : null,
+
+ // Anti-gaming: round-trips on the trader's OWN coins, excluded from every
+ // credited metric above and surfaced here so the exclusion is auditable.
+ self_dealing_count: selfDealClosed,
+ self_dealing_excluded_pnl_sol: Number(selfDealPnlSol.toFixed(6)),
+ self_dealing_excluded_pnl_usd: usd(selfDealPnlSol) != null ? Number(usd(selfDealPnlSol).toFixed(2)) : null,
+
first_active_at: firstActive ? new Date(firstActive).toISOString() : null,
last_active_at: lastActive ? new Date(lastActive).toISOString() : null,
};
diff --git a/api/_lib/vault-jupiter.js b/api/_lib/vault-jupiter.js
new file mode 100644
index 000000000..f4a14b591
--- /dev/null
+++ b/api/_lib/vault-jupiter.js
@@ -0,0 +1,135 @@
+// @ts-check
+// Back-an-Agent Vaults — real Jupiter swaps + mark-to-market.
+//
+// A USDC-denominated vault deploys capital by swapping USDC → token and harvests
+// it back token → USDC. Both legs are REAL Jupiter v1 swaps (the same lite-api
+// endpoint and signing path api/_lib/wallet-intents.js uses for the autopilot's
+// buys) — no synthetic prices, no fake fills. NAV marks open positions to market
+// with a live token → USDC quote, so the share price a backer sees is what the
+// holdings are actually worth right now.
+
+import { PublicKey } from '@solana/web3.js';
+
+const JUPITER_BASE = 'https://lite-api.jup.ag/swap/v1';
+
+export const USDC_MINT_BY_NETWORK = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
+export const USDC_DECIMALS = 6;
+
+function usdcMint(network) {
+ return network === 'devnet' ? USDC_MINT_BY_NETWORK.devnet : USDC_MINT_BY_NETWORK.mainnet;
+}
+
+async function fetchWithTimeout(url, opts = {}, ms = 15_000) {
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), ms);
+ try {
+ return await fetch(url, { ...opts, signal: ctrl.signal });
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+/**
+ * A Jupiter ExactIn quote. Returns the parsed quote object (with `outAmount`,
+ * `priceImpactPct`, route plan) or throws a structured error so the trade path can
+ * surface a clean 4xx/502.
+ * @param {object} a
+ * @param {string} a.inputMint
+ * @param {string} a.outputMint
+ * @param {bigint} a.amountRaw input amount in the input mint's base units
+ * @param {number} a.slippageBps
+ */
+export async function jupQuote({ inputMint, outputMint, amountRaw, slippageBps }) {
+ const amount = BigInt(amountRaw);
+ if (amount <= 0n) throw Object.assign(new Error('amount rounds to zero'), { code: 'zero_amount' });
+ const url = `${JUPITER_BASE}/quote?inputMint=${inputMint}&outputMint=${outputMint}`
+ + `&amount=${amount.toString()}&slippageBps=${Math.max(0, Math.round(slippageBps))}&swapMode=ExactIn`;
+ const res = await fetchWithTimeout(url, {}, 15_000);
+ if (!res.ok) throw Object.assign(new Error(`no swap route (${res.status})`), { code: 'no_route' });
+ const quote = await res.json();
+ if (!quote?.outAmount) throw Object.assign(new Error('no swap route for this pair'), { code: 'no_route' });
+ return quote;
+}
+
+/**
+ * Build a signed-ready Jupiter swap VersionedTransaction for `quote`, owned by
+ * `userPublicKey`. The caller signs + submits it (vault-trade.js), so this never
+ * touches a key.
+ */
+export async function buildSwapTx({ quote, userPublicKey }) {
+ const { VersionedTransaction } = await import('@solana/web3.js');
+ const res = await fetchWithTimeout(`${JUPITER_BASE}/swap`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ quoteResponse: quote,
+ userPublicKey: typeof userPublicKey === 'string' ? userPublicKey : userPublicKey.toBase58(),
+ wrapAndUnwrapSol: true,
+ dynamicComputeUnitLimit: true,
+ prioritizationFeeLamports: 'auto',
+ }),
+ }, 20_000);
+ if (!res.ok) throw Object.assign(new Error(`swap build failed (${res.status})`), { code: 'swap_failed' });
+ const { swapTransaction } = await res.json();
+ if (!swapTransaction) throw Object.assign(new Error('swap build returned no transaction'), { code: 'swap_failed' });
+ return VersionedTransaction.deserialize(Buffer.from(swapTransaction, 'base64'));
+}
+
+/**
+ * Quote a buy: how many token base units `usdcAtomics` of USDC buys, plus impact.
+ * @returns {Promise<{ quote:object, expectedOutRaw:bigint, priceImpactPct:number, inputMint:string, outputMint:string }>}
+ */
+export async function quoteBuy({ network, mint, usdcAtomics, slippageBps }) {
+ const inputMint = usdcMint(network);
+ const quote = await jupQuote({ inputMint, outputMint: mint, amountRaw: usdcAtomics, slippageBps });
+ return {
+ quote,
+ expectedOutRaw: BigInt(quote.outAmount),
+ priceImpactPct: Number(quote.priceImpactPct ?? 0),
+ inputMint, outputMint: mint,
+ };
+}
+
+/**
+ * Quote a sell: how much USDC `amountRaw` token base units fetches, plus impact.
+ * @returns {Promise<{ quote:object, expectedOutAtomics:bigint, priceImpactPct:number, inputMint:string, outputMint:string }>}
+ */
+export async function quoteSell({ network, mint, amountRaw, slippageBps }) {
+ const outputMint = usdcMint(network);
+ const quote = await jupQuote({ inputMint: mint, outputMint, amountRaw, slippageBps });
+ return {
+ quote,
+ expectedOutAtomics: BigInt(quote.outAmount),
+ priceImpactPct: Number(quote.priceImpactPct ?? 0),
+ inputMint: mint, outputMint,
+ };
+}
+
+/**
+ * Mark a holding to market: the USDC atomics `amountRaw` base units of `mint` would
+ * fetch right now (zero-slippage reference quote). Returns null if it can't be
+ * priced — callers treat that as "exclude from NAV this tick", never as zero, so a
+ * transient Jupiter hiccup never fabricates a loss that could trip the breaker.
+ */
+export async function markToUsdc({ network, mint, amountRaw }) {
+ const amount = BigInt(amountRaw || 0n);
+ if (amount <= 0n) return 0n;
+ try {
+ const quote = await jupQuote({ inputMint: mint, outputMint: usdcMint(network), amountRaw: amount, slippageBps: 0 });
+ return BigInt(quote.outAmount);
+ } catch {
+ return null;
+ }
+}
+
+/** Validate a mint is a syntactically valid Solana address; returns the base58 or null. */
+export function validateMint(mint) {
+ try {
+ return new PublicKey(String(mint)).toBase58();
+ } catch {
+ return null;
+ }
+}
diff --git a/api/_lib/vault-store.js b/api/_lib/vault-store.js
new file mode 100644
index 000000000..ce9cd5073
--- /dev/null
+++ b/api/_lib/vault-store.js
@@ -0,0 +1,339 @@
+// @ts-check
+// Back-an-Agent Vaults — the DB access layer.
+//
+// Every read/write against agent_vaults / vault_backers / vault_positions /
+// vault_events goes through here, so the routes stay thin and the SQL stays in
+// one auditable place. All money columns are numeric(40,0) USDC atomics and come
+// back as strings — callers convert with vault-accounting.toBig() before doing
+// any arithmetic. Nothing here moves funds or signs; that's vault-trade.js /
+// vault-transfer.js. This module is purely the system of record.
+
+import { sql } from './db.js';
+
+// Columns safe to expose publicly (NEVER the encrypted_secret). Spread into a
+// SELECT to guarantee the vault keypair ciphertext can't leak through a read.
+const PUBLIC_COLS = sql`
+ id, agent_id, owner_user_id, network, vault_address, status,
+ performance_fee_bps, per_backer_cap_atomics, max_drawdown_bps,
+ max_per_trade_atomics, daily_budget_atomics,
+ total_shares, peak_nav_atomics, accrued_fee_atomics,
+ halt_reason, paused_at, created_at, updated_at
+`;
+
+/** Create a vault row. The caller has already generated + encrypted the wallet. */
+export async function createVault({
+ agentId, ownerUserId, network, vaultAddress, encryptedSecret,
+ performanceFeeBps, perBackerCapAtomics, maxDrawdownBps,
+ maxPerTradeAtomics, dailyBudgetAtomics,
+}) {
+ const [row] = await sql`
+ INSERT INTO agent_vaults
+ (agent_id, owner_user_id, network, vault_address, encrypted_secret,
+ performance_fee_bps, per_backer_cap_atomics, max_drawdown_bps,
+ max_per_trade_atomics, daily_budget_atomics)
+ VALUES (
+ ${agentId}, ${ownerUserId}, ${network}, ${vaultAddress}, ${encryptedSecret},
+ ${performanceFeeBps}, ${perBackerCapAtomics == null ? null : String(perBackerCapAtomics)},
+ ${maxDrawdownBps}, ${String(maxPerTradeAtomics)}, ${String(dailyBudgetAtomics)}
+ )
+ RETURNING ${PUBLIC_COLS}
+ `;
+ return row;
+}
+
+/** Public vault row by id (no secret). */
+export async function getVault(id) {
+ const [row] = await sql`SELECT ${PUBLIC_COLS} FROM agent_vaults WHERE id = ${id} LIMIT 1`;
+ return row || null;
+}
+
+/** The active (non-closed) vault for an agent, if any. */
+export async function getVaultByAgent(agentId) {
+ const [row] = await sql`
+ SELECT ${PUBLIC_COLS} FROM agent_vaults
+ WHERE agent_id = ${agentId} AND status <> 'closed'
+ ORDER BY created_at DESC LIMIT 1
+ `;
+ return row || null;
+}
+
+/**
+ * Internal: the vault row WITH the encrypted secret. Only vault-trade.js /
+ * vault-transfer.js call this, right before recovering the keypair to sign. Never
+ * return this shape to an HTTP response.
+ */
+export async function getVaultWithSecret(id) {
+ const [row] = await sql`
+ SELECT ${PUBLIC_COLS}, encrypted_secret FROM agent_vaults WHERE id = ${id} LIMIT 1
+ `;
+ return row || null;
+}
+
+/**
+ * Discovery feed: open/paused vaults with their owning agent's identity, ranked.
+ * The ranking is computed by the caller against verified reputation; here we just
+ * return the raw rows + agent facts and a deposited-backer count.
+ */
+export async function listVaults({ status = 'open', limit = 60 } = {}) {
+ const lim = Math.max(1, Math.min(120, Number(limit) || 60));
+ const rows = await sql`
+ SELECT
+ v.id, v.agent_id, v.network, v.vault_address, v.status,
+ v.performance_fee_bps, v.per_backer_cap_atomics, v.max_drawdown_bps,
+ v.max_per_trade_atomics, v.daily_budget_atomics,
+ v.total_shares, v.peak_nav_atomics, v.created_at, v.updated_at,
+ a.name AS agent_name,
+ COALESCE(a.profile_image_url, a.avatar_url) AS agent_image,
+ a.description AS agent_description,
+ (SELECT COUNT(*) FROM vault_backers b WHERE b.vault_id = v.id AND b.shares > 0)::int AS backer_count,
+ (SELECT COALESCE(SUM(b.deposited_atomics), 0) FROM vault_backers b WHERE b.vault_id = v.id) AS lifetime_deposited
+ FROM agent_vaults v
+ JOIN agent_identities a ON a.id = v.agent_id AND a.deleted_at IS NULL
+ WHERE (${status === 'all'} OR v.status = ${status})
+ AND v.status <> 'closed'
+ ORDER BY v.updated_at DESC
+ LIMIT ${lim}
+ `;
+ return rows;
+}
+
+/** Vaults the user has backed (their portfolio). */
+export async function listBackedVaults(userId, { limit = 60 } = {}) {
+ const lim = Math.max(1, Math.min(120, Number(limit) || 60));
+ const rows = await sql`
+ SELECT
+ b.shares, b.cost_basis_atomics, b.deposited_atomics, b.redeemed_atomics,
+ b.realized_gain_atomics, b.fees_paid_atomics, b.backer_agent_id,
+ v.id, v.agent_id, v.network, v.status, v.performance_fee_bps,
+ v.max_drawdown_bps, v.total_shares, v.peak_nav_atomics,
+ a.name AS agent_name, COALESCE(a.profile_image_url, a.avatar_url) AS agent_image
+ FROM vault_backers b
+ JOIN agent_vaults v ON v.id = b.vault_id
+ JOIN agent_identities a ON a.id = v.agent_id
+ WHERE b.user_id = ${userId} AND b.shares > 0
+ ORDER BY b.updated_at DESC
+ LIMIT ${lim}
+ `;
+ return rows;
+}
+
+/** A single backer's position in a vault (null if they hold none). */
+export async function getBacker(vaultId, userId) {
+ const [row] = await sql`
+ SELECT * FROM vault_backers WHERE vault_id = ${vaultId} AND user_id = ${userId} LIMIT 1
+ `;
+ return row || null;
+}
+
+/** The list of backers in a vault (for the vault page roster). */
+export async function listBackers(vaultId, { limit = 50 } = {}) {
+ const lim = Math.max(1, Math.min(200, Number(limit) || 50));
+ const rows = await sql`
+ SELECT user_id, backer_agent_id, shares, cost_basis_atomics, deposited_atomics, updated_at
+ FROM vault_backers
+ WHERE vault_id = ${vaultId} AND shares > 0
+ ORDER BY shares DESC
+ LIMIT ${lim}
+ `;
+ return rows;
+}
+
+/** Open positions held by the vault (marked to market by the caller). */
+export async function getOpenPositions(vaultId) {
+ return sql`
+ SELECT id, mint, token_decimals, amount_raw, cost_atomics, last_mark_atomics, opened_at
+ FROM vault_positions WHERE vault_id = ${vaultId} AND status = 'open'
+ ORDER BY opened_at ASC
+ `;
+}
+
+/** Append an event to the immutable ledger. Returns the row id (or null on idem clash). */
+export async function recordVaultEvent(e) {
+ const rows = await sql`
+ INSERT INTO vault_events
+ (vault_id, type, user_id, backer_agent_id, shares_delta, atomics_delta,
+ nav_atomics, share_price_e6, signature, status, reason, idempotency_key, meta)
+ VALUES (
+ ${e.vaultId}, ${e.type}, ${e.userId ?? null}, ${e.backerAgentId ?? null},
+ ${e.sharesDelta == null ? null : String(e.sharesDelta)},
+ ${e.atomicsDelta == null ? null : String(e.atomicsDelta)},
+ ${e.navAtomics == null ? null : String(e.navAtomics)},
+ ${e.sharePriceE6 == null ? null : String(e.sharePriceE6)},
+ ${e.signature ?? null}, ${e.status ?? 'ok'}, ${e.reason ?? null},
+ ${e.idempotencyKey ?? null}, ${JSON.stringify(e.meta ?? {})}::jsonb
+ )
+ ON CONFLICT (vault_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
+ RETURNING id
+ `;
+ return rows.length ? Number(rows[0].id) : null;
+}
+
+/** Finalize a previously-recorded (pending) event: status/signature/nav/meta. */
+export async function updateVaultEvent(id, patch) {
+ await sql`
+ UPDATE vault_events SET
+ status = COALESCE(${patch.status ?? null}, status),
+ signature = COALESCE(${patch.signature ?? null}, signature),
+ nav_atomics = ${patch.navAtomics == null ? sql`nav_atomics` : String(patch.navAtomics)},
+ share_price_e6 = ${patch.sharePriceE6 == null ? sql`share_price_e6` : String(patch.sharePriceE6)},
+ atomics_delta = ${patch.atomicsDelta == null ? sql`atomics_delta` : String(patch.atomicsDelta)},
+ meta = meta || ${JSON.stringify(patch.meta ?? {})}::jsonb
+ WHERE id = ${id}
+ `.catch(() => {});
+}
+
+/** Cursor-paginated event feed for the audit trail. */
+export async function listVaultEvents(vaultId, { limit = 50, beforeId = null, type = null } = {}) {
+ const lim = Math.max(1, Math.min(200, Number(limit) || 50));
+ return sql`
+ SELECT id, type, user_id, backer_agent_id, shares_delta, atomics_delta,
+ nav_atomics, share_price_e6, signature, status, reason, meta, created_at
+ FROM vault_events
+ WHERE vault_id = ${vaultId}
+ AND (${beforeId == null}::bool OR id < ${beforeId == null ? 0 : beforeId})
+ AND (${type == null}::bool OR type = ${type})
+ ORDER BY id DESC
+ LIMIT ${lim}
+ `;
+}
+
+/** Rolling 24h confirmed buy spend (USDC atomics) — the daily-budget denominator. */
+export async function getDailyTradeSpend(vaultId) {
+ const [r] = await sql`
+ SELECT COALESCE(SUM((meta->>'usdc_in')::numeric), 0) AS spent
+ FROM vault_events
+ WHERE vault_id = ${vaultId} AND type = 'trade' AND status = 'ok'
+ AND (meta->>'side') = 'buy'
+ AND created_at > now() - interval '24 hours'
+ `;
+ return r?.spent ?? '0';
+}
+
+/** Upsert a backer's position after a deposit (mint shares) or redemption (burn). */
+export async function applyBackerDelta({ vaultId, userId, backerAgentId, sharesDelta, basisDelta, depositedDelta = 0n, redeemedDelta = 0n, realizedGainDelta = 0n, feesPaidDelta = 0n }) {
+ const [row] = await sql`
+ INSERT INTO vault_backers
+ (vault_id, user_id, backer_agent_id, shares, cost_basis_atomics,
+ deposited_atomics, redeemed_atomics, realized_gain_atomics, fees_paid_atomics)
+ VALUES (
+ ${vaultId}, ${userId}, ${backerAgentId},
+ ${String(sharesDelta)}, ${String(basisDelta < 0n ? 0n : basisDelta)},
+ ${String(depositedDelta)}, ${String(redeemedDelta)},
+ ${String(realizedGainDelta)}, ${String(feesPaidDelta)}
+ )
+ ON CONFLICT (vault_id, user_id) DO UPDATE SET
+ shares = GREATEST(vault_backers.shares + ${String(sharesDelta)}, 0),
+ cost_basis_atomics = GREATEST(vault_backers.cost_basis_atomics + ${String(basisDelta)}, 0),
+ deposited_atomics = vault_backers.deposited_atomics + ${String(depositedDelta)},
+ redeemed_atomics = vault_backers.redeemed_atomics + ${String(redeemedDelta)},
+ realized_gain_atomics = vault_backers.realized_gain_atomics + ${String(realizedGainDelta)},
+ fees_paid_atomics = vault_backers.fees_paid_atomics + ${String(feesPaidDelta)},
+ backer_agent_id = ${backerAgentId},
+ updated_at = now()
+ RETURNING *
+ `;
+ return row;
+}
+
+/** Move total_shares by a signed delta and ratchet the high-water peak. */
+export async function applyVaultShareDelta(vaultId, sharesDelta, peakNavAtomics = null) {
+ const [row] = await sql`
+ UPDATE agent_vaults SET
+ total_shares = GREATEST(total_shares + ${String(sharesDelta)}, 0),
+ peak_nav_atomics = ${peakNavAtomics == null ? sql`peak_nav_atomics` : sql`GREATEST(peak_nav_atomics, ${String(peakNavAtomics)})`},
+ updated_at = now()
+ WHERE id = ${vaultId}
+ RETURNING ${PUBLIC_COLS}
+ `;
+ return row || null;
+}
+
+/** Accrue (delta>0) or claim (delta<0) owner performance fees. */
+export async function applyAccruedFee(vaultId, deltaAtomics) {
+ const [row] = await sql`
+ UPDATE agent_vaults SET
+ accrued_fee_atomics = GREATEST(accrued_fee_atomics + ${String(deltaAtomics)}, 0),
+ updated_at = now()
+ WHERE id = ${vaultId}
+ RETURNING accrued_fee_atomics
+ `;
+ return row?.accrued_fee_atomics ?? '0';
+}
+
+/** Set vault status (pause/resume/halt/close), recording the reason. */
+export async function setVaultStatus(vaultId, status, { haltReason = null } = {}) {
+ const [row] = await sql`
+ UPDATE agent_vaults SET
+ status = ${status},
+ halt_reason = ${haltReason},
+ paused_at = ${status === 'paused' ? sql`now()` : sql`NULL`},
+ updated_at = now()
+ WHERE id = ${vaultId}
+ RETURNING ${PUBLIC_COLS}
+ `;
+ return row || null;
+}
+
+/** Update disclosed terms (owner-only; caller enforces ownership + safety bounds). */
+export async function updateVaultTerms(vaultId, patch) {
+ const [row] = await sql`
+ UPDATE agent_vaults SET
+ performance_fee_bps = COALESCE(${patch.performanceFeeBps ?? null}, performance_fee_bps),
+ per_backer_cap_atomics = ${patch.perBackerCapAtomics === undefined ? sql`per_backer_cap_atomics` : (patch.perBackerCapAtomics == null ? null : String(patch.perBackerCapAtomics))},
+ max_drawdown_bps = COALESCE(${patch.maxDrawdownBps ?? null}, max_drawdown_bps),
+ max_per_trade_atomics = COALESCE(${patch.maxPerTradeAtomics == null ? null : String(patch.maxPerTradeAtomics)}, max_per_trade_atomics),
+ daily_budget_atomics = COALESCE(${patch.dailyBudgetAtomics == null ? null : String(patch.dailyBudgetAtomics)}, daily_budget_atomics),
+ updated_at = now()
+ WHERE id = ${vaultId}
+ RETURNING ${PUBLIC_COLS}
+ `;
+ return row || null;
+}
+
+/** Add to / open a token position after a buy. */
+export async function upsertPosition({ vaultId, mint, tokenDecimals, amountRawDelta, costDelta, markAtomics = null }) {
+ const [row] = await sql`
+ INSERT INTO vault_positions (vault_id, mint, token_decimals, amount_raw, cost_atomics, last_mark_atomics, status)
+ VALUES (${vaultId}, ${mint}, ${tokenDecimals}, ${String(amountRawDelta)}, ${String(costDelta)}, ${markAtomics == null ? null : String(markAtomics)}, 'open')
+ ON CONFLICT (vault_id, mint) WHERE status = 'open' DO UPDATE SET
+ amount_raw = vault_positions.amount_raw + ${String(amountRawDelta)},
+ cost_atomics = vault_positions.cost_atomics + ${String(costDelta)},
+ token_decimals = ${tokenDecimals},
+ last_mark_atomics = ${markAtomics == null ? sql`vault_positions.last_mark_atomics` : String(markAtomics)},
+ updated_at = now()
+ RETURNING *
+ `;
+ return row;
+}
+
+/** Reduce a position after a sell; closes it when the balance hits zero. */
+export async function reducePosition({ vaultId, mint, amountRawDelta, proceedsAtomics, costRemovedAtomics }) {
+ const [pos] = await sql`SELECT * FROM vault_positions WHERE vault_id = ${vaultId} AND mint = ${mint} AND status = 'open' LIMIT 1`;
+ if (!pos) return null;
+ const remaining = BigInt(pos.amount_raw) - BigInt(amountRawDelta);
+ const realized = BigInt(proceedsAtomics) - BigInt(costRemovedAtomics);
+ if (remaining <= 0n) {
+ const [row] = await sql`
+ UPDATE vault_positions SET
+ amount_raw = 0, cost_atomics = 0,
+ realized_pnl_atomics = realized_pnl_atomics + ${String(realized)},
+ status = 'closed', closed_at = now(), updated_at = now()
+ WHERE id = ${pos.id} RETURNING *
+ `;
+ return row;
+ }
+ const [row] = await sql`
+ UPDATE vault_positions SET
+ amount_raw = ${String(remaining)},
+ cost_atomics = GREATEST(cost_atomics - ${String(costRemovedAtomics)}, 0),
+ realized_pnl_atomics = realized_pnl_atomics + ${String(realized)},
+ updated_at = now()
+ WHERE id = ${pos.id} RETURNING *
+ `;
+ return row;
+}
+
+/** Mark an open position's last NAV contribution (cosmetic cache for the feed). */
+export async function markPosition(positionId, markAtomics) {
+ await sql`UPDATE vault_positions SET last_mark_atomics = ${String(markAtomics)}, updated_at = now() WHERE id = ${positionId}`.catch(() => {});
+}
diff --git a/api/_lib/vault-wallet.js b/api/_lib/vault-wallet.js
new file mode 100644
index 000000000..0ac8cafd6
--- /dev/null
+++ b/api/_lib/vault-wallet.js
@@ -0,0 +1,130 @@
+// @ts-check
+// Back-an-Agent Vaults — the dedicated, segregated custodial wallet + live NAV.
+//
+// Each vault owns its OWN Solana keypair, generated at open and stored
+// AES-256-GCM-encrypted (api/_lib/secret-box.js, the same scheme protecting agent
+// wallets). Backer capital lives in THIS wallet — never the agent's personal
+// wallet, never another vault's — so a fork (a different agent → a different
+// vault) can never co-mingle funds. The secret is decrypted only at signing time
+// (vault-trade.js / vault-transfer.js) and every decrypt is audit-logged.
+
+import { PublicKey, Keypair } from '@solana/web3.js';
+import { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID } from '@solana/spl-token';
+import { encryptSecret, decryptSecret } from './secret-box.js';
+import { solanaConnection } from './agent-pumpfun.js';
+import { logAudit } from './audit.js';
+import { markToUsdc, USDC_MINT_BY_NETWORK } from './vault-jupiter.js';
+import { toBig } from './vault-accounting.js';
+
+const SOL_FEE_HEADROOM_LAMPORTS = 3_000_000n; // ~0.003 SOL kept for fees/ATA rent
+
+function net(network) {
+ return network === 'devnet' ? 'devnet' : 'mainnet';
+}
+
+/** Generate a fresh vault wallet. Returns { address, encrypted_secret }. */
+export async function generateVaultWallet() {
+ const kp = Keypair.generate();
+ const secretB64 = Buffer.from(kp.secretKey).toString('base64');
+ const encrypted_secret = await encryptSecret(secretB64);
+ return { address: kp.publicKey.toBase58(), encrypted_secret };
+}
+
+/**
+ * Recover the vault keypair from its ciphertext, audit-logged. `audit` carries the
+ * vault id + reason so every signing decrypt is traceable in the platform audit log
+ * — mirroring recoverSolanaAgentKeypair's guarantee for agent wallets.
+ */
+export async function recoverVaultKeypair(encryptedSecret, audit = null) {
+ const b64 = await decryptSecret(encryptedSecret);
+ const secret = Buffer.from(b64, 'base64');
+ const kp = Keypair.fromSecretKey(new Uint8Array(secret));
+ if (audit?.vaultId) {
+ logAudit({
+ userId: audit.userId ?? null,
+ action: 'vault.key_use',
+ resourceId: audit.vaultId,
+ meta: { reason: audit.reason || 'sign', address: kp.publicKey.toBase58(), ...(audit.meta || {}) },
+ });
+ }
+ return kp;
+}
+
+/** Raw on-chain USDC balance of the vault wallet, in atomics (BigInt). 0 if no ATA. */
+export async function readVaultUsdcAtomics(address, network = 'mainnet') {
+ const n = net(network);
+ const conn = solanaConnection(n);
+ const owner = new PublicKey(address);
+ const ata = getAssociatedTokenAddressSync(new PublicKey(USDC_MINT_BY_NETWORK[n]), owner, false, TOKEN_PROGRAM_ID);
+ try {
+ const bal = await conn.getTokenAccountBalance(ata);
+ return BigInt(bal?.value?.amount ?? '0');
+ } catch {
+ return 0n; // no ATA yet → zero USDC
+ }
+}
+
+/** Raw on-chain SOL balance of the vault wallet, in lamports (BigInt). */
+export async function readVaultSolLamports(address, network = 'mainnet') {
+ const conn = solanaConnection(net(network));
+ try {
+ return BigInt(await conn.getBalance(new PublicKey(address), 'confirmed'));
+ } catch {
+ return 0n;
+ }
+}
+
+/** True when the vault holds enough SOL to cover a swap's fee + ATA rent buffer. */
+export async function hasSolHeadroom(address, network = 'mainnet') {
+ const lamports = await readVaultSolLamports(address, network);
+ return lamports >= SOL_FEE_HEADROOM_LAMPORTS;
+}
+
+export { SOL_FEE_HEADROOM_LAMPORTS };
+
+/**
+ * Re-derive the vault's NAV from chain + a live mark of every open position.
+ * NAV = on-chain USDC balance + Σ (mark-to-market value of open token positions)
+ *
+ * `freeAtomics` is the liquid USDC available for instant redemption (the rest of
+ * NAV is locked in positions). `priced` is false when one or more positions could
+ * not be marked (Jupiter hiccup) — callers must NOT settle a redemption against an
+ * unpriced NAV, and the breaker must not trip on a transient pricing gap.
+ *
+ * @param {object} vault a vault row (id, vault_address, network)
+ * @param {Array} positions open positions from vault-store.getOpenPositions
+ * @returns {Promise<{ navAtomics:bigint, freeAtomics:bigint, usdcAtomics:bigint,
+ * positions:Array<{ mint:string, amount_raw:string, mark_atomics:string|null }>, priced:boolean }>}
+ */
+export async function computeVaultNav(vault, positions) {
+ const network = net(vault.network);
+ const usdcAtomics = await readVaultUsdcAtomics(vault.vault_address, network);
+ let positionsValue = 0n;
+ let priced = true;
+ const marked = [];
+ for (const p of positions) {
+ const amountRaw = toBig(p.amount_raw);
+ if (amountRaw <= 0n) {
+ marked.push({ mint: p.mint, amount_raw: '0', mark_atomics: '0' });
+ continue;
+ }
+ const mark = await markToUsdc({ network, mint: p.mint, amountRaw });
+ if (mark == null) {
+ priced = false;
+ // Fall back to last known mark or cost so NAV is conservative, not zero.
+ const fallback = p.last_mark_atomics != null ? toBig(p.last_mark_atomics) : toBig(p.cost_atomics);
+ positionsValue += fallback;
+ marked.push({ mint: p.mint, amount_raw: String(amountRaw), mark_atomics: null });
+ } else {
+ positionsValue += mark;
+ marked.push({ mint: p.mint, amount_raw: String(amountRaw), mark_atomics: String(mark) });
+ }
+ }
+ return {
+ navAtomics: usdcAtomics + positionsValue,
+ freeAtomics: usdcAtomics,
+ usdcAtomics,
+ positions: marked,
+ priced,
+ };
+}
diff --git a/api/agent-memory.js b/api/agent-memory.js
index 67801b012..db0ff654e 100644
--- a/api/agent-memory.js
+++ b/api/agent-memory.js
@@ -14,6 +14,7 @@ import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
import { decorateMemory, defaultTier, MEMORY_TIERS } from './_lib/memory-store.js';
+import { signMemoryWithAgent } from './_lib/brain-sign.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
@@ -59,6 +60,7 @@ async function handleList(req, res) {
? await sql`
SELECT id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
(embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ content_hash, signature, signer_address, signed_at, storage_mode, ipfs_cid,
created_at, updated_at, last_accessed_at, expires_at
FROM agent_memories
WHERE agent_id = ${agentId}
@@ -71,6 +73,7 @@ async function handleList(req, res) {
: await sql`
SELECT id, agent_id, type, content, tags, context, salience, tier, pinned, embedder,
(embedding IS NOT NULL) AS has_embedding, access_count, is_public,
+ content_hash, signature, signer_address, signed_at, storage_mode, ipfs_cid,
created_at, updated_at, last_accessed_at, expires_at
FROM agent_memories
WHERE agent_id = ${agentId}
@@ -179,7 +182,28 @@ async function handleUpsert(req, res) {
// client generates a new ID instead of silently losing the write.
if (!row) return error(res, 409, 'id_conflict', 'memory id already in use');
- return json(res, 201, { entry: decorateMemory(row) });
+ // Sign the committed memory with the agent's wallet (ERC-191) so its
+ // authorship + integrity are publicly verifiable. Best-effort: an agent
+ // without a provisioned wallet stores the memory unsigned (with its
+ // content_hash) rather than failing the write — verification reports that
+ // honestly. The signature must cover the *final* row (real id + created_at),
+ // so we sign after the insert and fold the result into the row we return.
+ let signed = { content_hash: undefined, signature: undefined, signer_address: undefined, signed_at: undefined };
+ try {
+ signed = await signMemoryWithAgent(row);
+ } catch (err) {
+ console.error('[agent-memory] signing failed', row.id, err?.message);
+ }
+
+ return json(res, 201, {
+ entry: decorateMemory({
+ ...row,
+ content_hash: signed.content_hash ?? row.content_hash,
+ signature: signed.signature ?? row.signature ?? null,
+ signer_address: signed.signer_address ?? row.signer_address ?? null,
+ signed_at: signed.signed_at ?? row.signed_at ?? null,
+ }),
+ });
}
// ── Delete ────────────────────────────────────────────────────────────────
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 616b61ec0..785f2fddd 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -198,6 +198,11 @@ export default wrap(async function handler(req, res) {
return mod.handlePersona(req, res, id, action);
}
+ if (sub === 'brain') {
+ const mod = await import('./_id/brain.js');
+ return mod.handleBrain(req, res, id, action);
+ }
+
if (sub === 'payments') {
const mod = await import('./_id/payments.js');
return mod.handlePayments(req, res, id);
diff --git a/api/agents/_id/brain.js b/api/agents/_id/brain.js
new file mode 100644
index 000000000..be387a925
--- /dev/null
+++ b/api/agents/_id/brain.js
@@ -0,0 +1,529 @@
+/**
+ * Portable & Verifiable Brain — ownership endpoints.
+ *
+ * GET /api/agents/:id/brain — brain passport: storage mode, signed/
+ * verified counts, pin status + CIDs,
+ * on-chain anchor + drift, persona status.
+ * GET /api/agents/:id/brain/export — download a schema-versioned, signed
+ * .brain bundle (private memories stay
+ * encrypted unless explicitly opted in).
+ * POST /api/agents/:id/brain/verify — verify one memory by id, or a posted
+ * bundle, against its signatures.
+ * POST /api/agents/:id/brain/anchor — anchor the current brain_hash on-chain.
+ * POST /api/agents/:id/brain/storage — set the agent default storage mode and/
+ * or a per-memory override + record a CID.
+ * POST /api/agents/:id/brain/import — reconstitute a bundle into THIS owned
+ * (forked) agent, preserving provenance,
+ * with diff/merge against existing memories.
+ *
+ * All routes are owner-only. Mutations require CSRF. The verify route accepts an
+ * unauthenticated bundle body too (public verification of a shared brain), but
+ * never reveals private content.
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, readJson, error } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { parse } from '../../_lib/validate.js';
+import { z } from 'zod';
+
+import {
+ verifyMemorySignature,
+ memoryDigest,
+ signMemoryWithAgent,
+ loadAgentSigner,
+} from '../../_lib/brain-sign.js';
+import {
+ buildBundle,
+ buildMemoryEntry,
+ verifyBundle,
+ brainBundleSchema,
+} from '../../_lib/brain-bundle.js';
+import {
+ anchorBrain,
+ latestAnchor,
+ BrainAnchorError,
+} from '../../_lib/brain-anchor.js';
+
+const STORAGE_MODES = ['local', 'ipfs', 'encrypted-ipfs', 'none'];
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+async function ownedAgent(id, userId) {
+ const [agent] = await sql`
+ SELECT id, user_id, name, description, avatar_id, chain_id, erc8004_agent_id,
+ wallet_address, memory_storage_mode,
+ persona_prompt, persona_prompt_hash, persona_prompt_sig,
+ persona_tone_tags, persona_extracted_at, meta
+ FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return { agent: null, code: 404 };
+ if (agent.user_id !== userId) return { agent: null, code: 403 };
+ return { agent, code: 200 };
+}
+
+function personaFrom(agent, { includePrompt }) {
+ if (!agent.persona_prompt_hash) return null;
+ return {
+ prompt: includePrompt ? agent.persona_prompt : null,
+ prompt_hash: agent.persona_prompt_hash,
+ prompt_sig: agent.persona_prompt_sig,
+ tone_tags: agent.persona_tone_tags || [],
+ extracted_at: agent.persona_extracted_at
+ ? new Date(agent.persona_extracted_at).toISOString()
+ : null,
+ };
+}
+
+/**
+ * @param {import('http').IncomingMessage} req
+ * @param {import('http').ServerResponse} res
+ * @param {string} id agent id
+ * @param {string} [action] the segment after /brain (export|verify|anchor|storage|import)
+ */
+export async function handleBrain(req, res, id, action) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ // Public bundle verification: POST /brain/verify with a `bundle` body and no
+ // session is allowed — it reveals nothing private.
+ if (req.method === 'POST' && action === 'verify') {
+ const body = await readJson(req);
+ if (body && body.bundle) return verifyPostedBundle(res, body.bundle);
+ // else fall through to authenticated per-memory verify
+ }
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const { agent, code } = await ownedAgent(id, auth.userId);
+ if (!agent) {
+ return code === 403
+ ? error(res, 403, 'forbidden', 'not your agent')
+ : error(res, 404, 'not_found', 'agent not found');
+ }
+
+ if (req.method === 'GET' && !action) return getPassport(res, agent);
+ if (req.method === 'GET' && action === 'export') return exportBundle(req, res, agent);
+
+ // Mutations below require CSRF.
+ if (req.method === 'POST') {
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ if (action === 'verify') return verifyMemory(req, res, agent);
+ if (action === 'anchor') return anchor(req, res, agent);
+ if (action === 'storage') return setStorage(req, res, agent);
+ if (action === 'import') return importBundle(req, res, agent, auth.userId);
+ }
+
+ return error(res, 404, 'not_found', 'unknown brain action');
+}
+
+// ── GET /brain — passport ─────────────────────────────────────────────────────
+
+async function getPassport(res, agent) {
+ const rows = await sql`
+ SELECT id, type, content, tags, salience, tier, is_public,
+ content_hash, signature, signer_address, signed_at, storage_mode, ipfs_cid, created_at
+ FROM agent_memories
+ WHERE agent_id = ${agent.id} AND (expires_at IS NULL OR expires_at > now())
+ `;
+
+ let signed = 0;
+ let verified = 0;
+ let publicCount = 0;
+ let encrypted = 0;
+ for (const r of rows) {
+ if (r.is_public) publicCount++;
+ if (r.ipfs_cid) encrypted++;
+ if (r.signature) {
+ signed++;
+ const v = verifyMemorySignature(r, {
+ signature: r.signature,
+ signer_address: r.signer_address,
+ content_hash: r.content_hash,
+ });
+ if (v.valid) verified++;
+ }
+ }
+
+ const pins = await sql`
+ SELECT cid, filename, bytes, created_at FROM agent_memory_pins
+ WHERE agent_id = ${agent.id}
+ ORDER BY created_at DESC LIMIT 200
+ `;
+
+ let anchorState = { anchor: null, currentBrainHash: null, inSync: false };
+ try {
+ anchorState = await latestAnchor(agent.id);
+ } catch (err) {
+ console.error('[brain] latestAnchor failed', agent.id, err?.message);
+ }
+
+ return json(res, 200, {
+ agent: {
+ id: agent.id,
+ name: agent.name,
+ wallet_address: agent.wallet_address,
+ chain_id: agent.chain_id,
+ erc8004_agent_id: agent.erc8004_agent_id != null ? String(agent.erc8004_agent_id) : null,
+ registered_onchain: agent.erc8004_agent_id != null,
+ },
+ storage_mode: agent.memory_storage_mode || 'local',
+ persona: agent.persona_prompt_hash
+ ? {
+ has_persona: true,
+ prompt_hash: agent.persona_prompt_hash,
+ tone_tags: agent.persona_tone_tags || [],
+ extracted_at: agent.persona_extracted_at,
+ }
+ : { has_persona: false },
+ memories: {
+ total: rows.length,
+ public: publicCount,
+ private: rows.length - publicCount,
+ signed,
+ verified,
+ unsigned: rows.length - signed,
+ encrypted_pinned: encrypted,
+ },
+ pins: pins.map((p) => ({
+ cid: p.cid,
+ filename: p.filename,
+ bytes: p.bytes,
+ created_at: p.created_at,
+ gateway_url: `https://dweb.link/ipfs/${p.cid}`,
+ })),
+ anchor: anchorState.anchor,
+ current_brain_hash: anchorState.currentBrainHash,
+ anchor_in_sync: anchorState.inSync,
+ provenance: agent.meta?.brain_provenance || null,
+ });
+}
+
+// ── GET /brain/export ───────────────────────────────────────────────────────
+
+async function exportBundle(req, res, agent) {
+ const url = new URL(req.url, 'http://x');
+ const includePrivate = url.searchParams.get('includePrivate') === 'true';
+ const publicOnly = url.searchParams.get('publicOnly') === 'true';
+
+ const rows = await sql`
+ SELECT id, agent_id, type, content, tags, salience, tier, is_public,
+ content_hash, signature, signer_address, signed_at, storage_mode, ipfs_cid, created_at
+ FROM agent_memories
+ WHERE agent_id = ${agent.id} AND (expires_at IS NULL OR expires_at > now())
+ ${publicOnly ? sql`AND is_public = true` : sql``}
+ ORDER BY created_at ASC
+ `;
+
+ // Encrypted private memories travel as a CID reference (ciphertext stays on
+ // IPFS, key never leaves the owner's wallet).
+ const cipherRefs = new Map();
+ for (const r of rows) {
+ if (!r.is_public && r.ipfs_cid) {
+ cipherRefs.set(String(r.id), { cid: r.ipfs_cid, filename: `${r.id}.enc` });
+ }
+ }
+
+ const memoryEntries = rows
+ .map((r) => buildMemoryEntry(r, { includePrivatePlaintext: includePrivate, cipherRefs }))
+ .filter(Boolean);
+
+ // Sign the bundle with the agent wallet when available.
+ let signerPrivKey = null;
+ try {
+ const signer = await loadAgentSigner(agent.id, { agentId: agent.id, reason: 'brain_export' });
+ if (signer) signerPrivKey = signer.privKey;
+ } catch (err) {
+ console.error('[brain] export signer load failed', agent.id, err?.message);
+ }
+
+ const bundle = await buildBundle({
+ agent,
+ persona: personaFrom(agent, { includePrompt: true }),
+ memoryEntries,
+ anchor: await safeAnchorForExport(agent.id),
+ exportedAt: new Date().toISOString(),
+ signerPrivKey,
+ });
+
+ const filename = `${(agent.name || 'agent').replace(/[^a-z0-9]+/gi, '-').toLowerCase()}-${agent.id.slice(0, 8)}.brain.json`;
+ res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
+ return json(res, 200, bundle);
+}
+
+async function safeAnchorForExport(agentId) {
+ try {
+ const { anchor } = await latestAnchor(agentId);
+ if (!anchor) return null;
+ return {
+ brain_hash: anchor.brain_hash,
+ proof_uri: anchor.proof_uri || undefined,
+ proof_hash: anchor.proof_hash || undefined,
+ tx_hash: anchor.tx_hash || undefined,
+ chain_id: anchor.chain_id || undefined,
+ anchored_at: anchor.anchored_at ? new Date(anchor.anchored_at).toISOString() : undefined,
+ explorer_url: anchor.explorer_url || null,
+ };
+ } catch {
+ return null;
+ }
+}
+
+// ── POST /brain/verify ──────────────────────────────────────────────────────
+
+const verifyBody = z.object({ memoryId: z.string().uuid() });
+
+async function verifyMemory(req, res, agent) {
+ const body = parse(verifyBody, await readJson(req));
+ const [row] = await sql`
+ SELECT id, agent_id, type, content, tags, content_hash, signature, signer_address, signed_at
+ FROM agent_memories WHERE id = ${body.memoryId} AND agent_id = ${agent.id}
+ `;
+ if (!row) return error(res, 404, 'not_found', 'memory not found');
+
+ const v = verifyMemorySignature(row, {
+ signature: row.signature,
+ signer_address: row.signer_address,
+ content_hash: row.content_hash,
+ });
+
+ // Cross-check the recovered signer against the agent's known wallet — a
+ // signature can be valid yet authored by a different key.
+ const matchesAgentWallet =
+ v.recovered && agent.wallet_address
+ ? v.recovered.toLowerCase() === agent.wallet_address.toLowerCase()
+ : null;
+
+ return json(res, 200, {
+ memoryId: row.id,
+ valid: v.valid,
+ reason: v.reason,
+ recovered_signer: v.recovered,
+ expected_signer: row.signer_address || null,
+ matches_agent_wallet: matchesAgentWallet,
+ current_hash: v.digest,
+ stored_hash: row.content_hash || null,
+ });
+}
+
+function verifyPostedBundle(res, bundle) {
+ const result = verifyBundle(bundle);
+ return json(res, 200, result);
+}
+
+// ── POST /brain/anchor ──────────────────────────────────────────────────────
+
+const anchorReq = z.object({ publicOnly: z.boolean().optional() });
+
+async function anchor(req, res, agent) {
+ const body = parse(anchorReq, (await readJson(req)) || {});
+ try {
+ const result = await anchorBrain({
+ agentId: agent.id,
+ anchoredAt: new Date().toISOString(),
+ publicOnly: body.publicOnly === true,
+ });
+ return json(res, 200, {
+ ok: true,
+ brain_hash: result.brain_hash,
+ tx_hash: result.tx_hash,
+ proof_uri: result.proof_uri,
+ chain_id: result.chain_id,
+ explorer_url: result.explorer_url,
+ anchored_at: result.anchored_at,
+ });
+ } catch (err) {
+ if (err instanceof BrainAnchorError) {
+ // Honest, actionable failure — never a fake success.
+ const status = err.code === 'not_registered' ? 409 : 502;
+ return error(res, status, err.code, err.message);
+ }
+ console.error('[brain] anchor failed', agent.id, err?.message);
+ return error(res, 500, 'anchor_failed', 'could not anchor brain');
+ }
+}
+
+// ── POST /brain/storage ─────────────────────────────────────────────────────
+
+const storageReq = z.object({
+ defaultMode: z.enum(STORAGE_MODES).optional(),
+ memoryId: z.string().uuid().optional(),
+ memoryMode: z.enum(STORAGE_MODES).nullable().optional(),
+ // When the client has pinned an encrypted copy, it records the CID here.
+ cid: z.string().min(1).max(120).optional(),
+});
+
+async function setStorage(req, res, agent) {
+ const body = parse(storageReq, await readJson(req));
+
+ if (body.defaultMode) {
+ await sql`
+ UPDATE agent_identities SET memory_storage_mode = ${body.defaultMode}, updated_at = now()
+ WHERE id = ${agent.id}
+ `;
+ }
+
+ if (body.memoryId) {
+ const [mem] = await sql`SELECT id FROM agent_memories WHERE id = ${body.memoryId} AND agent_id = ${agent.id}`;
+ if (!mem) return error(res, 404, 'not_found', 'memory not found');
+ await sql`
+ UPDATE agent_memories
+ SET storage_mode = ${body.memoryMode ?? null},
+ ipfs_cid = ${body.cid ?? sql`ipfs_cid`}
+ WHERE id = ${body.memoryId} AND agent_id = ${agent.id}
+ `;
+ }
+
+ const [updated] = await sql`SELECT memory_storage_mode FROM agent_identities WHERE id = ${agent.id}`;
+ return json(res, 200, { ok: true, storage_mode: updated.memory_storage_mode });
+}
+
+// ── POST /brain/import ──────────────────────────────────────────────────────
+
+const importReq = z.object({
+ bundle: brainBundleSchema,
+ strategy: z.enum(['merge', 'replace']).default('merge'),
+ importPersona: z.boolean().default(false),
+});
+
+async function importBundle(req, res, agent, userId) {
+ const body = parse(importReq, await readJson(req));
+ const bundle = body.bundle;
+
+ // Reject a bundle that fails its own integrity check before it can
+ // reconstitute a broken or forged mind.
+ const verdict = verifyBundle(bundle);
+ if (!verdict.schemaValid) {
+ return error(res, 422, 'invalid_bundle', `bundle failed schema validation: ${verdict.errors.join('; ')}`);
+ }
+ if (!verdict.brainHashValid) {
+ return error(res, 422, 'integrity_failed', 'bundle brain_hash does not match its memory set');
+ }
+ if (verdict.bundleSignatureValid === false) {
+ return error(res, 422, 'integrity_failed', 'bundle signature failed verification');
+ }
+ // A forged plaintext memory (signed but tampered) is a hard reject.
+ const forged = verdict.memories.find((m) => m.signed && !m.valid && m.reason !== 'encrypted');
+ if (forged) {
+ return error(res, 422, 'integrity_failed', `memory ${forged.id} has an invalid signature (${forged.reason})`);
+ }
+
+ // Diff against the target agent's existing memories (by content_hash) so a
+ // merge is idempotent and the response is a real, reviewable diff.
+ const existing = await sql`
+ SELECT content_hash FROM agent_memories WHERE agent_id = ${agent.id} AND content_hash IS NOT NULL
+ `;
+ const existingHashes = new Set(existing.map((r) => r.content_hash?.toLowerCase()).filter(Boolean));
+
+ if (body.strategy === 'replace') {
+ await sql`DELETE FROM agent_memories WHERE agent_id = ${agent.id}`;
+ existingHashes.clear();
+ }
+
+ // Only plaintext memories can be reconstituted here — encrypted entries
+ // require the owner's key client-side and are reported as skipped.
+ const toImport = bundle.memories.filter((m) => typeof m.content === 'string');
+ const skippedEncrypted = bundle.memories.length - toImport.length;
+
+ let imported = 0;
+ let duplicates = 0;
+ const newSignings = [];
+
+ for (const m of toImport) {
+ const hash = (m.content_hash || memoryDigest({ id: m.id, agent_id: bundle.agent.id, type: m.type, content: m.content, tags: m.tags, created_at: m.created_at })).toLowerCase();
+ if (existingHashes.has(hash)) {
+ duplicates++;
+ continue;
+ }
+ existingHashes.add(hash);
+
+ // Preserve the original authorship as provenance; the new agent re-signs
+ // for its own chain of custody (handled after insert).
+ const provenance = {
+ source_agent_id: bundle.agent.id,
+ source_memory_id: m.id,
+ source_content_hash: m.content_hash || null,
+ source_signature: m.signature || null,
+ source_signer_address: m.signer_address || null,
+ };
+
+ const [row] = await sql`
+ INSERT INTO agent_memories
+ (agent_id, type, content, tags, context, salience, tier, is_public, created_at)
+ VALUES (
+ ${agent.id}, ${m.type}, ${String(m.content).slice(0, 10000)}, ${m.tags || []},
+ ${JSON.stringify({ provenance })}::jsonb, ${m.salience ?? 0.5},
+ ${m.tier || 'recall'}, ${m.is_public === true}, now()
+ )
+ RETURNING id, agent_id, type, content, tags, created_at
+ `;
+ imported++;
+ newSignings.push(row);
+ }
+
+ // Re-sign imported memories under the new agent's wallet (best-effort).
+ for (const row of newSignings) {
+ try {
+ await signMemoryWithAgent(row);
+ } catch (err) {
+ console.error('[brain] import re-sign failed', row.id, err?.message);
+ }
+ }
+
+ // Optionally adopt the source persona (only if the target has none, unless
+ // replace strategy). Persona prompt is signed with the platform HMAC the same
+ // way the persona extractor does — but we keep the source hash as provenance.
+ let personaImported = false;
+ if (body.importPersona && bundle.persona?.prompt) {
+ const adopt = body.strategy === 'replace' || !agent.persona_prompt_hash;
+ if (adopt) {
+ await sql`
+ UPDATE agent_identities
+ SET persona_prompt = ${bundle.persona.prompt},
+ persona_prompt_hash = ${bundle.persona.prompt_hash || null},
+ persona_tone_tags = ${JSON.stringify(bundle.persona.tone_tags || [])}::jsonb,
+ persona_extracted_at = now(),
+ updated_at = now()
+ WHERE id = ${agent.id}
+ `;
+ personaImported = true;
+ }
+ }
+
+ // Record provenance on the agent so the fork's lineage is legible.
+ const meta = { ...(agent.meta || {}) };
+ meta.brain_provenance = {
+ source_agent_id: bundle.agent.id,
+ source_agent_name: bundle.agent.name || null,
+ source_brain_hash: bundle.manifest.brain_hash,
+ imported_at: new Date().toISOString(),
+ imported_count: imported,
+ strategy: body.strategy,
+ };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agent.id}`;
+
+ return json(res, 200, {
+ ok: true,
+ imported,
+ duplicates,
+ skipped_encrypted: skippedEncrypted,
+ persona_imported: personaImported,
+ strategy: body.strategy,
+ provenance: meta.brain_provenance,
+ verification: { verifiedCount: verdict.verifiedCount, signedCount: verdict.signedCount },
+ });
+}
+
+export default function handler(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean); // api agents :id brain [action]
+ return handleBrain(req, res, parts[2], parts[4]);
+}
diff --git a/api/autopilot/activity.js b/api/autopilot/activity.js
new file mode 100644
index 000000000..08ddb30a3
--- /dev/null
+++ b/api/autopilot/activity.js
@@ -0,0 +1,114 @@
+// /api/autopilot/activity — the signed receipts feed (owner-only).
+//
+// GET ?agentId=&limit=&cursor= → { receipts, trust, agents }
+// Every autonomous action the agent took, newest first, each with:
+// • the signed agent_actions row (signature + signer when present)
+// • its full explanation (rationale) and outcome (created rule / tx / briefing)
+// • the source memories it was grounded in (provenance), hydrated for linking
+// Omit agentId to aggregate across all of the caller's agents.
+//
+// This reads the real, append-only agent_actions log — the same provenance trail
+// every other surface writes to. No mocks. $THREE is the only coin referenced.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { computeTrust } from '../_lib/autopilot.js';
+
+const AUTOPILOT_TYPES = ['autopilot.alert.created', 'autopilot.briefing.authored', 'autopilot.wallet.transfer'];
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
+ const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
+ const cursorRaw = url.searchParams.get('cursor');
+ if (cursorRaw != null && !/^\d+$/.test(cursorRaw)) return error(res, 400, 'validation_error', 'cursor must be numeric');
+ const cursor = cursorRaw || null;
+
+ // Resolve the set of agents to read. A specific agent must be owned by caller;
+ // otherwise aggregate across all of the caller's agents.
+ let agentIds;
+ if (agentId) {
+ const [agent] = await sql`SELECT id, user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ agentIds = [agentId];
+ } else {
+ const owned = await sql`SELECT id FROM agent_identities WHERE user_id = ${auth.userId} AND deleted_at IS NULL`;
+ agentIds = owned.map((a) => a.id);
+ }
+
+ const agents = await sql`
+ SELECT id, name, avatar_id FROM agent_identities WHERE id = ANY(${agentIds}::uuid[])
+ `;
+ const agentById = new Map(agents.map((a) => [a.id, { id: a.id, name: a.name, avatarId: a.avatar_id }]));
+
+ if (!agentIds.length) {
+ return json(res, 200, { receipts: [], next_cursor: null, agents: [], trust: null });
+ }
+
+ const rows = cursor
+ ? await sql`
+ SELECT * FROM agent_actions
+ WHERE agent_id = ANY(${agentIds}::uuid[]) AND type = ANY(${AUTOPILOT_TYPES}) AND id < ${cursor}
+ ORDER BY id DESC LIMIT ${limit + 1}`
+ : await sql`
+ SELECT * FROM agent_actions
+ WHERE agent_id = ANY(${agentIds}::uuid[]) AND type = ANY(${AUTOPILOT_TYPES})
+ ORDER BY id DESC LIMIT ${limit + 1}`;
+
+ const hasMore = rows.length > limit;
+ const page = hasMore ? rows.slice(0, limit) : rows;
+ const nextCursor = hasMore ? String(page[page.length - 1].id) : null;
+
+ // Hydrate the cited source memories across the page so the UI can link them.
+ const memIds = [...new Set(page.flatMap((r) => (r.payload?.source_memory_ids || [])))];
+ const memRows = memIds.length
+ ? await sql`SELECT id, agent_id, type, content, salience FROM agent_memories WHERE id = ANY(${memIds}::uuid[])`
+ : [];
+ const memById = new Map(memRows.map((m) => [m.id, { id: m.id, agentId: m.agent_id, type: m.type, content: m.content, salience: Number(m.salience) }]));
+
+ const receipts = page.map((r) => {
+ const p = r.payload || {};
+ return {
+ id: String(r.id),
+ agentId: r.agent_id,
+ agent: agentById.get(r.agent_id) || { id: r.agent_id, name: 'Agent' },
+ type: r.type,
+ kind: r.type.replace('autopilot.', '').replace('.', '_'),
+ rationale: p.rationale || null,
+ result: stripProvenance(p),
+ proposalId: p.proposal_id || null,
+ sourceReflectionId: p.source_reflection_id || null,
+ sources: (p.source_memory_ids || []).map((id) => memById.get(id) || { id, forgotten: true }),
+ signed: Boolean(r.signature),
+ signature: r.signature || null,
+ signerAddress: r.signer_address || null,
+ at: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at,
+ };
+ });
+
+ const trust = agentId ? await computeTrust({ agentId }) : null;
+ return json(res, 200, { receipts, next_cursor: nextCursor, agents: [...agentById.values()], trust });
+});
+
+// The receipt's "what happened" — payload minus the provenance fields the UI
+// renders separately (rationale + source ids + ids/ts).
+function stripProvenance(payload) {
+ const { rationale, source_memory_ids, source_reflection_id, proposal_id, ts, ...rest } = payload || {};
+ return rest;
+}
diff --git a/api/autopilot/config.js b/api/autopilot/config.js
new file mode 100644
index 000000000..94ef24b3e
--- /dev/null
+++ b/api/autopilot/config.js
@@ -0,0 +1,76 @@
+// /api/autopilot/config — the agent's autopilot permission/scope model (owner-only).
+//
+// GET ?agentId= → { config, trust }
+// POST { agentId, ...patch } → { config } (patch: enabled, scopes, auto_execute,
+// daily_spend_three, require_confirm)
+//
+// Scope lives on agent_identities.meta.autopilot and is enforced server-side at
+// execution time (api/_lib/autopilot.js). Nothing the agent does is possible
+// without a scope the owner granted here. $THREE is the only coin referenced.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { getAutopilotConfig, setAutopilotConfig, computeTrust } from '../_lib/autopilot.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+async function ownedAgent(req, res, agentId, auth) {
+ if (!agentId) {
+ error(res, 400, 'validation_error', 'agentId required');
+ return null;
+ }
+ const [agent] = await sql`
+ SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) {
+ error(res, 404, 'not_found', 'agent not found');
+ return null;
+ }
+ if (agent.user_id !== auth.userId) {
+ error(res, 403, 'forbidden', 'not your agent');
+ return null;
+ }
+ return agent;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ if (req.method === 'GET') {
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
+ const agent = await ownedAgent(req, res, agentId, auth);
+ if (!agent) return;
+ const config = getAutopilotConfig(agent.meta);
+ const trust = await computeTrust({ agentId });
+ return json(res, 200, { config, trust });
+ }
+
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ const body = await readJson(req);
+ const agentId = body.agentId || body.agent_id;
+ const agent = await ownedAgent(req, res, agentId, auth);
+ if (!agent) return;
+
+ const patch = {};
+ if ('enabled' in body) patch.enabled = body.enabled === true;
+ if (body.scopes && typeof body.scopes === 'object') patch.scopes = body.scopes;
+ if (body.auto_execute && typeof body.auto_execute === 'object') patch.auto_execute = body.auto_execute;
+ if ('daily_spend_three' in body) patch.daily_spend_three = body.daily_spend_three;
+ if ('require_confirm' in body) patch.require_confirm = body.require_confirm === true;
+
+ const config = await setAutopilotConfig(agentId, patch);
+ return json(res, 200, { config });
+});
diff --git a/api/autopilot/proposals.js b/api/autopilot/proposals.js
new file mode 100644
index 000000000..a41c11fd6
--- /dev/null
+++ b/api/autopilot/proposals.js
@@ -0,0 +1,162 @@
+// /api/autopilot/proposals — the proposal queue: generate, review, act (owner-only).
+//
+// GET ?agentId=&status=pending → { proposals, trust, config }
+// Each proposal carries its provenance (cited memories hydrated) so the UI
+// can show + link the evidence.
+//
+// POST { agentId, action, ... }
+// action = 'generate' → run the mind: produce real proposals from high-salience
+// memories + pending dreams. → { created, source, trust }
+// action = 'dryrun' → { proposalId } non-mutating preview of what executing does.
+// action = 'execute' → { proposalId, confirm? } take the real action (scope +
+// confirmation enforced). → { proposal, receipt, action }
+// action = 'dismiss' → { proposalId } drop it; records a feedback memory.
+// action = 'undo' → { proposalId } reverse a reversible executed action;
+// records a feedback memory (the agent learns the boundary).
+// action = 'adjust' → { proposalId, params } edit a pending proposal's params.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import {
+ generateProposals, executeProposal, dismissProposal, undoProposal, dryRunProposal,
+ computeTrust, getAutopilotConfig, decorateProposal, validateProposal, AutopilotError,
+} from '../_lib/autopilot.js';
+
+export const maxDuration = 60;
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+async function ownedAgent(req, res, agentId, auth) {
+ if (!agentId) {
+ error(res, 400, 'validation_error', 'agentId required');
+ return null;
+ }
+ const [agent] = await sql`
+ SELECT id, user_id, name, description, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) {
+ error(res, 404, 'not_found', 'agent not found');
+ return null;
+ }
+ if (agent.user_id !== auth.userId) {
+ error(res, 403, 'forbidden', 'not your agent');
+ return null;
+ }
+ return agent;
+}
+
+// Hydrate the cited source memories so the UI can show + link the evidence.
+async function attachSources(agentId, proposals) {
+ const ids = [...new Set(proposals.flatMap((p) => p.sourceMemoryIds || []))];
+ const rows = ids.length
+ ? await sql`SELECT id, type, content, salience FROM agent_memories WHERE agent_id = ${agentId} AND id = ANY(${ids}::uuid[])`
+ : [];
+ const byId = new Map(rows.map((m) => [m.id, { id: m.id, type: m.type, content: m.content, salience: Number(m.salience) }]));
+ return proposals.map((p) => ({
+ ...p,
+ sources: (p.sourceMemoryIds || []).map((id) => byId.get(id) || { id, forgotten: true }),
+ }));
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ if (req.method === 'GET') return handleList(req, res, auth);
+ return handleAct(req, res, auth);
+});
+
+async function handleList(req, res, auth) {
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
+ const status = url.searchParams.get('status');
+ const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
+
+ const agent = await ownedAgent(req, res, agentId, auth);
+ if (!agent) return;
+
+ const rows = ['pending', 'executed', 'dismissed', 'undone', 'failed'].includes(status)
+ ? await sql`SELECT * FROM agent_autopilot_proposals WHERE agent_id = ${agentId} AND status = ${status} ORDER BY created_at DESC LIMIT ${limit}`
+ : await sql`SELECT * FROM agent_autopilot_proposals WHERE agent_id = ${agentId} ORDER BY created_at DESC LIMIT ${limit}`;
+
+ const proposals = await attachSources(agentId, rows.map(decorateProposal));
+ const trust = await computeTrust({ agentId });
+ return json(res, 200, { proposals, trust, config: getAutopilotConfig(agent.meta) });
+}
+
+async function handleAct(req, res, auth) {
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
+ const body = await readJson(req);
+ const agentId = body.agentId || body.agent_id;
+ const action = body.action;
+
+ const agent = await ownedAgent(req, res, agentId, auth);
+ if (!agent) return;
+
+ if (action === 'generate') {
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'too many generation requests');
+ const result = await generateProposals({ agentId, userId: auth.userId, agent: { name: agent.name, description: agent.description } });
+ const created = await attachSources(agentId, result.created);
+ const trust = await computeTrust({ agentId });
+ return json(res, 200, { created, source: result.source, scanned: result.scanned, trust });
+ }
+
+ // All remaining actions operate on a specific proposal.
+ const proposalId = body.proposalId || body.proposal_id;
+ if (!proposalId) return error(res, 400, 'validation_error', 'proposalId required');
+ const [row] = await sql`SELECT * FROM agent_autopilot_proposals WHERE id = ${proposalId} AND agent_id = ${agentId}`;
+ if (!row) return error(res, 404, 'not_found', 'proposal not found');
+ const proposal = decorateProposal(row);
+
+ try {
+ if (action === 'dryrun') {
+ const preview = await dryRunProposal({ proposal, agent, config: getAutopilotConfig(agent.meta) });
+ return json(res, 200, { preview });
+ }
+ if (action === 'execute') {
+ const result = await executeProposal({
+ proposal, agent, userId: auth.userId, meta: agent.meta, confirmed: body.confirm === true,
+ });
+ const trust = await computeTrust({ agentId });
+ return json(res, 200, { ...result, trust });
+ }
+ if (action === 'dismiss') {
+ await dismissProposal({ proposal, agentId, userId: auth.userId });
+ const [updated] = await sql`SELECT * FROM agent_autopilot_proposals WHERE id = ${proposalId}`;
+ return json(res, 200, { proposal: decorateProposal(updated), trust: await computeTrust({ agentId }) });
+ }
+ if (action === 'undo') {
+ await undoProposal({ proposal, agentId, userId: auth.userId });
+ const [updated] = await sql`SELECT * FROM agent_autopilot_proposals WHERE id = ${proposalId}`;
+ return json(res, 200, { proposal: decorateProposal(updated), trust: await computeTrust({ agentId }) });
+ }
+ if (action === 'adjust') {
+ if (proposal.status !== 'pending') return error(res, 409, 'not_pending', 'only a pending proposal can be adjusted');
+ const v = validateProposal(proposal.kind, body.params || {});
+ if (!v.ok) return error(res, 400, 'validation_error', v.reason);
+ const [updated] = await sql`
+ UPDATE agent_autopilot_proposals SET params = ${JSON.stringify(v.params)}::jsonb
+ WHERE id = ${proposalId} AND status = 'pending' RETURNING *
+ `;
+ return json(res, 200, { proposal: decorateProposal(updated) });
+ }
+ return error(res, 400, 'validation_error', "action must be one of: generate, dryrun, execute, dismiss, undo, adjust");
+ } catch (err) {
+ if (err instanceof AutopilotError) return error(res, err.status, err.code, err.message);
+ throw err;
+ }
+}
diff --git a/api/chat.js b/api/chat.js
index 9b284101c..a88abc427 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -50,6 +50,7 @@ import {
TOTAL_BUDGET_MS,
PER_CALL_TIMEOUT_MS,
} from './_lib/chat-models.js';
+import { computeContext, searchMemories } from './_lib/memory-store.js';
import { z } from 'zod';
// Providers anonymous (unauthenticated) callers may use. Groq and OpenRouter
@@ -439,6 +440,7 @@ export default wrap(async (req, res) => {
);
let personaPrompt = null;
+ let isOwner = false;
if (body.agentId) {
// Persona prompts are private IP: only serve them for published agents,
// or to the agent's owner. Anonymous callers get published personas only.
@@ -448,6 +450,7 @@ export default wrap(async (req, res) => {
AND (is_published = true OR user_id = ${auth?.userId ?? null})
LIMIT 1
`;
+ isOwner = Boolean(auth?.userId && agentRow?.user_id === auth.userId);
// Brain Studio preview: the owner may audition an unsaved compiled persona.
// The override only applies to the agent's owner — never published-agent
// visitors — so it can't be used to inject a prompt into someone's agent.
@@ -459,7 +462,25 @@ export default wrap(async (req, res) => {
}
if (!personaPrompt && body.system_prompt) personaPrompt = body.system_prompt;
- const systemPrompt = buildSystemPrompt(body.context, personaPrompt);
+ // Real memory recall: surface the agent's always-in-context core (pinned /
+ // working tier) plus the memories most relevant to THIS message, inject them
+ // into the system prompt so they actually shape the reply, and report exactly
+ // which ones were used in the `done` event (the client emits `memory:recalled`
+ // from that). The owner sees all their memories; a third party chatting with a
+ // published agent sees only its public memories. Best-effort: a memory-store
+ // hiccup degrades to a memory-less reply, never a failed chat.
+ let recalledMemories = [];
+ let recalledSemantic = false;
+ if (body.agentId) {
+ try {
+ recalledMemories = await recallForChat(body.agentId, body.message, isOwner);
+ recalledSemantic = recalledMemories.some((m) => m.match === 'semantic');
+ } catch (err) {
+ captureException(err, { route: 'chat', stage: 'recall', agentId: body.agentId });
+ }
+ }
+
+ const systemPrompt = buildSystemPrompt(body.context, personaPrompt, recalledMemories);
const history = body.history.map((m) => ({ role: m.role, content: m.content }));
history.push({ role: 'user', content: body.message });
@@ -820,6 +841,11 @@ export default wrap(async (req, res) => {
governance,
model: route.model,
provider: route.name,
+ // Exactly the memories the server injected into this reply's context — the
+ // client emits `memory:recalled` from this. Empty when nothing was recalled.
+ recalled: recalledMemories,
+ recalledSemantic,
+ recalledTs: new Date().toISOString(),
});
res.end();
@@ -1264,7 +1290,44 @@ function parseToolJson(name, jsonText) {
// ── System prompt + auth + helpers ───────────────────────────────────────────
-function buildSystemPrompt(ctx = {}, personaPrompt = null) {
+// Pull the memories that should ground THIS reply: the agent's always-in-context
+// core (pinned + working tier, via computeContext) merged with the memories most
+// relevant to the user's message (semantic + lexical, via searchMemories). The
+// owner sees everything; a visitor to a published agent sees only public
+// memories. Returns the compact shape the `done` event and the client bus event
+// share — id, type, tier, salience, a display snippet, and how it surfaced.
+async function recallForChat(agentId, message, isOwner) {
+ const visible = (m) => isOwner || m.isPublic;
+ const [ctx, search] = await Promise.all([
+ computeContext(agentId).catch(() => ({ entries: [] })),
+ searchMemories(agentId, message, { topK: 6 }).catch(() => ({ results: [] })),
+ ]);
+
+ const byId = new Map();
+ for (const m of ctx.entries || []) {
+ if (visible(m)) byId.set(m.id, { row: m, match: 'context' });
+ }
+ for (const m of search.results || []) {
+ if (!visible(m)) continue;
+ // A search hit on a core memory keeps the more specific match label.
+ const prev = byId.get(m.id);
+ byId.set(m.id, { row: m, match: m.match || prev?.match || 'lexical' });
+ }
+
+ return [...byId.values()]
+ .sort((a, b) => (b.row.salience || 0) - (a.row.salience || 0))
+ .slice(0, 10)
+ .map(({ row, match }) => ({
+ id: row.id,
+ type: row.type,
+ tier: row.tier,
+ salience: row.salience,
+ snippet: String(row.content || '').replace(/\s+/g, ' ').trim().slice(0, 160),
+ match,
+ }));
+}
+
+function buildSystemPrompt(ctx = {}, personaPrompt = null, recalled = []) {
const loaded = ctx.modelName
? `A model named "${ctx.modelName}" is loaded. Stats: ${fmt(ctx.vertices)} vertices, ${fmt(ctx.triangles)} triangles, ${fmt(ctx.materials)} materials, ${ctx.animations ?? 0} animations.`
: 'No model is currently loaded in the viewer.';
@@ -1276,6 +1339,13 @@ function buildSystemPrompt(ctx = {}, personaPrompt = null) {
const lines = [];
if (personaPrompt) lines.push(personaPrompt, '');
+ if (Array.isArray(recalled) && recalled.length) {
+ lines.push(
+ 'What you remember (recalled for this conversation — speak from it naturally, never read it back verbatim or mention "memory IDs"):',
+ ...recalled.map((m) => `- (${m.type}) ${m.snippet}`),
+ '',
+ );
+ }
lines.push(
'You are an embodied AI assistant rendered as a 3D avatar at three.ws — the platform for building, embedding, and monetising 3D AI agents.',
'',
diff --git a/data/changelog.json b/data/changelog.json
index c13b8ff49..e57600d6e 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-23",
+ "title": "Alpha Co-pilot: your agent reads a real launch in character and speaks its verdict aloud",
+ "summary": "Trading bots are silent black boxes — your agent isn't. Open the new Alpha Co-pilot, pick a live pump.fun launch, and your agent reads it in character: it pulls the real liquidity, holder concentration, smart-money, age, and price-impact signals, forms a verdict (snipe / watch / pass) with a conviction score, and its 3D avatar speaks the rationale out loud. A cautious persona and an aggressive one genuinely reach different calls on the same coin. Every number it voices is checked against the live data shown beside it — a fabricated figure is rejected and a grounded line spoken instead, never an invented price. If you own the agent, you can act on the call in one tap, but only within your hard spend limits: the buy runs through the same guarded wallet path as the rest of the platform — re-checked against the rug/honeypot firewall and your per-trade and daily caps at submit, and written to the custody audit. Logged-out visitors can hear the public read but can't act.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/alpha-copilot"
+ },
{
"date": "2026-06-23",
"title": "Your agent's Earn tab now shows hire income on its own and ranks your top customers",
diff --git a/data/pages.json b/data/pages.json
index 308135eb7..3b544b120 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -70,6 +70,14 @@
"changefreq": "yearly",
"added": "2026-06-17"
},
+ {
+ "path": "/alpha-copilot",
+ "title": "Alpha Co-pilot — your agent narrates its own alpha",
+ "description": "Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.",
+ "priority": 0.8,
+ "changefreq": "weekly",
+ "added": "2026-06-23"
+ },
{
"path": "/world-lines",
"title": "World Lines — agent proof-of-presence quests",
@@ -594,6 +602,14 @@
"changefreq": "daily",
"added": "2026-06-12"
},
+ {
+ "path": "/theater",
+ "title": "Live Trading Theater",
+ "description": "Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.",
+ "priority": 0.8,
+ "changefreq": "daily",
+ "added": "2026-06-23"
+ },
{
"path": "/pulse",
"title": "Money Pulse",
diff --git a/pages/agent-edit.html b/pages/agent-edit.html
index 09222e69c..02ccf524d 100644
--- a/pages/agent-edit.html
+++ b/pages/agent-edit.html
@@ -1042,6 +1042,9 @@
.dream-card-status { font-size: 0.72rem; margin-top: 0.5rem; min-height: 1em; }
.dream-card-status.err { color: #fca5a5; }
.dream-card-status.ok { color: #86efac; }
+ .link-btn { background: none; border: none; color: #a78bfa; cursor: pointer; font-family: inherit; font-size: inherit; text-decoration: underline; padding: 0; }
+ .link-btn:hover { color: #c4b5fd; }
+ .link-btn:focus-visible { outline: 2px solid rgba(167,139,250,0.6); outline-offset: 2px; }
.dreams-empty { text-align: center; padding: 2.5rem 1rem; color: rgba(255,255,255,0.5); }
.dreams-empty .moon { font-size: 2rem; display: block; margin-bottom: 0.6rem; }
@@ -1197,6 +1200,7 @@
</div>
<div class="edit-sidebar-group">
<div class="edit-sidebar-group-title">Brain</div>
+ <button class="edit-tab" data-tab="brain" role="tab" aria-selected="false" aria-controls="panel-brain" id="tab-brain">Brain Studio</button>
<button class="edit-tab" data-tab="knowledge" role="tab" aria-selected="false" aria-controls="panel-knowledge" id="tab-knowledge">Knowledge</button>
<button class="edit-tab" data-tab="dreams" role="tab" aria-selected="false" aria-controls="panel-dreams" id="tab-dreams">Dreams<span class="tab-badge" id="dreams-tab-badge" hidden aria-hidden="true">0</span></button>
<button class="edit-tab" data-tab="skills" role="tab" aria-selected="false" aria-controls="panel-skills" id="tab-skills">Skills</button>
@@ -1252,6 +1256,19 @@
</div>
</section>
+ <!-- Brain Studio tab -->
+ <section
+ class="edit-panel persona-panel"
+ id="panel-brain"
+ role="tabpanel"
+ aria-labelledby="tab-brain"
+ hidden
+ >
+ <div id="brain-studio-host">
+ <div class="loading-msg" role="status" aria-live="polite">Loading the Brain Studio…</div>
+ </div>
+ </section>
+
<!-- Outfit tab -->
<section
class="edit-panel outfit-panel"
diff --git a/pages/genesis.html b/pages/genesis.html
new file mode 100644
index 000000000..7c15c9024
--- /dev/null
+++ b/pages/genesis.html
@@ -0,0 +1,287 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
+ <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" />
+ <title>Instant Agent Genesis · three.ws</title>
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <meta
+ name="description"
+ content="A prompt or a selfie becomes a 3D AI agent with its own custodial wallet and a verifiable on-chain identity — in under a minute. It's yours from birth."
+ />
+ <meta name="robots" content="index, follow" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/genesis" />
+ <meta property="og:title" content="Instant Agent Genesis · three.ws" />
+ <meta
+ property="og:description"
+ content="Selfie or prompt → 3D agent → funded wallet → tradeable on-chain identity in 60 seconds. Yours from the first frame."
+ />
+ <meta
+ property="og:image"
+ content="https://three.ws/api/page-og?s=build&amp;t=Instant+Agent+Genesis&amp;d=Selfie+or+prompt+%E2%86%92+3D+agent+%E2%86%92+funded+wallet+%E2%86%92+on-chain+identity+in+60s&amp;p=%2Fgenesis"
+ />
+ <meta name="twitter:card" content="summary_large_image" />
+
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/genesis.css" />
+ </head>
+ <body>
+ <a href="#genesis-main" class="skip-link">Skip to genesis</a>
+ <div id="nav-container"></div>
+
+ <main id="genesis-main" class="gx">
+ <header class="gx-head">
+ <span class="gx-eyebrow">60-second genesis</span>
+ <h1 class="gx-title">Instant <em>Agent Genesis</em></h1>
+ <p class="gx-sub">
+ A prompt or a selfie becomes a living 3D agent — with its own custodial
+ wallet and a verifiable on-chain identity. Yours from the first frame.
+ </p>
+ </header>
+
+ <!-- ── STAGE: INPUT ─────────────────────────────────────────────── -->
+ <section class="gx-stage" data-stage="input">
+ <div class="gx-auth" id="gx-auth" hidden>
+ <p>Sign in to claim your agent and its wallet. Genesis writes to <b>your</b> account.</p>
+ <button class="gx-btn gx-btn-primary" id="gx-signin" type="button">Sign in</button>
+ </div>
+
+ <div class="gx-card">
+ <div class="gx-tabs" role="tablist" aria-label="Genesis source">
+ <button class="gx-tab" role="tab" id="gx-tab-text" aria-selected="true" data-mode="text" type="button">
+ <span class="gx-tab-icon" aria-hidden="true">✍️</span>
+ <strong>Describe</strong>
+ <span>Type how your agent looks</span>
+ </button>
+ <button class="gx-tab" role="tab" id="gx-tab-photo" aria-selected="false" data-mode="photo" type="button">
+ <span class="gx-tab-icon" aria-hidden="true">📸</span>
+ <strong>Selfie</strong>
+ <span>A photo becomes the body</span>
+ </button>
+ <button class="gx-tab" role="tab" id="gx-tab-remix" aria-selected="false" data-mode="remix" type="button">
+ <span class="gx-tab-icon" aria-hidden="true">🧬</span>
+ <strong>Remix</strong>
+ <span>Fork a public avatar to own</span>
+ </button>
+ </div>
+
+ <!-- describe -->
+ <div class="gx-panel" data-panel="text">
+ <label class="gx-label" for="gx-prompt">Describe your agent's look</label>
+ <textarea
+ class="gx-input"
+ id="gx-prompt"
+ placeholder="A silver-haired explorer in a teal flight jacket, calm and curious…"
+ maxlength="1000"
+ ></textarea>
+ <p class="gx-hint">Full-body characters work best. We rig it automatically so it can walk and emote.</p>
+ <div class="gx-chips" id="gx-chips" aria-label="Example prompts"></div>
+ <details class="gx-adv">
+ <summary>Advanced — bring your own Meshy key for higher fidelity</summary>
+ <div class="gx-field" style="margin-top: 12px">
+ <input
+ class="gx-input"
+ id="gx-meshy-key"
+ type="password"
+ autocomplete="off"
+ placeholder="msy_… (optional — kept in your browser, sent only with this job)"
+ />
+ <p class="gx-hint">
+ Without a key, genesis uses the platform's avatar engine. A Meshy key routes
+ geometry through your own Meshy credits at higher detail.
+ </p>
+ </div>
+ </details>
+ </div>
+
+ <!-- selfie -->
+ <div class="gx-panel" data-panel="photo" hidden>
+ <label class="gx-label" for="gx-photo-input">Use a photo</label>
+ <label class="gx-drop" id="gx-drop" for="gx-photo-input">
+ <span class="gx-drop-icon" aria-hidden="true">📷</span>
+ <div>Tap to choose a photo, or drag one here</div>
+ <input id="gx-photo-input" type="file" accept="image/*" />
+ </label>
+ <div class="gx-preview" id="gx-photo-preview">
+ <img id="gx-photo-img" alt="Your selected photo" />
+ <button class="gx-btn gx-btn-ghost" id="gx-photo-clear" type="button">Remove</button>
+ </div>
+ <div class="gx-row" style="margin-top: 14px">
+ <div>
+ <label class="gx-label" for="gx-bodytype">Body</label>
+ <select class="gx-input" id="gx-bodytype">
+ <option value="female">Feminine</option>
+ <option value="male">Masculine</option>
+ </select>
+ </div>
+ <div>
+ <label class="gx-label" for="gx-style">Style</label>
+ <select class="gx-input" id="gx-style">
+ <option value="v2">Stylized</option>
+ <option value="v1">Photoreal</option>
+ </select>
+ </div>
+ </div>
+ <p class="gx-privacy">
+ Use a photo of yourself or one you have the right to use. It's processed only to
+ build your avatar, stored privately in your account, and never shared.
+ </p>
+ </div>
+
+ <!-- remix -->
+ <div class="gx-panel" data-panel="remix" hidden>
+ <label class="gx-label">Start from a public avatar — forking mints a fresh wallet you own</label>
+ <div class="gx-remix-grid" id="gx-remix-grid" aria-label="Public avatars to fork">
+ <p class="gx-hint" id="gx-remix-empty">Loading avatars…</p>
+ </div>
+ </div>
+
+ <!-- shared: name + persona + voice -->
+ <div class="gx-field" style="margin-top: 4px">
+ <label class="gx-label" for="gx-name">Name your agent <span style="color: var(--ink-faint); font-weight: 400">(optional)</span></label>
+ <input class="gx-input" id="gx-name" type="text" maxlength="80" placeholder="We'll suggest one if you leave this blank" />
+ </div>
+ <div class="gx-row">
+ <div class="gx-field">
+ <label class="gx-label" for="gx-persona">Persona <span style="color: var(--ink-faint); font-weight: 400">(optional)</span></label>
+ <input class="gx-input" id="gx-persona" type="text" maxlength="600" placeholder="Witty, sharp, talks like a degen trader…" />
+ </div>
+ <div class="gx-field">
+ <label class="gx-label" for="gx-voice">Voice</label>
+ <select class="gx-input" id="gx-voice">
+ <option value="">Browser voice (default)</option>
+ </select>
+ </div>
+ </div>
+
+ <button class="gx-btn gx-btn-primary gx-btn-lg" id="gx-begin" type="button">
+ Begin genesis →
+ </button>
+
+ <div class="gx-explain">
+ <div><strong>3D body</strong>A rigged avatar that walks, idles and emotes.</div>
+ <div><strong>Custodial wallet</strong>A real Solana + EVM wallet, ready to fund &amp; snipe.</div>
+ <div><strong>On-chain identity</strong>An ERC-8004 record — verifiable from birth.</div>
+ </div>
+ </div>
+
+ <div class="gx-error" id="gx-input-error" hidden></div>
+ </section>
+
+ <!-- ── STAGE: FORGING ───────────────────────────────────────────── -->
+ <section class="gx-stage" data-stage="forging" hidden>
+ <div class="gx-forge">
+ <div>
+ <div class="gx-steps" id="gx-steps">
+ <div class="gx-step" data-step="model" data-state="active">
+ <div class="gx-step-dot" aria-hidden="true"></div>
+ <div class="gx-step-body">
+ <strong>Sculpting your 3D body</strong>
+ <small data-role="detail">Warming up the avatar engine…</small>
+ <div class="gx-bar"><i data-role="bar"></i></div>
+ </div>
+ </div>
+ <div class="gx-step" data-step="wallet" data-state="pending">
+ <div class="gx-step-dot" aria-hidden="true"></div>
+ <div class="gx-step-body">
+ <strong>Minting your custodial wallet</strong>
+ <small data-role="detail">Waiting on your agent…</small>
+ </div>
+ </div>
+ <div class="gx-step" data-step="persona" data-state="pending">
+ <div class="gx-step-dot" aria-hidden="true"></div>
+ <div class="gx-step-body">
+ <strong>Shaping persona &amp; voice</strong>
+ <small data-role="detail">Pending…</small>
+ </div>
+ </div>
+ </div>
+ <p class="gx-elapsed" id="gx-elapsed">Elapsed 0s</p>
+ <button class="gx-btn gx-btn-ghost" id="gx-cancel" type="button" style="margin-top: 12px">Cancel</button>
+ </div>
+ <div>
+ <div class="gx-stage-preview" id="gx-forge-preview">
+ <div class="gx-placeholder">
+ <div class="gx-orb" aria-hidden="true"></div>
+ Your agent is taking shape…
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="gx-error" id="gx-forge-error" hidden></div>
+ </section>
+
+ <!-- ── STAGE: REVEAL ────────────────────────────────────────────── -->
+ <section class="gx-stage" data-stage="reveal" hidden>
+ <div class="gx-reveal">
+ <div class="gx-reveal-viewer" id="gx-reveal-viewer"></div>
+ <div>
+ <div class="gx-meet">Meet your agent</div>
+ <h2 class="gx-agent-name" id="gx-reveal-name">Your Agent</h2>
+ <p class="gx-own">This agent, its wallet, and its identity are <b>yours</b> — self-custodial from birth.</p>
+
+ <div class="gx-detail">
+ <div class="gx-detail-h"><span>Custodial wallet</span></div>
+ <div id="gx-wallets"></div>
+ </div>
+
+ <div class="gx-detail">
+ <div class="gx-detail-h">
+ <span>On-chain identity</span>
+ <span class="gx-badge gx-badge-pending" id="gx-identity-badge">Not registered</span>
+ </div>
+ <div id="gx-identity-body">
+ <button class="gx-btn gx-btn-primary" id="gx-register" type="button" style="width: 100%">
+ Register ERC-8004 identity
+ </button>
+ <p class="gx-identity-status" id="gx-identity-status">
+ Connect an EVM wallet to mint a verifiable, tradeable identity. Optional — you can do this anytime.
+ </p>
+ </div>
+ </div>
+
+ <div class="gx-cta-grid">
+ <a class="gx-cta gx-cta-primary" id="gx-cta-fund" href="#">
+ <strong>Fund &amp; snipe →</strong>
+ <span>Top up the wallet and start trading</span>
+ </a>
+ <a class="gx-cta" id="gx-cta-open" href="#">
+ <strong>Open your agent</strong>
+ <span>Its profile, chat &amp; controls</span>
+ </a>
+ <a class="gx-cta" id="gx-cta-copilot" href="/alpha-copilot">
+ <strong>Trading co-pilot</strong>
+ <span>Put your agent to work on alpha</span>
+ </a>
+ <a class="gx-cta" id="gx-cta-share" href="#" target="_blank" rel="noopener">
+ <strong>Share the reveal</strong>
+ <span>A shareable agent card</span>
+ </a>
+ </div>
+
+ <button class="gx-btn gx-btn-ghost gx-btn-lg" id="gx-again" type="button" style="margin-top: 16px">
+ Spin up another agent
+ </button>
+ </div>
+ </div>
+ </section>
+ </main>
+
+ <script type="module" src="/model-viewer-meshopt.js"></script>
+ <script type="module" src="/src/genesis.js"></script>
+ <script src="/nav.js" defer></script>
+ <script src="/theme-switcher.js" defer></script>
+ </body>
+</html>
diff --git a/pages/theater.html b/pages/theater.html
new file mode 100644
index 000000000..4ca449f2f
--- /dev/null
+++ b/pages/theater.html
@@ -0,0 +1,103 @@
+<!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 http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Live Trading Theater · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <meta name="author" content="nirholas" />
+ <meta
+ name="description"
+ content="Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs and a real receipt rises with an explorer link."
+ />
+ <meta name="theme-color" content="#05050a" />
+ <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 property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Live Trading Theater · three.ws" />
+ <meta
+ property="og:description"
+ content="Trading as spectator sport. Real agents, real wallets, real on-chain fills — performed in a shared 3D stage."
+ />
+ <meta property="og:url" content="https://three.ws/theater" />
+
+ <!-- tokens.css = design variables only; buttons.css targets .btn — neither
+ touches the theater's own .th-* UI. theater.css owns the layout. -->
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/src/theater.css" />
+ </head>
+ <body>
+ <div id="th-root" class="th-root">
+ <header class="th-topbar">
+ <a class="th-back" href="/" aria-label="Back to three.ws">
+ <span aria-hidden="true">←</span> three.ws
+ </a>
+ <div class="th-title-wrap">
+ <h1 class="th-title">Live Trading Theater</h1>
+ <p class="th-room-hint" id="th-room-hint"></p>
+ </div>
+ <div class="th-status th-dot-amber" id="th-status" role="status" aria-live="polite">
+ <span class="th-status-dot" aria-hidden="true"></span>
+ <span class="th-status-label">Connecting</span>
+ </div>
+ </header>
+
+ <nav class="th-rooms" id="th-rooms" role="tablist" aria-label="Theater rooms"></nav>
+
+ <div class="th-layout">
+ <section class="th-stage" id="th-stage" aria-label="3D trading stage">
+ <canvas id="th-canvas" class="th-canvas"></canvas>
+ <div id="th-overlay" class="th-overlay" aria-hidden="true"></div>
+
+ <!-- loading -->
+ <div class="th-state th-loading" id="th-loading">
+ <div class="th-spinner" aria-hidden="true"></div>
+ <p>Assembling the cast…</p>
+ </div>
+
+ <!-- quiet market -->
+ <div class="th-state th-quiet" id="th-quiet" hidden>
+ <h2>The market's quiet right now</h2>
+ <p class="th-muted">No agent is moving this second. Here's the most recent real activity — the stage lights up the instant the next on-chain buy fills.</p>
+ <div class="th-highlights" data-highlights></div>
+ </div>
+
+ <!-- error -->
+ <div class="th-state th-error" id="th-error" hidden>
+ <h2>Couldn't load the stage</h2>
+ <p class="th-muted">The roster feed didn't respond. Your connection or our edge may be hiccuping.</p>
+ <button class="th-btn th-btn-primary" data-retry>Try again</button>
+ </div>
+
+ <!-- read-only HUD -->
+ <aside class="th-panel" id="th-panel" aria-label="Agent details"></aside>
+ </section>
+
+ <aside class="th-rail" aria-label="Live activity and replay">
+ <section class="th-rail-block">
+ <h2 class="th-rail-h">
+ <span class="th-status-dot th-rail-dot" aria-hidden="true"></span> Live tape
+ </h2>
+ <ul class="th-ticker" id="th-ticker" aria-live="polite"></ul>
+ </section>
+
+ <section class="th-rail-block th-replay" id="th-replay">
+ <div class="th-replay-head">
+ <h2 class="th-rail-h">Replay</h2>
+ <button class="th-btn th-btn-sm" data-play-all>▶ Play session</button>
+ </div>
+ <p class="th-muted th-replay-empty" data-empty>Every real move this session lands here. Tap a marker to replay it on stage.</p>
+ <div class="th-replay-rail" data-rail aria-label="Captured moves"></div>
+ </section>
+ </aside>
+ </div>
+ </div>
+
+ <script type="module" src="/src/theater.js"></script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index 0d1210bfd..416babfae 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T12:03:26.611Z",
+ "generated_at": "2026-06-23T12:13:30.167Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "Alpha Co-pilot — your agent narrates its own alpha",
+ "summary": "Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.",
+ "link": "/alpha-copilot",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -66,6 +76,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "Live Trading Theater",
+ "summary": "Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.",
+ "link": "/theater",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -168,6 +188,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Alpha Co-pilot: your agent reads a real launch in character and speaks its verdict aloud",
+ "summary": "Trading bots are silent black boxes — your agent isn't. Open the new Alpha Co-pilot, pick a live pump.fun launch, and your agent reads it in character: it pulls the real liquidity, holder concentration, smart-money, age, and price-impact signals, forms a verdict (snipe / watch / pass) with a conviction score, and its 3D avatar speaks the rationale out loud. A cautious persona and an aggressive one genuinely reach different calls on the same coin. Every number it voices is checked against the live data shown beside it — a fabricated figure is rejected and a grounded line spoken instead, never an invented price. If you own the agent, you can act on the call in one tap, but only within your hard spend limits: the buy runs through the same guarded wallet path as the rest of the platform — re-checked against the rug/honeypot firewall and your per-trade and daily caps at submit, and written to the custody audit. Logged-out visitors can hear the public read but can't act.",
+ "link": "/alpha-copilot",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 52ddbe5ef..58e6d819e 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>launch</category>
<description>A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.</description>
</item>
+ <item>
+ <title>Alpha Co-pilot — your agent narrates its own alpha</title>
+ <link>https://three.ws/alpha-copilot</link>
+ <guid isPermaLink="false">2026-06-23:Alpha Co-pilot — your agent narrates its own alpha</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.</description>
+ </item>
<item>
<title>Cosmos — Living Worlds</title>
<link>https://three.ws/cosmos</link>
@@ -54,6 +62,14 @@
<category>launch</category>
<description>The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.</description>
</item>
+ <item>
+ <title>Live Trading Theater</title>
+ <link>https://three.ws/theater</link>
+ <guid isPermaLink="false">2026-06-23:Live Trading Theater</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.</description>
+ </item>
<item>
<title>Living Stages</title>
<link>https://three.ws/stage</link>
@@ -134,6 +150,14 @@
<category>feature</category>
<description>A freshly created agent used to show blank space where its Recent Actions, Memory, and Strategy panels live — nothing to tell its owner what those panels are for or how to fill them. Now, when you own an agent that hasn't done anything yet, each of those panels shows a clear, friendly empty state instead: what the panel tracks, why it matters, and a button that takes you straight to the exact place to act. “No signed actions yet” sends you to the Skills studio to switch on capabilities; “No memories yet” opens the Memory studio to seed what it remembers; “No strategy set” drops you into the Brain studio to define how it trades and acts on its own. Those buttons now deep-link to the specific agent you were viewing — the studio opens that agent on the right tab, instead of defaulting to your first one — so the path from profile to configured agent is a single click. Visitors who don't own the agent see none of this; the panels stay owner-only. Only coin referenced is $THREE.</description>
</item>
+ <item>
+ <title>Alpha Co-pilot: your agent reads a real launch in character and speaks its verdict aloud</title>
+ <link>https://three.ws/alpha-copilot</link>
+ <guid isPermaLink="false">2026-06-23:Alpha Co-pilot: your agent reads a real launch in character and speaks its verdict aloud</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Trading bots are silent black boxes — your agent isn't. Open the new Alpha Co-pilot, pick a live pump.fun launch, and your agent reads it in character: it pulls the real liquidity, holder concentration, smart-money, age, and price-impact signals, forms a verdict (snipe / watch / pass) with a conviction score, and its 3D avatar speaks the rationale out loud. A cautious persona and an aggressive one genuinely reach different calls on the same coin. Every number it voices is checked against the live data shown beside it — a fabricated figure is rejected and a grounded line spoken instead, never an invented price. If you own the agent, you can act on the call in one tap, but only within your hard spend limits: the buy runs through the same guarded wallet path as the rest of the platform — re-checked against the rug/honeypot firewall and your per-trade and daily caps at submit, and written to the custody audit. Logged-out visitors can hear the public read but can't act.</description>
+ </item>
<item>
<title>Audio2Face: your avatar's face now moves with its voice</title>
<link>https://three.ws/audio2face</link>
diff --git a/public/features.json b/public/features.json
index 8a4e6d87b..2c12a2e04 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T12:03:26.589Z",
+ "generated_at": "2026-06-23T12:13:30.151Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -85,6 +85,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/alpha-copilot",
+ "title": "Alpha Co-pilot — your agent narrates its own alpha",
+ "description": "Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/world-lines",
"title": "World Lines — agent proof-of-presence quests",
@@ -726,6 +736,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/theater",
+ "title": "Live Trading Theater",
+ "description": "Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/pulse",
"title": "Money Pulse",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index f50d3e879..efc595722 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -55,6 +55,12 @@ URL: https://three.ws/irl-privacy
Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.
+### Alpha Co-pilot — your agent narrates its own alpha
+
+URL: https://three.ws/alpha-copilot
+
+Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.
+
### World Lines — agent proof-of-presence quests
URL: https://three.ws/world-lines
@@ -442,6 +448,12 @@ URL: https://three.ws/launches
Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.
+### Live Trading Theater
+
+URL: https://three.ws/theater
+
+Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.
+
### Money Pulse
URL: https://three.ws/pulse
diff --git a/public/llms.txt b/public/llms.txt
index 0c1c7452d..8dbd53516 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -18,6 +18,7 @@ Entry points into the product.
- [Drive Your Avatar](https://three.ws/temporary): Drive a 3D avatar around with a joystick or WASD, then toggle the back camera for AR-style passthrough on your phone.
- [IRL](https://three.ws/irl): Place a 3D avatar in your real environment. Camera AR passthrough, joystick movement, and tap-to-place 3D objects on your floor.
- [How location works on IRL](https://three.ws/irl-privacy): Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.
+- [Alpha Co-pilot — your agent narrates its own alpha](https://three.ws/alpha-copilot): Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.
- [World Lines — agent proof-of-presence quests](https://three.ws/world-lines): Walk to an AI agent's real-world spot, complete its AR challenge, and earn a cryptographically real, agent-signed proof of presence. Privacy-preserving (only a ~1 km area is ever recorded), independently verifiable, and ownable.
- [Marketplace](https://three.ws/marketplace): Buy access to agents, skills, and avatars from other creators.
- [Marketplace Analytics](https://three.ws/marketplace/analytics): Real-time stats on the three.ws skill marketplace: top skills, top agents, and sales volume.
@@ -93,6 +94,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Guardian console — recover & inherit agent wallets](https://three.ws/guardian): The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
- [Launch a Coin](https://three.ws/launch): Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.
- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.
+- [Live Trading Theater](https://three.ws/theater): Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.
- [Money Pulse](https://three.ws/pulse): The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.
- [Coin Clash](https://three.ws/clash): Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.
- [Trader Leaderboard](https://three.ws/leaderboard): Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.
diff --git a/public/nav-data.js b/public/nav-data.js
index 4a8c75bd3..0d81aa8f6 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -180,6 +180,13 @@ export const NAV_GROUPS = [
badgeTone: 'live',
desc: 'Agents hire, pay & verify each other — a live $THREE machine economy',
},
+ {
+ title: 'Alpha Co-pilot',
+ href: '/alpha-copilot',
+ badge: 'New',
+ badgeTone: 'live',
+ desc: 'Your agent reads a real launch in character, speaks its verdict aloud & acts within your spend limits',
+ },
{
title: 'Live Trade Feed',
href: '/trades',
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 5d5d7735f..2b1431ec7 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 318 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 320 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 318 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 320 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>
@@ -96,7 +96,7 @@
</nav>
<section class="sm-section" id="main">
<header>
- <h2>Main<span class="sm-count" data-count>20</span></h2>
+ <h2>Main<span class="sm-count" data-count>21</span></h2>
<p class="sm-section-desc">Entry points into the product.</p>
</header>
<ul class="sm-list">
@@ -149,6 +149,13 @@
<span class="sm-desc">Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.</span>
</a>
</li>
+ <li>
+ <a href="/alpha-copilot">
+ <span class="sm-title">Alpha Co-pilot — your agent narrates its own alpha</span>
+ <span class="sm-path">/alpha-copilot</span>
+ <span class="sm-desc">Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.</span>
+ </a>
+ </li>
<li>
<a href="/world-lines">
<span class="sm-title">World Lines — agent proof-of-presence quests</span>
@@ -564,7 +571,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>62</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>63</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -610,6 +617,13 @@
<span class="sm-desc">Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.</span>
</a>
</li>
+ <li>
+ <a href="/theater">
+ <span class="sm-title">Live Trading Theater</span>
+ <span class="sm-path">/theater</span>
+ <span class="sm-desc">Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.</span>
+ </a>
+ </li>
<li>
<a href="/pulse">
<span class="sm-title">Money Pulse</span>
diff --git a/src/agent-edit.js b/src/agent-edit.js
index baf4a22b1..12a334f75 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -5,6 +5,7 @@ import { openAvatarPicker } from './avatar-gallery-picker.js';
import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
import { log } from './shared/log.js';
import { isValidGlbMagic } from './shared/glb-magic.js';
+import { agentBus } from './agents/agent-bus.js';
const API_BASE = '/api';
const params = new URLSearchParams(location.search);
@@ -2681,10 +2682,354 @@ $('danger-delete-btn').addEventListener('click', async () => {
// Tab switching
// ─────────────────────────────────────────────────────────────────────────────
+// ─────────────────────────────────────────────────────────────────────────────
+// Dreams tab — reflection review (memory consolidation)
+// ─────────────────────────────────────────────────────────────────────────────
+
+let dreamsTabMounted = false;
+let dreamsReflecting = false;
+let dreamsJournalLoaded = false;
+
+const KIND_LABEL = { insight: 'Insight', belief: 'Belief', question: 'Question', prune: 'Prune' };
+
+function setDreamsBadge(n) {
+ const b = $('dreams-tab-badge');
+ if (!b) return;
+ const count = Number(n) || 0;
+ if (count > 0) {
+ b.textContent = String(count);
+ b.hidden = false;
+ b.setAttribute('aria-hidden', 'false');
+ } else {
+ b.hidden = true;
+ b.setAttribute('aria-hidden', 'true');
+ }
+}
+
+async function ensureDreamsTab() {
+ if (!dreamsTabMounted) {
+ dreamsTabMounted = true;
+ $('dreams-reflect-btn').addEventListener('click', () => reflectNow());
+ $('dreams-journal-toggle').addEventListener('click', toggleDreamJournal);
+ }
+ await loadDreams();
+ // Opening the review surface kicks a debounced background reflection so a user
+ // returning after time away finds fresh dreams — the server debounce makes
+ // repeated opens cheap (it simply reports it reflected recently).
+ backgroundReflect();
+}
+
+async function loadDreams() {
+ const list = $('dreams-list');
+ try {
+ const r = await apiFetch(`${API_BASE}/agent/dreams?agentId=${agentId}&status=pending`, { credentials: 'include' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const j = await r.json();
+ renderDreams(j.dreams || []);
+ setDreamsBadge(j.pending ?? (j.dreams || []).length);
+ renderDreamsMeta(j.lastRun);
+ $('dreams-journal').hidden = false;
+ if (dreamsJournalLoaded) loadDreamJournal();
+ } catch (err) {
+ list.innerHTML = `<div class="dream-card-status err">Could not load dreams: ${escapeHtml(err.message)}. <button class="link-btn" id="dreams-retry">Retry</button></div>`;
+ const retry = $('dreams-retry');
+ if (retry) retry.addEventListener('click', loadDreams);
+ }
+}
+
+function renderDreamsMeta(lastRun) {
+ const meta = $('dreams-meta');
+ if (!meta) return;
+ if (!lastRun) {
+ meta.textContent = 'Your agent has not reflected yet.';
+ return;
+ }
+ const when = timeAgo(lastRun.at);
+ if (lastRun.status === 'ok' && lastRun.dreamsCreated > 0) {
+ meta.innerHTML = `<span class="dot">●</span> Last reflected ${escapeHtml(when)} — ${lastRun.dreamsCreated} new dream${lastRun.dreamsCreated === 1 ? '' : 's'}.`;
+ } else if (lastRun.status === 'skipped') {
+ meta.innerHTML = `<span class="dot">●</span> Last checked ${escapeHtml(when)} — ${escapeHtml(lastRun.reason || 'nothing new to consolidate')}.`;
+ } else if (lastRun.status === 'error') {
+ meta.innerHTML = `<span class="dot">●</span> Last attempt ${escapeHtml(when)} hit an error (${escapeHtml(lastRun.reason || 'unknown')}).`;
+ } else {
+ meta.innerHTML = `<span class="dot">●</span> Last reflected ${escapeHtml(when)} — no new insights that pass.`;
+ }
+}
+
+function timeAgo(iso) {
+ const t = Date.parse(iso);
+ if (!Number.isFinite(t)) return 'recently';
+ const s = Math.max(0, Math.round((Date.now() - t) / 1000));
+ if (s < 60) return 'just now';
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.round(m / 60);
+ if (h < 24) return `${h}h ago`;
+ const d = Math.round(h / 24);
+ return `${d}d ago`;
+}
+
+function renderDreams(dreams) {
+ const list = $('dreams-list');
+ if (!dreams.length) {
+ list.innerHTML = `
+ <div class="dreams-empty">
+ <span class="moon" aria-hidden="true">🌙</span>
+ <div class="lead">No new reflections yet.</div>
+ <div>Your agent consolidates its memories on its own while you're away. Give it some memories and conversations to think about — or reflect now.</div>
+ </div>`;
+ return;
+ }
+ list.innerHTML = dreams.map(dreamCardHTML).join('');
+ dreams.forEach((d) => wireDreamCard(d));
+}
+
+function dreamCardHTML(d) {
+ const conf = Math.round((Number(d.confidence) || 0) * 100);
+ const kindClass = d.kind === 'question' ? ' kind-question' : '';
+ const propType = d.proposedType ? `<span class="pill">→ ${escapeHtml(d.proposedType)} memory</span>` : '';
+ const propSal = `<span class="pill">salience ${Number(d.proposedSalience).toFixed(2)}</span>`;
+ const propAction = d.proposedAction
+ ? `<span class="pill" title="${escapeHtml(JSON.stringify(d.proposedAction))}">⚡ proposes an automation</span>`
+ : '';
+ const sources = (d.sources || []).map((s) => {
+ if (s.forgotten) {
+ return `<div class="dream-src forgotten" aria-disabled="true">source memory was forgotten</div>`;
+ }
+ return `<button type="button" class="dream-src" data-src-id="${escapeHtml(s.id)}" data-full="${escapeHtml(s.content)}" title="Click to view full memory">
+ <span class="src-type">${escapeHtml(s.type)}</span>${escapeHtml(truncateText(s.content, 140))}
+ </button>`;
+ }).join('');
+
+ const isQuestion = d.kind === 'question' && d.question;
+ const questionUI = isQuestion
+ ? `<div class="dream-answer">
+ <input class="form-input" type="text" id="dream-ans-${escapeHtml(d.id)}" placeholder="Your answer…" maxlength="2000" aria-label="Answer the agent's question" />
+ <button class="dream-answer-send" data-answer="${escapeHtml(d.id)}">Answer &amp; save</button>
+ </div>`
+ : '';
+
+ const acceptLabel = isQuestion ? 'Accept as-is' : 'Accept';
+
+ return `
+ <article class="dream-card entering" data-dream="${escapeHtml(d.id)}">
+ <span class="dream-kind${kindClass}">${escapeHtml(KIND_LABEL[d.kind] || d.kind)}</span>
+ <p class="dream-statement">${escapeHtml(d.statement)}</p>
+ ${isQuestion ? `<p class="dream-rationale">${escapeHtml(d.question)}</p>` : (d.rationale ? `<p class="dream-rationale">${escapeHtml(d.rationale)}</p>` : '')}
+ <div class="dream-conf" title="How confident the agent is in this synthesis">
+ confidence ${conf}%
+ <span class="dream-conf-bar"><span class="dream-conf-fill" style="width:${conf}%"></span></span>
+ </div>
+ <div class="dream-prop">${propType}${propSal}${propAction}</div>
+ ${sources ? `<div class="dream-sources"><div class="dream-sources-label">Drawn from ${(d.sources || []).length} ${(d.sources || []).length === 1 ? 'memory' : 'memories'} — its evidence</div>${sources}</div>` : ''}
+ ${questionUI}
+ <div class="dream-actions">
+ <button class="dream-accept" data-accept="${escapeHtml(d.id)}">${acceptLabel}</button>
+ <button class="dream-reject" data-reject="${escapeHtml(d.id)}">Reject</button>
+ </div>
+ <div class="dream-card-status" data-status="${escapeHtml(d.id)}" role="status" aria-live="polite"></div>
+ </article>`;
+}
+
+function wireDreamCard(d) {
+ const card = document.querySelector(`.dream-card[data-dream="${cssEscape(d.id)}"]`);
+ if (!card) return;
+ card.querySelectorAll('.dream-src[data-src-id]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const expanded = btn.classList.toggle('expanded');
+ const full = btn.dataset.full || '';
+ const type = btn.querySelector('.src-type')?.outerHTML || '';
+ btn.innerHTML = `${type}${escapeHtml(expanded ? full : truncateText(full, 140))}`;
+ });
+ });
+ card.querySelector('[data-accept]')?.addEventListener('click', () => reviewDream(d, 'accept'));
+ card.querySelector('[data-reject]')?.addEventListener('click', () => reviewDream(d, 'reject'));
+ const ans = card.querySelector('[data-answer]');
+ if (ans) ans.addEventListener('click', () => reviewDream(d, 'answer'));
+}
+
+function cssEscape(s) {
+ return String(s).replace(/["\\\]]/g, '\\$&');
+}
+
+function truncateText(s, n) {
+ const str = String(s ?? '');
+ return str.length > n ? str.slice(0, n - 1) + '…' : str;
+}
+
+async function reviewDream(d, decision) {
+ const card = document.querySelector(`.dream-card[data-dream="${cssEscape(d.id)}"]`);
+ const statusEl = card?.querySelector(`[data-status]`);
+ const buttons = card?.querySelectorAll('button') || [];
+ let answer = null;
+ if (decision === 'answer') {
+ const input = $(`dream-ans-${d.id}`);
+ answer = (input?.value || '').trim();
+ if (!answer) {
+ if (statusEl) { statusEl.textContent = 'Type an answer first.'; statusEl.className = 'dream-card-status err'; }
+ input?.focus();
+ return;
+ }
+ }
+ buttons.forEach((b) => (b.disabled = true));
+ if (statusEl) {
+ statusEl.textContent = decision === 'reject' ? 'Letting it go…' : 'Saving…';
+ statusEl.className = 'dream-card-status';
+ }
+ try {
+ const r = await apiFetch(`${API_BASE}/agent/dreams`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ agentId, dreamId: d.id, decision, answer }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+
+ if (j.memory) {
+ // A real, higher-salience memory now exists — tell the rest of the app.
+ agentBus.emit('memory:added', {
+ agentId,
+ memoryId: j.memory.id,
+ type: j.memory.type,
+ salience: j.memory.salience,
+ source: 'reflection',
+ ts: j.memory.createdAt,
+ });
+ // Refresh the Knowledge tab if the user has it open so the new memory shows.
+ if (knowledgeTabMounted) loadMemories();
+ }
+
+ // Animate the card out, then refresh counts + journal.
+ if (card) {
+ card.classList.add('leaving');
+ setTimeout(() => {
+ card.remove();
+ const remaining = document.querySelectorAll('.dream-card').length;
+ setDreamsBadge(remaining);
+ if (remaining === 0) renderDreams([]);
+ }, 250);
+ }
+ dreamsJournalLoaded = false; // journal is now stale
+ } catch (err) {
+ buttons.forEach((b) => (b.disabled = false));
+ if (statusEl) {
+ statusEl.textContent = `Could not ${decision}: ${err.message}`;
+ statusEl.className = 'dream-card-status err';
+ }
+ }
+}
+
+async function runReflectPass({ force }) {
+ if (dreamsReflecting) return;
+ dreamsReflecting = true;
+ const btn = $('dreams-reflect-btn');
+ if (force && btn) {
+ btn.disabled = true;
+ btn.classList.add('is-dreaming');
+ btn.querySelector('.dreams-reflect-label').textContent = 'Reflecting';
+ } else if (btn) {
+ btn.classList.add('is-dreaming');
+ }
+ try {
+ const r = await apiFetch(`${API_BASE}/agent/reflect`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ agentId, force: !!force }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (r.ok && j.status === 'ok' && Array.isArray(j.created) && j.created.length) {
+ for (const dream of j.created) {
+ agentBus.emit('dream:created', {
+ agentId,
+ dreamId: dream.id,
+ kind: dream.kind,
+ statement: dream.statement,
+ ts: dream.createdAt,
+ });
+ }
+ await loadDreams();
+ } else if (force) {
+ // Force run that produced nothing — refresh so the meta line explains why.
+ await loadDreams();
+ }
+ } catch {
+ // Background reflection failures are non-fatal; the meta line + list already
+ // reflect the last known state. A forced run surfaces the error via meta.
+ if (force) await loadDreams();
+ } finally {
+ dreamsReflecting = false;
+ if (btn) {
+ btn.disabled = false;
+ btn.classList.remove('is-dreaming');
+ btn.querySelector('.dreams-reflect-label').textContent = 'Reflect now';
+ }
+ }
+}
+
+function reflectNow() {
+ runReflectPass({ force: true });
+}
+
+function backgroundReflect() {
+ runReflectPass({ force: false });
+}
+
+function toggleDreamJournal() {
+ const toggle = $('dreams-journal-toggle');
+ const listEl = $('dreams-journal-list');
+ const open = toggle.getAttribute('aria-expanded') === 'true';
+ const next = !open;
+ toggle.setAttribute('aria-expanded', String(next));
+ listEl.hidden = !next;
+ if (next && !dreamsJournalLoaded) loadDreamJournal();
+}
+
+async function loadDreamJournal() {
+ const listEl = $('dreams-journal-list');
+ const countEl = $('dreams-journal-count');
+ try {
+ const r = await apiFetch(`${API_BASE}/agent/dreams?agentId=${agentId}&limit=100`, { credentials: 'include' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const j = await r.json();
+ dreamsJournalLoaded = true;
+ const reviewed = (j.dreams || []).filter((d) => d.status === 'accepted' || d.status === 'rejected');
+ if (countEl) countEl.textContent = reviewed.length ? `(${reviewed.length})` : '';
+ if (!reviewed.length) {
+ listEl.innerHTML = '<div class="muted" style="font-size:0.78rem">Accepted and rejected dreams will appear here as your agent grows.</div>';
+ return;
+ }
+ listEl.innerHTML = reviewed.map((d) => `
+ <div class="journal-item">
+ <span class="jstatus ${escapeHtml(d.status)}">${d.status === 'accepted' ? '✓ kept' : '✕ let go'}</span>
+ <span class="jtext">${escapeHtml(d.statement)}${d.answer ? ` — <em>${escapeHtml(d.answer)}</em>` : ''}</span>
+ </div>`).join('');
+ } catch (err) {
+ listEl.innerHTML = `<div class="dream-card-status err">Could not load journal: ${escapeHtml(err.message)}</div>`;
+ }
+}
+
+let brainTabMounted = false;
+async function ensureBrainTab() {
+ if (brainTabMounted) return;
+ brainTabMounted = true;
+ const host = $('brain-studio-host');
+ try {
+ const { mountBrainStudio } = await import('./brain-studio.js');
+ await mountBrainStudio(host, { agentId, agent: agentData });
+ } catch (err) {
+ brainTabMounted = false;
+ host.innerHTML = `<div class="error-msg" style="padding:1rem">Could not load the Brain Studio: ${escapeHtml(err.message)}</div>`;
+ }
+}
+
const TAB_LOADERS = {
+ brain: ensureBrainTab,
outfit: ensureOutfitTab,
voice: ensureVoiceTab,
knowledge: ensureKnowledgeTab,
+ dreams: ensureDreamsTab,
skills: ensureSkillsTab,
wallet: ensureWalletTab,
social: ensureSocialTab,
@@ -2730,6 +3075,21 @@ async function init() {
if (initialTab && document.getElementById(`panel-${initialTab}`)) {
activateTab(initialTab);
}
+ // Surface the pending-dreams count on the tab badge without forcing the user
+ // to open the tab — so a returning user sees "their agent has been thinking".
+ primeDreamsBadge();
+}
+
+async function primeDreamsBadge() {
+ if (!agentId) return;
+ try {
+ const r = await apiFetch(`${API_BASE}/agent/dreams?agentId=${agentId}&status=pending&limit=1`, { credentials: 'include' });
+ if (!r.ok) return;
+ const j = await r.json();
+ setDreamsBadge(j.pending || 0);
+ } catch {
+ // Non-fatal — the badge simply stays hidden until the tab is opened.
+ }
}
init();
diff --git a/src/agents/agent-bus-debug.js b/src/agents/agent-bus-debug.js
new file mode 100644
index 000000000..f2ea3ac3b
--- /dev/null
+++ b/src/agents/agent-bus-debug.js
@@ -0,0 +1,145 @@
+// Agent Bus debug overlay — a developer tool, NOT product UI.
+//
+// Loaded only when the URL carries ?agentbus=1 (see agent-bus.js). It taps the
+// wildcard subscriber and renders a live, scrolling log of every bus event in a
+// fixed corner panel, so you can watch the nervous system fire: change the active
+// agent, send a chat that recalls memory, add/forget a memory — each shows up
+// here with its agentId, timestamp, and payload. This is the verification tool
+// for the Foundation task; it never ships in the normal UI.
+
+import { agentBus, AGENT_EVENTS } from './agent-bus.js';
+
+const MAX_ROWS = 200;
+let mounted = false;
+
+// A stable, readable colour per event family so the stream is scannable.
+const COLORS = {
+ 'memory:added': '#34d399',
+ 'memory:recalled': '#60a5fa',
+ 'memory:updated': '#fbbf24',
+ 'memory:forgotten': '#f87171',
+ 'brain:updated': '#a78bfa',
+ 'mood:changed': '#f472b6',
+ 'dream:created': '#c084fc',
+ 'action:taken': '#fb923c',
+ 'agent:changed': '#22d3ee',
+};
+
+function fmtTime(ts) {
+ const d = ts ? new Date(ts) : new Date();
+ if (Number.isNaN(d.getTime())) return String(ts);
+ return d.toLocaleTimeString(undefined, { hour12: false }) + '.' + String(d.getMilliseconds()).padStart(3, '0');
+}
+
+function summarize(type, payload) {
+ const p = payload || {};
+ switch (type) {
+ case 'memory:recalled':
+ return `${p.memories?.length ?? 0} recalled${p.semantic ? ' (semantic)' : ''}${p.query ? ` · “${String(p.query).slice(0, 40)}”` : ''}`;
+ case 'memory:added':
+ case 'memory:updated':
+ return p.memory ? `${p.memory.type}: ${String(p.memory.content || '').slice(0, 48)}` : '';
+ case 'memory:forgotten':
+ return p.memoryId || '';
+ case 'agent:changed':
+ return p.agent?.name ? `→ ${p.agent.name}` : p.agentId ? `→ ${p.agentId}` : '(cleared)';
+ case 'mood:changed':
+ return p.mood || '';
+ case 'dream:created':
+ return p.title || p.insight ? String(p.title || p.insight).slice(0, 48) : '';
+ case 'action:taken':
+ return p.summary || p.kind || '';
+ case 'brain:updated':
+ return p.change || (p.toneTags ? p.toneTags.join(', ') : '');
+ default:
+ return '';
+ }
+}
+
+/** Mount the overlay (idempotent). Safe to call repeatedly. */
+export function mountAgentBusDebug() {
+ if (mounted || typeof document === 'undefined') return;
+ mounted = true;
+
+ const style = document.createElement('style');
+ style.textContent = `
+ #agentbus-debug{position:fixed;right:12px;bottom:12px;z-index:2147483000;width:360px;max-width:calc(100vw - 24px);
+ max-height:46vh;display:flex;flex-direction:column;font:11px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;
+ color:#e5e7eb;background:rgba(9,11,16,.92);border:1px solid rgba(255,255,255,.12);border-radius:12px;
+ box-shadow:0 12px 40px rgba(0,0,0,.5);backdrop-filter:blur(8px);overflow:hidden}
+ #agentbus-debug header{display:flex;align-items:center;gap:8px;padding:8px 10px;background:rgba(255,255,255,.04);
+ border-bottom:1px solid rgba(255,255,255,.08);cursor:default}
+ #agentbus-debug header b{font-weight:600;letter-spacing:.02em}
+ #agentbus-debug header .dot{width:7px;height:7px;border-radius:50%;background:#22d3ee;box-shadow:0 0 8px #22d3ee}
+ #agentbus-debug header .count{margin-left:auto;opacity:.6}
+ #agentbus-debug header button{appearance:none;border:1px solid rgba(255,255,255,.14);background:transparent;
+ color:#e5e7eb;border-radius:6px;padding:2px 7px;cursor:pointer;font:inherit}
+ #agentbus-debug header button:hover{background:rgba(255,255,255,.08)}
+ #agentbus-debug header button:focus-visible{outline:2px solid #60a5fa;outline-offset:1px}
+ #agentbus-debug .rows{overflow-y:auto;padding:4px 0}
+ #agentbus-debug .row{display:grid;grid-template-columns:auto auto 1fr;gap:8px;padding:3px 10px;align-items:baseline}
+ #agentbus-debug .row:hover{background:rgba(255,255,255,.04)}
+ #agentbus-debug .row time{opacity:.5;font-variant-numeric:tabular-nums}
+ #agentbus-debug .row .type{font-weight:600}
+ #agentbus-debug .row .msg{opacity:.85;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+ #agentbus-debug .empty{padding:14px 12px;opacity:.6}
+ #agentbus-debug.collapsed .rows,#agentbus-debug.collapsed .empty{display:none}
+ @media (prefers-reduced-motion:no-preference){#agentbus-debug .row{animation:abFade .25s ease}}
+ @keyframes abFade{from{opacity:0;transform:translateY(3px)}to{opacity:1;transform:none}}
+ `;
+ document.head.appendChild(style);
+
+ const panel = document.createElement('section');
+ panel.id = 'agentbus-debug';
+ panel.setAttribute('role', 'log');
+ panel.setAttribute('aria-label', 'Agent bus debug log');
+ panel.innerHTML = `
+ <header>
+ <span class="dot" aria-hidden="true"></span>
+ <b>agent bus</b>
+ <span class="count" data-count>0 events</span>
+ <button type="button" data-collapse aria-label="Collapse log">–</button>
+ <button type="button" data-clear aria-label="Clear log">clear</button>
+ </header>
+ <div class="rows" data-rows></div>
+ <div class="empty" data-empty>Listening on ${AGENT_EVENTS.length} event types. Trigger one — change the active agent, send a chat that recalls memory, add or forget a memory.</div>
+ `;
+ document.body.appendChild(panel);
+
+ const rows = panel.querySelector('[data-rows]');
+ const empty = panel.querySelector('[data-empty]');
+ const countEl = panel.querySelector('[data-count]');
+ let count = 0;
+
+ panel.querySelector('[data-clear]').addEventListener('click', () => {
+ rows.innerHTML = '';
+ count = 0;
+ countEl.textContent = '0 events';
+ empty.style.display = '';
+ });
+ panel.querySelector('[data-collapse]').addEventListener('click', (e) => {
+ const collapsed = panel.classList.toggle('collapsed');
+ e.currentTarget.textContent = collapsed ? '+' : '–';
+ e.currentTarget.setAttribute('aria-label', collapsed ? 'Expand log' : 'Collapse log');
+ });
+
+ agentBus.on('*', (payload, type) => {
+ empty.style.display = 'none';
+ const row = document.createElement('div');
+ row.className = 'row';
+ const color = COLORS[type] || '#9ca3af';
+ const msg = summarize(type, payload);
+ row.innerHTML = `<time>${fmtTime(payload?.ts)}</time><span class="type" style="color:${color}">${type}</span><span class="msg"></span>`;
+ row.querySelector('.msg').textContent = msg;
+ row.title = JSON.stringify(payload, null, 2);
+ rows.appendChild(row);
+ while (rows.children.length > MAX_ROWS) rows.removeChild(rows.firstChild);
+ rows.scrollTop = rows.scrollHeight;
+ count += 1;
+ countEl.textContent = `${count} event${count === 1 ? '' : 's'}`;
+ });
+
+ console.info('[agent-bus] debug overlay active (?agentbus=1). window.__agentBus is live.');
+}
+
+export default mountAgentBusDebug;
diff --git a/src/agents/memory-client.js b/src/agents/memory-client.js
new file mode 100644
index 000000000..b0bb5188e
--- /dev/null
+++ b/src/agents/memory-client.js
@@ -0,0 +1,146 @@
+// The shared memory client. Every Living-Agents surface that reads or mutates an
+// agent's memory goes through here instead of hand-rolling fetch logic, so:
+// • there is one place that knows the real /api/agent-memory contract, and
+// • every successful mutation emits the matching bus event, which is what makes
+// a memory added in a marketplace chat ripple to the Mind Palace and the HUD
+// in real time.
+//
+// Tasks 03 (Mind Palace), 04 (Dreams), 07 (Emotion) and 08 (Autopilot) mutate
+// memory exclusively through this module.
+
+import { apiFetch } from '../api.js';
+import { agentBus } from './agent-bus.js';
+
+/** ISO timestamp for a bus event, derived from the server's ms epoch when present. */
+function isoFrom(ms) {
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : new Date().toISOString();
+}
+
+async function readJson(res) {
+ return res.json().catch(() => ({}));
+}
+
+/**
+ * List an agent's memories. Owner-only on the server: a non-owner (or anonymous)
+ * caller receives an empty list rather than an error, so this is safe to call on
+ * any surface.
+ *
+ * @param {string} agentId
+ * @param {Object} [opts]
+ * @param {('user'|'feedback'|'project'|'reference')} [opts.type] - filter by type
+ * @param {number} [opts.since] - only entries created after this epoch-ms
+ * @param {number} [opts.limit=200] - 1..500
+ * @returns {Promise<Array<Object>>} decorated memory records (newest first)
+ */
+export async function listMemories(agentId, opts = {}) {
+ if (!agentId) return [];
+ const params = new URLSearchParams({ agentId });
+ if (opts.type) params.set('type', opts.type);
+ if (Number.isFinite(opts.since)) params.set('since', String(opts.since));
+ if (Number.isFinite(opts.limit)) params.set('limit', String(opts.limit));
+ const res = await apiFetch(`/api/agent-memory?${params.toString()}`, {
+ credentials: 'include',
+ allowAnonymous: true,
+ });
+ if (!res.ok) throw new Error(`listMemories failed: ${res.status}`);
+ const j = await readJson(res);
+ return Array.isArray(j.entries) ? j.entries : [];
+}
+
+// One upsert path on the server; the client distinguishes create vs update by
+// whether the entry already carries an id, and emits the right bus event.
+async function upsert(agentId, entry) {
+ const res = await apiFetch('/api/agent-memory', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ agentId, entry }),
+ });
+ if (!res.ok) {
+ const j = await readJson(res);
+ throw new Error(j.error || `memory write failed: ${res.status}`);
+ }
+ const j = await readJson(res);
+ return j.entry || null;
+}
+
+/**
+ * Create a memory and emit `memory:added`.
+ *
+ * @param {string} agentId
+ * @param {Object} entry - { type, content, tags?, context?, salience?, pinned?, expiresAt? }
+ * @returns {Promise<Object|null>} the created, decorated memory
+ */
+export async function addMemory(agentId, entry) {
+ if (!agentId) throw new Error('addMemory requires an agentId');
+ const { id, ...rest } = entry || {};
+ const memory = await upsert(agentId, rest);
+ if (memory) {
+ agentBus.emit('memory:added', { agentId, memory, ts: isoFrom(memory.createdAt) });
+ }
+ return memory;
+}
+
+/**
+ * Update an existing memory (content / salience / pin / visibility / expiry) and
+ * emit `memory:updated`. The entry MUST carry its `id`.
+ *
+ * @param {string} agentId
+ * @param {Object} entry - must include `id`
+ * @returns {Promise<Object|null>} the updated, decorated memory
+ */
+export async function updateMemory(agentId, entry) {
+ if (!agentId) throw new Error('updateMemory requires an agentId');
+ if (!entry?.id) throw new Error('updateMemory requires entry.id');
+ const memory = await upsert(agentId, entry);
+ if (memory) {
+ agentBus.emit('memory:updated', { agentId, memory, ts: isoFrom(memory.updatedAt) });
+ }
+ return memory;
+}
+
+/**
+ * Delete a memory and emit `memory:forgotten`.
+ *
+ * @param {string} agentId - the owning agent (carried in the event for routing)
+ * @param {string} memoryId
+ * @returns {Promise<boolean>} true on success
+ */
+export async function forgetMemory(agentId, memoryId) {
+ if (!memoryId) throw new Error('forgetMemory requires a memoryId');
+ const res = await apiFetch(`/api/agent-memory/${encodeURIComponent(memoryId)}`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
+ if (!res.ok) {
+ const j = await readJson(res);
+ throw new Error(j.error || `forget failed: ${res.status}`);
+ }
+ agentBus.emit('memory:forgotten', { agentId: agentId || null, memoryId, ts: new Date().toISOString() });
+ return true;
+}
+
+/**
+ * Emit `memory:recalled` from a chat `done` SSE event's recalled-memory set. The
+ * chat endpoint reports exactly which memories it injected into the prompt; this
+ * is the single place that turns that server truth into a bus event, so every
+ * SSE consumer (avatar page, embedded <agent-3d>, NPC chat) stays consistent. No
+ * heuristic guessing — if the server recalled nothing, nothing is emitted.
+ *
+ * @param {string|null} agentId
+ * @param {Object} done - the parsed `{ type:'done', recalled, recalledTs, ... }` event
+ * @param {string} [query] - the user message that triggered the recall
+ * @returns {Array<Object>} the recalled memories that were emitted (possibly empty)
+ */
+export function emitRecallFromChat(agentId, done, query) {
+ const recalled = Array.isArray(done?.recalled) ? done.recalled : [];
+ if (!recalled.length) return [];
+ agentBus.emit('memory:recalled', {
+ agentId: agentId || null,
+ memories: recalled,
+ query: query || undefined,
+ semantic: Boolean(done.recalledSemantic),
+ ts: done.recalledTs || new Date().toISOString(),
+ });
+ return recalled;
+}
diff --git a/src/alpha-copilot.css b/src/alpha-copilot.css
new file mode 100644
index 000000000..274daba4c
--- /dev/null
+++ b/src/alpha-copilot.css
@@ -0,0 +1,213 @@
+/* Alpha Co-pilot — in-character alpha narration surface.
+ Monochrome glass on near-black; violet wallet accent for the finance verdict.
+ All values from public/tokens.css. */
+
+@import '/tokens.css';
+
+.ac-shell {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: var(--space-xl) var(--space-md) var(--space-2xl);
+ color: var(--ink);
+ font-family: var(--font-body);
+}
+
+/* ── hero ─────────────────────────────────────────────────────────────────── */
+.ac-hero { text-align: center; max-width: 760px; margin: 0 auto var(--space-xl); }
+.ac-kicker {
+ display: inline-flex; align-items: center; gap: var(--space-xs);
+ font-family: var(--font-mono); font-size: var(--text-2xs); letter-spacing: 0.04em;
+ text-transform: uppercase; color: var(--wallet-accent);
+ background: var(--wallet-accent-soft); border: 1px solid var(--wallet-stroke);
+ padding: var(--space-2xs) var(--space-sm); border-radius: var(--radius-pill);
+ margin: 0 0 var(--space-md);
+}
+.ac-live-dot {
+ width: 7px; height: 7px; border-radius: 50%;
+ background: var(--success); box-shadow: 0 0 0 0 var(--success);
+ animation: ac-pulse 2s infinite;
+}
+@keyframes ac-pulse {
+ 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5); }
+ 70% { box-shadow: 0 0 0 7px rgba(74, 222, 128, 0); }
+ 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }
+}
+.ac-title { font-family: var(--font-display); font-size: var(--text-2xl); line-height: 1.05; margin: 0 0 var(--space-sm); color: var(--ink-bright); }
+.ac-sub { font-size: var(--text-base); color: var(--ink-dim); line-height: 1.55; margin: 0 auto var(--space-lg); max-width: 640px; }
+.ac-sub strong { color: var(--ink); }
+
+.ac-agentpick { display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap; align-items: flex-end; }
+.ac-field { display: flex; flex-direction: column; gap: var(--space-2xs); text-align: left; }
+.ac-field > span { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-faint); }
+.ac-field input {
+ width: min(420px, 76vw); font-family: var(--font-mono); font-size: var(--text-md);
+ padding: var(--space-sm) var(--space-md); border-radius: var(--radius-md);
+ background: var(--bg-1); border: 1px solid var(--stroke); color: var(--ink);
+ transition: border-color var(--duration-fast) var(--ease-standard);
+}
+.ac-field input:focus { outline: none; border-color: var(--wallet-focus); box-shadow: 0 0 0 3px var(--wallet-accent-soft); }
+.ac-field input.is-invalid { border-color: var(--danger); animation: ac-shake 0.3s; }
+@keyframes ac-shake { 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } }
+
+/* ── buttons ──────────────────────────────────────────────────────────────── */
+.ac-btn {
+ font-family: var(--font-body); font-size: var(--text-md); font-weight: 600;
+ padding: var(--space-sm) var(--space-md); border-radius: var(--radius-md);
+ background: var(--bg-1); border: 1px solid var(--stroke-strong); color: var(--ink);
+ cursor: pointer; transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast), transform var(--duration-instant);
+}
+.ac-btn:hover { background: var(--surface-3); border-color: var(--wallet-stroke); }
+.ac-btn:active { transform: translateY(1px); }
+.ac-btn:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--wallet-accent-soft); }
+.ac-btn-ghost { background: transparent; border-color: var(--stroke); color: var(--ink-dim); font-weight: 500; }
+.ac-btn-ghost:hover { color: var(--ink); }
+.ac-btn-read {
+ width: 100%; margin-top: var(--space-sm);
+ background: var(--wallet-accent-fill); border-color: var(--wallet-stroke); color: var(--wallet-accent);
+}
+.ac-btn-read:hover { background: var(--wallet-accent-soft); border-color: var(--wallet-stroke-strong); color: var(--ink-bright); }
+.ac-btn-act {
+ background: linear-gradient(180deg, var(--wallet-accent-strong), #8b5cf6);
+ border: 1px solid var(--wallet-stroke-strong); color: #fff; font-weight: 700;
+ box-shadow: 0 0 18px var(--wallet-glow);
+}
+.ac-btn-act:hover { filter: brightness(1.08); }
+.ac-btn-act:disabled { opacity: 0.5; cursor: not-allowed; box-shadow: none; }
+
+/* ── grid ─────────────────────────────────────────────────────────────────── */
+.ac-grid {
+ display: grid;
+ grid-template-columns: 320px 1fr 300px;
+ gap: var(--space-md);
+ align-items: start;
+}
+@media (max-width: 1080px) { .ac-grid { grid-template-columns: 1fr 300px; } .ac-stage { grid-column: 1 / -1; } }
+@media (max-width: 760px) { .ac-grid { grid-template-columns: 1fr; } }
+
+.ac-stage, .ac-read, .ac-launches {
+ background: var(--surface-glass); backdrop-filter: blur(var(--blur-md));
+ border: 1px solid var(--stroke); border-radius: var(--radius-lg);
+ box-shadow: var(--shadow-2); overflow: hidden;
+}
+
+/* ── stage (avatar narrator) ──────────────────────────────────────────────── */
+.ac-stage { display: flex; flex-direction: column; }
+.ac-stage.is-speaking { border-color: var(--wallet-stroke-strong); box-shadow: var(--shadow-2), 0 0 28px var(--wallet-glow); }
+.ac-stage-avatar { position: relative; aspect-ratio: 1 / 1; background: radial-gradient(circle at 50% 38%, rgba(139, 92, 246, 0.12), transparent 62%), var(--bg-0); }
+.ac-avatar { display: block; width: 100%; height: 100%; opacity: 0; transition: opacity var(--duration-slow) var(--ease-out); }
+.ac-avatar.ready, agent-3d.ready { opacity: 1; }
+.ac-stage-placeholder { position: absolute; inset: 0; display: grid; place-items: center; padding: var(--space-lg); text-align: center; color: var(--ink-faint); font-size: var(--text-sm); }
+.ac-stage-meta { padding: var(--space-sm) var(--space-md); border-top: 1px solid var(--stroke); }
+.ac-stage-name { font-family: var(--font-display); font-size: var(--text-lg); color: var(--ink-bright); }
+.ac-stage-role { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.05em; color: var(--wallet-accent); }
+.ac-speak { display: flex; gap: var(--space-sm); align-items: flex-start; padding: var(--space-md); border-top: 1px solid var(--stroke); background: var(--wallet-accent-soft); }
+.ac-speak.is-speaking { animation: ac-glow 1.4s ease-in-out infinite; }
+@keyframes ac-glow { 50% { background: var(--wallet-accent-fill); } }
+.ac-speak-btn {
+ flex: 0 0 auto; width: 30px; height: 30px; border-radius: 50%;
+ background: var(--wallet-accent-fill); border: 1px solid var(--wallet-stroke); color: var(--wallet-accent);
+ cursor: pointer; font-size: 11px; display: grid; place-items: center;
+}
+.ac-speak-btn:hover { background: var(--wallet-accent-soft); color: var(--ink-bright); }
+.ac-speak-line { margin: 0; font-size: var(--text-md); line-height: 1.5; color: var(--ink); font-style: italic; }
+
+/* ── the read ─────────────────────────────────────────────────────────────── */
+.ac-read { padding: var(--space-md); min-height: 220px; }
+.ac-read-empty { color: var(--ink-faint); font-size: var(--text-sm); line-height: 1.5; display: grid; place-items: center; min-height: 200px; text-align: center; }
+.ac-read-loading { display: grid; place-items: center; gap: var(--space-sm); min-height: 200px; color: var(--ink-dim); font-size: var(--text-sm); }
+.ac-thinking { display: flex; gap: 5px; }
+.ac-thinking span { width: 8px; height: 8px; border-radius: 50%; background: var(--wallet-accent); animation: ac-bounce 1.2s infinite; }
+.ac-thinking span:nth-child(2) { animation-delay: 0.15s; }
+.ac-thinking span:nth-child(3) { animation-delay: 0.3s; }
+@keyframes ac-bounce { 0%, 60%, 100% { transform: translateY(0); opacity: 0.5; } 30% { transform: translateY(-6px); opacity: 1; } }
+
+.ac-read-top { display: flex; align-items: center; gap: var(--space-md); margin-bottom: var(--space-sm); }
+.ac-verdict {
+ font-family: var(--font-display); font-size: var(--text-md); font-weight: 700;
+ padding: var(--space-2xs) var(--space-md); border-radius: var(--radius-pill);
+ text-transform: uppercase; letter-spacing: 0.05em;
+}
+.ac-verdict.is-snipe { background: rgba(74, 222, 128, 0.14); color: var(--success); border: 1px solid rgba(74, 222, 128, 0.4); }
+.ac-verdict.is-watch { background: rgba(251, 191, 36, 0.14); color: var(--warn); border: 1px solid rgba(251, 191, 36, 0.4); }
+.ac-verdict.is-pass { background: rgba(248, 113, 113, 0.12); color: var(--danger); border: 1px solid rgba(248, 113, 113, 0.35); }
+.ac-conviction { display: flex; align-items: center; gap: var(--space-sm); flex: 1; }
+.ac-conviction-bar { flex: 1; height: 7px; border-radius: var(--radius-pill); background: var(--surface-2); overflow: hidden; }
+.ac-conviction-bar span { display: block; height: 100%; background: linear-gradient(90deg, var(--wallet-accent), var(--wallet-accent-strong)); border-radius: var(--radius-pill); transition: width var(--duration-slow) var(--ease-emphasized); }
+.ac-conviction-val { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink); }
+.ac-conviction-val small { color: var(--ink-faint); }
+.ac-read-target { font-family: var(--font-mono); font-size: var(--text-base); color: var(--ink-bright); margin-bottom: var(--space-sm); }
+.ac-read-coinname { color: var(--ink-dim); font-family: var(--font-body); font-size: var(--text-sm); }
+
+.ac-guard { display: flex; gap: var(--space-xs); align-items: flex-start; font-size: var(--text-2xs); color: var(--warn); background: rgba(251, 191, 36, 0.08); border: 1px solid rgba(251, 191, 36, 0.25); border-radius: var(--radius-sm); padding: var(--space-xs) var(--space-sm); margin: 0 0 var(--space-sm); line-height: 1.4; }
+.ac-guard-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: var(--warn); margin-top: 5px; }
+
+.ac-risks { margin: 0 0 var(--space-md); padding-left: var(--space-md); display: flex; flex-direction: column; gap: var(--space-2xs); }
+.ac-risks li { font-size: var(--text-sm); color: var(--ink-dim); line-height: 1.45; }
+
+.ac-read-signals { border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); background: var(--surface-1); margin-bottom: var(--space-sm); }
+.ac-read-signals-head { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-faint); margin-bottom: var(--space-xs); }
+.ac-read-signals-head span { color: var(--success); text-transform: none; letter-spacing: 0; }
+.ac-read-signals dl { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-2xs) var(--space-md); margin: 0; }
+.ac-read-signals dl > div { display: flex; justify-content: space-between; gap: var(--space-sm); border-bottom: 1px dashed var(--stroke); padding: 3px 0; }
+.ac-read-signals dt { font-size: var(--text-sm); color: var(--ink-dim); }
+.ac-read-signals dd { margin: 0; font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink); }
+.ac-read-wallet { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-faint); margin-bottom: var(--space-sm); }
+
+.ac-action { margin-top: var(--space-sm); }
+.ac-action .ac-btn-act { width: 100%; }
+.ac-action-note { font-size: var(--text-2xs); color: var(--ink-faint); margin: var(--space-xs) 0 0; text-align: center; }
+.ac-action-blocked, .ac-action-public { font-size: var(--text-sm); color: var(--ink-dim); background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); margin: 0; text-align: center; }
+.ac-action-public { color: var(--wallet-accent); }
+
+/* ── launches ─────────────────────────────────────────────────────────────── */
+.ac-launches { padding: var(--space-sm); display: flex; flex-direction: column; }
+.ac-launches-head { display: flex; align-items: center; justify-content: space-between; padding: var(--space-xs) var(--space-sm) var(--space-sm); }
+.ac-launches-head h2 { display: flex; align-items: center; gap: var(--space-xs); font-size: var(--text-md); font-family: var(--font-display); margin: 0; color: var(--ink-bright); }
+.ac-launches-list { display: flex; flex-direction: column; gap: var(--space-sm); max-height: 620px; overflow-y: auto; padding: 0 var(--space-2xs); }
+.ac-launch { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); transition: border-color var(--duration-fast); }
+.ac-launch:hover { border-color: var(--wallet-stroke); }
+.ac-launch-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm); }
+.ac-launch-id { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
+.ac-launch-sym { font-family: var(--font-mono); font-weight: 700; color: var(--ink-bright); font-size: var(--text-md); }
+.ac-launch-name { font-size: var(--text-2xs); color: var(--ink-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 160px; }
+.ac-launch-age { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-faint); }
+.ac-launch-stats { display: flex; flex-wrap: wrap; gap: var(--space-xs); margin-top: var(--space-xs); }
+.ac-launch-stats span { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-dim); background: var(--surface-2); padding: 2px var(--space-xs); border-radius: var(--radius-sm); }
+.ac-launch-stats .is-good { color: var(--success); }
+.ac-flag { color: var(--danger) !important; background: rgba(248, 113, 113, 0.1) !important; }
+
+/* ── shared states ────────────────────────────────────────────────────────── */
+.ac-state { padding: var(--space-lg) var(--space-md); text-align: center; color: var(--ink-faint); font-size: var(--text-sm); display: flex; flex-direction: column; gap: var(--space-sm); align-items: center; }
+.ac-state-error { color: var(--danger); }
+.ac-skel { pointer-events: none; }
+.ac-skel-line { height: 9px; border-radius: var(--radius-sm); background: linear-gradient(90deg, var(--surface-1), var(--surface-3), var(--surface-1)); background-size: 200% 100%; animation: ac-shimmer 1.4s infinite; margin: var(--space-2xs) 0; }
+.ac-skel-line.w40 { width: 40%; } .ac-skel-line.w60 { width: 60%; } .ac-skel-line.w80 { width: 80%; }
+@keyframes ac-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+
+.ac-disclaimer { max-width: 760px; margin: var(--space-xl) auto 0; text-align: center; font-size: var(--text-2xs); color: var(--ink-faint); line-height: 1.5; }
+
+/* ── act drawer ───────────────────────────────────────────────────────────── */
+.ac-drawer { position: fixed; inset: 0; z-index: 1000; display: grid; place-items: center; padding: var(--space-md); }
+.ac-modal-backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(var(--blur-sm)); }
+.ac-drawer-card { position: relative; width: min(440px, 94vw); background: var(--bg-1); border: 1px solid var(--wallet-stroke); border-radius: var(--radius-lg); box-shadow: var(--shadow-3); padding: var(--space-lg); animation: ac-rise var(--duration-base) var(--ease-emphasized); }
+@keyframes ac-rise { from { transform: translateY(12px); opacity: 0; } }
+.ac-modal-x { position: absolute; top: var(--space-sm); right: var(--space-sm); width: 30px; height: 30px; border-radius: 50%; background: var(--surface-2); border: 1px solid var(--stroke); color: var(--ink-dim); cursor: pointer; font-size: 18px; line-height: 1; }
+.ac-modal-x:hover { color: var(--ink); }
+.ac-drawer-card h3 { font-family: var(--font-display); margin: 0 0 var(--space-md); color: var(--ink-bright); }
+.ac-act-lead { font-size: var(--text-base); color: var(--ink); margin: 0 0 var(--space-md); }
+.ac-act-quote { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); margin-bottom: var(--space-md); font-size: var(--text-sm); color: var(--ink-dim); }
+.ac-act-qrow { display: flex; justify-content: space-between; padding: 3px 0; }
+.ac-act-qrow strong { font-family: var(--font-mono); color: var(--ink); }
+.ac-act-warn { color: var(--warn); font-size: var(--text-2xs); margin: var(--space-xs) 0 0; }
+.ac-act-controls { display: flex; gap: var(--space-sm); }
+.ac-act-controls .ac-btn-act { flex: 1; }
+.ac-act-fine { font-size: var(--text-2xs); color: var(--ink-faint); margin: var(--space-sm) 0 0; line-height: 1.45; }
+.ac-act-done { text-align: center; }
+.ac-act-done-mark { width: 48px; height: 48px; margin: 0 auto var(--space-sm); border-radius: 50%; background: rgba(74, 222, 128, 0.14); color: var(--success); display: grid; place-items: center; font-size: 24px; border: 1px solid rgba(74, 222, 128, 0.4); }
+.ac-act-done p { color: var(--ink); margin: 0 0 var(--space-sm); }
+.ac-act-audit { display: inline-block; margin-top: var(--space-sm); color: var(--wallet-accent); font-size: var(--text-sm); text-decoration: none; }
+.ac-act-audit:hover { text-decoration: underline; }
+
+@media (prefers-reduced-motion: reduce) {
+ .ac-live-dot, .ac-thinking span, .ac-skel-line, .ac-speak.is-speaking, .ac-drawer-card { animation: none; }
+}
diff --git a/src/alpha-copilot.js b/src/alpha-copilot.js
new file mode 100644
index 000000000..69b1cb0d3
--- /dev/null
+++ b/src/alpha-copilot.js
@@ -0,0 +1,474 @@
+/**
+ * Alpha Co-pilot — client mount.
+ *
+ * The intelligence + voice layer on top of the wallet program's trade rails:
+ * an agent reads a REAL pump.fun launch in character (POST /api/agents/:id/alpha/read),
+ * its 3D avatar speaks the verdict aloud (TTS + talk animation), and the owner
+ * can act on the call through the SAME guarded path the conversational copilot
+ * uses (executeAgentTrade → POST /solana/trade) — clamped to the agent's spend
+ * limits and fully audited. The narrator never moves funds.
+ *
+ * Every number shown comes from the server's grounded `signals` bundle; a
+ * fabricated figure is rejected server-side and never reaches the avatar's mouth.
+ */
+
+import { agentAvatarGlb } from './shared/agent-3d.js';
+import { previewAgentTrade, executeAgentTrade, TradeError } from './agent-solana-wallet.js';
+
+const NETWORK = 'mainnet';
+const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
+const LS_KEY = 'ac_last_agent';
+
+const $ = (sel, root = document) => root.querySelector(sel);
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+// ── formatting ──────────────────────────────────────────────────────────────
+const num = (v) => (v == null || !Number.isFinite(Number(v)) ? null : Number(v));
+function fmtUsd(v) {
+ const n = num(v);
+ if (n == null) return '—';
+ if (n >= 1e9) return '$' + (n / 1e9).toFixed(2) + 'B';
+ if (n >= 1e6) return '$' + (n / 1e6).toFixed(2) + 'M';
+ if (n >= 1e3) return '$' + (n / 1e3).toFixed(1) + 'K';
+ return '$' + n.toFixed(0);
+}
+function fmtSol(v) { const n = num(v); return n == null ? '—' : '◎' + n.toLocaleString(undefined, { maximumFractionDigits: 4 }); }
+function fmtPct(v) { const n = num(v); return n == null ? '—' : n.toFixed(n >= 10 ? 0 : 1) + '%'; }
+function fmtScore(v) { const n = num(v); return n == null ? '—' : Math.round(n) + ''; }
+function ageLabel(seconds) {
+ const s = num(seconds);
+ if (s == null) return '—';
+ if (s < 90) return Math.round(s) + 's';
+ const m = Math.round(s / 60);
+ if (m < 90) return m + 'm';
+ const h = Math.round(m / 60);
+ if (h < 48) return h + 'h';
+ return Math.round(h / 24) + 'd';
+}
+function short(s, h = 4, t = 4) { return !s || s.length <= h + t + 1 ? s || '' : `${s.slice(0, h)}…${s.slice(-t)}`; }
+function explorerTxUrl(sig) { return `https://solscan.io/tx/${sig}`; }
+
+// ── state ──────────────────────────────────────────────────────────────────
+const state = {
+ agent: null, // full GET /api/agents/:id object
+ avatarEl: null, // <agent-3d>
+ candidates: [],
+ read: null, // last /alpha/read response
+ lastSpoken: '',
+ speaking: false,
+ loadingRead: false,
+};
+
+// ── DOM refs ────────────────────────────────────────────────────────────────
+const dom = {};
+function cacheDom() {
+ dom.agentInput = $('#ac-agent-input');
+ dom.agentLoad = $('#ac-agent-load');
+ dom.avatarHost = $('#ac-avatar-host');
+ dom.avatarPlaceholder = $('#ac-avatar-placeholder');
+ dom.agentName = $('#ac-agent-name');
+ dom.agentRole = $('#ac-agent-role');
+ dom.speak = $('#ac-speak');
+ dom.speakLine = $('#ac-speak-line');
+ dom.replay = $('#ac-replay');
+ dom.readEmpty = $('#ac-read-empty');
+ dom.readBody = $('#ac-read-body');
+ dom.launchesList = $('#ac-launches-list');
+ dom.refresh = $('#ac-refresh');
+ dom.actDrawer = $('#ac-act-drawer');
+ dom.actBody = $('#ac-act-body');
+}
+
+// ── agent loading ───────────────────────────────────────────────────────────
+function parseAgentId(raw) {
+ if (!raw) return null;
+ const m = String(raw).match(UUID_RE);
+ return m ? m[0] : null;
+}
+
+async function loadAgent(id) {
+ dom.agentName.textContent = 'Loading…';
+ dom.agentRole.textContent = 'Alpha co-pilot';
+ let agent;
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(id)}`, { credentials: 'include' });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j?.error?.message || `Could not load agent (${r.status})`);
+ agent = j.agent || j;
+ } catch (e) {
+ dom.agentName.textContent = 'Not found';
+ dom.agentRole.textContent = e.message || 'Could not load that agent';
+ state.agent = null;
+ return;
+ }
+ state.agent = agent;
+ try { localStorage.setItem(LS_KEY, agent.id); } catch { /* ignore */ }
+ dom.agentName.textContent = agent.name || 'Agent';
+ dom.agentRole.textContent = agent.is_owner ? 'Your alpha co-pilot' : 'Alpha co-pilot · public read';
+ mountAvatar(agent);
+ resetRead();
+ loadCandidates();
+}
+
+async function mountAvatar(agent) {
+ const glb = agentAvatarGlb(agent);
+ try { await import('./element.js'); } catch { /* element may already be registered */ }
+ // Rebuild the avatar element each load so a new agent shows its own body.
+ if (state.avatarEl) { try { state.avatarEl.remove(); } catch { /* ignore */ } state.avatarEl = null; }
+ if (dom.avatarPlaceholder) dom.avatarPlaceholder.hidden = true;
+ const el = document.createElement('agent-3d');
+ el.setAttribute('body', glb);
+ el.setAttribute('width', '100%');
+ el.setAttribute('height', '100%');
+ el.setAttribute('autorotate', '');
+ el.className = 'ac-avatar';
+ dom.avatarHost.appendChild(el);
+ state.avatarEl = el;
+}
+
+// ── candidate launches ──────────────────────────────────────────────────────
+async function loadCandidates() {
+ if (!state.agent) return;
+ dom.launchesList.innerHTML = skeletonLaunches(4);
+ let items = [];
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(state.agent.id)}/alpha/candidates?network=${NETWORK}`, { credentials: 'include' });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j?.error?.message || 'feed unavailable');
+ items = Array.isArray(j.items) ? j.items : [];
+ } catch (e) {
+ dom.launchesList.innerHTML = `<div class="ac-state ac-state-error"><p>Live feed hiccup — ${esc(e.message || 'try again')}.</p><button type="button" class="ac-btn ac-btn-ghost" id="ac-retry-feed">Retry</button></div>`;
+ $('#ac-retry-feed')?.addEventListener('click', loadCandidates);
+ return;
+ }
+ state.candidates = items;
+ if (!items.length) {
+ dom.launchesList.innerHTML = `<div class="ac-state"><p>No live launches on the feed this second. New pump.fun mints appear here the moment they land — hit Refresh.</p></div>`;
+ return;
+ }
+ dom.launchesList.innerHTML = '';
+ for (const c of items) dom.launchesList.appendChild(launchCard(c));
+}
+
+function launchCard(c) {
+ const node = document.createElement('article');
+ node.className = 'ac-launch';
+ const label = c.symbol ? `$${esc(c.symbol)}` : short(c.mint, 4, 4);
+ const sm = num(c.smart_money_score);
+ const q = num(c.quality_score);
+ node.innerHTML = `
+ <div class="ac-launch-head">
+ <div class="ac-launch-id">
+ <span class="ac-launch-sym">${label}</span>
+ ${c.name ? `<span class="ac-launch-name">${esc(c.name)}</span>` : ''}
+ </div>
+ <span class="ac-launch-age" title="Age">${ageLabel(c.age_seconds)}</span>
+ </div>
+ <div class="ac-launch-stats">
+ <span title="Market cap">${fmtUsd(c.market_cap_usd)}</span>
+ <span title="Smart-money score" class="${sm != null && sm >= 60 ? 'is-good' : ''}">SM ${fmtScore(sm)}</span>
+ <span title="Quality score" class="${q != null && q >= 60 ? 'is-good' : ''}">Q ${fmtScore(q)}</span>
+ ${c.sybil_flag ? '<span class="ac-flag" title="One funder cluster dominates">sybil</span>' : ''}
+ </div>
+ <button type="button" class="ac-btn ac-btn-read" data-mint="${esc(c.mint)}">Ask for a read</button>`;
+ node.querySelector('.ac-btn-read').addEventListener('click', () => requestRead(c.mint, label));
+ return node;
+}
+
+// ── the read ────────────────────────────────────────────────────────────────
+function resetRead() {
+ state.read = null;
+ dom.readEmpty.hidden = false;
+ dom.readBody.hidden = true;
+ dom.readBody.innerHTML = '';
+ dom.speak.hidden = true;
+ dom.speakLine.textContent = '';
+}
+
+async function requestRead(mint, label) {
+ if (!state.agent || state.loadingRead) return;
+ state.loadingRead = true;
+ dom.readEmpty.hidden = true;
+ dom.readBody.hidden = false;
+ dom.readBody.innerHTML = `<div class="ac-read-loading"><div class="ac-thinking"><span></span><span></span><span></span></div><p>${esc(state.agent.name || 'The agent')} is reading ${esc(label || 'this launch')}…</p></div>`;
+ setSpeaking(false);
+
+ let data;
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(state.agent.id)}/alpha/read`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ mint, network: NETWORK }),
+ });
+ data = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(data?.error_description || (typeof data?.error === 'object' ? data.error?.message : null) || `Read failed (${r.status})`);
+ } catch (e) {
+ dom.readBody.innerHTML = `<div class="ac-state ac-state-error"><p>${esc(e.message || 'The read failed.')}</p><button type="button" class="ac-btn ac-btn-ghost" id="ac-read-retry">Try again</button></div>`;
+ $('#ac-read-retry')?.addEventListener('click', () => requestRead(mint, label));
+ state.loadingRead = false;
+ return;
+ }
+ state.read = data;
+ state.loadingRead = false;
+ renderRead(data);
+ speakAloud(data.agent, data.read?.spoken_line || '');
+}
+
+function verdictMeta(v) {
+ if (v === 'snipe') return { label: 'Snipe', cls: 'is-snipe' };
+ if (v === 'pass') return { label: 'Pass', cls: 'is-pass' };
+ return { label: 'Watch', cls: 'is-watch' };
+}
+
+function renderRead(data) {
+ const read = data.read || {};
+ const sig = data.signals || {};
+ const vm = verdictMeta(read.verdict);
+ const conviction = num(read.conviction) ?? 0;
+ const sym = sig.symbol ? `$${esc(sig.symbol)}` : short(data.mint, 4, 4);
+
+ const signalRows = [
+ ['Liquidity', fmtSol(sig.liquidity_sol)],
+ ['Market cap', fmtUsd(sig.market_cap_usd)],
+ ['Age', sig.age_minutes != null ? `${sig.age_minutes}m` : '—'],
+ ['Buy impact (◎0.1)', fmtPct(sig.reference_buy_price_impact_pct)],
+ ['Curve filled', sig.bonding_curve_progress_pct != null ? `${sig.bonding_curve_progress_pct}%` : '—'],
+ ['Quality', fmtScore(sig.quality_score)],
+ ['Smart money', sig.smart_money_score != null ? `${fmtScore(sig.smart_money_score)} · ${sig.smart_money_wallets ?? 0} wallet${sig.smart_money_wallets === 1 ? '' : 's'}` : '—'],
+ ['Organic', fmtScore(sig.organic_score)],
+ ].filter(([, v]) => v !== '—' || true);
+
+ const ownerWallet = data.owner && sig.wallet_balance_sol != null
+ ? `<div class="ac-read-wallet">Wallet ${fmtSol(sig.wallet_balance_sol)} · per-trade ${sig.per_trade_limit_sol != null ? fmtSol(sig.per_trade_limit_sol) : '∞'} · daily ${sig.daily_budget_sol != null ? fmtSol(sig.daily_budget_sol) : '∞'}${sig.trading_paused ? ' · <span class="ac-flag">paused</span>' : ''}</div>`
+ : '';
+
+ const guard = read.hallucination_guard || {};
+ const guardNote = guard.line_replaced
+ ? `<p class="ac-guard"><span class="ac-guard-dot"></span> A figure in the draft didn't match the live data, so the co-pilot spoke a grounded line instead. The signals below are the ground truth.</p>`
+ : '';
+
+ dom.readBody.innerHTML = `
+ <div class="ac-read-top">
+ <div class="ac-verdict ${vm.cls}">${vm.label}</div>
+ <div class="ac-conviction" title="Conviction">
+ <div class="ac-conviction-bar"><span style="width:${Math.max(2, conviction)}%"></span></div>
+ <span class="ac-conviction-val">${conviction}<small>/100</small></span>
+ </div>
+ </div>
+ <div class="ac-read-target">${sym}${sig.name ? ` · <span class="ac-read-coinname">${esc(sig.name)}</span>` : ''}</div>
+ ${guardNote}
+ ${read.risks?.length ? `<ul class="ac-risks">${read.risks.map((r) => `<li>${esc(r)}</li>`).join('')}</ul>` : ''}
+ <div class="ac-read-signals">
+ <div class="ac-read-signals-head">Signals it used <span>(live, on-chain)</span></div>
+ <dl>${signalRows.map(([k, v]) => `<div><dt>${esc(k)}</dt><dd>${v}</dd></div>`).join('')}</dl>
+ </div>
+ ${ownerWallet}
+ <div class="ac-action" id="ac-action"></div>`;
+
+ renderAction(data);
+}
+
+function renderAction(data) {
+ const host = $('#ac-action');
+ if (!host) return;
+ const gate = data.gate || {};
+ if (gate.can_act) {
+ host.innerHTML = `<button type="button" class="ac-btn ac-btn-act" id="ac-act-go">Act — buy ${fmtSol(gate.size_sol)} SOL</button>
+ <p class="ac-action-note">${esc(gate.message || '')}</p>`;
+ $('#ac-act-go')?.addEventListener('click', () => openActDrawer(data));
+ } else {
+ const cls = data.owner ? 'ac-action-blocked' : 'ac-action-public';
+ host.innerHTML = `<p class="${cls}">${esc(gate.message || 'No action available.')}</p>`;
+ }
+}
+
+// ── voice ───────────────────────────────────────────────────────────────────
+let currentAudio = null;
+function setSpeaking(on) {
+ state.speaking = on;
+ dom.speak?.classList.toggle('is-speaking', on);
+ $('.ac-stage')?.classList.toggle('is-speaking', on);
+}
+
+async function fetchTtsBlob(agent, text) {
+ const provider = agent?.voice_provider || 'browser';
+ const body = JSON.stringify({ text: text.slice(0, 800), voice: agent?.voice_id || 'nova' });
+ const headers = { 'content-type': 'application/json' };
+ try {
+ if (provider === 'elevenlabs' && agent?.voice_id) {
+ const r = await fetch('/api/tts/eleven', { method: 'POST', credentials: 'include', headers, body: JSON.stringify({ voiceId: agent.voice_id, text: text.slice(0, 500) }) });
+ if (r.ok) return await r.blob();
+ }
+ // Default + cloned-but-non-eleven providers: the server's free TTS lane.
+ const r = await fetch('/api/tts/speak', { method: 'POST', credentials: 'include', headers, body });
+ if (r.ok) return await r.blob();
+ } catch { /* fall through to browser TTS */ }
+ return null;
+}
+
+function playBlob(blob) {
+ return new Promise((resolve) => {
+ try {
+ if (currentAudio) { try { currentAudio.pause(); } catch { /* ignore */ } }
+ const url = URL.createObjectURL(blob);
+ const audio = new Audio(url);
+ currentAudio = audio;
+ audio.addEventListener('ended', () => { URL.revokeObjectURL(url); resolve(true); }, { once: true });
+ audio.addEventListener('error', () => { URL.revokeObjectURL(url); resolve(false); }, { once: true });
+ audio.play().catch(() => resolve(false));
+ } catch { resolve(false); }
+ });
+}
+
+function browserSpeak(text) {
+ return new Promise((resolve) => {
+ if (typeof speechSynthesis === 'undefined' || !window.SpeechSynthesisUtterance) return resolve(false);
+ try {
+ speechSynthesis.cancel();
+ const u = new SpeechSynthesisUtterance(text);
+ u.rate = 1.02; u.pitch = 1;
+ u.onend = () => resolve(true);
+ u.onerror = () => resolve(false);
+ speechSynthesis.speak(u);
+ } catch { resolve(false); }
+ });
+}
+
+async function speakAloud(agent, text) {
+ const line = (text || '').trim();
+ if (!line) return;
+ state.lastSpoken = line;
+ dom.speak.hidden = false;
+ dom.speakLine.textContent = line;
+ setSpeaking(true);
+ // Gesture: the avatar plays a talk animation for the line's length.
+ try { state.avatarEl?.speak?.(line); } catch { /* avatar still mounting */ }
+ let played = false;
+ const blob = await fetchTtsBlob(agent, line);
+ if (blob) played = await playBlob(blob);
+ if (!played) played = await browserSpeak(line);
+ setSpeaking(false);
+}
+
+// ── act (owner) ─────────────────────────────────────────────────────────────
+function openActDrawer(data) {
+ const gate = data.gate || {};
+ const sig = data.signals || {};
+ const sym = sig.symbol ? `$${esc(sig.symbol)}` : short(data.mint, 4, 4);
+ dom.actBody.innerHTML = `
+ <p class="ac-act-lead">${esc(state.agent?.name || 'Your agent')} wants to buy <strong>${fmtSol(gate.size_sol)} SOL</strong> of ${sym}.</p>
+ <div class="ac-act-quote" id="ac-act-quote">Fetching a fresh live quote…</div>
+ <div class="ac-act-controls">
+ <button type="button" class="ac-btn ac-btn-act" id="ac-act-confirm" disabled>Confirm buy</button>
+ <button type="button" class="ac-btn ac-btn-ghost" data-close>Cancel</button>
+ </div>
+ <p class="ac-act-fine">Executes through the agent's guarded wallet — re-checked against the firewall and your spend limits at submit, and written to the custody audit.</p>`;
+ showDrawer(true);
+
+ const confirmBtn = $('#ac-act-confirm');
+ const quoteHost = $('#ac-act-quote');
+ let quote = null;
+ previewAgentTrade({ agentId: state.agent.id, side: 'buy', mint: data.mint, solAmount: gate.size_sol, slippageBps: 300, network: NETWORK })
+ .then((q) => {
+ quote = q;
+ const impact = num(q?.price_impact_pct ?? q?.priceImpactPct);
+ const expected = q?.expected_out ?? q?.out?.amount ?? q?.outUi;
+ const warn = q?.warning || q?.blocked_reason;
+ quoteHost.innerHTML = `
+ <div class="ac-act-qrow"><span>You pay</span><strong>${fmtSol(gate.size_sol)} SOL</strong></div>
+ ${expected != null ? `<div class="ac-act-qrow"><span>Expected</span><strong>${Number(expected).toLocaleString(undefined, { maximumFractionDigits: 2 })} ${esc(sig.symbol || 'tokens')}</strong></div>` : ''}
+ <div class="ac-act-qrow"><span>Price impact</span><strong>${fmtPct(impact)}</strong></div>
+ ${warn ? `<p class="ac-act-warn">${esc(warn)}</p>` : ''}`;
+ confirmBtn.disabled = false;
+ })
+ .catch((e) => {
+ quoteHost.innerHTML = `<p class="ac-act-warn">Couldn't fetch a live quote: ${esc(e.message || 'try again')}.</p>`;
+ });
+
+ confirmBtn?.addEventListener('click', async () => {
+ confirmBtn.disabled = true;
+ confirmBtn.textContent = 'Submitting…';
+ try {
+ const res = await executeAgentTrade({
+ agentId: state.agent.id, side: 'buy', mint: data.mint,
+ solAmount: gate.size_sol, slippageBps: 300, network: NETWORK,
+ idempotencyKey: (crypto?.randomUUID?.() || `ac-${Date.now()}-${Math.random().toString(16).slice(2)}`),
+ });
+ const sig2 = res?.signature;
+ const spent = res?.sol_spent ?? gate.size_sol;
+ dom.actBody.innerHTML = `
+ <div class="ac-act-done">
+ <div class="ac-act-done-mark">✓</div>
+ <p>Bought into ${sym} for ${fmtSol(spent)} SOL.</p>
+ ${sig2 ? `<a class="ac-btn ac-btn-ghost" href="${esc(res.explorer || explorerTxUrl(sig2))}" target="_blank" rel="noopener">View transaction</a>` : ''}
+ ${res?.new_balance_sol != null ? `<p class="ac-act-fine">Wallet now ${fmtSol(res.new_balance_sol)}.</p>` : ''}
+ <a class="ac-act-audit" href="/agent/${esc(state.agent.id)}" target="_blank" rel="noopener">See it in the custody trail →</a>
+ </div>`;
+ } catch (e) {
+ const msg = e instanceof TradeError ? e.message : (e?.message || 'Trade failed.');
+ dom.actBody.querySelector('.ac-act-controls')?.insertAdjacentHTML('beforebegin', `<p class="ac-act-warn">${esc(msg)}</p>`);
+ confirmBtn.disabled = false;
+ confirmBtn.textContent = 'Confirm buy';
+ }
+ });
+}
+
+function showDrawer(open) {
+ dom.actDrawer.hidden = !open;
+ document.body.style.overflow = open ? 'hidden' : '';
+}
+function wireDrawer() {
+ dom.actDrawer.addEventListener('click', (e) => {
+ if (e.target.matches('[data-close]')) showDrawer(false);
+ });
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !dom.actDrawer.hidden) showDrawer(false); });
+}
+
+// ── skeletons ───────────────────────────────────────────────────────────────
+function skeletonLaunches(n) {
+ return Array.from({ length: n }, () => `<div class="ac-launch ac-skel"><div class="ac-skel-line w60"></div><div class="ac-skel-line w40"></div><div class="ac-skel-line w80"></div></div>`).join('');
+}
+
+// ── boot ────────────────────────────────────────────────────────────────────
+async function resolveInitialAgent() {
+ const url = new URL(location.href);
+ const fromUrl = parseAgentId(url.searchParams.get('agent'));
+ if (fromUrl) return fromUrl;
+ const stored = (() => { try { return localStorage.getItem(LS_KEY); } catch { return null; } })();
+ if (stored && UUID_RE.test(stored)) return stored;
+ // Logged-in default: the caller's own agent.
+ try {
+ const r = await fetch('/api/agents/me', { credentials: 'include' });
+ if (r.ok) { const j = await r.json().catch(() => ({})); const a = j.agent || j; if (a?.id) return a.id; }
+ } catch { /* logged out — prompt for an id */ }
+ return null;
+}
+
+async function init() {
+ cacheDom();
+ wireDrawer();
+ dom.agentLoad.addEventListener('click', () => {
+ const id = parseAgentId(dom.agentInput.value);
+ if (id) loadAgent(id);
+ else { dom.agentInput.focus(); dom.agentInput.classList.add('is-invalid'); setTimeout(() => dom.agentInput.classList.remove('is-invalid'), 1200); }
+ });
+ dom.agentInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') dom.agentLoad.click(); });
+ dom.refresh.addEventListener('click', loadCandidates);
+ dom.replay.addEventListener('click', () => { if (state.lastSpoken) speakAloud(state.read?.agent || state.agent, state.lastSpoken); });
+ const mintFromUrl = new URL(location.href).searchParams.get('mint');
+
+ const id = await resolveInitialAgent();
+ if (id) {
+ await loadAgent(id);
+ dom.agentInput.value = id;
+ if (mintFromUrl && UUID_RE.test(id)) requestRead(mintFromUrl, null);
+ } else {
+ dom.avatarPlaceholder.textContent = 'Enter an agent id (or paste a profile URL) to begin.';
+ dom.agentName.textContent = 'No agent';
+ dom.agentRole.textContent = 'Pick an agent to hear its read';
+ }
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
+else init();
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 74eb66128..e7a6b6e66 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -21,6 +21,7 @@ import { mountAgentVanityGrinderCard } from './agent-vanity-grinder.js';
import { mountRoyaltySetting } from './shared/agent-fork-royalty.js';
import { hydrateAvatarWallet, walletTierBadge } from './shared/wallet-aura.js';
import { mountPresence } from './shared/networth-presence.js';
+import { emitRecallFromChat } from './agents/memory-client.js';
const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';
@@ -1841,6 +1842,11 @@ async function sendChatMessage(text) {
assistantNode.textContent = acc;
log.scrollTop = log.scrollHeight;
streamThoughtText(acc);
+ } else if (evt.type === 'done') {
+ // The server reports exactly which memories it recalled into this
+ // reply's context — turn that into a `memory:recalled` bus event so
+ // the HUD, Mind Palace, and any other surface can react live.
+ emitRecallFromChat(isUuid ? agentIdMaybe : null, evt, text);
} else if (evt.type === 'error') {
throw new Error(evt.message || evt.error || 'Stream error');
}
diff --git a/src/brain-studio.js b/src/brain-studio.js
new file mode 100644
index 000000000..cf4854d82
--- /dev/null
+++ b/src/brain-studio.js
@@ -0,0 +1,1037 @@
+// Brain Studio — sculpt your agent's mind and feel the change land on the live
+// avatar within a second.
+//
+// You don't write a system prompt here; you direct a character. Trait sliders,
+// tone chips, and characteristic vocabulary compile (deterministically, via the
+// shared compiler in src/agents/persona-compile.js) into a real persona prompt.
+// Every change re-runs a REAL /api/chat against that candidate prompt (owner-only
+// persona_override) and the avatar re-greets in the new register, in the agent's
+// real voice. A/B compare runs real dual inference; promoting a side writes a
+// real agent_versions entry and emits `brain:updated` so the Companion re-greets
+// everywhere.
+//
+// Mounted lazily by src/agent-edit.js when the Brain tab opens.
+
+import { apiFetch } from './api.js';
+import {
+ PERSONA_TRAITS,
+ defaultTraitValues,
+ clampTraits,
+ describeTrait,
+ compilePersona,
+ registerSummary,
+ bandIndex,
+} from './agents/persona-compile.js';
+import { agentBus, EVENTS } from './agents/agent-bus.js';
+
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+const PROBES = [
+ { id: 'greet', label: 'Greet me', prompt: 'Greet me in one or two sentences, in character.' },
+ { id: 'explain', label: 'What do you do?', prompt: 'In two sentences, tell me what you can help me with — in character.' },
+ { id: 'take', label: 'Honest take', prompt: 'Give me your honest, in-character take on whether I should ship a feature that is 90% done today or polish it for one more week.' },
+];
+
+let STYLE_INJECTED = false;
+function injectStyle() {
+ if (STYLE_INJECTED) return;
+ STYLE_INJECTED = true;
+ const css = `
+.brain-studio{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.05fr);gap:24px;align-items:start}
+@media (max-width:900px){.brain-studio{grid-template-columns:1fr}}
+.bs-col{min-width:0}
+.bs-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;margin:0 0 4px}
+.bs-head h2{font-size:1.05rem;margin:0;font-weight:650}
+.bs-sub{font-size:.78rem;color:rgba(255,255,255,.5);margin:0 0 18px}
+.bs-dna{font-variant:small-caps;letter-spacing:.02em;color:#a4f0bc}
+.bs-trait{margin:0 0 16px}
+.bs-trait-top{display:flex;justify-content:space-between;align-items:baseline;font-size:.78rem;margin-bottom:5px}
+.bs-trait-label{font-weight:600;color:rgba(255,255,255,.92)}
+.bs-trait-val{color:#7aa2ff;font-weight:600;font-variant:small-caps}
+.bs-trait-poles{display:flex;justify-content:space-between;font-size:.66rem;color:rgba(255,255,255,.38);margin-top:3px}
+.bs-range{-webkit-appearance:none;appearance:none;width:100%;height:6px;border-radius:999px;background:linear-gradient(90deg,#1c2030,#2a3350);outline:none;cursor:pointer}
+.bs-range::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:18px;height:18px;border-radius:50%;background:#7aa2ff;border:2px solid #0b0d14;box-shadow:0 1px 4px rgba(0,0,0,.5);transition:transform .1s}
+.bs-range::-moz-range-thumb{width:18px;height:18px;border-radius:50%;background:#7aa2ff;border:2px solid #0b0d14;cursor:pointer}
+.bs-range:hover::-webkit-slider-thumb,.bs-range:focus::-webkit-slider-thumb{transform:scale(1.12)}
+.bs-range:focus-visible{box-shadow:0 0 0 3px rgba(122,162,255,.4)}
+.bs-section-title{font-size:.7rem;text-transform:uppercase;letter-spacing:.08em;color:rgba(255,255,255,.45);margin:22px 0 8px;font-weight:600}
+.bs-chips{display:flex;flex-wrap:wrap;gap:7px}
+.bs-chip{display:inline-flex;align-items:center;gap:6px;background:rgba(122,162,255,.14);border:1px solid rgba(122,162,255,.3);color:#cdd9ff;border-radius:999px;padding:4px 6px 4px 11px;font-size:.74rem;font-weight:500}
+.bs-chip button{background:none;border:0;color:inherit;cursor:pointer;font-size:14px;line-height:1;opacity:.6;padding:0 2px;border-radius:50%}
+.bs-chip button:hover{opacity:1;color:#fff}
+.bs-chip-add{display:inline-flex;gap:6px}
+.bs-input{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.14);color:#fff;border-radius:8px;padding:6px 10px;font-size:.78rem;min-width:0;width:100%}
+.bs-input:focus{outline:none;border-color:#7aa2ff;box-shadow:0 0 0 3px rgba(122,162,255,.18)}
+.bs-vocab{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
+.bs-vocab li{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:6px 8px 6px 12px;font-size:.76rem;color:rgba(255,255,255,.86)}
+.bs-vocab li span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.bs-vocab li button{background:none;border:0;color:rgba(255,255,255,.5);cursor:pointer;font-size:15px;line-height:1}
+.bs-vocab li button:hover{color:#fff}
+.bs-stage{position:relative;background:radial-gradient(120% 100% at 50% 0%,#161a28 0%,#0b0d14 70%);border:1px solid rgba(255,255,255,.09);border-radius:16px;overflow:hidden;aspect-ratio:1/1;max-height:360px}
+.bs-stage agent-3d{width:100%;height:100%;display:block}
+.bs-bubble{position:absolute;left:14px;right:14px;bottom:14px;min-height:46px;background:rgba(12,14,20,.82);backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.1);border-radius:12px;padding:11px 13px;font-size:.82rem;line-height:1.45;color:#eef1f8;transition:opacity .2s;max-height:46%;overflow:auto}
+.bs-bubble.thinking{color:rgba(255,255,255,.5)}
+.bs-bubble .bs-caret{display:inline-block;width:7px;height:1.05em;background:#7aa2ff;margin-left:1px;vertical-align:-2px;animation:bs-blink 1s steps(2) infinite}
+@keyframes bs-blink{50%{opacity:0}}
+.bs-dots span{display:inline-block;width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,.5);margin-right:4px;animation:bs-bounce 1.2s infinite}
+.bs-dots span:nth-child(2){animation-delay:.15s}.bs-dots span:nth-child(3){animation-delay:.3s}
+@keyframes bs-bounce{0%,60%,100%{transform:translateY(0);opacity:.5}30%{transform:translateY(-4px);opacity:1}}
+.bs-controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}
+.bs-probes{display:flex;gap:6px;flex-wrap:wrap}
+.bs-probe{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);color:rgba(255,255,255,.8);border-radius:999px;padding:5px 11px;font-size:.72rem;font-weight:600;cursor:pointer;transition:all .12s}
+.bs-probe[aria-pressed="true"]{background:rgba(122,162,255,.22);border-color:rgba(122,162,255,.5);color:#fff}
+.bs-probe:hover{border-color:rgba(122,162,255,.5)}
+.bs-iconbtn{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);color:rgba(255,255,255,.85);border-radius:8px;padding:6px 10px;font-size:.74rem;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:6px;transition:all .12s}
+.bs-iconbtn:hover{border-color:rgba(122,162,255,.5);color:#fff}
+.bs-iconbtn[aria-pressed="true"]{background:rgba(164,240,188,.18);border-color:rgba(164,240,188,.45);color:#cdeed5}
+.bs-iconbtn:disabled{opacity:.45;cursor:not-allowed}
+.bs-savebar{display:flex;gap:10px;align-items:center;margin-top:18px;flex-wrap:wrap}
+.bs-save{background:#7aa2ff;color:#0b0d14;border:0;border-radius:9px;padding:9px 18px;font-size:.82rem;font-weight:700;cursor:pointer;transition:filter .12s}
+.bs-save:hover{filter:brightness(1.08)}
+.bs-save:disabled{opacity:.5;cursor:not-allowed}
+.bs-status{font-size:.76rem}.bs-status.ok{color:#a4f0bc}.bs-status.err{color:#fca5a5}
+.bs-dirty{font-size:.72rem;color:#fcd34d}
+.bs-disclosure{margin-top:18px;border-top:1px solid rgba(255,255,255,.08);padding-top:14px}
+.bs-disclosure>summary{cursor:pointer;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.78);list-style:none;display:flex;align-items:center;gap:8px}
+.bs-disclosure>summary::-webkit-details-marker{display:none}
+.bs-disclosure>summary::before{content:'▸';color:#7aa2ff;transition:transform .15s}
+.bs-disclosure[open]>summary::before{transform:rotate(90deg)}
+.bs-diff{font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-word;background:#0a0c12;border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:12px;margin-top:10px;max-height:280px;overflow:auto}
+.bs-diff .add{background:rgba(34,197,94,.16);color:#bbf7d0;display:block}
+.bs-diff .del{background:rgba(239,68,68,.14);color:#fecaca;text-decoration:line-through;display:block;opacity:.8}
+.bs-diff .ctx{color:rgba(255,255,255,.6);display:block}
+.bs-versions{list-style:none;margin:10px 0 0;padding:0;display:flex;flex-direction:column;gap:6px}
+.bs-versions li{display:flex;align-items:center;gap:10px;font-size:.76rem;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:8px;padding:7px 10px}
+.bs-versions .v{color:#7aa2ff;font-weight:700;font-variant:tabular-nums}
+.bs-versions .note{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:rgba(255,255,255,.78)}
+.bs-versions .when{color:rgba(255,255,255,.4);font-size:.7rem}
+.bs-versions button{background:none;border:1px solid rgba(255,255,255,.18);color:rgba(255,255,255,.8);border-radius:6px;padding:3px 9px;font-size:.7rem;cursor:pointer}
+.bs-versions button:hover{border-color:#7aa2ff;color:#fff}
+.bs-ab{display:grid;grid-template-columns:1fr 1fr;gap:14px}
+.bs-ab-side{display:flex;flex-direction:column;gap:8px}
+.bs-ab-side h3{margin:0;font-size:.74rem;text-transform:uppercase;letter-spacing:.06em;color:rgba(255,255,255,.55)}
+.bs-ab-side .bs-stage{max-height:240px}
+.bs-promote{background:rgba(164,240,188,.16);border:1px solid rgba(164,240,188,.4);color:#cdeed5;border-radius:8px;padding:7px;font-size:.74rem;font-weight:700;cursor:pointer}
+.bs-promote:hover{filter:brightness(1.1)}
+.bs-empty{text-align:center;color:rgba(255,255,255,.5);font-size:.8rem;padding:18px}
+.bs-error{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);color:#fecaca;border-radius:10px;padding:12px 14px;font-size:.8rem}
+.bs-error button{margin-top:8px}
+@media (prefers-reduced-motion:reduce){.bs-caret,.bs-dots span{animation:none}}
+`;
+ const tag = document.createElement('style');
+ tag.id = 'brain-studio-style';
+ tag.textContent = css;
+ document.head.appendChild(tag);
+}
+
+// ── agent-3d loader (mirrors agent-edit.js) ─────────────────────────────────
+async function ensureAgent3DLib() {
+ if (customElements.get('agent-3d')) return true;
+ for (const url of [
+ 'https://three.ws/agent-3d/latest/agent-3d.js',
+ '/agent-3d/latest/agent-3d.js',
+ '/dist-lib/agent-3d.js',
+ ]) {
+ try {
+ await import(/* @vite-ignore */ url);
+ if (customElements.get('agent-3d')) return true;
+ } catch {
+ /* next */
+ }
+ }
+ return false;
+}
+
+// ── Real voice synthesis in the agent's configured voice ────────────────────
+function createVoice(agentId) {
+ let cfg = null;
+ let cfgLoaded = false;
+ let enabled = false;
+ let audio = null;
+ let objectUrl = null;
+ let controller = null;
+
+ async function loadCfg() {
+ if (cfgLoaded) return cfg;
+ cfgLoaded = true;
+ try {
+ const r = await apiFetch(`/api/agents/${agentId}/voice`, { credentials: 'include' });
+ if (r.ok) cfg = await r.json();
+ } catch {
+ cfg = null;
+ }
+ return cfg;
+ }
+
+ function cancel() {
+ if (controller) {
+ controller.abort();
+ controller = null;
+ }
+ if (audio) {
+ audio.pause();
+ audio.onended = audio.onerror = null;
+ audio = null;
+ }
+ if (objectUrl) {
+ URL.revokeObjectURL(objectUrl);
+ objectUrl = null;
+ }
+ }
+
+ // Fetch a clip in the agent's real voice and play it. Returns true if audio
+ // began. Never throws; degrades silently to the on-screen text bubble.
+ async function speak(text) {
+ cancel();
+ if (!enabled || !text) return false;
+ await loadCfg();
+ controller = new AbortController();
+ let blob;
+ try {
+ const isEleven = cfg?.voice_provider === 'elevenlabs' && cfg?.voice_id;
+ const res = isEleven
+ ? await apiFetch('/api/tts/eleven', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ voiceId: cfg.voice_id, text: text.slice(0, 600) }),
+ signal: controller.signal,
+ })
+ : await apiFetch('/api/tts/speak', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ text: text.slice(0, 600), voice: cfg?.voice_id || 'nova', format: 'mp3' }),
+ signal: controller.signal,
+ });
+ if (!res.ok) return false;
+ blob = await res.blob();
+ } catch {
+ return false;
+ }
+ if (!blob || blob.size === 0) return false;
+ objectUrl = URL.createObjectURL(blob);
+ audio = new Audio(objectUrl);
+ try {
+ await audio.play();
+ return true;
+ } catch {
+ cancel();
+ return false;
+ }
+ }
+
+ return {
+ speak,
+ cancel,
+ setEnabled(v) {
+ enabled = v;
+ if (!v) cancel();
+ },
+ isEnabled: () => enabled,
+ loadCfg,
+ };
+}
+
+// ── Real streamed /api/chat against a candidate persona ─────────────────────
+// onChunk(text) per token; resolves with the full reply. Honours abort.
+async function streamPersona({ agentId, personaOverride, message, signal, onChunk }) {
+ const res = await apiFetch('/api/chat', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ agentId, persona_override: personaOverride, message, history: [] }),
+ signal,
+ });
+ if (!res.ok || !res.body) {
+ const j = await res.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || `chat failed (${res.status})`);
+ }
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let full = '';
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop();
+ for (const line of lines) {
+ if (!line.startsWith('data: ')) continue;
+ const raw = line.slice(6).trim();
+ if (!raw) continue;
+ let evt;
+ try {
+ evt = JSON.parse(raw);
+ } catch {
+ continue;
+ }
+ if (evt.type === 'chunk' && evt.text) {
+ full += evt.text;
+ onChunk?.(evt.text, full);
+ } else if (evt.type === 'error') {
+ throw new Error(evt.message || 'stream error');
+ }
+ }
+ }
+ return full.trim();
+}
+
+// ── Minimal line diff (LCS) for the prompt-change view ──────────────────────
+function lineDiff(a, b) {
+ const A = (a || '').split('\n');
+ const B = (b || '').split('\n');
+ const n = A.length;
+ const m = B.length;
+ const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
+ for (let i = n - 1; i >= 0; i--)
+ for (let j = m - 1; j >= 0; j--)
+ dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
+ const out = [];
+ let i = 0;
+ let j = 0;
+ while (i < n && j < m) {
+ if (A[i] === B[j]) {
+ out.push({ t: 'ctx', line: A[i] });
+ i++;
+ j++;
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
+ out.push({ t: 'del', line: A[i] });
+ i++;
+ } else {
+ out.push({ t: 'add', line: B[j] });
+ j++;
+ }
+ }
+ while (i < n) out.push({ t: 'del', line: A[i++] });
+ while (j < m) out.push({ t: 'add', line: B[j++] });
+ return out;
+}
+
+// ════════════════════════════════════════════════════════════════════════════
+export async function mountBrainStudio(host, { agentId, agent }) {
+ injectStyle();
+
+ // ── State ────────────────────────────────────────────────────────────────
+ const state = {
+ name: agent?.name || 'Agent',
+ description: agent?.description || '',
+ traits: defaultTraitValues(),
+ toneTags: [],
+ vocabulary: [],
+ base: '',
+ // Last-saved baseline — for dirty detection, diff, and the A side.
+ saved: { traits: defaultTraitValues(), toneTags: [], vocabulary: [], base: '', prompt: '' },
+ probe: 'greet',
+ abMode: false,
+ loaded: false,
+ };
+
+ const voice = createVoice(agentId);
+ let previewTimer = null;
+ let previewAbort = null;
+ let avatarEl = null; // main preview avatar
+ let abAvatars = { a: null, b: null };
+ let abAborts = { a: null, b: null };
+
+ host.innerHTML = `<div class="bs-empty"><span class="bs-dots"><span></span><span></span><span></span></span> Loading the Brain Studio…</div>`;
+
+ // ── Load real persona ──────────────────────────────────────────────────────
+ let data;
+ try {
+ const r = await apiFetch(`/api/agents/${agentId}/persona`, { credentials: 'include' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ data = await r.json();
+ } catch (err) {
+ host.innerHTML = `<div class="bs-error">Couldn't load this agent's persona: ${esc(err.message)}.
+ <div><button class="bs-iconbtn" id="bs-retry">Try again</button></div></div>`;
+ host.querySelector('#bs-retry')?.addEventListener('click', () => mountBrainStudio(host, { agentId, agent }));
+ return;
+ }
+
+ state.name = data.name || state.name;
+ state.description = data.description || state.description;
+ state.traits = clampTraits(data.traits || {});
+ state.toneTags = Array.isArray(data.tone_tags) ? data.tone_tags.slice(0, 12) : [];
+ state.vocabulary = Array.isArray(data.vocabulary) ? data.vocabulary.slice(0, 10) : [];
+ state.base = data.base || '';
+ state.saved = {
+ traits: { ...state.traits },
+ toneTags: [...state.toneTags],
+ vocabulary: [...state.vocabulary],
+ base: state.base,
+ prompt: data.persona_prompt || '',
+ };
+ state.loaded = true;
+
+ // ── Build DOM ──────────────────────────────────────────────────────────────
+ host.innerHTML = '';
+ const root = document.createElement('div');
+ root.className = 'brain-studio';
+ root.innerHTML = template();
+ host.appendChild(root);
+
+ const $ = (sel) => root.querySelector(sel);
+
+ function template() {
+ return `
+ <div class="bs-col bs-editor">
+ <div class="bs-head"><h2>Brain Studio</h2></div>
+ <p class="bs-sub" id="bs-dna">${esc(registerSummary(state.traits))}</p>
+
+ <div id="bs-traits">${PERSONA_TRAITS.map(traitRow).join('')}</div>
+
+ <div class="bs-section-title">Tone</div>
+ <div class="bs-chips" id="bs-tone"></div>
+ <div class="bs-chip-add" style="margin-top:8px">
+ <input class="bs-input" id="bs-tone-input" placeholder="Add a tone word, e.g. candid" maxlength="40" aria-label="Add tone word">
+ </div>
+
+ <div class="bs-section-title">Characteristic phrasing</div>
+ <ul class="bs-vocab" id="bs-vocab"></ul>
+ <div class="bs-chip-add" style="margin-top:8px">
+ <input class="bs-input" id="bs-vocab-input" placeholder="Add a phrase it naturally uses" maxlength="120" aria-label="Add characteristic phrase">
+ </div>
+
+ <div class="bs-savebar">
+ <input class="bs-input" id="bs-changelog" placeholder="What changed? (optional note for this version)" maxlength="280" style="flex:1;min-width:140px" aria-label="Version note">
+ <button class="bs-save" id="bs-save">Save persona</button>
+ <span class="bs-dirty" id="bs-dirty" hidden>● unsaved</span>
+ <span class="bs-status" id="bs-status" role="status" aria-live="polite"></span>
+ </div>
+
+ <div style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap">
+ <button class="bs-iconbtn" id="bs-rerun">🎙 Re-run interview</button>
+ <button class="bs-iconbtn" id="bs-ab-toggle" aria-pressed="false">⚖ Compare A/B</button>
+ <button class="bs-iconbtn" id="bs-dna-copy">🧬 Copy DNA</button>
+ <button class="bs-iconbtn" id="bs-reset" title="Revert to last saved">↺ Revert</button>
+ </div>
+
+ <details class="bs-disclosure" id="bs-diff-wrap">
+ <summary>How this rewrote the underlying prompt</summary>
+ <div class="bs-diff" id="bs-diff"></div>
+ </details>
+
+ <details class="bs-disclosure" id="bs-hist-wrap">
+ <summary>Version history</summary>
+ <ul class="bs-versions" id="bs-versions"><li class="bs-empty">Loading…</li></ul>
+ </details>
+ </div>
+
+ <div class="bs-col bs-preview">
+ <div id="bs-single">
+ <div class="bs-stage" id="bs-stage"><div class="bs-bubble thinking" id="bs-bubble">Adjust a trait — your agent re-greets in the new character.</div></div>
+ <div class="bs-controls">
+ <div class="bs-probes" id="bs-probes">${PROBES.map((p) => `<button class="bs-probe" data-probe="${p.id}" aria-pressed="${p.id === state.probe}">${esc(p.label)}</button>`).join('')}</div>
+ </div>
+ <div class="bs-controls">
+ <button class="bs-iconbtn" id="bs-regen">↻ Re-greet</button>
+ <button class="bs-iconbtn" id="bs-voice" aria-pressed="false">🔊 Voice off</button>
+ </div>
+ </div>
+ <div id="bs-ab" hidden></div>
+ </div>`;
+ }
+
+ function traitRow(t) {
+ const v = state.traits[t.key];
+ return `
+ <div class="bs-trait" data-trait="${t.key}">
+ <div class="bs-trait-top">
+ <span class="bs-trait-label">${esc(t.label)}</span>
+ <span class="bs-trait-val" data-val="${t.key}">${esc(describeTrait(t.key, v))}</span>
+ </div>
+ <input class="bs-range" type="range" min="0" max="100" value="${Math.round(v * 100)}"
+ data-trait-input="${t.key}" aria-label="${esc(t.label)}: ${esc(t.hint)}"
+ aria-valuetext="${esc(describeTrait(t.key, v))}">
+ <div class="bs-trait-poles"><span>${esc(t.low)}</span><span>${esc(t.high)}</span></div>
+ </div>`;
+ }
+
+ // ── Candidate persona compilation (client side; identical to server) ────────
+ function candidatePrompt(traits = state.traits, toneTags = state.toneTags, vocabulary = state.vocabulary, base = state.base) {
+ return compilePersona({ name: state.name, description: state.description, base, traits, toneTags, vocabulary });
+ }
+
+ function isDirty() {
+ const s = state.saved;
+ if (s.base !== state.base) return true;
+ if (s.toneTags.join('|') !== state.toneTags.join('|')) return true;
+ if (s.vocabulary.join('|') !== state.vocabulary.join('|')) return true;
+ return PERSONA_TRAITS.some((t) => Math.round(s.traits[t.key] * 100) !== Math.round(state.traits[t.key] * 100));
+ }
+
+ function refreshMeta() {
+ $('#bs-dna').textContent = registerSummary(state.traits);
+ $('#bs-dirty').hidden = !isDirty();
+ renderDiff();
+ }
+
+ function renderTone() {
+ $('#bs-tone').innerHTML = state.toneTags.length
+ ? state.toneTags
+ .map((t, i) => `<span class="bs-chip">${esc(t)}<button data-tone-rm="${i}" aria-label="Remove ${esc(t)}">×</button></span>`)
+ .join('')
+ : `<span style="font-size:.74rem;color:rgba(255,255,255,.4)">No tone words yet — add a few.</span>`;
+ $('#bs-tone')
+ .querySelectorAll('[data-tone-rm]')
+ .forEach((b) =>
+ b.addEventListener('click', () => {
+ state.toneTags.splice(Number(b.dataset.toneRm), 1);
+ renderTone();
+ onEdit();
+ }),
+ );
+ }
+
+ function renderVocab() {
+ $('#bs-vocab').innerHTML = state.vocabulary.length
+ ? state.vocabulary
+ .map((v, i) => `<li><span title="${esc(v)}">${esc(v)}</span><button data-vocab-rm="${i}" aria-label="Remove phrase">×</button></li>`)
+ .join('')
+ : `<li class="bs-empty" style="padding:8px">No signature phrases yet.</li>`;
+ $('#bs-vocab')
+ .querySelectorAll('[data-vocab-rm]')
+ .forEach((b) =>
+ b.addEventListener('click', () => {
+ state.vocabulary.splice(Number(b.dataset.vocabRm), 1);
+ renderVocab();
+ onEdit();
+ }),
+ );
+ }
+
+ function renderDiff() {
+ const wrap = $('#bs-diff-wrap');
+ if (!wrap || !wrap.open) return;
+ const diff = lineDiff(state.saved.prompt, candidatePrompt());
+ $('#bs-diff').innerHTML = diff
+ .map((d) => `<span class="${d.t}">${d.t === 'add' ? '+ ' : d.t === 'del' ? '- ' : ' '}${esc(d.line) || '&nbsp;'}</span>`)
+ .join('');
+ }
+
+ // ── Live preview ────────────────────────────────────────────────────────────
+ function setBubble(html, { thinking = false } = {}) {
+ const b = $('#bs-bubble');
+ if (!b) return;
+ b.classList.toggle('thinking', thinking);
+ b.innerHTML = html;
+ }
+
+ function schedulePreview() {
+ if (!avatarEl) return; // single preview not mounted (A/B mode)
+ clearTimeout(previewTimer);
+ setBubble(`<span class="bs-dots"><span></span><span></span><span></span></span>`, { thinking: true });
+ previewTimer = setTimeout(runPreview, 600);
+ }
+
+ async function runPreview() {
+ if (previewAbort) previewAbort.abort();
+ previewAbort = new AbortController();
+ const probe = PROBES.find((p) => p.id === state.probe) || PROBES[0];
+ const prompt = candidatePrompt();
+ try {
+ avatarEl?.playGesture?.('think', { hold: 0.6 });
+ let any = false;
+ const reply = await streamPersona({
+ agentId,
+ personaOverride: prompt,
+ message: probe.prompt,
+ signal: previewAbort.signal,
+ onChunk: (_t, full) => {
+ any = true;
+ setBubble(`${esc(full)}<span class="bs-caret"></span>`);
+ },
+ });
+ if (!reply && !any) {
+ setBubble('No reply came back — try again.', { thinking: true });
+ return;
+ }
+ setBubble(esc(reply));
+ avatarEl?.speak?.(reply);
+ voice.speak(reply);
+ } catch (err) {
+ if (err.name === 'AbortError') return;
+ setBubble(`Preview failed: ${esc(err.message)}. <button class="bs-iconbtn" id="bs-prev-retry" style="margin-top:6px">Retry</button>`, { thinking: true });
+ $('#bs-prev-retry')?.addEventListener('click', runPreview);
+ }
+ }
+
+ // Any edit: update derived UI, mark dirty, re-run preview.
+ function onEdit() {
+ refreshMeta();
+ schedulePreview();
+ }
+
+ // ── Wire trait sliders ──────────────────────────────────────────────────────
+ root.querySelectorAll('[data-trait-input]').forEach((inp) => {
+ inp.addEventListener('input', () => {
+ const key = inp.dataset.traitInput;
+ state.traits[key] = Number(inp.value) / 100;
+ const word = describeTrait(key, state.traits[key]);
+ const valEl = root.querySelector(`[data-val="${key}"]`);
+ if (valEl) valEl.textContent = word;
+ inp.setAttribute('aria-valuetext', word);
+ // Cheap UI updates immediately; the network preview is debounced.
+ refreshMeta();
+ schedulePreview();
+ });
+ });
+
+ // Tone + vocab inputs (Enter to add)
+ $('#bs-tone-input').addEventListener('keydown', (e) => {
+ if (e.key !== 'Enter') return;
+ e.preventDefault();
+ const v = e.target.value.trim().slice(0, 40);
+ if (v && !state.toneTags.some((t) => t.toLowerCase() === v.toLowerCase()) && state.toneTags.length < 12) {
+ state.toneTags.push(v);
+ renderTone();
+ onEdit();
+ }
+ e.target.value = '';
+ });
+ $('#bs-vocab-input').addEventListener('keydown', (e) => {
+ if (e.key !== 'Enter') return;
+ e.preventDefault();
+ const v = e.target.value.trim().slice(0, 120);
+ if (v && !state.vocabulary.some((p) => p.toLowerCase() === v.toLowerCase()) && state.vocabulary.length < 10) {
+ state.vocabulary.push(v);
+ renderVocab();
+ onEdit();
+ }
+ e.target.value = '';
+ });
+
+ // Probe selector
+ $('#bs-probes').addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-probe]');
+ if (!btn) return;
+ state.probe = btn.dataset.probe;
+ $('#bs-probes')
+ .querySelectorAll('[data-probe]')
+ .forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
+ if (state.abMode) runAB();
+ else runPreview();
+ });
+
+ $('#bs-regen').addEventListener('click', () => (state.abMode ? runAB() : runPreview()));
+
+ $('#bs-voice').addEventListener('click', (e) => {
+ const on = !voice.isEnabled();
+ voice.setEnabled(on);
+ e.currentTarget.setAttribute('aria-pressed', String(on));
+ e.currentTarget.textContent = on ? '🔊 Voice on' : '🔊 Voice off';
+ });
+
+ $('#bs-diff-wrap').addEventListener('toggle', renderDiff);
+ $('#bs-hist-wrap').addEventListener('toggle', (e) => {
+ if (e.target.open) loadVersions();
+ });
+
+ $('#bs-reset').addEventListener('click', () => {
+ state.traits = { ...state.saved.traits };
+ state.toneTags = [...state.saved.toneTags];
+ state.vocabulary = [...state.saved.vocabulary];
+ state.base = state.saved.base;
+ syncControls();
+ onEdit();
+ });
+
+ $('#bs-dna-copy').addEventListener('click', async (e) => {
+ const dna = personalityDNA();
+ try {
+ await navigator.clipboard.writeText(dna);
+ e.currentTarget.textContent = '🧬 Copied!';
+ setTimeout(() => (e.currentTarget.textContent = '🧬 Copy DNA'), 1500);
+ } catch {
+ setStatus('Clipboard unavailable', 'err');
+ }
+ });
+
+ $('#bs-save').addEventListener('click', save);
+ $('#bs-rerun').addEventListener('click', openInterview);
+ $('#bs-ab-toggle').addEventListener('click', toggleAB);
+
+ // Cmd/Ctrl+S saves while focus is inside the studio.
+ root.addEventListener('keydown', (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
+ e.preventDefault();
+ save();
+ }
+ });
+
+ function syncControls() {
+ root.querySelectorAll('[data-trait-input]').forEach((inp) => {
+ const key = inp.dataset.traitInput;
+ inp.value = Math.round(state.traits[key] * 100);
+ const word = describeTrait(key, state.traits[key]);
+ const valEl = root.querySelector(`[data-val="${key}"]`);
+ if (valEl) valEl.textContent = word;
+ inp.setAttribute('aria-valuetext', word);
+ });
+ renderTone();
+ renderVocab();
+ }
+
+ function personalityDNA() {
+ const traitLine = PERSONA_TRAITS.map((t) => `${t.label} ${Math.round(state.traits[t.key] * 100)}`).join(' · ');
+ return [
+ `🧬 ${state.name} — personality DNA`,
+ registerSummary(state.traits),
+ traitLine,
+ state.toneTags.length ? `Tone: ${state.toneTags.join(', ')}` : '',
+ 'Sculpted in the three.ws Brain Studio',
+ ]
+ .filter(Boolean)
+ .join('\n');
+ }
+
+ function setStatus(msg, kind = '') {
+ const el = $('#bs-status');
+ el.textContent = msg;
+ el.className = `bs-status ${kind}`;
+ if (kind === 'ok') setTimeout(() => { if (el.textContent === msg) el.textContent = ''; }, 3000);
+ }
+
+ // ── Save ─────────────────────────────────────────────────────────────────
+ async function save() {
+ if (!isDirty()) {
+ setStatus('Nothing to save.', 'ok');
+ return;
+ }
+ const btn = $('#bs-save');
+ btn.disabled = true;
+ setStatus('Saving…');
+ try {
+ const r = await apiFetch(`/api/agents/${agentId}/persona/save`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ traits: state.traits,
+ tone_tags: state.toneTags,
+ vocabulary: state.vocabulary,
+ base: state.base,
+ changelog: $('#bs-changelog').value.trim() || undefined,
+ }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ state.saved = {
+ traits: { ...state.traits },
+ toneTags: [...state.toneTags],
+ vocabulary: [...state.vocabulary],
+ base: state.base,
+ prompt: j.persona_prompt || candidatePrompt(),
+ };
+ $('#bs-changelog').value = '';
+ refreshMeta();
+ setStatus(`Saved as v${j.version}.`, 'ok');
+ // Bus: the Companion + every surface re-greet in the new character.
+ agentBus.emit(EVENTS.BRAIN_UPDATED, {
+ agentId,
+ personaPrompt: j.persona_prompt,
+ toneTags: j.tone_tags,
+ change: j.changelog,
+ ts: j.updated_at || undefined,
+ });
+ if ($('#bs-hist-wrap').open) loadVersions();
+ } catch (err) {
+ setStatus(`Error: ${err.message}`, 'err');
+ } finally {
+ btn.disabled = false;
+ }
+ }
+
+ // ── Version history + restore ───────────────────────────────────────────
+ async function loadVersions() {
+ const ul = $('#bs-versions');
+ ul.innerHTML = `<li class="bs-empty">Loading…</li>`;
+ try {
+ const r = await apiFetch(`/api/agents/${agentId}/persona/versions`, { credentials: 'include' });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error_description || `HTTP ${r.status}`);
+ const versions = j.versions || [];
+ if (!versions.length) {
+ ul.innerHTML = `<li class="bs-empty" style="padding:12px">No saved versions yet. Your next save is v1 of this persona.</li>`;
+ return;
+ }
+ ul.innerHTML = versions
+ .map(
+ (v) => `<li>
+ <span class="v">v${v.version}</span>
+ <span class="note" title="${esc(v.changelog || '')}">${esc(v.changelog || 'Persona updated')}</span>
+ <span class="when">${esc(new Date(v.created_at).toLocaleDateString())}</span>
+ <button data-restore="${v.version}">Restore</button>
+ </li>`,
+ )
+ .join('');
+ ul.querySelectorAll('[data-restore]').forEach((b) =>
+ b.addEventListener('click', () => restore(Number(b.dataset.restore))),
+ );
+ } catch (err) {
+ ul.innerHTML = `<li class="bs-error">Couldn't load history: ${esc(err.message)}</li>`;
+ }
+ }
+
+ async function restore(version) {
+ setStatus(`Restoring v${version}…`);
+ try {
+ const r = await apiFetch(`/api/agents/${agentId}/persona/restore`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ version }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ state.traits = clampTraits(j.traits);
+ state.toneTags = j.tone_tags || [];
+ state.vocabulary = j.vocabulary || [];
+ state.base = j.base || '';
+ state.saved = {
+ traits: { ...state.traits },
+ toneTags: [...state.toneTags],
+ vocabulary: [...state.vocabulary],
+ base: state.base,
+ prompt: j.persona_prompt || candidatePrompt(),
+ };
+ syncControls();
+ refreshMeta();
+ setStatus(`Restored v${j.restored_from} as v${j.version}.`, 'ok');
+ agentBus.emit(EVENTS.BRAIN_UPDATED, {
+ agentId,
+ personaPrompt: j.persona_prompt,
+ toneTags: j.tone_tags,
+ change: j.changelog,
+ });
+ loadVersions();
+ schedulePreview();
+ } catch (err) {
+ setStatus(`Error: ${err.message}`, 'err');
+ }
+ }
+
+ // ── A/B compare (real dual inference) ───────────────────────────────────
+ async function toggleAB() {
+ state.abMode = !state.abMode;
+ $('#bs-ab-toggle').setAttribute('aria-pressed', String(state.abMode));
+ const single = $('#bs-single');
+ const abWrap = $('#bs-ab');
+ if (state.abMode) {
+ // Free the single-preview context before opening two more.
+ disposeAvatar();
+ single.hidden = true;
+ abWrap.hidden = false;
+ abWrap.innerHTML = `
+ <div class="bs-section-title" style="margin-top:0">A — last saved &nbsp;·&nbsp; B — your edits · same prompt to both</div>
+ <div class="bs-ab">
+ <div class="bs-ab-side"><h3>A · Saved</h3><div class="bs-stage"><div class="bs-bubble thinking" id="bs-ab-bubble-a">…</div></div><button class="bs-promote" data-promote="a">Keep A (saved)</button></div>
+ <div class="bs-ab-side"><h3>B · Your edits</h3><div class="bs-stage"><div class="bs-bubble thinking" id="bs-ab-bubble-b">…</div></div><button class="bs-promote" data-promote="b">Promote B →</button></div>
+ </div>`;
+ abWrap.querySelector('[data-promote="a"]').addEventListener('click', () => promote('a'));
+ abWrap.querySelector('[data-promote="b"]').addEventListener('click', () => promote('b'));
+ await ensureAgent3DLib();
+ const stages = abWrap.querySelectorAll('.bs-stage');
+ abAvatars.a = makeAvatar();
+ abAvatars.b = makeAvatar();
+ stages[0].insertBefore(abAvatars.a, stages[0].firstChild);
+ stages[1].insertBefore(abAvatars.b, stages[1].firstChild);
+ runAB();
+ } else {
+ disposeAB();
+ abWrap.hidden = true;
+ abWrap.innerHTML = '';
+ single.hidden = false;
+ await mountAvatar();
+ schedulePreview();
+ }
+ }
+
+ async function runAB() {
+ const probe = PROBES.find((p) => p.id === state.probe) || PROBES[0];
+ const sides = [
+ { key: 'a', prompt: compilePersona({ name: state.name, description: state.description, base: state.saved.base, traits: state.saved.traits, toneTags: state.saved.toneTags, vocabulary: state.saved.vocabulary }), el: abAvatars.a, bubble: '#bs-ab-bubble-a' },
+ { key: 'b', prompt: candidatePrompt(), el: abAvatars.b, bubble: '#bs-ab-bubble-b' },
+ ];
+ await Promise.all(
+ sides.map(async (s) => {
+ if (abAborts[s.key]) abAborts[s.key].abort();
+ abAborts[s.key] = new AbortController();
+ const bub = $(s.bubble);
+ if (bub) {
+ bub.classList.add('thinking');
+ bub.innerHTML = `<span class="bs-dots"><span></span><span></span><span></span></span>`;
+ }
+ try {
+ const reply = await streamPersona({
+ agentId,
+ personaOverride: s.prompt,
+ message: probe.prompt,
+ signal: abAborts[s.key].signal,
+ onChunk: (_t, full) => {
+ if (bub) {
+ bub.classList.remove('thinking');
+ bub.innerHTML = `${esc(full)}<span class="bs-caret"></span>`;
+ }
+ },
+ });
+ if (bub) bub.innerHTML = esc(reply);
+ s.el?.speak?.(reply);
+ } catch (err) {
+ if (err.name === 'AbortError') return;
+ if (bub) {
+ bub.classList.add('thinking');
+ bub.textContent = `Failed: ${err.message}`;
+ }
+ }
+ }),
+ );
+ }
+
+ async function promote(side) {
+ if (side === 'a') {
+ // Keep A — revert working edits to the saved baseline.
+ state.traits = { ...state.saved.traits };
+ state.toneTags = [...state.saved.toneTags];
+ state.vocabulary = [...state.saved.vocabulary];
+ state.base = state.saved.base;
+ syncControls();
+ refreshMeta();
+ await toggleAB(); // exit compare
+ setStatus('Kept the saved persona (A).', 'ok');
+ return;
+ }
+ // Promote B — exit compare, then save the current edits as the winner.
+ await toggleAB();
+ await save();
+ }
+
+ // ── Avatar lifecycle ───────────────────────────────────────────────────────
+ function makeAvatar() {
+ const el = document.createElement('agent-3d');
+ el.setAttribute('agent-id', agentId);
+ el.setAttribute('chat', 'off');
+ el.setAttribute('mode', 'section');
+ el.style.cssText = 'width:100%;height:100%;display:block';
+ return el;
+ }
+
+ async function mountAvatar() {
+ const ok = await ensureAgent3DLib();
+ const stage = $('#bs-stage');
+ if (!ok || !stage) return;
+ avatarEl = makeAvatar();
+ stage.insertBefore(avatarEl, stage.firstChild);
+ }
+
+ function disposeAvatar() {
+ if (previewAbort) previewAbort.abort();
+ clearTimeout(previewTimer);
+ avatarEl?.remove();
+ avatarEl = null;
+ }
+
+ function disposeAB() {
+ for (const k of ['a', 'b']) {
+ abAborts[k]?.abort();
+ abAborts[k] = null;
+ abAvatars[k]?.remove();
+ abAvatars[k] = null;
+ }
+ }
+
+ // ── Re-run interview modal ──────────────────────────────────────────────
+ function openInterview() {
+ const QUESTIONS = [
+ 'How would a close colleague describe the way you communicate?',
+ 'When you explain something complex, what is your style?',
+ 'What words, phrases, or metaphors do you reach for often?',
+ 'How do you handle disagreement or bad news?',
+ 'What should this agent never sound like?',
+ ];
+ const overlay = document.createElement('div');
+ overlay.style.cssText =
+ 'position:fixed;inset:0;z-index:9999;background:rgba(6,8,12,.72);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;padding:20px';
+ overlay.innerHTML = `
+ <div role="dialog" aria-modal="true" aria-label="Re-run persona interview" style="background:#11141d;border:1px solid rgba(255,255,255,.12);border-radius:16px;max-width:560px;width:100%;max-height:88vh;overflow:auto;padding:24px">
+ <h2 style="margin:0 0 4px;font-size:1.05rem">Re-run the persona interview</h2>
+ <p style="margin:0 0 16px;color:rgba(255,255,255,.5);font-size:.8rem">Five answers become a fresh base persona (your trait sliders still apply on top). Limited to 5 runs a day.</p>
+ <form id="bs-int-form">
+ ${QUESTIONS.map((q, i) => `<label style="display:block;margin-bottom:12px"><span style="display:block;font-size:.78rem;font-weight:600;margin-bottom:5px">${i + 1}. ${esc(q)}</span><textarea required minlength="5" maxlength="1000" rows="2" class="bs-input" data-q="${i}" style="resize:vertical"></textarea></label>`).join('')}
+ <div style="display:flex;gap:10px;align-items:center;margin-top:8px">
+ <button type="submit" class="bs-save">Extract persona</button>
+ <button type="button" class="bs-iconbtn" id="bs-int-cancel">Cancel</button>
+ <span class="bs-status" id="bs-int-status" role="status" aria-live="polite"></span>
+ </div>
+ </form>
+ </div>`;
+ document.body.appendChild(overlay);
+ const close = () => overlay.remove();
+ overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
+ overlay.querySelector('#bs-int-cancel').addEventListener('click', close);
+ const firstField = overlay.querySelector('textarea');
+ firstField?.focus();
+ const escHandler = (e) => { if (e.key === 'Escape') { close(); document.removeEventListener('keydown', escHandler); } };
+ document.addEventListener('keydown', escHandler);
+
+ overlay.querySelector('#bs-int-form').addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const answers = [...overlay.querySelectorAll('[data-q]')].map((t) => t.value.trim());
+ const stat = overlay.querySelector('#bs-int-status');
+ stat.textContent = 'Extracting…';
+ stat.className = 'bs-status';
+ try {
+ const r = await apiFetch(`/api/agents/${agentId}/persona/extract`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ answers }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (r.status === 429) throw new Error('Daily limit reached (5 per day). Try again tomorrow.');
+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ state.base = j.base || '';
+ state.toneTags = j.tone_tags || state.toneTags;
+ state.vocabulary = j.vocabulary || state.vocabulary;
+ if (j.traits) state.traits = clampTraits(j.traits);
+ state.saved = {
+ traits: { ...state.traits },
+ toneTags: [...state.toneTags],
+ vocabulary: [...state.vocabulary],
+ base: state.base,
+ prompt: j.system_prompt || candidatePrompt(),
+ };
+ syncControls();
+ refreshMeta();
+ close();
+ document.removeEventListener('keydown', escHandler);
+ setStatus('New base persona extracted & saved.', 'ok');
+ agentBus.emit(EVENTS.BRAIN_UPDATED, { agentId, personaPrompt: j.system_prompt, toneTags: j.tone_tags, change: 'Re-ran persona interview', ts: j.extracted_at || undefined });
+ schedulePreview();
+ } catch (err) {
+ stat.textContent = err.message;
+ stat.className = 'bs-status err';
+ }
+ });
+ }
+
+ // ── First paint ────────────────────────────────────────────────────────────
+ renderTone();
+ renderVocab();
+ refreshMeta();
+ await mountAvatar();
+ // Kick off the first live greeting so the stage isn't a dead body.
+ schedulePreview();
+
+ // Hand back a disposer so the host can tear down WebGL contexts on unmount.
+ return {
+ dispose() {
+ disposeAvatar();
+ disposeAB();
+ voice.cancel();
+ },
+ };
+}
diff --git a/src/genesis.css b/src/genesis.css
new file mode 100644
index 000000000..3b7e54eaa
--- /dev/null
+++ b/src/genesis.css
@@ -0,0 +1,853 @@
+/* Instant Agent Genesis — selfie/prompt → 3D agent → funded wallet → on-chain
+ identity in under a minute. Styling leans on the shared design tokens
+ (public/tokens.css) with safe fallbacks so the page stays portable. */
+
+:root {
+ --gx-gap: var(--space-md, 16px);
+ --gx-radius: var(--radius-lg, 14px);
+ --gx-radius-sm: var(--radius-md, 10px);
+ --gx-border: 1px solid rgba(255, 255, 255, 0.08);
+ --gx-border-strong: 1px solid rgba(255, 255, 255, 0.16);
+ --gx-surface: rgba(255, 255, 255, 0.03);
+ --gx-surface-2: rgba(255, 255, 255, 0.05);
+ --gx-gold: rgb(var(--gold-rgb, 255, 215, 0));
+ --gx-max: 1080px;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ background: var(--bg, #000);
+ color: var(--ink, #e8e8e8);
+ font:
+ 15px/1.55 -apple-system,
+ BlinkMacSystemFont,
+ 'Segoe UI',
+ Roboto,
+ sans-serif;
+ min-height: 100vh;
+}
+
+.skip-link {
+ position: absolute;
+ left: -999px;
+ top: 0;
+ z-index: 100;
+ padding: var(--space-sm, 10px) var(--space-md, 16px);
+ background: var(--gx-gold);
+ color: #000;
+ border-radius: 0 0 var(--gx-radius-sm) 0;
+ font-weight: 600;
+}
+.skip-link:focus {
+ left: 0;
+}
+
+.gx {
+ max-width: var(--gx-max);
+ margin: 0 auto;
+ padding: clamp(20px, 5vw, 56px) clamp(16px, 4vw, 32px) 96px;
+}
+
+/* ── Headline ─────────────────────────────────────────────────────────── */
+.gx-head {
+ text-align: center;
+ margin-bottom: clamp(24px, 5vw, 44px);
+}
+.gx-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ color: var(--gx-gold);
+ border: 1px solid rgba(var(--gold-rgb, 255, 215, 0), 0.32);
+ background: rgba(var(--gold-rgb, 255, 215, 0), 0.06);
+ padding: 5px 12px;
+ border-radius: var(--radius-pill, 999px);
+}
+.gx-eyebrow::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 999px;
+ background: var(--gx-gold);
+ box-shadow: 0 0 10px var(--gx-gold);
+ animation: gx-pulse 2.4s ease-in-out infinite;
+}
+.gx-title {
+ font-size: clamp(1.9rem, 5.5vw, 3.2rem);
+ line-height: 1.05;
+ font-weight: 700;
+ margin: 18px 0 10px;
+ letter-spacing: -0.02em;
+ color: var(--ink-bright, #fff);
+}
+.gx-title em {
+ font-style: normal;
+ background: linear-gradient(120deg, var(--gx-gold), #fff7d6 60%, var(--gx-gold));
+ -webkit-background-clip: text;
+ background-clip: text;
+ -webkit-text-fill-color: transparent;
+}
+.gx-sub {
+ color: var(--ink-dim, #888);
+ font-size: clamp(0.95rem, 2vw, 1.1rem);
+ max-width: 560px;
+ margin: 0 auto;
+}
+
+/* ── Stages ───────────────────────────────────────────────────────────── */
+.gx-stage {
+ animation: gx-rise var(--duration-slow, 420ms) var(--ease-emphasized, cubic-bezier(0.22, 1, 0.36, 1)) both;
+}
+
+.gx-card {
+ background: var(--gx-surface);
+ border: var(--gx-border);
+ border-radius: var(--gx-radius);
+ padding: clamp(16px, 3vw, 28px);
+}
+
+/* ── Auth banner ──────────────────────────────────────────────────────── */
+.gx-auth {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ margin-bottom: var(--gx-gap);
+ padding: 12px 16px;
+ border: 1px solid rgba(var(--gold-rgb, 255, 215, 0), 0.28);
+ background: rgba(var(--gold-rgb, 255, 215, 0), 0.05);
+ border-radius: var(--gx-radius-sm);
+}
+.gx-auth p {
+ margin: 0;
+ color: var(--ink, #e8e8e8);
+ font-size: var(--text-sm, 13px);
+}
+
+/* ── Mode tabs ────────────────────────────────────────────────────────── */
+.gx-tabs {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 8px;
+ margin-bottom: var(--gx-gap);
+}
+.gx-tab {
+ appearance: none;
+ cursor: pointer;
+ text-align: left;
+ background: var(--gx-surface);
+ border: var(--gx-border);
+ border-radius: var(--gx-radius-sm);
+ padding: 14px 16px;
+ color: var(--ink, #e8e8e8);
+ transition:
+ border-color var(--duration-fast, 140ms) var(--ease-standard, ease),
+ background var(--duration-fast, 140ms) var(--ease-standard, ease),
+ transform var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.gx-tab:hover {
+ background: var(--gx-surface-2);
+ border-color: rgba(255, 255, 255, 0.2);
+}
+.gx-tab:focus-visible {
+ outline: 2px solid var(--gx-gold);
+ outline-offset: 2px;
+}
+.gx-tab[aria-selected='true'] {
+ border-color: var(--gx-gold);
+ background: rgba(var(--gold-rgb, 255, 215, 0), 0.08);
+}
+.gx-tab strong {
+ display: block;
+ font-size: var(--text-md, 13px);
+ margin-bottom: 3px;
+}
+.gx-tab span {
+ display: block;
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #888);
+}
+.gx-tab-icon {
+ font-size: 18px;
+ margin-bottom: 8px;
+ display: block;
+}
+
+/* ── Panels ───────────────────────────────────────────────────────────── */
+.gx-panel {
+ margin-bottom: var(--gx-gap);
+}
+.gx-panel[hidden] {
+ display: none;
+}
+
+label.gx-label {
+ display: block;
+ font-size: var(--text-sm, 13px);
+ color: var(--ink, #e8e8e8);
+ margin-bottom: 6px;
+ font-weight: 600;
+}
+.gx-hint {
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #888);
+ margin: 6px 0 0;
+}
+
+textarea.gx-input,
+input.gx-input,
+select.gx-input {
+ width: 100%;
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: var(--gx-border-strong);
+ border-radius: var(--gx-radius-sm);
+ color: var(--ink-bright, #fff);
+ padding: 12px 14px;
+ font: inherit;
+ resize: vertical;
+ transition: border-color var(--duration-fast, 140ms) ease;
+}
+textarea.gx-input {
+ min-height: 96px;
+}
+.gx-input:focus {
+ outline: none;
+ border-color: var(--gx-gold);
+}
+.gx-input::placeholder {
+ color: var(--ink-faint, rgba(255, 255, 255, 0.4));
+}
+
+.gx-field {
+ margin-bottom: var(--gx-gap);
+}
+.gx-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: var(--gx-gap);
+}
+
+/* example chips */
+.gx-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 7px;
+ margin-top: 10px;
+}
+.gx-chip {
+ appearance: none;
+ cursor: pointer;
+ font: inherit;
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #aaa);
+ background: var(--gx-surface);
+ border: var(--gx-border);
+ border-radius: var(--radius-pill, 999px);
+ padding: 5px 11px;
+ transition: all var(--duration-fast, 140ms) ease;
+}
+.gx-chip:hover {
+ color: #fff;
+ border-color: var(--gx-gold);
+}
+
+/* selfie dropzone */
+.gx-drop {
+ position: relative;
+ border: 1.5px dashed rgba(255, 255, 255, 0.22);
+ border-radius: var(--gx-radius);
+ padding: 28px 16px;
+ text-align: center;
+ cursor: pointer;
+ transition: border-color var(--duration-fast, 140ms) ease, background var(--duration-fast, 140ms) ease;
+}
+.gx-drop:hover,
+.gx-drop.is-drag {
+ border-color: var(--gx-gold);
+ background: rgba(var(--gold-rgb, 255, 215, 0), 0.04);
+}
+.gx-drop input[type='file'] {
+ display: none;
+}
+.gx-drop-icon {
+ font-size: 26px;
+ display: block;
+ margin-bottom: 8px;
+}
+.gx-preview {
+ margin-top: 12px;
+ display: none;
+ align-items: center;
+ gap: 12px;
+}
+.gx-preview.is-on {
+ display: flex;
+}
+.gx-preview img {
+ width: 84px;
+ height: 84px;
+ object-fit: cover;
+ border-radius: var(--gx-radius-sm);
+ border: var(--gx-border-strong);
+}
+.gx-privacy {
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-faint, rgba(255, 255, 255, 0.45));
+ margin-top: 10px;
+ line-height: 1.5;
+}
+
+/* remix grid */
+.gx-remix-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));
+ gap: 10px;
+ max-height: 320px;
+ overflow-y: auto;
+ padding: 2px;
+}
+.gx-remix-tile {
+ appearance: none;
+ cursor: pointer;
+ padding: 0;
+ border: 2px solid transparent;
+ border-radius: var(--gx-radius-sm);
+ overflow: hidden;
+ background: var(--gx-surface);
+ aspect-ratio: 1;
+ position: relative;
+ transition: border-color var(--duration-fast, 140ms) ease, transform var(--duration-fast, 140ms) ease;
+}
+.gx-remix-tile:hover {
+ transform: translateY(-2px);
+}
+.gx-remix-tile[aria-pressed='true'] {
+ border-color: var(--gx-gold);
+}
+.gx-remix-tile img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+.gx-remix-tile span {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ font-size: 10px;
+ padding: 3px 5px;
+ background: linear-gradient(0deg, rgba(0, 0, 0, 0.85), transparent);
+ color: #fff;
+ text-align: left;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* advanced disclosure */
+.gx-adv {
+ margin-top: 12px;
+ border-top: var(--gx-border);
+ padding-top: 12px;
+}
+.gx-adv summary {
+ cursor: pointer;
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #888);
+ list-style: none;
+}
+.gx-adv summary::-webkit-details-marker {
+ display: none;
+}
+.gx-adv summary::before {
+ content: '⌄ ';
+}
+
+/* ── Buttons ──────────────────────────────────────────────────────────── */
+.gx-btn {
+ appearance: none;
+ cursor: pointer;
+ font: inherit;
+ font-weight: 600;
+ border-radius: var(--gx-radius-sm);
+ padding: 12px 20px;
+ border: var(--gx-border-strong);
+ background: var(--gx-surface-2);
+ color: var(--ink-bright, #fff);
+ transition: all var(--duration-fast, 140ms) ease;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+}
+.gx-btn:hover:not(:disabled) {
+ border-color: rgba(255, 255, 255, 0.32);
+ background: rgba(255, 255, 255, 0.09);
+}
+.gx-btn:focus-visible {
+ outline: 2px solid var(--gx-gold);
+ outline-offset: 2px;
+}
+.gx-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+.gx-btn-primary {
+ background: linear-gradient(120deg, var(--gx-gold), #ffe680);
+ color: #1a1500;
+ border-color: transparent;
+ box-shadow: 0 6px 24px rgba(var(--gold-rgb, 255, 215, 0), 0.18);
+}
+.gx-btn-primary:hover:not(:disabled) {
+ filter: brightness(1.05);
+ background: linear-gradient(120deg, var(--gx-gold), #ffe680);
+}
+.gx-btn-lg {
+ width: 100%;
+ padding: 16px 24px;
+ font-size: var(--text-ui, 14px);
+}
+.gx-btn-ghost {
+ background: transparent;
+ border-color: var(--gx-border);
+}
+
+/* explainer strip */
+.gx-explain {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 10px;
+ margin-top: var(--gx-gap);
+}
+.gx-explain div {
+ background: var(--gx-surface);
+ border: var(--gx-border);
+ border-radius: var(--gx-radius-sm);
+ padding: 12px;
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #999);
+}
+.gx-explain strong {
+ display: block;
+ color: var(--ink-bright, #fff);
+ font-size: var(--text-sm, 13px);
+ margin-bottom: 3px;
+}
+
+/* ── Forging stage ────────────────────────────────────────────────────── */
+.gx-forge {
+ display: grid;
+ grid-template-columns: 1.1fr 0.9fr;
+ gap: clamp(16px, 3vw, 28px);
+ align-items: start;
+}
+.gx-steps {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.gx-step {
+ display: flex;
+ gap: 12px;
+ align-items: flex-start;
+ padding: 14px 16px;
+ border-radius: var(--gx-radius-sm);
+ border: var(--gx-border);
+ background: var(--gx-surface);
+ transition: border-color var(--duration-base, 220ms) ease, background var(--duration-base, 220ms) ease;
+}
+.gx-step[data-state='active'] {
+ border-color: var(--gx-gold);
+ background: rgba(var(--gold-rgb, 255, 215, 0), 0.05);
+}
+.gx-step[data-state='done'] {
+ border-color: rgba(74, 222, 128, 0.3);
+}
+.gx-step[data-state='failed'] {
+ border-color: rgba(248, 113, 113, 0.4);
+}
+.gx-step-dot {
+ flex: 0 0 auto;
+ width: 22px;
+ height: 22px;
+ border-radius: 999px;
+ border: 2px solid rgba(255, 255, 255, 0.2);
+ display: grid;
+ place-items: center;
+ font-size: 11px;
+ margin-top: 1px;
+}
+.gx-step[data-state='active'] .gx-step-dot {
+ border-color: var(--gx-gold);
+ border-top-color: transparent;
+ animation: gx-spin 0.8s linear infinite;
+}
+.gx-step[data-state='done'] .gx-step-dot {
+ border-color: var(--success, #4ade80);
+ background: var(--success, #4ade80);
+ color: #062b12;
+ animation: none;
+}
+.gx-step[data-state='failed'] .gx-step-dot {
+ border-color: var(--danger, #f87171);
+ color: var(--danger, #f87171);
+ animation: none;
+}
+.gx-step-body {
+ flex: 1;
+ min-width: 0;
+}
+.gx-step-body strong {
+ display: block;
+ font-size: var(--text-md, 13px);
+ color: var(--ink-bright, #fff);
+}
+.gx-step-body small {
+ display: block;
+ color: var(--ink-dim, #888);
+ font-size: var(--text-2xs, 11px);
+ margin-top: 2px;
+}
+.gx-bar {
+ height: 4px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.08);
+ overflow: hidden;
+ margin-top: 8px;
+}
+.gx-bar i {
+ display: block;
+ height: 100%;
+ width: 0;
+ background: linear-gradient(90deg, var(--gx-gold), #ffe680);
+ border-radius: 999px;
+ transition: width var(--duration-slow, 420ms) var(--ease-out, ease);
+}
+
+.gx-stage-preview {
+ position: relative;
+ border-radius: var(--gx-radius);
+ overflow: hidden;
+ border: var(--gx-border);
+ background:
+ radial-gradient(120% 90% at 50% 0%, rgba(var(--gold-rgb, 255, 215, 0), 0.07), transparent 60%),
+ var(--panel, #0a0a0a);
+ aspect-ratio: 3 / 4;
+ display: grid;
+ place-items: center;
+}
+.gx-stage-preview model-viewer {
+ width: 100%;
+ height: 100%;
+ --poster-color: transparent;
+ background: transparent;
+}
+.gx-stage-preview .gx-placeholder {
+ text-align: center;
+ color: var(--ink-faint, rgba(255, 255, 255, 0.4));
+ font-size: var(--text-sm, 13px);
+ padding: 24px;
+}
+.gx-stage-preview .gx-placeholder .gx-orb {
+ width: 64px;
+ height: 64px;
+ margin: 0 auto 14px;
+ border-radius: 999px;
+ background: radial-gradient(circle at 35% 30%, #fff7d6, var(--gx-gold) 55%, #7a5c00);
+ box-shadow: 0 0 40px rgba(var(--gold-rgb, 255, 215, 0), 0.4);
+ animation: gx-float 3.2s ease-in-out infinite;
+}
+.gx-elapsed {
+ margin-top: 12px;
+ text-align: center;
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #888);
+}
+
+/* ── Reveal stage ─────────────────────────────────────────────────────── */
+.gx-reveal {
+ display: grid;
+ grid-template-columns: 0.85fr 1.15fr;
+ gap: clamp(16px, 3vw, 32px);
+ align-items: start;
+}
+.gx-reveal-viewer {
+ border-radius: var(--gx-radius);
+ overflow: hidden;
+ border: var(--gx-border);
+ background:
+ radial-gradient(120% 90% at 50% 0%, rgba(var(--gold-rgb, 255, 215, 0), 0.08), transparent 60%),
+ var(--panel, #0a0a0a);
+ aspect-ratio: 3 / 4;
+ position: sticky;
+ top: 20px;
+}
+.gx-reveal-viewer model-viewer {
+ width: 100%;
+ height: 100%;
+ background: transparent;
+}
+.gx-meet {
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ color: var(--gx-gold);
+}
+.gx-agent-name {
+ font-size: clamp(1.6rem, 4vw, 2.2rem);
+ font-weight: 700;
+ margin: 4px 0 4px;
+ color: var(--ink-bright, #fff);
+ letter-spacing: -0.01em;
+}
+.gx-own {
+ color: var(--ink-dim, #999);
+ font-size: var(--text-sm, 13px);
+ margin: 0 0 18px;
+}
+.gx-own b {
+ color: var(--gx-gold);
+}
+
+.gx-detail {
+ border: var(--gx-border);
+ border-radius: var(--gx-radius-sm);
+ background: var(--gx-surface);
+ padding: 14px 16px;
+ margin-bottom: 12px;
+}
+.gx-detail-h {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ font-size: var(--text-2xs, 11px);
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+ color: var(--ink-dim, #888);
+ margin-bottom: 10px;
+}
+.gx-addr {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 9px 11px;
+ border-radius: var(--gx-radius-sm);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: var(--gx-border);
+ margin-bottom: 8px;
+}
+.gx-addr:last-child {
+ margin-bottom: 0;
+}
+.gx-addr .gx-addr-l {
+ min-width: 0;
+}
+.gx-addr-chain {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-dim, #888);
+}
+.gx-addr code {
+ display: block;
+ font-family: ui-monospace, 'SF Mono', Menlo, monospace;
+ font-size: var(--text-sm, 12px);
+ color: var(--ink-bright, #fff);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.gx-copy {
+ appearance: none;
+ cursor: pointer;
+ flex: 0 0 auto;
+ border: var(--gx-border);
+ background: var(--gx-surface-2);
+ color: var(--ink, #ccc);
+ border-radius: var(--radius-sm, 6px);
+ padding: 5px 9px;
+ font-size: 11px;
+ transition: all var(--duration-fast, 140ms) ease;
+}
+.gx-copy:hover {
+ border-color: var(--gx-gold);
+ color: #fff;
+}
+.gx-copy.is-copied {
+ border-color: var(--success, #4ade80);
+ color: var(--success, #4ade80);
+}
+
+.gx-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: var(--text-2xs, 11px);
+ padding: 4px 10px;
+ border-radius: 999px;
+}
+.gx-badge-pending {
+ color: var(--warn, #fbbf24);
+ border: 1px solid rgba(251, 191, 36, 0.3);
+ background: rgba(251, 191, 36, 0.06);
+}
+.gx-badge-live {
+ color: var(--success, #4ade80);
+ border: 1px solid rgba(74, 222, 128, 0.3);
+ background: rgba(74, 222, 128, 0.06);
+}
+.gx-tx {
+ font-family: ui-monospace, 'SF Mono', Menlo, monospace;
+ font-size: var(--text-sm, 12px);
+ color: var(--gx-gold);
+ text-decoration: none;
+ word-break: break-all;
+}
+.gx-tx:hover {
+ text-decoration: underline;
+}
+.gx-identity-status {
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #888);
+ margin: 8px 0 0;
+ min-height: 1em;
+}
+
+.gx-cta-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+ margin-top: 16px;
+}
+.gx-cta {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ text-decoration: none;
+ padding: 14px 16px;
+ border-radius: var(--gx-radius-sm);
+ border: var(--gx-border);
+ background: var(--gx-surface);
+ color: var(--ink-bright, #fff);
+ transition: all var(--duration-fast, 140ms) ease;
+}
+.gx-cta:hover {
+ border-color: var(--gx-gold);
+ background: var(--gx-surface-2);
+ transform: translateY(-2px);
+}
+.gx-cta strong {
+ font-size: var(--text-md, 13px);
+}
+.gx-cta span {
+ font-size: var(--text-2xs, 11px);
+ color: var(--ink-dim, #888);
+}
+.gx-cta-primary {
+ border-color: rgba(var(--gold-rgb, 255, 215, 0), 0.4);
+ background: rgba(var(--gold-rgb, 255, 215, 0), 0.07);
+}
+
+/* ── Error ────────────────────────────────────────────────────────────── */
+.gx-error {
+ margin-top: var(--gx-gap);
+ padding: 12px 16px;
+ border-radius: var(--gx-radius-sm);
+ border: 1px solid rgba(248, 113, 113, 0.35);
+ background: rgba(248, 113, 113, 0.07);
+ color: #fca5a5;
+ font-size: var(--text-sm, 13px);
+}
+.gx-error[hidden] {
+ display: none;
+}
+.gx-error button {
+ margin-top: 10px;
+}
+
+/* ── Animations ───────────────────────────────────────────────────────── */
+@keyframes gx-rise {
+ from {
+ opacity: 0;
+ transform: translateY(14px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+@keyframes gx-pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+ 50% {
+ opacity: 0.4;
+ }
+}
+@keyframes gx-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+@keyframes gx-float {
+ 0%,
+ 100% {
+ transform: translateY(0);
+ }
+ 50% {
+ transform: translateY(-8px);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .gx-stage,
+ .gx-step-dot,
+ .gx-orb,
+ .gx-eyebrow::before {
+ animation: none !important;
+ }
+ .gx-bar i {
+ transition: none;
+ }
+}
+
+/* ── Responsive ───────────────────────────────────────────────────────── */
+@media (max-width: 760px) {
+ .gx-forge,
+ .gx-reveal {
+ grid-template-columns: 1fr;
+ }
+ .gx-reveal-viewer {
+ position: relative;
+ top: 0;
+ max-width: 320px;
+ margin: 0 auto;
+ }
+ .gx-row,
+ .gx-cta-grid {
+ grid-template-columns: 1fr;
+ }
+ .gx-explain {
+ grid-template-columns: 1fr;
+ }
+ .gx-tabs {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/src/studio/money/money-studio.js b/src/studio/money/money-studio.js
index f772d44f7..9ebb1d9a6 100644
--- a/src/studio/money/money-studio.js
+++ b/src/studio/money/money-studio.js
@@ -20,6 +20,7 @@
import { apiFetch } from '../../api.js';
import { isSellable, skillMeta } from '../skills/skills-catalog.js';
+import { mountTradingBrain } from './trading-brain.js';
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
@@ -62,7 +63,10 @@ class MoneyStudio {
wallet: null, // { solana_address, solana_balance, usdc_balance, ... }
prices: {}, // skill → { amount, currency_mint, chain }
payments: null, // received payments array
+ holdings: null, // { sol, tokens[] } real SPL holdings
+ activity: null, // recent on-chain signatures
provisioning: false,
+ withdrawing: false,
};
this._render();
this._load();
@@ -89,6 +93,12 @@ class MoneyStudio {
this.state.prices = prices;
this.state.payments = payments;
this.state.error = null;
+ // Holdings + activity are real on-chain reads — fetch after the wallet so
+ // we know there's an address; a transient RPC miss never blocks the panel.
+ if (wallet?.solana_address) {
+ this._fetchHoldings().then((h) => { this.state.holdings = h; this._renderHoldings(); });
+ this._fetchActivity().then((a) => { this.state.activity = a; this._renderActivity(); });
+ }
} catch (err) {
this.state.error = err?.message || 'Could not load the money studio.';
} finally {
@@ -124,9 +134,24 @@ class MoneyStudio {
const wallet = await this._fetchWallet();
this.state.wallet = wallet;
this._renderWalletBalances();
+ this._fetchHoldings().then((h) => { this.state.holdings = h; this._renderHoldings(); }).catch(() => {});
} catch { /* transient RPC hiccup — keep the last balances */ }
}
+ async _fetchHoldings() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/solana/holdings`);
+ if (!res.ok) return null;
+ const { data } = await res.json();
+ return data;
+ }
+
+ async _fetchActivity() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/solana/activity`);
+ if (!res.ok) return null;
+ const { data } = await res.json();
+ return data?.signatures || [];
+ }
+
// ── Shell ─────────────────────────────────────────────────────────────────
_render() {
@@ -137,8 +162,20 @@ class MoneyStudio {
const host = this._q('[data-root]');
if (this.state.loading) { host.innerHTML = this._skeleton(); return; }
if (this.state.error) { host.innerHTML = this._errorState(this.state.error); this._bindError(); return; }
- host.innerHTML = `${this._walletSection()}${this._pricingSection()}${this._earningsSection()}`;
+ host.innerHTML = `${this._walletSection()}${this._tradingSection()}${this._pricingSection()}${this._earningsSection()}`;
this._bind();
+ this._mountTrading();
+ }
+
+ _tradingSection() {
+ return `<section class="mny-section mny-section-trading"><div data-trading-brain></div></section>`;
+ }
+
+ _mountTrading() {
+ const host = this._q('[data-trading-brain]');
+ if (host && !host.dataset.tbMounted) {
+ this._tradingBrain = mountTradingBrain(host, { studio: this.studio });
+ }
}
_skeleton() {
@@ -191,11 +228,99 @@ class MoneyStudio {
<div class="mny-wallet-tools">
<a class="studio-btn studio-btn-primary studio-action" href="/agent/${encodeURIComponent(this.agentId)}/wallet#deposit">Add funds</a>
<button class="studio-btn studio-btn-ghost studio-action" data-action="refresh">Refresh balance</button>
+ <button class="studio-btn studio-btn-ghost studio-action" data-action="toggle-withdraw">Withdraw</button>
</div>
+ <div class="mny-withdraw" data-withdraw hidden>${this._withdrawForm()}</div>
+ <div class="mny-holdings" data-holdings>${this._holdingsHtml()}</div>
+ <div class="mny-activity" data-activity>${this._activityHtml()}</div>
</div>
</section>`;
}
+ _holdingsHtml() {
+ const h = this.state.holdings;
+ if (h == null) return `<div class="mny-sub-head">Holdings</div><div class="mny-skel-line"></div>`;
+ const tokens = (h.tokens || []).filter((t) => !t.is_usdc);
+ if (!tokens.length) return `<div class="mny-sub-head">Holdings</div><p class="mny-faint">No token holdings yet — buys made by the Trading Brain appear here.</p>`;
+ return `<div class="mny-sub-head">Holdings <span class="mny-count">${tokens.length}</span></div>
+ <ul class="mny-hold-list">${tokens.slice(0, 8).map((t) => `
+ <li class="mny-hold-row">
+ <a class="mny-hold-mint" href="https://solscan.io/token/${esc(t.mint)}" target="_blank" rel="noopener" title="${esc(t.mint)}">${esc(short(t.mint))} ↗</a>
+ <span class="mny-hold-amt">${Number(t.ui_amount).toLocaleString(undefined, { maximumFractionDigits: 2 })}</span>
+ </li>`).join('')}</ul>`;
+ }
+
+ _activityHtml() {
+ const a = this.state.activity;
+ if (a == null) return '';
+ if (!a.length) return '';
+ return `<div class="mny-sub-head">Recent activity</div>
+ <ul class="mny-act-list">${a.slice(0, 6).map((s) => `
+ <li class="mny-act-row ${s.success ? '' : 'is-fail'}">
+ <span class="mny-act-sum">${esc(s.summary || (s.success ? 'transaction' : 'failed tx'))}</span>
+ <span class="mny-act-delta ${s.sol_delta == null ? '' : s.sol_delta >= 0 ? 'pos' : 'neg'}">${s.sol_delta == null ? '' : `${s.sol_delta >= 0 ? '+' : ''}${Number(s.sol_delta).toFixed(4)} SOL`}</span>
+ <a class="mny-act-tx" href="https://solscan.io/tx/${esc(s.signature)}" target="_blank" rel="noopener" title="View transaction">↗</a>
+ </li>`).join('')}</ul>`;
+ }
+
+ _withdrawForm() {
+ return `
+ <div class="mny-withdraw-head">Withdraw SOL</div>
+ <div class="mny-withdraw-row">
+ <input type="text" data-wd="destination" placeholder="Destination address" aria-label="Destination Solana address" />
+ <input type="number" min="0" step="any" data-wd="amount" placeholder="Amount" aria-label="Amount in SOL" />
+ <button class="studio-btn studio-btn-ghost" data-action="wd-max" title="Withdraw everything (keeps a little for fees)">Max</button>
+ <button class="studio-btn studio-btn-primary" data-action="do-withdraw" ${this.state.withdrawing ? 'disabled' : ''}>${this.state.withdrawing ? 'Sending…' : 'Withdraw'}</button>
+ </div>
+ <p class="mny-faint">Real on-chain transfer from the agent's custodial wallet. Double-check the address — Solana transfers are irreversible.</p>
+ <div class="mny-withdraw-result" data-wd-result hidden></div>`;
+ }
+
+ _renderHoldings() {
+ const host = this._q('[data-holdings]');
+ if (host) host.innerHTML = this._holdingsHtml();
+ }
+
+ _renderActivity() {
+ const host = this._q('[data-activity]');
+ if (host) host.innerHTML = this._activityHtml();
+ }
+
+ async _withdraw(useMax = false) {
+ if (this.state.withdrawing) return;
+ const wrap = this._q('[data-withdraw]');
+ const dest = wrap?.querySelector('[data-wd="destination"]')?.value.trim();
+ const amtRaw = wrap?.querySelector('[data-wd="amount"]')?.value.trim();
+ if (!dest) return this._toast('Enter a destination address', true);
+ const amount = useMax ? 'max' : Number(amtRaw);
+ if (!useMax && (!Number.isFinite(amount) || amount <= 0)) return this._toast('Enter a valid amount', true);
+ this.state.withdrawing = true;
+ const btn = wrap?.querySelector('[data-action="do-withdraw"]');
+ if (btn) { btn.disabled = true; btn.textContent = 'Sending…'; }
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/wallet/withdraw`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ destination: dest, amount, asset: 'SOL', network: 'mainnet' }),
+ });
+ const payload = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(payload?.error?.message || 'Withdrawal failed.');
+ const d = payload.data || {};
+ const result = wrap?.querySelector('[data-wd-result]');
+ if (result) {
+ result.hidden = false;
+ result.innerHTML = `✓ Sent. <a href="https://solscan.io/tx/${esc(d.signature)}" target="_blank" rel="noopener">View transaction ↗</a>`;
+ }
+ this._toast('Withdrawal sent');
+ this._refreshWallet();
+ } catch (err) {
+ this._toast(err.message || 'Withdrawal failed', true);
+ } finally {
+ this.state.withdrawing = false;
+ if (btn) { btn.disabled = false; btn.textContent = 'Withdraw'; }
+ }
+ }
+
_balancesHtml() {
const w = this.state.wallet || {};
const sol = w.solana_balance == null ? '—' : Number(w.solana_balance).toFixed(4);
@@ -306,6 +431,9 @@ class MoneyStudio {
if (a === 'refresh') return this._refreshWallet();
if (a === 'copy') return this._copy(btn.dataset.copy);
if (a === 'save-price') return this._savePrice(btn.dataset.skill);
+ if (a === 'toggle-withdraw') { const w = this._q('[data-withdraw]'); if (w) w.hidden = !w.hidden; return; }
+ if (a === 'do-withdraw') return this._withdraw(false);
+ if (a === 'wd-max') return this._withdraw(true);
if (a === 'go-skills') return document.dispatchEvent(new CustomEvent('studio:navigate', { detail: { tab: 'skills' } }));
});
this.el.querySelectorAll('[data-price-input]').forEach((inp) =>
@@ -392,5 +520,6 @@ class MoneyStudio {
destroy() {
clearInterval(this._poll);
clearTimeout(this._toastTimer);
+ try { this._tradingBrain?.destroy(); } catch { /* noop */ }
}
}
diff --git a/src/studio/money/trading-brain.js b/src/studio/money/trading-brain.js
new file mode 100644
index 000000000..dfa9b69e7
--- /dev/null
+++ b/src/studio/money/trading-brain.js
@@ -0,0 +1,864 @@
+/**
+ * Trading Brain — visual sniping/trading rules (P4, the centerpiece)
+ * =================================================================
+ * The brain (P1) reasons; THIS executes. The owner draws their agent's trading
+ * behaviour as a connected flow of blocks — trigger → filters → buy → exits →
+ * risk — and the agent runs it against the real Solana stack: real launches, real
+ * quotes, real slippage, real signatures, real confirmations. No simulated fills,
+ * no paper P&L.
+ *
+ * Two first-class modes, both real:
+ * • Assisted (default) — the agent proposes; the owner confirms each snipe with
+ * one tap. "Scan for matches" (POST /api/trading/scan) surfaces live launches
+ * that fit the rule, each with a live quote + rug/honeypot verdict; confirming
+ * routes through the discretionary trade endpoint, which re-runs every guard.
+ * • Autonomous — arming equips the rule as a real strategy
+ * (POST /api/agents/:id/strategies); the cron fan-out runner fires it within
+ * hard, server-enforced guardrails. Autonomy is explicit, revocable, and
+ * auditable, and a global kill switch halts it instantly.
+ *
+ * Safety is enforced SERVER-SIDE (api/_lib/agent-trade-guards.js): per-trade cap,
+ * daily budget, slippage ceiling, price-impact breaker, max concurrent, kill
+ * switch — the UI here only edits them; it can never widen the leash.
+ *
+ * Every fill writes a trade memory (P2) and emits a market event the avatar reacts
+ * to (P5) via studio.emitMarket.
+ *
+ * Mount: import { mountTradingBrain } from './trading-brain.js';
+ * mountTradingBrain(host, { studio });
+ */
+
+import { apiFetch } from '../../api.js';
+import {
+ emptyRule, normalizeRule, validateRule, ruleToEnglish,
+ compileRuleToConfig, configToSniperStrategy,
+} from './trading-compile.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const short = (a) => (a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '');
+const fmtSol = (n) => (n == null ? '—' : Number(n).toLocaleString(undefined, { maximumFractionDigits: 4 }));
+const fmtUsd = (n) => (n == null ? '—' : '$' + Number(n).toLocaleString(undefined, { maximumFractionDigits: 0 }));
+const fmtPct = (n) => (n == null ? '—' : `${n > 0 ? '+' : ''}${Number(n).toFixed(1)}%`);
+
+function relTime(ts) {
+ if (!ts) return '';
+ const d = Date.now() - new Date(ts).getTime();
+ if (d < 60000) return 'just now';
+ if (d < 3600000) return Math.floor(d / 60000) + 'm ago';
+ if (d < 86400000) return Math.floor(d / 3600000) + 'h ago';
+ return Math.floor(d / 86400000) + 'd ago';
+}
+
+const SOLSCAN = (sig) => `https://solscan.io/tx/${sig}`;
+const SOLSCAN_ACCT = (a) => `https://solscan.io/account/${a}`;
+
+export function mountTradingBrain(host, { studio }) {
+ if (host.dataset.tbMounted) return null;
+ host.dataset.tbMounted = '1';
+ return new TradingBrain(host, studio);
+}
+
+class TradingBrain {
+ constructor(el, studio) {
+ this.el = el;
+ this.studio = studio;
+ this.agentId = studio.agent?.id;
+
+ const bag = studio.agent?.meta?.studio?.trading || {};
+ this.rule = normalizeRule(bag.rule || emptyRule());
+ this.mode = bag.mode === 'autonomous' ? 'autonomous' : 'assisted';
+ this.strategyId = typeof bag.strategyId === 'string' ? bag.strategyId : null;
+
+ this.state = {
+ loading: true,
+ error: null,
+ killed: false,
+ equips: [],
+ positions: [],
+ tradeLimits: null,
+ spentTodaySol: null,
+ candidates: null, // null = not scanned; [] = scanned, none
+ scanNote: null,
+ scanning: false,
+ backtest: null,
+ backtesting: false,
+ saving: false,
+ arming: false,
+ audit: [],
+ dirty: false, // rule changed since last server save
+ };
+
+ this._render();
+ this._load();
+ }
+
+ _q(sel) { return this.el.querySelector(sel); }
+
+ get _armed() {
+ return this.state.equips.some((e) => e.strategy_id === this.strategyId && e.active);
+ }
+
+ // ── Data ──────────────────────────────────────────────────────────────────
+
+ async _load() {
+ this.state.loading = true;
+ this._renderBody();
+ try {
+ const [strat, limits, audit] = await Promise.all([
+ this._fetchStrategies(),
+ this._fetchLimits(),
+ this._fetchAudit(),
+ ]);
+ this.state.killed = strat.killed;
+ this.state.equips = strat.equips;
+ this.state.positions = strat.positions;
+ this.state.tradeLimits = limits.trade_limits;
+ this.state.spentTodaySol = limits.spent_today_sol;
+ this.state.audit = audit;
+ this.state.error = null;
+ } catch (err) {
+ this.state.error = err?.message || 'Could not load the Trading Brain.';
+ } finally {
+ this.state.loading = false;
+ this._renderBody();
+ }
+ }
+
+ async _fetchStrategies() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/strategies`);
+ if (!res.ok) throw new Error('Could not read trading strategies.');
+ const { data } = await res.json();
+ return { killed: !!data.killed, equips: data.equips || [], positions: data.positions || [] };
+ }
+
+ async _fetchLimits() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/trade/limits`);
+ if (!res.ok) return { trade_limits: null, spent_today_sol: null };
+ const { data } = await res.json();
+ return { trade_limits: data.trade_limits, spent_today_sol: data.spent_today_sol };
+ }
+
+ async _fetchAudit() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/solana/custody?category=trade&limit=50`);
+ if (!res.ok) return [];
+ const { data } = await res.json();
+ return data.items || [];
+ }
+
+ // ── Persist rule (local studio meta + backend strategy) ─────────────────────
+
+ _persistMeta() {
+ this.studio.patch({ meta: { studio: { trading: { rule: this.rule, mode: this.mode, strategyId: this.strategyId } } } });
+ this.studio.emit('trading:change', { mode: this.mode, armed: this._armed });
+ }
+
+ async _saveStrategy() {
+ const { valid, errors } = validateRule(this.rule);
+ if (!valid) {
+ this._toast(Object.values(errors)[0], true);
+ this._renderBuilder();
+ return null;
+ }
+ this.state.saving = true;
+ this._renderActions();
+ const config = compileRuleToConfig(this.rule);
+ try {
+ let strategy;
+ if (this.strategyId) {
+ const res = await apiFetch(`/api/strategies/${this.strategyId}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name: this.rule.name, config }),
+ });
+ if (res.status === 404) { this.strategyId = null; return this._saveStrategy(); }
+ if (!res.ok) throw new Error('Could not save the rule.');
+ strategy = (await res.json()).data;
+ } else {
+ const res = await apiFetch('/api/strategies', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ name: this.rule.name,
+ description: ruleToEnglish(this.rule),
+ config,
+ }),
+ });
+ if (!res.ok) {
+ const d = await res.json().catch(() => ({}));
+ throw new Error(d?.error?.message || 'Could not save the rule.');
+ }
+ strategy = (await res.json()).data;
+ this.strategyId = strategy.id;
+ }
+ this.state.dirty = false;
+ this._persistMeta();
+ this._toast('Rule saved');
+ return strategy;
+ } catch (err) {
+ this._toast(err.message || 'Save failed', true);
+ return null;
+ } finally {
+ this.state.saving = false;
+ this._renderActions();
+ }
+ }
+
+ // ── Mode + arming ───────────────────────────────────────────────────────────
+
+ async _setMode(mode) {
+ if (mode === this.mode) return;
+ // Switching to assisted must disarm any live autonomous strategy.
+ if (mode === 'assisted' && this._armed) await this._disarm({ silent: true });
+ this.mode = mode;
+ this._persistMeta();
+ this.state.candidates = null;
+ this.state.scanNote = null;
+ this._renderBody();
+ }
+
+ async _arm() {
+ // Saving first guarantees the equipped config matches what's on screen.
+ const strategy = this.state.dirty || !this.strategyId ? await this._saveStrategy() : { id: this.strategyId };
+ if (!strategy) return;
+ this.state.arming = true;
+ this._renderActions();
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/strategies`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy_id: this.strategyId, network: this.rule.network }),
+ });
+ if (!res.ok) throw new Error('Could not arm the agent.');
+ await this._refreshStrategies();
+ this._toast('Agent armed — it will trade within your guardrails');
+ this.studio.emitMarket?.({ type: 'alert' });
+ this.studio.emit('trading:change', { mode: this.mode, armed: true });
+ } catch (err) {
+ this._toast(err.message || 'Arming failed', true);
+ } finally {
+ this.state.arming = false;
+ this._renderBody();
+ }
+ }
+
+ async _disarm({ silent = false } = {}) {
+ this.state.arming = true;
+ if (!silent) this._renderActions();
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/strategies/unequip`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy_id: this.strategyId }),
+ });
+ if (!res.ok) throw new Error('Could not disarm the agent.');
+ await this._refreshStrategies();
+ if (!silent) this._toast('Agent disarmed — no new autonomous trades');
+ this.studio.emit('trading:change', { mode: this.mode, armed: false });
+ } catch (err) {
+ if (!silent) this._toast(err.message || 'Disarm failed', true);
+ } finally {
+ this.state.arming = false;
+ if (!silent) this._renderBody();
+ }
+ }
+
+ async _refreshStrategies() {
+ const strat = await this._fetchStrategies().catch(() => null);
+ if (strat) {
+ this.state.killed = strat.killed;
+ this.state.equips = strat.equips;
+ this.state.positions = strat.positions;
+ }
+ }
+
+ // ── Kill switch ─────────────────────────────────────────────────────────────
+
+ async _toggleKill() {
+ const next = !this.state.killed;
+ // Optimistic — this is a safety control; reflect intent immediately.
+ this.state.killed = next;
+ this._renderHeader();
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/strategies/kill`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ killed: next }),
+ });
+ if (!res.ok) throw new Error('kill toggle failed');
+ const { data } = await res.json();
+ this.state.killed = !!data.killed;
+ this._toast(this.state.killed ? 'Kill switch ON — all autonomous trading halted' : 'Kill switch off');
+ } catch {
+ this.state.killed = !next; // roll back
+ this._toast('Could not toggle the kill switch', true);
+ }
+ this._renderHeader();
+ }
+
+ // ── Guardrails (server-enforced trade limits) ───────────────────────────────
+
+ async _saveGuardrails() {
+ const card = this._q('[data-guardrails]');
+ if (!card) return;
+ const val = (k) => {
+ const inp = card.querySelector(`[data-glimit="${k}"]`);
+ if (!inp) return undefined;
+ const v = inp.value.trim();
+ return v === '' ? null : Number(v);
+ };
+ const patch = {
+ per_trade_sol: val('per_trade_sol'),
+ daily_budget_sol: val('daily_budget_sol'),
+ max_price_impact_pct: val('max_price_impact_pct'),
+ max_concurrent: val('max_concurrent'),
+ };
+ const btn = card.querySelector('[data-action="save-guardrails"]');
+ if (btn) { btn.disabled = true; btn.textContent = 'Saving…'; }
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/trade/limits`, {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ trade_limits: patch }),
+ });
+ if (!res.ok) throw new Error('Could not save guardrails.');
+ const { data } = await res.json();
+ this.state.tradeLimits = data.trade_limits;
+ this._toast('Guardrails saved — enforced server-side on every trade');
+ } catch (err) {
+ this._toast(err.message || 'Save failed', true);
+ } finally {
+ if (btn) { btn.disabled = false; btn.textContent = 'Save guardrails'; }
+ }
+ }
+
+ // ── Assisted scan + confirm ─────────────────────────────────────────────────
+
+ async _scan() {
+ if (this.state.scanning) return;
+ if (this.state.killed) { this._toast('Kill switch is on — turn it off to scan', true); return; }
+ this.state.scanning = true;
+ this.state.candidates = null;
+ this.state.scanNote = null;
+ this._renderAssisted();
+ try {
+ const res = await apiFetch('/api/trading/scan', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agent_id: this.agentId, config: compileRuleToConfig(this.rule) }),
+ });
+ if (!res.ok) {
+ const d = await res.json().catch(() => ({}));
+ throw new Error(d?.error?.message || 'Scan failed.');
+ }
+ const { data } = await res.json();
+ this.state.candidates = data.candidates || [];
+ this.state.scanNote = data.note || `Scanned ${data.scanned} live launches.`;
+ if (this.state.candidates.length) this.studio.emitMarket?.({ type: 'alert' });
+ } catch (err) {
+ this._toast(err.message || 'Scan failed', true);
+ this.state.candidates = [];
+ } finally {
+ this.state.scanning = false;
+ this._renderAssisted();
+ }
+ }
+
+ async _confirmSnipe(mint) {
+ const cand = (this.state.candidates || []).find((c) => c.mint === mint);
+ if (!cand) return;
+ const card = this.el.querySelector(`[data-cand="${CSS.escape(mint)}"]`);
+ const btn = card?.querySelector('[data-action="confirm-snipe"]');
+ if (btn) { btn.disabled = true; btn.textContent = 'Sniping…'; }
+ this.studio.emitMarket?.({ type: 'trade:buy', mint });
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/solana/trade`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ side: 'buy', mint, solAmount: cand.amount_sol,
+ slippageBps: cand.slippage_bps, network: this.rule.network,
+ }),
+ });
+ const payload = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const msg = payload?.error?.message || 'Snipe rejected.';
+ throw Object.assign(new Error(msg), { detail: payload?.error });
+ }
+ const d = payload.data || {};
+ this.studio.emitMarket?.({ type: 'snipe:filled', mint, amount: cand.amount_sol, signature: d.signature });
+ this._writeTradeMemory(cand, d.signature);
+ this._toast(`Sniped ${cand.symbol || short(mint)} — ${fmtSol(cand.amount_sol)} SOL`);
+ if (card) card.classList.add('tb-cand-done');
+ if (btn) { btn.textContent = 'Filled ✓'; }
+ // Refresh positions + audit so the fill shows immediately.
+ this._refreshStrategies().then(() => this._renderPositions());
+ this._fetchAudit().then((a) => { this.state.audit = a; this._renderAudit(); });
+ } catch (err) {
+ this.studio.emitMarket?.({ type: 'snipe:failed', mint });
+ this._toast(err.message || 'Snipe failed', true);
+ if (btn) { btn.disabled = false; btn.textContent = 'Confirm snipe'; }
+ }
+ }
+
+ async _writeTradeMemory(cand, signature) {
+ // Coordinate with P2: record the trade, its rationale, and the outcome so the
+ // agent remembers what it did and why. Best-effort — a memory hiccup never
+ // blocks a confirmed on-chain trade.
+ try {
+ await apiFetch('/api/agent-memory', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agentId: this.agentId,
+ entry: {
+ type: 'project',
+ content: `Sniped ${cand.symbol || cand.name || short(cand.mint)} (${cand.mint}) for ${cand.amount_sol} SOL — ` +
+ `matched rule "${this.rule.name}" (${(cand.reasons || []).join(', ')}). ` +
+ `Firewall: ${cand.firewall?.verdict || 'n/a'}. tx ${signature || 'pending'}.`,
+ tags: ['trade', 'snipe', 'assisted'],
+ context: {
+ mint: cand.mint, sol: cand.amount_sol, signature: signature || null,
+ market_cap_usd: cand.market_cap_usd, reasons: cand.reasons,
+ },
+ salience: 0.75,
+ },
+ }),
+ });
+ } catch { /* non-blocking */ }
+ }
+
+ // ── Backtest (historical, honest) ───────────────────────────────────────────
+
+ async _backtest() {
+ if (this.state.backtesting) return;
+ const { valid, errors } = validateRule(this.rule);
+ if (!valid) { this._toast(Object.values(errors)[0], true); return; }
+ this.state.backtesting = true;
+ this.state.backtest = null;
+ this._renderBacktest();
+ try {
+ const config = compileRuleToConfig(this.rule);
+ const strategy = configToSniperStrategy(config, { maxPriceImpactPct: this.state.tradeLimits?.max_price_impact_pct ?? null });
+ const res = await apiFetch('/api/sniper/backtest', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agent_id: this.agentId, strategy, window_days: 30, network: this.rule.network }),
+ });
+ if (!res.ok) {
+ const d = await res.json().catch(() => ({}));
+ throw new Error(d?.error?.message || 'Backtest failed.');
+ }
+ const { data } = await res.json();
+ this.state.backtest = data;
+ } catch (err) {
+ this._toast(err.message || 'Backtest failed', true);
+ this.state.backtest = { error: err.message };
+ } finally {
+ this.state.backtesting = false;
+ this._renderBacktest();
+ }
+ }
+
+ // ── Audit export ────────────────────────────────────────────────────────────
+
+ _exportAudit() {
+ const rows = this.state.audit || [];
+ if (!rows.length) { this._toast('No trades to export yet', true); return; }
+ const head = ['date', 'type', 'asset', 'amount_sol', 'usd', 'status', 'reason', 'signature'];
+ const csv = [head.join(',')].concat(rows.map((r) => [
+ r.created_at, r.category, r.asset || '',
+ r.amount_lamports != null ? (Number(r.amount_lamports) / 1e9) : '',
+ r.usd ?? '', r.status, (r.reason || '').replace(/,/g, ';'), r.signature || '',
+ ].join(','))).join('\n');
+ const blob = new Blob([csv], { type: 'text/csv' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${this.agentId}-trade-audit.csv`;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ }
+
+ // ── Render ──────────────────────────────────────────────────────────────────
+
+ _render() {
+ this.el.innerHTML = `
+ <section class="tb" aria-labelledby="tb-h">
+ <header class="tb-head" data-head></header>
+ <div class="tb-body" data-body></div>
+ </section>
+ <div class="mny-toast tb-toast" data-tbtoast hidden></div>`;
+ }
+
+ _renderBody() {
+ this._renderHeader();
+ const body = this._q('[data-body]');
+ if (this.state.loading) { body.innerHTML = `<div class="tb-skel"></div>`; return; }
+ if (this.state.error) {
+ body.innerHTML = `
+ <div class="mny-empty">
+ <div class="mny-empty-glyph" aria-hidden="true">⚠</div>
+ <h3>Couldn’t load the Trading Brain</h3>
+ <p>${esc(this.state.error)}</p>
+ <button class="studio-btn studio-btn-ghost" data-action="retry">Try again</button>
+ </div>`;
+ body.querySelector('[data-action="retry"]')?.addEventListener('click', () => this._load());
+ return;
+ }
+ body.innerHTML = `
+ <p class="tb-disclosure">Trading is risky. Coins can go to zero. Your agent only ever spends what you fund and within the guardrails you set below — never more. Past results never guarantee future ones.</p>
+ <div class="tb-builder" data-builder></div>
+ <div class="tb-guardrails-wrap" data-guardrails-wrap></div>
+ <div class="tb-actions" data-actions></div>
+ <div class="tb-assisted" data-assisted></div>
+ <div class="tb-backtest" data-backtest></div>
+ <div class="tb-positions" data-positions></div>
+ <div class="tb-audit" data-audit></div>`;
+ this._renderBuilder();
+ this._renderGuardrails();
+ this._renderActions();
+ this._renderAssisted();
+ this._renderBacktest();
+ this._renderPositions();
+ this._renderAudit();
+ this._bind();
+ }
+
+ _renderHeader() {
+ const head = this._q('[data-head]');
+ if (!head) return;
+ const killed = this.state.killed;
+ const armed = this._armed;
+ head.innerHTML = `
+ <div class="tb-title">
+ <h3 id="tb-h">Trading Brain</h3>
+ <p>Draw how your agent snipes and trades. The brain reasons; this executes — for real, within your guardrails.</p>
+ </div>
+ <div class="tb-head-controls">
+ <div class="tb-mode" role="tablist" aria-label="Trading mode">
+ <button class="tb-mode-btn ${this.mode === 'assisted' ? 'is-on' : ''}" role="tab" aria-selected="${this.mode === 'assisted'}" data-action="mode" data-mode="assisted">Assisted</button>
+ <button class="tb-mode-btn ${this.mode === 'autonomous' ? 'is-on' : ''}" role="tab" aria-selected="${this.mode === 'autonomous'}" data-action="mode" data-mode="autonomous">Autonomous</button>
+ </div>
+ ${armed ? `<span class="tb-status tb-status-live" title="Autonomous strategy is live">● Armed</span>` : ''}
+ <button class="tb-kill ${killed ? 'is-killed' : ''}" data-action="kill" aria-pressed="${killed}" title="Halt all autonomous trading instantly">
+ ${killed ? 'Killed — resume' : 'Kill switch'}
+ </button>
+ </div>`;
+ }
+
+ // — Visual flow builder —
+ _renderBuilder() {
+ const host = this._q('[data-builder]');
+ if (!host) return;
+ const r = this.rule;
+ const { errors } = validateRule(r);
+ const err = (k) => errors[k] ? `<span class="tb-err">${esc(errors[k])}</span>` : '';
+ const field = (label, k, val, attrs = '', suffix = '') => `
+ <label class="tb-field">
+ <span class="tb-field-l">${esc(label)}</span>
+ <span class="tb-input-wrap">
+ <input data-rule="${k}" value="${val == null ? '' : esc(val)}" ${attrs} />
+ ${suffix ? `<span class="tb-suffix">${esc(suffix)}</span>` : ''}
+ </span>
+ </label>`;
+ const num = 'type="number" inputmode="decimal" min="0" step="any"';
+
+ host.innerHTML = `
+ <label class="tb-name">
+ <span class="tb-field-l">Rule name</span>
+ <input data-rule="name" value="${esc(r.name)}" maxlength="60" placeholder="My sniper" />
+ </label>
+ <div class="tb-flow">
+ ${this._block('trigger', '◎', 'When', `
+ ${field('Launched within (min)', 'trigger.max_age_minutes', r.trigger.max_age_minutes, num, 'min')}
+ `)}
+ ${this._connector()}
+ ${this._block('filters', '⊜', 'And it matches', `
+ ${field('Min market cap', 'filters.min_market_cap_usd', r.filters.min_market_cap_usd, num, 'USD')}
+ ${field('Max market cap', 'filters.max_market_cap_usd', r.filters.max_market_cap_usd, num, 'USD')}
+ ${err('filters.max_market_cap_usd')}
+ ${field('Min liquidity', 'filters.min_liquidity_sol', r.filters.min_liquidity_sol, num, 'SOL')}
+ ${field('Creator: max prior launches', 'filters.max_creator_launches', r.filters.max_creator_launches, num)}
+ ${field('Creator: min graduated', 'filters.min_creator_graduated', r.filters.min_creator_graduated, num)}
+ <label class="tb-check"><input type="checkbox" data-rule="filters.require_socials" ${r.filters.require_socials ? 'checked' : ''}/> Must have socials</label>
+ <label class="tb-check"><input type="checkbox" data-rule="filters.require_sol_quote" ${r.filters.require_sol_quote ? 'checked' : ''}/> SOL-quoted only</label>
+ `)}
+ ${this._connector()}
+ ${this._block('buy', '↑', 'Buy', `
+ ${field('Per-trade size', 'buy.amount_sol', r.buy.amount_sol, num, 'SOL')}
+ ${err('buy.amount_sol')}
+ ${field('Max slippage', 'buy.max_slippage_bps', r.buy.max_slippage_bps, num, 'bps')}
+ `)}
+ ${this._connector()}
+ ${this._block('exits', '⇄', 'Then exit', `
+ ${field('Take profit', 'exits.take_profit_pct', r.exits.take_profit_pct, num, '%')}
+ ${field('Stop loss', 'exits.stop_loss_pct', r.exits.stop_loss_pct, num, '%')}
+ ${err('exits.stop_loss_pct')}
+ ${field('Trailing stop', 'exits.trailing_stop_pct', r.exits.trailing_stop_pct, num, '%')}
+ ${field('Max hold', 'exits.max_hold_minutes', r.exits.max_hold_minutes, num, 'min')}
+ ${err('exits')}
+ `)}
+ ${this._connector()}
+ ${this._block('risk', '⚖', 'Within limits', `
+ ${field('Max concurrent positions', 'risk.max_concurrent_positions', r.risk.max_concurrent_positions, num)}
+ ${field('Cooldown between buys', 'risk.cooldown_minutes', r.risk.cooldown_minutes, num, 'min')}
+ `)}
+ </div>
+ <p class="tb-english"><span aria-hidden="true">🗣</span> ${esc(ruleToEnglish(r))}</p>`;
+ }
+
+ _block(key, glyph, title, inner) {
+ return `
+ <div class="tb-node tb-node-${key}">
+ <div class="tb-node-head"><span class="tb-node-glyph" aria-hidden="true">${glyph}</span><span class="tb-node-title">${esc(title)}</span></div>
+ <div class="tb-node-body">${inner}</div>
+ </div>`;
+ }
+
+ _connector() {
+ return `<div class="tb-connector" aria-hidden="true"><span></span></div>`;
+ }
+
+ _renderGuardrails() {
+ const host = this._q('[data-guardrails-wrap]');
+ if (!host) return;
+ const t = this.state.tradeLimits || {};
+ const v = (x) => (x == null ? '' : x);
+ host.innerHTML = `
+ <div class="tb-guardrails" data-guardrails>
+ <div class="tb-card-head">
+ <h4>Guardrails <span class="tb-badge">enforced server-side</span></h4>
+ <p>Hard caps the agent can never exceed — checked on every trade, autonomous or assisted. Leave blank for no cap.</p>
+ </div>
+ <div class="tb-glimits">
+ <label class="tb-field"><span class="tb-field-l">Max per trade</span><span class="tb-input-wrap"><input type="number" min="0" step="any" data-glimit="per_trade_sol" value="${v(t.per_trade_sol)}" placeholder="∞"/><span class="tb-suffix">SOL</span></span></label>
+ <label class="tb-field"><span class="tb-field-l">Daily budget</span><span class="tb-input-wrap"><input type="number" min="0" step="any" data-glimit="daily_budget_sol" value="${v(t.daily_budget_sol)}" placeholder="∞"/><span class="tb-suffix">SOL</span></span></label>
+ <label class="tb-field"><span class="tb-field-l">Max price impact</span><span class="tb-input-wrap"><input type="number" min="0" step="any" data-glimit="max_price_impact_pct" value="${v(t.max_price_impact_pct)}" placeholder="15"/><span class="tb-suffix">%</span></span></label>
+ <label class="tb-field"><span class="tb-field-l">Max open positions</span><span class="tb-input-wrap"><input type="number" min="0" step="1" data-glimit="max_concurrent" value="${v(t.max_concurrent)}" placeholder="∞"/></span></label>
+ </div>
+ <div class="tb-glimits-foot">
+ <span class="tb-spent">${this.state.spentTodaySol != null ? `Spent today: ${fmtSol(this.state.spentTodaySol)} SOL` : ''}</span>
+ <button class="studio-btn studio-btn-ghost" data-action="save-guardrails">Save guardrails</button>
+ </div>
+ </div>`;
+ }
+
+ _renderActions() {
+ const host = this._q('[data-actions]');
+ if (!host) return;
+ const saving = this.state.saving;
+ const arming = this.state.arming;
+ const armed = this._armed;
+ const modeBtn = this.mode === 'autonomous'
+ ? (armed
+ ? `<button class="studio-btn studio-btn-danger" data-action="disarm" ${arming ? 'disabled' : ''}>${arming ? 'Disarming…' : 'Disarm agent'}</button>`
+ : `<button class="studio-btn studio-btn-primary" data-action="arm" ${arming ? 'disabled' : ''}>${arming ? 'Arming…' : 'Arm agent'}</button>`)
+ : `<button class="studio-btn studio-btn-primary" data-action="scan" ${this.state.scanning ? 'disabled' : ''}>${this.state.scanning ? 'Scanning…' : 'Scan for matches'}</button>`;
+ host.innerHTML = `
+ <button class="studio-btn studio-btn-ghost" data-action="save" ${saving ? 'disabled' : ''}>${saving ? 'Saving…' : 'Save rule'}</button>
+ <button class="studio-btn studio-btn-ghost" data-action="backtest" ${this.state.backtesting ? 'disabled' : ''}>${this.state.backtesting ? 'Backtesting…' : 'Backtest'}</button>
+ ${modeBtn}`;
+ }
+
+ _renderAssisted() {
+ const host = this._q('[data-assisted]');
+ if (!host) return;
+ if (this.mode !== 'assisted') { host.innerHTML = ''; return; }
+ const c = this.state.candidates;
+ if (this.state.scanning) { host.innerHTML = `<div class="tb-card-head"><h4>Scanning live launches…</h4></div><div class="tb-skel small"></div>`; return; }
+ if (c == null) {
+ host.innerHTML = `<div class="tb-hint">Assisted mode: tap <b>Scan for matches</b> to see live launches that fit your rule. Your agent proposes — you confirm each snipe.</div>`;
+ return;
+ }
+ if (!c.length) {
+ host.innerHTML = `<div class="tb-card-head"><h4>No matches right now</h4><p>${esc(this.state.scanNote || '')} Loosen a filter and scan again — new coins launch every minute.</p></div>`;
+ return;
+ }
+ host.innerHTML = `
+ <div class="tb-card-head"><h4>${c.length} live match${c.length === 1 ? '' : 'es'}</h4><p>${esc(this.state.scanNote || '')} Real quotes, real safety checks. Confirm to snipe with your custodial wallet.</p></div>
+ <ul class="tb-cands">${c.map((x) => this._candRow(x)).join('')}</ul>`;
+ }
+
+ _candRow(x) {
+ const fw = x.firewall || {};
+ const fwClass = fw.verdict === 'block' ? 'block' : fw.verdict === 'warn' ? 'warn' : 'ok';
+ const fwLabel = fw.verdict === 'block' ? 'Unsafe' : fw.verdict === 'warn' ? 'Caution' : 'Clean';
+ const impact = x.quote?.price_impact_pct;
+ const blocked = fw.verdict === 'block';
+ return `
+ <li class="tb-cand" data-cand="${esc(x.mint)}">
+ <div class="tb-cand-main">
+ <div class="tb-cand-id">
+ <b>${esc(x.symbol || x.name || short(x.mint))}</b>
+ <a class="tb-cand-link" href="${SOLSCAN_ACCT(esc(x.mint))}" target="_blank" rel="noopener" title="View coin">${esc(short(x.mint))} ↗</a>
+ </div>
+ <div class="tb-cand-meta">
+ ${x.age_minutes != null ? `<span>${x.age_minutes}m old</span>` : ''}
+ ${x.market_cap_usd != null ? `<span>${fmtUsd(x.market_cap_usd)} mc</span>` : ''}
+ ${x.has_socials ? `<span>socials</span>` : ''}
+ ${impact != null ? `<span title="Price impact">${impact.toFixed(1)}% impact</span>` : ''}
+ </div>
+ </div>
+ <div class="tb-cand-side">
+ <span class="tb-fw tb-fw-${fwClass}" title="${esc((fw.reasons || []).join(' · ') || fwLabel)}">${fwLabel}${fw.score != null ? ` ${fw.score}` : ''}</span>
+ <span class="tb-cand-out">${x.quote?.out_ui != null ? `≈ ${Number(x.quote.out_ui).toLocaleString(undefined, { maximumFractionDigits: 0 })}` : '—'} <i>for ${fmtSol(x.amount_sol)} SOL</i></span>
+ <button class="studio-btn ${blocked ? 'studio-btn-ghost' : 'studio-btn-primary'}" data-action="confirm-snipe" data-mint="${esc(x.mint)}" ${blocked ? 'disabled title="Firewall flagged this coin as unsafe"' : ''}>${blocked ? 'Blocked' : 'Confirm snipe'}</button>
+ </div>
+ </li>`;
+ }
+
+ _renderBacktest() {
+ const host = this._q('[data-backtest]');
+ if (!host) return;
+ const b = this.state.backtest;
+ if (this.state.backtesting) { host.innerHTML = `<div class="tb-card-head"><h4>Replaying real launch history…</h4></div><div class="tb-skel small"></div>`; return; }
+ if (!b) { host.innerHTML = ''; return; }
+ if (b.error) { host.innerHTML = `<div class="tb-hint tb-hint-warn">Backtest unavailable: ${esc(b.error)}</div>`; return; }
+ if (b.insufficient_data) {
+ host.innerHTML = `<div class="tb-card-head"><h4>Backtest — historical, not a guarantee</h4></div><div class="tb-hint">${esc(b.message)}</div>`;
+ return;
+ }
+ const m = b.metrics || {};
+ const conf = b.caveats?.confidence || 'low';
+ host.innerHTML = `
+ <div class="tb-card-head">
+ <h4>Backtest <span class="tb-badge tb-badge-${conf}">${esc(conf)} confidence</span></h4>
+ <p>Replayed over ${b.sample_size} real labeled launches (last ${b.window_days}d, ${esc(b.network)}). Historical only — never a guarantee of future results.</p>
+ </div>
+ <div class="tb-bt-grid">
+ <div class="tb-bt-stat"><b class="${m.win_rate >= 0.5 ? 'pos' : ''}">${(m.win_rate * 100).toFixed(0)}%</b><span>win rate</span></div>
+ <div class="tb-bt-stat"><b class="${m.expected_value_pct >= 0 ? 'pos' : 'neg'}">${fmtPct(m.expected_value_pct)}</b><span>avg ROI / trade</span></div>
+ <div class="tb-bt-stat"><b class="${m.net_pnl_sol >= 0 ? 'pos' : 'neg'}">${fmtSol(m.net_pnl_sol)}</b><span>net SOL (${b.sample_size}×${fmtSol(b.stake_sol)})</span></div>
+ <div class="tb-bt-stat"><b class="neg">−${fmtSol(m.max_drawdown_sol)}</b><span>max drawdown</span></div>
+ <div class="tb-bt-stat"><b>${fmtPct(m.roi_best_pct)}</b><span>best</span></div>
+ <div class="tb-bt-stat"><b class="neg">${fmtPct(m.roi_worst_pct)}</b><span>worst</span></div>
+ </div>
+ ${b.caveats?.items?.length ? `<details class="tb-caveats"><summary>How this is computed (${b.caveats.items.length} caveats)</summary><ul>${b.caveats.items.map((i) => `<li>${esc(i)}</li>`).join('')}</ul></details>` : ''}`;
+ }
+
+ _renderPositions() {
+ const host = this._q('[data-positions]');
+ if (!host) return;
+ const pos = this.state.positions || [];
+ if (!pos.length) {
+ host.innerHTML = `<div class="tb-card-head"><h4>Positions</h4></div><div class="tb-hint">No positions yet. Snipe a match or arm the agent — open and closed positions, with real P&L, land here.</div>`;
+ return;
+ }
+ const open = pos.filter((p) => p.status === 'open' || p.status === 'closing');
+ const closed = pos.filter((p) => p.status === 'closed');
+ host.innerHTML = `
+ <div class="tb-card-head"><h4>Positions <span class="tb-badge">${open.length} open</span></h4></div>
+ <ul class="tb-pos">${pos.slice(0, 20).map((p) => this._posRow(p)).join('')}</ul>`;
+ void closed;
+ }
+
+ _posRow(p) {
+ const live = p.status === 'open' || p.status === 'closing';
+ const pnl = live ? null : p.pnl_sol;
+ const pnlPct = live ? null : p.pnl_pct;
+ const cls = pnlPct == null ? '' : pnlPct >= 0 ? 'pos' : 'neg';
+ return `
+ <li class="tb-pos-row" data-status="${esc(p.status)}">
+ <span class="tb-pos-id"><b>${esc(p.symbol || p.name || short(p.mint))}</b>
+ ${p.entry_sig ? `<a href="${SOLSCAN(esc(p.entry_sig))}" target="_blank" rel="noopener" title="Entry tx">in ↗</a>` : ''}
+ ${p.exit_sig ? `<a href="${SOLSCAN(esc(p.exit_sig))}" target="_blank" rel="noopener" title="Exit tx">out ↗</a>` : ''}
+ </span>
+ <span class="tb-pos-state">${live ? `<span class="tb-pos-live">● ${esc(p.status)}</span>` : esc(p.exit_reason || 'closed')}</span>
+ <span class="tb-pos-entry">${fmtSol(p.entry_sol)} SOL in</span>
+ <span class="tb-pos-pnl ${cls}">${live ? (p.value_sol != null ? `${fmtSol(p.value_sol)} SOL value` : 'live') : `${pnl >= 0 ? '+' : ''}${fmtSol(pnl)} SOL ${pnlPct != null ? `(${fmtPct(pnlPct)})` : ''}`}</span>
+ </li>`;
+ }
+
+ _renderAudit() {
+ const host = this._q('[data-audit]');
+ if (!host) return;
+ const a = this.state.audit || [];
+ host.innerHTML = `
+ <div class="tb-card-head">
+ <h4>Audit log</h4>
+ ${a.length ? `<button class="studio-btn studio-btn-ghost tb-export" data-action="export-audit">Export CSV</button>` : ''}
+ </div>
+ ${a.length
+ ? `<ul class="tb-audit-list">${a.slice(0, 30).map((r) => this._auditRow(r)).join('')}</ul>`
+ : `<div class="tb-hint">Every decision and execution is logged here, exportable for your records.</div>`}`;
+ }
+
+ _auditRow(r) {
+ const sol = r.amount_lamports != null ? Number(r.amount_lamports) / 1e9 : null;
+ return `
+ <li class="tb-audit-row" data-status="${esc(r.status)}">
+ <span class="tb-audit-time">${esc(relTime(r.created_at))}</span>
+ <span class="tb-audit-what">${esc(r.reason || r.category)}</span>
+ <span class="tb-audit-amt">${sol != null ? `${fmtSol(sol)} ${esc(r.asset || 'SOL')}` : ''}${r.usd != null ? ` · ${fmtUsd(r.usd)}` : ''}</span>
+ <span class="tb-audit-status tb-audit-${esc(r.status)}">${esc(r.status)}</span>
+ ${r.signature ? `<a class="tb-audit-tx" href="${SOLSCAN(esc(r.signature))}" target="_blank" rel="noopener" title="View transaction">↗</a>` : ''}
+ </li>`;
+ }
+
+ // ── Bind ─────────────────────────────────────────────────────────────────────
+
+ _bind() {
+ this.el.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-action]');
+ if (!btn) return;
+ const a = btn.dataset.action;
+ if (a === 'retry') return this._load();
+ if (a === 'mode') return this._setMode(btn.dataset.mode);
+ if (a === 'kill') return this._toggleKill();
+ if (a === 'save') return this._saveStrategy();
+ if (a === 'backtest') return this._backtest();
+ if (a === 'arm') return this._arm();
+ if (a === 'disarm') return this._disarm();
+ if (a === 'scan') return this._scan();
+ if (a === 'confirm-snipe') return this._confirmSnipe(btn.dataset.mint);
+ if (a === 'save-guardrails') return this._saveGuardrails();
+ if (a === 'export-audit') return this._exportAudit();
+ });
+ // Rule edits — live recompute (English + validation) and debounced meta save.
+ this.el.addEventListener('input', (e) => {
+ const inp = e.target.closest('[data-rule]');
+ if (!inp) return;
+ this._applyRuleEdit(inp);
+ });
+ this.el.addEventListener('change', (e) => {
+ const inp = e.target.closest('[data-rule][type="checkbox"]');
+ if (!inp) return;
+ this._applyRuleEdit(inp);
+ });
+ }
+
+ _applyRuleEdit(inp) {
+ const path = inp.dataset.rule.split('.');
+ let v;
+ if (inp.type === 'checkbox') v = inp.checked;
+ else if (path[path.length - 1] === 'name') v = inp.value;
+ else v = inp.value === '' ? null : Number(inp.value);
+ // Set into this.rule by path.
+ let obj = this.rule;
+ for (let i = 0; i < path.length - 1; i++) obj = obj[path[i]];
+ obj[path[path.length - 1]] = v;
+ this.state.dirty = true;
+ // Live english + validation refresh without stealing focus: update just the
+ // english line + error spans, not the whole builder.
+ const eng = this._q('.tb-english');
+ if (eng) eng.innerHTML = `<span aria-hidden="true">🗣</span> ${esc(ruleToEnglish(this.rule))}`;
+ clearTimeout(this._metaTimer);
+ this._metaTimer = setTimeout(() => this._persistMeta(), 700);
+ }
+
+ _toast(msg, isError = false) {
+ const t = this._q('[data-tbtoast]');
+ if (!t) return;
+ t.textContent = msg;
+ t.hidden = false;
+ t.className = `mny-toast tb-toast ${isError ? 'mny-toast-err' : ''} show`;
+ clearTimeout(this._toastTimer);
+ this._toastTimer = setTimeout(() => { t.classList.remove('show'); setTimeout(() => { t.hidden = true; }, 300); }, 2800);
+ }
+
+ destroy() {
+ clearTimeout(this._metaTimer);
+ clearTimeout(this._toastTimer);
+ }
+}
diff --git a/src/studio/money/trading-runner.js b/src/studio/money/trading-runner.js
new file mode 100644
index 000000000..01c1bf9c3
--- /dev/null
+++ b/src/studio/money/trading-runner.js
@@ -0,0 +1,116 @@
+/**
+ * Trading Brain — P1 brain `market` node runner (P4)
+ * ==================================================
+ * P1's brain graph can contain a `market` node. The brain *reasons*; THIS runner
+ * gives it real, live trading context to reason with — closing the loop the P1
+ * spec opened (brain-nodes.js#registerNodeRunner). When the brain runs (the owner
+ * chats with their agent), any wired market node calls this runner; we return a
+ * `context` string injected into the system prompt so the model answers grounded
+ * in the agent's *actual* trading state, not a hallucination:
+ *
+ * • the live rule (assisted vs autonomous, armed or not, kill switch),
+ * • real open positions and their P&L,
+ * • for a propose/ask-brain trigger, the live launches matching the rule RIGHT
+ * NOW (real scan — same endpoint the assisted UI uses).
+ *
+ * It never executes a trade — execution stays behind the explicit assisted-confirm
+ * / autonomous-arm guards. This runner only informs the brain. When live matches
+ * appear it emits a market event so the avatar (P5) perks up.
+ *
+ * Loaded for its side effect (registration) by money-mount.js.
+ */
+
+import { studio } from '../agent-studio-store.js';
+import { registerNodeRunner } from '../brain/brain-nodes.js';
+import { apiFetch } from '../../api.js';
+import { compileRuleToConfig, normalizeRule, ruleToEnglish } from './trading-compile.js';
+
+// Live market reads are not free — cache the scan briefly so a chatty brain
+// doesn't hammer the RPC/feed on every message.
+let _scanCache = { at: 0, key: '', candidates: null };
+const SCAN_TTL_MS = 60_000;
+
+async function loadTradingState(agentId) {
+ const out = { armed: false, killed: false, open: [], rule: null, mode: 'assisted' };
+ const bag = studio.agent?.meta?.studio?.trading || {};
+ out.rule = bag.rule ? normalizeRule(bag.rule) : null;
+ out.mode = bag.mode === 'autonomous' ? 'autonomous' : 'assisted';
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies`);
+ if (res.ok) {
+ const { data } = await res.json();
+ out.killed = !!data.killed;
+ out.armed = (data.equips || []).some((e) => e.strategy_id === bag.strategyId && e.active);
+ out.open = (data.positions || []).filter((p) => p.status === 'open' || p.status === 'closing');
+ }
+ } catch { /* best-effort context */ }
+ return out;
+}
+
+async function scanMatches(agentId, rule, signal) {
+ const key = JSON.stringify(compileRuleToConfig(rule));
+ if (_scanCache.candidates && _scanCache.key === key && Date.now() - _scanCache.at < SCAN_TTL_MS) {
+ return _scanCache.candidates;
+ }
+ try {
+ const res = await apiFetch('/api/trading/scan', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agent_id: agentId, config: compileRuleToConfig(rule) }),
+ signal,
+ });
+ if (!res.ok) return null;
+ const { data } = await res.json();
+ _scanCache = { at: Date.now(), key, candidates: data.candidates || [] };
+ return _scanCache.candidates;
+ } catch {
+ return null;
+ }
+}
+
+registerNodeRunner('market', async (node, ctx) => {
+ const agentId = studio.agent?.id;
+ if (!agentId) return { context: '' };
+
+ const action = node?.data?.action || 'propose-action';
+ const st = await loadTradingState(agentId);
+
+ const lines = ['[Live trading context — real, from this agent\'s wallet and strategy engine]'];
+ if (st.rule) {
+ lines.push(`Active rule: "${st.rule.name}" — ${ruleToEnglish(st.rule)}`);
+ lines.push(`Mode: ${st.mode}. ${st.armed ? 'Autonomous strategy is ARMED.' : 'Not armed for autonomous trading.'}${st.killed ? ' KILL SWITCH IS ON — all autonomous trading is halted.' : ''}`);
+ } else {
+ lines.push('No trading rule has been authored yet in the Money studio.');
+ }
+
+ if (st.open.length) {
+ const desc = st.open.slice(0, 5).map((p) => {
+ const v = p.value_sol != null ? `${p.value_sol} SOL value` : 'live';
+ return `${p.symbol || p.name || p.mint.slice(0, 6)} (${p.entry_sol} SOL in, ${v})`;
+ }).join('; ');
+ lines.push(`Open positions (${st.open.length}): ${desc}.`);
+ } else {
+ lines.push('No open positions right now.');
+ }
+
+ // Only spend a live scan when the brain is actually meant to act on the signal.
+ if (st.rule && !st.killed && (action === 'propose-action' || action === 'ask-brain')) {
+ const matches = await scanMatches(agentId, st.rule, ctx?.signal);
+ if (matches && matches.length) {
+ const top = matches.slice(0, 4).map((c) => {
+ const fw = c.firewall?.verdict || 'n/a';
+ const mc = c.market_cap_usd != null ? `$${Math.round(c.market_cap_usd).toLocaleString()} mc` : '';
+ return `${c.symbol || c.name || c.mint.slice(0, 6)} (${mc}, ${c.age_minutes ?? '?'}m old, firewall: ${fw})`;
+ }).join('; ');
+ lines.push(`RIGHT NOW ${matches.length} live launch${matches.length === 1 ? '' : 'es'} match the rule: ${top}.`);
+ lines.push(action === 'ask-brain'
+ ? 'Think it through out loud, then tell the user whether to snipe any of these and at what size — but do NOT claim to have traded; the user confirms each snipe in the Money studio.'
+ : 'Propose a concrete action (which coin, what size, why) within the guardrails. The user confirms the snipe; you never execute it yourself.');
+ studio.emitMarket?.({ type: 'alert', mint: matches[0].mint });
+ } else if (matches) {
+ lines.push('No live launches currently match the rule.');
+ }
+ }
+
+ return { context: lines.join('\n') };
+});
diff --git a/src/theater.css b/src/theater.css
new file mode 100644
index 000000000..f3c379fbf
--- /dev/null
+++ b/src/theater.css
@@ -0,0 +1,371 @@
+/* Live Trading Theater — layout & UI. Built on /tokens.css; the violet finance
+ accent matches the wallet surfaces. All .th-* so it never collides with the
+ global stylesheet (which this bespoke 3D page skips). */
+
+.th-root {
+ --th-accent: #c4b5fd;
+ --th-accent-fill: rgba(139, 92, 246, 0.16);
+ --th-accent-stroke: rgba(139, 92, 246, 0.34);
+ position: fixed;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ background:
+ radial-gradient(120% 90% at 50% -10%, rgba(139, 92, 246, 0.14), transparent 60%),
+ #05050a;
+ color: var(--ink, #e8e8e8);
+ font-family: var(--font-body, system-ui, sans-serif);
+ overflow: hidden;
+}
+
+/* ── top bar ─────────────────────────────────────────────────────────────── */
+.th-topbar {
+ display: flex;
+ align-items: center;
+ gap: var(--space-4, 16px);
+ padding: var(--space-3, 12px) var(--space-5, 20px);
+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ backdrop-filter: blur(var(--blur-sm, 8px));
+}
+.th-back {
+ color: var(--ink-dim, #888);
+ text-decoration: none;
+ font-size: var(--text-sm, 0.78rem);
+ font-weight: var(--weight-medium, 500);
+ white-space: nowrap;
+ transition: color var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.th-back:hover { color: var(--ink-bright, #fff); }
+.th-title-wrap { flex: 1; min-width: 0; }
+.th-title {
+ margin: 0;
+ font-family: var(--font-display, system-ui);
+ font-size: var(--text-lg, 1.24rem);
+ font-weight: var(--weight-bold, 700);
+ letter-spacing: -0.01em;
+ color: var(--ink-bright, #fff);
+ line-height: 1.1;
+}
+.th-room-hint {
+ margin: 2px 0 0;
+ font-size: var(--text-xs, 0.7rem);
+ color: var(--ink-dim, #888);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* ── status pill ─────────────────────────────────────────────────────────── */
+.th-status {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2, 8px);
+ padding: 6px 12px;
+ border-radius: var(--radius-pill, 999px);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ font-size: var(--text-2xs, 0.69rem);
+ font-weight: var(--weight-semibold, 600);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+.th-status-dot {
+ width: 8px; height: 8px; border-radius: 50%;
+ background: var(--ink-dim, #888);
+ box-shadow: 0 0 0 0 currentColor;
+}
+.th-dot-green { color: var(--success, #4ade80); }
+.th-dot-green .th-status-dot { background: var(--success, #4ade80); animation: th-pulse 2s infinite; }
+.th-dot-amber { color: var(--warn, #fbbf24); }
+.th-dot-amber .th-status-dot { background: var(--warn, #fbbf24); }
+.th-dot-red { color: var(--danger, #f87171); }
+.th-dot-red .th-status-dot { background: var(--danger, #f87171); }
+@keyframes th-pulse {
+ 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5); }
+ 70% { box-shadow: 0 0 0 6px rgba(74, 222, 128, 0); }
+ 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }
+}
+
+/* ── rooms ───────────────────────────────────────────────────────────────── */
+.th-rooms {
+ display: flex;
+ gap: var(--space-2, 8px);
+ padding: var(--space-2, 8px) var(--space-5, 20px);
+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+.th-rooms::-webkit-scrollbar { display: none; }
+.th-room {
+ flex: 0 0 auto;
+ padding: 7px 14px;
+ border-radius: var(--radius-pill, 999px);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ background: transparent;
+ color: var(--ink-dim, #888);
+ font-size: var(--text-sm, 0.78rem);
+ font-weight: var(--weight-medium, 500);
+ cursor: pointer;
+ transition: all var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.th-room:hover { color: var(--ink-bright, #fff); border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14)); }
+.th-room.is-active {
+ color: var(--ink-bright, #fff);
+ background: var(--th-accent-fill);
+ border-color: var(--th-accent-stroke);
+}
+.th-room:focus-visible { outline: 2px solid var(--th-accent); outline-offset: 2px; }
+
+/* ── layout ──────────────────────────────────────────────────────────────── */
+.th-layout {
+ flex: 1;
+ display: grid;
+ grid-template-columns: 1fr 320px;
+ min-height: 0;
+}
+.th-stage {
+ position: relative;
+ min-height: 0;
+ overflow: hidden;
+}
+.th-canvas { display: block; width: 100%; height: 100%; touch-action: none; }
+.th-overlay {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ overflow: hidden;
+}
+
+/* ── floating receipts ───────────────────────────────────────────────────── */
+.th-receipt {
+ position: absolute;
+ top: 0; left: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 2px;
+ padding: 6px 12px;
+ border-radius: var(--radius-md, 10px);
+ background: rgba(10, 10, 18, 0.82);
+ border: 1px solid var(--th-accent-stroke);
+ backdrop-filter: blur(var(--blur-sm, 8px));
+ box-shadow: var(--shadow-2, 0 4px 24px rgba(0, 0, 0, 0.4));
+ white-space: nowrap;
+ pointer-events: auto;
+ will-change: transform, opacity;
+ transition: opacity 120ms linear;
+}
+.th-rec-title { font-size: var(--text-2xs, 0.69rem); font-weight: var(--weight-bold, 700); color: var(--ink-bright, #fff); letter-spacing: 0.02em; }
+.th-rec-sub { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, 0.69rem); color: var(--th-accent); }
+.th-rec-link { font-size: var(--text-2xs, 0.69rem); color: var(--ink-dim, #888); text-decoration: none; }
+.th-rec-link:hover { color: var(--ink-bright, #fff); }
+.th-rec-win { border-color: rgba(74, 222, 128, 0.45); }
+.th-rec-win .th-rec-sub { color: var(--success, #4ade80); }
+.th-rec-loss { border-color: rgba(248, 113, 113, 0.45); }
+.th-rec-loss .th-rec-sub { color: var(--danger, #f87171); }
+
+/* ── overlay states ──────────────────────────────────────────────────────── */
+.th-state {
+ position: absolute;
+ inset: auto 0 0 0;
+ margin: auto;
+ max-width: 460px;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ text-align: center;
+ padding: var(--space-6, 24px);
+ border-radius: var(--radius-lg, 14px);
+ background: rgba(8, 8, 14, 0.72);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ backdrop-filter: blur(var(--blur-md, 16px));
+ box-shadow: var(--shadow-3, 0 8px 32px rgba(0, 0, 0, 0.5));
+}
+.th-state[hidden] { display: none; }
+.th-state h2 { margin: 0 0 8px; font-family: var(--font-display, system-ui); font-size: var(--text-lg, 1.24rem); color: var(--ink-bright, #fff); }
+.th-state p { margin: 0; font-size: var(--text-sm, 0.78rem); line-height: var(--leading-normal, 1.6); }
+.th-muted { color: var(--ink-dim, #888); }
+.th-spinner {
+ width: 34px; height: 34px; margin: 0 auto 14px;
+ border: 3px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));
+ border-top-color: var(--th-accent);
+ border-radius: 50%;
+ animation: th-spin 0.9s linear infinite;
+}
+@keyframes th-spin { to { transform: rotate(360deg); } }
+.th-loading p { color: var(--ink-dim, #888); font-size: var(--text-sm, 0.78rem); }
+
+.th-highlights { margin-top: var(--space-4, 16px); display: flex; flex-direction: column; gap: 6px; text-align: left; max-height: 38vh; overflow-y: auto; }
+.th-hl {
+ display: flex; align-items: center; gap: 8px;
+ padding: 8px 10px;
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ text-decoration: none; color: var(--ink, #e8e8e8);
+ transition: background var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.th-hl:hover { background: var(--surface-2, rgba(255, 255, 255, 0.05)); }
+.th-hl-title { font-size: var(--text-sm, 0.78rem); font-weight: var(--weight-semibold, 600); }
+.th-hl-sub { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, 0.69rem); color: var(--th-accent); }
+.th-hl .th-tick-time { margin-left: auto; }
+
+/* ── read-only HUD panel ─────────────────────────────────────────────────── */
+.th-panel {
+ position: absolute;
+ top: var(--space-4, 16px);
+ left: var(--space-4, 16px);
+ width: min(340px, calc(100% - 32px));
+ max-height: calc(100% - 32px);
+ overflow-y: auto;
+ padding: var(--space-5, 20px);
+ border-radius: var(--radius-lg, 14px);
+ background: rgba(8, 8, 14, 0.9);
+ border: 1px solid var(--th-accent-stroke);
+ backdrop-filter: blur(var(--blur-lg, 28px));
+ box-shadow: var(--shadow-3, 0 8px 32px rgba(0, 0, 0, 0.5));
+ opacity: 0;
+ transform: translateX(-12px) scale(0.98);
+ pointer-events: none;
+ transition: opacity var(--duration-base, 220ms) var(--ease-emphasized, ease),
+ transform var(--duration-base, 220ms) var(--ease-emphasized, ease);
+}
+.th-panel.is-open { opacity: 1; transform: none; pointer-events: auto; }
+.th-panel-close {
+ position: absolute; top: 12px; right: 12px;
+ width: 28px; height: 28px;
+ border-radius: var(--radius-sm, 6px);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ color: var(--ink-dim, #888);
+ cursor: pointer; font-size: 13px; line-height: 1;
+}
+.th-panel-close:hover { color: var(--ink-bright, #fff); }
+.th-panel-head { display: flex; gap: var(--space-3, 12px); align-items: center; margin-bottom: var(--space-4, 16px); padding-right: 28px; }
+.th-panel-av { width: 52px; height: 52px; border-radius: var(--radius-md, 10px); object-fit: cover; background: var(--surface-2, rgba(255, 255, 255, 0.05)); flex: 0 0 auto; }
+.th-panel-av-fallback { display: flex; align-items: center; justify-content: center; font-family: var(--font-display, system-ui); font-weight: var(--weight-bold, 700); font-size: 22px; color: var(--th-accent); border: 1px solid var(--th-accent-stroke); }
+.th-panel-name { margin: 0; font-size: var(--text-md, 0.81rem); font-weight: var(--weight-bold, 700); color: var(--ink-bright, #fff); }
+.th-panel-tier { font-size: var(--text-2xs, 0.69rem); color: var(--th-accent); font-weight: var(--weight-medium, 500); }
+
+.th-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-2, 8px); margin-bottom: var(--space-3, 12px); }
+.th-stat { display: flex; flex-direction: column; gap: 2px; padding: 8px 6px; border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255, 255, 255, 0.03)); text-align: center; }
+.th-stat-v { font-family: var(--font-mono, monospace); font-size: var(--text-md, 0.81rem); font-weight: var(--weight-bold, 700); color: var(--ink-bright, #fff); }
+.th-stat-l { font-size: 0.6rem; color: var(--ink-dim, #888); text-transform: uppercase; letter-spacing: 0.04em; }
+.th-skel-inline { display: inline-block; width: 32px; height: 12px; border-radius: 4px; background: linear-gradient(90deg, var(--surface-1) 25%, var(--surface-3) 50%, var(--surface-1) 75%); background-size: 200% 100%; animation: th-shimmer 1.4s infinite; }
+@keyframes th-shimmer { to { background-position: -200% 0; } }
+
+.th-addr {
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
+ padding: 8px 10px; margin-bottom: var(--space-3, 12px);
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ font-family: var(--font-mono, monospace); font-size: var(--text-2xs, 0.69rem);
+ color: var(--ink, #e8e8e8); text-decoration: none;
+}
+.th-addr:hover { border-color: var(--th-accent-stroke); }
+.th-addr-ext { color: var(--ink-dim, #888); }
+
+.th-panel-actions { display: flex; flex-wrap: wrap; gap: var(--space-2, 8px); margin-bottom: var(--space-3, 12px); }
+.th-btn {
+ flex: 1 1 auto;
+ display: inline-flex; align-items: center; justify-content: center;
+ padding: 9px 12px;
+ border-radius: var(--radius-md, 10px);
+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ color: var(--ink, #e8e8e8);
+ font-size: var(--text-sm, 0.78rem); font-weight: var(--weight-semibold, 600);
+ text-decoration: none; cursor: pointer; white-space: nowrap;
+ transition: all var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.th-btn:hover { background: var(--surface-2, rgba(255, 255, 255, 0.05)); border-color: var(--th-accent-stroke); }
+.th-btn:focus-visible { outline: 2px solid var(--th-accent); outline-offset: 2px; }
+.th-btn-primary { background: var(--th-accent-fill); border-color: var(--th-accent-stroke); color: var(--ink-bright, #fff); }
+.th-btn-on { background: var(--th-accent-fill); border-color: var(--th-accent-stroke); color: var(--ink-bright, #fff); }
+.th-btn-sm { flex: 0 0 auto; padding: 5px 10px; font-size: var(--text-2xs, 0.69rem); }
+.th-panel-foot { font-size: var(--text-2xs, 0.69rem); line-height: var(--leading-normal, 1.6); margin: 0 0 var(--space-3, 12px); }
+.th-panel-foot a { color: var(--th-accent); text-decoration: none; }
+.th-panel-foot a:hover { text-decoration: underline; }
+.th-panel-recent-h, .th-rail-h { font-size: var(--text-2xs, 0.69rem); text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-dim, #888); margin: 0 0 8px; font-weight: var(--weight-semibold, 600); }
+.th-panel-recent ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 5px; }
+.th-panel-recent li { display: flex; align-items: center; gap: 7px; font-size: var(--text-2xs, 0.69rem); color: var(--ink, #e8e8e8); }
+.th-panel-recent .th-tick-time { margin-left: auto; }
+
+/* ── right rail (ticker + replay) ────────────────────────────────────────── */
+.th-rail {
+ border-left: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+.th-rail-block { padding: var(--space-4, 16px); border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08)); min-height: 0; display: flex; flex-direction: column; }
+.th-rail-block:first-child { flex: 1; }
+.th-rail-h { display: flex; align-items: center; gap: 7px; }
+.th-rail-dot { background: var(--success, #4ade80); animation: th-pulse 2s infinite; color: var(--success); }
+.th-ticker { list-style: none; margin: 0; padding: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 4px; }
+.th-tick {
+ display: flex; align-items: center; gap: 8px;
+ padding: 8px 10px;
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ animation: th-slidein var(--duration-base, 220ms) var(--ease-emphasized, ease);
+}
+@keyframes th-slidein { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }
+.th-tick-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-dim, #888); flex: 0 0 auto; }
+.th-tick-buy .th-tick-dot, .th-tick-win .th-tick-dot { background: var(--success, #4ade80); }
+.th-tick-loss .th-tick-dot { background: var(--danger, #f87171); }
+.th-tick-launch .th-tick-dot, .th-tick-verify .th-tick-dot, .th-tick-pay .th-tick-dot { background: var(--th-accent); }
+.th-tick-body { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+.th-tick-title { font-size: var(--text-sm, 0.78rem); font-weight: var(--weight-semibold, 600); color: var(--ink-bright, #fff); text-transform: capitalize; }
+.th-tick-sub { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, 0.69rem); color: var(--ink-dim, #888); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.th-tick-link { color: var(--ink-dim, #888); text-decoration: none; font-size: 13px; flex: 0 0 auto; }
+.th-tick-link:hover { color: var(--th-accent); }
+.th-tick-time { font-size: 0.6rem; color: var(--ink-faint, rgba(255, 255, 255, 0.45)); font-variant-numeric: tabular-nums; flex: 0 0 auto; }
+
+.th-replay-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
+.th-replay-empty { font-size: var(--text-2xs, 0.69rem); margin: 0; }
+.th-replay-rail { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
+.th-replay-mark {
+ width: 16px; height: 16px; border-radius: var(--radius-sm, 6px);
+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ cursor: pointer; padding: 0;
+ transition: transform var(--duration-fast, 140ms) var(--ease-standard, ease);
+}
+.th-replay-mark:hover { transform: scale(1.2); }
+.th-replay-mark.th-tick-buy, .th-replay-mark.th-tick-win { border-color: var(--success, #4ade80); background: rgba(74, 222, 128, 0.2); }
+.th-replay-mark.th-tick-loss { border-color: var(--danger, #f87171); background: rgba(248, 113, 113, 0.2); }
+.th-replay-mark.th-tick-launch, .th-replay-mark.th-tick-verify, .th-replay-mark.th-tick-pay { border-color: var(--th-accent-stroke); background: var(--th-accent-fill); }
+
+/* ── responsive ──────────────────────────────────────────────────────────── */
+@media (max-width: 900px) {
+ .th-layout { grid-template-columns: 1fr; }
+ .th-rail {
+ position: absolute; right: 0; bottom: 0; left: 0;
+ max-height: 40%;
+ flex-direction: row;
+ border-left: none; border-top: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ background: rgba(8, 8, 14, 0.86);
+ backdrop-filter: blur(var(--blur-md, 16px));
+ }
+ .th-rail-block { flex: 1; border-bottom: none; border-right: 1px solid var(--stroke, rgba(255, 255, 255, 0.08)); }
+ .th-replay { max-width: 40%; }
+ .th-panel { width: calc(100% - 24px); top: 12px; left: 12px; max-height: 50%; }
+}
+@media (max-width: 560px) {
+ .th-topbar { gap: var(--space-2, 8px); padding: 10px 14px; }
+ .th-title { font-size: var(--text-md, 0.81rem); }
+ .th-room-hint { display: none; }
+ .th-rail { flex-direction: column; max-height: 46%; }
+ .th-rail-block { border-right: none; border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08)); }
+ .th-replay { max-width: none; }
+ .th-stats { grid-template-columns: repeat(2, 1fr); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .th-spinner, .th-dot-green .th-status-dot, .th-rail-dot { animation: none; }
+ .th-tick { animation: none; }
+ .th-receipt { transition: none; }
+}
diff --git a/tests/agent-dreams-endpoint.test.js b/tests/agent-dreams-endpoint.test.js
new file mode 100644
index 000000000..7805224f8
--- /dev/null
+++ b/tests/agent-dreams-endpoint.test.js
@@ -0,0 +1,159 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+const getSessionUserMock = vi.fn();
+const authenticateBearerMock = vi.fn();
+const extractBearerMock = vi.fn();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (...a) => extractBearerMock(...a),
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' } }));
+// reflection.js (for decorateReflection) pulls in llm.js — stub it so the import
+// graph stays light and never touches a real provider.
+vi.mock('../api/_lib/llm.js', () => ({ llmComplete: vi.fn(), LlmUnavailableError: class extends Error {} }));
+
+const { default: dreamsHandler } = await import('../api/agent/dreams.js');
+
+function mkReq({ method = 'GET', url = '/api/agent/dreams', headers = {}, body = null } = {}) {
+ const hdrs = { ...headers };
+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';
+ return {
+ method, url, headers: hdrs,
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => { cb(buf); this._endCb?.(); });
+ } else if (event === 'end') this._endCb = cb;
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+const AGENT = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+const DREAM = 'dddddddd-dddd-dddd-dddd-dddddddddddd';
+const MEM = 'mmmmmmmm-mmmm-mmmm-mmmm-mmmmmmmmmmmm';
+
+let sqlQueue = [];
+beforeEach(() => {
+ sqlQueue = [];
+ sqlMock.mockReset().mockImplementation(() => Promise.resolve(sqlQueue.length ? sqlQueue.shift() : []));
+ getSessionUserMock.mockReset().mockResolvedValue({ id: 'user-1' });
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+});
+
+describe('GET /api/agent/dreams', () => {
+ it('returns pending dreams with their cited source memories hydrated', async () => {
+ const now = new Date();
+ sqlQueue = [
+ [{ id: AGENT, user_id: 'user-1' }], // ownership
+ [{
+ id: DREAM, agent_id: AGENT, status: 'pending', kind: 'belief',
+ statement: 'You prefer finality.', rationale: null, confidence: 0.8,
+ source_memory_ids: [MEM], proposed_type: 'user', proposed_salience: 0.85,
+ proposed_action: null, question: null, answer: null, accepted_memory_id: null,
+ created_at: now, reviewed_at: null,
+ }], // reflections
+ [{ id: MEM, type: 'user', content: 'cares about settlement', salience: 0.6, created_at: now }], // memories
+ [{ pending: 1 }], // pending count
+ [{ trigger: 'cron', status: 'ok', reason: null, dreams_created: 1, created_at: now }], // lastRun
+ ];
+ const req = mkReq({ url: `/api/agent/dreams?agentId=${AGENT}&status=pending` });
+ const res = mkRes();
+ await dreamsHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parse(res);
+ expect(body.pending).toBe(1);
+ expect(body.dreams).toHaveLength(1);
+ expect(body.dreams[0].sources[0]).toMatchObject({ id: MEM, type: 'user' });
+ expect(body.lastRun.dreamsCreated).toBe(1);
+ });
+
+ it('401s when not signed in', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ const req = mkReq({ url: `/api/agent/dreams?agentId=${AGENT}` });
+ const res = mkRes();
+ await dreamsHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('403s when the agent belongs to another user', async () => {
+ sqlQueue = [[{ id: AGENT, user_id: 'someone-else' }]];
+ const req = mkReq({ url: `/api/agent/dreams?agentId=${AGENT}` });
+ const res = mkRes();
+ await dreamsHandler(req, res);
+ expect(res.statusCode).toBe(403);
+ });
+});
+
+describe('POST /api/agent/dreams — review', () => {
+ it('accept writes a real higher-salience memory and resolves the dream', async () => {
+ const now = new Date();
+ sqlQueue = [
+ [{ id: AGENT, user_id: 'user-1' }], // ownership
+ [{ id: DREAM, agent_id: AGENT, status: 'pending', kind: 'belief', statement: 'You prefer finality.', proposed_type: 'user', proposed_salience: 0.85, confidence: 0.8, source_memory_ids: [MEM], proposed_action: null }], // dream
+ [{ id: MEM, type: 'user', content: 'You prefer finality.', salience: 0.85, created_at: now }], // memory insert
+ [{ id: DREAM, agent_id: AGENT, status: 'accepted', kind: 'belief', statement: 'You prefer finality.', confidence: 0.8, source_memory_ids: [MEM], proposed_type: 'user', proposed_salience: 0.85, proposed_action: null, question: null, answer: null, accepted_memory_id: MEM, created_at: now, reviewed_at: now }], // reflection update
+ ];
+ const req = mkReq({ method: 'POST', body: { agentId: AGENT, dreamId: DREAM, decision: 'accept' } });
+ const res = mkRes();
+ await dreamsHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parse(res);
+ expect(body.memory).toMatchObject({ id: MEM, type: 'user' });
+ expect(body.memory.salience).toBe(0.85);
+ expect(body.dream.status).toBe('accepted');
+ // 4 sql calls: ownership, dream fetch, memory insert, reflection update.
+ expect(sqlMock).toHaveBeenCalledTimes(4);
+ });
+
+ it('reject stores the rejection without writing a memory', async () => {
+ const now = new Date();
+ sqlQueue = [
+ [{ id: AGENT, user_id: 'user-1' }], // ownership
+ [{ id: DREAM, agent_id: AGENT, status: 'pending', kind: 'insight', statement: 'guess', proposed_type: 'project', proposed_salience: 0.7, confidence: 0.4, source_memory_ids: [MEM], proposed_action: null }], // dream
+ [{ id: DREAM, agent_id: AGENT, status: 'rejected', kind: 'insight', statement: 'guess', confidence: 0.4, source_memory_ids: [MEM], proposed_type: 'project', proposed_salience: 0.7, proposed_action: null, question: null, answer: null, accepted_memory_id: null, created_at: now, reviewed_at: now }], // update
+ ];
+ const req = mkReq({ method: 'POST', body: { agentId: AGENT, dreamId: DREAM, decision: 'reject' } });
+ const res = mkRes();
+ await dreamsHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parse(res);
+ expect(body.dream.status).toBe('rejected');
+ expect(body.memory).toBeUndefined();
+ // 3 sql calls: ownership, dream fetch, update (no memory insert).
+ expect(sqlMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('409s when the dream was already reviewed', async () => {
+ sqlQueue = [
+ [{ id: AGENT, user_id: 'user-1' }],
+ [{ id: DREAM, agent_id: AGENT, status: 'accepted', statement: 'x' }],
+ ];
+ const req = mkReq({ method: 'POST', body: { agentId: AGENT, dreamId: DREAM, decision: 'reject' } });
+ const res = mkRes();
+ await dreamsHandler(req, res);
+ expect(res.statusCode).toBe(409);
+ });
+
+ it('rejects an invalid decision', async () => {
+ const req = mkReq({ method: 'POST', body: { agentId: AGENT, dreamId: DREAM, decision: 'maybe' } });
+ const res = mkRes();
+ await dreamsHandler(req, res);
+ expect(res.statusCode).toBe(400);
+ });
+});
diff --git a/tests/agent-reflection.test.js b/tests/agent-reflection.test.js
new file mode 100644
index 000000000..47ded34a3
--- /dev/null
+++ b/tests/agent-reflection.test.js
@@ -0,0 +1,182 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the data + LLM layers so we can drive runReflection deterministically.
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+class LlmUnavailableError extends Error {
+ constructor() {
+ super('no provider');
+ this.code = 'llm_unavailable';
+ this.status = 503;
+ }
+}
+const llmCompleteMock = vi.fn();
+vi.mock('../api/_lib/llm.js', () => ({
+ llmComplete: (...a) => llmCompleteMock(...a),
+ LlmUnavailableError,
+}));
+
+const {
+ parseInsightPayload,
+ validateInsight,
+ runReflection,
+ MIN_NEW_SIGNALS,
+} = await import('../api/_lib/reflection.js');
+
+const ID_A = '11111111-1111-1111-1111-111111111111';
+const ID_B = '22222222-2222-2222-2222-222222222222';
+const ID_C = '33333333-3333-3333-3333-333333333333';
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ llmCompleteMock.mockReset();
+});
+
+// Helper: feed runReflection a scripted sequence of sql() results, in call order.
+function scriptSql(results) {
+ let i = 0;
+ sqlMock.mockImplementation(() => Promise.resolve(results[i++] ?? []));
+}
+
+describe('parseInsightPayload', () => {
+ it('parses a bare JSON object', () => {
+ expect(parseInsightPayload('{"insights":[]}')).toEqual({ insights: [] });
+ });
+ it('parses JSON inside a ```json fence', () => {
+ const txt = 'Here you go:\n```json\n{"insights":[{"statement":"x"}]}\n```';
+ expect(parseInsightPayload(txt)).toEqual({ insights: [{ statement: 'x' }] });
+ });
+ it('parses JSON wrapped in stray prose', () => {
+ const txt = 'Sure! {"insights":[{"statement":"y"}]} hope that helps';
+ expect(parseInsightPayload(txt)).toEqual({ insights: [{ statement: 'y' }] });
+ });
+ it('returns null on unparseable output', () => {
+ expect(parseInsightPayload('not json at all')).toBeNull();
+ expect(parseInsightPayload('')).toBeNull();
+ expect(parseInsightPayload(null)).toBeNull();
+ });
+});
+
+describe('validateInsight — provenance + schema', () => {
+ const ids = new Set([ID_A, ID_B]);
+
+ it('drops an insight with no cited source memories (provenance mandatory)', () => {
+ expect(validateInsight({ statement: 'no sources', source_memory_ids: [] }, ids)).toBeNull();
+ });
+
+ it('drops an insight whose cited ids are not in the provided context', () => {
+ expect(validateInsight({ statement: 'fabricated', source_memory_ids: [ID_C] }, ids)).toBeNull();
+ });
+
+ it('filters cited ids down to the real ones and de-dupes', () => {
+ const v = validateInsight(
+ { statement: 'real', source_memory_ids: [ID_A, ID_A, ID_C] },
+ ids,
+ );
+ expect(v).not.toBeNull();
+ expect(v.sourceIds).toEqual([ID_A]);
+ });
+
+ it('clamps proposed salience into the elevated band and defaults type', () => {
+ const v = validateInsight(
+ { statement: 's', source_memory_ids: [ID_A], proposed_salience: 5, proposed_type: 'bogus' },
+ ids,
+ );
+ expect(v.proposedSalience).toBeLessThanOrEqual(0.95);
+ expect(v.proposedSalience).toBeGreaterThanOrEqual(0.5);
+ expect(v.proposedType).toBe('project');
+ });
+
+ it('reclassifies a low-confidence insight with a question as kind=question', () => {
+ const v = validateInsight(
+ { statement: 's', source_memory_ids: [ID_A], confidence: 0.3, question: 'Do you prefer X?' },
+ ids,
+ );
+ expect(v.kind).toBe('question');
+ expect(v.question).toBe('Do you prefer X?');
+ });
+
+ it('rejects an empty or oversized statement', () => {
+ expect(validateInsight({ statement: '', source_memory_ids: [ID_A] }, ids)).toBeNull();
+ expect(validateInsight({ statement: 'x'.repeat(1001), source_memory_ids: [ID_A] }, ids)).toBeNull();
+ });
+});
+
+describe('runReflection — eligibility gates', () => {
+ it('skips (and logs a run) when there is not enough new material', async () => {
+ // gather: lastRun, runs-count, lastOk, memories, actions, then recordRun insert
+ scriptSql([
+ [], // lastRun (none)
+ [{ runs: 0 }], // daily count
+ [], // lastOk (none)
+ [{ id: ID_A, type: 'user', content: 'a', tags: [], salience: 0.5, created_at: new Date() }], // 1 memory
+ [], // actions
+ [{ id: 'run1', created_at: new Date() }], // recordRun insert
+ ]);
+ const res = await runReflection({ agentId: 'agent-1', trigger: 'cron' });
+ expect(res.status).toBe('skipped');
+ expect(res.reason).toMatch(/not enough new material/);
+ expect(res.created).toEqual([]);
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ expect(MIN_NEW_SIGNALS).toBeGreaterThan(1);
+ });
+
+ it('persists only groundable dreams from a real model pass', async () => {
+ const now = new Date();
+ const mems = [
+ { id: ID_A, type: 'user', content: 'asked about settlement speed', tags: [], salience: 0.6, created_at: now },
+ { id: ID_B, type: 'project', content: 'wants finality over fees', tags: [], salience: 0.6, created_at: now },
+ { id: ID_C, type: 'reference', content: 'reads $THREE alerts daily', tags: [], salience: 0.6, created_at: now },
+ ];
+ scriptSql([
+ [], // lastRun
+ [{ runs: 0 }], // daily count
+ [], // lastOk
+ mems, // memories (3 → enough signal)
+ [], // actions
+ [], // rejected
+ [{ id: 'run-ok', created_at: now }], // recordRun (ok)
+ [{
+ id: 'dream-1', agent_id: 'agent-1', status: 'pending', kind: 'belief',
+ statement: 'You prioritize finality over fees.', rationale: 'from 2 memories',
+ confidence: 0.8, source_memory_ids: [ID_A, ID_B], proposed_type: 'user',
+ proposed_salience: 0.85, proposed_action: null, question: null,
+ run_id: 'run-ok', accepted_memory_id: null, created_at: now, reviewed_at: null,
+ }], // reflection insert RETURNING *
+ ]);
+ llmCompleteMock.mockResolvedValue({
+ text: JSON.stringify({
+ insights: [
+ // valid — cites real ids
+ { kind: 'belief', statement: 'You prioritize finality over fees.', confidence: 0.8, source_memory_ids: [ID_A, ID_B], proposed_type: 'user', proposed_salience: 0.85 },
+ // invalid — no real provenance, must be dropped (not inserted)
+ { kind: 'insight', statement: 'fabricated', confidence: 0.9, source_memory_ids: ['99999999-9999-9999-9999-999999999999'] },
+ ],
+ }),
+ provider: 'groq', model: 'llama-3.3-70b-versatile', usage: { input: 100, output: 50 },
+ });
+
+ const res = await runReflection({ agentId: 'agent-1', userId: 'user-1', trigger: 'on-demand', agent: { name: 'Aria' } });
+ expect(res.status).toBe('ok');
+ expect(res.candidates).toBe(2); // model proposed 2
+ expect(res.created).toHaveLength(1); // only the groundable one persisted
+ expect(res.created[0].statement).toMatch(/finality over fees/);
+ expect(res.created[0].sourceMemoryIds).toEqual([ID_A, ID_B]);
+ expect(llmCompleteMock).toHaveBeenCalledOnce();
+ });
+
+ it('records an error run when the model output is unparseable', async () => {
+ const now = new Date();
+ const mems = [
+ { id: ID_A, type: 'user', content: 'a', tags: [], salience: 0.6, created_at: now },
+ { id: ID_B, type: 'user', content: 'b', tags: [], salience: 0.6, created_at: now },
+ { id: ID_C, type: 'user', content: 'c', tags: [], salience: 0.6, created_at: now },
+ ];
+ scriptSql([[], [{ runs: 0 }], [], mems, [], [], [{ id: 'run-err', created_at: now }]]);
+ llmCompleteMock.mockResolvedValue({ text: 'totally not json', provider: 'groq', model: 'm', usage: {} });
+ const res = await runReflection({ agentId: 'agent-1', trigger: 'cron' });
+ expect(res.status).toBe('error');
+ expect(res.reason).toMatch(/unparseable/);
+ });
+});
diff --git a/vercel.json b/vercel.json
index c2deeaa41..48976bed3 100644
--- a/vercel.json
+++ b/vercel.json
@@ -980,6 +980,10 @@
"src": "/club/?",
"dest": "/club.html"
},
+ {
+ "src": "/theater/?",
+ "dest": "/theater.html"
+ },
{
"src": "/stage/?",
"dest": "/stage.html"
@@ -1984,6 +1988,10 @@
"src": "/api/agents/([^/]+)/persona(/.*)?",
"dest": "/api/agents/[id]"
},
+ {
+ "src": "/api/agents/([^/]+)/brain(/.*)?",
+ "dest": "/api/agents/[id]"
+ },
{
"src": "/api/agents/([^/]+)/eth-vanity/([^/]+)",
"dest": "/api/agents/[id]"
diff --git a/vite.config.js b/vite.config.js
index 4c3b56b4c..d1019410c 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -344,6 +344,7 @@ const appConfig = {
watchlist: resolve(__dirname, 'pages/watchlist.html'),
leaderboard: resolve(__dirname, 'pages/leaderboard.html'),
'labor-market': resolve(__dirname, 'pages/labor-market.html'),
+ 'alpha-copilot': resolve(__dirname, 'pages/alpha-copilot.html'),
'reasoning-ledger': resolve(__dirname, 'pages/reasoning-ledger.html'),
mirror: resolve(__dirname, 'pages/mirror.html'),
strategies: resolve(__dirname, 'pages/strategies.html'),
@@ -435,6 +436,7 @@ const appConfig = {
pose: resolve(__dirname, 'pages/pose.html'),
animations: resolve(__dirname, 'pages/animations.html'),
club: resolve(__dirname, 'pages/club.html'),
+ theater: resolve(__dirname, 'pages/theater.html'),
stage: resolve(__dirname, 'pages/stage.html'),
skills: resolve(__dirname, 'pages/skills.html'),
'agenc-embodied': resolve(__dirname, 'pages/agenc/embodied.html'),
@@ -791,6 +793,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/leaderboard/': resolve(root, 'pages/leaderboard.html'),
'/labor-market': resolve(root, 'pages/labor-market.html'),
'/labor-market/': resolve(root, 'pages/labor-market.html'),
+ '/alpha-copilot': resolve(root, 'pages/alpha-copilot.html'),
+ '/alpha-copilot/': resolve(root, 'pages/alpha-copilot.html'),
'/arena': resolve(root, 'pages/arena.html'),
'/arena/': resolve(root, 'pages/arena.html'),
'/mirror': resolve(root, 'pages/mirror.html'),
@@ -885,6 +889,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/pose/': resolve(root, 'pages/pose.html'),
'/club': resolve(root, 'pages/club.html'),
'/club/': resolve(root, 'pages/club.html'),
+ '/theater': resolve(root, 'pages/theater.html'),
+ '/theater/': resolve(root, 'pages/theater.html'),
'/stage': resolve(root, 'pages/stage.html'),
'/stage/': resolve(root, 'pages/stage.html'),
'/dad': resolve(root, 'pages/dad.html'),