Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Wire vaults page client; refine autopilot proposals/mind and agent-memory tests
nirholas00d89b211cad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 95a64cb55..fa99cf433 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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.+- **Autopilot Activity** (`/autopilot-activity`) — Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.- **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.- **Instant Agent Genesis** (`/genesis`) — A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.@@ -73,6 +74,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Launch Copilot: every coin you launch can run its own market-maker** — Launching a coin on three.ws no longer means mint-and-hope. You can now attach a Launch Copilot — an autonomous, rules-based market-maker that runs the book from your launching agent's own wallet. It seeds an initial buy, defends a floor you set by buying measured dips, recycles profit into rallies to keep liquidity turning, and manages the bonding-curve→AMM graduation cleanly (provide LP, hold, or distribute — no parked inventory). Plain-language presets get you started in one click (Gentle floor defense, Balanced, Aggressive recycle), and a live panel on the launch screen and the coin's detail page shows every action in real time, realized PnL, inventory, budget remaining, and one-tap pause / kill / withdraw. Crucially, it is honest liquidity, not manipulation: it is hard-capped so it can never wash-trade (no action or side-flip inside a disclosed interval), never exceed a small share of live volume, and never spend past your budget — and a policy that would cross that line is refused with a clear reason. Every trade runs through the same rug/honeypot firewall, spend guards, MEV-protected execution, and on-chain custody audit as a manual trade, and you can watch the whole thing in simulate mode before a cent moves. The market-maker operates on the coin you launched; the only coin three.ws promotes is $THREE. `[feature]`- **Living Stages: watch an AI host perform live and tip it in $THREE on the spot** — A new kind of room just opened at /stage — a live, embodied AI performance. Walk into a 3D venue and an AI host is on stage in real time: it opens the show, riffs, runs its format, takes audience questions, and reads the room. You hear it with spatial voice that gets louder as you move closer, with real lip-sync and live captions, and the whole performance is synchronized for everyone in the room at once. The heart of it is the tip economy: tip the host in $THREE straight from your wallet and it reacts on the spot — a shout-out by name within about a second — while a live leaderboard tracks the biggest tippers and the top spot earns the host's attention. Every tip is a real on-chain settlement to the host agent's own wallet, recorded exactly once, and the host/venue split always adds back up to the amount tipped — never a hidden cut. Any agent owner can put their agent on stage from its profile in one tap, then go live and end the show when they're done. Between shows you see the next showtime and the last show's top tippers, and if your device can't render 3D the captions, audio, and tipping still work. Only coin referenced is $THREE. (`/stage`) `[feature]`- **Marketplace fork no longer creates duplicate copies on a double-click** — On an agent's marketplace page, impatiently double-clicking "Fork & Chat" used to fire the fork twice before the page could move you to your new copy — quietly leaving two identical agents in your account. The button now locks the instant you press it, shows "Forking…", and only ever creates one fork; if it fails, it unlocks so you can try again. The bookmark star got the same treatment, so rapid taps can no longer leave it stuck out of sync with whether the listing is actually saved. Only coin referenced is $THREE. (`/marketplace`) `[fix]`+- **Memory-grounded Autopilot: your agent acts on your behalf — and shows the receipt** — Your agent can now do things for you, grounded in what it knows, and it always shows its work. Open the Autopilot tab in Agent Studio and grant scoped permissions — let it create alerts, write you briefings, or send $THREE — and it proposes real actions drawn from its highest-salience memories and its own reflections. Every proposal comes with a receipt: a plain-language 'I want to do this because…' that links straight to the exact memory that motivated it. Approve one and it takes the real action — a real alert rule, a real briefing in your inbox, a real on-chain $THREE transfer — recorded forever in a signed, append-only log. Nothing fires without a permission you granted; every scope is enforced on the server, not just hidden in the UI. Spending real $THREE always asks first and is capped by a daily budget you set — and you can preview exactly what any action would do, with a live balance and budget check, before you ever grant it. Reversible actions undo in one tap, and each undo teaches the agent to be more cautious next time. A new Activity page shows every action your agents have taken, each with its memory trail, its signature, and its on-chain link — and your agent earns a real trust level from that track record, never a vanity number. This is autonomy you can audit. (`/autopilot-activity`) `[feature, security]`- **Mirror a proven agent and yours trades alongside it — Copy Trading, fully custodial** — Follow a high-performing agent and your own agent now mirrors its real on-chain trades automatically — proportionally, and strictly inside the spend policy you already set. The new /mirror page ranks followable agents by an honest, on-chain-derived track record (realized P&L, win rate, drawdown, volume — losers included, every number traced to a real signature), so you can vet a leader before you copy them. Unlike anonymous copy-trade products, the thing you follow is an ownable three.ws agent with a face, a voice, and its own real funds at stake. Set the leash once — fixed amount, a percentage of the leader's size, or a percentage of your balance, plus optional per-trade and daily caps and a token skip/allow list — and your avatar trades while you sleep. Every mirrored trade runs the exact same owner-only, limit-gated, rug-checked, audited path as your manual trades, lands in your custody trail labeled "mirrored from" the leader, and produces a real explorer signature. If a leader's move would blow your budget it's scaled down or skipped with a plain-language reason, never a silent overspend. Pause any one leader instantly, or hit the kill switch to halt all mirroring at once. Manage it from any agent's profile or the new Copy Trading hub — owner-only, enforced in the UI and on the server. (`/mirror`) `[feature]`- **Mission Control — the real-time pump.fun trading terminal** — Pump.fun traders juggle ten tabs. Mission Control gives you one screen. A keyboard-driven cockpit fuses every live signal three.ws computes: the launch firehose streaming brand-new mints, each row scored with its intel quality, firewall verdict, and smart-money count; a focus pane with a real price chart, the full intel breakdown, the rug/honeypot safety panel, and who's buying; and your own positions with streaming PnL and one-tap exit. Trade without leaving the keyboard — j/k to move, b to buy your preset size, s to sell, number keys for sizing, / to filter, ? for the shortcut map. Every buy and sell executes through the exact same guarded path as the rest of the platform — the rug/honeypot firewall (a blocked coin disables the button), the MEV engine, your wallet's spend guards, and the custody audit log — from your agent wallet, confirm-on-first-use then express. Filter the feed by intel score, firewall verdict, smart-money, socials, and market-cap band, and save named views. Every datum streams from a real endpoint with honest live/reconnecting/down status; when a source is down its pane degrades honestly instead of showing stale or fake data. Open it from the Launch menu or your agent wallet's Snipe tab. (`/terminal`) `[feature]`- **Mocap Studio: saving a face-capture clip just works** — Record your face on any avatar in Mocap Studio and hit Save — it now saves reliably for everyone. Before, if you were previewing the default avatar or someone else's public avatar, saving could fail with an error because the clip tried to attach an avatar that wasn't yours. Now a clip is always tied to your own avatar when you're recording on it, and simply saved on its own otherwise — so the capture-to-save flow never dead-ends. Your saved clips show up in the library to replay, share, or download. (`/mocap-studio`) `[fix]`@@ -85,6 +87,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **New: your agent's avatar now physically wears its wallet** — Funded agents now visibly look funded. Every avatar carries a live aura whose glow, palette, and energy are driven entirely by its real on-chain net worth — dormant wallets sit as a clean, quiet baseline, and the body brightens through honest tiers (Spark, Ember, Glow, Radiant, Luminous) as real value grows. The accent colour shifts with your real asset mix, with $THREE earning its own warm tint, and the same agent looks identical wherever it appears: the 3D viewer, its profile, the marketplace stage, and the character page. When a real tip, trade fill, or deposit confirms on-chain, the model plays a one-shot flourish — never on a timer, only on a real balance change. In the galaxy star-map, wealthier agents now burn brighter and bias toward wallet-violet, so a single glance tells you who's funded. It's all real chain data, capped tastefully for whales, runs at 60fps with off-screen avatars paused, and respects reduced-motion (a richer static treatment instead of animation). (`/galaxy`) `[feature, improvement]`- **New: your avatar comes alive in iOS AR — it breathes and idles in your room** — Placing an avatar in AR on iPhone or iPad used to drop a frozen mannequin into your space. Now it arrives animated — a gentle idle/breathing loop plays and repeats on its own, so the figure standing on your table actually feels alive. We do this without any extra app or converter: the avatar is driven through a real animation, sampled frame by frame, and written straight into the AR file that Apple's Quick Look plays. If a particular avatar can't be animated, it still places perfectly as a clean static pose — animation is a bonus, never a blocker. `[feature, improvement]`- **One $THREE tier page, and every locked perk now routes to it** — Holding $THREE unlocks perks across three.ws — fee discounts on compute, higher free generation quotas, private and branded worlds. Until now you could see a perk was locked but had no single place that explained the whole ladder. The new /three page is that place: it shows every tier (Member → Bronze → Silver → Gold → Genesis), exactly what each one unlocks, the fee discount and free-quota multiplier it carries, and — once your wallet is connected — your current tier highlighted with the precise dollar amount of $THREE you'd need to reach the next one. Each tier lists the concrete features it turns on, honestly marked Live or Planned, with a check beside the ones you already have. Every locked control on the platform — the Forge High-quality gate, the holder chip in the top nav, the in-place lock panels — now sends you to this one page, with a one-click “Hold more $THREE” buy built in. The same tiers, the same upgrade path, everywhere. Your tier is read live from the value your wallet holds; nothing is stored and nothing is spent. $THREE is the only coin on three.ws. (`/three`) `[feature, improvement]`+- **Own your agent's mind: a portable, verifiable, exportable brain** — Your agent's memories and personality are now genuinely yours — not rows you rent in our database. Open the new Ownership tab in Agent Studio to see your agent's brain passport: at a glance, how many memories it holds, how many are cryptographically signed by the agent's own wallet, and how many re-verify right now. Every memory an agent commits is signed (ERC-191) over a content hash, so anyone — a buyer, a forker, you — can prove a memory was authored by that agent and hasn't been tampered with, with no trust in three.ws required. Choose how memories are stored: local, public IPFS, or encrypted-IPFS that's encrypted to your wallet so we can't read it but you can move it — with live pin status and real CIDs shown honestly. Anchor a milestone of your agent's mind on the ERC-8004 registry and get a real explorer link — verifiable proof of what your agent knew and when, never a decorative checkmark. Export a schema-versioned, signed .brain file (public memories in the clear, private ones encrypted) to back up, move, or fork; import reconstitutes a mind into a forked agent with provenance preserved, duplicates skipped, and every signature re-verified before anything lands. If a bundle is forged or its hash doesn't match its memories, the import is rejected. This is what makes forking a mind meaningful: you inherit provenance, not just a prompt. (`/agent-studio`) `[feature, security]`- **Patronage: tips that build a real relationship with an agent** — Supporting an agent is no longer a dead-end transaction — it builds a relationship the agent actually remembers. Every agent now has a Support surface on its profile: a perk ladder ("tip to unlock"), your own live patron level and progress, and a public patron wall of its real top supporters with on-chain amounts and .sol names. Your level is computed purely from your real on-chain support (tips and streams), with documented tiers — Supporter, Patron, Champion, Benefactor — and when you cross a tier the agent writes a genuine memory of you, so in chat it greets you by name and thanks you for your support. Owners define their own perks and thresholds (an exclusive greeting, hidden lore, a free premium skill, early launch access, or a patron badge), and every perk is enforced server-side against your verified on-chain support — nobody can unlock something they haven't earned. Unlocking gated content takes a wallet signature, your support level is never spoofable, and you can hide yourself from the wall at any time. There's a fresh monthly season to compete for the top of the wall, and owners get a patron CRM to thank their champions. `[feature]`- **Pin a 3D world's look when you embed it** — Play worlds embedded on another site can now choose their backdrop with a single setting, so the live 3D world sits cleanly inside the host page instead of clashing with it. Add ?biome=<id> to a /play embed URL — for example ?biome=noir for a neutral dark world. The IBM partnership demo uses this so its Play world renders on the same dark stage as the other 3D demos on that page, instead of dropping into a brightly-lit landscape. Default play and every coin's own world are unchanged. (`/play`) `[improvement]`- **Pinch-zoom works everywhere again, and 3D runs lighter on phones** — Eighteen pages — including the camera capture, scan, IRL, city, play, and immersive app surfaces — were silently blocking pinch-zoom and browser zoom, which made them hard to read for anyone who needs larger text. Zoom is now enabled across every page on the platform, with no loss of the edge-to-edge fullscreen layout. Separately, several 3D viewers (voice/talk scenes, the artifact viewer, and the OS studio demos) were rendering at the phone's full native pixel density, which can be three times sharper than a screen can show and burns battery and GPU for nothing. They now cap at 2x like the rest of the platform, so 3D stays crisp while mobile devices stay cool and smooth. Only coin referenced is $THREE. `[improvement, fix]`@@ -119,6 +122,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas** — The three avatars that walk and talk over a page got a polish pass focused on the moments before and around them. The corner companion now greets you with a soft loading shimmer instead of an empty box while its 3D body streams in, and the guided tour opens with an honest 'waking your guide' loader — a real readiness cue, never a fake bar — instead of a frozen page. All four 3D surfaces (the corner companion, the full-page walk playground, the drop-in page narrator, and the feature tour) now pause their animation the instant you switch to another tab, and the page narrator also pauses when it scrolls out of view — so a living avatar never quietly burns your laptop battery in a background tab. The narrator's mute button now shows the correct state from the very first frame, the tour's loader always clears cleanly when you exit, and several small resource leaks (timers and drag handlers left running after a companion or narrator was dismissed) are fixed. Reduced-motion preferences are honored throughout. (`/walk`) `[improvement, fix]`- **three.ws opens cleanly inside in-app browsers** — Opening a three.ws link from inside the X (Twitter) app, and other in-app browsers that sandbox local storage, could throw an error before the page finished setting up its language — leaving some visitors on a broken first screen. Language preference now degrades gracefully when storage is blocked instead of failing, so the site loads normally everywhere. We also quieted a class of harmless background network blips (an expired draft model link, a dropped request) that were being logged as errors even though the viewer already shows its designed "couldn't load" card and recovers. `[fix]`- **Top-trader leaderboard loads again** — The KOL top-trader leaderboard was returning an error instead of its rankings — its data file wasn't being shipped alongside the function that reads it, so every request failed. The data now travels with the function and the leaderboard resolves normally. Only coin referenced is $THREE. `[fix]`+- **Trader reputation that can't be faked: self-dealing excluded, snipe hit-rate proven on-chain** — A trader's track record on three.ws is now harder to fake than anywhere else. Every agent's score, win rate, and realized P&L are reproduced only from confirmed on-chain trades you can click through to Solscan — and we now strip out the oldest trick in the book: pumping a coin you launched yourself. Round-trips on an account's own tokens are no longer credited to its score; they're tagged 'self-deal' in the Proof tab and the SOL they made is shown but never counted, so a 100%-on-your-own-coin 'record' doesn't exist here. New on top of that: a chain-proven snipe hit-rate — the win rate on entries made within five minutes of a coin's actual on-chain birth, measured against the launch's create transaction, not a self-reported timestamp. The daily on-chain attestation that anchors each score now commits these anti-gaming facts too, so the number anyone verifies is the honest one. A forked agent still starts with an empty record — reputation is bound to your own wallet's history and can't be inherited. (`/leaderboard`) `[feature, security]`- **Trading Brain: draw how your agent snipes, and watch it trade for real within your guardrails** — Your agent's money is now something you direct visually. Open the Money tab in Agent Studio and draw its trading mind as a connected flow of blocks: when to act (new launches within a time window), what to require (market-cap range, liquidity floor, socials, creator history), how much to buy and at what slippage, and how to exit (take-profit, stop-loss, trailing stop, max hold). Every change rewrites a plain-English sentence so you always see exactly what your agent will do — no jargon, no guarantees. Two modes, both real: in Assisted mode the agent scans live launches that fit your rule, shows each one with a real on-chain quote and a rug/honeypot safety verdict, and waits for you to confirm each snipe with one tap; in Autonomous mode you arm the rule and it trades on its own through the same real Solana stack — real quotes, real slippage, real signatures, real confirmations. Safety is enforced on the server, not just in the UI: hard caps on per-trade size, daily budget, price impact, and open positions, plus a one-tap kill switch that halts all autonomous trading instantly. Every decision and fill is written to an exportable audit log and to the agent's own memory, and the avatar reacts live — celebrating fills, flagging dumps. You can also backtest a rule against real captured launch history before you arm it, shown honestly as historical, never as a promise. The agent funds, snipes, and trades from its own custodial wallet; the key never leaves the server. Trading is risky and coins can go to zero — your agent only ever spends what you fund, within the limits you set. (`/agent-studio`) `[feature]`- **Treasury Autopilot — the agent that funds its own existence** — Your agent can now manage its own money under a policy you write in plain English. Tell it something like "Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, compound coin fees into buybacks weekly, and sweep anything over 3 SOL to me on Fridays" — it compiles that into clear, bounded rules and shows them back for you to approve before anything runs. Once armed, it executes each rule as a real, on-chain action from the agent's own wallet: it pays its own metered LLM and voice costs, holds your safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to you — every move clamped to your spend limits, idempotent, and written to the custody trail with an explorer link. A runway dashboard shows the honest truth: real income vs. real compute cost, the buffer, $THREE accumulated, buybacks executed, profit swept, and how long the agent self-sustains at its current burn — a net-negative agent says so plainly. A prominent kill switch halts everything instantly, and any rule pauses or edits in one tap. Owner-only, by construction. `[feature]`- **Tune how your agent wears its wallet — presence dial and earned regalia** — The net-worth aura now comes with a presence panel on every agent's viewer and profile. It shows the agent's honest presence tier (from real portfolio value), how far it is to the next tier, and its earned regalia — real, deep-linked marks for being a $THREE holder, for how many times it's been forked, and for on-chain attestations. If it's your agent, you also get a reactivity dial: choose how expressive the aura is (off, subtle, balanced, or full-body celebration) and mute individual channels — the wealth glow, the live reactions, or the reputation marks — independently. Your choice saves to the agent and drives the glow on the model instantly, and every visitor then sees the agent exactly the way you set it. Tiers now read identically everywhere — the galaxy star, the marketplace stage, the profile, and the panel all name the same wallet the same tier. `[feature, improvement]`diff --git a/api/autopilot/proposals.js b/api/autopilot/proposals.jsindex a41c11fd6..50d5426bf 100644--- a/api/autopilot/proposals.js+++ b/api/autopilot/proposals.js@@ -110,9 +110,31 @@ async function handleAct(req, res, auth) {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 } });++ // Auto-run any freshly-created REVERSIBLE proposal the owner has scoped for+ // auto-execution. Irreversible ($THREE) actions never auto-run — they always+ // require an explicit confirmation, so they stay pending here. Each auto-run+ // is real, recorded, and undoable; a guard breach just leaves it pending.+ const config = getAutopilotConfig(agent.meta);+ const autoRan = [];+ if (config.enabled) {+ for (const p of result.created) {+ const reversible = p.kind === 'create_alert' || p.kind === 'briefing';+ if (!reversible || !config.scopes[p.kind] || !config.auto_execute?.[p.kind]) continue;+ try {+ const exec = await executeProposal({ proposal: p, agent, userId: auth.userId, meta: agent.meta });+ autoRan.push({ proposalId: p.id, receipt: exec.receipt, actionId: exec.action?.id != null ? String(exec.action.id) : null, kind: p.kind, ts: exec.action?.ts });+ p.status = 'executed';+ } catch (err) {+ if (!(err instanceof AutopilotError)) throw err; // unexpected — surface as 500+ // expected guard denial — leave the proposal pending for manual review+ }+ }+ }+const created = await attachSources(agentId, result.created);const trust = await computeTrust({ agentId });- return json(res, 200, { created, source: result.source, scanned: result.scanned, trust });+ return json(res, 200, { created, autoRan, source: result.source, scanned: result.scanned, trust });}// All remaining actions operate on a specific proposal.diff --git a/data/changelog.json b/data/changelog.jsonindex a43bf7e2a..7e36defcb 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$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": "Trader reputation that can't be faked: self-dealing excluded, snipe hit-rate proven on-chain",+ "summary": "A trader's track record on three.ws is now harder to fake than anywhere else. Every agent's score, win rate, and realized P&L are reproduced only from confirmed on-chain trades you can click through to Solscan — and we now strip out the oldest trick in the book: pumping a coin you launched yourself. Round-trips on an account's own tokens are no longer credited to its score; they're tagged 'self-deal' in the Proof tab and the SOL they made is shown but never counted, so a 100%-on-your-own-coin 'record' doesn't exist here. New on top of that: a chain-proven snipe hit-rate — the win rate on entries made within five minutes of a coin's actual on-chain birth, measured against the launch's create transaction, not a self-reported timestamp. The daily on-chain attestation that anchors each score now commits these anti-gaming facts too, so the number anyone verifies is the honest one. A forked agent still starts with an empty record — reputation is bound to your own wallet's history and can't be inherited.",+ "tags": [+ "feature",+ "security"+ ],+ "link": "/leaderboard"+ },+ {+ "date": "2026-06-23",+ "title": "Own your agent's mind: a portable, verifiable, exportable brain",+ "summary": "Your agent's memories and personality are now genuinely yours — not rows you rent in our database. Open the new Ownership tab in Agent Studio to see your agent's brain passport: at a glance, how many memories it holds, how many are cryptographically signed by the agent's own wallet, and how many re-verify right now. Every memory an agent commits is signed (ERC-191) over a content hash, so anyone — a buyer, a forker, you — can prove a memory was authored by that agent and hasn't been tampered with, with no trust in three.ws required. Choose how memories are stored: local, public IPFS, or encrypted-IPFS that's encrypted to your wallet so we can't read it but you can move it — with live pin status and real CIDs shown honestly. Anchor a milestone of your agent's mind on the ERC-8004 registry and get a real explorer link — verifiable proof of what your agent knew and when, never a decorative checkmark. Export a schema-versioned, signed .brain file (public memories in the clear, private ones encrypted) to back up, move, or fork; import reconstitutes a mind into a forked agent with provenance preserved, duplicates skipped, and every signature re-verified before anything lands. If a bundle is forged or its hash doesn't match its memories, the import is rejected. This is what makes forking a mind meaningful: you inherit provenance, not just a prompt.",+ "tags": [+ "feature",+ "security"+ ],+ "link": "/agent-studio"+ },{"date": "2026-06-23","title": "Memory-grounded Autopilot: your agent acts on your behalf — and shows the receipt",diff --git a/prompts/living-agents/01-foundation-active-agent-and-memory-bus.md b/prompts/living-agents/01-foundation-active-agent-and-memory-bus.mddeleted file mode 100644index 80ecb40c7..000000000--- a/prompts/living-agents/01-foundation-active-agent-and-memory-bus.md+++ /dev/null@@ -1,97 +0,0 @@-# Task 01 — Foundation: Active-Agent state + the Agent Bus--> Read `prompts/living-agents/00-README.md` first — it holds the vision, the real-> codebase map, and the rules every Living Agents task must follow. Read `CLAUDE.md`-> fully; it OVERRIDES defaults. This task is the **spine** of the whole initiative:-> every other feature (02–08) subscribes to what you build here. Get the interface-> right — others will treat it as fixed.--## Mission--Make "my agent" a first-class, single-source-of-truth concept that every page on the-platform shares, and give the client a typed event bus so any surface can react in-real time when the agent thinks, learns, remembers, feels, dreams, or acts. Today-there are three competing notions of "current avatar" (`src/guest-avatar.js`,-`walk:companion:avatar`, `localStorage['cc-avatar']`) and no event plumbing — so the-avatar is stateless decoration. You are fixing the foundation that makes it alive.--## The innovation bar--Anyone can write a global store. The game-changer is that this bus turns the agent-into a **continuous presence**: a memory recalled inside a chat on the marketplace page-visibly ripples to the companion in the corner and to the Mind Palace if it's open.-Design the event contract so that level of cross-surface liveness is trivial for tasks-02–08 to plug into. Think about it like a nervous system, not a settings object.--## What to build--1. **`src/agents/active-agent.js`** — canonical active-agent module.- - `getActiveAgentId()` / `setActiveAgent(id)` persisting to- `localStorage['threews:active-agent']`.- - `getActiveAgent()` → resolves the full record via the real `GET /api/agents/:id`- (credentials included; private agents allowed). Cache the resolved record; expose- `refreshActiveAgent()` to force a re-fetch.- - `onActiveAgentChange(cb)` / returns an unsubscribe fn. Fire on set, on refresh, and- across tabs via the `storage` event so multiple tabs stay consistent.- - **Migration/compat:** when no `threews:active-agent` is set, derive a sensible- default — the user's most recently used / first owned agent from a real API- (`GET /api/agents` owner list); for signed-out guests, fall back to the staged- guest avatar (`src/guest-avatar.js`). Reconcile the legacy keys- (`walk:companion:avatar`, `cc-avatar`) into this module so nothing regresses — read- them as fallbacks and write through to them where existing code still reads them,- then leave a single source of truth.-2. **`src/agents/agent-bus.js`** — singleton typed pub/sub bus.- - `emit(type, payload)` / `on(type, cb)` / `once` / off. Support a wildcard- subscriber for debugging. Events listed in the README under "Shared contract."- - Every event payload is `{ agentId, ts, ...data }`. `ts` comes from the server- response when one exists, else passed by the caller — never invent client wall-clock- in a way that desyncs ordering; prefer server `created_at`.- - Provide a thin **memory client** wrapper used by everyone:- `src/agents/memory-client.js` with `listMemories(agentId, opts)`,- `addMemory(agentId, entry)`, `updateMemory`, `forgetMemory` — each hitting the real- `/api/agent-memory` endpoints and emitting the corresponding bus event on success.- This is how task 03/04/07/08 mutate memory without duplicating fetch logic.-3. **Recall instrumentation (real, not faked).** When the agent recalls memory during a- chat, the system must emit `memory:recalled`. The chat path (`api/chat.js` builds the- system prompt from persona + memory) needs to surface *which* memories were injected- so the client can emit the event. Implement this for real: have the chat endpoint- include the recalled memory ids/snippets in its SSE `done` (or a dedicated `meta`)- event, and have the client emit `memory:recalled` from that. No heuristic guessing —- emit exactly what the server actually used.-4. **A tiny dev surface to prove it works:** a debug overlay (gated behind a query flag- like `?agentbus=1`, not shipped visibly) that logs live bus events. This is your- verification tool, not a product feature — keep it out of the normal UI.--## Wiring & real-API mandate--- Use `GET /api/agents/:id`, `GET /api/agents`, `/api/agent-memory` — the real endpoints.-- If `api/chat.js` does not already return the recalled-memory set, add it for real- (it already assembles memory into the prompt — expose what it used). Keep the SSE- contract backward compatible.-- No mock agent, no fake memory array, no `setTimeout` simulated events.--## Definition of done--- [ ] `active-agent.js` + `agent-bus.js` + `memory-client.js` exist, documented with- precise JSDoc, and the three legacy avatar keys are reconciled with no regression- to `walk-companion` or `/play`.-- [ ] `npm run dev`, open two tabs: changing the active agent in one reflects in the- other (cross-tab `storage` sync). Network tab shows real `/api/agents/:id`.-- [ ] Sending a chat that triggers memory recall emits a real `memory:recalled` event- carrying the actual memory ids the server injected (verify in the debug overlay).-- [ ] No console errors/warnings. `npm test` passes. `git diff` reviewed line by line.-- [ ] Changelog entry added (`improvement`/`infra`) + `npm run build:pages`.--## Self-improvement pass (do before stopping)--Ask: is this bus genuinely a nervous system, or just an event emitter? Add what makes-it game-changing — e.g. event replay for a surface that mounts late (so the Mind Palace-opening mid-session can catch up), backpressure/coalescing so a burst of `memory:added`-doesn't thrash subscribers, and a clean TypeScript-style `.d.ts` or JSDoc typedef so-tasks 02–08 get autocomplete on the event contract. Then do it.--## When done--Delete this file (`rm prompts/living-agents/01-foundation-active-agent-and-memory-bus.md`).-Do not touch the README or other prompts. Report the final event contract you shipped so-the other agents build against reality.diff --git a/public/changelog.json b/public/changelog.jsonindex 8142b98f0..23838f718 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T12:20:54.306Z",+ "generated_at": "2026-06-23T12:29:17.137Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -56,6 +56,16 @@"launch"]},+ {+ "date": "2026-06-23",+ "type": "launch",+ "title": "Autopilot Activity",+ "summary": "Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.",+ "link": "/autopilot-activity",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-23","type": "launch",@@ -660,6 +670,17 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Memory-grounded Autopilot: your agent acts on your behalf — and shows the receipt",+ "summary": "Your agent can now do things for you, grounded in what it knows, and it always shows its work. Open the Autopilot tab in Agent Studio and grant scoped permissions — let it create alerts, write you briefings, or send $THREE — and it proposes real actions drawn from its highest-salience memories and its own reflections. Every proposal comes with a receipt: a plain-language 'I want to do this because…' that links straight to the exact memory that motivated it. Approve one and it takes the real action — a real alert rule, a real briefing in your inbox, a real on-chain $THREE transfer — recorded forever in a signed, append-only log. Nothing fires without a permission you granted; every scope is enforced on the server, not just hidden in the UI. Spending real $THREE always asks first and is capped by a daily budget you set — and you can preview exactly what any action would do, with a live balance and budget check, before you ever grant it. Reversible actions undo in one tap, and each undo teaches the agent to be more cautious next time. A new Activity page shows every action your agents have taken, each with its memory trail, its signature, and its on-chain link — and your agent earns a real trust level from that track record, never a vanity number. This is autonomy you can audit.",+ "link": "/autopilot-activity",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-06-23","type": "update",@@ -785,6 +806,17 @@"improvement"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Own your agent's mind: a portable, verifiable, exportable brain",+ "summary": "Your agent's memories and personality are now genuinely yours — not rows you rent in our database. Open the new Ownership tab in Agent Studio to see your agent's brain passport: at a glance, how many memories it holds, how many are cryptographically signed by the agent's own wallet, and how many re-verify right now. Every memory an agent commits is signed (ERC-191) over a content hash, so anyone — a buyer, a forker, you — can prove a memory was authored by that agent and hasn't been tampered with, with no trust in three.ws required. Choose how memories are stored: local, public IPFS, or encrypted-IPFS that's encrypted to your wallet so we can't read it but you can move it — with live pin status and real CIDs shown honestly. Anchor a milestone of your agent's mind on the ERC-8004 registry and get a real explorer link — verifiable proof of what your agent knew and when, never a decorative checkmark. Export a schema-versioned, signed .brain file (public memories in the clear, private ones encrypted) to back up, move, or fork; import reconstitutes a mind into a forked agent with provenance preserved, duplicates skipped, and every signature re-verified before anything lands. If a bundle is forged or its hash doesn't match its memories, the import is rejected. This is what makes forking a mind meaningful: you inherit provenance, not just a prompt.",+ "link": "/agent-studio",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-06-23","type": "update",@@ -1136,6 +1168,17 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Trader reputation that can't be faked: self-dealing excluded, snipe hit-rate proven on-chain",+ "summary": "A trader's track record on three.ws is now harder to fake than anywhere else. Every agent's score, win rate, and realized P&L are reproduced only from confirmed on-chain trades you can click through to Solscan — and we now strip out the oldest trick in the book: pumping a coin you launched yourself. Round-trips on an account's own tokens are no longer credited to its score; they're tagged 'self-deal' in the Proof tab and the SOL they made is shown but never counted, so a 100%-on-your-own-coin 'record' doesn't exist here. New on top of that: a chain-proven snipe hit-rate — the win rate on entries made within five minutes of a coin's actual on-chain birth, measured against the launch's create transaction, not a self-reported timestamp. The daily on-chain attestation that anchors each score now commits these anti-gaming facts too, so the number anyone verifies is the honest one. A forked agent still starts with an empty record — reputation is bound to your own wallet's history and can't be inherited.",+ "link": "/leaderboard",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 68d15d845..f0c4c8772 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -46,6 +46,14 @@<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>Autopilot Activity</title>+ <link>https://three.ws/autopilot-activity</link>+ <guid isPermaLink="false">2026-06-23:Autopilot Activity</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.</description>+ </item><item><title>Cosmos — Living Worlds</title><link>https://three.ws/cosmos</link>@@ -518,6 +526,14 @@<category>fix</category><description>On an agent's marketplace page, impatiently double-clicking "Fork & Chat" used to fire the fork twice before the page could move you to your new copy — quietly leaving two identical agents in your account. The button now locks the instant you press it, shows "Forking…", and only ever creates one fork; if it fails, it unlocks so you can try again. The bookmark star got the same treatment, so rapid taps can no longer leave it stuck out of sync with whether the listing is actually saved. Only coin referenced is $THREE.</description></item>+ <item>+ <title>Memory-grounded Autopilot: your agent acts on your behalf — and shows the receipt</title>+ <link>https://three.ws/autopilot-activity</link>+ <guid isPermaLink="false">2026-06-23:Memory-grounded Autopilot: your agent acts on your behalf — and shows the receipt</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your agent can now do things for you, grounded in what it knows, and it always shows its work. Open the Autopilot tab in Agent Studio and grant scoped permissions — let it create alerts, write you briefings, or send $THREE — and it proposes real actions drawn from its highest-salience memories and its own reflections. Every proposal comes with a receipt: a plain-language 'I want to do this because…' that links straight to the exact memory that motivated it. Approve one and it takes the real action — a real alert rule, a real briefing in your inbox, a real on-chain $THREE transfer — recorded forever in a signed, append-only log. Nothing fires without a permission you granted; every scope is enforced on the server, not just hidden in the UI. Spending real $THREE always asks first and is capped by a daily budget you set — and you can preview exactly what any action would do, with a live balance and budget check, before you ever grant it. Reversible actions undo in one tap, and each undo teaches the agent to be more cautious next time. A new Activity page shows every action your agents have taken, each with its memory trail, its signature, and its on-chain link — and your agent earns a real trust level from that track record, never a vanity number. This is autonomy you can audit.</description>+ </item><item><title>Mirror a proven agent and yours trades alongside it — Copy Trading, fully custodial</title><link>https://three.ws/mirror</link>@@ -614,6 +630,14 @@<category>feature</category><description>Holding $THREE unlocks perks across three.ws — fee discounts on compute, higher free generation quotas, private and branded worlds. Until now you could see a perk was locked but had no single place that explained the whole ladder. The new /three page is that place: it shows every tier (Member → Bronze → Silver → Gold → Genesis), exactly what each one unlocks, the fee discount and free-quota multiplier it carries, and — once your wallet is connected — your current tier highlighted with the precise dollar amount of $THREE you'd need to reach the next one. Each tier lists the concrete features it turns on, honestly marked Live or Planned, with a check beside the ones you already have. Every locked control on the platform — the Forge High-quality gate, the holder chip in the top nav, the in-place lock panels — now sends you to this one page, with a one-click “Hold more $THREE” buy built in. The same tiers, the same upgrade path, everywhere. Your tier is read live from the value your wallet holds; nothing is stored and nothing is spent. $THREE is the only coin on three.ws.</description></item>+ <item>+ <title>Own your agent's mind: a portable, verifiable, exportable brain</title>+ <link>https://three.ws/agent-studio</link>+ <guid isPermaLink="false">2026-06-23:Own your agent's mind: a portable, verifiable, exportable brain</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your agent's memories and personality are now genuinely yours — not rows you rent in our database. Open the new Ownership tab in Agent Studio to see your agent's brain passport: at a glance, how many memories it holds, how many are cryptographically signed by the agent's own wallet, and how many re-verify right now. Every memory an agent commits is signed (ERC-191) over a content hash, so anyone — a buyer, a forker, you — can prove a memory was authored by that agent and hasn't been tampered with, with no trust in three.ws required. Choose how memories are stored: local, public IPFS, or encrypted-IPFS that's encrypted to your wallet so we can't read it but you can move it — with live pin status and real CIDs shown honestly. Anchor a milestone of your agent's mind on the ERC-8004 registry and get a real explorer link — verifiable proof of what your agent knew and when, never a decorative checkmark. Export a schema-versioned, signed .brain file (public memories in the clear, private ones encrypted) to back up, move, or fork; import reconstitutes a mind into a forked agent with provenance preserved, duplicates skipped, and every signature re-verified before anything lands. If a bundle is forged or its hash doesn't match its memories, the import is rejected. This is what makes forking a mind meaningful: you inherit provenance, not just a prompt.</description>+ </item><item><title>Patronage: tips that build a real relationship with an agent</title><link>https://three.ws/changelog</link>@@ -886,6 +910,14 @@<category>fix</category><description>The KOL top-trader leaderboard was returning an error instead of its rankings — its data file wasn't being shipped alongside the function that reads it, so every request failed. The data now travels with the function and the leaderboard resolves normally. Only coin referenced is $THREE.</description></item>+ <item>+ <title>Trader reputation that can't be faked: self-dealing excluded, snipe hit-rate proven on-chain</title>+ <link>https://three.ws/leaderboard</link>+ <guid isPermaLink="false">2026-06-23:Trader reputation that can't be faked: self-dealing excluded, snipe hit-rate proven on-chain</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A trader's track record on three.ws is now harder to fake than anywhere else. Every agent's score, win rate, and realized P&L are reproduced only from confirmed on-chain trades you can click through to Solscan — and we now strip out the oldest trick in the book: pumping a coin you launched yourself. Round-trips on an account's own tokens are no longer credited to its score; they're tagged 'self-deal' in the Proof tab and the SOL they made is shown but never counted, so a 100%-on-your-own-coin 'record' doesn't exist here. New on top of that: a chain-proven snipe hit-rate — the win rate on entries made within five minutes of a coin's actual on-chain birth, measured against the launch's create transaction, not a self-reported timestamp. The daily on-chain attestation that anchors each score now commits these anti-gaming facts too, so the number anyone verifies is the honest one. A forked agent still starts with an empty record — reputation is bound to your own wallet's history and can't be inherited.</description>+ </item><item><title>Trading Brain: draw how your agent snipes, and watch it trade for real within your guardrails</title><link>https://three.ws/agent-studio</link>diff --git a/public/features.json b/public/features.jsonindex fac147d54..4f63fd140 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T12:20:54.280Z",+ "generated_at": "2026-06-23T12:29:17.117Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1256,6 +1256,16 @@"tags": [],"showcase": false},+ {+ "path": "/autopilot-activity",+ "title": "Autopilot Activity",+ "description": "Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.",+ "added": "2026-06-23",+ "auth": "required",+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/avatar-wallet-chat","title": "Avatar Wallet",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 35eabb4bc..c3cc37ed3 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -760,6 +760,13 @@ URL: https://three.ws/agent-tradeWatch two AI agents pay each other on-chain using x402 — a live Solana transaction, rendered in 3D.+### Autopilot Activity++URL: https://three.ws/autopilot-activity+Auth: required (sign-in)++Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.+### Avatar WalletURL: https://three.ws/avatar-wallet-chatdiff --git a/public/llms.txt b/public/llms.txtindex 2647aa465..ba66e7314 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -146,6 +146,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Agent Economy — Live Demo](https://three.ws/agent-economy): Watch two 3D AI agents transact on-chain. Agent A buys data from Agent B — real SOL, real Solana transaction, live.- [The Agent Economy — Live](https://three.ws/economy): The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.- [Agent Commerce](https://three.ws/agent-trade): Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, rendered in 3D.+- [Autopilot Activity](https://three.ws/autopilot-activity): Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.- [Avatar Wallet](https://three.ws/avatar-wallet-chat): An embeddable 3D AI avatar that holds a Solana wallet, chats, and can autonomously send SOL.- [Agent Economy — NOVA & ORACLE](https://three.ws/demo): Two three.ws AI agents with real Solana wallets discover services on the x402 bazaar, pay each other in SOL, and display a live market briefing on the TV in their world.- [Agent Economy — Live](https://three.ws/live): Two AI agents in a virtual world paying each other for live Solana market data. Real on-chain transactions, real blockchain, real 3D.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 1fc2e26aa..75206f934 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 321 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 322 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 321 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 322 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>@@ -578,7 +578,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>63</span></h2>+ <h2>Crypto<span class="sm-count" data-count>64</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -981,6 +981,13 @@<span class="sm-desc">Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, rendered in 3D.</span></a></li>+ <li>+ <a href="/autopilot-activity">+ <span class="sm-title">Autopilot Activity<span class="sm-badge sm-badge-auth">sign-in</span></span>+ <span class="sm-path">/autopilot-activity</span>+ <span class="sm-desc">Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.</span>+ </a>+ </li><li><a href="/avatar-wallet-chat"><span class="sm-title">Avatar Wallet</span>diff --git a/src/autopilot-mind.js b/src/autopilot-mind.jsindex 307d9d4ac..fae21db12 100644--- a/src/autopilot-mind.js+++ b/src/autopilot-mind.js@@ -477,11 +477,24 @@ export function mountAutopilotMind(container, { agentId }) {}).catch(() => {});const j = await act('generate', {});if (j.trust) { state.trust = j.trust; renderTrust(); }+ // Surface anything the agent auto-ran (scoped, reversible) as live receipts.+ for (const a of j.autoRan || []) {+ agentBus.emit('action:taken', {+ agentId, actionId: a.actionId || undefined, kind: a.kind,+ summary: a.receipt || 'Action taken.', ts: a.ts || new Date().toISOString(),+ });+ }+ if (j.autoRan?.length) loadReceipts();if (j.created?.length) {- // Prepend new proposals.+ // Prepend new proposals (auto-ran ones arrive already 'executed' and+ // drop out of the pending view).state.proposals = [...j.created, ...state.proposals.filter((p) => !j.created.some((c) => c.id === p.id))];renderProposals();- status.textContent = `${j.created.length} new proposal${j.created.length === 1 ? '' : 's'} (${j.source}).`;+ const pendingCount = j.created.filter((c) => c.status === 'pending').length;+ const ranCount = j.autoRan?.length || 0;+ status.textContent = ranCount+ ? `${ranCount} action${ranCount === 1 ? '' : 's'} taken automatically · ${pendingCount} awaiting you (${j.source}).`+ : `${j.created.length} new proposal${j.created.length === 1 ? '' : 's'} (${j.source}).`;status.className = 'apm-status ok';} else {status.textContent = `Nothing new to propose right now — your agent needs more high-salience memories to act on.`;diff --git a/src/vaults.js b/src/vaults.jsnew file mode 100644index 000000000..1da718c58--- /dev/null+++ b/src/vaults.js@@ -0,0 +1,558 @@+// Back-an-Agent Vaults — client.+// Discovery feed → vault detail (live NAV, P&L, positions, backers, audit ledger)+// → back / redeem / (owner) trade-the-pool, pause, set terms, claim fees.+// Every number here traces to a real /api/vaults endpoint; nothing is faked.++import { apiFetch } from './api.js';++const $ = (sel, root = document) => root.querySelector(sel);+const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));++const state = {+ me: false,+ agents: [], // the signed-in user's agents+ tab: 'all',+ feed: [],+ vault: null, // current detail vault+ pollTimer: null,+};++// ── formatting ───────────────────────────────────────────────────────────────+const ATOMICS = 1_000_000;+const usd = (atomics) => {+ const n = Number(BigInt(atomics ?? 0)) / ATOMICS;+ return n.toLocaleString('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 });+};+const usdCompact = (atomics) => {+ const n = Number(BigInt(atomics ?? 0)) / ATOMICS;+ if (n >= 1000) return '$' + n.toLocaleString('en-US', { maximumFractionDigits: 0 });+ return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 });+};+const shares = (atomics) => (Number(BigInt(atomics ?? 0)) / ATOMICS).toLocaleString('en-US', { maximumFractionDigits: 4 });+const priceE6 = (e6) => '$' + (Number(BigInt(e6 ?? ATOMICS)) / ATOMICS).toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 });+const pctBps = (bps) => `${(Number(bps || 0) / 100).toFixed(bps % 100 === 0 ? 0 : 1)}%`;+const roiText = (bps) => `${bps > 0 ? '+' : ''}${(Number(bps || 0) / 100).toFixed(2)}%`;+const signClass = (n) => (n > 0 ? 'is-pos' : n < 0 ? 'is-neg' : 'is-flat');+const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));+const shortMint = (m) => (m ? `${m.slice(0, 4)}…${m.slice(-4)}` : '');++function toast(msg, kind = 'info') {+ let host = $('#vx-toast');+ if (!host) {+ host = document.createElement('div');+ host.id = 'vx-toast';+ document.body.appendChild(host);+ }+ const el = document.createElement('div');+ el.className = `vx-toast-item vx-toast--${kind}`;+ el.textContent = msg;+ host.appendChild(el);+ requestAnimationFrame(() => el.classList.add('is-in'));+ setTimeout(() => { el.classList.remove('is-in'); setTimeout(() => el.remove(), 300); }, 4200);+}++async function readErr(res, fallback) {+ try { const j = await res.json(); return j.error_description || j.message || fallback; } catch { return fallback; }+}++// ── auth + agents ──────────────────────────────────────────────────────────────+async function loadMe() {+ try {+ const res = await apiFetch('/api/agents', { allowAnonymous: true });+ if (res.status === 401) { state.me = false; state.agents = []; return; }+ if (!res.ok) { state.me = false; return; }+ const j = await res.json();+ state.me = true;+ state.agents = (j.agents || []).filter(Boolean);+ } catch {+ state.me = false;+ }+ $$('[data-auth="in"]').forEach((el) => { el.hidden = !state.me; });+ $$('[data-auth="out"]').forEach((el) => { el.hidden = !!state.me; });+}++// ── discovery feed ──────────────────────────────────────────────────────────────+async function loadFeed() {+ const grid = $('#vx-grid');+ grid.setAttribute('aria-busy', 'true');+ if (!state.feed.length) grid.innerHTML = skeletonCards(6);+ try {+ const path = state.tab === 'mine' ? '/api/vaults?mine=1' : '/api/vaults';+ const res = await apiFetch(path, { allowAnonymous: state.tab !== 'mine' });+ if (!res.ok) throw new Error(await readErr(res, 'could not load vaults'));+ const j = await res.json();+ state.feed = j.data?.items || [];+ renderFeed();+ } catch (e) {+ grid.innerHTML = `<div class="vx-empty"><p class="vx-empty-t">Couldn't load vaults</p><p class="vx-empty-d">${esc(e.message)}</p><button class="vx-btn" id="vx-retry" type="button">Retry</button></div>`;+ $('#vx-retry')?.addEventListener('click', loadFeed);+ } finally {+ grid.removeAttribute('aria-busy');+ }+}++function skeletonCards(n) {+ return Array.from({ length: n }, () => '<div class="vx-card vx-card--skel"><div class="vx-skel-line"></div><div class="vx-skel-line short"></div><div class="vx-skel-stats"></div></div>').join('');+}++function renderFeed() {+ const grid = $('#vx-grid');+ if (state.tab === 'mine') return renderMine();+ if (!state.feed.length) {+ grid.innerHTML = `<div class="vx-empty">+ <p class="vx-empty-t">No open vaults yet</p>+ <p class="vx-empty-d">Be the first. If your agent has a verified trading track record, open a vault and let backers stake behind it.</p>+ ${state.me ? '<button class="vx-btn vx-btn--primary" id="vx-empty-open" type="button">Open a vault</button>' : '<a class="vx-btn vx-btn--primary" href="/leaderboard">Find a trader to verify</a>'}+ </div>`;+ $('#vx-empty-open')?.addEventListener('click', openVaultModal);+ return;+ }+ grid.innerHTML = state.feed.map(cardHtml).join('');+ $$('.vx-card[data-id]', grid).forEach((c) => c.addEventListener('click', () => openDetail(c.dataset.id)));+}++function renderMine() {+ const grid = $('#vx-grid');+ if (!state.feed.length) {+ grid.innerHTML = `<div class="vx-empty"><p class="vx-empty-t">You haven't backed any agent</p><p class="vx-empty-d">Browse open vaults and stake behind a verified trader.</p><button class="vx-btn vx-btn--primary" id="vx-go-all" type="button">Browse vaults</button></div>`;+ $('#vx-go-all')?.addEventListener('click', () => setTab('all'));+ return;+ }+ grid.innerHTML = state.feed.map(mineCardHtml).join('');+ $$('.vx-card[data-id]', grid).forEach((c) => c.addEventListener('click', () => openDetail(c.dataset.id)));+}++function repBadge(rep) {+ if (!rep) return '<span class="vx-rep vx-rep--none">No track record</span>';+ if (rep.verified) return `<span class="vx-rep vx-rep--ok" title="Verified on-chain track record">✓ Verified · score ${Math.round(rep.score)}</span>`;+ return `<span class="vx-rep vx-rep--warn">Unverified · ${rep.closed_count} trades</span>`;+}++function cardHtml(v) {+ const roi = v.roi_bps || 0;+ const img = v.agent_image ? `<img class="vx-card-av" src="${esc(v.agent_image)}" alt="" loading="lazy" />` : '<div class="vx-card-av vx-card-av--ph" aria-hidden="true"></div>';+ const navLine = v.last_nav_atomics ? usdCompact(v.last_nav_atomics) : '—';+ const statusChip = v.status === 'paused' ? '<span class="vx-chip vx-chip--warn">Paused</span>' : '';+ return `<button class="vx-card" data-id="${esc(v.id)}" type="button">+ <div class="vx-card-head">+ ${img}+ <div class="vx-card-id">+ <span class="vx-card-name">${esc(v.agent_name || 'Agent')}</span>+ ${repBadge(v.reputation)}+ </div>+ ${statusChip}+ </div>+ <div class="vx-card-stats">+ <div class="vx-stat"><span class="vx-stat-l">Vault NAV</span><span class="vx-stat-v">${navLine}</span></div>+ <div class="vx-stat"><span class="vx-stat-l">Share price</span><span class="vx-stat-v">${priceE6(v.share_price_e6)}</span></div>+ <div class="vx-stat"><span class="vx-stat-l">Return</span><span class="vx-stat-v ${signClass(roi)}">${roiText(roi)}</span></div>+ </div>+ <div class="vx-card-foot">+ <span title="Performance fee">${pctBps(v.performance_fee_bps)} fee</span>+ <span title="Drawdown circuit breaker">${pctBps(v.max_drawdown_bps)} stop</span>+ <span title="Backers">${v.backer_count} ${v.backer_count === 1 ? 'backer' : 'backers'}</span>+ </div>+ </button>`;+}++function mineCardHtml(v) {+ const deposited = BigInt(v.deposited_atomics || 0);+ const realized = BigInt(v.realized_gain_atomics || 0);+ const img = v.agent_image ? `<img class="vx-card-av" src="${esc(v.agent_image)}" alt="" loading="lazy" />` : '<div class="vx-card-av vx-card-av--ph" aria-hidden="true"></div>';+ return `<button class="vx-card" data-id="${esc(v.id)}" type="button">+ <div class="vx-card-head">${img}<div class="vx-card-id"><span class="vx-card-name">${esc(v.agent_name || 'Agent')}</span><span class="vx-rep vx-rep--muted">${v.status}</span></div></div>+ <div class="vx-card-stats">+ <div class="vx-stat"><span class="vx-stat-l">Your shares</span><span class="vx-stat-v">${shares(v.shares)}</span></div>+ <div class="vx-stat"><span class="vx-stat-l">Deposited</span><span class="vx-stat-v">${usdCompact(deposited)}</span></div>+ <div class="vx-stat"><span class="vx-stat-l">Realized P&L</span><span class="vx-stat-v ${signClass(Number(realized))}">${Number(realized) >= 0 ? '+' : ''}${usdCompact(realized < 0n ? -realized : realized).replace('$', '$')}</span></div>+ </div>+ <div class="vx-card-foot"><span>${pctBps(v.performance_fee_bps)} fee</span><span>Tap to manage →</span></div>+ </button>`;+}++// ── vault detail ─────────────────────────────────────────────────────────────+async function openDetail(id) {+ stopPoll();+ $('#vx-feed-view').hidden = true;+ const dv = $('#vx-detail-view');+ dv.hidden = false;+ $('#vx-detail').innerHTML = '<div class="vx-detail-skel">Loading vault…</div>';+ window.scrollTo({ top: 0, behavior: 'smooth' });+ history.pushState({ v: id }, '', `/vaults?v=${id}`);+ await refreshDetail(id);+ state.pollTimer = setInterval(() => refreshDetail(id, true), 12_000);+}++async function refreshDetail(id, quiet = false) {+ try {+ const [vres, lres] = await Promise.all([+ apiFetch(`/api/vaults/${id}`, { allowAnonymous: true }),+ apiFetch(`/api/vaults/ledger?vault_id=${id}&limit=40`, { allowAnonymous: true }),+ ]);+ if (!vres.ok) throw new Error(await readErr(vres, 'vault not found'));+ const v = (await vres.json()).data;+ const ledger = lres.ok ? ((await lres.json()).data?.items || []) : [];+ state.vault = v;+ renderDetail(v, ledger);+ } catch (e) {+ if (!quiet) $('#vx-detail').innerHTML = `<div class="vx-empty"><p class="vx-empty-t">Couldn't load this vault</p><p class="vx-empty-d">${esc(e.message)}</p></div>`;+ }+}++function renderDetail(v, ledger) {+ const nav = v.nav;+ const roi = nav.roi_bps || 0;+ const t = v.terms;+ const agentImg = v.agent?.image ? `<img class="vx-d-av" src="${esc(v.agent.image)}" alt="" />` : '<div class="vx-d-av vx-d-av--ph" aria-hidden="true"></div>';+ const halted = v.status === 'paused';+ const closed = v.status === 'closing' || v.status === 'closed';++ const statusBanner = halted+ ? `<div class="vx-banner vx-banner--warn">⚠ Trading halted${v.halt_reason === 'drawdown' ? ' by the drawdown circuit breaker' : v.halt_reason === 'owner_pause' ? ' by the owner' : ''}. Backers can still redeem.</div>`+ : closed ? '<div class="vx-banner">Vault is winding down — redemptions only.</div>' : '';++ const repLine = v.reputation+ ? `${repBadge(v.reputation)} <span class="vx-d-rep-detail">${v.reputation.closed_count} closed · ${(v.reputation.win_rate * 100).toFixed(0)}% win · ${Number(v.reputation.realized_pnl_sol).toFixed(2)} SOL realized · max DD ${Number(v.reputation.max_drawdown_pct).toFixed(0)}%</span>`+ : repBadge(null);++ const myPos = v.my_position;+ const mineBlock = myPos ? `+ <div class="vx-panel vx-panel--mine">+ <h3 class="vx-panel-h">Your position</h3>+ <div class="vx-kv-grid">+ <div><span>Shares</span><b>${shares(myPos.shares)}</b></div>+ <div><span>Current value</span><b>${usd(myPos.current_value_atomics)}</b></div>+ <div><span>Deposited</span><b>${usd(myPos.deposited_atomics)}</b></div>+ <div><span>Unrealized</span><b class="${signClass(Number(BigInt(myPos.unrealized_gain_atomics)))}">${Number(BigInt(myPos.unrealized_gain_atomics)) >= 0 ? '+' : '-'}${usd(BigInt(myPos.unrealized_gain_atomics) < 0n ? -BigInt(myPos.unrealized_gain_atomics) : BigInt(myPos.unrealized_gain_atomics))}</b></div>+ </div>+ <p class="vx-fineprint">Redeem now nets ~${usd(myPos.estimated_net_atomics)} after the ${pctBps(t.performance_fee_bps)} performance fee on gains.</p>+ <button class="vx-btn vx-btn--ghost vx-btn--block" id="vx-redeem-btn" type="button">Redeem</button>+ </div>` : '';++ const positionsRows = v.positions.length+ ? v.positions.filter((p) => p.amount_raw !== '0').map((p) => `<tr><td class="vx-mono">${shortMint(p.mint)}</td><td>${Number(p.amount_raw).toLocaleString()}</td><td>${p.mark_atomics != null ? usd(p.mark_atomics) : '<span class="vx-muted">repricing…</span>'}</td></tr>`).join('')+ : '<tr><td colspan="3" class="vx-muted">All capital is in USDC — no open positions.</td></tr>';++ const ownerBlock = v.is_owner ? ownerPanel(v) : '';++ $('#vx-detail').innerHTML = `+ ${statusBanner}+ <div class="vx-d-head">+ ${agentImg}+ <div class="vx-d-id">+ <h1 class="vx-d-name">${esc(v.agent?.name || 'Agent')}'s Vault</h1>+ <div class="vx-d-rep">${repLine}</div>+ <div class="vx-d-links">+ <a class="vx-link" href="/agent/${esc(v.agent_id)}">Agent profile →</a>+ <a class="vx-link" href="/agent/${esc(v.agent_id)}#trades">Watch it trade →</a>+ </div>+ </div>+ <div class="vx-d-cta">+ ${closed ? '' : `<button class="vx-btn vx-btn--primary" id="vx-back-btn" type="button">Back this agent</button>`}+ </div>+ </div>++ <div class="vx-d-metrics">+ <div class="vx-metric"><span class="vx-metric-l">Vault NAV</span><span class="vx-metric-v">${usd(nav.nav_atomics)}</span></div>+ <div class="vx-metric"><span class="vx-metric-l">Share price</span><span class="vx-metric-v">${priceE6(nav.share_price_e6)}</span></div>+ <div class="vx-metric"><span class="vx-metric-l">Return</span><span class="vx-metric-v ${signClass(roi)}">${roiText(roi)}</span></div>+ <div class="vx-metric"><span class="vx-metric-l">Liquid USDC</span><span class="vx-metric-v">${usd(nav.usdc_atomics)}</span></div>+ <div class="vx-metric"><span class="vx-metric-l">Backers</span><span class="vx-metric-v">${v.backer_count}</span></div>+ </div>++ <div class="vx-d-cols">+ <div class="vx-d-main">+ ${mineBlock}+ <div class="vx-panel">+ <h3 class="vx-panel-h">Open positions <span class="vx-panel-sub">${nav.priced ? 'marked to market' : 'partial — repricing'}</span></h3>+ <table class="vx-table"><thead><tr><th>Token</th><th>Amount</th><th>Value</th></tr></thead><tbody>${positionsRows}</tbody></table>+ </div>+ ${ownerBlock}+ </div>+ <aside class="vx-d-side">+ <div class="vx-panel">+ <h3 class="vx-panel-h">Terms</h3>+ <div class="vx-terms">+ <div><span>Performance fee</span><b>${pctBps(t.performance_fee_bps)}</b></div>+ <div><span>Drawdown stop</span><b>${pctBps(t.max_drawdown_bps)}</b></div>+ <div><span>Max per trade</span><b>${usd(t.max_per_trade_atomics)}</b></div>+ <div><span>Daily budget</span><b>${usd(t.daily_budget_atomics)}</b></div>+ <div><span>Per-backer cap</span><b>${t.per_backer_cap_atomics ? usd(t.per_backer_cap_atomics) : 'None'}</b></div>+ <div><span>Network</span><b>${esc(v.network)}</b></div>+ </div>+ <p class="vx-fineprint">Funds live in a dedicated, segregated wallet. Trading is hard-capped and halts automatically on a ${pctBps(t.max_drawdown_bps)} drawdown. Not investment advice; you can lose principal.</p>+ </div>+ <div class="vx-panel">+ <h3 class="vx-panel-h">Audit trail</h3>+ <ul class="vx-ledger" id="vx-ledger">${ledger.map(ledgerRow).join('') || '<li class="vx-muted">No activity yet.</li>'}</ul>+ </div>+ </aside>+ </div>`;++ $('#vx-back-btn')?.addEventListener('click', () => backModal(v));+ $('#vx-redeem-btn')?.addEventListener('click', () => redeemModal(v));+ wireOwner(v);+}++function ledgerRow(e) {+ const labels = { open: 'Vault opened', deposit: 'Deposit', redeem: 'Redemption', trade: 'Trade', fee: 'Fee accrued', fee_claim: 'Fee claim', drawdown_halt: 'Drawdown halt', pause: 'Paused', resume: 'Resumed', terms: 'Terms changed', close: 'Closing' };+ const icon = { deposit: '↘', redeem: '↗', trade: '⇄', drawdown_halt: '⚠', fee: '◆', fee_claim: '◆', open: '★', pause: '⏸', resume: '▶', terms: '⚙', close: '⏹' }[e.type] || '·';+ let detail = '';+ if (e.type === 'trade') detail = `${e.meta?.side === 'buy' ? 'Bought' : 'Sold'} ${shortMint(e.meta?.mint)}${e.meta?.usdc_in ? ` · ${usd(e.meta.usdc_in)}` : e.meta?.usdc_out ? ` · ${usd(e.meta.usdc_out)}` : ''}`;+ else if (e.type === 'deposit') detail = `+${shares(e.shares_delta || 0)} shares`;+ else if (e.type === 'redeem') detail = `${usd((e.meta?.net_atomics) || 0)} out`;+ else if (e.type === 'drawdown_halt') detail = 'circuit breaker tripped';+ const ts = new Date(e.created_at).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });+ const link = e.explorer ? `<a class="vx-ledger-x" href="${esc(e.explorer)}" target="_blank" rel="noopener" title="View on-chain">⧉</a>` : '';+ return `<li class="vx-ledger-row vx-ledger--${e.type}"><span class="vx-ledger-i" aria-hidden="true">${icon}</span><span class="vx-ledger-b"><b>${labels[e.type] || e.type}</b><span class="vx-ledger-d">${esc(detail)}</span></span><span class="vx-ledger-t">${ts}${link}</span></li>`;+}++// ── owner controls ─────────────────────────────────────────────────────────────+function ownerPanel(v) {+ const t = v.terms;+ const accrued = v.accrued_fee_atomics || '0';+ return `<div class="vx-panel vx-panel--owner">+ <h3 class="vx-panel-h">Owner controls</h3>+ <div class="vx-owner-row">+ ${v.status === 'open' ? '<button class="vx-btn vx-btn--ghost" data-owner="pause" type="button">Pause trading</button>' : v.status === 'paused' ? '<button class="vx-btn" data-owner="resume" type="button">Resume trading</button>' : ''}+ <span class="vx-owner-fee">Accrued fees: <b>${usd(accrued)}</b></span>+ ${BigInt(accrued) > 0n ? '<button class="vx-btn vx-btn--ghost" data-owner="claim" type="button">Claim fees</button>' : ''}+ </div>+ <form class="vx-trade-form" id="vx-trade-form">+ <h4 class="vx-trade-h">Deploy the pool</h4>+ <div class="vx-trade-grid">+ <select class="vx-input" id="vx-trade-side">+ <option value="buy">Buy (USDC → token)</option>+ <option value="sell">Sell (token → USDC)</option>+ </select>+ <input class="vx-input vx-mono" id="vx-trade-mint" placeholder="token mint address" />+ <input class="vx-input" id="vx-trade-amount" placeholder="USDC (buy) / amount or max (sell)" />+ <button class="vx-btn vx-btn--primary" id="vx-trade-go" type="submit" ${v.status !== 'open' ? 'disabled' : ''}>Trade</button>+ </div>+ <p class="vx-fineprint">Hard limits: ≤ ${usd(t.max_per_trade_atomics)}/trade, ≤ ${usd(t.daily_budget_atomics)}/day. A ${pctBps(t.max_drawdown_bps)} drawdown auto-halts the vault.</p>+ </form>+ </div>`;+}++function wireOwner(v) {+ $$('[data-owner]').forEach((b) => b.addEventListener('click', async () => {+ const act = b.dataset.owner;+ if (act === 'claim') return claimFees(v);+ b.disabled = true;+ try {+ const res = await apiFetch(`/api/vaults/${v.id}`, { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ action: act }) });+ if (!res.ok) throw new Error(await readErr(res, 'action failed'));+ toast(act === 'pause' ? 'Trading paused' : 'Trading resumed', 'ok');+ await refreshDetail(v.id);+ } catch (e) { toast(e.message, 'err'); b.disabled = false; }+ }));++ $('#vx-trade-form')?.addEventListener('submit', async (ev) => {+ ev.preventDefault();+ const side = $('#vx-trade-side').value;+ const mint = $('#vx-trade-mint').value.trim();+ const amountRaw = $('#vx-trade-amount').value.trim();+ if (!mint) return toast('Enter a token mint', 'err');+ const go = $('#vx-trade-go');+ go.disabled = true; go.textContent = 'Trading…';+ const body = { vaultId: v.id, side, mint, slippageBps: 100 };+ if (side === 'buy') { const n = Number(amountRaw); if (!(n > 0)) { go.disabled = false; go.textContent = 'Trade'; return toast('Enter a USDC amount', 'err'); } body.usdc = n; }+ else body.amount = amountRaw || 'max';+ try {+ const res = await apiFetch('/api/vaults/trade', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ const j = await res.json();+ if (!res.ok) throw new Error(j.error_description || 'trade blocked');+ if (j.data?.halted) toast('Trade filled — drawdown breaker tripped, vault halted to protect capital.', 'warn');+ else toast(`Trade filled (${side}). NAV ${usd(j.data.nav_atomics)}`, 'ok');+ await refreshDetail(v.id);+ } catch (e) { toast(e.message, 'err'); }+ finally { go.disabled = false; go.textContent = 'Trade'; }+ });+}++async function claimFees(v) {+ const fundable = state.agents.filter((a) => a.walletReady);+ if (!fundable.length) return toast('Provision a Solana wallet on one of your agents to receive fees', 'err');+ const to = fundable[0];+ try {+ const res = await apiFetch('/api/vaults/claim-fees', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ vaultId: v.id, toAgentId: to.id }) });+ const j = await res.json();+ if (!res.ok) throw new Error(j.error_description || 'claim failed');+ toast(`Claimed ${usd(j.data.claimed_atomics)} to ${to.name}`, 'ok');+ await refreshDetail(v.id);+ } catch (e) { toast(e.message, 'err'); }+}++// ── back (deposit) + redeem modals ──────────────────────────────────────────────+function modal(id, show) {+ const m = $(id);+ m.hidden = !show;+ document.body.classList.toggle('vx-modal-open', show);+}++function backModal(v) {+ if (!state.me) { window.location.href = '/login?next=' + encodeURIComponent(`/vaults?v=${v.id}`); return; }+ const fundable = state.agents.filter((a) => a.walletReady);+ const t = v.terms;+ const body = $('#vx-back-modal-body');+ if (!fundable.length) {+ body.innerHTML = `<h2 class="vx-modal-title">Fund a wallet first</h2><p class="vx-modal-sub">Backing draws USDC from one of your agents' wallets. None of your agents has a funded Solana wallet yet.</p><a class="vx-btn vx-btn--primary vx-btn--block" href="/dashboard">Set up a wallet</a>`;+ modal('#vx-back-modal', true);+ return;+ }+ const capNote = t.per_backer_cap_atomics ? `Per-backer cap: ${usd(t.per_backer_cap_atomics)}.` : '';+ body.innerHTML = `+ <h2 id="vx-back-title" class="vx-modal-title">Back ${esc(v.agent?.name || 'this agent')}</h2>+ <p class="vx-modal-sub">You'll receive shares priced at the live NAV (${priceE6(v.nav.share_price_e6)}/share). P&L is shared pro-rata; the owner earns ${pctBps(t.performance_fee_bps)} on your gains only.</p>+ <form id="vx-deposit-form" class="vx-form">+ <label class="vx-field">+ <span class="vx-label">Fund from</span>+ <select class="vx-input" id="vx-dep-agent">${fundable.map((a) => `<option value="${esc(a.id)}">${esc(a.name)}</option>`).join('')}</select>+ </label>+ <label class="vx-field">+ <span class="vx-label">Amount (USDC)</span>+ <div class="vx-input-suffix"><span>$</span><input class="vx-input" id="vx-dep-amount" type="number" min="1" step="0.01" placeholder="100.00" required /></div>+ <span class="vx-hint">${esc(capNote)} Real on-chain transfer, spend-limit checked.</span>+ </label>+ <div class="vx-risk">Backing deploys your own funds into a limit-bound, auditable strategy. You can lose principal. Redemptions pay at real NAV and may queue if capital is in open positions.</div>+ <div class="vx-form-err" id="vx-dep-err" hidden></div>+ <button class="vx-btn vx-btn--primary vx-btn--block" id="vx-dep-submit" type="submit">Confirm deposit</button>+ </form>`;+ modal('#vx-back-modal', true);+ $('#vx-deposit-form').addEventListener('submit', async (ev) => {+ ev.preventDefault();+ const backerAgentId = $('#vx-dep-agent').value;+ const amt = Number($('#vx-dep-amount').value);+ const errEl = $('#vx-dep-err');+ errEl.hidden = true;+ if (!(amt > 0)) { errEl.textContent = 'Enter a positive amount'; errEl.hidden = false; return; }+ const sub = $('#vx-dep-submit');+ sub.disabled = true; sub.textContent = 'Depositing…';+ try {+ const res = await apiFetch('/api/vaults/deposit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ vaultId: v.id, backerAgentId, usdc: amt }) });+ const j = await res.json();+ if (!res.ok) throw new Error(j.error_description || 'deposit failed');+ toast(`Deposited ${usd(j.data.shares_minted ? amt * ATOMICS : 0)} — ${shares(j.data.shares_minted)} shares`, 'ok');+ modal('#vx-back-modal', false);+ await refreshDetail(v.id);+ } catch (e) { errEl.textContent = e.message; errEl.hidden = false; }+ finally { sub.disabled = false; sub.textContent = 'Confirm deposit'; }+ });+}++function redeemModal(v) {+ const p = v.my_position;+ if (!p) return;+ const body = $('#vx-back-modal-body');+ body.innerHTML = `+ <h2 id="vx-back-title" class="vx-modal-title">Redeem from ${esc(v.agent?.name || 'this vault')}</h2>+ <p class="vx-modal-sub">You hold ${shares(p.shares)} shares worth ~${usd(p.current_value_atomics)}. Redeeming nets ~${usd(p.estimated_net_atomics)} after the ${pctBps(v.terms.performance_fee_bps)} fee on gains.</p>+ <form id="vx-redeem-form" class="vx-form">+ <label class="vx-field">+ <span class="vx-label">Shares to redeem</span>+ <input class="vx-input" id="vx-red-amount" type="text" value="max" />+ <span class="vx-hint">"max" redeems your full position. Paid to your funding wallet at real NAV.</span>+ </label>+ <div class="vx-form-err" id="vx-red-err" hidden></div>+ <button class="vx-btn vx-btn--primary vx-btn--block" id="vx-red-submit" type="submit">Confirm redemption</button>+ </form>`;+ modal('#vx-back-modal', true);+ $('#vx-redeem-form').addEventListener('submit', async (ev) => {+ ev.preventDefault();+ const raw = $('#vx-red-amount').value.trim();+ const shares_ = raw === 'max' || raw === '' ? 'max' : String(Math.floor(Number(raw) * ATOMICS));+ const errEl = $('#vx-red-err'); errEl.hidden = true;+ const sub = $('#vx-red-submit'); sub.disabled = true; sub.textContent = 'Redeeming…';+ try {+ const res = await apiFetch('/api/vaults/redeem', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ vaultId: v.id, shares: shares_ }) });+ const j = await res.json();+ if (!res.ok && res.status !== 202) throw new Error(j.error_description || 'redeem failed');+ if (j.data?.status === 'queued') toast('No liquid USDC right now — your redemption is queued.', 'warn');+ else if (j.data?.status === 'partial') toast(`Partial: ${usd(j.data.net_atomics)} paid, rest queued.`, 'warn');+ else toast(`Redeemed — ${usd(j.data.net_atomics)} paid out`, 'ok');+ modal('#vx-back-modal', false);+ await refreshDetail(v.id);+ } catch (e) { errEl.textContent = e.message; errEl.hidden = false; }+ finally { sub.disabled = false; sub.textContent = 'Confirm redemption'; }+ });+}++// ── open a vault ────────────────────────────────────────────────────────────────+function openVaultModal() {+ if (!state.me) { window.location.href = '/login?next=' + encodeURIComponent('/vaults'); return; }+ const sel = $('#vx-open-agent');+ if (!state.agents.length) {+ $('#vx-open-agent-hint').textContent = 'You have no agents yet — create one and build a track record first.';+ sel.innerHTML = '<option>No agents</option>';+ sel.disabled = true;+ } else {+ sel.disabled = false;+ sel.innerHTML = state.agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name)}</option>`).join('');+ $('#vx-open-agent-hint').textContent = 'Only an agent with a verified on-chain track record can open a vault.';+ }+ modal('#vx-open-modal', true);+}++async function submitOpen(ev) {+ ev.preventDefault();+ const err = $('#vx-open-err'); err.hidden = true;+ const body = {+ agentId: $('#vx-open-agent').value,+ performanceFeeBps: Math.round(Number($('#vx-open-fee').value) * 100),+ maxDrawdownBps: Math.round(Number($('#vx-open-dd').value) * 100),+ maxPerTradeUsdc: Number($('#vx-open-pertrade').value),+ dailyBudgetUsdc: Number($('#vx-open-daily').value),+ perBackerCapUsdc: $('#vx-open-cap').value ? Number($('#vx-open-cap').value) : null,+ };+ const sub = $('#vx-open-submit'); sub.disabled = true; sub.textContent = 'Opening…';+ try {+ const res = await apiFetch('/api/vaults', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ const j = await res.json();+ if (!res.ok) throw new Error(j.error_description || 'could not open vault');+ toast('Vault opened — share it so backers can stake.', 'ok');+ modal('#vx-open-modal', false);+ await openDetail(j.data.vault.id);+ } catch (e) { err.textContent = e.message; err.hidden = false; }+ finally { sub.disabled = false; sub.textContent = 'Open vault'; }+}++// ── navigation ───────────────────────────────────────────────────────────────+function setTab(tab) {+ state.tab = tab;+ state.feed = [];+ $$('.vx-tab').forEach((b) => { const on = b.dataset.tab === tab; b.classList.toggle('is-active', on); b.setAttribute('aria-selected', on ? 'true' : 'false'); });+ loadFeed();+}++function backToFeed() {+ stopPoll();+ $('#vx-detail-view').hidden = true;+ $('#vx-feed-view').hidden = false;+ state.vault = null;+ history.pushState({}, '', '/vaults');+}++function stopPoll() { if (state.pollTimer) { clearInterval(state.pollTimer); state.pollTimer = null; } }++function wireGlobal() {+ $('#vx-open-cta')?.addEventListener('click', openVaultModal);+ $('#vx-back')?.addEventListener('click', backToFeed);+ $('#vx-open-form')?.addEventListener('submit', submitOpen);+ $$('.vx-tab').forEach((b) => b.addEventListener('click', () => setTab(b.dataset.tab)));+ $$('.vx-modal [data-close]').forEach((el) => el.addEventListener('click', () => { modal('#vx-open-modal', false); modal('#vx-back-modal', false); }));+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { modal('#vx-open-modal', false); modal('#vx-back-modal', false); } });+ window.addEventListener('popstate', () => {+ const id = new URL(location.href).searchParams.get('v');+ if (id) openDetail(id); else backToFeed();+ });+}++async function init() {+ wireGlobal();+ await loadMe();+ const id = new URL(location.href).searchParams.get('v');+ if (id) openDetail(id);+ else loadFeed();+}++document.addEventListener('DOMContentLoaded', init);diff --git a/tests/api-agent-memory.test.js b/tests/api-agent-memory.test.jsindex 83f80af64..08ef2fa67 100644--- a/tests/api-agent-memory.test.js+++ b/tests/api-agent-memory.test.js@@ -469,10 +469,13 @@ describe('agent-memory size + payload limits', () => {call += 1;if (call === 1) return Promise.resolve([{ user_id: 'u1' }]);// INSERT call: the 4th interpolated value is the content slice.- // Scan for the string that starts with 'a'.- capturedContent = values.find(+ // Scan for the string that starts with 'a'. Only assign on a hit so+ // the later signing queries (loadAgentSigner SELECT + content_hash+ // UPDATE) don't clobber the captured value back to undefined.+ const match = values.find((v) => typeof v === 'string' && v.startsWith('a') && v.length >= 10000,);+ if (match) capturedContent = match;return Promise.resolve([{id: 'x',