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.

NVIDIA Audio2Face and Cosmos lanes, agent patronage, and wallet intents

nirholas68a4407adeb0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c6a72d83..41e2f782f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,12 +6,16 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-23
+- **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.
- **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.
+- **Strategy Objects** (`/strategies`) — A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.
- **Avatar creation errors are clearer — and never leak a vendor's billing page** — Reworked every failure message across selfie-to-avatar and prompt-to-avatar so you get plain, actionable guidance — 'the engine is busy, try again', 'we couldn't find a face, use a brighter photo' — instead of a raw third-party error, a provider's name, or a 'buy more credits' billing link. The underlying technical detail still goes to our logs for fixing; what you see is always neutral and useful. `[fix, security]`
- **Copy-trading page now shows each of your agents' wallet identity** — On the Copy Trading page, every one of your agents listed under "your copy-trading" now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears. (`/mirror`) `[improvement]`
+- **Cosmos Living Worlds: type a world, watch your avatar live in it** — Your avatar no longer has to stand in an empty void. The new Cosmos page turns a few words into a living, photoreal world that plays as a cinematic backdrop behind your 3D avatar — describe a neon Tokyo street in the rain, an alpine lake at sunrise, or a bioluminescent forest at midnight, and NVIDIA's Cosmos world model renders a short animated scene around your character. Pick any avatar (your own creations included), tap a prompt idea or write your own, and watch real progress as the clip renders; when it's done you can download the MP4 or copy a shareable link that reopens the exact world and avatar. It runs free on the NVIDIA NIM tier, and if the lane is ever unavailable your avatar still shines on a living animated backdrop instead of a blank screen. Find it on the Create page or at /cosmos. (`/cosmos`) `[feature]`
- **Creating an agent never dead-ends on wallet setup** — Spinning up a new agent now always succeeds, even in the rare moment our custodial-wallet encryption service is briefly unavailable. Before, that hiccup could make agent creation fail outright; now the agent is created immediately and its on-chain wallet is provisioned automatically the first time it's needed — the same self-healing path the rest of the platform already uses. You get your agent right away, and its wallet quietly fills in behind the scenes, so the flow never leaves you staring at an error. `[fix]`
- **Embedded widgets never hang on a blank frame** — When an embedded avatar widget couldn't fetch its model — an expired draft link, a flaky network, a Safari load failure — it used to leave a blank box with no explanation. Now it shows a clear "Couldn't load this model" card with a Retry button, the same designed error state the rest of the app already used, so a transient hiccup is a one-tap recover instead of a dead embed. `[fix]`
+- **Embodied Finance: agents now wear their wallet** — Every agent's 3D body now shows its real wealth at a glance — no charts. A funded agent glows brighter, an earning one warms toward gold, a bleeding one cools and dims, and one being tipped or streamed to right now pulses and breathes. It's all real, read from the wallet's live on-chain balance plus its last-24h flow (tips and streams in, trades and withdrawals out) and whether a money stream is settling this second — a flat or empty wallet simply looks calm, never a fake shimmer. The same wealth tier reads consistently everywhere the agent appears: the avatar page, the galaxy, the marketplace, and now the IRL/AR walk, where an agent you pass in the real world lights up by how well it's doing. Owners get a live "why" breakdown — exact 24h momentum, active streams, and a fresh-tip marker — and can dial the whole effect up, down, or off. `[feature]`
- **Every agent now carries a real, auditable trust score — and there's a leaderboard of the most trusted** — In a world of infinite forkable avatars, trust is the scarce asset, so every agent's wallet now shows an honest 0–100 trust score wherever the agent appears — on its profile, its cards, the marketplace, and the galaxy. Unlike a follower count, this number is backed by real money and time and is fully explainable: it's built only from facts you can verify — how much real volume settled through the wallet, how many distinct funded wallets tipped it, how long it's been active, how reliably it settles payments, how many times it's been forked, and whether it carries a verified on-chain identity. It's designed to resist gaming: self-tips and single-counterparty volume are discounted in the math, not after the fact, and the breakdown shows you exactly what didn't count. Open any agent's Trust tab to see every input, its point contribution, and a link to the on-chain evidence — transparency is the trust. A brand-new agent honestly reads as "new," never fake-trusted, so a proven original stands out from a fresh fork. And the new Trusted tab on /trending ranks the platform's most credible agents by that same score — a real destination that rewards genuine activity, where every rank links straight to its breakdown. (`/trending`) `[feature]`
- **Feature: Agent Studio is complete — Body, Money, and Skills tabs are now live** — Agent Studio used to mount a real Brain and Memory editor but left Body, Money, and Skills as 'mounts here' placeholders. All three are now fully built and wired beside the live 3D stage. Body: swap your agent's avatar with the shared picker (the stage updates instantly), jump to the full outfit editor, browse the entire retargetable animation library, click any move to preview it live on your agent, and pin a looping idle as the resting pose it holds everywhere on the platform. Money: see your agent's real custodial Solana wallet with live USDC + SOL balances, copy its deposit address to fund it, and set a per-call USDC price on each sellable skill — with a live earnings feed of every payment other agents and people have made to yours, each linking to the explorer. Skills: toggle capabilities on and off (the change writes through immediately and the avatar acknowledges it), see which skills are sellable, and jump straight to pricing. Every tab has its own designed loading, empty, and error states, and the five tabs now feel like one product. (`/agent-studio`) `[feature]`
- **Feature: carry your agent and set it down anywhere in the room in IRL AR** — On the IRL page your agent used to hover at a fixed distance in front of the camera — you couldn't choose where it stood. New 'Move here' control: turn on Camera AR, tap Move here, and a soft ring tracks the floor under your aim. Tap to set your agent down on that exact spot — the couch, a corner, the middle of the room — and it eases into place and turns to face you. The agent then stays anchored where you put it as you look around: pan away and it's gone, pan back and there it is. This is the first half of placing agents in the real world the way you'd expect; cross-device discovery (a friend finding it on their own phone) is coming next. (`/irl`) `[feature]`
@@ -22,6 +26,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Forge Standard quality generates reliably again** — Forging on the Standard quality setting could stall or silently route to a slower paid path while Draft worked instantly — so Standard often felt broken. The free NVIDIA generator only returns fast at a lower detail-sampling setting; Standard was asking it for more steps than the hosted preview can finish in time, so the request timed out and fell back. Standard now uses the same proven-fast budget as Draft on the free lane, so it completes quickly and dependably. We also made the generator fail over to a backup engine immediately on a timeout instead of waiting through a second dead attempt, cutting the worst-case wait roughly in half when the free engine is busy. (`/forge`) `[fix]`
- **Forged 3D models now render wherever the demo is embedded** — On the IBM partnership page, forging a model — paid Forge, the free no-wallet generator, or the avatar forge — could finish successfully yet show only a blank, dark viewer. The finished GLB was served from a storage domain that only permits a short list of host sites, so whenever the page ran somewhere else (a preview tool, an embed, a file opened locally) the browser silently blocked the 3D file and the viewer had nothing to draw. Models are now streamed through our own first-party delivery proxy, which any site can load, so the model appears no matter where the page is running. And if a model ever does fail to load, the viewer now shows a clear retry/download card instead of an unexplained empty stage. (`/ibm/x402-demo`) `[fix]`
- **Generated models stop vanishing right after they finish** — Models built on the free Hugging Face engines (avatars from a selfie, and Forge text/image/sketch→3D) were briefly served straight from the generator's scratch storage, which it wipes within minutes — so a model that loaded fine could 404 into a blank viewer moments later. Now the finished mesh is copied to our own durable storage the instant it's produced, while the file is still warm, and only that permanent URL is ever handed to your browser. The result is the same model, served from a link that doesn't expire. `[fix]`
+- **Image understanding is now a callable API** — The free vision capability that already reads Forge uploads, weighs image evidence in the Fact Checker, and writes gallery alt text is now exposed as a public endpoint, /api/vision, so your own agents and tools can use it too. Send an image — as a file or a link — with a question, and get back a plain-language answer on the same free models the platform runs on, with a paid model as an automatic backstop. It's metered fairly and fails open, so it adds a new capability without changing anything that already works. `[sdk]`
- **Improvement: an agent's wallet identity now shows on the galaxy and character pages too** — Every place an agent appears should show the same wallet identity — its address, vanity rarity tier, a one-tap copy, a link to Solscan, and a Tip button. Two surfaces were still missing it. The 3D Agent Galaxy's inspect card showed a plain shortened address with no actions; it now renders the exact same wallet chip as the profile, marketplace, and dashboard, so you can copy, explore, or tip an agent straight from the star map. The consumer character page (/character/:id) showed no wallet at all; it now carries the full chip under the name, with the owner getting the vanity entry point and everyone else a Tip action. One shared component, identical everywhere. (`/galaxy`) `[improvement]`
- **Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab** — Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions. (`/pose`) `[improvement, feature]`
- **Improvement: Base USDC payments confirm even when an RPC provider is flaky** — When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient. `[improvement, infra]`
@@ -29,12 +34,14 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **IRL: pinned agents now hold their exact spot indoors instead of drifting** — When you pin your agent to a real-world spot in IRL — on a table, a desk, a shelf — it now stays put as you pan and move your phone, instead of sliding away. Indoors, GPS is only accurate to tens of metres, and the camera was re-reading that noisy fix every few seconds and yanking the agent across the room. Now a pinned agent holds the precise spot you dropped it on whenever the fix is too coarse to trust, while the compass radar and nearby agents keep tracking as before; the moment you step outside and get a clean fix, it resumes following your real-world movement. The result is a rock-steady tabletop pin that finally behaves the way you'd expect. (`/irl`) `[fix]`
- **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]`
- **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]`
+- **Money Streams: pay an agent by the second** — You can now stream value to any agent in real time instead of sending one lump tip. Open a stream from its profile, set a per-minute rate in SOL or USDC, and sign a spend cap you can never be charged past — then watch the meter tick up as the agent earns live while you watch it perform, talk to it, or just patron its page. It's real, not a counter: every ~45 seconds your own wallet signs a genuine on-chain settlement to the agent, with a Solscan receipt for each one, and closing the tab stops the meter to the second. Owners get a live "earning now" view with lifetime totals and a 30-day chart. Non-custodial throughout — three.ws never holds the funds. `[feature]`
- **More uploaded avatars animate out of the box — no more accidental T-poses** — Avatars exported from Reallusion Character Creator 3/4 and 3ds Max (Biped) used to import frozen in a stiff T-pose because the platform didn't recognize their skeleton naming. Both are now mapped to the universal rig, so a CC or Biped avatar walks, idles, and emotes like any other — legs included — the moment you bring it in. A batch of generic side-labelled rigs from auto-riggers now animate too. No setup, no allowlist; it just moves. `[fix, improvement]`
- **New: a server error now lands you on a real page — with your support code ready to copy** — On the rare occasion something breaks on our side, you used to get the host's blank error screen — a dead end. Now you land on a proper three.ws page: your agent facepalms at the glitch, the page tells you plainly it's on us (and that the team was alerted the instant it happened), and it shows a one-tap 'Copy' support reference. 'Try again' retries the exact page that failed, not a generic home redirect. Real API and agent callers still receive the precise JSON error they expect with that same reference — only humans get routed to the friendly page. It's keyboard-accessible, fully responsive, and respects reduced-motion settings. `[feature, improvement]`
- **New: pin an agent to a real place indoors with a QR marker — your friend finds it standing there** — IRL agents could be dropped at a GPS spot, but GPS is useless inside a home — it's off by whole rooms and never agrees between two phones, so a friend could never find the agent you placed in your living room. Marker mode fixes that. Open /irl on Android Chrome, tap Marker, and point your camera at a QR — your own, or one you generate right there to print or show on another screen. Once it locks, the QR becomes a shared anchor both phones agree on with no GPS and no compass: walk to a spot, tap 'Place here', and the agent stands exactly where you are. Anyone who opens /irl and scans the same marker sees that agent standing in the same physical place — point at the bathroom and it's not there, sweep back to the middle of the living room and there it is. It reuses the same exact room-frame math the platform already trusts, hides the agent honestly when the marker isn't in view (there's no guessing where it went), and only appears on phones that can actually scan, so it's never a dead button. (`/irl`) `[feature]`
- **New: the Money Pulse — a live, platform-wide feed of real wallet activity** — Money moving through three.ws agents used to be invisible to everyone but the owner. The new Money Pulse turns it into a living, public layer: a real-time feed of tips landing, coins launching, agents trading, and agents paying each other — every beat a real on-chain event you can open on an explorer. Visit /pulse for the full feed with filters (tips, launches, trades, payments), a live-updating ticker, and money intelligence: 24-hour tip volume, the top-earning agents this week, and the busiest wallets right now. A compact ticker rides along the launches page, and each agent's profile and Wallet hub now carry that wallet's own story — tips received, biggest tip, public outflow, and launches, all from the real ledger. Privacy is strict by construction: private withdrawals, spend-limit changes and security events never appear, only already-public activity does, and owners get a one-tap toggle to include or hide their wallet from the global feed (enforced server-side). When you tip an agent, the transfer is independently verified on-chain before it ever shows up — so there is never a fake event. The feed pauses when it's off-screen or the tab is hidden, animates new beats as they land, and offers an opt-in money sound. (`/pulse`) `[feature]`
- **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]`
+- **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]`
- **Prompt-to-avatar: a live progress bar you can cancel, plus motion and screen-reader polish** — Building an avatar from a text prompt now shows a progress bar that actually moves second-to-second (tied to real elapsed time) instead of sitting frozen between stages, a real elapsed clock, and a Cancel button (or Escape) so you're never stuck watching a spinner. Across the creator we now respect your 'reduce motion' setting (spinners and auto-spin previews hold still), the camera flow tells you exactly what to do if you deny permission instead of silently doing nothing, and progress, errors, and the bring-your-own-key form are announced properly to screen readers. Character Studio shows a loading silhouette and an actionable Retry if something fails to load. (`/create/prompt`) `[improvement]`
- **Security: CSRF protection extended to sniper arming and trade limits** — Arming an autonomous sniper strategy and changing an agent's discretionary trade limits both commit or unlock real custodial funds, so both writes now require the same one-time CSRF token every other money-moving action already enforced (withdraw, vanity grind, spend limits, trade execution). Ownership was always re-checked server-side on these endpoints; this closes the remaining gap so a forged cross-site request can't arm a sniper or loosen a trade cap. No change to how you use them — the dashboard already sends the token. `[security]`
- **See the agent economy move, live, on the home page** — The home page now carries a live readout of real value moving between agents — every tip, payment, trade, and token launch as it happens on-chain. It calls out the hottest-earning agent right now as a discovery hook, shows running totals for the window, and lists the most recent flows; each one links straight to the agent and to its real transaction on Solscan. Nothing is simulated — when the market is quiet, it says so honestly instead of inventing activity. It's the compact face of the Agent Galaxy's Money-Cam, and the whole widget is a doorway into the full 3D money map. (`/galaxy`) `[feature]`
@@ -42,6 +49,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Skill-sale earnings now show up in your agent's Earn tab** — The Earn tab's headline number — what your avatar has actually earned — now counts every skill sale, not just tips. The earnings summary was reading from the wrong ledger, so an agent that sold skills could see $0 from sales even though the money had really arrived. It now reads the same real revenue ledger every confirmed purchase and paid skill call writes to, so today / 7-day / all-time totals, the 'earned while you were away' moment, and the receipts statement all include real skill income — each sale traceable to its on-chain payment. Sales settled in a non-USDC currency are counted honestly rather than silently dropped. (`/agent`) `[fix]`
- **Social recovery & inheritance — a funded agent that never dies with its owner** — Your agent's wallet is custodial and real-money funded, so "I lost access" or "the owner is gone" should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping "I'm here"). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds. (`/guardian`) `[feature, security]`
- **Steadier 3D generation and token stats when free providers get busy** — Two backend reliability fixes. The free image step behind text→3D now shrugs off a brief blip from NVIDIA's gateway — if it answers with a fast, transient hiccup, we retry once before handing off, so fewer prompts have to fall through to a slower backup and fewer fail outright. (A real timeout still hands off immediately, so nothing waits twice.) Separately, live token stats lean on several market-data sources; when one hits its monthly quota we already pause it, but each fresh server instance used to re-discover that the hard way and waste another doomed call. That pause is now shared across the whole fleet, so the moment one instance sees a source is exhausted, none of the others retry it — quieter, faster, and no wasted quota. `[fix, infra]`
+- **Strategy Objects: equip an ownable, forkable trade strategy on your agent** — A trading strategy is now a first-class thing you can own, share, and equip — not a buried setting. Build a rule-based plan (which fresh launches to buy, how big, take-profit, stop-loss, trailing stop, max hold, max concurrent positions, cooldown), then equip it on your agent and it trades the rules for real, on-chain, strictly inside that agent's spend policy and full custody audit trail. Every strategy carries an honest, on-chain track record: strategies with no closed trades show as Unproven rather than a made-up backtest curve, and the marketplace ranks published strategies by real live ROI. Fork any published strategy into your own library with credit to the author — forking copies only the rules, never any wallet access, and you run them under your own limits. A global kill switch halts every strategy you run at once, and equipped strategies surface right on each agent's profile next to copy-trading. Browse and manage everything at /strategies. (`/strategies`) `[feature]`
- **Talk to your agent and it trades — the Conversational Wallet** — Your avatar's wallet now takes voice and text commands. Tell your agent "tip 0.1 SOL to vault.sol", "snipe that mint with half a SOL", "sell half my $THREE", or "withdraw 2 SOL to my Phantom" — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit "yes" or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, "cancel" is always one word away, and there's a full keyboard path with no mic required. `[feature]`
- **Talk to your avatar — a new free speech-to-text lane closes the voice loop** — Your avatar could already speak for free; now it can listen for free too. A new /api/asr endpoint turns spoken audio into text using NVIDIA's hosted Riva recognition on the same free key that already powers avatar voices, 3D generation, and chat — so voice-in costs nothing extra. Until now, talking to an avatar relied on the browser's built-in recognizer, which only exists in Chrome and Edge and quietly sends your microphone to Google; the new lane is server-side and works the same everywhere. It's purely additive: when the lane isn't switched on, voice keeps working exactly as before — nothing changes for anyone. Send a short WAV, PCM, FLAC, or Ogg clip and get back the transcript, the language detected, and optional word-level timestamps, all metered fairly so it can't be abused. `[feature]`
- **Talk to your avatar out loud — in any browser** — Your avatar could already think and speak; now it can listen. Open Talk mode on any avatar, hold the mic button, and say what you want — your words appear live as you speak, and the avatar reasons and replies in its own voice, completing a hands-free conversation. Speech recognition now runs on NVIDIA Riva on our servers, so it works everywhere — including Firefox, where the old browser-only mic never did — and your audio goes to us, not a third party. Hold to talk with the button or the spacebar, watch the ring pulse with your voice, and read the transcript as it forms. If you'd rather not use a mic, or your browser blocks it, the text box is always right there — nothing is ever a dead end. `[feature]`
diff --git a/api/_lib/a2f-nvidia.js b/api/_lib/a2f-nvidia.js
new file mode 100644
index 000000000..8906c71d0
--- /dev/null
+++ b/api/_lib/a2f-nvidia.js
@@ -0,0 +1,365 @@
+// Free NVIDIA NIM facial-animation lane — Audio2Face-3D over NVCF gRPC.
+//
+// This is the face-MOTION sibling of api/_lib/tts-nvidia.js (voice-OUT) and
+// api/_lib/asr-nvidia.js (voice-IN). It closes the "talking head" loop: Magpie
+// TTS gives every avatar a voice; Audio2Face-3D turns that exact spoken audio
+// into a per-frame ARKit blendshape track so the avatar's mouth and face move
+// in sync with the words — two named NVIDIA models driving one face.
+//
+// Like Magpie and Riva, A2F-3D is hosted as an NVCF gRPC function on
+// grpc.nvcf.nvidia.com:443, selected by a `function-id` metadata entry with the
+// nvapi key as a bearer `authorization` entry. The wire contract is NVIDIA's
+// ACE `nvidia_ace.services.a2f_controller.v1.A2FControllerService` — a
+// BIDIRECTIONAL streaming `ProcessAudioStream`: the client streams an audio
+// header + PCM chunks + an end-of-audio marker; the server streams back an
+// animation header (the ordered blendshape names) followed by animation-data
+// frames (per-frame blendshape weights with a time code), at 30 fps. The proto
+// definitions are vendored under ./a2f-protos/ and loaded from a generated JSON
+// descriptor (descriptor.js — kept separate from the Riva descriptors) so no
+// .proto file needs to exist on the serverless filesystem (api/ routes are
+// esbuild-bundled in place — scripts/bundle-api.mjs).
+//
+// ── Audio contract ───────────────────────────────────────────────────────────
+// A2F-3D is trained on 16 kHz mono 16-bit PCM. Magpie emits 44.1 kHz, so this
+// module decodes the WAV, downmixes to mono, and resamples to 16 kHz before
+// streaming. The returned blendshape time codes are in SECONDS relative to the
+// clip start, independent of the audio sample rate, so the browser plays the
+// ORIGINAL Magpie audio and samples the track by the audio element's currentTime
+// — lips track the real voice, not a resampled copy.
+//
+// ── Function id ──────────────────────────────────────────────────────────────
+// Unlike Riva ASR (pure config), A2F-3D ships a stable published NVCF function
+// id (the "James" model from NVIDIA's official sample — tongue blendshapes
+// included), so the lane works out of the box with only NVIDIA_API_KEY set. A
+// deployment can pin a different model (Mark/Claire) via NVIDIA_A2F_FUNCTION_ID;
+// discover the live ids for your account with
+// node scripts/verify-nvidia-a2f.mjs --list
+//
+// Error codes match the established provider contract (tts-nvidia.js / asr-nvidia.js):
+// invalid_key / rate_limited / invalid_argument / timeout /
+// provider_unreachable / provider_error / not_configured.
+
+import { env } from './env.js';
+import { parseWav } from './asr-nvidia.js';
+import a2fDescriptor from './a2f-protos/descriptor.js';
+
+export const NVIDIA_A2F_HOST = 'grpc.nvcf.nvidia.com:443';
+
+// Published NVCF function id for the hosted Audio2Face-3D "James" model, taken
+// verbatim from NVIDIA's official sample client invocation
+// (Audio2Face-3D-Samples/scripts/audio2face_3d_api_client). James carries the
+// full ARKit-52 set plus tongue blendshapes. Override with NVIDIA_A2F_FUNCTION_ID.
+export const A2F_DEFAULT_FUNCTION_ID = '9327c39f-a361-4e02-bd72-e11b4c9b7b5e';
+
+// A2F-3D's native inference rate and the rate the audio is resampled to before
+// streaming. The model runs 30 inferences per second of audio (→ 30 fps output).
+const A2F_SAMPLE_RATE_HZ = 16000;
+const A2F_FPS = 30;
+const DEFAULT_TIMEOUT_MS = 30_000;
+// Bound the clip the lambda will buffer + stream. 60 s of 16 kHz mono s16 is
+// ~1.9 MB of PCM and ~1800 frames — generous for avatar speech, small enough
+// that one request can't pin a serverless instance.
+const MAX_AUDIO_SECONDS = 60;
+
+export function nvidiaA2fConfigured() {
+ return Boolean(env.NVIDIA_API_KEY);
+}
+
+export function resolveA2fFunctionId(explicit) {
+ return explicit || env.NVIDIA_A2F_FUNCTION_ID || A2F_DEFAULT_FUNCTION_ID;
+}
+
+// Downmix interleaved s16 PCM to mono. Returns the input untouched when already
+// mono. Averaging avoids the +6 dB clipping a naive sum would cause.
+function toMonoInt16(pcm, channels) {
+ if (channels <= 1) return new Int16Array(pcm.buffer, pcm.byteOffset, Math.floor(pcm.byteLength / 2));
+ const view = new Int16Array(pcm.buffer, pcm.byteOffset, Math.floor(pcm.byteLength / 2));
+ const frames = Math.floor(view.length / channels);
+ const out = new Int16Array(frames);
+ for (let i = 0; i < frames; i++) {
+ let sum = 0;
+ for (let c = 0; c < channels; c++) sum += view[i * channels + c];
+ out[i] = Math.round(sum / channels);
+ }
+ return out;
+}
+
+// Linear-interpolation resampler for mono s16. Speech feature extraction does
+// not need a windowed-sinc kernel; linear keeps formant cues intact at a
+// fraction of the cost and introduces no audible artifacts the model cares about.
+function resampleInt16(mono, fromRate, toRate) {
+ if (fromRate === toRate) return mono;
+ const ratio = toRate / fromRate;
+ const outLen = Math.max(1, Math.floor(mono.length * ratio));
+ const out = new Int16Array(outLen);
+ for (let i = 0; i < outLen; i++) {
+ const srcPos = i / ratio;
+ const i0 = Math.floor(srcPos);
+ const i1 = Math.min(i0 + 1, mono.length - 1);
+ const frac = srcPos - i0;
+ out[i] = Math.round(mono[i0] * (1 - frac) + mono[i1] * frac);
+ }
+ return out;
+}
+
+// gRPC status code → platform error code (numeric codes so the mapping does not
+// depend on the grpc-js import being resolved). Mirrors tts-nvidia.js / asr-nvidia.js.
+function normalizeGrpcError(err) {
+ const code = typeof err?.code === 'number' ? err.code : null;
+ const map = {
+ 3: 'invalid_argument', // bad audio header / encoding
+ 4: 'timeout', // DEADLINE_EXCEEDED
+ 7: 'invalid_key', // PERMISSION_DENIED
+ 8: 'rate_limited', // RESOURCE_EXHAUSTED (credit-metered free tier)
+ 14: 'provider_unreachable', // UNAVAILABLE
+ 16: 'invalid_key', // UNAUTHENTICATED
+ };
+ const normalized = new Error(
+ `NVIDIA Audio2Face-3D failed${code !== null ? ` (gRPC ${code})` : ''}: ${err?.details || err?.message || 'unknown error'}`,
+ );
+ normalized.code = (code !== null && map[code]) || 'provider_error';
+ normalized.grpcCode = code;
+ return normalized;
+}
+
+// One cached client per warm lambda (the TLS channel is keyless — auth rides in
+// per-call metadata). @grpc/grpc-js is imported lazily so non-A2F importers do
+// not pay for the dependency at cold start. See tts-nvidia.js for the NVCF
+// warm-channel auth caveat the verify script works around.
+let clientPromise = null;
+async function getClient() {
+ if (!clientPromise) {
+ clientPromise = (async () => {
+ const [{ default: grpc }, { default: protoLoader }] = await Promise.all([
+ import('@grpc/grpc-js'),
+ import('@grpc/proto-loader'),
+ ]);
+ const definition = protoLoader.fromJSON(a2fDescriptor, {
+ keepCase: true,
+ longs: Number,
+ enums: String,
+ defaults: true,
+ oneofs: true,
+ });
+ const pkg = grpc.loadPackageDefinition(definition);
+ const Service = pkg.nvidia_ace.services.a2f_controller.v1.A2FControllerService;
+ return {
+ grpc,
+ client: new Service(NVIDIA_A2F_HOST, grpc.credentials.createSsl(), {
+ // Animation streams come back as many small frames, but the echoed
+ // audio + headers can be sizeable on long clips — lift both caps.
+ 'grpc.max_receive_message_length': 64 * 1024 * 1024,
+ 'grpc.max_send_message_length': 64 * 1024 * 1024,
+ }),
+ };
+ })().catch((e) => {
+ clientPromise = null; // a failed init must not poison the warm lambda
+ throw e;
+ });
+ }
+ return clientPromise;
+}
+
+// Generate a facial-animation track from spoken audio on the free NIM lane.
+//
+// { wav?: Buffer, pcm?: Buffer, sampleRateHz?, channels?, functionId?,
+// faceParams?, blendshapeMultipliers?, timeoutMs?, apiKey? }
+// → { fps, blendShapeNames, frames: [{ t, w }], frameCount, durationSec,
+// sampleRateHz, model, functionId }
+//
+// Provide EITHER `wav` (a RIFF/WAVE buffer — the Magpie output is passed straight
+// through; its header is parsed for rate + channels) OR raw `pcm` (header-less
+// little-endian s16) with `sampleRateHz`. `frames[i].t` is the time code in
+// seconds relative to the clip start; `frames[i].w` is the blendshape weights in
+// the order of `blendShapeNames` (the names come from the model, ARKit naming).
+//
+// Throws Error with .code ∈ not_configured | invalid_key | rate_limited |
+// invalid_argument | timeout | provider_unreachable | provider_error.
+export async function animateNvidiaA2F({
+ wav,
+ pcm,
+ sampleRateHz,
+ channels = 1,
+ functionId,
+ faceParams,
+ blendshapeMultipliers,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ apiKey,
+} = {}) {
+ const key = apiKey || env.NVIDIA_API_KEY;
+ if (!key) {
+ const err = new Error('NVIDIA_API_KEY not set');
+ err.code = 'not_configured';
+ throw err;
+ }
+
+ // ── Normalize the audio to 16 kHz mono s16 ────────────────────────────────
+ let monoSrc;
+ let srcRate;
+ if (Buffer.isBuffer(wav) && wav.length) {
+ const parsed = parseWav(wav);
+ if (!parsed) {
+ const err = new Error('audio is not a valid WAV (no RIFF/WAVE header)');
+ err.code = 'invalid_argument';
+ throw err;
+ }
+ monoSrc = toMonoInt16(parsed.pcm, parsed.channels);
+ srcRate = parsed.sampleRateHz;
+ } else if (Buffer.isBuffer(pcm) && pcm.length) {
+ if (!sampleRateHz) {
+ const err = new Error('sampleRateHz is required when passing raw pcm');
+ err.code = 'invalid_argument';
+ throw err;
+ }
+ monoSrc = toMonoInt16(pcm, channels);
+ srcRate = sampleRateHz;
+ } else {
+ const err = new Error('no audio provided (expected wav or pcm)');
+ err.code = 'invalid_argument';
+ throw err;
+ }
+
+ if (monoSrc.length / srcRate > MAX_AUDIO_SECONDS) {
+ const err = new Error(`audio exceeds ${MAX_AUDIO_SECONDS}s limit`);
+ err.code = 'invalid_argument';
+ throw err;
+ }
+
+ const mono16k = resampleInt16(monoSrc, srcRate, A2F_SAMPLE_RATE_HZ);
+ // Int16Array → little-endian byte buffer for the proto `bytes` field.
+ const audioBytes = Buffer.from(mono16k.buffer, mono16k.byteOffset, mono16k.byteLength);
+
+ const fnId = resolveA2fFunctionId(functionId);
+ const { grpc, client } = await getClient();
+ const metadata = new grpc.Metadata();
+ metadata.set('function-id', fnId);
+ metadata.set('authorization', `Bearer ${key}`);
+
+ const header = {
+ audio_stream_header: {
+ audio_header: {
+ audio_format: 'AUDIO_FORMAT_PCM',
+ channel_count: 1,
+ samples_per_second: A2F_SAMPLE_RATE_HZ,
+ bits_per_sample: 16,
+ },
+ // Clamp output weights to [0,1] so they map straight onto morph target
+ // influences without the frontend having to renormalize. Optional
+ // per-shape multipliers let a caller dial specific shapes up/down.
+ blendshape_params: {
+ enable_clamping_bs_weight: true,
+ ...(blendshapeMultipliers ? { bs_weight_multipliers: blendshapeMultipliers } : {}),
+ },
+ ...(faceParams ? { face_params: { float_params: faceParams } } : {}),
+ },
+ };
+
+ const result = await new Promise((resolveCall, rejectCall) => {
+ let settled = false;
+ const fail = (e) => {
+ if (settled) return;
+ settled = true;
+ rejectCall(e instanceof Error && e.code ? e : normalizeGrpcError(e));
+ };
+
+ let call;
+ try {
+ call = client.processAudioStream(metadata, { deadline: new Date(Date.now() + timeoutMs) });
+ } catch (e) {
+ fail(e);
+ return;
+ }
+
+ let blendShapeNames = [];
+ const frames = [];
+
+ call.on('data', (msg) => {
+ if (msg.animation_data_stream_header) {
+ const names = msg.animation_data_stream_header.skel_animation_header?.blend_shapes;
+ if (Array.isArray(names) && names.length) blendShapeNames = names;
+ } else if (msg.animation_data) {
+ const weights = msg.animation_data.skel_animation?.blend_shape_weights;
+ if (Array.isArray(weights)) {
+ for (const frame of weights) {
+ frames.push({
+ t: Number(frame.time_code) || 0,
+ w: Array.isArray(frame.values) ? frame.values.map((v) => clamp01(v)) : [],
+ });
+ }
+ }
+ } else if (msg.status && msg.status.code === 'ERROR') {
+ // A2F can answer ERROR in-band (e.g. audio-limit) before closing OK.
+ fail(Object.assign(new Error(`A2F status ERROR: ${msg.status.message || 'unknown'}`), {
+ code: 'provider_error',
+ }));
+ try { call.cancel(); } catch {}
+ }
+ });
+
+ call.on('error', fail);
+
+ call.on('end', () => {
+ if (settled) return;
+ settled = true;
+ if (!frames.length) {
+ rejectCall(Object.assign(new Error('Audio2Face-3D returned no animation frames'), {
+ code: 'provider_error',
+ }));
+ return;
+ }
+ // Time codes are strictly increasing; keep them sorted defensively in
+ // case the server interleaves frames across animation-data messages.
+ frames.sort((a, b) => a.t - b.t);
+ resolveCall({ blendShapeNames, frames });
+ });
+
+ // Stream: header → audio (1 s chunks, matching NVIDIA's sample cadence) →
+ // end-of-audio. Chunking keeps any single gRPC message small; the size is
+ // not semantically meaningful to the model.
+ try {
+ call.write(header);
+ const chunkSamples = A2F_SAMPLE_RATE_HZ; // 1 second
+ for (let i = 0; i < mono16k.length; i += chunkSamples) {
+ const slice = mono16k.subarray(i, Math.min(i + chunkSamples, mono16k.length));
+ const buf = Buffer.from(slice.buffer, slice.byteOffset, slice.byteLength);
+ call.write({ audio_with_emotion: { audio_buffer: buf } });
+ }
+ call.write({ end_of_audio: {} });
+ call.end();
+ } catch (e) {
+ fail(e);
+ }
+ });
+
+ const durationSec = mono16k.length / A2F_SAMPLE_RATE_HZ;
+ // Derive the real fps from the frame cadence when we have enough frames;
+ // fall back to the documented 30 fps for a 1-frame clip.
+ let fps = A2F_FPS;
+ if (result.frames.length > 1) {
+ const span = result.frames[result.frames.length - 1].t - result.frames[0].t;
+ if (span > 0) fps = Math.round((result.frames.length - 1) / span);
+ }
+
+ return {
+ fps,
+ blendShapeNames: result.blendShapeNames,
+ frames: result.frames,
+ frameCount: result.frames.length,
+ durationSec,
+ sampleRateHz: A2F_SAMPLE_RATE_HZ,
+ model: 'audio2face-3d',
+ functionId: fnId,
+ };
+}
+
+function clamp01(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return 0;
+ if (v < 0) return 0;
+ if (v > 1) return 1;
+ return v;
+}
+
+// Mirror just enough audio math for the verify script + tests to exercise the
+// resampler/downmixer without a live gRPC call.
+export const _internals = { toMonoInt16, resampleInt16 };
diff --git a/api/_lib/a2f-protos/descriptor.js b/api/_lib/a2f-protos/descriptor.js
new file mode 100644
index 000000000..3ae2376df
--- /dev/null
+++ b/api/_lib/a2f-protos/descriptor.js
@@ -0,0 +1,865 @@
+// GENERATED FILE — do not edit by hand.
+// Regenerate with: node scripts/generate-a2f-descriptor.mjs
+// protobufjs JSON descriptor for NVIDIA Audio2Face-3D (ACE) — the
+// nvidia_ace.services.a2f_controller.v1.A2FControllerService gRPC surface,
+// parsed (keepCase) from the vendored protos in api/_lib/a2f-protos/*.proto,
+// themselves from https://github.com/NVIDIA/Audio2Face-3D-Samples.
+// SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+export default {
+ "nested": {
+ "google": {
+ "nested": {
+ "protobuf": {
+ "nested": {
+ "Any": {
+ "fields": {
+ "type_url": {
+ "type": "string",
+ "id": 1
+ },
+ "value": {
+ "type": "bytes",
+ "id": 2
+ }
+ }
+ },
+ "Empty": {
+ "fields": {}
+ }
+ }
+ }
+ }
+ },
+ "nvidia_ace": {
+ "nested": {
+ "audio": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "AudioHeader": {
+ "fields": {
+ "audio_format": {
+ "type": "AudioFormat",
+ "id": 1
+ },
+ "channel_count": {
+ "type": "uint32",
+ "id": 2
+ },
+ "samples_per_second": {
+ "type": "uint32",
+ "id": 3
+ },
+ "bits_per_sample": {
+ "type": "uint32",
+ "id": 4
+ }
+ },
+ "nested": {
+ "AudioFormat": {
+ "values": {
+ "AUDIO_FORMAT_PCM": 0
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "animation_id": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "AnimationIds": {
+ "fields": {
+ "request_id": {
+ "type": "string",
+ "id": 1
+ },
+ "stream_id": {
+ "type": "string",
+ "id": 2
+ },
+ "target_object_id": {
+ "type": "string",
+ "id": 3
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "status": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "Status": {
+ "fields": {
+ "code": {
+ "type": "Code",
+ "id": 1
+ },
+ "message": {
+ "type": "string",
+ "id": 2
+ }
+ },
+ "nested": {
+ "Code": {
+ "values": {
+ "SUCCESS": 0,
+ "INFO": 1,
+ "WARNING": 2,
+ "ERROR": 3
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "emotion_with_timecode": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "EmotionWithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "emotion": {
+ "keyType": "string",
+ "type": "float",
+ "id": 2
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "a2f": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "AudioStream": {
+ "oneofs": {
+ "stream_part": {
+ "oneof": [
+ "audio_stream_header",
+ "audio_with_emotion"
+ ]
+ }
+ },
+ "fields": {
+ "audio_stream_header": {
+ "type": "AudioStreamHeader",
+ "id": 1
+ },
+ "audio_with_emotion": {
+ "type": "nvidia_ace.a2f.v1.AudioWithEmotion",
+ "id": 2
+ }
+ }
+ },
+ "AudioStreamHeader": {
+ "fields": {
+ "animation_ids": {
+ "type": "nvidia_ace.animation_id.v1.AnimationIds",
+ "id": 1
+ },
+ "audio_header": {
+ "type": "nvidia_ace.audio.v1.AudioHeader",
+ "id": 2
+ },
+ "face_params": {
+ "type": "FaceParameters",
+ "id": 3
+ },
+ "emotion_post_processing_params": {
+ "type": "EmotionPostProcessingParameters",
+ "id": 4
+ },
+ "blendshape_params": {
+ "type": "BlendShapeParameters",
+ "id": 5
+ },
+ "emotion_params": {
+ "type": "EmotionParameters",
+ "id": 6
+ }
+ }
+ },
+ "FloatArray": {
+ "fields": {
+ "values": {
+ "rule": "repeated",
+ "type": "float",
+ "id": 1
+ }
+ }
+ },
+ "FaceParameters": {
+ "fields": {
+ "float_params": {
+ "keyType": "string",
+ "type": "float",
+ "id": 1
+ },
+ "integer_params": {
+ "keyType": "string",
+ "type": "int32",
+ "id": 2
+ },
+ "float_array_params": {
+ "keyType": "string",
+ "type": "FloatArray",
+ "id": 3
+ }
+ }
+ },
+ "BlendShapeParameters": {
+ "oneofs": {
+ "_enable_clamping_bs_weight": {
+ "oneof": [
+ "enable_clamping_bs_weight"
+ ]
+ }
+ },
+ "fields": {
+ "bs_weight_multipliers": {
+ "keyType": "string",
+ "type": "float",
+ "id": 1
+ },
+ "bs_weight_offsets": {
+ "keyType": "string",
+ "type": "float",
+ "id": 2
+ },
+ "enable_clamping_bs_weight": {
+ "type": "bool",
+ "id": 3,
+ "options": {
+ "proto3_optional": true
+ }
+ }
+ }
+ },
+ "EmotionParameters": {
+ "oneofs": {
+ "_live_transition_time": {
+ "oneof": [
+ "live_transition_time"
+ ]
+ }
+ },
+ "fields": {
+ "live_transition_time": {
+ "type": "float",
+ "id": 1,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "beginning_emotion": {
+ "keyType": "string",
+ "type": "float",
+ "id": 2
+ }
+ }
+ },
+ "EmotionPostProcessingParameters": {
+ "oneofs": {
+ "_emotion_contrast": {
+ "oneof": [
+ "emotion_contrast"
+ ]
+ },
+ "_live_blend_coef": {
+ "oneof": [
+ "live_blend_coef"
+ ]
+ },
+ "_enable_preferred_emotion": {
+ "oneof": [
+ "enable_preferred_emotion"
+ ]
+ },
+ "_preferred_emotion_strength": {
+ "oneof": [
+ "preferred_emotion_strength"
+ ]
+ },
+ "_emotion_strength": {
+ "oneof": [
+ "emotion_strength"
+ ]
+ },
+ "_max_emotions": {
+ "oneof": [
+ "max_emotions"
+ ]
+ }
+ },
+ "fields": {
+ "emotion_contrast": {
+ "type": "float",
+ "id": 1,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "live_blend_coef": {
+ "type": "float",
+ "id": 2,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "enable_preferred_emotion": {
+ "type": "bool",
+ "id": 3,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "preferred_emotion_strength": {
+ "type": "float",
+ "id": 4,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "emotion_strength": {
+ "type": "float",
+ "id": 5,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "max_emotions": {
+ "type": "int32",
+ "id": 6,
+ "options": {
+ "proto3_optional": true
+ }
+ }
+ }
+ },
+ "AudioWithEmotion": {
+ "fields": {
+ "audio_buffer": {
+ "type": "bytes",
+ "id": 1
+ },
+ "emotions": {
+ "rule": "repeated",
+ "type": "nvidia_ace.emotion_with_timecode.v1.EmotionWithTimeCode",
+ "id": 2
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "animation_data": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "AnimationDataStreamHeader": {
+ "oneofs": {
+ "_source_service_id": {
+ "oneof": [
+ "source_service_id"
+ ]
+ },
+ "_audio_header": {
+ "oneof": [
+ "audio_header"
+ ]
+ },
+ "_skel_animation_header": {
+ "oneof": [
+ "skel_animation_header"
+ ]
+ }
+ },
+ "fields": {
+ "animation_ids": {
+ "type": "nvidia_ace.animation_id.v1.AnimationIds",
+ "id": 1
+ },
+ "source_service_id": {
+ "type": "string",
+ "id": 2,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "audio_header": {
+ "type": "nvidia_ace.audio.v1.AudioHeader",
+ "id": 3,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "skel_animation_header": {
+ "type": "nvidia_ace.animation_data.v1.SkelAnimationHeader",
+ "id": 4,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "start_time_code_since_epoch": {
+ "type": "double",
+ "id": 5
+ }
+ }
+ },
+ "AnimationDataStream": {
+ "oneofs": {
+ "stream_part": {
+ "oneof": [
+ "animation_data_stream_header",
+ "animation_data",
+ "status"
+ ]
+ }
+ },
+ "fields": {
+ "animation_data_stream_header": {
+ "type": "AnimationDataStreamHeader",
+ "id": 1
+ },
+ "animation_data": {
+ "type": "nvidia_ace.animation_data.v1.AnimationData",
+ "id": 2
+ },
+ "status": {
+ "type": "nvidia_ace.status.v1.Status",
+ "id": 3
+ }
+ }
+ },
+ "AnimationData": {
+ "oneofs": {
+ "_skel_animation": {
+ "oneof": [
+ "skel_animation"
+ ]
+ },
+ "_audio": {
+ "oneof": [
+ "audio"
+ ]
+ },
+ "_camera": {
+ "oneof": [
+ "camera"
+ ]
+ }
+ },
+ "fields": {
+ "skel_animation": {
+ "type": "SkelAnimation",
+ "id": 1,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "audio": {
+ "type": "AudioWithTimeCode",
+ "id": 2,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "camera": {
+ "type": "Camera",
+ "id": 3,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "metadata": {
+ "keyType": "string",
+ "type": "google.protobuf.Any",
+ "id": 4
+ }
+ }
+ },
+ "AudioWithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "audio_buffer": {
+ "type": "bytes",
+ "id": 2
+ }
+ }
+ },
+ "SkelAnimationHeader": {
+ "fields": {
+ "blend_shapes": {
+ "rule": "repeated",
+ "type": "string",
+ "id": 1
+ },
+ "joints": {
+ "rule": "repeated",
+ "type": "string",
+ "id": 2
+ }
+ }
+ },
+ "SkelAnimation": {
+ "fields": {
+ "blend_shape_weights": {
+ "rule": "repeated",
+ "type": "FloatArrayWithTimeCode",
+ "id": 1
+ },
+ "translations": {
+ "rule": "repeated",
+ "type": "Float3ArrayWithTimeCode",
+ "id": 2
+ },
+ "rotations": {
+ "rule": "repeated",
+ "type": "QuatFArrayWithTimeCode",
+ "id": 3
+ },
+ "scales": {
+ "rule": "repeated",
+ "type": "Float3ArrayWithTimeCode",
+ "id": 4
+ }
+ }
+ },
+ "Camera": {
+ "fields": {
+ "position": {
+ "rule": "repeated",
+ "type": "Float3WithTimeCode",
+ "id": 1
+ },
+ "rotation": {
+ "rule": "repeated",
+ "type": "QuatFWithTimeCode",
+ "id": 2
+ },
+ "focal_length": {
+ "rule": "repeated",
+ "type": "FloatWithTimeCode",
+ "id": 3
+ },
+ "focus_distance": {
+ "rule": "repeated",
+ "type": "FloatWithTimeCode",
+ "id": 4
+ }
+ }
+ },
+ "FloatArrayWithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "values": {
+ "rule": "repeated",
+ "type": "float",
+ "id": 2
+ }
+ }
+ },
+ "Float3ArrayWithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "values": {
+ "rule": "repeated",
+ "type": "Float3",
+ "id": 2
+ }
+ }
+ },
+ "QuatFArrayWithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "values": {
+ "rule": "repeated",
+ "type": "QuatF",
+ "id": 2
+ }
+ }
+ },
+ "Float3WithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "value": {
+ "type": "Float3",
+ "id": 2
+ }
+ }
+ },
+ "QuatFWithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "value": {
+ "type": "QuatF",
+ "id": 2
+ }
+ }
+ },
+ "FloatWithTimeCode": {
+ "fields": {
+ "time_code": {
+ "type": "double",
+ "id": 1
+ },
+ "value": {
+ "type": "float",
+ "id": 2
+ }
+ }
+ },
+ "QuatF": {
+ "fields": {
+ "real": {
+ "type": "float",
+ "id": 1
+ },
+ "i": {
+ "type": "float",
+ "id": 2
+ },
+ "j": {
+ "type": "float",
+ "id": 3
+ },
+ "k": {
+ "type": "float",
+ "id": 4
+ }
+ }
+ },
+ "Float3": {
+ "fields": {
+ "x": {
+ "type": "float",
+ "id": 1
+ },
+ "y": {
+ "type": "float",
+ "id": 2
+ },
+ "z": {
+ "type": "float",
+ "id": 3
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "controller": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "AudioStream": {
+ "oneofs": {
+ "stream_part": {
+ "oneof": [
+ "audio_stream_header",
+ "audio_with_emotion",
+ "end_of_audio"
+ ]
+ }
+ },
+ "fields": {
+ "audio_stream_header": {
+ "type": "AudioStreamHeader",
+ "id": 1
+ },
+ "audio_with_emotion": {
+ "type": "nvidia_ace.a2f.v1.AudioWithEmotion",
+ "id": 2
+ },
+ "end_of_audio": {
+ "type": "EndOfAudio",
+ "id": 3
+ }
+ },
+ "nested": {
+ "EndOfAudio": {
+ "fields": {}
+ }
+ }
+ },
+ "AudioStreamHeader": {
+ "fields": {
+ "audio_header": {
+ "type": "nvidia_ace.audio.v1.AudioHeader",
+ "id": 1
+ },
+ "face_params": {
+ "type": "nvidia_ace.a2f.v1.FaceParameters",
+ "id": 2
+ },
+ "emotion_post_processing_params": {
+ "type": "nvidia_ace.a2f.v1.EmotionPostProcessingParameters",
+ "id": 3
+ },
+ "blendshape_params": {
+ "type": "nvidia_ace.a2f.v1.BlendShapeParameters",
+ "id": 4
+ },
+ "emotion_params": {
+ "type": "nvidia_ace.a2f.v1.EmotionParameters",
+ "id": 5
+ }
+ }
+ },
+ "EventType": {
+ "values": {
+ "END_OF_A2F_AUDIO_PROCESSING": 0
+ }
+ },
+ "Event": {
+ "oneofs": {
+ "_metadata": {
+ "oneof": [
+ "metadata"
+ ]
+ }
+ },
+ "fields": {
+ "event_type": {
+ "type": "EventType",
+ "id": 1
+ },
+ "metadata": {
+ "type": "google.protobuf.Any",
+ "id": 2,
+ "options": {
+ "proto3_optional": true
+ }
+ }
+ }
+ },
+ "AnimationDataStreamHeader": {
+ "oneofs": {
+ "_audio_header": {
+ "oneof": [
+ "audio_header"
+ ]
+ },
+ "_skel_animation_header": {
+ "oneof": [
+ "skel_animation_header"
+ ]
+ }
+ },
+ "fields": {
+ "audio_header": {
+ "type": "nvidia_ace.audio.v1.AudioHeader",
+ "id": 1,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "skel_animation_header": {
+ "type": "nvidia_ace.animation_data.v1.SkelAnimationHeader",
+ "id": 2,
+ "options": {
+ "proto3_optional": true
+ }
+ },
+ "start_time_code_since_epoch": {
+ "type": "double",
+ "id": 3
+ }
+ }
+ },
+ "AnimationDataStream": {
+ "oneofs": {
+ "stream_part": {
+ "oneof": [
+ "animation_data_stream_header",
+ "animation_data",
+ "event",
+ "status"
+ ]
+ }
+ },
+ "fields": {
+ "animation_data_stream_header": {
+ "type": "AnimationDataStreamHeader",
+ "id": 1
+ },
+ "animation_data": {
+ "type": "nvidia_ace.animation_data.v1.AnimationData",
+ "id": 2
+ },
+ "event": {
+ "type": "Event",
+ "id": 3
+ },
+ "status": {
+ "type": "nvidia_ace.status.v1.Status",
+ "id": 4
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "services": {
+ "nested": {
+ "a2f_controller": {
+ "nested": {
+ "v1": {
+ "nested": {
+ "A2FControllerService": {
+ "methods": {
+ "ProcessAudioStream": {
+ "requestType": "nvidia_ace.controller.v1.AudioStream",
+ "requestStream": true,
+ "responseType": "nvidia_ace.controller.v1.AnimationDataStream",
+ "responseStream": true
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+};
diff --git a/api/_lib/a2f-protos/google_protobuf_any.proto b/api/_lib/a2f-protos/google_protobuf_any.proto
new file mode 100644
index 000000000..b84ef2402
--- /dev/null
+++ b/api/_lib/a2f-protos/google_protobuf_any.proto
@@ -0,0 +1,14 @@
+// Vendored minimal stub of google/protobuf/any.proto so the Audio2Face-3D
+// descriptor is self-contained (the upstream ACE protos import this well-known
+// type for the opaque `metadata` map<string, Any> fields). We never decode the
+// Any payloads — they stay packed bytes — so the canonical two-field layout is
+// all proto-loader needs to walk an AnimationData message without erroring.
+// SPDX-License-Identifier: Apache-2.0
+syntax = "proto3";
+
+package google.protobuf;
+
+message Any {
+ string type_url = 1;
+ bytes value = 2;
+}
diff --git a/api/_lib/a2f-protos/google_protobuf_empty.proto b/api/_lib/a2f-protos/google_protobuf_empty.proto
new file mode 100644
index 000000000..be2050311
--- /dev/null
+++ b/api/_lib/a2f-protos/google_protobuf_empty.proto
@@ -0,0 +1,8 @@
+// Vendored minimal stub of google/protobuf/empty.proto. The A2F controller
+// service file imports it; the message itself carries no fields.
+// SPDX-License-Identifier: Apache-2.0
+syntax = "proto3";
+
+package google.protobuf;
+
+message Empty {}
diff --git a/api/_lib/a2f-protos/nvidia_ace.a2f.v1.proto b/api/_lib/a2f-protos/nvidia_ace.a2f.v1.proto
new file mode 100644
index 000000000..c97b8053e
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.a2f.v1.proto
@@ -0,0 +1,176 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.a2f.v1;
+
+
+import "nvidia_ace.animation_id.v1.proto";
+import "nvidia_ace.status.v1.proto";
+import "nvidia_ace.audio.v1.proto";
+import "nvidia_ace.emotion_with_timecode.v1.proto";
+
+
+message AudioStream {
+ // The header must be sent as the first message.
+ // One or more audio with emotion messages must be sent thereafter.
+ // The end of audio will happen when the client closes the connection
+ oneof stream_part {
+ AudioStreamHeader audio_stream_header = 1;
+ nvidia_ace.a2f.v1.AudioWithEmotion audio_with_emotion = 2;
+ }
+}
+
+// IMPORTANT NOTE: this is an AudioStreamHeader WITH ID
+// A similar AudioStreamHeader exist in nvidia_ace.controller.v1.proto
+// but that one does NOT contain IDs
+message AudioStreamHeader {
+ // IDs of the current stream
+ nvidia_ace.animation_id.v1.AnimationIds animation_ids = 1;
+
+ nvidia_ace.audio.v1.AudioHeader audio_header = 2;
+
+ // Parameters for updating the facial characteristics of an avatar
+ // See the documentation for more information
+ FaceParameters face_params = 3;
+
+ // Parameters relative to the emotion blending and processing
+ // before using it to generate blendshapes
+ // See the documentation for more information
+ EmotionPostProcessingParameters emotion_post_processing_params = 4;
+
+ // Multipliers and offsets to apply to the generated blendshape values
+ BlendShapeParameters blendshape_params = 5;
+
+ // Emotion parameters (live transition time, beginning emotion)
+ EmotionParameters emotion_params = 6;
+}
+
+message FloatArray { repeated float values = 1; }
+
+
+message FaceParameters {
+ // The following float parameters are available:
+ // "lowerFaceSmoothing", "upperFaceSmoothing", "lowerFaceStrength", "upperFaceStrength",
+ // "faceMaskLevel", "faceMaskSoftness", "skinStrength", "blinkStrength", "eyelidOpenOffset",
+ // "lipOpenOffset", "blinkOffset", "tongueStrength", "tongueHeightOffset", "tongueDepthOffset"
+ map<string, float> float_params = 1;
+ // With the current Audio2Face Service no integer parameters are available
+ map<string, int32> integer_params = 2;
+ // With the current Audio2Face Service no FloatArray parameters are available
+ map<string, FloatArray> float_array_params = 3;
+}
+
+// The following blendshape can be used here as key:
+// "EyeBlinkLeft", "EyeLookDownLeft", "EyeLookInLeft", "EyeLookOutLeft", "EyeLookUpLeft",
+// "EyeSquintLeft", "EyeWideLeft", "EyeBlinkRight", "EyeLookDownRight", "EyeLookInRight",
+// "EyeLookOutRight", "EyeLookUpRight", "EyeSquintRight", "EyeWideRight", "JawForward",
+// "JawLeft", "JawRight", "JawOpen", "MouthClose", "MouthFunnel", "MouthPucker", "MouthLeft",
+// "MouthRight", "MouthSmileLeft", "MouthSmileRight", "MouthFrownLeft", "MouthFrownRight",
+// "MouthDimpleLeft", "MouthDimpleRight", "MouthStretchLeft", "MouthStretchRight", "MouthRollLower",
+// "MouthRollUpper", "MouthShrugLower", "MouthShrugUpper", "MouthPressLeft", "MouthPressRight",
+// "MouthLowerDownLeft", "MouthLowerDownRight", "MouthUpperUpLeft", "MouthUpperUpRight", "BrowDownLeft",
+// "BrowDownRight", "BrowInnerUp", "BrowOuterUpLeft", "BrowOuterUpRight", "CheekPuff",
+// "CheekSquintLeft", "CheekSquintRight", "NoseSneerLeft", "NoseSneerRight", "TongueOut"
+// Note1: some multipliers and offset visual impact are lighter than others.
+// "JawOpen", "MouthSmileLeft" and "MouthSmileRight" have stronger visual impact
+// Note2: Blendshape values are after applying multipliers and offset are clamped between 0 and 1
+// E.g.:
+// * inferenced_weight is 0.9
+// * multiplier_value is set to 3
+// * offset_value is set to -1
+// Then the result will be:
+// 0.9 * 3 - 1 = 1.7 ===> clamp between 0, 1 ===> adjusted weight is 1
+message BlendShapeParameters {
+ // When a key is not specified the default value is 1
+ map<string, float> bs_weight_multipliers = 1;
+ // When a key is not specified the default value is 0
+ map<string, float> bs_weight_offsets = 2;
+ // Default output bs weight is unclamped. When clamped, range is [0, 1].
+ optional bool enable_clamping_bs_weight = 3;
+}
+
+message EmotionParameters {
+ // Transition time value used for temporal smoothing by A2E SDK
+ // Expected value range: 0 < val < inf
+ optional float live_transition_time = 1;
+
+ // Beginning emotion used for temporal emotion smoothing
+ // This maps the emotion names to the corresponding emotion strength
+ // Missing emotion values will be set to 0.0
+ // The following emotions can be set:
+ // "amazement", "anger", "cheekiness", "disgust", "fear",
+ // "grief", "joy", "outofbreath", "pain", "sadness"
+ // Emotion values must be set between 0.0 and 1.0
+ map<string, float> beginning_emotion = 2;
+}
+
+// For more information refer to the documentation
+message EmotionPostProcessingParameters {
+ // Increases the spread between emotion values by pushing them higher or lower.
+ // Default value: 1
+ // Min: 0.3
+ // Max: 3
+ optional float emotion_contrast = 1;
+
+ // Coefficient for smoothing emotions over time
+ // 0 means no smoothing at all (can be jittery)
+ // 1 means extreme smoothing (emotion values not updated over time)
+ // Default value: 0.7
+ // Min: 0
+ // Max: 1
+ optional float live_blend_coef = 2;
+
+ // Activate blending between the preferred emotions (passed as input) and the emotions detected by A2E.
+ // Default: True
+ optional bool enable_preferred_emotion = 3;
+
+ // Sets the strength of the preferred emotions (passed as input) relative to emotions detected by A2E.
+ // 0 means only A2E output will be used for emotion rendering.
+ // 1 means only the preferred emotions will be used for emotion rendering.
+ // Default value: 0.5
+ // Min: 0
+ // Max: 1
+ optional float preferred_emotion_strength = 4;
+
+ // Sets the strength of generated emotions relative to neutral emotion.
+ // This multiplier is applied globally after the mix of emotion is done.
+ // If set to 0, emotion will be neutral.
+ // If set to 1, the blend of emotion will be fully used. (can be too intense)
+ // Default value: 0.6
+ // Min: 0
+ // Max: 1
+ optional float emotion_strength = 5;
+
+ // Sets a firm limit on the quantity of emotion sliders engaged by A2E
+ // emotions with highest weight will be prioritized
+ // Default value: 3
+ // Min: 1
+ // Max: 6
+ optional int32 max_emotions = 6;
+}
+
+message AudioWithEmotion {
+ // audio buffer in bytes to interpret depending on the audio header
+ bytes audio_buffer = 1;
+
+ // The time codes are relative to the beginning of the audio clip.
+ repeated nvidia_ace.emotion_with_timecode.v1.EmotionWithTimeCode emotions = 2;
+}
+//nvidia_ace.a2f.v1
+//v1.1.0
diff --git a/api/_lib/a2f-protos/nvidia_ace.animation_data.v1.proto b/api/_lib/a2f-protos/nvidia_ace.animation_data.v1.proto
new file mode 100644
index 000000000..16fdbda7a
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.animation_data.v1.proto
@@ -0,0 +1,168 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.animation_data.v1;
+
+import "nvidia_ace.animation_id.v1.proto";
+import "nvidia_ace.audio.v1.proto";
+import "nvidia_ace.status.v1.proto";
+
+import "google/protobuf/any.proto";
+
+// IMPORTANT NOTE: this is an AnimationDataStreamHeader WITH ID
+// A similar AudioStreamHeader exist in nvidia_ace.controller.v1.proto
+// but that one does NOT contain IDs
+message AnimationDataStreamHeader {
+ nvidia_ace.animation_id.v1.AnimationIds animation_ids = 1;
+
+ // This is required to identify from which animation source (e.g. A2F) the
+ // request originates. This allows us to map the incoming animation data
+ // stream to the correct pose provider animation graph node. The animation
+ // source MSs (e.g. A2F MS) should populate this with their name. (e.g. A2F).
+ // Example Value: "A2F MS"
+ optional string source_service_id = 2;
+
+ // Metadata of the audio buffers. This defines the audio clip properties
+ // at the beginning the streaming process.
+ optional nvidia_ace.audio.v1.AudioHeader audio_header = 3;
+
+ // Metadata containing the blendshape and joints names.
+ // This defines the names of the blendshapes and joints flowing though a stream.
+ optional nvidia_ace.animation_data.v1.SkelAnimationHeader
+ skel_animation_header = 4;
+
+ // Animation data streams use time codes (`time_code`) to define the temporal
+ // position of audio (e.g. `AudioWithTimeCode`), animation key frames (e.g.
+ // `SkelAnimation`), etc. relative to the beginning of the stream. The unit of
+ // `time_code` is seconds. In addition, the `AnimationDataStreamHeader` also
+ // provides the `start_time_code_since_epoch` field, which defines the
+ // absolute start time of the animation data stream. This start time is stored
+ // in seconds elapsed since the Unix time epoch.
+ double start_time_code_since_epoch = 5;
+
+ // A generic metadata field to attach use case specific data (e.g. session id,
+ // or user id?) map<string, string> metadata = 6; map<string,
+ // google.protobuf.Any> metadata = 6;
+}
+
+// This message represent each message of a stream of animation data.
+message AnimationDataStream {
+ oneof stream_part {
+ // The header must be sent as the first message.
+ AnimationDataStreamHeader animation_data_stream_header = 1;
+ // Then one or more animation data message must be sent.
+ nvidia_ace.animation_data.v1.AnimationData animation_data = 2;
+ // The status must be sent last and may be sent in between.
+ nvidia_ace.status.v1.Status status = 3;
+ }
+}
+
+message AnimationData {
+ optional SkelAnimation skel_animation = 1;
+ optional AudioWithTimeCode audio = 2;
+ optional Camera camera = 3;
+
+ // Metadata such as emotion aggregates, etc...
+ map<string, google.protobuf.Any> metadata = 4;
+}
+
+message AudioWithTimeCode {
+ // The time code is relative to the `start_time_code_since_epoch`.
+ // Example Value: 0.0 (for the very first audio buffer flowing out of a service)
+ double time_code = 1;
+ // Audio Data in bytes, for how to interpret these bytes you need to refer to
+ // the audio header.
+ bytes audio_buffer = 2;
+}
+
+message SkelAnimationHeader {
+ // Names of the blendshapes only sent once in the header
+ // The position of these names is the same as the position of the values
+ // of the blendshapes messages
+ // As an example if the blendshape names are ["Eye Left", "Eye Right", "Jaw"]
+ // Then when receiving blendshape data over the streaming process
+ // E.g.: [0.1, 0.5, 0.2] & timecode = 0.0
+ // The pairing will be for timecode=0.0, "Eye Left"=0.1, "Eye Right"=0.5, "Jaw"=0.2
+ repeated string blend_shapes = 1;
+ // Names of the joints only sent once in the header
+ repeated string joints = 2;
+}
+
+message SkelAnimation {
+ // Time codes must be strictly monotonically increasing.
+ // Two successive SkelAnimation messages must not have overlapping time code
+ // ranges.
+ repeated FloatArrayWithTimeCode blend_shape_weights = 1;
+ repeated Float3ArrayWithTimeCode translations = 2;
+ repeated QuatFArrayWithTimeCode rotations = 3;
+ repeated Float3ArrayWithTimeCode scales = 4;
+}
+
+message Camera {
+ repeated Float3WithTimeCode position = 1;
+ repeated QuatFWithTimeCode rotation = 2;
+
+ repeated FloatWithTimeCode focal_length = 3;
+ repeated FloatWithTimeCode focus_distance = 4;
+}
+
+message FloatArrayWithTimeCode {
+ double time_code = 1;
+ repeated float values = 2;
+}
+
+message Float3ArrayWithTimeCode {
+ double time_code = 1;
+ repeated Float3 values = 2;
+}
+
+message QuatFArrayWithTimeCode {
+ double time_code = 1;
+ repeated QuatF values = 2;
+}
+
+message Float3WithTimeCode {
+ double time_code = 1;
+ Float3 value = 2;
+}
+
+message QuatFWithTimeCode {
+ double time_code = 1;
+ QuatF value = 2;
+}
+
+message FloatWithTimeCode {
+ double time_code = 1;
+ float value = 2;
+}
+
+message QuatF {
+ float real = 1;
+ float i = 2;
+ float j = 3;
+ float k = 4;
+}
+
+message Float3 {
+ float x = 1;
+ float y = 2;
+ float z = 3;
+}
+//nvidia_ace.animation_data.v1
+//v1.0.0
\ No newline at end of file
diff --git a/api/_lib/a2f-protos/nvidia_ace.animation_id.v1.proto b/api/_lib/a2f-protos/nvidia_ace.animation_id.v1.proto
new file mode 100644
index 000000000..eeb4f8528
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.animation_id.v1.proto
@@ -0,0 +1,51 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.animation_id.v1;
+
+message AnimationIds {
+
+ // This is required to track a single animation source (e.g. A2X) request
+ // through the animation pipeline. This is going to allow e.g. the controller
+ // to stop a request after it has been sent to the animation compositor (e.g.
+ // animation graph).
+ // Example Value: "8b09637f-737e-488c-872e-e367e058aa15"
+ // Note1: The above value is an example UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier)
+ // Note2: You don't need to provide specifically a UUID, any text should work, however UUID are recommended
+ // for their low chance of collision
+ string request_id = 1;
+
+ // The stream id is shared across the animation pipeline and identifies all
+ // animation data streams that belong to the same stream. Thus, there will be
+ // multiple request all belonging to the same stream. Different user sessions,
+ // will usually result in a new stream id. This is required for stateful MSs
+ // (e.g. anim graph) to map different requests to the same stream.
+ // Example Value: "17f1fefd-3812-4211-94e8-7af1ef723d7f"
+ // Note1: The above value is an example UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier)
+ // Note2: You don't need to provide specifically a UUID, any text should work, however UUID are recommended
+ // for their low chance of collision
+ string stream_id = 2;
+
+ // This identifies the target avatar or object the animation data applies to.
+ // This is required when there are multiple avatars or objects in the scene.
+ // Example Value: "AceModel"
+ string target_object_id = 3;
+}
+//nvidia_ace.animation_id.v1
+//v1.0.0
\ No newline at end of file
diff --git a/api/_lib/a2f-protos/nvidia_ace.audio.v1.proto b/api/_lib/a2f-protos/nvidia_ace.audio.v1.proto
new file mode 100644
index 000000000..bdca5e3cd
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.audio.v1.proto
@@ -0,0 +1,41 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.audio.v1;
+
+message AudioHeader {
+ enum AudioFormat { AUDIO_FORMAT_PCM = 0; }
+
+ // Example value: AUDIO_FORMAT_PCM
+ AudioFormat audio_format = 1;
+
+ // Currently only mono sound must be supported.
+ // Example value: 1
+ uint32 channel_count = 2;
+
+ // Defines the sample rate of the provided audio data
+ // Example value: 16000
+ uint32 samples_per_second = 3;
+
+ // Currently only 16 bits per sample must be supported.
+ // Example value: 16
+ uint32 bits_per_sample = 4;
+}
+//nvidia_ace.audio.v1
+//v1.0.0
\ No newline at end of file
diff --git a/api/_lib/a2f-protos/nvidia_ace.controller.v1.proto b/api/_lib/a2f-protos/nvidia_ace.controller.v1.proto
new file mode 100644
index 000000000..1c7e9d2cd
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.controller.v1.proto
@@ -0,0 +1,120 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.controller.v1;
+
+import "nvidia_ace.a2f.v1.proto";
+import "nvidia_ace.animation_data.v1.proto";
+import "nvidia_ace.audio.v1.proto";
+import "nvidia_ace.status.v1.proto";
+import "google/protobuf/any.proto";
+
+message AudioStream {
+ // This is a marker for the end of an audio clip.
+ message EndOfAudio {}
+
+ oneof stream_part {
+ // The header must be sent as the first message.
+ AudioStreamHeader audio_stream_header = 1;
+ // At least one AudioWithEmotion messages must be sent thereafter.
+ nvidia_ace.a2f.v1.AudioWithEmotion audio_with_emotion = 2;
+ // The EndOfAudio must be sent last.
+ EndOfAudio end_of_audio = 3;
+ }
+}
+
+// IMPORTANT NOTE: this is an AudioStreamHeader WITHOUT ID
+// A similar AudioStreamHeader exist in nvidia_ace.a2f.v1.proto
+// but that one does contain IDs.
+message AudioStreamHeader {
+ // Metadata about the audio being sent to the service.
+ nvidia_ace.audio.v1.AudioHeader audio_header = 1;
+ // Parameters for updating the facial characteristics of an avatar.
+ // See the documentation for more information.
+ nvidia_ace.a2f.v1.FaceParameters face_params = 2;
+ // Parameters relative to the emotion blending and processing
+ // before using it to generate blendshapes.
+ // See the documentation for more information.
+ nvidia_ace.a2f.v1.EmotionPostProcessingParameters emotion_post_processing_params = 3;
+ // Multipliers and offsets to apply to the generated blendshape values.
+ nvidia_ace.a2f.v1.BlendShapeParameters blendshape_params = 4;
+ // Emotion parameters (live transition time, beginning emotion)
+ nvidia_ace.a2f.v1.EmotionParameters emotion_params = 5;
+}
+
+enum EventType {
+ // This event type means that the A2F Microservice is done processing audio,
+ // However it doesn't mean that you finished receiving all the audio data,
+ // You will receive a Status message once you are done receiving all the audio
+ // data. Events are independent of that.
+ END_OF_A2F_AUDIO_PROCESSING = 0;
+}
+
+message Event {
+ // Type of the event.
+ EventType event_type = 1;
+ // Data attached to the event if any.
+ optional google.protobuf.Any metadata = 2;
+}
+
+// IMPORTANT NOTE: this is an AnimationDataStreamHeader WITHOUT ID
+// A similar AudioStreamHeader exist in nvidia_ace.animation_data.v1.proto
+// but that one does contain IDs.
+message AnimationDataStreamHeader {
+ // Metadata of the audio buffers. This defines the audio clip properties
+ // at the beginning the streaming process.
+ optional nvidia_ace.audio.v1.AudioHeader audio_header = 1;
+ // Metadata containing the blendshape and joints names.
+ // This defines the names of the blendshapes and joints flowing through a stream.
+ optional nvidia_ace.animation_data.v1.SkelAnimationHeader
+ skel_animation_header = 2;
+
+ // Time codes indicate the relative progression of an animation data, audio
+ // clip, etc. The unit is seconds. In addition, we also need an absolute time
+ // reference shared across services. The start time is stored in time codes
+ // elapsed since the Unix time epoch. start_time_code_since_epoch = `Unix
+ // timestamp in seconds`. NTP should be good enough to synchronize clocks
+ // across nodes. From Wikipedia: NTP can usually maintain time to within tens
+ // of milliseconds over the public Internet, and can achieve better than one
+ // millisecond accuracy in local area networks under ideal conditions.
+ // Alternatively, there is PTP.
+ double start_time_code_since_epoch = 3;
+
+ // A generic metadata field to attach use case specific data (e.g. session id,
+ // or user id?) map<string, string> metadata = 4; map<string,
+ // google.protobuf.Any> metadata = 4;
+}
+
+message AnimationDataStream {
+ // The header must be sent as the first message.
+ // One or more animation data message must be sent.
+ // The status must be sent last and may be sent in between.
+ oneof stream_part {
+ // The header must be sent as the first message.
+ AnimationDataStreamHeader animation_data_stream_header = 1;
+ // Then one or more animation data message must be sent.
+ nvidia_ace.animation_data.v1.AnimationData animation_data = 2;
+ // The event may be sent in between.
+ Event event = 3;
+ // The status must be sent last and may be sent in between.
+ nvidia_ace.status.v1.Status status = 4;
+ }
+}
+//nvidia_ace.controller.v1
+//v1.0.0
\ No newline at end of file
diff --git a/api/_lib/a2f-protos/nvidia_ace.emotion_with_timecode.v1.proto b/api/_lib/a2f-protos/nvidia_ace.emotion_with_timecode.v1.proto
new file mode 100644
index 000000000..5e74aac57
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.emotion_with_timecode.v1.proto
@@ -0,0 +1,47 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.emotion_with_timecode.v1;
+
+// Emotions with time code allow clients to control when emotions are
+// being applied to an audio clip
+// Example 1:
+// time_code = 0.0
+// emotion = { "joy" : 1.0 }
+// At the start of the audio clip, the joy emotion will be applied
+// at its maximum intensity.
+// Example 2:
+// time_code = 3.0
+// emotion = { "outofbreath" : 0.5 }
+// At the 3-second mark in the audio clip, the outofbreath emotion
+// will be applied at half intensity.
+message EmotionWithTimeCode {
+ // Time when to apply the selected emotion
+ // This time is relative to the beginning of the audio clip
+ double time_code = 1;
+ // This maps the emotion names to the corresponding emotion strength
+ // Missing emotion values will be set to 0.0
+ // The following emotions can be set:
+ // "amazement", "anger", "cheekiness", "disgust", "fear",
+ // "grief", "joy", "outofbreath", "pain", "sadness"
+ // Emotion values must be set between 0.0 and 1.0
+ map<string, float> emotion = 2;
+}
+//nvidia_ace.emotion_with_timecode.v1
+//v1.0.0
\ No newline at end of file
diff --git a/api/_lib/a2f-protos/nvidia_ace.services.a2f_controller.v1.proto b/api/_lib/a2f-protos/nvidia_ace.services.a2f_controller.v1.proto
new file mode 100644
index 000000000..e64b04c4e
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.services.a2f_controller.v1.proto
@@ -0,0 +1,33 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.services.a2f_controller.v1;
+
+import "nvidia_ace.controller.v1.proto";
+import "nvidia_ace.animation_id.v1.proto";
+import "google/protobuf/empty.proto";
+
+service A2FControllerService {
+ // Will process a single audio clip and answer animation data
+ // in a burst.
+ rpc ProcessAudioStream(stream nvidia_ace.controller.v1.AudioStream)
+ returns (stream nvidia_ace.controller.v1.AnimationDataStream) {}
+}
+//nvidia_ace.services.a2f_controller.v1
+//v1.0.0
\ No newline at end of file
diff --git a/api/_lib/a2f-protos/nvidia_ace.status.v1.proto b/api/_lib/a2f-protos/nvidia_ace.status.v1.proto
new file mode 100644
index 000000000..b1a3bff13
--- /dev/null
+++ b/api/_lib/a2f-protos/nvidia_ace.status.v1.proto
@@ -0,0 +1,39 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package nvidia_ace.status.v1;
+
+// This status message indicates the result of an operation
+// Refer to the rpc using it for more information
+message Status {
+ enum Code {
+ SUCCESS = 0;
+ INFO = 1;
+ WARNING = 2;
+ ERROR = 3;
+ }
+ // Type of message returned by the service
+ // Example value: SUCCESS
+ Code code = 1;
+ // Message returned by the service
+ // Example value: "Audio processing completed successfully!"
+ string message = 2;
+}
+//nvidia_ace.status.v1
+//v1.0.0
\ No newline at end of file
diff --git a/api/_lib/avatar-agent.js b/api/_lib/avatar-agent.js
index ba8d2f701..b993011bf 100644
--- a/api/_lib/avatar-agent.js
+++ b/api/_lib/avatar-agent.js
@@ -61,11 +61,24 @@ export async function provisionAvatarAgent({ userId, avatarId, avatarName }) {
}
return agentId;
} catch (err) {
- console.error('[avatar-agent] auto-agent failed', {
- avatarId,
- userId,
- error: err?.message,
- });
+ // This path is idempotent, fire-and-forget, and self-healing: the claim is
+ // guarded by NOT EXISTS and re-runs the next time the user opens their
+ // avatar/agent, so a transient DB stall (Neon scale-to-zero wake, a
+ // connection blip — see db-retry.js) leaves nothing broken and the avatar
+ // was already created. Logging that at error level trips false alarms, so
+ // classify it the same way db-retry does and warn instead; reserve error
+ // for genuinely unexpected failures (constraint violations, bugs).
+ const transient =
+ err?.code === 'DB_TIMEOUT' ||
+ /fetch failed|connecting to database|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up|terminat/i.test(
+ err?.message || '',
+ );
+ const detail = { avatarId, userId, error: err?.message };
+ if (transient) {
+ console.warn('[avatar-agent] auto-agent provisioning deferred (transient DB stall — retries on next interaction)', detail);
+ } else {
+ console.error('[avatar-agent] auto-agent failed', detail);
+ }
return null;
}
}
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 142a2ea76..29da13ebd 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -281,6 +281,28 @@ export const env = {
return opt('NVIDIA_ASR_FUNCTION_ID');
},
+ // NVCF function id for the hosted Audio2Face-3D model used by the free facial-
+ // animation lane (api/_lib/a2f-nvidia.js, api/a2f.js) that turns Magpie speech
+ // into a per-frame ARKit blendshape track. Unlike the ASR id this is OPTIONAL:
+ // the module defaults to the published "James" model id from NVIDIA's official
+ // sample, so the lane works with only NVIDIA_API_KEY set. Override to pin a
+ // different model (Mark/Claire) — discover live ids with
+ // `node scripts/verify-nvidia-a2f.mjs --list`.
+ get NVIDIA_A2F_FUNCTION_ID() {
+ return opt('NVIDIA_A2F_FUNCTION_ID');
+ },
+
+ // Optional override for the hosted NVIDIA Cosmos world-model invoke URL used by
+ // the Cosmos text→world video lane (api/_providers/nvidia-cosmos.js, api/cosmos.js).
+ // Defaults to the published genai gateway path for cosmos-predict
+ // (https://ai.api.nvidia.com/v1/genai/nvidia/cosmos-predict1-7b); set this only
+ // to pin a different Cosmos model/version or a self-hosted NIM without a code
+ // deploy. Confirm the live contract for an account with
+ // `node scripts/verify-nvidia-cosmos.mjs`. Auth reuses NVIDIA_API_KEY.
+ get NVIDIA_COSMOS_INVOKE_URL() {
+ return opt('NVIDIA_COSMOS_INVOKE_URL');
+ },
+
// IBM watsonx.ai (Granite foundation models) — selectable brain in
// /api/chat and /api/brain/chat. Requires the API key AND a project (or
// space) id; the shared client in _lib/watsonx.js exchanges the key for an
diff --git a/api/_lib/migrations/20260625120000_agent_wallet_intents.sql b/api/_lib/migrations/20260625120000_agent_wallet_intents.sql
new file mode 100644
index 000000000..bdde05db2
--- /dev/null
+++ b/api/_lib/migrations/20260625120000_agent_wallet_intents.sql
@@ -0,0 +1,74 @@
+begin;
+
+-- Wallet Intents — the programmable, conversational money layer.
+--
+-- An intent is an owner-owned policy that makes an agent's custodial wallet
+-- *react* to real events: "tip back anyone who tips me more than 0.1 SOL, half
+-- of what they sent", "when my balance is under 0.05 SOL, freeze spending and DM
+-- me", "every Friday, withdraw profit above 2 SOL to my main wallet", "split 10%
+-- of everything I earn to my other agent". The owner writes the rule in plain
+-- language; an LLM compiles it into a STRICT structured intent; the cron engine
+-- (api/_lib/wallet-intents.js) evaluates enabled intents on their trigger and
+-- executes through the SAME owner-authorized, spend-policy-gated, audited signing
+-- paths every other outbound action uses. An intent can never exceed the agent's
+-- spend policy (api/_lib/agent-trade-guards.js enforceSpendLimit) and every
+-- execution writes an agent_custody_events row with meta.intent_id.
+--
+-- One agent = one owner (agent_identities.user_id, immutable). Intents are
+-- owner-only: only the owner may create, arm, edit, pause, or delete one, and the
+-- executor re-checks ownership against agent_identities at fire time. user_id is
+-- the owner at creation; the executor always trusts the live agent_identities row.
+--
+-- Triggers (trigger_type): on_tip_received, on_income, on_balance_below,
+-- on_schedule, on_launch_matching, on_stream_started.
+-- Actions (action_type): tip, transfer, buy, snipe, withdraw, split_income,
+-- freeze, notify.
+-- The only coin the platform promotes is $THREE; a mint named for a buy/snipe is
+-- the owner's own runtime input, never hardcoded here.
+
+create table if not exists agent_wallet_intents (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null,
+ user_id uuid not null, -- owner at creation (executor trusts live agent_identities.user_id)
+ title text not null default '', -- short owner-facing label
+ trigger_type text not null, -- on_tip_received | on_income | on_balance_below | on_schedule | on_launch_matching | on_stream_started
+ trigger_config jsonb not null default '{}'::jsonb, -- e.g. { min_sol, threshold_sol, weekday, hour, creator, max_mcap_usd }
+ action_type text not null, -- tip | transfer | buy | snipe | withdraw | split_income | freeze | notify
+ action_config jsonb not null default '{}'::jsonb, -- e.g. { pct, amount_sol, destination, destination_label, mint, slippage_pct, message }
+ limits jsonb not null default '{}'::jsonb, -- { per_action_usd, daily_usd, total_usd } — clamped under the agent spend policy
+ network text not null default 'mainnet', -- mainnet | devnet
+ enabled boolean not null default true, -- armed?
+ public_trait boolean not null default false, -- owner opt-in: advertise the BEHAVIOR (never the rule/caps) on the public persona
+ source_text text, -- the plain-language instruction the owner described
+ readback text, -- one-sentence confirmable summary
+ fire_count integer not null default 0, -- lifetime real executions
+ spent_usd numeric not null default 0, -- lifetime USD moved by this intent (real, from custody rows)
+ last_fired_at timestamptz,
+ last_status text, -- ok | skipped | paused | error | notified
+ last_note text,
+ last_signature text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- Owner-facing list (newest first) for one agent.
+create index if not exists agent_wallet_intents_agent
+ on agent_wallet_intents (agent_id, created_at desc);
+
+-- Cron scans: "every enabled intent of this trigger kind" (schedule/balance/launch
+-- sweeps) and the tip/income/stream hot path ("enabled intents for THIS agent of
+-- this trigger kind"). Partial on enabled keeps the working set small.
+create index if not exists agent_wallet_intents_trigger
+ on agent_wallet_intents (trigger_type, enabled)
+ where enabled = true;
+
+create index if not exists agent_wallet_intents_agent_trigger
+ on agent_wallet_intents (agent_id, trigger_type, enabled)
+ where enabled = true;
+
+-- Public persona traits the owner opted to advertise (read-only behavior badges).
+create index if not exists agent_wallet_intents_public
+ on agent_wallet_intents (agent_id)
+ where public_trait = true;
+
+commit;
diff --git a/api/_lib/migrations/20260625140000_patronage.sql b/api/_lib/migrations/20260625140000_patronage.sql
new file mode 100644
index 000000000..dff716441
--- /dev/null
+++ b/api/_lib/migrations/20260625140000_patronage.sql
@@ -0,0 +1,75 @@
+begin;
+
+-- Patronage, Relationships & Tip-to-Unlock
+-- ========================================
+-- A tip on three.ws is not a dead-end transaction. Because every agent has a
+-- persona + real memory, support BUILDS A RELATIONSHIP: the agent remembers its
+-- patrons, greets its top supporters by name, and unlocks real, gated
+-- capabilities for them. The patron ledger itself is DERIVED, not stored — it is
+-- aggregated live from the real on-chain custody ledger (agent_custody_events:
+-- event_type IN ('tip','stream'), grouped by the verified on-chain payer
+-- meta->>'from'). These two tables hold only the owner's PERK CONFIG and each
+-- patron's PRIVACY/MILESTONE STATE; no amount, level, or count is ever stored
+-- here — those are always recomputed from chain truth in api/_lib/patronage.js.
+
+-- ── Owner-defined perk ladder ──────────────────────────────────────────────────
+-- Each row is one rung: "support me with >= $threshold_usd and unlock <perk>".
+-- Only the agent's owner can write these (owner auth + CSRF in api/agents/patronage.js).
+-- Access is ENFORCED server-side by recomputing the supporter's verified on-chain
+-- support on every gated request — never trusted from the client. perk_type maps
+-- to capabilities that really exist:
+-- greeting — an exclusive chat greeting/mode the agent uses for this patron
+-- lore — a hidden memory/lore entry revealed only to patrons at tier
+-- skill — a premium agent skill the patron may use for free (payload.skill)
+-- launch_access — early/priority access to this agent's coin launches
+-- badge — a patron badge rendered on the public patron wall (payload.label)
+create table if not exists agent_patron_perks (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ perk_type text not null check (perk_type in ('greeting','lore','skill','launch_access','badge')),
+ threshold_usd numeric not null check (threshold_usd >= 0),
+ title text not null,
+ description text,
+ payload jsonb not null default '{}'::jsonb, -- type-specific: { body } | { skill } | { label }
+ is_active boolean not null default true,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- The Support surface reads a single agent's ladder ordered by threshold.
+create index if not exists agent_patron_perks_agent
+ on agent_patron_perks (agent_id, threshold_usd)
+ where is_active;
+
+-- ── Per-patron privacy + milestone state ───────────────────────────────────────
+-- Keyed by the patron's on-chain wallet (the spoof-proof identity = the verified
+-- `from` of their support). Holds only:
+-- hidden — the patron opted OUT of the public wall (set by the patron,
+-- proven by an ed25519 signature over a challenge; their support
+-- still counts toward totals, they just aren't displayed).
+-- milestone_level — the highest patron level we've already written a relationship
+-- MEMORY for, so a level-up writes exactly one memory (dedupe).
+-- display_name — cached SNS/.sol reverse-resolution, to avoid re-resolving on
+-- every read of the wall.
+create table if not exists agent_patron_prefs (
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ patron_wallet text not null,
+ hidden boolean not null default false,
+ milestone_level text,
+ display_name text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ primary key (agent_id, patron_wallet)
+);
+
+comment on table agent_patron_perks is
+ 'Owner-defined tip-to-unlock perk ladder for an agent. Owner-only writes. '
+ 'Perk access is enforced server-side by recomputing the supporter''s verified '
+ 'on-chain support (agent_custody_events tip+stream grouped by payer) against '
+ 'threshold_usd on every gated request — never trusted from the client.';
+comment on table agent_patron_prefs is
+ 'Per-patron privacy (wall opt-out, proven by wallet signature) and milestone '
+ 'dedupe state. Patron identity = on-chain wallet. No support amount/level is '
+ 'stored — those derive from the custody ledger in api/_lib/patronage.js.';
+
+commit;
diff --git a/api/_lib/patronage.js b/api/_lib/patronage.js
new file mode 100644
index 000000000..1b9857d3e
--- /dev/null
+++ b/api/_lib/patronage.js
@@ -0,0 +1,346 @@
+// Patronage — relationships derived from real on-chain support
+// =============================================================
+// The single source of truth for patron levels, perk entitlement, seasons, and
+// the relationship-memory pipeline. Every number it returns is DERIVED LIVE from
+// the real custody ledger (agent_custody_events) — there is no stored balance,
+// level, or count anywhere. A patron's identity is their on-chain wallet: the
+// verified `from` of their tips/streams (api/agents/solana-wallet.js records it
+// only after independently re-verifying the transfer on-chain).
+//
+// Consumed by:
+// api/agents/patronage.js — the Support surface, owner CRM, unlock gating
+// api/agents/solana-wallet.js — writes a relationship memory on a level-up
+// api/agents/talk.js — greets recognized patrons; frees patron-perk skills
+
+import { sql } from './db.js';
+import { reverseLookupAddress } from '../../src/solana/sns.js';
+
+// ── Levels (documented thresholds) ──────────────────────────────────────────────
+// Cumulative lifetime support in USD, normalized at the moment of each transfer
+// (SOL priced to USD, USDC 1:1). Thresholds are intentionally public and stable so
+// the ladder a visitor sees is the ladder that gates real perks. `minUsd` is the
+// INCLUSIVE floor; `supporter` is anyone who has given more than $0.
+export const PATRON_LEVELS = Object.freeze([
+ { key: 'supporter', label: 'Supporter', minUsd: 0, glyph: '◔', accent: '#c4b5fd' },
+ { key: 'patron', label: 'Patron', minUsd: 10, glyph: '◑', accent: '#a78bfa' },
+ { key: 'champion', label: 'Champion', minUsd: 50, glyph: '◕', accent: '#8b5cf6' },
+ { key: 'benefactor', label: 'Benefactor', minUsd: 250, glyph: '●', accent: '#7c3aed' },
+]);
+
+/** The level for a cumulative USD figure, or null when there is no support yet. */
+export function levelForUsd(usd) {
+ const n = Number(usd) || 0;
+ if (n <= 0) return null;
+ let cur = PATRON_LEVELS[0];
+ for (const lvl of PATRON_LEVELS) if (n >= lvl.minUsd) cur = lvl;
+ return cur;
+}
+
+export function levelIndex(key) {
+ return PATRON_LEVELS.findIndex((l) => l.key === key);
+}
+
+/**
+ * The next level the viewer has NOT yet reached — their goal. A wallet with $0
+ * support hasn't even reached Supporter (which needs any positive support), so its
+ * goal is Supporter; once benefactor is reached this returns null.
+ */
+export function nextLevelForUsd(usd) {
+ const n = Number(usd) || 0;
+ for (const lvl of PATRON_LEVELS) {
+ const reached = n > 0 && n >= lvl.minUsd;
+ if (!reached) return lvl;
+ }
+ return null;
+}
+
+/** Progress toward the next level: { current, next, pct, remainingUsd }. */
+export function progressForUsd(usd) {
+ const n = Number(usd) || 0;
+ const current = levelForUsd(n);
+ const next = nextLevelForUsd(n);
+ if (!next) return { current, next: null, pct: 1, remainingUsd: 0 };
+ const floor = current ? current.minUsd : 0;
+ const span = next.minUsd - floor || next.minUsd || 1;
+ const pct = Math.max(0, Math.min(1, (n - floor) / span));
+ return { current, next, pct, remainingUsd: Math.max(0, next.minUsd - n) };
+}
+
+// ── Seasons / epochs (monthly) ──────────────────────────────────────────────────
+// A live competitive window computed purely from the calendar in UTC — no stored
+// season rows, so rollover is automatic and historical aggregation just changes
+// the `since` bound. There is always a season in flight to compete for.
+export function currentSeason(now = new Date()) {
+ const y = now.getUTCFullYear();
+ const m = now.getUTCMonth();
+ const startsAt = new Date(Date.UTC(y, m, 1));
+ const endsAt = new Date(Date.UTC(y, m + 1, 1));
+ const key = `${y}-${String(m + 1).padStart(2, '0')}`;
+ const label = startsAt.toLocaleString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
+ return { key, label, startsAt: startsAt.toISOString(), endsAt: endsAt.toISOString() };
+}
+
+// ── Patron ledger (derived from the real custody ledger) ─────────────────────────
+// Group every verified inbound transfer to this agent by its on-chain payer and
+// sum the normalized USD. Tips and stream settlements are the inbound events that
+// carry a verified `from` (api/agents/solana-wallet.js). Unpriceable rows count as
+// $0 toward the total but still as a support event, so the count never lies.
+
+/**
+ * Aggregate an agent's supporters from chain truth.
+ * @param {string} agentId
+ * @param {{ network?:string, since?:string|null, limit?:number|null, offset?:number }} [opts]
+ * @returns {Promise<Array<{wallet:string, usd:number, supportCount:number, firstAt:string, lastAt:string}>>}
+ */
+export async function aggregatePatrons(agentId, opts = {}) {
+ const { network = 'mainnet', since = null, limit = null, offset = 0 } = opts;
+ const rows = await sql`
+ SELECT meta->>'from' AS wallet,
+ COALESCE(SUM(usd), 0)::float8 AS usd,
+ COUNT(*)::int AS support_count,
+ MIN(created_at) AS first_at,
+ MAX(created_at) AS last_at
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${network}
+ AND event_type IN ('tip', 'stream')
+ AND meta->>'from' IS NOT NULL
+ AND meta->>'from' <> ''
+ AND (${since}::timestamptz IS NULL OR created_at >= ${since})
+ GROUP BY meta->>'from'
+ ORDER BY usd DESC, support_count DESC, MIN(created_at) ASC
+ ${limit != null ? sql`LIMIT ${Number(limit)} OFFSET ${Number(offset) || 0}` : sql``}
+ `;
+ return rows.map((r) => ({
+ wallet: r.wallet,
+ usd: Number(r.usd) || 0,
+ supportCount: r.support_count,
+ firstAt: r.first_at ? new Date(r.first_at).toISOString() : null,
+ lastAt: r.last_at ? new Date(r.last_at).toISOString() : null,
+ }));
+}
+
+/** Total distinct patrons + total normalized USD supported (lifetime or season). */
+export async function patronTotals(agentId, { network = 'mainnet', since = null } = {}) {
+ const [row] = await sql`
+ SELECT COUNT(DISTINCT meta->>'from')::int AS patrons,
+ COALESCE(SUM(usd), 0)::float8 AS usd,
+ COUNT(*)::int AS supports
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${network}
+ AND event_type IN ('tip', 'stream')
+ AND meta->>'from' IS NOT NULL
+ AND meta->>'from' <> ''
+ AND (${since}::timestamptz IS NULL OR created_at >= ${since})
+ `;
+ return { patrons: row?.patrons || 0, usd: Number(row?.usd) || 0, supports: row?.supports || 0 };
+}
+
+/** One wallet's standing on one agent, fully derived. usd=0 when not a patron. */
+export async function patronStanding(agentId, wallet, { network = 'mainnet' } = {}) {
+ if (!wallet) return { wallet: null, usd: 0, supportCount: 0, firstAt: null, lastAt: null, level: null, progress: progressForUsd(0) };
+ const [row] = await sql`
+ SELECT COALESCE(SUM(usd), 0)::float8 AS usd,
+ COUNT(*)::int AS support_count,
+ MIN(created_at) AS first_at,
+ MAX(created_at) AS last_at
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${network}
+ AND event_type IN ('tip', 'stream')
+ AND meta->>'from' = ${wallet}
+ `;
+ const usd = Number(row?.usd) || 0;
+ return {
+ wallet,
+ usd,
+ supportCount: row?.support_count || 0,
+ firstAt: row?.first_at ? new Date(row.first_at).toISOString() : null,
+ lastAt: row?.last_at ? new Date(row.last_at).toISOString() : null,
+ level: levelForUsd(usd),
+ progress: progressForUsd(usd),
+ };
+}
+
+// ── Perk ladder config ──────────────────────────────────────────────────────────
+
+export const PERK_TYPES = Object.freeze(['greeting', 'lore', 'skill', 'launch_access', 'badge']);
+
+export async function listPerks(agentId, { activeOnly = false } = {}) {
+ const rows = await sql`
+ SELECT id, perk_type, threshold_usd, title, description, payload, is_active, created_at, updated_at
+ FROM agent_patron_perks
+ WHERE agent_id = ${agentId}
+ ${activeOnly ? sql`AND is_active = true` : sql``}
+ ORDER BY threshold_usd ASC, created_at ASC
+ `;
+ return rows.map((r) => ({
+ id: r.id,
+ perkType: r.perk_type,
+ thresholdUsd: Number(r.threshold_usd) || 0,
+ title: r.title,
+ description: r.description || '',
+ payload: r.payload || {},
+ isActive: r.is_active,
+ }));
+}
+
+/**
+ * Perks a given USD level has earned. A perk is earned only by REAL support: a
+ * wallet with $0 support is not a patron and unlocks nothing, even a $0-threshold
+ * rung (which means "any supporter", not "everyone"). Used for display flags and
+ * for the signature-gated unlock alike.
+ */
+export function entitledPerks(perks, usd) {
+ const n = Number(usd) || 0;
+ if (n <= 0) return [];
+ return perks.filter((p) => p.isActive && n >= p.thresholdUsd);
+}
+
+// ── Display name (SNS reverse with a per-agent cache) ────────────────────────────
+// reverseLookupAddress hits Bonfida; we cache the resolution on agent_patron_prefs
+// so a busy wall doesn't re-resolve every wallet on every read.
+export async function resolvePatronName(agentId, wallet) {
+ if (!wallet) return null;
+ try {
+ const [pref] = await sql`
+ SELECT display_name FROM agent_patron_prefs
+ WHERE agent_id = ${agentId} AND patron_wallet = ${wallet}
+ `;
+ if (pref && pref.display_name) return pref.display_name;
+ } catch { /* fall through to live lookup */ }
+ let name = null;
+ try { name = await reverseLookupAddress(wallet); } catch { name = null; }
+ if (name) {
+ await sql`
+ INSERT INTO agent_patron_prefs (agent_id, patron_wallet, display_name, updated_at)
+ VALUES (${agentId}, ${wallet}, ${name}, now())
+ ON CONFLICT (agent_id, patron_wallet)
+ DO UPDATE SET display_name = EXCLUDED.display_name, updated_at = now()
+ `.catch(() => {});
+ }
+ return name;
+}
+
+/** The set of wallets that opted out of the public wall for this agent. */
+export async function hiddenWallets(agentId) {
+ const rows = await sql`
+ SELECT patron_wallet FROM agent_patron_prefs
+ WHERE agent_id = ${agentId} AND hidden = true
+ `;
+ return new Set(rows.map((r) => r.patron_wallet));
+}
+
+// ── Relationship memory on a level-up (the magic) ────────────────────────────────
+// When a patron crosses into a NEW level, write a real agent memory through the
+// same store the chat reads, so the agent naturally references the relationship.
+// Idempotent per level via agent_patron_prefs.milestone_level — a re-tip at the
+// same level writes nothing. Best-effort: a failure never blocks tip recording.
+
+const SHORT = (w) => (w && w.length > 9 ? `${w.slice(0, 4)}…${w.slice(-4)}` : w || 'someone');
+
+/**
+ * Recompute a patron's standing and, if they just reached a higher level than the
+ * last one we recorded a memory for, write a relationship memory + update state.
+ * @returns {Promise<{wrote:boolean, level:string|null}>}
+ */
+export async function maybeWritePatronMemory({ agentId, wallet, network = 'mainnet' }) {
+ if (!agentId || !wallet) return { wrote: false, level: null };
+ let standing;
+ try {
+ standing = await patronStanding(agentId, wallet, { network });
+ } catch {
+ return { wrote: false, level: null };
+ }
+ if (!standing.level) return { wrote: false, level: null };
+
+ const [pref] = await sql`
+ SELECT milestone_level FROM agent_patron_prefs
+ WHERE agent_id = ${agentId} AND patron_wallet = ${wallet}
+ `.catch(() => [null]);
+ const prevIdx = pref?.milestone_level ? levelIndex(pref.milestone_level) : -1;
+ const nowIdx = levelIndex(standing.level.key);
+ if (nowIdx <= prevIdx) return { wrote: false, level: standing.level.key };
+
+ const name = await resolvePatronName(agentId, wallet);
+ const who = name ? `${name} (${SHORT(wallet)})` : SHORT(wallet);
+ const usdStr = standing.usd >= 1 ? `$${standing.usd.toFixed(2)}` : `$${standing.usd.toFixed(4)}`;
+ const content =
+ `Patron ${who} has supported me with ${usdStr} in total across ${standing.supportCount} ` +
+ `${standing.supportCount === 1 ? 'gift' : 'gifts'} and is now a ${standing.level.label}. ` +
+ `When ${name || 'this supporter'} talks to me, greet them warmly by name and thank them ` +
+ `sincerely for their support — they are one of my real patrons.`;
+
+ try {
+ await sql`
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, tier, pinned, updated_at)
+ VALUES (
+ ${agentId}, 'user', ${content},
+ ${['patron', 'relationship', standing.level.key]},
+ ${JSON.stringify({ kind: 'patron_milestone', patron_wallet: wallet, level: standing.level.key, usd: standing.usd, name: name || null })}::jsonb,
+ 0.85, 'working', false, now()
+ )
+ `;
+ await sql`
+ INSERT INTO agent_patron_prefs (agent_id, patron_wallet, milestone_level, display_name, updated_at)
+ VALUES (${agentId}, ${wallet}, ${standing.level.key}, ${name || null}, now())
+ ON CONFLICT (agent_id, patron_wallet)
+ DO UPDATE SET milestone_level = EXCLUDED.milestone_level,
+ display_name = COALESCE(EXCLUDED.display_name, agent_patron_prefs.display_name),
+ updated_at = now()
+ `;
+ return { wrote: true, level: standing.level.key };
+ } catch {
+ return { wrote: false, level: standing.level.key };
+ }
+}
+
+/**
+ * The agent's patron-relationship context for the chat system prompt: the recent
+ * milestone memories (so the agent can greet any recognized patron by name), plus
+ * — when the caller's own wallet is known — an explicit "this user is patron X"
+ * line. Pure read; safe for the public talk endpoint.
+ */
+export async function patronChatContext(agentId, callerWallet, { network = 'mainnet' } = {}) {
+ let memories = [];
+ try {
+ memories = await sql`
+ SELECT content, context FROM agent_memories
+ WHERE agent_id = ${agentId}
+ AND tags @> ARRAY['patron']::text[]
+ AND (expires_at IS NULL OR expires_at > now())
+ ORDER BY salience DESC, created_at DESC
+ LIMIT 8
+ `;
+ } catch { memories = []; }
+
+ let caller = null;
+ if (callerWallet) {
+ try {
+ const standing = await patronStanding(agentId, callerWallet, { network });
+ if (standing.level) {
+ const name = await resolvePatronName(agentId, callerWallet).catch(() => null);
+ caller = { ...standing, name };
+ }
+ } catch { caller = null; }
+ }
+
+ if (!memories.length && !caller) return null;
+
+ const lines = ['## Your patrons (real on-chain supporters)'];
+ if (memories.length) {
+ lines.push('You remember these relationships — reference them naturally, never invent one:');
+ for (const m of memories) lines.push(`- ${m.content}`);
+ }
+ if (caller) {
+ const usdStr = caller.usd >= 1 ? `$${caller.usd.toFixed(2)}` : `$${caller.usd.toFixed(4)}`;
+ const who = caller.name ? `${caller.name} (${SHORT(caller.wallet)})` : SHORT(caller.wallet);
+ lines.push(
+ `The user talking to you RIGHT NOW is ${who}, a ${caller.level.label} who has supported you with ` +
+ `${usdStr}. Open by greeting them warmly by name and thanking them for their support.`,
+ );
+ }
+ lines.push('Never fabricate a patron relationship that is not listed above.');
+ return lines.join('\n');
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 67c309653..7bc0f26d8 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -652,6 +652,17 @@ export const limits = {
getLimiter('asr:user', { limit: 60, window: '1 h', critical: true }).limit(userId),
asrIp: (ip) =>
getLimiter('asr:ip', { limit: 15, window: '1 h', critical: true }).limit(ip),
+ // NVIDIA Audio2Face-3D (api/a2f) — free upstream but credit-metered, and each
+ // call streams a full speech clip through a bidirectional gRPC stream the
+ // server holds in memory while collecting the blendshape track. Meter per
+ // principal like the other free NVIDIA lanes; the per-IP bucket is tighter
+ // since the optional text→speech→animation path also burns a Magpie synthesis.
+ // Critical so a missing Redis in prod fails closed rather than leaving an open
+ // animation drain.
+ a2fUser: (userId) =>
+ getLimiter('a2f:user', { limit: 40, window: '1 h', critical: true }).limit(userId),
+ a2fIp: (ip) =>
+ getLimiter('a2f:ip', { limit: 10, window: '1 h', critical: true }).limit(ip),
// NVIDIA NIM vision (api/vision) — free upstream but credit-metered, and each
// call carries an image the server may relay to the NVCF asset store. Meter
// per principal like the other free NVIDIA lanes; critical so it fails closed
diff --git a/api/_lib/strip-reasoning.js b/api/_lib/strip-reasoning.js
new file mode 100644
index 000000000..3affef915
--- /dev/null
+++ b/api/_lib/strip-reasoning.js
@@ -0,0 +1,121 @@
+// Reasoning-trace stripper for model output.
+//
+// Several open reasoning models (NVIDIA Nemotron, DeepSeek-R1, QwQ, and friends)
+// emit their chain-of-thought inline, wrapped in <think>…</think> (or
+// <thinking>, <reason>, <reasoning>) before the actual answer. That trace is
+// useful internally but must never reach a chat UI — it leaks the model's
+// scratch work and reads as broken output.
+//
+// This module removes those tagged blocks. Two entry points:
+//
+// • stripReasoning(text) — clean a complete string (trimmed).
+// • createReasoningStripper() — a streaming filter for token-by-token
+// output, where a tag can span SSE chunk
+// boundaries. push(chunk) returns the safe
+// text to emit so far; flush() returns any
+// trailing safe text once the stream ends.
+//
+// The streaming filter holds back only the minimal tail that could be the start
+// of a tag, so normal text flows through with near-zero latency and a tag split
+// across chunks (e.g. "<thi" + "nk>") is still caught.
+
+const OPENERS = ['<think>', '<thinking>', '<reason>', '<reasoning>'];
+const CLOSERS = ['</think>', '</thinking>', '</reason>', '</reasoning>'];
+
+// Earliest occurrence of any tag in `tags` within the (already lowercased)
+// haystack. Returns { i, tag } with i === -1 when none is present.
+function earliestTag(hayLower, tags) {
+ let best = -1;
+ let bestTag = null;
+ for (const t of tags) {
+ const i = hayLower.indexOf(t);
+ if (i !== -1 && (best === -1 || i < best)) {
+ best = i;
+ bestTag = t;
+ }
+ }
+ return { i: best, tag: bestTag };
+}
+
+// Length of the longest suffix of `sLower` that is a proper, non-empty prefix of
+// some tag in `tags`. That suffix might be the beginning of a tag whose
+// remainder arrives in the next chunk, so the streaming filter must hold it back
+// rather than emit (when scanning for openers) or rescan it (for closers).
+function partialTailLength(sLower, tags) {
+ let max = 0;
+ for (const t of tags) {
+ const lim = Math.min(t.length - 1, sLower.length);
+ for (let k = lim; k > 0; k--) {
+ if (sLower.endsWith(t.slice(0, k))) {
+ if (k > max) max = k;
+ break;
+ }
+ }
+ }
+ return max;
+}
+
+// Streaming reasoning-trace filter. Stateful across calls.
+// push(chunk) -> string safe text to emit for this chunk (may be '')
+// flush() -> string trailing safe text after the final chunk
+export function createReasoningStripper() {
+ let buffer = '';
+ let inside = false; // currently inside a reasoning block (content discarded)
+
+ function push(chunk) {
+ if (!chunk) return '';
+ buffer += chunk;
+ let out = '';
+ for (;;) {
+ const lower = buffer.toLowerCase();
+ if (!inside) {
+ const { i, tag } = earliestTag(lower, OPENERS);
+ if (i !== -1) {
+ out += buffer.slice(0, i); // text before the opener is real
+ buffer = buffer.slice(i + tag.length);
+ inside = true;
+ continue;
+ }
+ // No complete opener. Emit everything except a tail that could be
+ // the start of one arriving next chunk.
+ const keep = partialTailLength(lower, OPENERS);
+ out += buffer.slice(0, buffer.length - keep);
+ buffer = keep ? buffer.slice(buffer.length - keep) : '';
+ break;
+ }
+ const { i, tag } = earliestTag(lower, CLOSERS);
+ if (i !== -1) {
+ buffer = buffer.slice(i + tag.length); // drop trace + closer
+ inside = false;
+ continue;
+ }
+ // Still inside the trace: discard it, but keep a tail that could be the
+ // start of a closer split across chunks.
+ const keep = partialTailLength(lower, CLOSERS);
+ buffer = keep ? buffer.slice(buffer.length - keep) : '';
+ break;
+ }
+ return out;
+ }
+
+ function flush() {
+ if (inside) {
+ // Unterminated reasoning block: everything left is trace — drop it.
+ buffer = '';
+ return '';
+ }
+ const out = buffer; // any held partial tail was real text after all
+ buffer = '';
+ return out;
+ }
+
+ return { push, flush };
+}
+
+// Remove tagged reasoning blocks from a complete string and trim the result.
+// Built on the streaming filter so behavior is identical to the live chat path.
+export function stripReasoning(text) {
+ if (!text) return text ?? '';
+ const s = createReasoningStripper();
+ return (s.push(text) + s.flush()).trim();
+}
diff --git a/api/_lib/wallet-intents.js b/api/_lib/wallet-intents.js
new file mode 100644
index 000000000..13b6ff37d
--- /dev/null
+++ b/api/_lib/wallet-intents.js
@@ -0,0 +1,1141 @@
+// Wallet Intents engine — the programmable, conversational money layer.
+//
+// An intent is an owner-owned policy that makes an agent's custodial Solana
+// wallet REACT to real events. The owner describes it in plain language; an LLM
+// compiles it into a STRICT, server-validated structured intent; and the cron
+// engine here executes enabled intents on their trigger through the SAME
+// owner-authorized, spend-policy-gated, audited signing paths every other
+// outbound action uses. An intent can NEVER exceed the agent's spend policy
+// (enforceSpendLimit), and every real execution writes an agent_custody_events
+// row with meta.intent_id so the owner sees real receipts.
+//
+// Triggers : on_tip_received | on_income | on_balance_below | on_schedule
+// | on_launch_matching | on_stream_started
+// Actions : tip | transfer | buy | snipe | withdraw | split_income | freeze | notify
+//
+// $THREE is the only coin three.ws promotes. "$THREE"/"three" resolves to its
+// canonical mint; any other mint is the owner's own runtime input (a snipe
+// target), never hardcoded or recommended.
+//
+// This file deliberately reuses the building blocks proven by the Treasury
+// Autopilot engine (sendSol, swap, the gated-spend → claim → finalize custody
+// pattern) so intents move money exactly the way the rest of the wallet does.
+
+import { PublicKey } from '@solana/web3.js';
+import { sql } from './db.js';
+import { solUsdPrice, sendSol, explorerTxUrl } from './avatar-wallet.js';
+import { solanaConnection } from './agent-pumpfun.js';
+import { getSolanaAddressBalances, recoverSolanaAgentKeypair } from './agent-wallet.js';
+import {
+ getSpendLimits,
+ getTradeLimits,
+ setSpendLimits,
+ enforceSpendLimit,
+ SpendLimitError,
+ recordCustodyEvent,
+ updateCustodyEvent,
+ validateSolanaAddress,
+ lamportsToUsd,
+ SOL_FEE_HEADROOM_LAMPORTS,
+} from './agent-trade-guards.js';
+import { THREE_MINT } from './networth-model.js';
+import { resolveSolanaRecipient } from '../../src/solana/sns.js';
+import { recentPumpLaunches, enrichCreatorStats } from './pump-launch-feed.js';
+import { logAudit } from './audit.js';
+
+const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+const JUPITER_BASE = 'https://lite-api.jup.ag/swap/v1';
+const LAMPORTS_PER_SOL = 1_000_000_000n;
+const DUST_USD = 0.02;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+export const INTENT_TRIGGERS = Object.freeze([
+ 'on_tip_received',
+ 'on_income',
+ 'on_balance_below',
+ 'on_schedule',
+ 'on_launch_matching',
+ 'on_stream_started',
+]);
+
+export const INTENT_ACTIONS = Object.freeze([
+ 'tip',
+ 'transfer',
+ 'buy',
+ 'snipe',
+ 'withdraw',
+ 'split_income',
+ 'freeze',
+ 'notify',
+]);
+
+// Actions that move funds (need spend-policy enforcement + a signing keypair).
+const SPENDING_ACTIONS = new Set(['tip', 'transfer', 'buy', 'snipe', 'withdraw', 'split_income']);
+
+// ── small pure helpers ───────────────────────────────────────────────────────────
+
+function num(v, def = null) {
+ const n = Number(v);
+ return Number.isFinite(n) ? n : def;
+}
+function clamp(n, min, max) {
+ return Math.max(min, Math.min(max, n));
+}
+function posNum(v) {
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : null;
+}
+function str(v, max = 280) {
+ return typeof v === 'string' ? v.slice(0, max) : '';
+}
+function solToLamports(sol) {
+ return BigInt(Math.floor(Number(sol) * 1e9));
+}
+
+// Resolve a free-text asset reference to a canonical Solana asset. $THREE is the
+// only coin we resolve by name; everything else is SOL, USDC, a raw mint, or
+// unknown — mirrors api/agents/solana-intent.js so both speak the same language.
+export function resolveAssetToken(raw, { threeMint = THREE_MINT } = {}) {
+ const s = String(raw || '').trim();
+ if (!s) return { kind: 'none', mint: null, symbol: null };
+ const lower = s.toLowerCase().replace(/^\$/, '');
+ if (lower === 'sol' || lower === 'solana') return { kind: 'sol', mint: null, symbol: 'SOL' };
+ if (lower === 'usdc') return { kind: 'usdc', mint: null, symbol: 'USDC' };
+ if (lower === 'three') return { kind: 'three', mint: threeMint, symbol: '$THREE' };
+ if (BASE58_RE.test(s)) {
+ return { kind: s === threeMint ? 'three' : 'mint', mint: s, symbol: s === threeMint ? '$THREE' : null };
+ }
+ return { kind: 'unknown', mint: null, symbol: s };
+}
+
+// ── normalization / validation ───────────────────────────────────────────────────
+//
+// Turn a raw intent (from the LLM tool call OR the manual form) into the canonical
+// stored shape. Anything malformed degrades to a precise validation error — money
+// must never move on a guess. Returns { ok, intent } | { ok:false, error, message }.
+
+export function normalizeIntent(raw, { threeMint = THREE_MINT } = {}) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+
+ const triggerType = String(r.trigger_type || r.trigger?.type || '').trim();
+ if (!INTENT_TRIGGERS.includes(triggerType)) {
+ return { ok: false, error: 'bad_trigger', message: `unsupported trigger "${triggerType || '(none)'}"` };
+ }
+ const actionType = String(r.action_type || r.action?.type || '').trim();
+ if (!INTENT_ACTIONS.includes(actionType)) {
+ return { ok: false, error: 'bad_action', message: `unsupported action "${actionType || '(none)'}"` };
+ }
+
+ const tcfg = r.trigger_config || r.trigger || {};
+ const acfg = r.action_config || r.action || {};
+
+ // ── trigger config ──
+ const trigger = { type: triggerType };
+ if (triggerType === 'on_tip_received') {
+ trigger.min_sol = posNum(tcfg.min_sol) ?? 0;
+ } else if (triggerType === 'on_balance_below') {
+ const t = posNum(tcfg.threshold_sol);
+ if (t == null) return { ok: false, error: 'needs_threshold', message: 'a balance threshold (SOL) is required' };
+ trigger.threshold_sol = t;
+ } else if (triggerType === 'on_schedule') {
+ trigger.cadence = ['daily', 'weekly'].includes(tcfg.cadence) ? tcfg.cadence : 'weekly';
+ const wd = Number(tcfg.weekday);
+ trigger.weekday = trigger.cadence === 'weekly' ? (Number.isInteger(wd) && wd >= 0 && wd <= 6 ? wd : 5) : null;
+ const hr = Number(tcfg.hour);
+ trigger.hour = Number.isInteger(hr) && hr >= 0 && hr <= 23 ? hr : 13;
+ } else if (triggerType === 'on_launch_matching') {
+ const creator = str(tcfg.creator, 64).trim();
+ trigger.creator = creator && BASE58_RE.test(creator) ? creator : null;
+ trigger.max_mcap_usd = posNum(tcfg.max_mcap_usd);
+ trigger.min_mcap_usd = posNum(tcfg.min_mcap_usd);
+ if (!trigger.creator && trigger.max_mcap_usd == null) {
+ return { ok: false, error: 'needs_filter', message: 'a launch rule needs a creator address and/or a max market cap to match on' };
+ }
+ }
+ // on_income / on_stream_started carry no required config.
+
+ // ── action config ──
+ const action = { type: actionType };
+ if (actionType === 'freeze') {
+ // no params — the kill switch
+ } else if (actionType === 'notify') {
+ action.message = str(acfg.message, 280) || null;
+ action.channel = ['email', 'log'].includes(acfg.channel) ? acfg.channel : 'email';
+ } else if (actionType === 'buy' || actionType === 'snipe') {
+ // For on_launch_matching/snipe the mint is supplied at fire time (the matched
+ // launch); otherwise the owner names a mint/symbol to acquire.
+ const tgt = resolveAssetToken(acfg.mint || acfg.destination_or_mint || acfg.target, { threeMint });
+ action.mint = tgt.mint || (tgt.kind === 'three' ? threeMint : null);
+ action.mint_symbol = tgt.symbol || null;
+ action.amount_sol = posNum(acfg.amount_sol);
+ if (action.amount_sol == null) return { ok: false, error: 'needs_amount', message: `${actionType} needs a SOL amount to spend` };
+ const slip = num(acfg.slippage_pct);
+ action.slippage_pct = slip != null ? clamp(slip, 0, 50) : 5;
+ // For a non-launch buy the mint must be known up front.
+ if (triggerType !== 'on_launch_matching' && !action.mint) {
+ return { ok: false, error: 'needs_mint', message: 'name the token to buy ($THREE or a mint address)' };
+ }
+ } else {
+ // tip | transfer | withdraw | split_income — move SOL to a destination.
+ const pct = posNum(acfg.pct);
+ const amount = posNum(acfg.amount_sol);
+ const above = posNum(acfg.above_sol);
+ action.pct = pct != null ? clamp(pct, 0.01, 100) : null;
+ action.amount_sol = amount;
+ action.above_sol = above; // for withdraw: "profit above N SOL"
+ action.of = ['tip', 'income', 'balance'].includes(acfg.of) ? acfg.of : (pct != null ? (actionType === 'split_income' ? 'income' : 'tip') : null);
+ action.destination = str(acfg.destination, 64).trim();
+ action.destination_label = str(acfg.destination_label, 80) || null;
+
+ if (actionType === 'split_income') {
+ if (action.pct == null) return { ok: false, error: 'needs_pct', message: 'split needs a percentage of income' };
+ action.of = 'income';
+ }
+ if (actionType === 'tip' || actionType === 'transfer') {
+ if (action.pct == null && action.amount_sol == null) {
+ return { ok: false, error: 'needs_amount', message: 'a tip/transfer needs a fixed SOL amount or a percentage' };
+ }
+ }
+ if (actionType === 'withdraw') {
+ if (action.amount_sol == null && action.above_sol == null && action.pct == null) {
+ return { ok: false, error: 'needs_amount', message: 'a withdraw needs an amount, a "profit above N SOL" threshold, or a percentage' };
+ }
+ }
+ if (!action.destination) {
+ return { ok: false, error: 'needs_destination', message: `${actionType} needs a destination address or .sol name` };
+ }
+ }
+
+ // ── owner-set caps (clamped under the spend policy at execution time) ──
+ const lim = r.limits || {};
+ const limits = {
+ per_action_usd: posNum(lim.per_action_usd),
+ daily_usd: posNum(lim.daily_usd),
+ total_usd: posNum(lim.total_usd),
+ };
+
+ const intent = {
+ title: str(r.title, 80).trim() || defaultTitle(triggerType, actionType, action),
+ trigger,
+ action,
+ limits,
+ readback: str(r.readback, 280).trim() || null,
+ };
+ return { ok: true, intent };
+}
+
+function defaultTitle(triggerType, actionType, action) {
+ const T = {
+ on_tip_received: 'On a tip',
+ on_income: 'On income',
+ on_balance_below: 'On low balance',
+ on_schedule: 'On schedule',
+ on_launch_matching: 'On matching launch',
+ on_stream_started: 'On stream start',
+ }[triggerType] || 'Intent';
+ const A = {
+ tip: 'tip back',
+ transfer: 'transfer',
+ buy: `buy ${action?.mint_symbol || 'token'}`,
+ snipe: 'snipe',
+ withdraw: 'withdraw',
+ split_income: 'split income',
+ freeze: 'freeze the wallet',
+ notify: 'notify me',
+ }[actionType] || actionType;
+ return `${T} → ${A}`;
+}
+
+// One-sentence human read-back when the model didn't supply one.
+export function describeIntent(intent) {
+ if (intent.readback) return intent.readback;
+ const t = intent.trigger || {};
+ const a = intent.action || {};
+ const dest = a.destination_label || (a.destination ? `${a.destination.slice(0, 4)}…${a.destination.slice(-4)}` : '');
+ const amt = a.pct != null ? `${a.pct}%${a.of ? ` of ${a.of}` : ''}` : a.amount_sol != null ? `${a.amount_sol} SOL` : a.above_sol != null ? `anything above ${a.above_sol} SOL` : '';
+ switch (t.type) {
+ case 'on_tip_received':
+ return `When someone tips ${t.min_sol ? `more than ${t.min_sol} SOL` : 'me'}, ${a.type === 'tip' ? `tip back ${amt}` : `${a.type} ${amt} to ${dest}`}.`;
+ case 'on_income':
+ return `On income, ${a.type === 'split_income' ? `split ${amt} to ${dest}` : `${a.type} ${amt}`}.`;
+ case 'on_balance_below':
+ return `When my balance drops below ${t.threshold_sol} SOL, ${a.type === 'freeze' ? 'freeze all spending and notify me' : a.type === 'notify' ? 'notify me' : `${a.type} ${amt}`}.`;
+ case 'on_schedule':
+ return `${t.cadence === 'weekly' ? `Every ${['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][t.weekday ?? 5]}` : 'Daily'} at ${String(t.hour).padStart(2, '0')}:00 UTC, ${a.type} ${amt}${dest ? ` to ${dest}` : ''}.`;
+ case 'on_launch_matching':
+ return `When a launch matches${t.creator ? ` creator ${t.creator.slice(0, 4)}…` : ''}${t.max_mcap_usd ? ` under $${Math.round(t.max_mcap_usd / 1000)}k` : ''}, ${a.type} ${a.amount_sol} SOL.`;
+ case 'on_stream_started':
+ return `When a money stream starts, ${a.type} ${amt}${dest ? ` to ${dest}` : ''}.`;
+ default:
+ return intent.title || 'Wallet intent';
+ }
+}
+
+// ── DB access ────────────────────────────────────────────────────────────────────
+
+function rowToIntent(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ agent_id: row.agent_id,
+ title: row.title,
+ trigger: { type: row.trigger_type, ...(row.trigger_config || {}) },
+ action: { type: row.action_type, ...(row.action_config || {}) },
+ limits: row.limits || {},
+ network: row.network,
+ enabled: row.enabled,
+ public_trait: row.public_trait,
+ source_text: row.source_text,
+ readback: row.readback,
+ stats: {
+ fire_count: row.fire_count,
+ spent_usd: Number(row.spent_usd || 0),
+ last_fired_at: row.last_fired_at,
+ last_status: row.last_status,
+ last_note: row.last_note,
+ last_signature: row.last_signature,
+ },
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ };
+}
+
+export async function listIntents(agentId) {
+ const rows = await sql`
+ SELECT * FROM agent_wallet_intents WHERE agent_id = ${agentId} ORDER BY created_at DESC
+ `;
+ return rows.map(rowToIntent);
+}
+
+export async function getIntent(agentId, intentId) {
+ const [row] = await sql`SELECT * FROM agent_wallet_intents WHERE id = ${intentId} AND agent_id = ${agentId}`;
+ return rowToIntent(row);
+}
+
+export async function createIntent(agentId, userId, normalized, { network = 'mainnet', sourceText = null, publicTrait = false } = {}) {
+ const { trigger, action, limits, title, readback } = normalized;
+ const triggerConfig = { ...trigger };
+ delete triggerConfig.type;
+ const actionConfig = { ...action };
+ delete actionConfig.type;
+ const [row] = await sql`
+ INSERT INTO agent_wallet_intents
+ (agent_id, user_id, title, trigger_type, trigger_config, action_type, action_config, limits, network, source_text, readback, public_trait, enabled)
+ VALUES (
+ ${agentId}, ${userId}, ${title}, ${trigger.type}, ${JSON.stringify(triggerConfig)}::jsonb,
+ ${action.type}, ${JSON.stringify(actionConfig)}::jsonb, ${JSON.stringify(limits || {})}::jsonb,
+ ${network}, ${sourceText}, ${readback || describeIntent(normalized)}, ${!!publicTrait}, true
+ )
+ RETURNING *
+ `;
+ logAudit({ userId, action: 'wallet_intent.create', resourceId: agentId, meta: { intent_id: row.id, trigger: trigger.type, action: action.type } });
+ return rowToIntent(row);
+}
+
+export async function updateIntent(agentId, userId, intentId, patch) {
+ const existing = await getIntent(agentId, intentId);
+ if (!existing) return null;
+
+ const fields = [];
+ const next = {};
+ if ('enabled' in patch) next.enabled = patch.enabled === true;
+ if ('public_trait' in patch) next.public_trait = patch.public_trait === true;
+ if ('title' in patch) next.title = str(patch.title, 80).trim() || existing.title;
+ // A full re-validated intent may replace trigger/action/limits.
+ let normalized = null;
+ if (patch.intent) {
+ const r = normalizeIntent(patch.intent);
+ if (!r.ok) return { error: r.error, message: r.message };
+ normalized = r.intent;
+ }
+
+ const triggerConfig = normalized ? (() => { const c = { ...normalized.trigger }; delete c.type; return c; })() : null;
+ const actionConfig = normalized ? (() => { const c = { ...normalized.action }; delete c.type; return c; })() : null;
+
+ const [row] = await sql`
+ UPDATE agent_wallet_intents SET
+ enabled = ${'enabled' in next ? next.enabled : existing.enabled},
+ public_trait = ${'public_trait' in next ? next.public_trait : existing.public_trait},
+ title = ${normalized ? normalized.title : ('title' in next ? next.title : existing.title)},
+ trigger_type = ${normalized ? normalized.trigger.type : existing.trigger.type},
+ trigger_config = ${JSON.stringify(triggerConfig ?? (() => { const c = { ...existing.trigger }; delete c.type; return c; })())}::jsonb,
+ action_type = ${normalized ? normalized.action.type : existing.action.type},
+ action_config = ${JSON.stringify(actionConfig ?? (() => { const c = { ...existing.action }; delete c.type; return c; })())}::jsonb,
+ limits = ${JSON.stringify(normalized ? normalized.limits : existing.limits)}::jsonb,
+ readback = ${normalized ? (normalized.readback || describeIntent(normalized)) : existing.readback},
+ updated_at = now()
+ WHERE id = ${intentId} AND agent_id = ${agentId}
+ RETURNING *
+ `;
+ logAudit({ userId, action: 'wallet_intent.update', resourceId: agentId, meta: { intent_id: intentId } });
+ return rowToIntent(row);
+}
+
+export async function deleteIntent(agentId, userId, intentId) {
+ const rows = await sql`DELETE FROM agent_wallet_intents WHERE id = ${intentId} AND agent_id = ${agentId} RETURNING id`;
+ if (rows.length) logAudit({ userId, action: 'wallet_intent.delete', resourceId: agentId, meta: { intent_id: intentId } });
+ return rows.length > 0;
+}
+
+// Sum the REAL USD this intent has moved within a window (from custody rows it
+// wrote). Powers per-intent daily/total caps and the "remaining budget" read-out.
+async function intentSpentUsd(agentId, intentId, sinceIso = null) {
+ const [row] = await sql`
+ SELECT COALESCE(SUM(usd), 0)::float8 AS usd
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND usd IS NOT NULL
+ AND status IN ('ok', 'pending', 'confirmed')
+ AND meta->>'intent_id' = ${intentId}
+ AND (${sinceIso}::timestamptz IS NULL OR created_at > ${sinceIso}::timestamptz)
+ `;
+ return Number(row?.usd || 0);
+}
+
+// ── NL → structured intent compiler (real LLM proxy, strict tool schema) ─────────
+
+const COMPILE_TOOL = {
+ name: 'record_wallet_intent',
+ description:
+ 'Record the single standing wallet RULE the owner described, as a strict structured intent the engine can enforce. ' +
+ 'A rule is an event TRIGGER plus an ACTION the agent takes automatically when it fires, bounded by owner caps. ' +
+ 'NEVER invent an amount, destination, creator, or token. If anything required is missing or ambiguous, set ' +
+ 'needs_clarification true and ask one short question instead of guessing. The only coin the platform promotes is ' +
+ '$THREE; treat "$THREE"/"three" as that coin. A mint/creator the owner names is their own runtime input.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ title: { type: 'string', description: 'A short label, e.g. "Tip back generously".' },
+ trigger_type: {
+ type: 'string',
+ enum: INTENT_TRIGGERS,
+ description:
+ 'on_tip_received: someone tips the agent. on_income: any income arrives. on_balance_below: SOL balance drops under a floor. ' +
+ 'on_schedule: a daily/weekly time. on_launch_matching: a new pump.fun launch matches a creator and/or market cap. ' +
+ 'on_stream_started: a money stream to the agent begins.',
+ },
+ trigger_config: {
+ type: 'object',
+ description:
+ 'Fields by trigger. on_tip_received: { min_sol }. on_balance_below: { threshold_sol }. on_schedule: ' +
+ '{ cadence: "daily"|"weekly", weekday: 0-6 (Sun=0..Sat=6, Fri=5), hour: 0-23 (UTC) }. on_launch_matching: ' +
+ '{ creator: base58|null, max_mcap_usd, min_mcap_usd }.',
+ properties: {
+ min_sol: { type: 'number' },
+ threshold_sol: { type: 'number' },
+ cadence: { type: 'string', enum: ['daily', 'weekly'] },
+ weekday: { type: 'number' },
+ hour: { type: 'number' },
+ creator: { type: 'string' },
+ max_mcap_usd: { type: 'number' },
+ min_mcap_usd: { type: 'number' },
+ },
+ },
+ action_type: {
+ type: 'string',
+ enum: INTENT_ACTIONS,
+ description:
+ 'tip/transfer: send SOL to a destination. buy/snipe: spend SOL to acquire a token. withdraw: send SOL to an ' +
+ 'owner-controlled address. split_income: send a % of income to a destination. freeze: halt all spending ' +
+ '(kill switch). notify: just DM the owner.',
+ },
+ action_config: {
+ type: 'object',
+ description:
+ 'Fields by action. tip/transfer: { amount_sol } OR { pct, of: "tip"|"income"|"balance" }, destination. ' +
+ 'buy/snipe: { mint ("$THREE" or base58, omit for on_launch_matching), amount_sol, slippage_pct }. ' +
+ 'withdraw: { amount_sol } OR { above_sol } OR { pct }, destination. split_income: { pct, destination }. ' +
+ 'notify: { message }. "half of what they sent" → pct 50, of "tip".',
+ properties: {
+ amount_sol: { type: 'number' },
+ above_sol: { type: 'number' },
+ pct: { type: 'number' },
+ of: { type: 'string', enum: ['tip', 'income', 'balance'] },
+ destination: { type: 'string' },
+ mint: { type: 'string' },
+ slippage_pct: { type: 'number' },
+ message: { type: 'string' },
+ },
+ },
+ limits: {
+ type: 'object',
+ description: 'Owner caps. { per_action_usd, daily_usd, total_usd } — each in USD, omit if not stated.',
+ properties: {
+ per_action_usd: { type: 'number' },
+ daily_usd: { type: 'number' },
+ total_usd: { type: 'number' },
+ },
+ },
+ readback: { type: 'string', description: 'One plain sentence the owner can confirm, naming real amounts/destinations.' },
+ confidence: { type: 'number', description: '0..1 confidence this parse is correct.' },
+ needs_clarification: { type: 'boolean' },
+ clarifying_question: { type: 'string', description: 'When needs_clarification, the single short question to ask.' },
+ },
+ required: ['trigger_type', 'action_type', 'readback'],
+ },
+};
+
+const OPENAI_COMPILE_TOOL = {
+ type: 'function',
+ function: { name: COMPILE_TOOL.name, description: COMPILE_TOOL.description, parameters: COMPILE_TOOL.input_schema },
+};
+
+function compileSystemPrompt({ agentName, network, balanceSol, holdings, limits, tradeLimits }) {
+ const held = (holdings || []).slice(0, 6).map((h) => ` - ${h.symbol || h.mint}: ${h.ui_amount}`).join('\n');
+ return [
+ `You compile the owner's plain-language money rule into ONE structured standing intent for "${agentName || 'this agent'}", a 3D AI agent on three.ws that holds its own real Solana wallet.`,
+ 'Call record_wallet_intent exactly once. Map the request to one trigger + one action. Output nothing else.',
+ '',
+ 'Rules:',
+ '- NEVER invent an amount, destination, creator address, token, or schedule. If the rule is missing any of these, set needs_clarification=true with one short question.',
+ '- "tip back half of what they sent" → trigger on_tip_received, action tip, action_config { pct: 50, of: "tip" }, destination is the tipper (leave destination empty — the engine fills the tipper in at fire time).',
+ '- "when my balance is under X, freeze and DM me" → trigger on_balance_below { threshold_sol: X }, action freeze.',
+ '- "split 10% of everything I earn to <addr/name>" → trigger on_income, action split_income { pct: 10, destination: <addr/.sol> }.',
+ '- "every Friday withdraw profit above 2 SOL to <addr>" → trigger on_schedule { cadence: "weekly", weekday: 5, hour: 13 }, action withdraw { above_sol: 2, destination: <addr> }.',
+ '- "snipe launches from <creator> under $40k, max 1 SOL each" → trigger on_launch_matching { creator, max_mcap_usd: 40000 }, action snipe { amount_sol: 1 } (omit mint — it is the matched launch).',
+ '- The ONLY coin the platform promotes is $THREE. Treat "$THREE"/"three" as that coin. A mint/creator the owner pastes is their own input — pass it through, never invent one.',
+ '- Keep readback to one sentence the owner can confirm.',
+ '',
+ `Live context — network: ${network}; spendable SOL: ${balanceSol == null ? 'unknown' : balanceSol}.`,
+ held ? `Tokens held:\n${held}` : 'Tokens held: none detected.',
+ `Owner spend policy (hard ceilings the engine enforces): per-tx $${limits?.per_tx_usd ?? '∞'}, daily $${limits?.daily_usd ?? '∞'}. Any cap the owner sets is clamped under these.`,
+ ].join('\n');
+}
+
+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);
+ }
+}
+
+async function callAnthropicCompile({ apiKey, system, messages }) {
+ const resp = await fetchWithTimeout('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-8',
+ max_tokens: 700,
+ system,
+ messages,
+ tools: [COMPILE_TOOL],
+ tool_choice: { type: 'tool', name: COMPILE_TOOL.name },
+ }),
+ });
+ if (!resp.ok) throw new Error(`anthropic ${resp.status}`);
+ const j = await resp.json();
+ const block = (j.content || []).find((b) => b.type === 'tool_use' && b.name === COMPILE_TOOL.name);
+ if (!block) throw new Error('anthropic: no tool_use');
+ return block.input;
+}
+
+async function callOpenRouterCompile({ apiKey, system, messages }) {
+ const resp = await fetchWithTimeout('https://openrouter.ai/api/v1/chat/completions', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'content-type': 'application/json',
+ 'HTTP-Referer': 'https://three.ws',
+ 'X-Title': 'three.ws wallet intents',
+ },
+ body: JSON.stringify({
+ model: 'openai/gpt-oss-120b',
+ max_tokens: 700,
+ messages: [{ role: 'system', content: system }, ...messages],
+ tools: [OPENAI_COMPILE_TOOL],
+ tool_choice: { type: 'function', function: { name: COMPILE_TOOL.name } },
+ }),
+ });
+ if (!resp.ok) throw new Error(`openrouter ${resp.status}`);
+ const j = await resp.json();
+ const call = j.choices?.[0]?.message?.tool_calls?.[0];
+ if (!call?.function?.arguments) throw new Error('openrouter: no tool_call');
+ return JSON.parse(call.function.arguments);
+}
+
+/**
+ * Compile a plain-language rule into a validated structured intent. The model is
+ * forced to emit the tool schema; the server then re-validates every field. A
+ * missing-key deployment returns a precise "unavailable" so the client falls back
+ * to the manual form rather than faking a parse.
+ *
+ * @returns {Promise<{ ok:true, intent, provider, clarify?:string }
+ * | { ok:false, error, message, clarify?:string }>}
+ */
+export async function compileIntentFromText(text, ctx = {}) {
+ const utterance = String(text || '').trim();
+ if (!utterance) return { ok: false, error: 'empty', message: 'describe a rule first' };
+ if (utterance.length > 1000) return { ok: false, error: 'too_long', message: 'that is too long — shorten the rule' };
+
+ const anthropicKey = ctx.anthropicKey || process.env.ANTHROPIC_API_KEY;
+ const openrouterKey = ctx.openrouterKey || process.env.OPENROUTER_API_KEY;
+ if (!anthropicKey && !openrouterKey) {
+ return { ok: false, error: 'unavailable', message: 'the rule compiler is not configured on this deployment — build the rule with the form instead' };
+ }
+
+ const system = compileSystemPrompt(ctx);
+ const messages = [];
+ for (const h of (ctx.history || []).slice(-4)) {
+ if (h && (h.role === 'user' || h.role === 'assistant') && typeof h.content === 'string') {
+ messages.push({ role: h.role, content: h.content.slice(0, 800) });
+ }
+ }
+ messages.push({ role: 'user', content: utterance });
+ if (messages[0].role !== 'user') messages.shift();
+
+ let raw = null;
+ let provider = null;
+ const tried = [];
+ if (anthropicKey) {
+ try { raw = await callAnthropicCompile({ apiKey: anthropicKey, system, messages }); provider = 'anthropic'; }
+ catch (e) { tried.push(`anthropic:${e.message}`); }
+ }
+ if (!raw && openrouterKey) {
+ try { raw = await callOpenRouterCompile({ apiKey: openrouterKey, system, messages }); provider = 'openrouter'; }
+ catch (e) { tried.push(`openrouter:${e.message}`); }
+ }
+ if (!raw) {
+ console.warn('[wallet-intents] compile providers failed:', tried.join(' | '));
+ return { ok: false, error: 'parse_failed', message: 'could not parse that — rephrase, or build the rule with the form' };
+ }
+
+ if (raw.needs_clarification && raw.clarifying_question) {
+ return { ok: false, error: 'clarify', message: 'I need one more detail', clarify: str(raw.clarifying_question, 280), provider };
+ }
+
+ const norm = normalizeIntent(raw, { threeMint: THREE_MINT });
+ if (!norm.ok) {
+ return { ok: false, error: norm.error, message: norm.message, clarify: raw.clarifying_question ? str(raw.clarifying_question, 280) : null, provider };
+ }
+
+ // Resolve a .sol / name destination to a real address now, so the read-back and
+ // the stored intent both carry the real recipient. An unresolved name clarifies.
+ const a = norm.intent.action;
+ const needsDest = ['tip', 'transfer', 'withdraw', 'split_income'].includes(a.type) && a.destination;
+ // A tip-back to the tipper has an empty destination by design (filled at fire time).
+ const tipBackToTipper = a.type === 'tip' && norm.intent.trigger.type === 'on_tip_received' && !a.destination;
+ if (needsDest && !BASE58_RE.test(a.destination)) {
+ const resolved = await resolveSolanaRecipient(a.destination).catch(() => ({ address: null }));
+ if (resolved.address) {
+ a.destination_label = a.destination;
+ a.destination = resolved.address;
+ } else {
+ return { ok: false, error: 'bad_destination', message: `couldn't resolve "${a.destination}"`, clarify: `What Solana address or .sol name should "${norm.intent.title}" send to?`, provider };
+ }
+ } else if (needsDest && !a.destination_label) {
+ a.destination_label = `${a.destination.slice(0, 4)}…${a.destination.slice(-4)}`;
+ }
+ if (tipBackToTipper) a.to_tipper = true;
+
+ norm.intent.readback = norm.intent.readback || describeIntent(norm.intent);
+ return { ok: true, intent: norm.intent, provider };
+}
+
+// ── execution ─────────────────────────────────────────────────────────────────────
+//
+// Every spending action flows through gatedSpend: clamp to the agent spend policy
+// AND the intent's own caps, claim an idempotent custody row stamped with
+// intent_id, run the real transfer/swap, finalize the row. doSpend(lamports)
+// returns { signature }.
+
+async function gatedSpend({ ctx, intent, discriminator, category, usd, lamports, rowMeta, doSpend }) {
+ const { agentId, ownerId, userId, network, dryRun, now } = ctx;
+
+ // 1) intent-level caps (per-action / daily / total) — owner's own ceilings.
+ const lim = intent.limits || {};
+ if (lim.per_action_usd != null && usd > lim.per_action_usd + 1e-9) {
+ return { status: 'skipped', note: `over this rule's per-action cap ($${lim.per_action_usd})`, usd };
+ }
+ if (lim.daily_usd != null) {
+ const since = new Date(now.getTime() - 24 * 3600 * 1000).toISOString();
+ const spent = await intentSpentUsd(agentId, intent.id, since);
+ if (spent + usd > lim.daily_usd + 1e-9) {
+ return { status: 'paused', note: `would exceed this rule's daily budget ($${lim.daily_usd}; $${spent.toFixed(2)} used today)`, usd };
+ }
+ }
+ if (lim.total_usd != null) {
+ const spent = await intentSpentUsd(agentId, intent.id, null);
+ if (spent + usd > lim.total_usd + 1e-9) {
+ return { status: 'paused', note: `would exceed this rule's lifetime cap ($${lim.total_usd})`, usd };
+ }
+ }
+
+ // 2) the agent spend policy — the SAME hard ceiling every outbound path obeys.
+ try {
+ await enforceSpendLimit({ agentId, meta: ctx.meta, category: 'intent', usdValue: usd, network });
+ } catch (e) {
+ if (e instanceof SpendLimitError) return { status: 'paused', note: e.message, usd };
+ throw e;
+ }
+
+ if (dryRun) return { status: 'would_run', note: `would move ~$${usd.toFixed(2)}`, usd };
+
+ // 3) idempotent claim — one execution per (intent, discriminator).
+ const idemKey = `intent:${intent.id}:${discriminator}`;
+ const claim = await sql`
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset, amount_lamports, usd, status, idempotency_key, meta)
+ SELECT ${agentId}, ${userId ?? ownerId ?? null}, 'spend', ${category}, ${network}, 'SOL',
+ ${lamports != null ? String(lamports) : null}, ${usd ?? null}, 'pending', ${idemKey},
+ ${JSON.stringify({ ...rowMeta, intent_id: intent.id, intent_title: intent.title, trigger: intent.trigger?.type, action: intent.action?.type })}::jsonb
+ WHERE NOT EXISTS (SELECT 1 FROM agent_custody_events WHERE agent_id = ${agentId} AND idempotency_key = ${idemKey})
+ RETURNING id
+ `;
+ if (!claim.length) return { status: 'skipped', note: 'already fired for this event' };
+ const eventId = claim[0].id;
+
+ try {
+ const { signature } = await doSpend(lamports);
+ await updateCustodyEvent(eventId, { status: 'confirmed', signature, meta: { settled_at: now.toISOString() } });
+ return { status: 'ok', signature, explorer: explorerTxUrl(signature, network), usd };
+ } catch (e) {
+ await updateCustodyEvent(eventId, { status: 'failed', meta: { error: (e?.message || 'failed').slice(0, 200) } });
+ return { status: 'error', note: (e?.message || 'transaction failed').slice(0, 240), usd };
+ }
+}
+
+// Real SOL transfer from the agent's wallet → destination.
+async function transferSol({ ctx, intent, discriminator, category, lamports, rowMeta }) {
+ if (lamports <= 0n) return { status: 'skipped', note: 'amount rounds to zero' };
+ // Keep a fee headroom so the wallet never bricks itself.
+ const usable = ctx.balanceLamports - SOL_FEE_HEADROOM_LAMPORTS;
+ if (lamports > usable) return { status: 'skipped', note: 'not enough SOL after the fee buffer' };
+ const usd = await lamportsToUsd(lamports).catch(() => null);
+ if (usd == null) return { status: 'paused', note: 'SOL/USD price feed unavailable — will retry' };
+ return gatedSpend({
+ ctx, intent, discriminator, category, usd, lamports, rowMeta,
+ doSpend: async (lams) => ({ signature: await sendSol({ connection: ctx.conn, fromKeypair: ctx.keypair, to: rowMeta.destination, lamports: Number(lams), memo: `intent:${intent.action.type}`, network: ctx.network }) }),
+ });
+}
+
+// Real SOL → token swap (Jupiter, mainnet) for buy/snipe.
+async function buyToken({ ctx, intent, discriminator, mint, lamports, slippagePct }) {
+ if (ctx.network !== 'mainnet') return { status: 'skipped', note: 'buys/snipes are mainnet-only — this wallet is on devnet' };
+ if (lamports <= 0n) return { status: 'skipped', note: 'amount rounds to zero' };
+ if ((ctx.balanceLamports - SOL_FEE_HEADROOM_LAMPORTS) < lamports) return { status: 'skipped', note: 'not enough SOL after the fee buffer' };
+ const usd = await lamportsToUsd(lamports).catch(() => null);
+ if (usd == null) return { status: 'paused', note: 'SOL/USD price feed unavailable — will retry' };
+ const slippageBps = Math.round(clamp(slippagePct ?? 5, 0, 50) * 100);
+ return gatedSpend({
+ ctx, intent, discriminator, category: intent.action.type === 'snipe' ? 'snipe' : 'trade', usd, lamports,
+ rowMeta: { action: intent.action.type, mint },
+ doSpend: async (lams) => {
+ const res = await swapSolToToken({ keypair: ctx.keypair, lamports: lams, outputMint: mint, slippageBps, network: ctx.network, conn: ctx.conn });
+ return { signature: res.signature };
+ },
+ });
+}
+
+async function swapSolToToken({ keypair, lamports, outputMint, slippageBps, conn }) {
+ const { VersionedTransaction } = await import('@solana/web3.js');
+ const qUrl = `${JUPITER_BASE}/quote?inputMint=${WSOL_MINT}&outputMint=${outputMint}&amount=${lamports.toString()}&slippageBps=${slippageBps}&swapMode=ExactIn`;
+ const qRes = await fetchWithTimeout(qUrl, {}, 15_000);
+ if (!qRes.ok) throw Object.assign(new Error(`no swap route (${qRes.status})`), { code: 'no_route' });
+ const quote = await qRes.json();
+ if (!quote?.outAmount) throw Object.assign(new Error('no swap route for this pair'), { code: 'no_route' });
+ const sRes = await fetchWithTimeout(`${JUPITER_BASE}/swap`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ quoteResponse: quote, userPublicKey: keypair.publicKey.toBase58(), wrapAndUnwrapSol: true, dynamicComputeUnitLimit: true, prioritizationFeeLamports: 'auto' }),
+ }, 20_000);
+ if (!sRes.ok) throw Object.assign(new Error(`swap build failed (${sRes.status})`), { code: 'swap_failed' });
+ const { swapTransaction } = await sRes.json();
+ if (!swapTransaction) throw Object.assign(new Error('swap build returned no transaction'), { code: 'swap_failed' });
+ const tx = VersionedTransaction.deserialize(Buffer.from(swapTransaction, 'base64'));
+ tx.sign([keypair]);
+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });
+ const bh = await conn.getLatestBlockhash();
+ await conn.confirmTransaction({ signature: sig, ...bh }, 'confirmed');
+ return { signature: sig, outAmount: quote.outAmount };
+}
+
+// Notify the owner (real audit event + best-effort email). No funds move.
+async function notifyOwner({ ctx, intent, discriminator, subject, body }) {
+ const idemKey = `intent:${intent.id}:${discriminator}`;
+ const claim = await sql`
+ INSERT INTO agent_custody_events (agent_id, user_id, event_type, category, network, reason, status, idempotency_key, meta)
+ SELECT ${ctx.agentId}, ${ctx.ownerId ?? null}, 'intent_notify', 'notify', ${ctx.network}, ${subject.slice(0, 200)}, 'ok', ${idemKey},
+ ${JSON.stringify({ intent_id: intent.id, intent_title: intent.title, message: body })}::jsonb
+ WHERE NOT EXISTS (SELECT 1 FROM agent_custody_events WHERE agent_id = ${ctx.agentId} AND idempotency_key = ${idemKey})
+ RETURNING id
+ `;
+ if (!claim.length) return { status: 'skipped', note: 'already notified for this event' };
+ // Best-effort email to the owner — never block on the channel being configured.
+ try {
+ const { sendEmail } = await import('./email.js');
+ const [u] = await sql`SELECT email FROM users WHERE id = ${ctx.ownerId}`;
+ if (u?.email) await sendEmail({ to: u.email, subject, html: `<p>${body}</p><p style="color:#888">— your agent's wallet copilot</p>` }).catch(() => {});
+ } catch { /* email optional */ }
+ return { status: 'notified', note: body.slice(0, 200) };
+}
+
+// ── the action dispatcher ──────────────────────────────────────────────────────────
+
+async function executeAction(intent, ctx, event = {}) {
+ const a = intent.action;
+ const now = ctx.now;
+
+ // Resolve the moving amount in lamports for the SOL-moving actions.
+ const resolveLamports = async () => {
+ if (a.pct != null) {
+ if (a.of === 'tip' || a.of === 'income') {
+ // % of the triggering event value, taken in SOL.
+ const eventSol = event.amount_sol != null ? event.amount_sol : (event.usd != null ? event.usd / ctx.price : 0);
+ return solToLamports(eventSol * (a.pct / 100));
+ }
+ if (a.of === 'balance') return BigInt(Math.floor(Number(ctx.balanceLamports) * (a.pct / 100)));
+ }
+ if (a.above_sol != null) {
+ // "withdraw profit above N SOL" → everything over the floor (minus headroom).
+ const over = ctx.balanceLamports - solToLamports(a.above_sol);
+ return over > 0n ? over : 0n;
+ }
+ if (a.amount_sol != null) return solToLamports(a.amount_sol);
+ return 0n;
+ };
+
+ switch (a.type) {
+ case 'freeze': {
+ // Kill switch: freeze every outbound spend + notify. Idempotent per breach/day.
+ const disc = ctx.discriminator || `bal:${now.toISOString().slice(0, 10)}`;
+ if (!ctx.dryRun) {
+ const limits = getSpendLimits(ctx.meta);
+ if (!limits.frozen) await setSpendLimits(intent.agent_id || ctx.agentId, ctx.ownerId, { frozen: true }).catch(() => {});
+ }
+ const note = `Spending frozen${event.balance_sol != null ? ` — balance ${event.balance_sol.toFixed(4)} SOL is below your ${intent.trigger.threshold_sol} SOL floor` : ''}.`;
+ if (ctx.dryRun) return { status: 'would_run', note };
+ const n = await notifyOwner({ ctx, intent, discriminator: disc, subject: `${ctx.agentName || 'Your agent'}: wallet frozen`, body: note });
+ return { status: 'ok', note, frozen: true, notify: n.status };
+ }
+ case 'notify': {
+ const disc = ctx.discriminator || `notify:${now.toISOString().slice(0, 13)}`;
+ const body = a.message || describeIntent(intent);
+ if (ctx.dryRun) return { status: 'would_run', note: body };
+ return notifyOwner({ ctx, intent, discriminator: disc, subject: `${ctx.agentName || 'Your agent'}: ${intent.title}`, body });
+ }
+ case 'buy':
+ case 'snipe': {
+ const mint = ctx.overrideMint || a.mint;
+ if (!mint || !BASE58_RE.test(mint)) return { status: 'skipped', note: 'no valid mint to buy' };
+ const lamports = solToLamports(a.amount_sol);
+ return buyToken({ ctx, intent, discriminator: ctx.discriminator || `buy:${mint}`, mint, lamports, slippagePct: a.slippage_pct });
+ }
+ case 'tip':
+ case 'transfer':
+ case 'withdraw':
+ case 'split_income': {
+ let destination = a.destination;
+ if (a.to_tipper && event.from) destination = event.from; // tip-back to the tipper
+ if (!destination || !BASE58_RE.test(destination)) return { status: 'skipped', note: 'no valid destination' };
+ const lamports = await resolveLamports();
+ if (lamports <= 0n) return { status: 'skipped', note: 'nothing to send for this event' };
+ const category = a.type === 'withdraw' ? 'withdraw' : a.type === 'split_income' ? 'split' : 'transfer';
+ return transferSol({
+ ctx, intent, discriminator: ctx.discriminator || `${a.type}:${event.signature || now.toISOString().slice(0, 13)}`,
+ category, lamports, rowMeta: { action: a.type, destination, destination_label: a.destination_label },
+ });
+ }
+ default:
+ return { status: 'skipped', note: 'unknown action' };
+ }
+}
+
+// ── execution context (loads the agent, gates safety, recovers the key once) ─────
+
+async function buildExecContext({ agentId, userId, network, dryRun, needsKey }) {
+ const [row] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!row) return { error: 'not_found' };
+ const meta = row.meta || {};
+ const address = meta.solana_address;
+ const encryptedSecret = meta.encrypted_solana_secret;
+ if (!address) return { error: 'no_wallet' };
+
+ const limits = getSpendLimits(meta);
+ if (limits.frozen && needsKey) return { error: 'wallet_frozen' };
+
+ let price;
+ try { price = await solUsdPrice(); } catch { return { error: 'price_unavailable' }; }
+
+ const conn = solanaConnection(network);
+ let balanceSol = 0;
+ try { balanceSol = Number((await getSolanaAddressBalances(address, network))?.sol || 0); }
+ catch (e) { return { error: 'balance_read_failed', detail: e?.message }; }
+
+ let keypair = null;
+ if (needsKey && !dryRun) {
+ if (!encryptedSecret) return { error: 'no_secret' };
+ try { keypair = await recoverSolanaAgentKeypair(encryptedSecret, { agentId, userId: userId ?? row.user_id, reason: 'wallet_intent' }); }
+ catch (e) { return { error: 'key_recover_failed', detail: e?.message }; }
+ }
+
+ return {
+ ctx: {
+ agentId, agentName: row.name, ownerId: row.user_id, userId, network, dryRun,
+ now: new Date(), conn, price, meta, address,
+ balanceSol, balanceLamports: solToLamports(balanceSol), keypair,
+ },
+ };
+}
+
+async function stampFire(intent, res, now = new Date()) {
+ const moved = res.status === 'ok' && res.usd ? Number(res.usd) : 0;
+ await sql`
+ UPDATE agent_wallet_intents SET
+ fire_count = fire_count + ${res.status === 'ok' || res.status === 'notified' ? 1 : 0},
+ spent_usd = spent_usd + ${moved},
+ last_fired_at = ${now.toISOString()},
+ last_status = ${res.status},
+ last_note = ${(res.note || (res.signature ? 'executed' : null) || res.status)?.slice?.(0, 280) ?? null},
+ last_signature = ${res.signature || null},
+ updated_at = now()
+ WHERE id = ${intent.id}
+ `;
+}
+
+// ── public entrypoints ─────────────────────────────────────────────────────────────
+
+/**
+ * Owner-initiated "test this rule now" — runs the real (or dry) execution path for
+ * a single intent. Honors freeze, spend policy, and the intent's caps exactly like
+ * the scheduler. dryRun reports what WOULD happen without moving funds.
+ */
+export async function runIntentNow({ agentId, userId, intentId, network = 'mainnet', dryRun = true }) {
+ const intent = await getIntent(agentId, intentId);
+ if (!intent) return { ran: false, reason: 'not_found' };
+ if (!intent.enabled && !dryRun) return { ran: false, reason: 'disabled' };
+
+ const needsKey = SPENDING_ACTIONS.has(intent.action.type);
+ const built = await buildExecContext({ agentId, userId, network, dryRun, needsKey });
+ if (built.error) return { ran: false, reason: built.error, note: built.detail || null };
+ const ctx = built.ctx;
+
+ // Synthesize a representative event for triggers that need one, so the dry-run is
+ // concrete (e.g. tip-back shows what it would send on a sample tip).
+ const event = synthEvent(intent, ctx);
+ ctx.discriminator = dryRun ? `dryrun:${Date.now ? 'now' : 'x'}` : `manual:${ctx.now.toISOString()}`;
+ if (intent.trigger.type === 'on_launch_matching' && intent.action.type === 'snipe') {
+ // A manual test of a snipe rule can't pick a real launch — report readiness.
+ return { ran: true, dryRun, results: [{ ...intentSummary(intent), status: 'would_run', note: `armed — will snipe up to ${intent.action.amount_sol} SOL on the next matching launch` }] };
+ }
+
+ let res;
+ try { res = await executeAction(intent, ctx, event); }
+ catch (e) { res = { status: 'error', note: (e?.message || 'failed').slice(0, 240) }; }
+ if (!dryRun) await stampFire(intent, res, ctx.now).catch(() => {});
+ return { ran: true, dryRun, results: [{ ...intentSummary(intent), ...res }] };
+}
+
+function intentSummary(intent) {
+ return { id: intent.id, title: intent.title, trigger: intent.trigger.type, action: intent.action.type };
+}
+
+function synthEvent(intent, ctx) {
+ const t = intent.trigger;
+ if (t.type === 'on_tip_received' || t.type === 'on_income') {
+ const sampleSol = Math.max(t.min_sol || 0.1, 0.1);
+ return { amount_sol: sampleSol, usd: sampleSol * ctx.price, from: null, signature: null, sample: true };
+ }
+ if (t.type === 'on_balance_below') return { balance_sol: ctx.balanceSol };
+ return {};
+}
+
+/**
+ * Fired from the tip-recording path: evaluate this agent's on_tip_received /
+ * on_income intents against a freshly-recorded REAL tip and execute any that
+ * match. Idempotent per (intent, tip signature) via the custody claim.
+ *
+ * @param {object} tip { signature, amount_sol, usd, from, network }
+ */
+export async function onTipRecorded(agentId, tip) {
+ try {
+ const rows = await sql`
+ SELECT * FROM agent_wallet_intents
+ WHERE agent_id = ${agentId} AND enabled = true AND trigger_type IN ('on_tip_received', 'on_income')
+ `;
+ if (!rows.length) return { fired: 0 };
+ const network = tip.network === 'devnet' ? 'devnet' : 'mainnet';
+ const intents = rows.map(rowToIntent).filter((i) => {
+ if (i.network !== network) return false;
+ if (i.trigger.type === 'on_tip_received') return (tip.amount_sol ?? 0) >= (i.trigger.min_sol || 0);
+ return true; // on_income — any inflow
+ });
+ if (!intents.length) return { fired: 0 };
+
+ const needsKey = intents.some((i) => SPENDING_ACTIONS.has(i.action.type));
+ const built = await buildExecContext({ agentId, userId: null, network, dryRun: false, needsKey });
+ if (built.error) {
+ console.warn('[wallet-intents] tip eval skipped:', built.error);
+ return { fired: 0, reason: built.error };
+ }
+ const ctx = built.ctx;
+ const event = { amount_sol: tip.amount_sol ?? null, usd: tip.usd ?? null, from: tip.from || null, signature: tip.signature || null };
+
+ let fired = 0;
+ for (const intent of intents) {
+ ctx.discriminator = `${intent.action.type}:tip:${tip.signature || ctx.now.toISOString()}`;
+ let res;
+ try { res = await executeAction(intent, ctx, event); }
+ catch (e) { res = { status: 'error', note: (e?.message || 'failed').slice(0, 240) }; }
+ await stampFire(intent, res, ctx.now).catch(() => {});
+ if (res.status === 'ok' || res.status === 'notified') fired++;
+ }
+ return { fired };
+ } catch (e) {
+ console.warn('[wallet-intents] onTipRecorded failed', e?.message);
+ return { fired: 0, error: e?.message };
+ }
+}
+
+const UTC_WEEKDAY = (d) => d.getUTCDay();
+
+function scheduleDue(intent, now) {
+ const t = intent.trigger;
+ if (t.cadence === 'weekly' && t.weekday != null && UTC_WEEKDAY(now) !== t.weekday) return false;
+ return now.getUTCHours() === (t.hour ?? 13);
+}
+
+/**
+ * The cron sweep: evaluate every enabled scheduled / balance / launch / stream
+ * intent across all agents and execute the due ones. Each kind is bounded and
+ * idempotent. Returns a per-agent summary (no secrets).
+ */
+export async function runIntentSweep({ network = 'mainnet', now = new Date(), launchLimit = 60 } = {}) {
+ const summary = { scanned: 0, fired: 0, by_trigger: {}, errors: 0 };
+
+ // 1) scheduled intents whose hour/weekday is now.
+ const scheduled = (await sql`
+ SELECT * FROM agent_wallet_intents WHERE enabled = true AND trigger_type = 'on_schedule' AND network = ${network}
+ `).map(rowToIntent).filter((i) => scheduleDue(i, now));
+ for (const intent of scheduled) {
+ summary.scanned++;
+ const r = await fireScheduledLike(intent, network, now, `sched:${isoBucket(intent.trigger, now)}`);
+ tallySweep(summary, intent.trigger.type, r);
+ }
+
+ // 2) balance-floor intents — poll each agent's SOL balance.
+ const balance = (await sql`
+ SELECT * FROM agent_wallet_intents WHERE enabled = true AND trigger_type = 'on_balance_below' AND network = ${network}
+ `).map(rowToIntent);
+ for (const intent of balance) {
+ summary.scanned++;
+ const r = await fireBalanceIntent(intent, network, now);
+ tallySweep(summary, intent.trigger.type, r);
+ }
+
+ // 3) launch-matching intents — one shared pull of recent launches, matched per rule.
+ const launch = (await sql`
+ SELECT * FROM agent_wallet_intents WHERE enabled = true AND trigger_type = 'on_launch_matching' AND network = ${network}
+ `).map(rowToIntent);
+ if (launch.length && network === 'mainnet') {
+ let launches = [];
+ try { launches = await recentPumpLaunches({ network, limit: launchLimit }); } catch { launches = []; }
+ let solPrice = 0;
+ try { solPrice = await solUsdPrice(); } catch { solPrice = 0; }
+ for (const intent of launch) {
+ summary.scanned++;
+ const r = await fireLaunchIntent(intent, network, now, launches, solPrice);
+ tallySweep(summary, intent.trigger.type, r);
+ }
+ }
+
+ return summary;
+}
+
+function isoBucket(trigger, now) {
+ if (trigger.cadence === 'weekly') {
+ // year-week bucket
+ const oneJan = Date.UTC(now.getUTCFullYear(), 0, 1);
+ const week = Math.ceil(((now.getTime() - oneJan) / 86400000 + 1) / 7);
+ return `${now.getUTCFullYear()}-W${week}`;
+ }
+ return now.toISOString().slice(0, 10);
+}
+
+function tallySweep(summary, triggerType, r) {
+ summary.by_trigger[triggerType] = (summary.by_trigger[triggerType] || 0) + 1;
+ if (r?.status === 'ok' || r?.status === 'notified') summary.fired++;
+ if (r?.status === 'error') summary.errors++;
+}
+
+async function fireScheduledLike(intent, network, now, discriminator) {
+ const needsKey = SPENDING_ACTIONS.has(intent.action.type);
+ const built = await buildExecContext({ agentId: intent.agent_id, userId: null, network, dryRun: false, needsKey });
+ if (built.error) { const res = { status: 'paused', note: built.error }; await stampFire(intent, res, now).catch(() => {}); return res; }
+ const ctx = built.ctx; ctx.discriminator = discriminator; ctx.now = now;
+ let res;
+ try { res = await executeAction(intent, ctx, { balance_sol: ctx.balanceSol }); }
+ catch (e) { res = { status: 'error', note: (e?.message || 'failed').slice(0, 240) }; }
+ await stampFire(intent, res, now).catch(() => {});
+ return res;
+}
+
+async function fireBalanceIntent(intent, network, now) {
+ const built = await buildExecContext({ agentId: intent.agent_id, userId: null, network, dryRun: false, needsKey: SPENDING_ACTIONS.has(intent.action.type) });
+ if (built.error) { const res = { status: 'paused', note: built.error }; await stampFire(intent, res, now).catch(() => {}); return res; }
+ const ctx = built.ctx; ctx.now = now;
+ if (ctx.balanceSol >= intent.trigger.threshold_sol) {
+ return { status: 'skipped', note: `balance ${ctx.balanceSol.toFixed(4)} SOL is above the ${intent.trigger.threshold_sol} SOL floor` };
+ }
+ // Idempotent per UTC day so a sustained low balance notifies/freezes at most daily.
+ ctx.discriminator = `bal:${now.toISOString().slice(0, 10)}`;
+ let res;
+ try { res = await executeAction(intent, ctx, { balance_sol: ctx.balanceSol }); }
+ catch (e) { res = { status: 'error', note: (e?.message || 'failed').slice(0, 240) }; }
+ await stampFire(intent, res, now).catch(() => {});
+ return res;
+}
+
+async function fireLaunchIntent(intent, network, now, launches, solPrice) {
+ const t = intent.trigger;
+ // Match by creator and/or market cap. Creator-gated rules enrich on demand.
+ let match = null;
+ for (const raw of launches) {
+ if (!raw?.mint) continue;
+ if (t.creator && raw.creator !== t.creator) continue;
+ const mc = raw.market_cap_usd;
+ if (t.max_mcap_usd != null && !(mc != null && mc <= t.max_mcap_usd)) continue;
+ if (t.min_mcap_usd != null && !(mc != null && mc >= t.min_mcap_usd)) continue;
+ match = raw;
+ break;
+ }
+ if (!match) return { status: 'skipped', note: 'no launch matched this cycle' };
+ if (t.creator) { try { await enrichCreatorStats(match, solPrice); } catch { /* best effort */ } }
+
+ const built = await buildExecContext({ agentId: intent.agent_id, userId: null, network, dryRun: false, needsKey: true });
+ if (built.error) { const res = { status: 'paused', note: built.error }; await stampFire(intent, res, now).catch(() => {}); return res; }
+ const ctx = built.ctx; ctx.now = now;
+ ctx.overrideMint = match.mint;
+ ctx.discriminator = `snipe:${match.mint}`; // one buy per matched mint, ever
+ let res;
+ try { res = await executeAction(intent, ctx, {}); }
+ catch (e) { res = { status: 'error', note: (e?.message || 'failed').slice(0, 240) }; }
+ if (res.signature || res.status === 'ok') res.note = `sniped ${match.symbol || match.mint.slice(0, 6)} @ ~$${Math.round(match.market_cap_usd || 0).toLocaleString()} mc`;
+ await stampFire(intent, res, now).catch(() => {});
+ return res;
+}
+
+// Public, read-only persona traits (owner opt-in). Visitors may see the BEHAVIOR,
+// never the rule, caps, or controls. Used by public agent surfaces.
+export async function publicIntentTraits(agentId) {
+ const rows = await sql`
+ SELECT trigger_type, action_type, title FROM agent_wallet_intents
+ WHERE agent_id = ${agentId} AND enabled = true AND public_trait = true
+ ORDER BY created_at DESC LIMIT 6
+ `;
+ return rows.map((r) => ({
+ label: traitLabel(r.trigger_type, r.action_type) || r.title,
+ trigger: r.trigger_type,
+ action: r.action_type,
+ }));
+}
+
+function traitLabel(trigger, action) {
+ if (trigger === 'on_tip_received' && action === 'tip') return 'Tips back generously';
+ if (action === 'split_income') return 'Shares its income';
+ if (trigger === 'on_launch_matching' && action === 'snipe') return 'Snipes fresh launches';
+ if (action === 'freeze') return 'Self-protects on low balance';
+ return null;
+}
diff --git a/api/_providers/nvidia-cosmos.js b/api/_providers/nvidia-cosmos.js
new file mode 100644
index 000000000..9e5687a72
--- /dev/null
+++ b/api/_providers/nvidia-cosmos.js
@@ -0,0 +1,398 @@
+// NVIDIA Cosmos provider — the FREE text→world VIDEO backend.
+//
+// Cosmos is NVIDIA's omnimodal World Foundation Model family for Physical AI.
+// The `cosmos-predict` line generates a short photoreal video of a world state
+// from a text prompt (Text2World) — a living, physically-plausible scene. We use
+// it to bring an avatar to life: a generated animated world plays behind the
+// static 3D avatar render, turning a still portrait into a cinematic shot.
+//
+// This is the video sibling of api/_providers/nvidia.js (TRELLIS text→3D) and
+// api/_mcp3d/text-to-image.js (FLUX text→image): the SAME platform NVIDIA_API_KEY
+// (nvapi-…) unlocks it on the NVIDIA NIM catalog at zero vendor cost, behind the
+// SAME NVCF async gateway (202 + NVCF-REQID → poll pexec/status), so the forge
+// poll loop and persistence (R2) work identically.
+//
+// ── Why Text2World (and not image→video) ─────────────────────────────────────
+// NVIDIA's HOSTED preview gateway rejects user-supplied images for the visual
+// models — verified live against TRELLIS (see the header of nvidia.js: every
+// inline/asset image form 422s; only NVIDIA's own predefined sample images are
+// accepted). Cosmos Video2World on the hosted tier carries the same constraint,
+// so the lowest-friction, always-available capability is Text2World: a prompt is
+// the only input, and it produces the most visually striking result for the
+// avatar backdrop. A self-deployed Cosmos NIM accepts real image conditioning;
+// if NVIDIA lifts the hosted-image restriction, the same provider extends to
+// Video2World by adding the image input to buildWorldBody().
+//
+// ── Protocol (NVCF genai gateway — same shape verified live for TRELLIS) ──────
+// submit POST {INVOKE_URL}
+// Authorization: Bearer nvapi-… Accept: application/json
+// KServe v2 body: { inputs: [ { name:"command", shape:[1],
+// datatype:"BYTES", data:[ 'text2world --prompt="…" --seed=…' ] } ] }
+// → 202 + header NVCF-REQID (async; poll) | 200 + body (sync, rare)
+//
+// poll GET https://api.nvcf.nvidia.com/v2/nvcf/pexec/status/{NVCF-REQID}
+// → 202 (still running) | 200 (done, body holds the MP4)
+//
+// result The MP4 rides in the response under one of several shapes the NVCF
+// preview has shipped over time — KServe `outputs[].data[0]` (base64),
+// `{ b64_video }`, `{ video }`, `{ artifacts:[{ base64|data|url }] }`,
+// or raw `video/mp4` bytes. extractVideoBase64 normalizes all of them,
+// we persist the bytes to R2, and hand back a durable public URL like
+// the other providers. On an unrecognized shape the warn logs the
+// top-level keys so the next schema drift is visible without guessing.
+//
+// The default INVOKE_URL follows NVIDIA's published genai gateway path for
+// cosmos-predict and is overridable (without a redeploy) via
+// NVIDIA_COSMOS_INVOKE_URL — confirm the live contract for an account with
+// `node scripts/verify-nvidia-cosmos.mjs`.
+//
+// Error codes match the established provider contract (nvidia.js / replicate.js):
+// provider_unreachable / invalid_key / insufficient_credits / rate_limited /
+// provider_error — so callers can route around a dead/limited lane.
+
+import { env } from '../_lib/env.js';
+
+// Published genai gateway path for the hosted cosmos-predict world model. The
+// `command` input's leading token (text2world) selects the modality, so one
+// endpoint serves the whole predict line.
+const DEFAULT_COSMOS_INVOKE_URL = 'https://ai.api.nvidia.com/v1/genai/nvidia/cosmos-predict1-7b';
+const NVCF_STATUS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/pexec/status';
+
+// Cosmos predict renders a fixed ~5 s 1280×704 @ 24fps clip; the prompt is the
+// only knob that meaningfully changes the output, so we keep the body minimal.
+// A long prompt is clamped so the request is honest about what conditions it.
+const COSMOS_PROMPT_MAX = 300;
+
+// Without scene/lighting cues Cosmos drifts toward muted, overcast worlds. Append
+// a cinematic suffix unless the caller already steered the look — the backdrop
+// should feel alive and vivid behind the avatar.
+const COSMOS_STYLE_SUFFIX = ', cinematic lighting, volumetric atmosphere, vivid color, photoreal';
+const COSMOS_STYLE_WORDS = ['cinematic', 'lighting', 'sunset', 'sunrise', 'neon', 'golden hour', 'vivid', 'photoreal', 'volumetric', 'dramatic'];
+
+function enhanceWorldPrompt(raw) {
+ const text = String(raw || '').trim().slice(0, COSMOS_PROMPT_MAX);
+ const lower = text.toLowerCase();
+ const hasStyle = COSMOS_STYLE_WORDS.some((w) => lower.includes(w));
+ if (hasStyle) return text;
+ return (text + COSMOS_STYLE_SUFFIX).slice(0, COSMOS_PROMPT_MAX + COSMOS_STYLE_SUFFIX.length);
+}
+
+// Bound the gateway's synchronous hold so a long render becomes a pollable 202
+// instead of timing out our socket and losing the request id (the failure the
+// TRELLIS provider documents at length). Video takes minutes, so the sync window
+// almost always yields a 202 + reqId immediately.
+const NVCF_POLL_SECONDS = 30;
+
+// Per-request timeouts. A completed poll streams the full MP4 (several MB), so it
+// gets the longer budget. Submit only needs to outlast the synchronous window.
+const SUBMIT_TIMEOUT_MS = 45_000;
+const POLL_TIMEOUT_MS = 90_000;
+
+// NVCF can answer a cold model or a momentary gateway blip with a transient
+// 502/503/504, or drop the socket before a worker is warm. A single short retry
+// usually lands once the model spins up; bounded to one so a genuinely-down
+// upstream still fails fast. Mirrors nvidia.js.
+const GATEWAY_RETRY_STATUSES = new Set([502, 503, 504]);
+const MAX_INVOKE_ATTEMPTS = 2;
+const INVOKE_RETRY_DELAY_MS = 1_500;
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+function invokeUrl() {
+ return env.NVIDIA_COSMOS_INVOKE_URL || DEFAULT_COSMOS_INVOKE_URL;
+}
+
+// Map an upstream HTTP status onto the normalized error callers route on.
+function providerError(status, message, retryAfter) {
+ let code = 'provider_error';
+ let mapped = 502;
+ if (status === 401 || status === 403) {
+ code = 'invalid_key';
+ mapped = 401;
+ } else if (status === 402) {
+ code = 'insufficient_credits';
+ mapped = 402;
+ } else if (status === 429) {
+ code = 'rate_limited';
+ mapped = 429;
+ }
+ const err = Object.assign(new Error(message || `NVIDIA Cosmos returned ${status}`), {
+ code,
+ status: mapped,
+ providerStatus: status,
+ });
+ if (retryAfter != null) {
+ const secs = Number(retryAfter);
+ if (Number.isFinite(secs)) err.retryAfter = secs;
+ }
+ return err;
+}
+
+// Is a base64 string actually base64 (not a URL or empty)? Cosmos may inline the
+// MP4 as base64 or point at a CDN URL; this routes the two apart.
+function isBase64Blob(s) {
+ return typeof s === 'string' && s.length > 64 && !/^https?:\/\//.test(s);
+}
+
+// Walk a JSON Cosmos response for the MP4, tolerant of the several shapes the
+// hosted NVCF preview has shipped. Returns { base64 } on success, or
+// { base64:null, diag } with a compact description of the unrecognized shape.
+async function extractFromJson(data) {
+ if (!data || typeof data !== 'object') return { base64: null, diag: 'non-object json' };
+
+ // KServe v2 inference output — the documented hosted shape:
+ // { outputs: [ { name, datatype:"BYTES", data: [ "<base64 mp4>" ] } ] }
+ const kserve = Array.isArray(data.outputs) ? data.outputs : null;
+ if (kserve) {
+ for (const out of kserve) {
+ const d = Array.isArray(out?.data) ? out.data[0] : out?.data;
+ if (isBase64Blob(d)) return { base64: d };
+ if (typeof d === 'string' && /^https?:\/\//.test(d)) {
+ const fetched = await fetchToBase64(d);
+ if (fetched.base64) return fetched;
+ }
+ }
+ }
+
+ // Flat fields some preview builds use.
+ for (const key of ['b64_video', 'video', 'b64_json', 'output']) {
+ const v = data[key];
+ if (isBase64Blob(v)) return { base64: v };
+ }
+
+ // Artifact array (same family as TRELLIS/FLUX): { base64 | data | url }.
+ const artifact0 = data?.artifacts?.[0];
+ if (artifact0) {
+ const inline = artifact0.base64 ?? artifact0.data ?? (isBase64Blob(artifact0) ? artifact0 : null);
+ if (isBase64Blob(inline)) return { base64: inline };
+ const url = artifact0.url ?? (typeof artifact0 === 'string' && artifact0.startsWith('http') ? artifact0 : null);
+ if (url) {
+ const fetched = await fetchToBase64(url);
+ if (fetched.base64) return fetched;
+ return fetched;
+ }
+ }
+
+ const topKeys = JSON.stringify(Object.keys(data)).slice(0, 120);
+ return { base64: null, diag: `json keys=${topKeys}` };
+}
+
+// Pull bytes from a CDN URL and base64 them, so the rest of the pipeline always
+// holds the MP4 itself (we own the durable persist, like nvidia.js does for GLBs).
+async function fetchToBase64(url) {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(POLL_TIMEOUT_MS) });
+ if (!res.ok) return { base64: null, diag: `artifact url fetch ${res.status}` };
+ const buf = Buffer.from(await res.arrayBuffer());
+ if (buf.length > 0) return { base64: buf.toString('base64') };
+ return { base64: null, diag: 'artifact url empty body' };
+ } catch (err) {
+ return { base64: null, diag: `artifact url error: ${err?.message}` };
+ }
+}
+
+// Normalize a successful Cosmos response (JSON shapes above, or raw MP4 bytes
+// when the gateway ignores Accept) into base64 MP4.
+async function extractVideoBase64(res) {
+ const ct = (res.headers.get('content-type') || '').toLowerCase();
+ if (ct.includes('json')) {
+ const data = await res.json().catch(() => null);
+ return extractFromJson(data);
+ }
+ if (ct.includes('mp4') || ct.startsWith('video/') || ct.includes('octet-stream') || ct.includes('binary')) {
+ const buf = Buffer.from(await res.arrayBuffer());
+ if (buf.length > 0) return { base64: buf.toString('base64') };
+ return { base64: null, diag: `empty ${ct} body` };
+ }
+ const body = await res.text().catch(() => '');
+ return { base64: null, diag: `ct=${ct || 'none'} body[0:160]=${body.slice(0, 160)}` };
+}
+
+// KServe v2 invoke body. The `command` BYTES input carries the NIM CLI line that
+// selects the Text2World modality and the prompt — the documented hosted contract.
+function buildWorldBody({ prompt, seed }) {
+ const cmd = [`text2world`, `--prompt="${enhanceWorldPrompt(prompt).replace(/"/g, "'")}"`];
+ if (Number.isInteger(seed)) cmd.push(`--seed=${seed}`);
+ return {
+ inputs: [
+ {
+ name: 'command',
+ shape: [1],
+ datatype: 'BYTES',
+ data: [cmd.join(' ')],
+ },
+ ],
+ };
+}
+
+export function nvidiaCosmosConfigured() {
+ return Boolean(env.NVIDIA_API_KEY);
+}
+
+export function createNvidiaCosmosProvider() {
+ const apiKey = env.NVIDIA_API_KEY;
+ if (!apiKey) {
+ throw Object.assign(
+ new Error('NVIDIA_API_KEY env var is required for the nvidia-cosmos (Text2World) provider'),
+ { code: 'missing_key', status: 503 },
+ );
+ }
+
+ const authHeader = { authorization: `Bearer ${apiKey}` };
+ const invokeHeaders = {
+ ...authHeader,
+ accept: 'application/json',
+ 'content-type': 'application/json',
+ 'nvcf-poll-seconds': String(NVCF_POLL_SECONDS),
+ };
+ const pollHeaders = { ...authHeader, accept: 'application/json' };
+
+ // Decode a base64 MP4 and store it in R2, returning a durable public URL.
+ async function persistVideo(base64) {
+ const { putObject, publicUrl } = await import('../_lib/r2.js');
+ const key = `forge/cosmos/${globalThis.crypto.randomUUID()}.mp4`;
+ await putObject({
+ key,
+ body: Buffer.from(base64, 'base64'),
+ contentType: 'video/mp4',
+ });
+ return publicUrl(key);
+ }
+
+ // POST the invoke. Returns { done:true, videoBase64 } on synchronous 200, or
+ // { done:false, reqId } when NVCF accepted it for async processing.
+ async function postInvoke(body) {
+ let lastErr = null;
+ for (let attempt = 1; attempt <= MAX_INVOKE_ATTEMPTS; attempt++) {
+ let res;
+ try {
+ res = await fetch(invokeUrl(), {
+ method: 'POST',
+ headers: invokeHeaders,
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(SUBMIT_TIMEOUT_MS),
+ });
+ } catch (err) {
+ lastErr = Object.assign(new Error(`nvidia cosmos unreachable: ${err?.message}`), {
+ code: 'provider_unreachable',
+ status: 502,
+ });
+ // A submit timeout means the gateway held our socket without handing back
+ // a pollable id — retrying just stacks another full window. Make it
+ // terminal; a genuine socket/DNS blip (non-timeout) gets one retry.
+ const timedOut = err?.name === 'TimeoutError' || err?.name === 'AbortError';
+ if (!timedOut && attempt < MAX_INVOKE_ATTEMPTS) {
+ await sleep(INVOKE_RETRY_DELAY_MS);
+ continue;
+ }
+ throw lastErr;
+ }
+
+ if (res.status === 202) {
+ const reqId = res.headers.get('nvcf-reqid');
+ if (!reqId) {
+ throw Object.assign(new Error('NVCF accepted the Cosmos job but returned no NVCF-REQID'), {
+ code: 'provider_error',
+ status: 502,
+ });
+ }
+ return { done: false, reqId };
+ }
+
+ if (res.ok) {
+ // NVCF sometimes 200s with an empty body + NVCF-REQID when routing to async.
+ const reqId = res.headers.get('nvcf-reqid');
+ const { base64, diag } = await extractVideoBase64(res);
+ if (!base64) {
+ if (reqId) return { done: false, reqId };
+ console.warn('[nvidia-cosmos] sync 200 but no video — %s', diag);
+ throw Object.assign(new Error('Cosmos completed but returned no video'), {
+ code: 'provider_error',
+ status: 502,
+ });
+ }
+ return { done: true, videoBase64: base64 };
+ }
+
+ if (GATEWAY_RETRY_STATUSES.has(res.status) && attempt < MAX_INVOKE_ATTEMPTS) {
+ await res.text().catch(() => {});
+ lastErr = providerError(res.status, undefined, res.headers.get('retry-after'));
+ await sleep(INVOKE_RETRY_DELAY_MS);
+ continue;
+ }
+
+ let detail = '';
+ try {
+ const d = await res.json();
+ detail = d?.detail || d?.message || d?.title || '';
+ if (detail && typeof detail !== 'string') detail = JSON.stringify(detail);
+ } catch {
+ detail = await res.text().catch(() => '');
+ }
+ throw providerError(res.status, detail || undefined, res.headers.get('retry-after'));
+ }
+ throw (
+ lastErr ||
+ Object.assign(new Error('nvidia cosmos invoke failed after retries'), {
+ code: 'provider_error',
+ status: 502,
+ })
+ );
+ }
+
+ return {
+ // Native text→world video. Returns a poll handle, or a ready R2 MP4 URL when
+ // NVCF completed within the submit request (rare for video).
+ async textToWorld({ prompt, seed } = {}) {
+ const parsed = await postInvoke(buildWorldBody({ prompt, seed }));
+ if (parsed.done) {
+ const resultVideoUrl = await persistVideo(parsed.videoBase64);
+ return { taskId: null, resultVideoUrl };
+ }
+ return { taskId: parsed.reqId };
+ },
+
+ // Poll an async job. Never throws — transient failures resolve to 'running'
+ // so the poll loop keeps the job alive; only terminal upstream states map to
+ // 'failed'. On 'done' the MP4 is decoded, persisted to R2, and returned.
+ async status({ taskId } = {}) {
+ if (!taskId) return { status: 'failed', error: 'missing NVCF request id' };
+
+ let res;
+ try {
+ res = await fetch(`${NVCF_STATUS_URL}/${encodeURIComponent(taskId)}`, {
+ headers: pollHeaders,
+ signal: AbortSignal.timeout(POLL_TIMEOUT_MS),
+ });
+ } catch (err) {
+ return { status: 'running', error: `nvidia cosmos poll failed: ${err?.message}` };
+ }
+
+ if (res.status === 202) return { status: 'running' };
+
+ if (res.ok) {
+ const { base64, diag } = await extractVideoBase64(res);
+ if (!base64) {
+ console.warn('[nvidia-cosmos] poll 200 but no video — %s', diag);
+ return { status: 'failed', error: 'Cosmos finished but returned no video' };
+ }
+ try {
+ const resultVideoUrl = await persistVideo(base64);
+ return { status: 'done', resultVideoUrl };
+ } catch (err) {
+ return { status: 'failed', error: `failed to persist video: ${err?.message}` };
+ }
+ }
+
+ if (res.status === 401 || res.status === 403) {
+ return { status: 'failed', error: 'NVIDIA rejected the API key' };
+ }
+ if (res.status === 404) {
+ return { status: 'failed', error: 'NVCF request not found or expired' };
+ }
+ if (res.status === 429) {
+ return { status: 'running', error: 'NVIDIA is rate limiting; will retry' };
+ }
+ return { status: 'running', error: `NVIDIA Cosmos poll returned ${res.status}` };
+ },
+ };
+}
diff --git a/api/a2f.js b/api/a2f.js
new file mode 100644
index 000000000..cb7c3a539
--- /dev/null
+++ b/api/a2f.js
@@ -0,0 +1,214 @@
+// POST /api/a2f — free facial animation (Audio2Face-3D) for the talking avatar.
+//
+// The third leg of the avatar voice loop: /api/tts/speak gives every avatar a
+// voice (Magpie), /api/asr lets users talk back (Riva), and THIS endpoint turns
+// the spoken audio into a per-frame ARKit blendshape track so the avatar's mouth
+// and face animate in sync with the words. Two named NVIDIA models on one face:
+// Magpie voice + Audio2Face-3D animation (api/_lib/a2f-nvidia.js).
+//
+// Lane: NVIDIA NIM Audio2Face-3D (free, bidirectional gRPC). Purely additive —
+// when the lane is unconfigured (no NVIDIA_API_KEY) the client keeps speaking and
+// falls back to its in-browser amplitude lipsync, so nothing depends on this and
+// nothing breaks when it is absent.
+//
+// Two ways to call it:
+//
+// 1. Animate audio you already have (lips match the EXACT bytes you'll play):
+// • raw audio body with Content-Type audio/wav | audio/pcm (+ ?rate=)
+// • or JSON { audio: <base64>, format?, sampleRate? }
+// → { ok, animation: { fps, blendShapeNames, frames, durationSec, … } }
+//
+// 2. One-shot text→speech→animation (server synthesizes via Magpie, then
+// animates that exact clip, and returns BOTH so you can play + drive):
+// • JSON { text, voice?, language? }
+// → { ok, audio: { base64, contentType, format }, animation: { … } }
+//
+// A frame is { t, w }: t = time code in seconds from clip start, w = weights in
+// the order of blendShapeNames (ARKit naming). The browser plays the audio and
+// samples the track by the audio element's currentTime — see
+// src/voice/a2f-blendshapes.js for the morph-target mapping + player.
+
+import { cors, method, readBody, readJson, error, json, wrap, rateLimited } from './_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { animateNvidiaA2F, nvidiaA2fConfigured, resolveA2fFunctionId } from './_lib/a2f-nvidia.js';
+import { synthesizeNvidiaTts, nvidiaTtsConfigured } from './_lib/tts-nvidia.js';
+import { TTS_VOICE_IDS } from './_lib/tts-voices.js';
+
+export const maxDuration = 60;
+
+// 8 MiB of audio — generous for an avatar line (~4 min of 16 kHz mono PCM) while
+// bounding the in-memory buffer per request.
+const MAX_AUDIO_BYTES = 8 * 1024 * 1024;
+const A2F_TIMEOUT_MS = 40_000;
+const TTS_TIMEOUT_MS = 30_000;
+const VOICES = new Set(TTS_VOICE_IDS);
+
+function encodingFromContentType(ct) {
+ const type = String(ct || '').split(';')[0].trim().toLowerCase();
+ switch (type) {
+ case 'audio/wav':
+ case 'audio/x-wav':
+ case 'audio/wave':
+ return 'wav';
+ case 'audio/l16':
+ case 'audio/pcm':
+ case 'audio/x-pcm':
+ return 'pcm';
+ default:
+ return null;
+ }
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ // Capability probe — lets the avatar UI decide whether to request a real A2F
+ // track or go straight to the amplitude fallback, without browser-sniffing.
+ if (req.method === 'GET' || req.method === 'HEAD') {
+ return json(
+ res,
+ 200,
+ {
+ configured: nvidiaA2fConfigured(),
+ canSynthesize: nvidiaTtsConfigured(),
+ model: 'audio2face-3d',
+ functionId: nvidiaA2fConfigured() ? resolveA2fFunctionId() : null,
+ fps: 30,
+ // A2F emits ARKit-52 blendshape names; the client maps them onto
+ // whatever convention the loaded GLB exposes (ARKit/RPM/VRM/Oculus).
+ blendshapeFormat: 'arkit',
+ sampleRate: 16000,
+ accepts: { audio: ['wav', 'pcm'], json: ['audio', 'text'] },
+ },
+ { 'cache-control': 'public, max-age=60' },
+ );
+ }
+
+ if (!nvidiaA2fConfigured()) {
+ return error(
+ res,
+ 503,
+ 'not_configured',
+ 'Audio2Face is not configured (set NVIDIA_API_KEY). The avatar still speaks and falls back to amplitude lipsync.',
+ );
+ }
+
+ // Metered like the other free NVIDIA lanes: per-user budget for signed-in
+ // callers, a tighter per-IP one otherwise. The text path also burns a Magpie
+ // synthesis, so the bucket covers both.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId ?? null;
+ if (userId) {
+ const rl = await limits.a2fUser(userId);
+ if (!rl.success) return rateLimited(res, rl, 'Audio2Face rate limit exceeded, try again later');
+ } else {
+ const rl = await limits.a2fIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'Audio2Face rate limit exceeded, sign in for a higher limit');
+ }
+
+ const url = new URL(req.url, 'http://localhost');
+ const q = url.searchParams;
+ const contentType = req.headers['content-type'] || '';
+ const isJson = contentType.split(';')[0].trim().toLowerCase() === 'application/json';
+
+ // ── Gather the audio (and, on the text path, synthesize it first) ─────────
+ let wavBuffer = null; // a RIFF/WAVE buffer handed straight to A2F
+ let rawPcm = null;
+ let rawRate = 0;
+ let audioOut = null; // { base64, contentType, format } when we synthesized
+
+ try {
+ if (isJson) {
+ const body = await readJson(req, Math.ceil(MAX_AUDIO_BYTES * 1.4)); // base64 inflates ~33%
+
+ const text = typeof body.text === 'string' ? body.text.trim() : '';
+ const b64 = typeof body.audio === 'string' ? body.audio.replace(/^data:[^,]*,/, '') : '';
+
+ if (b64) {
+ const buf = Buffer.from(b64, 'base64');
+ const fmt = String(body.format || 'wav').toLowerCase();
+ if (fmt === 'pcm' || fmt === 'l16') {
+ rawPcm = buf;
+ rawRate = Number(body.sampleRate) || 16000;
+ } else {
+ wavBuffer = buf;
+ }
+ } else if (text) {
+ if (!nvidiaTtsConfigured()) {
+ return error(res, 503, 'not_configured', 'Text path needs Magpie TTS (NVIDIA_API_KEY) — pass pre-synthesized audio instead.');
+ }
+ if (text.length > 4096) return error(res, 400, 'bad_request', 'text exceeds 4096 characters');
+ const voice = VOICES.has(body.voice) ? body.voice : 'nova';
+ const language = typeof body.language === 'string' ? body.language : 'en-US';
+ // WAV so A2F can parse the rate from the header and we can hand the
+ // same bytes back to the browser to play.
+ const tts = await synthesizeNvidiaTts({ text, voice, language, format: 'wav', timeoutMs: TTS_TIMEOUT_MS });
+ wavBuffer = tts.audio;
+ audioOut = {
+ base64: tts.audio.toString('base64'),
+ contentType: tts.contentType,
+ format: tts.format,
+ voiceName: tts.voiceName,
+ sampleRateHz: tts.sampleRateHz,
+ };
+ } else {
+ return error(res, 400, 'bad_request', 'provide { text } to synthesize, or { audio: <base64> } to animate');
+ }
+ } else {
+ const fmt = encodingFromContentType(contentType);
+ if (!fmt) {
+ return error(res, 415, 'unsupported_media_type', `Unsupported audio Content-Type "${contentType.split(';')[0] || 'none'}". Send audio/wav or audio/pcm (with ?rate=), or a JSON body.`);
+ }
+ const buf = await readBody(req, MAX_AUDIO_BYTES);
+ if (fmt === 'pcm') {
+ rawPcm = buf;
+ rawRate = Number(q.get('rate') || q.get('sampleRate')) || 16000;
+ } else {
+ wavBuffer = buf;
+ }
+ }
+ } catch (e) {
+ if (e?.status === 413) return error(res, 413, 'payload_too_large', 'audio exceeds the 8 MB limit');
+ // A synthesis failure on the text path surfaces as a provider error.
+ if (e?.code && e.code !== 'bad_request') {
+ const status = e.code === 'rate_limited' ? 429 : e.code === 'invalid_key' ? 502 : 502;
+ return error(res, status, e.code, `Speech synthesis failed: ${e.message || 'unknown error'}`);
+ }
+ return error(res, e?.status || 400, 'bad_request', e?.message || 'could not read request body');
+ }
+
+ if (!wavBuffer?.length && !rawPcm?.length) {
+ return error(res, 400, 'bad_request', 'no audio to animate');
+ }
+
+ // ── Drive Audio2Face-3D ───────────────────────────────────────────────────
+ try {
+ const animation = await animateNvidiaA2F(
+ wavBuffer
+ ? { wav: wavBuffer, timeoutMs: A2F_TIMEOUT_MS }
+ : { pcm: rawPcm, sampleRateHz: rawRate, timeoutMs: A2F_TIMEOUT_MS },
+ );
+ return json(
+ res,
+ 200,
+ {
+ ok: true,
+ ...(audioOut ? { audio: audioOut } : {}),
+ animation,
+ },
+ { 'cache-control': 'no-store' },
+ );
+ } catch (e) {
+ const code = e?.code || 'provider_error';
+ const status =
+ code === 'rate_limited' ? 429 :
+ code === 'invalid_argument' ? 400 :
+ code === 'not_configured' ? 503 :
+ code === 'timeout' ? 504 :
+ 502;
+ return error(res, status, code, `Audio2Face failed: ${e?.message || 'unknown error'}`);
+ }
+});
diff --git a/api/agents/[id].js b/api/agents/[id].js
index fe5fe4fde..674fdbd9e 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -77,6 +77,11 @@ export default wrap(async function handler(req, res) {
return mod.default(req, res, id, action);
}
+ if (sub === 'intents') {
+ const mod = await import('./wallet-intents.js');
+ return mod.default(req, res, id, action);
+ }
+
if (sub === 'mirror') {
const mod = await import('./agent-mirror.js');
return mod.default(req, res, id, action);
diff --git a/api/agents/patronage.js b/api/agents/patronage.js
new file mode 100644
index 000000000..6f507d7f9
--- /dev/null
+++ b/api/agents/patronage.js
@@ -0,0 +1,336 @@
+// Patronage — the Support surface, owner CRM, and server-enforced unlocks
+// ========================================================================
+// Routed from api/agents/solana-wallet.js as action 'patronage':
+//
+// GET /api/agents/:id/solana/patronage — public read: level ladder, perk
+// ?viewer=<wallet>&network=&offset= ladder, the patron wall, season
+// standings, and (when ?viewer is a
+// wallet) that wallet's own standing.
+// NEVER returns gated perk payloads.
+// PUT /api/agents/:id/solana/patronage — owner-only (auth + CSRF): replace the
+// perk ladder.
+// POST /api/agents/:id/solana/patronage — body.op:
+// op:'unlock' — prove wallet ownership (ed25519 over a fresh challenge),
+// recompute on-chain support, return ONLY the perks that
+// support level has really earned, with their payloads.
+// op:'optout' — patron hides/shows themselves on the wall (same proof).
+//
+// Patron levels, perk entitlement, seasons, and the wall all DERIVE from the real
+// custody ledger via api/_lib/patronage.js. Nothing here trusts a client claim of
+// support: gated payloads are released only after the wallet signature is verified
+// AND the live on-chain support clears the threshold.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { verifySiwsSignature } from '../_lib/siws.js';
+import { logAudit } from '../_lib/audit.js';
+import {
+ PATRON_LEVELS,
+ PERK_TYPES,
+ levelForUsd,
+ currentSeason,
+ aggregatePatrons,
+ patronTotals,
+ patronStanding,
+ listPerks,
+ entitledPerks,
+ resolvePatronName,
+ hiddenWallets,
+} from '../_lib/patronage.js';
+
+const WALL_PAGE = 24; // patrons per wall page
+const NAME_RESOLVE_CAP = 12; // SNS reverse-resolutions per request (bounds Bonfida calls)
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const CHALLENGE_TTL_MS = 10 * 60 * 1000;
+
+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;
+}
+
+function levelPayload(level) {
+ return level ? { key: level.key, label: level.label, glyph: level.glyph, accent: level.accent } : null;
+}
+
+// Verify a wallet-ownership challenge: the signature is a real ed25519 signature by
+// `wallet` over `message`, and the message is bound to this agent + wallet + a
+// recent timestamp (so it can't be replayed across agents or indefinitely).
+function verifyChallenge({ message, signature, wallet, agentId }) {
+ if (typeof message !== 'string' || typeof signature !== 'string') return { ok: false, reason: 'missing signature' };
+ if (!message.includes(wallet) || !message.includes(agentId)) return { ok: false, reason: 'challenge not bound to this agent/wallet' };
+ const m = /Issued At:\s*(.+)/.exec(message);
+ const issued = m ? Date.parse(m[1].trim()) : NaN;
+ if (!Number.isFinite(issued) || Math.abs(Date.now() - issued) > CHALLENGE_TTL_MS) {
+ return { ok: false, reason: 'challenge expired — refresh and sign again' };
+ }
+ let valid = false;
+ try { valid = verifySiwsSignature(message, signature, wallet); } catch { valid = false; }
+ return valid ? { ok: true } : { ok: false, reason: 'signature did not verify for this wallet' };
+}
+
+export default async function handler(req, res, id) {
+ if (req.method === 'PUT' || req.method === 'POST') return handleWrite(req, res, id);
+ return handleRead(req, res, id);
+}
+
+// ── GET: public Support state ───────────────────────────────────────────────────
+async function handleRead(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const viewer = (url.searchParams.get('viewer') || '').trim();
+ const offset = Math.max(0, parseInt(url.searchParams.get('offset') || '0', 10) || 0);
+
+ const [agent] = await sql`
+ SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const auth = await resolveAuth(req).catch(() => null);
+ const isOwner = !!auth && auth.userId === agent.user_id;
+
+ const season = currentSeason();
+ const [perks, lifetime, seasonTotals, hidden] = await Promise.all([
+ listPerks(id, { activeOnly: !isOwner }),
+ patronTotals(id, { network }),
+ patronTotals(id, { network, since: season.startsAt }),
+ hiddenWallets(id),
+ ]);
+
+ // Wall page: top supporters, opt-outs removed, top names resolved (bounded).
+ const page = await aggregatePatrons(id, { network, limit: WALL_PAGE + 1, offset });
+ const hasMore = page.length > WALL_PAGE;
+ const visible = page.slice(0, WALL_PAGE).filter((p) => !hidden.has(p.wallet));
+ let resolved = 0;
+ const wall = [];
+ for (const p of visible) {
+ let name = null;
+ if (resolved < NAME_RESOLVE_CAP) { name = await resolvePatronName(id, p.wallet).catch(() => null); resolved++; }
+ wall.push({
+ wallet: p.wallet,
+ name,
+ usd: p.usd,
+ supportCount: p.supportCount,
+ firstAt: p.firstAt,
+ lastAt: p.lastAt,
+ level: levelPayload(levelForUsd(p.usd)),
+ });
+ }
+
+ // Season leaderboard: top 3 by support within the current epoch.
+ const seasonTop = (await aggregatePatrons(id, { network, since: season.startsAt, limit: 3 }))
+ .filter((p) => !hidden.has(p.wallet))
+ .map((p) => ({ wallet: p.wallet, usd: p.usd, level: levelPayload(levelForUsd(p.usd)) }));
+
+ // Viewer's own standing + which perks they've earned (titles/types only — the
+ // gated payloads are released solely through the signature-verified unlock op).
+ let viewerBlock = null;
+ if (viewer && BASE58_RE.test(viewer)) {
+ const standing = await patronStanding(id, viewer, { network });
+ const earned = entitledPerks(perks, standing.usd);
+ const hiddenForViewer = hidden.has(viewer);
+ viewerBlock = {
+ wallet: viewer,
+ usd: standing.usd,
+ supportCount: standing.supportCount,
+ firstAt: standing.firstAt,
+ lastAt: standing.lastAt,
+ level: levelPayload(standing.level),
+ progress: {
+ pct: standing.progress.pct,
+ next: levelPayload(standing.progress.next),
+ remainingUsd: standing.progress.remainingUsd,
+ },
+ earnedPerkIds: earned.map((p) => p.id),
+ hidden: hiddenForViewer,
+ };
+ }
+
+ return json(res, 200, {
+ data: {
+ agent_id: id,
+ agent_name: agent.name,
+ network,
+ is_owner: isOwner,
+ levels: PATRON_LEVELS.map((l) => ({ key: l.key, label: l.label, glyph: l.glyph, accent: l.accent, min_usd: l.minUsd })),
+ perks: perks.map((p) => ({
+ id: p.id,
+ perk_type: p.perkType,
+ threshold_usd: p.thresholdUsd,
+ title: p.title,
+ description: p.description,
+ is_active: p.isActive,
+ // Owners may see their own payloads to edit them; visitors never do.
+ payload: isOwner ? p.payload : undefined,
+ })),
+ totals: { lifetime, season: seasonTotals },
+ season,
+ season_top: seasonTop,
+ wall,
+ wall_has_more: hasMore,
+ wall_offset: offset,
+ viewer: viewerBlock,
+ },
+ });
+}
+
+// ── PUT / POST: owner config + patron actions ────────────────────────────────────
+async function handleWrite(req, res, id) {
+ if (cors(req, res, { methods: 'PUT,POST,OPTIONS', credentials: true })) return;
+
+ const [agent] = await sql`
+ SELECT id, user_id, name FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ if (req.method === 'PUT') return handleSetPerks(req, res, id, agent);
+
+ // POST — patron-side actions (unlock / optout). Open to anyone with a wallet.
+ let body;
+ try { body = await readJson(req); } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+ const op = String(body.op || '').trim();
+ if (op === 'unlock') return handleUnlock(req, res, id, body);
+ if (op === 'optout') return handleOptOut(req, res, id, body);
+ return error(res, 400, 'bad_request', 'unknown op (expected "unlock" or "optout")');
+}
+
+// Owner replaces the whole ladder in one call. Enforcement is by threshold, so we
+// can rebuild from scratch each save without breaking any prior "unlock".
+async function handleSetPerks(req, res, id, agent) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (auth.userId !== agent.user_id) return error(res, 403, 'forbidden', 'not your agent');
+
+ const rl = await limits.walletRead(auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
+ let body;
+ try { body = await readJson(req); } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+ const input = Array.isArray(body.perks) ? body.perks : null;
+ if (!input) return error(res, 400, 'validation_error', 'perks must be an array');
+ if (input.length > 12) return error(res, 400, 'validation_error', 'at most 12 perks per agent');
+
+ const clean = [];
+ for (const raw of input) {
+ const perkType = String(raw.perk_type || '').trim();
+ if (!PERK_TYPES.includes(perkType)) return error(res, 400, 'validation_error', `invalid perk_type: ${perkType}`);
+ const threshold = Number(raw.threshold_usd);
+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1_000_000) {
+ return error(res, 400, 'validation_error', 'threshold_usd must be between 0 and 1,000,000');
+ }
+ const title = String(raw.title || '').trim().slice(0, 120);
+ if (!title) return error(res, 400, 'validation_error', 'each perk needs a title');
+ const description = String(raw.description || '').trim().slice(0, 600) || null;
+
+ const payloadIn = raw.payload && typeof raw.payload === 'object' ? raw.payload : {};
+ const payload = {};
+ if (perkType === 'skill') {
+ const skill = String(payloadIn.skill || '').trim().slice(0, 100);
+ if (!skill) return error(res, 400, 'validation_error', 'a skill perk needs payload.skill');
+ payload.skill = skill;
+ } else if (perkType === 'greeting' || perkType === 'lore') {
+ const text = String(payloadIn.body || '').trim().slice(0, 4000);
+ if (!text) return error(res, 400, 'validation_error', `a ${perkType} perk needs payload.body`);
+ payload.body = text;
+ } else if (perkType === 'badge') {
+ payload.label = String(payloadIn.label || title).trim().slice(0, 40);
+ }
+ const isActive = raw.is_active !== false;
+ clean.push({ perkType, threshold, title, description, payload, isActive });
+ }
+
+ await sql`DELETE FROM agent_patron_perks WHERE agent_id = ${id}`;
+ for (const p of clean) {
+ await sql`
+ INSERT INTO agent_patron_perks (agent_id, perk_type, threshold_usd, title, description, payload, is_active)
+ VALUES (${id}, ${p.perkType}, ${p.threshold}, ${p.title}, ${p.description}, ${JSON.stringify(p.payload)}::jsonb, ${p.isActive})
+ `;
+ }
+ logAudit({ userId: auth.userId, action: 'patronage.set_perks', resourceId: id, meta: { count: clean.length }, req });
+
+ const perks = await listPerks(id, { activeOnly: false });
+ return json(res, 200, {
+ data: {
+ perks: perks.map((p) => ({
+ id: p.id, perk_type: p.perkType, threshold_usd: p.thresholdUsd,
+ title: p.title, description: p.description, is_active: p.isActive, payload: p.payload,
+ })),
+ },
+ });
+}
+
+// Patron proves wallet ownership; we release exactly the perks their REAL,
+// live-recomputed on-chain support has earned — payloads included.
+async function handleUnlock(req, res, id, body) {
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const wallet = String(body.wallet || '').trim();
+ if (!BASE58_RE.test(wallet)) return error(res, 400, 'validation_error', 'a valid wallet is required');
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+
+ const check = verifyChallenge({ message: body.message, signature: body.signature, wallet, agentId: id });
+ if (!check.ok) return error(res, 401, 'unauthorized', check.reason);
+
+ const [standing, perks] = await Promise.all([
+ patronStanding(id, wallet, { network }),
+ listPerks(id, { activeOnly: true }),
+ ]);
+ const earned = entitledPerks(perks, standing.usd);
+ const name = await resolvePatronName(id, wallet).catch(() => null);
+
+ return json(res, 200, {
+ data: {
+ wallet,
+ name,
+ usd: standing.usd,
+ level: levelPayload(standing.level),
+ unlocked: earned.map((p) => ({
+ id: p.id, perk_type: p.perkType, threshold_usd: p.thresholdUsd,
+ title: p.title, description: p.description, payload: p.payload,
+ })),
+ locked: perks.filter((p) => standing.usd < p.thresholdUsd).map((p) => ({
+ id: p.id, perk_type: p.perkType, threshold_usd: p.thresholdUsd, title: p.title,
+ remaining_usd: Math.max(0, p.thresholdUsd - standing.usd),
+ })),
+ },
+ });
+}
+
+// Patron toggles their own visibility on the public wall. Signature-gated so only
+// the wallet owner can hide/show themselves. Support still counts toward totals.
+async function handleOptOut(req, res, id, body) {
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const wallet = String(body.wallet || '').trim();
+ if (!BASE58_RE.test(wallet)) return error(res, 400, 'validation_error', 'a valid wallet is required');
+ const hidden = body.hidden === true;
+
+ const check = verifyChallenge({ message: body.message, signature: body.signature, wallet, agentId: id });
+ if (!check.ok) return error(res, 401, 'unauthorized', check.reason);
+
+ await sql`
+ INSERT INTO agent_patron_prefs (agent_id, patron_wallet, hidden, updated_at)
+ VALUES (${id}, ${wallet}, ${hidden}, now())
+ ON CONFLICT (agent_id, patron_wallet)
+ DO UPDATE SET hidden = EXCLUDED.hidden, updated_at = now()
+ `;
+ return json(res, 200, { data: { wallet, hidden } });
+}
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 9672e9af1..0cdac9356 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -10,6 +10,7 @@ import { requireCsrf } from '../_lib/csrf.js';
import { generateSolanaAgentWallet, recoverSolanaAgentKeypair, encryptSecret } from '../_lib/agent-wallet.js';
import { solanaConnection, solanaPublicConnection } from '../_lib/agent-pumpfun.js';
import { reverseLookupAddress } from '../../src/solana/sns.js';
+import { maybeWritePatronMemory } from '../_lib/patronage.js';
import {
Keypair, PublicKey, LAMPORTS_PER_SOL, SystemProgram,
TransactionMessage, VersionedTransaction,
@@ -1417,7 +1418,7 @@ async function flowSignalsFor(id) {
const [flow] = await sql`
SELECT
COALESCE(sum(usd) FILTER (
- WHERE event_type = 'tip' AND created_at > now() - interval '24 hours'
+ WHERE event_type IN ('tip', 'stream') AND created_at > now() - interval '24 hours'
), 0)::float8 AS inflow,
COALESCE(sum(usd) FILTER (
WHERE event_type IN ('spend', 'withdraw') AND created_at > now() - interval '24 hours'
@@ -1430,15 +1431,17 @@ async function flowSignalsFor(id) {
const outflow = Number(flow?.outflow) || 0;
let streamingNow = 0;
try {
- // Open streams crediting this agent right now. Generic by design so it
- // lights up automatically when Money Streams (task 01) records its events,
- // and stays 0 — never faked — until then.
+ // Streams crediting this agent RIGHT NOW. A Money Streams session (task 01)
+ // settles on-chain every ~45s (SETTLE_INTERVAL_MS), each settlement a
+ // 'stream' custody row tagged with its stream_id — so a stream is "live"
+ // iff it settled within the last cadence-and-a-bit. Count the distinct
+ // still-settling sessions; a stream that stopped naturally drops to 0.
const [s] = await sql`
- SELECT count(*)::int AS n FROM agent_custody_events
+ SELECT count(DISTINCT meta->>'stream_id')::int AS n FROM agent_custody_events
WHERE agent_id = ${id}
- AND (category = 'stream' OR event_type = 'stream')
- AND status IN ('ok', 'pending')
- AND COALESCE((meta->>'end_at')::timestamptz, now() + interval '1 second') > now()
+ AND category = 'stream'
+ AND status IN ('ok', 'confirmed', 'pending')
+ AND created_at > now() - interval '100 seconds'
`;
streamingNow = s?.n || 0;
} catch { streamingNow = 0; }
@@ -1768,7 +1771,20 @@ async function handleTip(req, res, id) {
// Reflect the inbound funds in the cached balance immediately.
await cacheSet(`sol:bal:${address}:${network}`, null, 1).catch(() => {});
+ // Patronage: a tip is real support — if it just pushed this patron into a new
+ // level, write a relationship memory the agent's chat will greet them with.
+ // Best-effort; never blocks or fails the (already-final) tip record.
+ if (from) maybeWritePatronMemory({ agentId: id, wallet: from, network }).catch(() => {});
+
const human = amountLamports != null ? Number(amountLamports) / 1e9 : Number(amountRaw) / 10 ** decimals;
+
+ // Wallet Intents: a real, freshly-recorded tip is a trigger. Fire the owner's
+ // on_tip_received / on_income rules (tip-back, split-income, notify) through the
+ // same spend-policy-gated, audited signing path. Fire-and-forget, idempotent per
+ // (intent, tip signature) — never blocks or fails the already-final tip record.
+ import('../_lib/wallet-intents.js')
+ .then(({ onTipRecorded }) => onTipRecorded(id, { signature, amount_sol: amountLamports != null ? Number(amountLamports) / 1e9 : null, usd: usd ?? null, from: from || null, network }))
+ .catch((e) => console.warn('[tip] intent eval failed', e?.message));
return json(res, 201, {
data: {
recorded: true, replayed: false, id: String(inserted[0].id),
@@ -1995,6 +2011,10 @@ async function handleStreamRecord(req, res, id) {
// Reflect the inbound funds in the cached balance immediately.
await cacheSet(`sol:bal:${address}:${network}`, null, 1).catch(() => {});
+ // Patronage: streamed support accrues like tips — promote the patron's level
+ // and write a relationship memory on a crossing. Best-effort, non-blocking.
+ if (from) maybeWritePatronMemory({ agentId: id, wallet: from, network }).catch(() => {});
+
return json(res, 201, {
data: {
recorded: true, replayed: false, id: String(inserted[0].id),
@@ -2167,6 +2187,10 @@ export default async function handler(req, res, id, action) {
if (action === 'tip') return handleTip(req, res, id);
if (action === 'stream') return handleStream(req, res, id);
if (action === 'pulse-visibility') return handlePulseVisibility(req, res, id);
+ if (action === 'patronage') {
+ const mod = await import('./patronage.js');
+ return mod.default(req, res, id);
+ }
if (action === 'intent') {
const mod = await import('./solana-intent.js');
return mod.handleIntent(req, res, id);
diff --git a/api/agents/talk.js b/api/agents/talk.js
index a03a485de..686fdc500 100644
--- a/api/agents/talk.js
+++ b/api/agents/talk.js
@@ -24,6 +24,7 @@ import { normalizeLegacyPolicy } from '../_lib/embed-policy.js';
import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';
import { hasSkillAccess } from '../_lib/skill-access.js';
import { isUuid } from '../_lib/validate.js';
+import { patronChatContext, patronStanding, listPerks, entitledPerks } from '../_lib/patronage.js';
const ALLOWED_MODELS = new Set([
'claude-haiku-4-5-20251001',
@@ -44,7 +45,7 @@ const bodySchema = z.object({
// access via hasSkillAccess (purchase / subscription / trial). Anonymous callers
// (userId === null) own no premium skill. Returns a compact, structured prompt
// section, or null when the agent has no skills worth describing.
-async function buildSkillOwnershipBlock(agent, userId) {
+async function buildSkillOwnershipBlock(agent, userId, patronSkills = new Set()) {
const skills = Array.isArray(agent.skills) ? agent.skills.filter(Boolean) : [];
if (skills.length === 0) return null;
@@ -63,6 +64,12 @@ async function buildSkillOwnershipBlock(agent, userId) {
ownership[skill] = { is_premium: false, is_owned: true };
continue;
}
+ // A patron whose verified on-chain support clears a skill-perk threshold uses
+ // that premium skill for free — the same gate the Support surface advertises.
+ if (patronSkills.has(skill)) {
+ ownership[skill] = { is_premium: true, is_owned: true, via_patron: true };
+ continue;
+ }
if (!userId) {
ownership[skill] = { is_premium: true, is_owned: false };
continue;
@@ -144,11 +151,29 @@ export default wrap(async (req, res) => {
agent.meta?.brain?.instructions ||
`You are ${agent.name}. ${agent.description || ''}`.trim();
+ // Patronage: recognize the caller as a real on-chain patron (greet them by name,
+ // reference the relationship) and free any premium skill their support has earned.
+ // The caller's identity is their linked wallet; standing derives from chain truth.
+ const callerWallet = session?.wallet_address || null;
+ const patronSkills = new Set();
+ if (callerWallet) {
+ try {
+ const [standing, perks] = await Promise.all([
+ patronStanding(agent.id, callerWallet),
+ listPerks(agent.id, { activeOnly: true }),
+ ]);
+ for (const p of entitledPerks(perks, standing.usd)) {
+ if (p.perkType === 'skill' && p.payload?.skill) patronSkills.add(p.payload.skill);
+ }
+ } catch { /* patronage is enrichment — never block the reply */ }
+ }
+ const patronBlock = await patronChatContext(agent.id, callerWallet).catch(() => null);
+
// Real per-user skill-ownership context: lets the agent know which of its
// skills are premium and whether THIS caller has already unlocked them, so it
// can use owned skills freely and offer to sell the ones the user lacks.
- const ownershipBlock = await buildSkillOwnershipBlock(agent, userId);
- const systemPrompt = ownershipBlock ? `${basePrompt}\n\n${ownershipBlock}` : basePrompt;
+ const ownershipBlock = await buildSkillOwnershipBlock(agent, userId, patronSkills);
+ const systemPrompt = [basePrompt, patronBlock, ownershipBlock].filter(Boolean).join('\n\n');
const started = Date.now();
let result;
diff --git a/api/agents/wallet-intents.js b/api/agents/wallet-intents.js
new file mode 100644
index 000000000..789ef3401
--- /dev/null
+++ b/api/agents/wallet-intents.js
@@ -0,0 +1,383 @@
+/**
+ * Wallet Intents API — owner-only control surface for the programmable,
+ * conversational money layer. Routed from api/agents/[id].js as
+ * /api/agents/:id/intents.
+ *
+ * GET /api/agents/:id/intents → the owner's intents + live summary
+ * POST /api/agents/:id/intents/compile → plain-language rule → validated structured intent (preview; never arms)
+ * POST /api/agents/:id/intents → arm a validated intent (real)
+ * POST /api/agents/:id/intents/run → owner "test this rule now" (dry-run or real) { intent_id, dry_run }
+ * POST /api/agents/:id/intents/copilot → conversational "how am I doing?" over real holdings + custody P&L
+ * PUT /api/agents/:id/intents/:intentId → enable / disable / edit / publish
+ * DELETE /api/agents/:id/intents/:intentId → remove
+ *
+ * Every write is owner-only (server-side) and CSRF-protected. Executing paths act
+ * ONLY on the agent's own wallet, are clamped to the agent's spend policy at
+ * execution time, and write an audited custody event stamped with the intent_id.
+ * A visitor (or logged-out caller) can never read, create, arm, or fire an intent.
+ */
+
+import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { sql } from '../_lib/db.js';
+import { loadUserProviderKeys } from '../_lib/provider-keys.js';
+import { getSpendLimits, getTradeLimits, lamportsToUsd } from '../_lib/agent-trade-guards.js';
+import { getSolanaAddressBalances } from '../_lib/agent-wallet.js';
+import { solUsdPrice } from '../_lib/avatar-wallet.js';
+import {
+ listIntents,
+ getIntent,
+ createIntent,
+ updateIntent,
+ deleteIntent,
+ runIntentNow,
+ compileIntentFromText,
+ normalizeIntent,
+ describeIntent,
+} from '../_lib/wallet-intents.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+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 loadOwned(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) {
+ error(res, 401, 'unauthorized', 'sign in to manage this agent’s wallet intents');
+ return { error: true };
+ }
+ const [row] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return { error: true }; }
+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'only the owner can manage wallet intents'); return { error: true }; }
+ return { auth, row, meta: { ...(row.meta || {}) } };
+}
+
+function netOf(req) {
+ const url = new URL(req.url, 'http://x');
+ return url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+}
+
+export default async function handler(req, res, id, action) {
+ if (cors(req, res, { methods: 'GET,POST,PUT,DELETE,OPTIONS', credentials: true })) return;
+
+ if (action === 'compile') return handleCompile(req, res, id);
+ if (action === 'run') return handleRun(req, res, id);
+ if (action === 'copilot') return handleCopilot(req, res, id);
+ if (action && UUID_RE.test(action)) {
+ if (req.method === 'PUT') return handleUpdate(req, res, id, action);
+ if (req.method === 'DELETE') return handleDelete(req, res, id, action);
+ if (req.method === 'GET') return handleGetOne(req, res, id, action);
+ return error(res, 405, 'method_not_allowed', 'use PUT, DELETE, or GET on an intent');
+ }
+ if (action) return error(res, 404, 'not_found', 'unknown intents sub-resource');
+
+ if (req.method === 'GET') return handleList(req, res, id);
+ if (req.method === 'POST') return handleCreate(req, res, id);
+ return method(req, res, ['GET', 'POST']) ? error(res, 405, 'method_not_allowed', 'use GET or POST') : undefined;
+}
+
+// GET — the owner's intents + a live summary (balance, today's & lifetime impact).
+async function handleList(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const network = netOf(req);
+ const intents = await listIntents(id);
+ const spendLimits = getSpendLimits(owned.meta);
+
+ let balanceSol = null;
+ try { balanceSol = Number((await getSolanaAddressBalances(owned.meta.solana_address, network))?.sol ?? null); }
+ catch { balanceSol = null; }
+
+ const lifetimeUsd = intents.reduce((a, i) => a + (i.stats?.spent_usd || 0), 0);
+ const fires = intents.reduce((a, i) => a + (i.stats?.fire_count || 0), 0);
+
+ return json(res, 200, {
+ data: {
+ intents,
+ summary: {
+ count: intents.length,
+ enabled: intents.filter((i) => i.enabled).length,
+ lifetime_usd: lifetimeUsd,
+ lifetime_fires: fires,
+ balance_sol: balanceSol,
+ frozen: !!spendLimits.frozen,
+ spend_limits: { per_tx_usd: spendLimits.per_tx_usd, daily_usd: spendLimits.daily_usd },
+ },
+ },
+ });
+}
+
+async function handleGetOne(req, res, id, intentId) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ const intent = await getIntent(id, intentId);
+ if (!intent) return error(res, 404, 'not_found', 'intent not found');
+ return json(res, 200, { data: { intent } });
+}
+
+// Shared: the live context the compiler/dry-run needs (balance, holdings, caps).
+async function compileContext(req, owned, network) {
+ let balanceSol = null;
+ let holdings = [];
+ try {
+ const bal = await getSolanaAddressBalances(owned.meta.solana_address, network);
+ balanceSol = Number(bal?.sol ?? null);
+ } catch { /* unknown */ }
+ let userKeys = {};
+ try {
+ const [u] = await sql`SELECT provider_keys FROM users WHERE id = ${owned.auth.userId}`;
+ userKeys = await loadUserProviderKeys(u?.provider_keys);
+ } catch { userKeys = {}; }
+ return {
+ agentName: owned.row.name,
+ network,
+ balanceSol,
+ holdings,
+ limits: getSpendLimits(owned.meta),
+ tradeLimits: getTradeLimits(owned.meta),
+ anthropicKey: userKeys.anthropic,
+ openrouterKey: userKeys.openrouter,
+ };
+}
+
+// POST /compile — plain-language → structured intent. Preview only; never arms.
+async function handleCompile(req, res, id) {
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const rl = await limits.chatUser(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl, 'slow down — too many compile requests');
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+ const text = typeof body.text === 'string' ? body.text : '';
+ if (!text.trim()) return error(res, 400, 'validation_error', 'describe a rule to compile');
+
+ const network = netOf(req);
+ const ctx = await compileContext(req, owned, network);
+ ctx.history = Array.isArray(body.history) ? body.history : [];
+
+ let compiled;
+ try { compiled = await compileIntentFromText(text, ctx); }
+ catch (e) { return serverError(res, 500, 'compile_failed', e); }
+
+ if (!compiled.ok) {
+ const status = compiled.error === 'unavailable' ? 503 : compiled.error === 'clarify' ? 200 : 422;
+ return json(res, status, { data: { ok: false, error: compiled.error, message: compiled.message, clarify: compiled.clarify || null, provider: compiled.provider || null } });
+ }
+
+ // Concrete dry-run preview alongside the compiled intent.
+ const sim = await simulate(compiled.intent, owned, network).catch(() => null);
+ return json(res, 200, { data: { ok: true, intent: compiled.intent, readback: describeIntent(compiled.intent), simulation: sim, provider: compiled.provider } });
+}
+
+// Build a concrete "on a sample event, this does X; remaining budget Y" preview.
+async function simulate(intent, owned, network) {
+ const a = intent.action;
+ let balanceSol = null;
+ try { balanceSol = Number((await getSolanaAddressBalances(owned.meta.solana_address, network))?.sol ?? null); } catch { /* */ }
+ let price = null;
+ try { price = await solUsdPrice(); } catch { /* */ }
+
+ const lines = [];
+ if (intent.trigger.type === 'on_tip_received' && a.pct != null) {
+ const sampleSol = Math.max(intent.trigger.min_sol || 0.2, 0.2);
+ const back = sampleSol * (a.pct / 100);
+ lines.push(`On a ${sampleSol} SOL tip, this sends back ${back.toFixed(3)} SOL${a.to_tipper ? ' to the tipper' : ''}.`);
+ } else if (a.amount_sol != null) {
+ lines.push(`Each fire moves ${a.amount_sol} SOL${a.destination_label ? ` to ${a.destination_label}` : ''}${price ? ` (~$${(a.amount_sol * price).toFixed(2)})` : ''}.`);
+ } else if (a.above_sol != null && balanceSol != null) {
+ const over = Math.max(0, balanceSol - a.above_sol);
+ lines.push(`At your current ${balanceSol.toFixed(3)} SOL, this would withdraw ${over.toFixed(3)} SOL above the ${a.above_sol} SOL floor.`);
+ } else if (a.pct != null) {
+ lines.push(`Each fire moves ${a.pct}% of ${a.of || 'income'}${a.destination_label ? ` to ${a.destination_label}` : ''}.`);
+ } else if (a.type === 'freeze') {
+ lines.push(`When balance drops below ${intent.trigger.threshold_sol} SOL, all spending freezes and you're notified.`);
+ } else if (a.type === 'notify') {
+ lines.push('This sends you a notification — it never moves funds.');
+ }
+ const lim = intent.limits || {};
+ if (lim.daily_usd != null) lines.push(`Daily budget: $${lim.daily_usd}.`);
+ if (lim.per_action_usd != null) lines.push(`Per-action cap: $${lim.per_action_usd}.`);
+ return { balance_sol: balanceSol, lines };
+}
+
+// POST / — arm a validated intent. Re-validates server-side; ownership + CSRF gated.
+async function handleCreate(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+ if (!body.intent || typeof body.intent !== 'object') return error(res, 400, 'validation_error', 'an intent object is required');
+
+ const norm = normalizeIntent(body.intent);
+ if (!norm.ok) return error(res, 422, norm.error || 'invalid_intent', norm.message || 'the intent could not be validated');
+ // Preserve a resolved destination + tip-back flag the compiler already grounded.
+ if (body.intent.action) {
+ const src = body.intent.action;
+ if (src.destination && !norm.intent.action.destination) norm.intent.action.destination = src.destination;
+ if (src.destination_label) norm.intent.action.destination_label = src.destination_label;
+ if (src.to_tipper) norm.intent.action.to_tipper = true;
+ if (src.mint && !norm.intent.action.mint) norm.intent.action.mint = src.mint;
+ }
+
+ const network = netOf(req);
+ try {
+ const intent = await createIntent(id, owned.auth.userId, norm.intent, {
+ network,
+ sourceText: typeof body.source_text === 'string' ? body.source_text.slice(0, 1000) : null,
+ publicTrait: body.public_trait === true,
+ });
+ return json(res, 201, { data: { intent } });
+ } catch (e) {
+ return serverError(res, 500, 'create_failed', e);
+ }
+}
+
+// PUT /:intentId — enable/disable/edit/publish.
+async function handleUpdate(req, res, id, intentId) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+
+ const patch = {};
+ if ('enabled' in body) patch.enabled = body.enabled === true;
+ if ('public_trait' in body) patch.public_trait = body.public_trait === true;
+ if ('title' in body) patch.title = body.title;
+ if ('intent' in body) patch.intent = body.intent;
+
+ try {
+ const result = await updateIntent(id, owned.auth.userId, intentId, patch);
+ if (!result) return error(res, 404, 'not_found', 'intent not found');
+ if (result.error) return error(res, 422, result.error, result.message);
+ return json(res, 200, { data: { intent: result } });
+ } catch (e) {
+ return serverError(res, 500, 'update_failed', e);
+ }
+}
+
+async function handleDelete(req, res, id, intentId) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ try {
+ const ok = await deleteIntent(id, owned.auth.userId, intentId);
+ if (!ok) return error(res, 404, 'not_found', 'intent not found');
+ return json(res, 200, { data: { deleted: true } });
+ } catch (e) {
+ return serverError(res, 500, 'delete_failed', e);
+ }
+}
+
+// POST /run — owner "test this rule now" (honors freeze, spend policy, caps).
+async function handleRun(req, res, id) {
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body = {};
+ try { body = await readJson(req); } catch { body = {}; }
+ const intentId = String(body.intent_id || '');
+ if (!UUID_RE.test(intentId)) return error(res, 400, 'validation_error', 'intent_id is required');
+ const dryRun = body.dry_run !== false; // default to a safe simulation
+
+ try {
+ const result = await runIntentNow({ agentId: id, userId: owned.auth.userId, intentId, network: netOf(req), dryRun });
+ return json(res, 200, { data: result });
+ } catch (e) {
+ return serverError(res, 500, 'run_failed', e);
+ }
+}
+
+// POST /copilot — conversational "how am I doing?" over REAL holdings + custody P&L.
+// Funds never move here; the copilot only reads + explains. Owner-only.
+async function handleCopilot(req, res, id) {
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const rl = await limits.chatUser(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl, 'slow down');
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }
+ const message = typeof body.message === 'string' ? body.message.trim().slice(0, 500) : '';
+ if (!message) return error(res, 400, 'validation_error', 'ask a question');
+
+ const network = netOf(req);
+
+ // Real numbers first — the copilot never guesses a balance or a P&L.
+ let balanceSol = null;
+ try { balanceSol = Number((await getSolanaAddressBalances(owned.meta.solana_address, network))?.sol ?? null); } catch { /* */ }
+ const [agg] = await sql`
+ SELECT
+ COALESCE(SUM(usd) FILTER (WHERE event_type = 'tip'), 0)::float8 AS tip_usd,
+ COALESCE(SUM(usd) FILTER (WHERE event_type = 'spend'), 0)::float8 AS spend_usd,
+ COUNT(*) FILTER (WHERE meta->>'intent_id' IS NOT NULL) AS intent_events
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND network = ${network} AND created_at > now() - interval '30 days'
+ `;
+ const intents = await listIntents(id);
+ const facts = {
+ balance_sol: balanceSol,
+ tips_30d_usd: Number(agg?.tip_usd || 0),
+ spend_30d_usd: Number(agg?.spend_usd || 0),
+ net_30d_usd: Number(agg?.tip_usd || 0) - Number(agg?.spend_usd || 0),
+ active_intents: intents.filter((i) => i.enabled).length,
+ intent_fires: intents.reduce((a, i) => a + (i.stats?.fire_count || 0), 0),
+ intent_moved_usd: intents.reduce((a, i) => a + (i.stats?.spent_usd || 0), 0),
+ };
+
+ const factual = `Balance: ${facts.balance_sol == null ? 'unknown' : facts.balance_sol.toFixed(3) + ' SOL'}. ` +
+ `Last 30 days — tips in: $${facts.tips_30d_usd.toFixed(2)}, spend out: $${facts.spend_30d_usd.toFixed(2)}, net: ${facts.net_30d_usd >= 0 ? '+' : ''}$${facts.net_30d_usd.toFixed(2)}. ` +
+ `${facts.active_intents} active rule${facts.active_intents === 1 ? '' : 's'} have fired ${facts.intent_fires} time${facts.intent_fires === 1 ? '' : 's'}, moving $${facts.intent_moved_usd.toFixed(2)}.`;
+
+ // Phrase it in-character if an LLM is available; otherwise return the real facts.
+ let reply = factual;
+ let provider = 'facts';
+ try {
+ let userKeys = {};
+ try { const [u] = await sql`SELECT provider_keys FROM users WHERE id = ${owned.auth.userId}`; userKeys = await loadUserProviderKeys(u?.provider_keys); } catch { /* */ }
+ const key = userKeys.anthropic || process.env.ANTHROPIC_API_KEY;
+ const orKey = userKeys.openrouter || process.env.OPENROUTER_API_KEY;
+ const persona = (owned.row.meta?.persona_prompt || owned.meta.system_prompt || '').toString().slice(0, 600);
+ const sys = `You are the wallet copilot for "${owned.row.name}", a 3D AI agent on three.ws. Answer the owner's question about their money in 1–3 short sentences, in character${persona ? ` (persona: ${persona})` : ''}. Use ONLY these real facts — never invent numbers: ${factual}`;
+ if (key) {
+ const r = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST', headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },
+ body: JSON.stringify({ model: 'claude-opus-4-8', max_tokens: 300, system: sys, messages: [{ role: 'user', content: message }] }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (r.ok) { const j = await r.json(); const t = (j.content || []).find((b) => b.type === 'text')?.text; if (t) { reply = t.trim(); provider = 'anthropic'; } }
+ } else if (orKey) {
+ const r = await fetch('https://openrouter.ai/api/v1/chat/completions', {
+ method: 'POST', headers: { Authorization: `Bearer ${orKey}`, 'content-type': 'application/json', 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws wallet copilot' },
+ body: JSON.stringify({ model: 'openai/gpt-oss-120b', max_tokens: 300, messages: [{ role: 'system', content: sys }, { role: 'user', content: message }] }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (r.ok) { const j = await r.json(); const t = j.choices?.[0]?.message?.content; if (t) { reply = t.trim(); provider = 'openrouter'; } }
+ }
+ } catch { /* fall back to facts */ }
+
+ return json(res, 200, { data: { reply, facts, provider } });
+}
diff --git a/api/cosmos.js b/api/cosmos.js
new file mode 100644
index 000000000..c288d6eee
--- /dev/null
+++ b/api/cosmos.js
@@ -0,0 +1,122 @@
+/**
+ * /api/cosmos — text → animated WORLD video on the free NVIDIA Cosmos lane.
+ *
+ * POST /api/cosmos { prompt: string, seed?: number }
+ * → 202 { job_id, status, eta_seconds } (async — poll for the clip)
+ * → 200 { status:'done', video_url } (rare synchronous completion)
+ *
+ * GET /api/cosmos?job=<id>
+ * → { job_id, status, video_url?, error? }
+ *
+ * Cosmos is NVIDIA's World Foundation Model family. The Text2World predict model
+ * renders a short photoreal video of a world from a prompt — we play it as a
+ * living backdrop behind a 3D avatar (see /cosmos). The job runs on NVIDIA's NVCF
+ * async gateway: submit returns a request id, we hand it back as job_id, and the
+ * GET poll asks NVCF for status and (on completion) persists the MP4 to R2,
+ * returning a durable URL. There is no server-side job store — the NVCF request
+ * id IS the durable handle, exactly like the TRELLIS text→3D lane.
+ *
+ * Reuses the platform NVIDIA_API_KEY (free NIM tier). When it is absent the lane
+ * reports itself unconfigured (503) and the page degrades to a static backdrop.
+ */
+
+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { createNvidiaCosmosProvider, nvidiaCosmosConfigured } from './_providers/nvidia-cosmos.js';
+
+const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;
+// Cosmos predict renders ~5 s of 1280×704 @ 24fps video; on the shared free tier
+// that typically lands in 60–120 s. Surfaced to the client so the loading state
+// can set honest expectations instead of an open-ended spinner.
+const ETA_SECONDS = 90;
+
+function unconfigured(res) {
+ return json(res, 503, {
+ error: 'unconfigured',
+ message:
+ 'Cosmos world generation is not configured. Set NVIDIA_API_KEY (an nvapi-… key from ' +
+ 'build.nvidia.com) to enable the free NVIDIA Cosmos lane.',
+ });
+}
+
+async function startJob(req, res) {
+ const rl = await limits.mcp3dGenerate(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (!nvidiaCosmosConfigured()) return unconfigured(res);
+
+ const body = await readJson(req, 4_000).catch(() => null);
+ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';
+ if (prompt.length < 3 || prompt.length > 300) {
+ return json(res, 400, {
+ error: 'invalid_prompt',
+ message: 'Describe the world in 3–300 characters (e.g. "a neon Tokyo street in the rain at night").',
+ });
+ }
+ const seed = Number.isFinite(Number(body?.seed)) ? Math.trunc(Number(body.seed)) : undefined;
+
+ let provider;
+ try {
+ provider = createNvidiaCosmosProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ try {
+ const result = await provider.textToWorld({ prompt, seed });
+ // Synchronous completion (uncommon for video) — hand back the clip directly.
+ if (result.resultVideoUrl) {
+ return json(res, 200, { status: 'done', video_url: result.resultVideoUrl });
+ }
+ return json(res, 202, {
+ job_id: result.taskId,
+ status: 'queued',
+ eta_seconds: ETA_SECONDS,
+ });
+ } catch (err) {
+ const status = err?.code === 'rate_limited' ? 429 : err?.code === 'invalid_key' ? 401 : 502;
+ return json(res, status, {
+ error: err?.code || 'cosmos_failed',
+ message: err?.message || 'Cosmos world generation could not start.',
+ ...(err?.retryAfter ? { retry_after: err.retryAfter } : {}),
+ });
+ }
+}
+
+async function pollJob(req, res, jobId) {
+ if (!JOB_ID_RE.test(jobId)) {
+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
+ }
+
+ const rl = await limits.mcp3dStatus(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (!nvidiaCosmosConfigured()) return unconfigured(res);
+
+ let provider;
+ try {
+ provider = createNvidiaCosmosProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ const result = await provider.status({ taskId: jobId });
+ return json(res, 200, {
+ job_id: jobId,
+ status: result.status,
+ video_url: result.resultVideoUrl || null,
+ error: result.error || null,
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'POST') return startJob(req, res);
+
+ const url = new URL(req.url, 'http://localhost');
+ const jobId = (url.searchParams.get('job') || '').trim();
+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });
+ return pollJob(req, res, jobId);
+});
diff --git a/api/cron/wallet-intents.js b/api/cron/wallet-intents.js
new file mode 100644
index 000000000..7119da144
--- /dev/null
+++ b/api/cron/wallet-intents.js
@@ -0,0 +1,45 @@
+// GET /api/cron/wallet-intents — the Wallet Intents scheduler.
+//
+// Runs every 10 minutes. Evaluates every enabled scheduled / balance-floor /
+// launch-matching intent across all agents and executes the due ones through the
+// SAME owner-authorized, spend-policy-gated, audited signing paths the rest of
+// the wallet uses. Each execution is idempotent (one fire per period / per breach
+// per day / per matched mint) and clamped to both the intent's own caps and the
+// agent's spend policy. Tip/income/stream intents fire inline from their event
+// hooks (the tip-recording path), not here.
+//
+// Nothing here exposes a key: the engine decrypts only at signing, audit-logs
+// every recovery, and writes a custody event stamped with the intent_id.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { runIntentSweep } from '../_lib/wallet-intents.js';
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const token = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
+ if (!constantTimeEquals(token, secret)) {
+ error(res, 401, 'unauthorized', 'cron secret required');
+ return false;
+ }
+ return true;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const startedAt = Date.now();
+ const now = new Date();
+ // Mainnet is the live money network; the engine no-ops launch buys on devnet.
+ const summary = await runIntentSweep({ network: 'mainnet', now });
+ const ms = Date.now() - startedAt;
+ console.info(`[wallet-intents] sweep done in ${ms}ms`, summary);
+ return json(res, 200, { data: { ...summary, took_ms: ms } });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 4c42c4cdf..1ad51e9e6 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,56 @@
{
"$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": "Cosmos Living Worlds: type a world, watch your avatar live in it",
+ "summary": "Your avatar no longer has to stand in an empty void. The new Cosmos page turns a few words into a living, photoreal world that plays as a cinematic backdrop behind your 3D avatar — describe a neon Tokyo street in the rain, an alpine lake at sunrise, or a bioluminescent forest at midnight, and NVIDIA's Cosmos world model renders a short animated scene around your character. Pick any avatar (your own creations included), tap a prompt idea or write your own, and watch real progress as the clip renders; when it's done you can download the MP4 or copy a shareable link that reopens the exact world and avatar. It runs free on the NVIDIA NIM tier, and if the lane is ever unavailable your avatar still shines on a living animated backdrop instead of a blank screen. Find it on the Create page or at /cosmos.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/cosmos"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Patronage: tips that build a real relationship with an agent",
+ "summary": "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.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Embodied Finance: agents now wear their wallet",
+ "summary": "Every agent's 3D body now shows its real wealth at a glance — no charts. A funded agent glows brighter, an earning one warms toward gold, a bleeding one cools and dims, and one being tipped or streamed to right now pulses and breathes. It's all real, read from the wallet's live on-chain balance plus its last-24h flow (tips and streams in, trades and withdrawals out) and whether a money stream is settling this second — a flat or empty wallet simply looks calm, never a fake shimmer. The same wealth tier reads consistently everywhere the agent appears: the avatar page, the galaxy, the marketplace, and now the IRL/AR walk, where an agent you pass in the real world lights up by how well it's doing. Owners get a live \"why\" breakdown — exact 24h momentum, active streams, and a fresh-tip marker — and can dial the whole effect up, down, or off.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Strategy Objects: equip an ownable, forkable trade strategy on your agent",
+ "summary": "A trading strategy is now a first-class thing you can own, share, and equip — not a buried setting. Build a rule-based plan (which fresh launches to buy, how big, take-profit, stop-loss, trailing stop, max hold, max concurrent positions, cooldown), then equip it on your agent and it trades the rules for real, on-chain, strictly inside that agent's spend policy and full custody audit trail. Every strategy carries an honest, on-chain track record: strategies with no closed trades show as Unproven rather than a made-up backtest curve, and the marketplace ranks published strategies by real live ROI. Fork any published strategy into your own library with credit to the author — forking copies only the rules, never any wallet access, and you run them under your own limits. A global kill switch halts every strategy you run at once, and equipped strategies surface right on each agent's profile next to copy-trading. Browse and manage everything at /strategies.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/strategies"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Money Streams: pay an agent by the second",
+ "summary": "You can now stream value to any agent in real time instead of sending one lump tip. Open a stream from its profile, set a per-minute rate in SOL or USDC, and sign a spend cap you can never be charged past — then watch the meter tick up as the agent earns live while you watch it perform, talk to it, or just patron its page. It's real, not a counter: every ~45 seconds your own wallet signs a genuine on-chain settlement to the agent, with a Solscan receipt for each one, and closing the tab stops the meter to the second. Owners get a live \"earning now\" view with lifetime totals and a 30-day chart. Non-custodial throughout — three.ws never holds the funds.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Image understanding is now a callable API",
+ "summary": "The free vision capability that already reads Forge uploads, weighs image evidence in the Fact Checker, and writes gallery alt text is now exposed as a public endpoint, /api/vision, so your own agents and tools can use it too. Send an image — as a file or a link — with a question, and get back a plain-language answer on the same free models the platform runs on, with a paid model as an automatic backstop. It's metered fairly and fails open, so it adds a new capability without changing anything that already works.",
+ "tags": [
+ "sdk"
+ ]
+ },
{
"date": "2026-06-23",
"title": "Mocap Studio: saving a face-capture clip just works",
diff --git a/data/pages.json b/data/pages.json
index afd6a04fb..b146a5b26 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -239,6 +239,14 @@
"changefreq": "weekly",
"added": "2026-06-21"
},
+ {
+ "path": "/cosmos",
+ "title": "Cosmos — Living Worlds",
+ "description": "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.",
+ "priority": 0.8,
+ "changefreq": "weekly",
+ "added": "2026-06-23"
+ },
{
"path": "/scene",
"title": "Scene Studio",
@@ -713,6 +721,14 @@
"changefreq": "weekly",
"added": "2026-05-15"
},
+ {
+ "path": "/strategies",
+ "title": "Strategy Objects",
+ "description": "A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.",
+ "priority": 0.8,
+ "changefreq": "daily",
+ "added": "2026-06-23"
+ },
{
"path": "/vanity-wallet",
"title": "Solana Vanity Wallet",
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 2c16d9576..81ab88005 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -537,6 +537,7 @@
</button>
</form>
<div class="ad-preview-footer" id="d-preview-footer"></div>
+ <div id="d-preview-stream" hidden style="margin-top:12px"></div>
</section>
<section class="ad-card ad-pricing-card" id="ad-pricing-card" hidden>
@@ -595,6 +596,14 @@
<div id="ad-pulse-feed"></div>
</section>
+ <section class="ad-card" id="ad-patronage-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet"></span>
+ <h2>PATRONAGE</h2>
+ </div>
+ <div id="ad-patronage-panel"></div>
+ </section>
+
<section class="ad-card" id="ad-mirror-card" hidden>
<div class="ad-card-head">
<span class="ad-bullet"></span>
diff --git a/pages/cosmos.html b/pages/cosmos.html
new file mode 100644
index 000000000..d13e67240
--- /dev/null
+++ b/pages/cosmos.html
@@ -0,0 +1,757 @@
+<!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" />
+ <title>Cosmos · Living Worlds · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#000000" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <meta
+ name="description"
+ content="Bring your 3D avatar to life with NVIDIA Cosmos. Generate a living, photoreal world from a text prompt and watch your avatar stand inside a cinematic, animated scene."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/cosmos" />
+ <meta property="og:title" content="Cosmos · Living Worlds · three.ws" />
+ <meta
+ property="og:description"
+ content="Type a world, watch it come alive behind your avatar — powered by NVIDIA Cosmos world models."
+ />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+
+ <!-- Google <model-viewer> — same build the Forge viewer uses. Lazy: the page
+ renders its shell instantly; the avatar appears when the module loads. -->
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
+
+ <style>
+ :root {
+ --cz-bg: #06070d;
+ --cz-panel: rgba(16, 18, 28, 0.72);
+ --cz-panel-solid: #11131c;
+ --cz-border: rgba(255, 255, 255, 0.1);
+ --cz-text: #f4f6fb;
+ --cz-dim: #9aa3b8;
+ --cz-accent: #76e0c2;
+ --cz-accent-2: #8b7cf6;
+ --cz-danger: #ff6b6b;
+ --cz-radius: 16px;
+ --cz-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);
+ }
+ html[data-theme='light'] {
+ --cz-bg: #eef1f8;
+ --cz-panel: rgba(255, 255, 255, 0.82);
+ --cz-panel-solid: #ffffff;
+ --cz-border: rgba(10, 12, 20, 0.12);
+ --cz-text: #0c1018;
+ --cz-dim: #5a6172;
+ --cz-shadow: 0 24px 70px rgba(20, 30, 60, 0.18);
+ }
+
+ * {
+ box-sizing: border-box;
+ }
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ }
+ body {
+ background: var(--cz-bg);
+ color: var(--cz-text);
+ font-family:
+ 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif;
+ -webkit-font-smoothing: antialiased;
+ overflow-x: hidden;
+ }
+
+ /* ── Top bar ──────────────────────────────────────────────────── */
+ .cz-bar {
+ position: sticky;
+ top: 0;
+ z-index: 40;
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 12px 20px;
+ background: linear-gradient(180deg, rgba(6, 7, 13, 0.92), rgba(6, 7, 13, 0));
+ backdrop-filter: blur(8px);
+ }
+ html[data-theme='light'] .cz-bar {
+ background: linear-gradient(180deg, rgba(238, 241, 248, 0.92), rgba(238, 241, 248, 0));
+ }
+ .cz-back {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ color: var(--cz-text);
+ text-decoration: none;
+ font-weight: 600;
+ font-size: 14px;
+ padding: 7px 12px;
+ border-radius: 10px;
+ border: 1px solid var(--cz-border);
+ transition:
+ background 0.18s ease,
+ transform 0.18s ease;
+ }
+ .cz-back:hover {
+ background: rgba(255, 255, 255, 0.06);
+ transform: translateX(-2px);
+ }
+ .cz-brand {
+ display: flex;
+ flex-direction: column;
+ line-height: 1.15;
+ }
+ .cz-brand b {
+ font-size: 15px;
+ letter-spacing: 0.2px;
+ }
+ .cz-brand span {
+ font-size: 11.5px;
+ color: var(--cz-dim);
+ }
+ .cz-badge {
+ margin-left: auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12px;
+ color: var(--cz-dim);
+ border: 1px solid var(--cz-border);
+ border-radius: 999px;
+ padding: 6px 12px;
+ }
+ .cz-badge .dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--cz-accent);
+ box-shadow: 0 0 10px var(--cz-accent);
+ }
+ .cz-badge.is-off .dot {
+ background: var(--cz-danger);
+ box-shadow: 0 0 10px var(--cz-danger);
+ }
+
+ /* ── Layout ───────────────────────────────────────────────────── */
+ .cz-wrap {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 380px;
+ gap: 20px;
+ max-width: 1320px;
+ margin: 0 auto;
+ padding: 8px 20px 40px;
+ }
+ @media (max-width: 900px) {
+ .cz-wrap {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ /* ── Stage (avatar in front of the living world) ──────────────── */
+ .cz-stage {
+ position: relative;
+ aspect-ratio: 16 / 10;
+ min-height: 420px;
+ border-radius: var(--cz-radius);
+ overflow: hidden;
+ border: 1px solid var(--cz-border);
+ box-shadow: var(--cz-shadow);
+ background: #05060a;
+ isolation: isolate;
+ }
+ /* Designed empty/fallback backdrop: a slow living aurora so the stage is
+ never a dead void before (or instead of) a generated world. */
+ .cz-aurora {
+ position: absolute;
+ inset: -40%;
+ z-index: 0;
+ background:
+ radial-gradient(closest-side at 30% 35%, rgba(139, 124, 246, 0.55), transparent 70%),
+ radial-gradient(closest-side at 70% 60%, rgba(118, 224, 194, 0.5), transparent 70%),
+ radial-gradient(closest-side at 50% 80%, rgba(94, 137, 255, 0.4), transparent 70%);
+ filter: blur(20px) saturate(1.2);
+ animation: cz-drift 18s ease-in-out infinite alternate;
+ will-change: transform;
+ }
+ @keyframes cz-drift {
+ 0% {
+ transform: translate3d(-3%, -2%, 0) rotate(0deg) scale(1.05);
+ }
+ 100% {
+ transform: translate3d(4%, 3%, 0) rotate(8deg) scale(1.18);
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .cz-aurora {
+ animation: none;
+ }
+ }
+ .cz-world {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ opacity: 0;
+ transition: opacity 0.9s ease;
+ }
+ .cz-world.is-live {
+ opacity: 1;
+ }
+ .cz-stage::after {
+ /* gentle vignette so the avatar reads against any world */
+ content: '';
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ pointer-events: none;
+ background: radial-gradient(120% 90% at 50% 35%, transparent 55%, rgba(0, 0, 0, 0.45) 100%);
+ }
+ model-viewer.cz-avatar {
+ position: absolute;
+ inset: 0;
+ z-index: 3;
+ width: 100%;
+ height: 100%;
+ --poster-color: transparent;
+ background: transparent;
+ }
+
+ /* Loading scrim driven by real poll state */
+ .cz-scrim {
+ position: absolute;
+ inset: 0;
+ z-index: 5;
+ display: none;
+ flex-direction: column;
+ align-items: center;
+ justify-content: flex-end;
+ padding: 22px;
+ gap: 10px;
+ background: linear-gradient(0deg, rgba(4, 5, 10, 0.78), rgba(4, 5, 10, 0) 60%);
+ }
+ .cz-stage.is-loading .cz-scrim {
+ display: flex;
+ }
+ .cz-stage.is-loading::before {
+ /* scanline shimmer — signals active rendering, CSS only (no fake %). */
+ content: '';
+ position: absolute;
+ inset: 0;
+ z-index: 4;
+ background: linear-gradient(180deg, transparent 0%, rgba(118, 224, 194, 0.12) 50%, transparent 100%);
+ background-size: 100% 220%;
+ animation: cz-scan 1.7s linear infinite;
+ pointer-events: none;
+ }
+ @keyframes cz-scan {
+ 0% {
+ background-position: 0 -110%;
+ }
+ 100% {
+ background-position: 0 110%;
+ }
+ }
+ .cz-prog {
+ width: 100%;
+ max-width: 460px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .cz-prog-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-size: 13px;
+ color: #e8ecf6;
+ }
+ .cz-prog-bar {
+ height: 5px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.14);
+ overflow: hidden;
+ }
+ .cz-prog-bar i {
+ display: block;
+ height: 100%;
+ width: 30%;
+ border-radius: inherit;
+ background: linear-gradient(90deg, var(--cz-accent), var(--cz-accent-2));
+ transition: width 0.6s ease;
+ }
+ .cz-phases {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ font-size: 11.5px;
+ color: var(--cz-dim);
+ }
+ .cz-phases b {
+ color: var(--cz-accent);
+ font-weight: 600;
+ }
+
+ /* Result toolbar over the stage */
+ .cz-stage-tools {
+ position: absolute;
+ z-index: 6;
+ top: 12px;
+ right: 12px;
+ display: none;
+ gap: 8px;
+ }
+ .cz-stage.is-done .cz-stage-tools {
+ display: flex;
+ }
+ .cz-iconbtn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12.5px;
+ font-weight: 600;
+ color: #fff;
+ background: rgba(8, 10, 18, 0.62);
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ border-radius: 10px;
+ padding: 8px 12px;
+ cursor: pointer;
+ backdrop-filter: blur(6px);
+ transition:
+ background 0.16s ease,
+ transform 0.16s ease;
+ }
+ .cz-iconbtn:hover {
+ background: rgba(20, 24, 40, 0.85);
+ transform: translateY(-1px);
+ }
+ .cz-iconbtn:focus-visible {
+ outline: 2px solid var(--cz-accent);
+ outline-offset: 2px;
+ }
+
+ /* ── Control panel ────────────────────────────────────────────── */
+ .cz-panel {
+ background: var(--cz-panel);
+ backdrop-filter: blur(14px);
+ border: 1px solid var(--cz-border);
+ border-radius: var(--cz-radius);
+ padding: 18px;
+ box-shadow: var(--cz-shadow);
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ align-self: start;
+ }
+ .cz-h {
+ font-size: 18px;
+ font-weight: 700;
+ margin: 0;
+ letter-spacing: -0.2px;
+ }
+ .cz-sub {
+ margin: 2px 0 0;
+ font-size: 13px;
+ color: var(--cz-dim);
+ line-height: 1.5;
+ }
+ .cz-label {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--cz-dim);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ margin-bottom: 8px;
+ display: block;
+ }
+ .cz-textarea {
+ width: 100%;
+ min-height: 84px;
+ resize: vertical;
+ background: rgba(0, 0, 0, 0.28);
+ border: 1px solid var(--cz-border);
+ border-radius: 12px;
+ color: var(--cz-text);
+ font: inherit;
+ font-size: 14.5px;
+ line-height: 1.5;
+ padding: 12px 14px;
+ transition: border-color 0.16s ease, box-shadow 0.16s ease;
+ }
+ html[data-theme='light'] .cz-textarea {
+ background: rgba(10, 12, 20, 0.04);
+ }
+ .cz-textarea:focus {
+ outline: none;
+ border-color: var(--cz-accent);
+ box-shadow: 0 0 0 3px rgba(118, 224, 194, 0.18);
+ }
+ .cz-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 7px;
+ margin-top: 10px;
+ }
+ .cz-chip {
+ font-size: 12.5px;
+ color: var(--cz-text);
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid var(--cz-border);
+ border-radius: 999px;
+ padding: 6px 11px;
+ cursor: pointer;
+ transition: background 0.14s ease, border-color 0.14s ease, transform 0.14s ease;
+ }
+ .cz-chip:hover {
+ background: rgba(118, 224, 194, 0.12);
+ border-color: rgba(118, 224, 194, 0.4);
+ transform: translateY(-1px);
+ }
+ .cz-chip:focus-visible {
+ outline: 2px solid var(--cz-accent);
+ outline-offset: 2px;
+ }
+
+ .cz-generate {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 9px;
+ width: 100%;
+ font-size: 15px;
+ font-weight: 700;
+ color: #05140f;
+ background: linear-gradient(120deg, var(--cz-accent), var(--cz-accent-2));
+ border: none;
+ border-radius: 12px;
+ padding: 14px 18px;
+ cursor: pointer;
+ transition: transform 0.16s ease, filter 0.16s ease, opacity 0.16s ease;
+ }
+ .cz-generate:hover:not(:disabled) {
+ transform: translateY(-1px);
+ filter: brightness(1.06);
+ }
+ .cz-generate:focus-visible {
+ outline: 2px solid #fff;
+ outline-offset: 2px;
+ }
+ .cz-generate:disabled {
+ cursor: not-allowed;
+ opacity: 0.55;
+ }
+ .cz-generate .spin {
+ width: 16px;
+ height: 16px;
+ border: 2px solid rgba(5, 20, 15, 0.4);
+ border-top-color: #05140f;
+ border-radius: 50%;
+ animation: cz-spin 0.8s linear infinite;
+ display: none;
+ }
+ .cz-generate.is-busy .spin {
+ display: inline-block;
+ }
+ .cz-generate.is-busy .label-go {
+ display: none;
+ }
+ @keyframes cz-spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .cz-secondary {
+ display: flex;
+ gap: 8px;
+ }
+ .cz-btn-ghost {
+ flex: 1;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--cz-text);
+ background: transparent;
+ border: 1px solid var(--cz-border);
+ border-radius: 11px;
+ padding: 11px;
+ cursor: pointer;
+ transition: background 0.14s ease, border-color 0.14s ease;
+ }
+ .cz-btn-ghost:hover {
+ background: rgba(255, 255, 255, 0.05);
+ border-color: var(--cz-accent);
+ }
+ .cz-btn-ghost:focus-visible {
+ outline: 2px solid var(--cz-accent);
+ outline-offset: 2px;
+ }
+
+ /* Avatar picker */
+ .cz-avatars {
+ display: grid;
+ grid-template-columns: repeat(5, 1fr);
+ gap: 8px;
+ }
+ .cz-av {
+ position: relative;
+ aspect-ratio: 1;
+ border-radius: 12px;
+ overflow: hidden;
+ border: 1.5px solid var(--cz-border);
+ background: rgba(0, 0, 0, 0.3);
+ cursor: pointer;
+ padding: 0;
+ transition: border-color 0.14s ease, transform 0.14s ease;
+ }
+ .cz-av:hover {
+ transform: translateY(-2px);
+ }
+ .cz-av img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .cz-av .ph {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+ font-size: 18px;
+ color: var(--cz-dim);
+ }
+ .cz-av.is-active {
+ border-color: var(--cz-accent);
+ box-shadow: 0 0 0 2px rgba(118, 224, 194, 0.3);
+ }
+ .cz-av:focus-visible {
+ outline: 2px solid var(--cz-accent);
+ outline-offset: 2px;
+ }
+
+ /* Status / error banner */
+ .cz-note {
+ display: none;
+ font-size: 13px;
+ line-height: 1.5;
+ border-radius: 11px;
+ padding: 11px 13px;
+ border: 1px solid var(--cz-border);
+ }
+ .cz-note.show {
+ display: block;
+ }
+ .cz-note.err {
+ color: #ffd8d8;
+ background: rgba(255, 107, 107, 0.1);
+ border-color: rgba(255, 107, 107, 0.4);
+ }
+ .cz-note.info {
+ color: var(--cz-text);
+ background: rgba(139, 124, 246, 0.1);
+ border-color: rgba(139, 124, 246, 0.35);
+ }
+ .cz-note a {
+ color: var(--cz-accent);
+ }
+
+ details.cz-adv {
+ border-top: 1px solid var(--cz-border);
+ padding-top: 12px;
+ }
+ details.cz-adv summary {
+ cursor: pointer;
+ font-size: 12.5px;
+ color: var(--cz-dim);
+ list-style: none;
+ }
+ details.cz-adv summary::-webkit-details-marker {
+ display: none;
+ }
+ .cz-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-top: 10px;
+ }
+ .cz-row input[type='number'] {
+ flex: 1;
+ background: rgba(0, 0, 0, 0.28);
+ border: 1px solid var(--cz-border);
+ border-radius: 10px;
+ color: var(--cz-text);
+ font: inherit;
+ padding: 9px 11px;
+ }
+ .cz-foot {
+ font-size: 11.5px;
+ color: var(--cz-dim);
+ line-height: 1.5;
+ text-align: center;
+ }
+
+ /* Toast */
+ .cz-toast {
+ position: fixed;
+ left: 50%;
+ bottom: 26px;
+ transform: translateX(-50%) translateY(20px);
+ z-index: 80;
+ background: var(--cz-panel-solid);
+ color: var(--cz-text);
+ border: 1px solid var(--cz-border);
+ border-radius: 12px;
+ padding: 11px 16px;
+ font-size: 13.5px;
+ font-weight: 600;
+ box-shadow: var(--cz-shadow);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.25s ease, transform 0.25s ease;
+ }
+ .cz-toast.show {
+ opacity: 1;
+ transform: translateX(-50%) translateY(0);
+ }
+ </style>
+ </head>
+ <body>
+ <header class="cz-bar">
+ <a class="cz-back" href="/forge" aria-label="Back to the Forge">
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <path d="M15 18l-6-6 6-6" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ Forge
+ </a>
+ <div class="cz-brand">
+ <b>Cosmos · Living Worlds</b>
+ <span>NVIDIA world models — type a world, watch your avatar live in it</span>
+ </div>
+ <div class="cz-badge" id="cz-status-badge" title="Cosmos lane status">
+ <span class="dot"></span>
+ <span id="cz-status-text">NVIDIA Cosmos</span>
+ </div>
+ </header>
+
+ <main class="cz-wrap">
+ <!-- Stage: avatar composited in front of the living world -->
+ <section class="cz-stage" id="cz-stage" aria-label="Avatar world stage">
+ <div class="cz-aurora" aria-hidden="true"></div>
+ <video class="cz-world" id="cz-world" muted loop playsinline preload="auto" aria-hidden="true"></video>
+ <model-viewer
+ class="cz-avatar"
+ id="cz-avatar"
+ camera-controls
+ auto-rotate
+ auto-rotate-delay="600"
+ rotation-per-second="14deg"
+ interaction-prompt="none"
+ shadow-intensity="0.9"
+ exposure="1.05"
+ camera-orbit="0deg 88deg 2.6m"
+ field-of-view="32deg"
+ disable-zoom
+ alt="Your 3D avatar"
+ ></model-viewer>
+
+ <div class="cz-stage-tools">
+ <button class="cz-iconbtn" id="cz-download" type="button" title="Download the world clip (MP4)">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <path d="M12 3v12m0 0l-4-4m4 4l4-4M5 21h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ MP4
+ </button>
+ <button class="cz-iconbtn" id="cz-copy" type="button" title="Copy a shareable link to this world">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <path d="M10 13a5 5 0 007 0l2-2a5 5 0 00-7-7l-1 1m-1 8a5 5 0 01-7 0l-2-2a5 5 0 017-7l1 1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ Share
+ </button>
+ </div>
+
+ <div class="cz-scrim" role="status" aria-live="polite">
+ <div class="cz-prog">
+ <div class="cz-prog-row">
+ <span id="cz-prog-label">Summoning the world…</span>
+ <span id="cz-prog-time">0s</span>
+ </div>
+ <div class="cz-prog-bar"><i id="cz-prog-fill"></i></div>
+ <div class="cz-phases" id="cz-phases">
+ <b>Submitting</b><span>· Rendering frames</span><span>· Finalizing</span>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Controls -->
+ <aside class="cz-panel">
+ <div>
+ <h1 class="cz-h">Bring your avatar to life</h1>
+ <p class="cz-sub">
+ NVIDIA Cosmos renders a living, photoreal world from your words. Describe a place — your
+ avatar steps straight into it.
+ </p>
+ </div>
+
+ <div>
+ <label class="cz-label" for="cz-prompt">Describe the world</label>
+ <textarea
+ id="cz-prompt"
+ class="cz-textarea"
+ maxlength="300"
+ placeholder="a neon Tokyo street in the rain at night, reflections shimmering on the pavement"
+ ></textarea>
+ <div class="cz-chips" id="cz-chips" role="group" aria-label="Prompt ideas"></div>
+ </div>
+
+ <button class="cz-generate" id="cz-generate" type="button">
+ <span class="spin" aria-hidden="true"></span>
+ <span class="label-go">Generate world</span>
+ </button>
+ <div class="cz-secondary" id="cz-secondary" style="display: none">
+ <button class="cz-btn-ghost" id="cz-cancel" type="button">Cancel</button>
+ <button class="cz-btn-ghost" id="cz-regen" type="button" style="display: none">New world</button>
+ </div>
+
+ <div class="cz-note" id="cz-note" role="alert"></div>
+
+ <div>
+ <label class="cz-label">Choose your avatar</label>
+ <div class="cz-avatars" id="cz-avatars"></div>
+ </div>
+
+ <details class="cz-adv">
+ <summary>Advanced</summary>
+ <div class="cz-row">
+ <label class="cz-label" for="cz-seed" style="margin: 0">Seed</label>
+ <input id="cz-seed" type="number" min="0" max="4294967295" placeholder="random" />
+ </div>
+ </details>
+
+ <p class="cz-foot">
+ Each world is a ~5-second 1280×704 clip from NVIDIA Cosmos. Free, on the NVIDIA NIM tier.
+ </p>
+ </aside>
+ </main>
+
+ <div class="cz-toast" id="cz-toast" role="status" aria-live="polite"></div>
+
+ <script type="module" src="/src/cosmos.js"></script>
+ </body>
+</html>
diff --git a/pages/create.html b/pages/create.html
index b4b6de0c0..4857eb18b 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -1382,6 +1382,38 @@
</svg>
</span>
</div>
+ <div
+ class="create-card tile"
+ id="card-cosmos"
+ role="button"
+ tabindex="0"
+ aria-label="Bring your avatar to life with a Cosmos living world"
+ >
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="3.2" />
+ <path d="M12 2.5c3 3.4 3 13.6 0 19M12 2.5c-3 3.4-3 13.6 0 19" />
+ <path d="M2.5 12c3.4-3 13.6-3 19 0M2.5 12c3.4 3 13.6 3 19 0" />
+ </svg>
+ </div>
+ <h2 class="card-title">Living world (Cosmos)</h2>
+ </div>
+ <p class="card-subtitle">
+ Type a world and NVIDIA Cosmos renders a living, photoreal scene behind your avatar — a cinematic clip you can download.
+ </p>
+ <div class="card-meta" aria-hidden="true">
+ <span class="chip">NVIDIA Cosmos</span>
+ <span class="chip">Free</span>
+ </div>
+ <span class="card-cta card-cta--ghost">
+ Open Cosmos
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
+ </div>
<div
class="create-card tile"
id="card-upload-glb"
diff --git a/prompts/agent-wallets-ii/04-money-constellation.md b/prompts/agent-wallets-ii/04-money-constellation.md
deleted file mode 100644
index 13d3a3b7f..000000000
--- a/prompts/agent-wallets-ii/04-money-constellation.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# Task 04 — The Money Constellation: a live map of value flowing between agents
-
-> Read [00-README-orchestration.md](./00-README-orchestration.md) first. This task
-> assumes all of it (ownership model, hard rules, design tokens, real APIs, concurrency
-> traps, definition of done, self-improve-then-delete).
-
-## The idea (why it's gamechanging)
-
-three.ws already renders its agents as a **galaxy of stars** ([src/galaxy.js] +
-[api/galaxy.js]). Turn it into a **living economy you can watch.** Every tip, stream,
-agent-to-agent payment, snipe, and coin launch becomes a **pulse of light traveling
-between stars** in real time. Zoom out and you see the whole economy breathing; zoom in
-and you see who pays whom, who earns, who's hot right now. Click an edge to see the real
-transaction; click a star to see that agent's money in/out.
-
-Nobody has a real-time, on-chain, embodied **money map** of an agent economy. It's a
-flagship "look what three.ws is" artifact — beautiful, screenshot-bait, and genuinely
-useful for discovering who's active and where value concentrates. It's also the natural
-home for the data the rest of the wave produces (tips 05, streams 01, intents 02).
-
-## How to build it for real (every edge is a real transaction)
-
-1. **Real flow feed.** Build a flows endpoint, e.g. `GET /api/economy/flows?since=…`, that
- returns recent **real** value movements between agents from sources that already exist:
- - tips + streams + agent-to-agent x402 payments + trades from `agent_custody_events`
- (`listCustodyEvents` across agents — add an admin/aggregate read that selects recent
- events with `from`/destination resolvable to agents),
- - launches from the pump feed / launch records,
- - resolve counterparties to agent ids where possible (a tip's `from` may be an external
- wallet — represent those as "external" nodes on the rim, not fake agents).
- Each flow: `{ id, kind, from, to, asset, amount, usd, signature, ts }`. **Never
- fabricate edges** — if a counterparty can't be resolved, show it honestly as external.
- Respect rate limits + cache; this is a hot read.
-2. **Live updates.** Stream new flows over SSE (mirror the existing live patterns, e.g.
- [api/club/tips-stream.js]) so the map animates as money actually moves. Reconnect/backoff
- on drop; render last-known on stale (with a clear "reconnecting" affordance, like the
- leaderboard already does).
-3. **Visualization.** Extend the existing Three.js galaxy:
- - animate a light particle along the arc from source star to target star on each flow,
- sized/brightness by `usd`, colored by `kind` (tip / stream / pay / trade / launch),
- wallet-violet as the family accent;
- - persistent faint edges for established relationships (who pays whom often);
- - a star's brightness/size can reflect recent net flow (coordinate with Embodied
- Finance, task 03, so the two share one wealth signal rather than two).
- GPU-cheap: instanced particles, pooled geometry, LOD by zoom, cap concurrent animations
- and queue overflow. No per-frame allocations.
-4. **Inspect.** Click an edge → a panel with the real tx (Solscan link), both agents, and
- amount. Click a star → that agent's money in/out summary (real, from custody) with deep
- links to its profile/wallet. Filters: by kind, by time window, by "my agents."
-
-## The UI
-
-- A dedicated mode on the galaxy ("Economy" toggle) plus a compact "live flows" ticker
- that can be embedded on the home/trending surfaces (real data, links through).
-- Legend, time-window control, kind filters, play/pause, and a "follow this agent's money"
- focus. Empty state (quiet market → "no flows in the last N min, here's the last hour"),
- loading skeletons over the 3D canvas, error/reconnecting states. a11y: the map has a
- parallel accessible list view of recent flows (keyboard-navigable, screen-reader-readable)
- — never make the data *only* available as moving 3D. Respect reduced-motion (static
- edges + the list).
-
-## Ownership / viewer states
-
-- **Public** map of public flows (tips/streams/pays/trades/launches are public on-chain
- events). Never expose owner-only figures (spend policy, exact custody notes) — only the
- public movement + amount + signature.
-- **Owner** can highlight/follow their own agents' flows ("my money map").
-- **Logged-out**: full read-only map; connecting unlocks "follow my agents."
-
-## Definition of done (in addition to 00's list)
-
-- Every rendered edge corresponds to a **real** transaction with a working explorer link;
- external counterparties shown honestly, never faked into agents.
-- Live SSE updates with robust reconnect/stale handling; cached aggregate reads respect
- RPC + DB limits.
-- 3D performant at scale (hundreds of agents, bursts of flows) with LOD + pooling; full
- reduced-motion + accessible list fallback.
-- Inspect panels show real data + deep links; filters and time windows work.
-- Edge cases: dead-quiet market (0 flows), a single whale dominating, 1000 flows in a
- burst (queue/throttle), unresolved counterparties, SSE dropped.
-
-## Then improve, then delete
-
-After done, run the self-review protocol. Pick the biggest weakness and fix it — e.g. a
-shareable snapshot/replay of "the last hour of the economy," or surfacing the hottest
-earning agent right now as a discovery hook on the home page. Then **delete this file**.
diff --git a/prompts/agent-wallets/10-strategy-objects.md b/prompts/agent-wallets/10-strategy-objects.md
deleted file mode 100644
index 19324825a..000000000
--- a/prompts/agent-wallets/10-strategy-objects.md
+++ /dev/null
@@ -1,91 +0,0 @@
-# Task 10 — Strategy Objects (an ownable, equippable, shareable trade strategy)
-
-> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** — the
-> invention bar, ownership model, tokens, real APIs, hard rules, and the "improve
-> then delete this file" close-out. Depends on the trade execution engine
-> (**task 05**). Every automated action runs through the spend policy and audit — read
-> "safe by construction" twice.
-
-## Mission
-
-Make a trading strategy a **first-class object** an agent can equip — like a skill or
-an item, not a buried setting. A Strategy Object encodes a real, rule-based plan
-("snipe launches under N minutes old with >X liquidity, size 0.2 SOL, take-profit at
-2x, stop at -40%") as a named, ownable, shareable thing. Equip it on your agent and,
-within your spend policy, the agent executes it for real, on-chain.
-
-Why only three.ws: the strategy is bound to a character with its own real wallet, its
-own real track record, and a hard spend leash. Strategies become collectible,
-forkable, leaderboard-ranked assets — a marketplace of *how agents trade*, all proven
-on real chain data.
-
-## What exists (read it before building)
-
-- Execution engine: task-05 `POST /api/agents/:id/solana/trade` and its spend-guard /
- audit path — strategies trigger trades **only** through it.
-- Real triggers: the pump.fun launch feed
- ([api/_lib/agent-pumpfun.js](../../api/_lib/agent-pumpfun.js)), real prices and
- holdings ([api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js),
- `.../solana/holdings`), and the agent's real positions/P&L from task 05.
-- Spend policy: `.../solana/limits` bounds every strategy action. Ownership +
- fork lineage patterns from [api/agents/fork.js](../../api/agents/fork.js) — reuse
- them so strategies can be forked with proper attribution.
-
-## How it must work
-
-1. **Strategy as a real object.** Persist strategies server-side as structured,
- validated rule sets (entry conditions, sizing, take-profit, stop-loss, max
- concurrent positions, cooldown). Owner-authored, named, with a real config schema —
- not free text. Versioned.
-2. **Equip / unequip on an agent.** Equipping activates the strategy for that agent;
- the agent evaluates real triggers (a real new launch, a real price move) and, on a
- match, executes via the task-05 engine within the spend policy. Unequip stops it
- cleanly. A global kill-switch halts all strategies at once.
-3. **Real evaluation, no fake backtests.** If you show expected performance, it must
- be a real backtest over real historical data you actually have, clearly labeled as
- backtest vs live. Never fabricate a curve. Live performance comes from real fills.
-4. **Shareable & forkable.** A strategy can be published, viewed, and forked into
- another owner's library (fresh ownership, lineage credited to the author, like
- avatar/agent forks). Forking a strategy never grants access to anyone's wallet — it
- copies the *rules*, and the forker runs them under *their own* spend policy.
-5. **Fully audited & leashed.** Every strategy-initiated trade is labeled (reason:
- `strategy:<name>`) in the custody trail, counts against the daily budget, and is
- owner-only to configure. No strategy can exceed the spend policy. Ever.
-
-## Innovation mandate
-
-- **Trading know-how becomes a collectible.** "Equip a strategy your favorite agent
- uses" is a brand-new primitive — ownable alpha, ranked by real on-chain results,
- forkable with attribution. That's a moat no DEX or bot has.
-- **Strategies have track records.** Rank published strategies by real, verified live
- performance (and honest drawdown/risk). Make discovery delightful and the numbers
- impossible to fake.
-- **Cross-pollinate.** A Strategy Object should feel native next to agent skills and
- the mirror graph (task 09): mirror an agent *or* equip its strategy. Wire that
- relationship. Surface equipped strategies on the wallet identity layer.
-- Invent beyond this where it raises the bar — but every trigger, trade, and
- performance number is real and on-chain; backtests are real and labeled.
-
-## States & edge cases (all designed)
-
-Strategy whose next action exceeds the spend budget (skip + notify, never overspend);
-conflicting equipped strategies (define precedence, no double-spend); a trigger firing
-during a network outage (reconcile against real chain state, no duplicate fills);
-take-profit/stop-loss on a position with no real entry basis (honest handling);
-forking a strategy (new owner, lineage, no wallet access transferred); equipping on an
-agent you don't own (refused server-side); unequip mid-evaluation (clean stop);
-0 / 1 / many equipped strategies; very long strategy names; a published strategy with
-no live history yet (honest "unproven" state).
-
-## Definition of done
-
-Per the orchestration README. Plus: a real strategy object persists and validates;
-equipping it causes a **real** trigger-driven trade through the task-05 engine within
-the spend policy (devnet acceptable), labeled in the custody trail; the kill-switch
-halts it; a strategy can be forked into another library with lineage and no wallet
-access; performance shown is real (live) or a real, labeled backtest; owner-only
-enforced in UI and server; no console errors; responsive.
-
-When done: self-review + improvement pass, changelog entry, commit (explicit paths
-only, push to **both** remotes if asked), then **delete this file**
-(`prompts/agent-wallets/10-strategy-objects.md`).
diff --git a/public/changelog.json b/public/changelog.json
index 83125fdaa..acdd2200d 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-23T05:35:52.601Z",
+ "generated_at": "2026-06-23T05:49:20.777Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "Cosmos — Living Worlds",
+ "summary": "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.",
+ "link": "/cosmos",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -26,6 +36,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "Strategy Objects",
+ "summary": "A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.",
+ "link": "/strategies",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -47,6 +67,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Cosmos Living Worlds: type a world, watch your avatar live in it",
+ "summary": "Your avatar no longer has to stand in an empty void. The new Cosmos page turns a few words into a living, photoreal world that plays as a cinematic backdrop behind your 3D avatar — describe a neon Tokyo street in the rain, an alpine lake at sunrise, or a bioluminescent forest at midnight, and NVIDIA's Cosmos world model renders a short animated scene around your character. Pick any avatar (your own creations included), tap a prompt idea or write your own, and watch real progress as the clip renders; when it's done you can download the MP4 or copy a shareable link that reopens the exact world and avatar. It runs free on the NVIDIA NIM tier, and if the lane is ever unavailable your avatar still shines on a living animated backdrop instead of a blank screen. Find it on the Create page or at /cosmos.",
+ "link": "/cosmos",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -67,6 +97,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Embodied Finance: agents now wear their wallet",
+ "summary": "Every agent's 3D body now shows its real wealth at a glance — no charts. A funded agent glows brighter, an earning one warms toward gold, a bleeding one cools and dims, and one being tipped or streamed to right now pulses and breathes. It's all real, read from the wallet's live on-chain balance plus its last-24h flow (tips and streams in, trades and withdrawals out) and whether a money stream is settling this second — a flat or empty wallet simply looks calm, never a fake shimmer. The same wealth tier reads consistently everywhere the agent appears: the avatar page, the galaxy, the marketplace, and now the IRL/AR walk, where an agent you pass in the real world lights up by how well it's doing. Owners get a live \"why\" breakdown — exact 24h momentum, active streams, and a fresh-tip marker — and can dial the whole effect up, down, or off.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -167,6 +207,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Image understanding is now a callable API",
+ "summary": "The free vision capability that already reads Forge uploads, weighs image evidence in the Fact Checker, and writes gallery alt text is now exposed as a public endpoint, /api/vision, so your own agents and tools can use it too. Send an image — as a file or a link — with a question, and get back a plain-language answer on the same free models the platform runs on, with a paid model as an automatic backstop. It's metered fairly and fails open, so it adds a new capability without changing anything that already works.",
+ "link": null,
+ "tags": [
+ "sdk"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -240,6 +290,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Money Streams: pay an agent by the second",
+ "summary": "You can now stream value to any agent in real time instead of sending one lump tip. Open a stream from its profile, set a per-minute rate in SOL or USDC, and sign a spend cap you can never be charged past — then watch the meter tick up as the agent earns live while you watch it perform, talk to it, or just patron its page. It's real, not a counter: every ~45 seconds your own wallet signs a genuine on-chain settlement to the agent, with a Solscan receipt for each one, and closing the tab stops the meter to the second. Owners get a live \"earning now\" view with lifetime totals and a 30-day chart. Non-custodial throughout — three.ws never holds the funds.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -304,6 +364,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Patronage: tips that build a real relationship with an agent",
+ "summary": "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.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -376,6 +446,16 @@
"infra"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Strategy Objects: equip an ownable, forkable trade strategy on your agent",
+ "summary": "A trading strategy is now a first-class thing you can own, share, and equip — not a buried setting. Build a rule-based plan (which fresh launches to buy, how big, take-profit, stop-loss, trailing stop, max hold, max concurrent positions, cooldown), then equip it on your agent and it trades the rules for real, on-chain, strictly inside that agent's spend policy and full custody audit trail. Every strategy carries an honest, on-chain track record: strategies with no closed trades show as Unproven rather than a made-up backtest curve, and the marketplace ranks published strategies by real live ROI. Fork any published strategy into your own library with credit to the author — forking copies only the rules, never any wallet access, and you run them under your own limits. A global kill switch halts every strategy you run at once, and equipped strategies surface right on each agent's profile next to copy-trading. Browse and manage everything at /strategies.",
+ "link": "/strategies",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index de7d37f30..698bbaa74 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Cosmos — Living Worlds</title>
+ <link>https://three.ws/cosmos</link>
+ <guid isPermaLink="false">2026-06-23:Cosmos — Living Worlds</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>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.</description>
+ </item>
<item>
<title>Guardian console — recover &amp; inherit agent wallets</title>
<link>https://three.ws/guardian</link>
@@ -22,6 +30,14 @@
<category>launch</category>
<description>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.</description>
</item>
+ <item>
+ <title>Strategy Objects</title>
+ <link>https://three.ws/strategies</link>
+ <guid isPermaLink="false">2026-06-23:Strategy Objects</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.</description>
+ </item>
<item>
<title>Avatar creation errors are clearer — and never leak a vendor's billing page</title>
<link>https://three.ws/changelog</link>
@@ -38,6 +54,14 @@
<category>improvement</category>
<description>On the Copy Trading page, every one of your agents listed under &quot;your copy-trading&quot; now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears.</description>
</item>
+ <item>
+ <title>Cosmos Living Worlds: type a world, watch your avatar live in it</title>
+ <link>https://three.ws/cosmos</link>
+ <guid isPermaLink="false">2026-06-23:Cosmos Living Worlds: type a world, watch your avatar live in it</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your avatar no longer has to stand in an empty void. The new Cosmos page turns a few words into a living, photoreal world that plays as a cinematic backdrop behind your 3D avatar — describe a neon Tokyo street in the rain, an alpine lake at sunrise, or a bioluminescent forest at midnight, and NVIDIA's Cosmos world model renders a short animated scene around your character. Pick any avatar (your own creations included), tap a prompt idea or write your own, and watch real progress as the clip renders; when it's done you can download the MP4 or copy a shareable link that reopens the exact world and avatar. It runs free on the NVIDIA NIM tier, and if the lane is ever unavailable your avatar still shines on a living animated backdrop instead of a blank screen. Find it on the Create page or at /cosmos.</description>
+ </item>
<item>
<title>Creating an agent never dead-ends on wallet setup</title>
<link>https://three.ws/changelog</link>
@@ -54,6 +78,14 @@
<category>fix</category>
<description>When an embedded avatar widget couldn't fetch its model — an expired draft link, a flaky network, a Safari load failure — it used to leave a blank box with no explanation. Now it shows a clear &quot;Couldn't load this model&quot; card with a Retry button, the same designed error state the rest of the app already used, so a transient hiccup is a one-tap recover instead of a dead embed.</description>
</item>
+ <item>
+ <title>Embodied Finance: agents now wear their wallet</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Embodied Finance: agents now wear their wallet</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every agent's 3D body now shows its real wealth at a glance — no charts. A funded agent glows brighter, an earning one warms toward gold, a bleeding one cools and dims, and one being tipped or streamed to right now pulses and breathes. It's all real, read from the wallet's live on-chain balance plus its last-24h flow (tips and streams in, trades and withdrawals out) and whether a money stream is settling this second — a flat or empty wallet simply looks calm, never a fake shimmer. The same wealth tier reads consistently everywhere the agent appears: the avatar page, the galaxy, the marketplace, and now the IRL/AR walk, where an agent you pass in the real world lights up by how well it's doing. Owners get a live &quot;why&quot; breakdown — exact 24h momentum, active streams, and a fresh-tip marker — and can dial the whole effect up, down, or off.</description>
+ </item>
<item>
<title>Every agent now carries a real, auditable trust score — and there's a leaderboard of the most trusted</title>
<link>https://three.ws/trending</link>
@@ -134,6 +166,14 @@
<category>fix</category>
<description>Models built on the free Hugging Face engines (avatars from a selfie, and Forge text/image/sketch→3D) were briefly served straight from the generator's scratch storage, which it wipes within minutes — so a model that loaded fine could 404 into a blank viewer moments later. Now the finished mesh is copied to our own durable storage the instant it's produced, while the file is still warm, and only that permanent URL is ever handed to your browser. The result is the same model, served from a link that doesn't expire.</description>
</item>
+ <item>
+ <title>Image understanding is now a callable API</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Image understanding is now a callable API</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>sdk</category>
+ <description>The free vision capability that already reads Forge uploads, weighs image evidence in the Fact Checker, and writes gallery alt text is now exposed as a public endpoint, /api/vision, so your own agents and tools can use it too. Send an image — as a file or a link — with a question, and get back a plain-language answer on the same free models the platform runs on, with a paid model as an automatic backstop. It's metered fairly and fails open, so it adds a new capability without changing anything that already works.</description>
+ </item>
<item>
<title>Improvement: an agent's wallet identity now shows on the galaxy and character pages too</title>
<link>https://three.ws/galaxy</link>
@@ -190,6 +230,14 @@
<category>fix</category>
<description>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.</description>
</item>
+ <item>
+ <title>Money Streams: pay an agent by the second</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Money Streams: pay an agent by the second</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>You can now stream value to any agent in real time instead of sending one lump tip. Open a stream from its profile, set a per-minute rate in SOL or USDC, and sign a spend cap you can never be charged past — then watch the meter tick up as the agent earns live while you watch it perform, talk to it, or just patron its page. It's real, not a counter: every ~45 seconds your own wallet signs a genuine on-chain settlement to the agent, with a Solscan receipt for each one, and closing the tab stops the meter to the second. Owners get a live &quot;earning now&quot; view with lifetime totals and a 30-day chart. Non-custodial throughout — three.ws never holds the funds.</description>
+ </item>
<item>
<title>More uploaded avatars animate out of the box — no more accidental T-poses</title>
<link>https://three.ws/changelog</link>
@@ -238,6 +286,14 @@
<category>feature</category>
<description>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.</description>
</item>
+ <item>
+ <title>Patronage: tips that build a real relationship with an agent</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Patronage: tips that build a real relationship with an agent</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>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 (&quot;tip to unlock&quot;), 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.</description>
+ </item>
<item>
<title>Prompt-to-avatar: a live progress bar you can cancel, plus motion and screen-reader polish</title>
<link>https://three.ws/create/prompt</link>
@@ -294,6 +350,14 @@
<category>fix</category>
<description>Two backend reliability fixes. The free image step behind text→3D now shrugs off a brief blip from NVIDIA's gateway — if it answers with a fast, transient hiccup, we retry once before handing off, so fewer prompts have to fall through to a slower backup and fewer fail outright. (A real timeout still hands off immediately, so nothing waits twice.) Separately, live token stats lean on several market-data sources; when one hits its monthly quota we already pause it, but each fresh server instance used to re-discover that the hard way and waste another doomed call. That pause is now shared across the whole fleet, so the moment one instance sees a source is exhausted, none of the others retry it — quieter, faster, and no wasted quota.</description>
</item>
+ <item>
+ <title>Strategy Objects: equip an ownable, forkable trade strategy on your agent</title>
+ <link>https://three.ws/strategies</link>
+ <guid isPermaLink="false">2026-06-23:Strategy Objects: equip an ownable, forkable trade strategy on your agent</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>A trading strategy is now a first-class thing you can own, share, and equip — not a buried setting. Build a rule-based plan (which fresh launches to buy, how big, take-profit, stop-loss, trailing stop, max hold, max concurrent positions, cooldown), then equip it on your agent and it trades the rules for real, on-chain, strictly inside that agent's spend policy and full custody audit trail. Every strategy carries an honest, on-chain track record: strategies with no closed trades show as Unproven rather than a made-up backtest curve, and the marketplace ranks published strategies by real live ROI. Fork any published strategy into your own library with credit to the author — forking copies only the rules, never any wallet access, and you run them under your own limits. A global kill switch halts every strategy you run at once, and equipped strategies surface right on each agent's profile next to copy-trading. Browse and manage everything at /strategies.</description>
+ </item>
<item>
<title>Talk to your agent and it trades — the Conversational Wallet</title>
<link>https://three.ws/changelog</link>
diff --git a/public/demos/audio2face.html b/public/demos/audio2face.html
new file mode 100644
index 000000000..72f36af03
--- /dev/null
+++ b/public/demos/audio2face.html
@@ -0,0 +1,506 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Audio2Face · two NVIDIA models on one face · three.ws</title>
+ <meta name="description" content="Type text, hear it in NVIDIA Magpie's voice, and watch the 3D avatar's face animate in real time — driven frame-for-frame by NVIDIA Audio2Face-3D. Real ARKit blendshapes, mapped onto any rig." />
+ <link rel="canonical" href="https://three.ws/audio2face" />
+ <meta property="og:title" content="Audio2Face · two NVIDIA models on one face · three.ws" />
+ <meta property="og:description" content="NVIDIA Magpie voice + NVIDIA Audio2Face-3D facial animation, in sync, in the browser. The avatar's lips track the real audio." />
+ <meta property="og:url" content="https://three.ws/audio2face" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Audio2Face · two NVIDIA models on one face · three.ws" />
+ <meta name="twitter:description" content="NVIDIA Magpie voice + NVIDIA Audio2Face-3D facial animation, in sync, in the browser." />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <style>
+ :root { color-scheme: dark; }
+ body { background: #060606; color: #eee; font: 15px/1.5 -apple-system, system-ui, sans-serif; margin: 0; }
+ .stage { max-width: 1100px; margin: 0 auto; padding: 48px 24px 90px; }
+ .crumb a { color: #8a8d98; text-decoration: none; }
+ .crumb a:hover { color: #76e0a1; }
+ h1 { font-size: 28px; font-weight: 600; letter-spacing: -0.015em; margin: 14px 0 8px; }
+ .sub { color: #8a8d98; max-width: 68ch; margin: 0 0 8px; }
+ .models { display: flex; flex-wrap: wrap; gap: 8px; margin: 14px 0 26px; }
+ .chip { display: inline-flex; align-items: center; gap: 7px; background: #0e140f; border: 1px solid #1d2a20; color: #9fe9bd; border-radius: 999px; padding: 5px 12px; font-size: 12px; font-weight: 600; }
+ .chip .dot { width: 7px; height: 7px; border-radius: 50%; background: #76e0a1; box-shadow: 0 0 8px #76e0a1; }
+ .chip.voice { background: #0d1117; border-color: #1c2430; color: #8fb7ff; }
+ .chip.voice .dot { background: #5b9bff; box-shadow: 0 0 8px #5b9bff; }
+ .row { display: grid; grid-template-columns: 1fr 340px; gap: 22px; }
+ @media (max-width: 900px) { .row { grid-template-columns: 1fr; } }
+ .viewer-host { background: #0c0e0c; border: 1.5px solid #1c241d; border-radius: 14px; min-height: 500px; position: relative; overflow: hidden; }
+ .viewer-host canvas { display: block; width: 100%; height: 100%; }
+ .viewer-label { position: absolute; top: 12px; left: 12px; background: rgba(0,0,0,0.6); padding: 5px 11px; border-radius: 999px; font-size: 11.5px; color: #76e0a1; font-weight: 600; letter-spacing: 0.02em; }
+ .viewer-badge { position: absolute; top: 12px; right: 12px; background: rgba(0,0,0,0.6); padding: 5px 11px; border-radius: 999px; font-size: 11.5px; color: #8a8d98; font-weight: 600; }
+ .viewer-badge b { color: #cfeede; }
+ .viewer-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 12px; color: #8a8d98; font-size: 13px; transition: opacity 0.3s ease; }
+ .viewer-loading[hidden] { display: none; }
+ .spinner { width: 30px; height: 30px; border-radius: 50%; border: 3px solid #1c241d; border-top-color: #76e0a1; animation: spin 0.8s linear infinite; }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ @media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 2.4s; } }
+ .panel { background: #0c0e0c; border: 1.5px solid #1c241d; border-radius: 14px; padding: 18px; display: flex; flex-direction: column; gap: 14px; }
+ .panel textarea { background: #070807; border: 1px solid #1c241d; color: #eee; padding: 11px 12px; border-radius: 9px; font: inherit; min-height: 88px; resize: vertical; }
+ .panel textarea:focus, .panel select:focus { outline: 2px solid #2c6b46; outline-offset: 1px; border-color: #2c6b46; }
+ .panel select { background: #070807; border: 1px solid #1c241d; color: #eee; padding: 8px 10px; border-radius: 9px; font: inherit; width: 100%; }
+ .panel label { font-size: 11px; color: #8a8d98; text-transform: uppercase; letter-spacing: 0.08em; }
+ .field { display: flex; flex-direction: column; gap: 5px; }
+ .grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
+ .btns { display: flex; gap: 8px; }
+ .panel button { background: #76e0a1; color: #06140c; border: 0; border-radius: 9px; padding: 11px 14px; font-weight: 700; cursor: pointer; font: inherit; transition: filter 0.15s ease, transform 0.1s ease; flex: 1; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
+ .panel button:hover:not(:disabled) { filter: brightness(1.07); }
+ .panel button:active:not(:disabled) { transform: translateY(1px); }
+ .panel button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+ .panel button.secondary { background: rgba(255,255,255,0.06); color: #eee; flex: 0 0 auto; }
+ .panel button:disabled { opacity: 0.45; cursor: not-allowed; }
+ .btn-spin { width: 14px; height: 14px; border-radius: 50%; border: 2px solid rgba(6,20,12,0.35); border-top-color: #06140c; animation: spin 0.7s linear infinite; }
+ .status { font-size: 12.5px; color: #8a8d98; min-height: 18px; display: flex; align-items: center; gap: 7px; }
+ .status .live-dot { width: 7px; height: 7px; border-radius: 50%; background: #76e0a1; animation: pulse 1.1s ease-in-out infinite; }
+ @keyframes pulse { 0%,100% { opacity: 0.35; } 50% { opacity: 1; } }
+ .pathline { font-size: 12px; color: #8a8d98; border-top: 1px solid #161c17; padding-top: 12px; }
+ .pathline b { color: #cfeede; font-weight: 600; }
+ .pathline.a2f b { color: #76e0a1; }
+ .pathline.fallback b { color: #ffd27a; }
+ .shapes { display: flex; flex-direction: column; gap: 6px; }
+ .shape-row { display: grid; grid-template-columns: 96px 1fr; gap: 8px; align-items: center; font-size: 11.5px; color: #8a8d98; font-family: ui-monospace, monospace; }
+ .meter { height: 7px; border-radius: 4px; background: rgba(118,224,161,0.12); overflow: hidden; }
+ .meter > span { display: block; height: 100%; width: 0%; background: linear-gradient(90deg,#3aa873,#76e0a1); border-radius: 4px; transition: width 0.05s linear; }
+ .a2f-error { background: rgba(255, 120, 86, 0.08); border: 1px solid rgba(255, 120, 86, 0.3); color: #ffc6ad; border-radius: 9px; padding: 11px 13px; font-size: 13px; line-height: 1.5; display: flex; align-items: center; gap: 10px; justify-content: space-between; }
+ .a2f-error[hidden] { display: none; }
+ .a2f-error span { flex: 1; }
+ .a2f-error strong { color: #fff; font-weight: 600; }
+ .a2f-error .retry { flex: 0 0 auto; cursor: pointer; font: inherit; font-weight: 600; color: #1a0d07; background: #ffb48a; border: 0; border-radius: 7px; padding: 7px 13px; }
+ .a2f-error .retry:hover { filter: brightness(1.07); }
+ .a2f-error .retry:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+ .foot { color: #6a6d75; font-size: 12px; margin-top: 28px; max-width: 70ch; }
+ .foot code { color: #9fe9bd; }
+ .foot a { color: #76e0a1; }
+ </style>
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Audio2Face","description":"NVIDIA Magpie voice + NVIDIA Audio2Face-3D facial animation, in sync, in the browser.","url":"https://three.ws/audio2face","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+
+ <main class="stage">
+ <p class="crumb"><a href="/">three.ws</a> · audio2face · <a href="/lipsync">amplitude lipsync</a></p>
+ <h1>Two NVIDIA models on one face</h1>
+ <p class="sub">
+ Type a line. It's spoken in <strong>NVIDIA Magpie</strong>'s voice, and that exact
+ audio is sent to <strong>NVIDIA Audio2Face-3D</strong>, which returns a per-frame
+ ARKit blendshape track. The avatar's mouth and face animate frame-for-frame with the
+ real voice — mapped onto whatever morph-target convention the loaded GLB ships
+ (ARKit, Ready Player Me, VRM, Oculus visemes). If Audio2Face is unavailable, the
+ avatar still speaks and falls back to amplitude lipsync — never a frozen face.
+ </p>
+ <div class="models">
+ <span class="chip voice"><span class="dot"></span>Magpie TTS · voice</span>
+ <span class="chip"><span class="dot"></span>Audio2Face-3D · facial animation</span>
+ </div>
+
+ <div class="row">
+ <div class="viewer-host" id="viewer-host">
+ <div class="viewer-label">live · Magpie → Audio2Face → morphs</div>
+ <div class="viewer-badge" id="viewer-badge">—</div>
+ <div class="viewer-loading" id="viewer-loading">
+ <div class="spinner"></div>
+ <div id="loading-text">Loading avatar…</div>
+ </div>
+ </div>
+ <div class="panel">
+ <div class="field">
+ <label for="text">Text to speak</label>
+ <textarea id="text">Hi! I'm a three dot w s avatar. My voice is NVIDIA Magpie, and my face is animated by NVIDIA Audio2Face, frame for frame.</textarea>
+ </div>
+
+ <div class="grid2">
+ <div class="field">
+ <label for="avatar">Avatar rig</label>
+ <select id="avatar">
+ <option value="/avatars/default.glb" data-conv="Oculus visemes">Default (visemes)</option>
+ <option value="/avatars/realistic-female.glb" data-conv="ARKit">Realistic female (ARKit)</option>
+ <option value="/avatars/realistic-male.glb" data-conv="ARKit">Realistic male (ARKit)</option>
+ <option value="/avatars/selfie-girl.glb" data-conv="ARKit">Selfie girl</option>
+ </select>
+ </div>
+ <div class="field">
+ <label for="voice">Voice</label>
+ <select id="voice">
+ <option value="nova" selected>Nova</option>
+ <option value="alloy">Alloy</option>
+ <option value="echo">Echo</option>
+ <option value="fable">Fable</option>
+ <option value="onyx">Onyx</option>
+ <option value="shimmer">Shimmer</option>
+ <option value="sage">Sage</option>
+ <option value="coral">Coral</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="btns">
+ <button id="speak"><span id="speak-label">Speak</span></button>
+ <button id="stop" class="secondary" disabled>Stop</button>
+ </div>
+
+ <div class="status" id="status" role="status" aria-live="polite"></div>
+
+ <div id="a2f-error" class="a2f-error" role="alert" aria-live="assertive" hidden></div>
+
+ <div class="pathline" id="pathline">Pipeline path will appear here after you press Speak.</div>
+
+ <div class="field">
+ <label>Live blendshapes</label>
+ <div class="shapes" id="shapes"></div>
+ </div>
+ </div>
+ </div>
+
+ <p class="foot">
+ Powered by <code>/api/a2f</code> (NVIDIA Audio2Face-3D over NVCF gRPC) and
+ <code>/api/tts/speak</code> (NVIDIA Magpie). The blendshape→morph mapping lives in
+ <code>src/voice/a2f-player.js</code> — it reuses the ARKit/VRM/Oculus vocabulary in
+ <code>src/voice/arkit-blendshapes.js</code>, so any humanoid rig lip-syncs without a
+ per-rig allowlist. See the <a href="/lipsync">amplitude-only lipsync demo</a> for the
+ fallback path on its own.
+ </p>
+ </main>
+
+ <script src="/nav.js" defer></script>
+ <script type="module">
+ import * as THREE from 'three';
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+ import { A2FPlayer } from '/src/voice/a2f-player.js';
+ import { LipsyncDriver, tapAudioElement } from '/src/voice/lipsync-driver.js';
+ import { AvatarMouthTarget } from '/src/voice/avatar-morph-target.js';
+
+ const $ = (id) => document.getElementById(id);
+ const host = $('viewer-host');
+ const statusEl = $('status');
+ const badgeEl = $('viewer-badge');
+ const pathEl = $('pathline');
+ const errEl = $('a2f-error');
+ const speakBtn = $('speak');
+ const speakLabel = $('speak-label');
+ const stopBtn = $('stop');
+ const loadingEl = $('viewer-loading');
+ const loadingText = $('loading-text');
+
+ // ── Live blendshape meters ────────────────────────────────────────────
+ const METERS = [
+ ['jawOpen', 'JawOpen'],
+ ['mouthFunnel', 'MouthFunnel'],
+ ['mouthSmileLeft', 'MouthSmile'],
+ ['mouthPucker', 'MouthPucker'],
+ ['browInnerUp', 'BrowInnerUp'],
+ ['eyeBlinkLeft', 'EyeBlink'],
+ ];
+ const meterBars = new Map();
+ for (const [key, label] of METERS) {
+ const row = document.createElement('div');
+ row.className = 'shape-row';
+ row.innerHTML = `<span>${label}</span><span class="meter"><span data-k="${key}"></span></span>`;
+ $('shapes').appendChild(row);
+ meterBars.set(key, row.querySelector(`[data-k="${key}"]`));
+ }
+ function paintMeters(getter) {
+ for (const [key] of METERS) {
+ const v = Math.max(0, Math.min(1, getter(key)));
+ meterBars.get(key).style.width = (v * 100).toFixed(0) + '%';
+ }
+ }
+ function clearMeters() { for (const [key] of METERS) meterBars.get(key).style.width = '0%'; }
+
+ // ── Three.js viewer ───────────────────────────────────────────────────
+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ renderer.setSize(host.clientWidth, host.clientHeight);
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ host.appendChild(renderer.domElement);
+
+ const scene = new THREE.Scene();
+ const camera = new THREE.PerspectiveCamera(26, host.clientWidth / host.clientHeight, 0.01, 100);
+ camera.position.set(0, 1.58, 0.7);
+ const controls = new OrbitControls(camera, renderer.domElement);
+ controls.target.set(0, 1.57, 0);
+ controls.enableDamping = true;
+ controls.minDistance = 0.35;
+ controls.maxDistance = 3.0;
+
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x404050, 1.15));
+ const key = new THREE.DirectionalLight(0xffffff, 1.5);
+ key.position.set(2, 4, 3);
+ scene.add(key);
+ const rim = new THREE.DirectionalLight(0x88ccff, 0.6);
+ rim.position.set(-3, 2, -2);
+ scene.add(rim);
+
+ window.addEventListener('resize', () => {
+ const w = host.clientWidth, h = host.clientHeight;
+ renderer.setSize(w, h);
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ });
+
+ const loader = new GLTFLoader();
+ const player = new A2FPlayer(); // A2F track-driven path
+ const mouthTarget = new AvatarMouthTarget(); // amplitude fallback target
+ let currentModel = null;
+ let avatarReady = false;
+
+ async function loadAvatar(url) {
+ avatarReady = false;
+ loadingEl.hidden = false;
+ loadingText.textContent = 'Loading avatar…';
+ badgeEl.textContent = '—';
+ try {
+ const gltf = await loader.loadAsync(url);
+ if (currentModel) { scene.remove(currentModel); disposeModel(currentModel); }
+ currentModel = gltf.scene;
+ // Frame the head: lift so the face sits at camera height regardless of rig origin.
+ const box = new THREE.Box3().setFromObject(currentModel);
+ const height = box.max.y - box.min.y;
+ if (height > 0.1) currentModel.position.y = -box.min.y;
+ scene.add(currentModel);
+
+ player.attach(currentModel);
+ mouthTarget.attach(currentModel);
+ avatarReady = true;
+ loadingEl.hidden = true;
+
+ const conv = $('avatar').selectedOptions[0]?.dataset.conv || '';
+ const cov = player.describe();
+ const drivers = cov.direct.length ? `${cov.direct.length} ARKit morphs` :
+ cov.expression.length ? `${cov.expression.length} viseme morphs (derived)` :
+ mouthTarget.hasMouthMorphs() ? 'mouth morphs' :
+ mouthTarget.hasJawBone() ? 'jaw bone' : 'head nod (fallback)';
+ badgeEl.innerHTML = `<b>${conv || 'rig'}</b> · ${drivers}`;
+ } catch (err) {
+ loadingText.textContent = `Avatar load failed: ${err.message}`;
+ }
+ }
+
+ function disposeModel(root) {
+ root.traverse((n) => {
+ if (n.geometry) n.geometry.dispose?.();
+ if (n.material) (Array.isArray(n.material) ? n.material : [n.material]).forEach((m) => m.dispose?.());
+ });
+ }
+
+ // ── Playback state ────────────────────────────────────────────────────
+ let audioEl = null;
+ let currentURL = null;
+ let mode = 'idle'; // 'a2f' | 'amplitude' | 'idle'
+ let amplitudeDriver = null;
+ let audioTap = null;
+
+ function tick() {
+ requestAnimationFrame(tick);
+ controls.update();
+ if (avatarReady && mode === 'a2f' && audioEl && !audioEl.paused) {
+ player.update(audioEl.currentTime);
+ paintMeters((k) => player.currentWeight(k));
+ }
+ renderer.render(scene, camera);
+ }
+ tick();
+
+ // ── Error banner ──────────────────────────────────────────────────────
+ function clearError() { errEl.hidden = true; errEl.innerHTML = ''; }
+ function showError(title, detail) {
+ errEl.innerHTML = `<span><strong>${title}</strong> ${detail}</span>`;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'retry';
+ btn.textContent = 'Retry';
+ btn.addEventListener('click', speak);
+ errEl.appendChild(btn);
+ errEl.hidden = false;
+ }
+
+ function setStatus(text, live) {
+ statusEl.innerHTML = live ? `<span class="live-dot"></span>${text}` : text;
+ }
+ function busy(on, label) {
+ speakBtn.disabled = on;
+ stopBtn.disabled = !on;
+ speakLabel.innerHTML = on ? `<span class="btn-spin"></span>${label || 'Working…'}` : 'Speak';
+ }
+
+ function teardownAudio() {
+ if (amplitudeDriver) { amplitudeDriver.stop(); amplitudeDriver = null; }
+ if (audioTap) { audioTap.disconnect(); audioTap = null; }
+ if (audioEl) { audioEl.pause(); audioEl.src = ''; audioEl = null; }
+ player.reset();
+ mouthTarget.setMouthShape({ open: 0, wide: 0, round: 0 });
+ clearMeters();
+ }
+
+ function onEnded() {
+ mode = 'idle';
+ busy(false);
+ setStatus('Done.');
+ player.reset();
+ clearMeters();
+ }
+
+ // ── The pipeline ──────────────────────────────────────────────────────
+ async function speak() {
+ const text = $('text').value.trim();
+ if (!text) { setStatus('Enter some text first.'); return; }
+ if (!avatarReady) { setStatus('Avatar still loading…'); return; }
+
+ clearError();
+ teardownAudio();
+ busy(true, 'Synthesizing…');
+ const voice = $('voice').value;
+
+ // Primary path: one round-trip to /api/a2f → Magpie audio + A2F track.
+ setStatus('Generating voice + facial animation…', true);
+ let data = null;
+ try {
+ const res = await fetch('/api/a2f', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text, voice }),
+ });
+ if (res.ok) {
+ data = await res.json();
+ } else {
+ const body = await res.json().catch(() => ({}));
+ // 503 not_configured (or 404 in an environment where the route
+ // isn't deployed yet) → drop to the amplitude fallback cleanly.
+ console.info(`[a2f] endpoint returned ${res.status} (${body.error || ''}); using amplitude fallback`);
+ }
+ } catch (err) {
+ console.info(`[a2f] request failed (${err.message}); using amplitude fallback`);
+ }
+
+ if (data?.animation?.frames?.length && data?.audio?.base64) {
+ return playA2F(data);
+ }
+ // Fallback: synthesize via /api/tts/speak and drive amplitude lipsync.
+ return playAmplitude(text, voice);
+ }
+
+ function makeAudio(blobUrl) {
+ if (currentURL) URL.revokeObjectURL(currentURL);
+ currentURL = blobUrl;
+ const el = new Audio();
+ el.crossOrigin = 'anonymous';
+ el.src = blobUrl;
+ el.addEventListener('ended', onEnded);
+ el.addEventListener('error', () => {
+ mode = 'idle'; busy(false);
+ showError('Playback failed.', 'The generated audio could not be played. Try again.');
+ });
+ return el;
+ }
+
+ function b64ToBlob(b64, type) {
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ return new Blob([bytes], { type });
+ }
+
+ async function playA2F(data) {
+ const anim = data.animation;
+ player.setTrack(anim);
+ if (!player.hasCoverage()) {
+ // Rig has no morphs A2F can drive — honour the track but the rig
+ // can't show it, so fall back to jaw/amplitude motion instead.
+ console.info('[a2f] track received but rig exposes no usable morphs; amplitude fallback');
+ return playAmplitude($('text').value.trim(), $('voice').value, data.audio);
+ }
+ const blob = b64ToBlob(data.audio.base64, data.audio.contentType || 'audio/wav');
+ audioEl = makeAudio(URL.createObjectURL(blob));
+ mode = 'a2f';
+ pathEl.className = 'pathline a2f';
+ pathEl.innerHTML = `<b>Audio2Face-3D</b> · ${anim.frameCount} frames @ ${anim.fps} fps · ${anim.blendShapeNames.length} ARKit blendshapes · ${anim.durationSec.toFixed(1)}s`;
+ try {
+ await audioEl.play();
+ busy(true, 'Speaking…');
+ setStatus('Lips tracking the real audio.', true);
+ } catch (err) {
+ mode = 'idle'; busy(false);
+ showError('Playback was blocked.', 'Your browser needs a click to play audio — press Retry.');
+ }
+ }
+
+ async function playAmplitude(text, voice, existingAudio) {
+ try {
+ let blobUrl;
+ if (existingAudio?.base64) {
+ blobUrl = URL.createObjectURL(b64ToBlob(existingAudio.base64, existingAudio.contentType || 'audio/wav'));
+ } else {
+ setStatus('Generating voice…', true);
+ const res = await fetch('/api/tts/speak', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text, voice, format: 'wav' }),
+ });
+ if (!res.ok) {
+ const detail = res.status === 429 ? 'Rate limit reached — wait a moment.' :
+ res.status >= 500 ? 'The speech service hit an error.' : `HTTP ${res.status}.`;
+ mode = 'idle'; busy(false);
+ setStatus('');
+ showError('Speech generation failed.', detail);
+ return;
+ }
+ blobUrl = URL.createObjectURL(await res.blob());
+ }
+
+ audioEl = makeAudio(blobUrl);
+ mode = 'amplitude';
+ pathEl.className = 'pathline fallback';
+ pathEl.innerHTML = `<b>Amplitude fallback</b> · Audio2Face unavailable — driving mouth shape from the audio envelope so the avatar never freezes.`;
+
+ // Web Audio analyser → LipsyncDriver → AvatarMouthTarget.
+ audioTap = tapAudioElement(audioEl);
+ amplitudeDriver = new LipsyncDriver({ analyser: audioTap.analyser, target: mouthTarget });
+ // Reflect the amplitude 'open' value on the JawOpen meter for feedback.
+ const origSet = mouthTarget.setMouthShape.bind(mouthTarget);
+ mouthTarget.setMouthShape = (s) => { origSet(s); paintMeters((k) => k === 'jawOpen' ? (s.open || 0) : 0); };
+ amplitudeDriver.start();
+
+ await audioEl.play();
+ busy(true, 'Speaking…');
+ setStatus('Speaking with amplitude lipsync.', true);
+ } catch (err) {
+ mode = 'idle'; busy(false);
+ showError('Could not play audio.', err.message || 'Try again.');
+ }
+ }
+
+ function stop() {
+ teardownAudio();
+ mode = 'idle';
+ busy(false);
+ setStatus('Stopped.');
+ }
+
+ speakBtn.addEventListener('click', speak);
+ stopBtn.addEventListener('click', stop);
+ $('avatar').addEventListener('change', () => { stop(); loadAvatar($('avatar').value); });
+
+ // Probe capability so the UI can hint when A2F isn't configured upstream.
+ fetch('/api/a2f', { method: 'GET' })
+ .then((r) => r.ok ? r.json() : null)
+ .then((cap) => {
+ if (cap && cap.configured === false) {
+ setStatus('Audio2Face is not configured on this deployment — the avatar will speak with amplitude lipsync.');
+ }
+ })
+ .catch(() => {});
+
+ loadAvatar($('avatar').value);
+ </script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/features.json b/public/features.json
index 2083d3b4c..fbf92ba87 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T05:35:52.581Z",
+ "generated_at": "2026-06-23T05:49:20.684Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -292,6 +292,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/cosmos",
+ "title": "Cosmos — Living Worlds",
+ "description": "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.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/scene",
"title": "Scene Studio",
@@ -876,6 +886,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/strategies",
+ "title": "Strategy Objects",
+ "description": "A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/vanity-wallet",
"title": "Solana Vanity Wallet",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 1c194a2dc..f74240628 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -182,6 +182,12 @@ URL: https://three.ws/forge-studio
One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.
+### Cosmos — Living Worlds
+
+URL: https://three.ws/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.
+
### Scene Studio
URL: https://three.ws/scene
@@ -532,6 +538,12 @@ URL: https://three.ws/strategy-lab
Build DCA and subscription strategies that trade on-chain on your behalf.
+### Strategy Objects
+
+URL: https://three.ws/strategies
+
+A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.
+
### Solana Vanity Wallet
URL: https://three.ws/vanity-wallet
diff --git a/public/llms.txt b/public/llms.txt
index 3a1305420..db5d82d27 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -41,6 +41,7 @@ Create and customize an agent.
- [Describe it to 3D](https://three.ws/create/prompt): Type a description. About a minute later: a rigged 3D avatar you can animate and download.
- [Forge — Text to 3D](https://three.ws/forge): Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
- [Studio — Object + Avatar from text](https://three.ws/forge-studio): One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.
+- [Cosmos — Living Worlds](https://three.ws/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.
- [Scene Studio](https://three.ws/scene): Full 3D scene editor in the browser — import GLB models, arrange them with transform gizmos, edit materials and lights, and export complete scenes.
- [Scene Composer](https://three.ws/compose): Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit.
- [Animation Studio](https://three.ws/pose): Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.
@@ -108,6 +109,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Watchlist](https://three.ws/watchlist): Your privately-stored watchlist of pump.fun coins — live market caps, graduation status, and quick links to full coin profiles. No account required; stored in your browser.
- [Pump Dashboard](https://three.ws/pump-dashboard): Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.
- [Strategy Lab](https://three.ws/strategy-lab): Build DCA and subscription strategies that trade on-chain on your behalf.
+- [Strategy Objects](https://three.ws/strategies): A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.
- [Solana Vanity Wallet](https://three.ws/vanity-wallet): Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.
- [Verify a Vanity Receipt](https://three.ws/vanity/verify): Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.
- [Proof-of-Grind Gallery](https://three.ws/vanity/gallery): A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.
diff --git a/public/nav-data.js b/public/nav-data.js
index 2db42428a..9abe5dc21 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -105,6 +105,12 @@ export const NAV_GROUPS = [
badge: 'New',
desc: 'Follow a proven agent by its honest on-chain track record — your agent mirrors its trades within your spend policy',
},
+ {
+ title: 'Strategy Objects',
+ href: '/strategies',
+ badge: 'New',
+ desc: 'Equip an ownable, forkable trade strategy on your agent — ranked by real on-chain results, run inside your spend policy',
+ },
{ title: 'Agents Index', href: '/agents', desc: 'Browse every registered agent' },
{ title: 'Marketplace', href: '/marketplace', desc: 'Buy, sell & remix agents' },
{ title: 'Avatar Gallery', href: '/gallery', desc: 'Every public 3D avatar' },
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index a8100022b..61a9b0359 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 200 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 202 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 200 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 202 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>
@@ -237,7 +237,7 @@
<section class="sm-section" id="build">
<header>
- <h2>Build<span class="sm-count" data-count>33</span></h2>
+ <h2>Build<span class="sm-count" data-count>34</span></h2>
<p class="sm-section-desc">Create and customize an agent.</p>
</header>
<ul class="sm-list">
@@ -297,6 +297,13 @@
<span class="sm-desc">One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.</span>
</a>
</li>
+ <li>
+ <a href="/cosmos">
+ <span class="sm-title">Cosmos — Living Worlds</span>
+ <span class="sm-path">/cosmos</span>
+ <span class="sm-desc">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.</span>
+ </a>
+ </li>
<li>
<a href="/scene">
<span class="sm-title">Scene Studio</span>
@@ -542,7 +549,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>55</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>56</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -714,6 +721,13 @@
<span class="sm-desc">Build DCA and subscription strategies that trade on-chain on your behalf.</span>
</a>
</li>
+ <li>
+ <a href="/strategies">
+ <span class="sm-title">Strategy Objects</span>
+ <span class="sm-path">/strategies</span>
+ <span class="sm-desc">A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.</span>
+ </a>
+ </li>
<li>
<a href="/vanity-wallet">
<span class="sm-title">Solana Vanity Wallet</span>
diff --git a/scripts/generate-a2f-descriptor.mjs b/scripts/generate-a2f-descriptor.mjs
new file mode 100644
index 000000000..7d4a2b89b
--- /dev/null
+++ b/scripts/generate-a2f-descriptor.mjs
@@ -0,0 +1,97 @@
+#!/usr/bin/env node
+// Regenerates api/_lib/a2f-protos/descriptor.js from the vendored NVIDIA
+// Audio2Face-3D (ACE) .proto sources.
+//
+// node scripts/generate-a2f-descriptor.mjs
+//
+// This is the A2F sibling of scripts/generate-riva-{tts,asr}-descriptor.mjs.
+// Audio2Face-3D is hosted as an NVCF gRPC function on grpc.nvcf.nvidia.com:443
+// (same transport as Magpie TTS and Riva ASR), selected by a `function-id`
+// metadata entry with the nvapi key as a bearer `authorization` entry. Its wire
+// contract is NVIDIA's ACE `nvidia_ace.services.a2f_controller.v1.A2FControllerService`
+// (bidirectional streaming ProcessAudioStream); the proto definitions are
+// vendored under api/_lib/a2f-protos/*.proto, copied verbatim from
+// https://github.com/NVIDIA/Audio2Face-3D-Samples (proto/protobuf_files), plus
+// minimal google/protobuf/{Any,Empty} stubs so the graph resolves without the
+// real well-known-type files on disk.
+//
+// Why a generated JS descriptor instead of loading .proto at runtime: api/
+// routes are esbuild-bundled in place on Vercel (scripts/bundle-api.mjs), so a
+// runtime fs read of a .proto would need fragile includeFiles + import.meta.url
+// path math. A checked-in JS module bundles cleanly, needs no filesystem at
+// runtime, and is loaded via @grpc/proto-loader's fromJSON().
+//
+// Parsed with keepCase:true so the gRPC surface uses the snake_case field names
+// from the proto (audio_stream_header, samples_per_second, blend_shape_weights,
+// time_code) — the same names NVIDIA's docs and Python samples use.
+
+import { readFile, writeFile } from 'fs/promises';
+import { fileURLToPath } from 'url';
+import { dirname, resolve } from 'path';
+import { createRequire } from 'module';
+
+const require = createRequire(import.meta.url);
+const protobuf = require('protobufjs');
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const PROTO_DIR = resolve(ROOT, 'api/_lib/a2f-protos');
+
+// Order matters only in that every referenced type must end up in the shared
+// root before resolveAll(); protobufjs resolves field references by fully
+// qualified type name, not by import filename, so the google stubs and leaf
+// messages are parsed first.
+const SOURCES = [
+ 'google_protobuf_any.proto',
+ 'google_protobuf_empty.proto',
+ 'nvidia_ace.audio.v1.proto',
+ 'nvidia_ace.animation_id.v1.proto',
+ 'nvidia_ace.status.v1.proto',
+ 'nvidia_ace.emotion_with_timecode.v1.proto',
+ 'nvidia_ace.a2f.v1.proto',
+ 'nvidia_ace.animation_data.v1.proto',
+ 'nvidia_ace.controller.v1.proto',
+ 'nvidia_ace.services.a2f_controller.v1.proto',
+];
+const OUTPUT = resolve(PROTO_DIR, 'descriptor.js');
+
+const root = new protobuf.Root();
+// Resolve the well-known-type imports ("google/protobuf/*.proto") to our
+// vendored stubs so resolveAll() never tries to read them off disk.
+const originalResolvePath = root.resolvePath.bind(root);
+root.resolvePath = (origin, target) => {
+ if (target.startsWith('google/protobuf/')) {
+ const stub = `google_protobuf_${target.slice('google/protobuf/'.length).replace(/\.proto$/, '')}.proto`;
+ return resolve(PROTO_DIR, stub);
+ }
+ if (!target.includes('/')) return resolve(PROTO_DIR, target);
+ return originalResolvePath(origin, target);
+};
+
+for (const name of SOURCES) {
+ const source = await readFile(resolve(PROTO_DIR, name), 'utf8');
+ protobuf.parse(source, root, { keepCase: true });
+}
+root.resolveAll();
+
+// Sanity: the exact surface api/_lib/a2f-nvidia.js depends on must exist.
+root.lookupService('nvidia_ace.services.a2f_controller.v1.A2FControllerService');
+root.lookupType('nvidia_ace.controller.v1.AudioStream');
+root.lookupType('nvidia_ace.controller.v1.AudioStreamHeader');
+root.lookupType('nvidia_ace.controller.v1.AnimationDataStream');
+root.lookupType('nvidia_ace.audio.v1.AudioHeader');
+root.lookupType('nvidia_ace.a2f.v1.AudioWithEmotion');
+root.lookupType('nvidia_ace.animation_data.v1.SkelAnimation');
+
+const banner = `// GENERATED FILE — do not edit by hand.
+// Regenerate with: node scripts/generate-a2f-descriptor.mjs
+// protobufjs JSON descriptor for NVIDIA Audio2Face-3D (ACE) — the
+// nvidia_ace.services.a2f_controller.v1.A2FControllerService gRPC surface,
+// parsed (keepCase) from the vendored protos in api/_lib/a2f-protos/*.proto,
+// themselves from https://github.com/NVIDIA/Audio2Face-3D-Samples.
+// SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+`;
+
+const body = `${banner}export default ${JSON.stringify(root.toJSON(), null, '\t')};\n`;
+await writeFile(OUTPUT, body);
+console.log(`wrote ${OUTPUT}`);
diff --git a/scripts/verify-nvidia-a2f.mjs b/scripts/verify-nvidia-a2f.mjs
new file mode 100644
index 000000000..b6dd84a93
--- /dev/null
+++ b/scripts/verify-nvidia-a2f.mjs
@@ -0,0 +1,108 @@
+#!/usr/bin/env node
+// Live verification for the free NVIDIA Audio2Face-3D lane (face MOTION).
+//
+// node scripts/verify-nvidia-a2f.mjs --list # enumerate NVCF functions and
+// # print the A2F candidates +
+// # their ids (needs NVIDIA_API_KEY)
+// node scripts/verify-nvidia-a2f.mjs # full round-trip check (needs
+// # NVIDIA_API_KEY; NVIDIA_A2F_FUNCTION_ID
+// # optional — defaults to the
+// # published "James" model id)
+//
+// The full check is a self-contained round-trip across the TTS + A2F lanes: it
+// synthesizes a known sentence through Magpie TTS (api/_lib/tts-nvidia.js) to get
+// real spoken audio, drives that exact audio through Audio2Face-3D
+// (api/_lib/a2f-nvidia.js), and asserts the returned blendshape track is real
+// facial motion — frames arrive, the ARKit names are present, and the JawOpen
+// channel actually opens and closes across the clip (not a frozen face). No
+// fixture files are needed and nothing is written to disk.
+
+import { config as dotenv } from 'dotenv';
+
+dotenv({ path: new URL('../.env.local', import.meta.url) });
+// .env.local can carry prod flags; clear them so nothing fails closed locally.
+delete process.env.NODE_ENV;
+delete process.env.VERCEL_ENV;
+
+const listOnly = process.argv.includes('--list');
+
+if (!process.env.NVIDIA_API_KEY) {
+ console.error('[a2f] NVIDIA_API_KEY missing from environment/.env.local — cannot verify');
+ process.exit(1);
+}
+
+const NVCF_FUNCTIONS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/functions';
+const A2F_NAME_HINT = /(audio2face|a2f|audio-2-face|face)/i;
+
+async function listFunctions() {
+ const res = await fetch(NVCF_FUNCTIONS_URL, {
+ headers: { authorization: `Bearer ${process.env.NVIDIA_API_KEY}`, accept: 'application/json' },
+ });
+ if (!res.ok) {
+ const detail = await res.text().catch(() => '');
+ throw new Error(`NVCF function list returned ${res.status}: ${detail.slice(0, 300)}`);
+ }
+ const data = await res.json();
+ const functions = Array.isArray(data?.functions) ? data.functions : [];
+ const a2f = functions.filter((f) => A2F_NAME_HINT.test(`${f?.name || ''} ${f?.id || ''}`));
+ console.log(`[a2f] ${functions.length} NVCF functions visible; ${a2f.length} look like Audio2Face:\n`);
+ for (const f of a2f) {
+ console.log(` ${f.id} ${f.status || ''} ${f.name || ''}${f.versionId ? ` (v ${f.versionId})` : ''}`);
+ }
+ if (!a2f.length) {
+ console.log(' (none matched — the published "James" id 9327c39f-a361-4e02-bd72-e11b4c9b7b5e is the default)');
+ } else {
+ console.log('\n[a2f] set NVIDIA_A2F_FUNCTION_ID to one of the ids above to pin a model, then re-run without --list.');
+ }
+}
+
+async function roundTrip() {
+ const { synthesizeNvidiaTts } = await import('../api/_lib/tts-nvidia.js');
+ const { animateNvidiaA2F, resolveA2fFunctionId } = await import('../api/_lib/a2f-nvidia.js');
+
+ const sentence = 'Hello! I am a three dot w s avatar, and my face moves with my voice.';
+ console.log(`[a2f] using function-id ${resolveA2fFunctionId()}`);
+ console.log(`[a2f] synthesizing reference audio via Magpie TTS: "${sentence}"`);
+ const t0 = Date.now();
+ const tts = await synthesizeNvidiaTts({ text: sentence, voice: 'nova', format: 'wav' });
+ if (!tts.audio?.length || tts.audio.toString('ascii', 0, 4) !== 'RIFF') {
+ throw new Error('TTS did not return a WAV — cannot build the A2F reference clip');
+ }
+ console.log(`[a2f] ${tts.audio.length} bytes of WAV in ${Date.now() - t0} ms`);
+
+ console.log('[a2f] driving Audio2Face-3D with that exact audio…');
+ const t1 = Date.now();
+ const anim = await animateNvidiaA2F({ wav: tts.audio });
+ console.log(
+ `[a2f] ${anim.frameCount} frames @ ~${anim.fps} fps over ${anim.durationSec.toFixed(2)}s ` +
+ `(${anim.blendShapeNames.length} blendshapes) in ${Date.now() - t1} ms`,
+ );
+
+ if (!anim.frameCount) throw new Error('no animation frames returned');
+
+ // The track must carry the ARKit names and JawOpen must actually move — a
+ // frozen JawOpen would mean the lane returned a flat/neutral track.
+ const jawIdx = anim.blendShapeNames.findIndex((n) => /jawopen/i.test(n));
+ if (jawIdx < 0) throw new Error(`no JawOpen channel among blendshapes: ${anim.blendShapeNames.slice(0, 8).join(', ')}…`);
+ let min = Infinity;
+ let max = -Infinity;
+ for (const f of anim.frames) {
+ const v = f.w[jawIdx] ?? 0;
+ if (v < min) min = v;
+ if (v > max) max = v;
+ }
+ console.log(`[a2f] JawOpen range across clip: ${min.toFixed(3)} … ${max.toFixed(3)}`);
+ if (max < 0.05) {
+ throw new Error(`JawOpen never opened (max ${max.toFixed(3)}) — the face is not moving with the audio`);
+ }
+
+ console.log(`[a2f] PASS — real lip-synced facial animation across the TTS + A2F lanes (JawOpen swing ${(max - min).toFixed(3)}).`);
+}
+
+try {
+ if (listOnly) await listFunctions();
+ else await roundTrip();
+} catch (e) {
+ console.error(`[a2f] FAIL — ${e?.message || e}`);
+ process.exit(1);
+}
diff --git a/scripts/verify-nvidia-cosmos.mjs b/scripts/verify-nvidia-cosmos.mjs
new file mode 100644
index 000000000..904fabba4
--- /dev/null
+++ b/scripts/verify-nvidia-cosmos.mjs
@@ -0,0 +1,142 @@
+#!/usr/bin/env node
+// Live verification for the free NVIDIA Cosmos text→world VIDEO lane.
+//
+// node scripts/verify-nvidia-cosmos.mjs # full round-trip (needs NVIDIA_API_KEY)
+// node scripts/verify-nvidia-cosmos.mjs "a koi pond at dawn, mist on the water"
+// node scripts/verify-nvidia-cosmos.mjs --out world.mp4 # also save the clip to disk
+//
+// Proves the contract the provider (api/_providers/nvidia-cosmos.js) and the
+// /api/cosmos endpoint depend on, against the REAL hosted endpoint: it submits a
+// Text2World prompt to the NVCF genai gateway, follows the 202 + NVCF-REQID async
+// handshake by polling pexec/status, and confirms a decodable MP4 comes back. It
+// prints the exact request/response shapes so a deployment can confirm the live
+// contract (and, if NVIDIA's gateway differs for an account, point
+// NVIDIA_COSMOS_INVOKE_URL at the right path without a code change).
+//
+// Nothing is written to disk unless --out is passed.
+
+import { config as dotenv } from 'dotenv';
+import { writeFileSync } from 'node:fs';
+
+dotenv({ path: new URL('../.env.local', import.meta.url) });
+// .env.local can carry prod flags; clear them so nothing fails closed locally.
+delete process.env.NODE_ENV;
+delete process.env.VERCEL_ENV;
+
+const KEY = process.env.NVIDIA_API_KEY;
+if (!KEY) {
+ console.error('[cosmos] NVIDIA_API_KEY missing from environment/.env.local — cannot verify');
+ process.exit(1);
+}
+
+const INVOKE_URL =
+ process.env.NVIDIA_COSMOS_INVOKE_URL || 'https://ai.api.nvidia.com/v1/genai/nvidia/cosmos-predict1-7b';
+const STATUS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/pexec/status';
+
+const args = process.argv.slice(2);
+const outIdx = args.indexOf('--out');
+const outPath = outIdx !== -1 ? args[outIdx + 1] : null;
+const prompt =
+ args.filter((a, i) => a !== '--out' && i !== outIdx + 1 && !a.startsWith('--')).join(' ') ||
+ 'a serene alpine lake at sunrise, mist drifting over the water, cinematic';
+
+const auth = { authorization: `Bearer ${KEY}` };
+
+function isBase64Blob(s) {
+ return typeof s === 'string' && s.length > 64 && !/^https?:\/\//.test(s);
+}
+
+// Same multi-shape extraction the provider uses — kept in sync so a pass here
+// means the provider will parse the same body.
+async function extract(res) {
+ const ct = (res.headers.get('content-type') || '').toLowerCase();
+ if (ct.includes('json')) {
+ const data = await res.json().catch(() => null);
+ if (data && typeof data === 'object') {
+ console.log(`[cosmos] response json keys: ${JSON.stringify(Object.keys(data))}`);
+ const outs = Array.isArray(data.outputs) ? data.outputs : null;
+ if (outs) {
+ for (const o of outs) {
+ const d = Array.isArray(o?.data) ? o.data[0] : o?.data;
+ if (isBase64Blob(d)) return Buffer.from(d, 'base64');
+ if (typeof d === 'string' && /^https?:\/\//.test(d)) return fetchBytes(d);
+ }
+ }
+ for (const k of ['b64_video', 'video', 'b64_json', 'output']) {
+ if (isBase64Blob(data[k])) return Buffer.from(data[k], 'base64');
+ }
+ const a = data?.artifacts?.[0];
+ if (a) {
+ const inline = a.base64 ?? a.data ?? (isBase64Blob(a) ? a : null);
+ if (isBase64Blob(inline)) return Buffer.from(inline, 'base64');
+ const url = a.url ?? (typeof a === 'string' && a.startsWith('http') ? a : null);
+ if (url) return fetchBytes(url);
+ }
+ }
+ return null;
+ }
+ if (ct.includes('mp4') || ct.startsWith('video/') || ct.includes('octet-stream') || ct.includes('binary')) {
+ return Buffer.from(await res.arrayBuffer());
+ }
+ console.log(`[cosmos] unexpected content-type: ${ct}\n${(await res.text().catch(() => '')).slice(0, 300)}`);
+ return null;
+}
+
+async function fetchBytes(url) {
+ const r = await fetch(url);
+ if (!r.ok) throw new Error(`artifact url ${url.slice(0, 60)} → ${r.status}`);
+ return Buffer.from(await r.arrayBuffer());
+}
+
+const body = {
+ inputs: [
+ { name: 'command', shape: [1], datatype: 'BYTES', data: [`text2world --prompt="${prompt.replace(/"/g, "'")}"`] },
+ ],
+};
+
+console.log(`[cosmos] POST ${INVOKE_URL}`);
+console.log(`[cosmos] prompt: ${prompt}`);
+
+const submit = await fetch(INVOKE_URL, {
+ method: 'POST',
+ headers: { ...auth, accept: 'application/json', 'content-type': 'application/json', 'nvcf-poll-seconds': '30' },
+ body: JSON.stringify(body),
+});
+
+console.log(`[cosmos] submit → ${submit.status} ${submit.statusText}`);
+
+let bytes = null;
+if (submit.status === 202) {
+ const reqId = submit.headers.get('nvcf-reqid');
+ if (!reqId) throw new Error('202 but no NVCF-REQID header');
+ console.log(`[cosmos] async job ${reqId} — polling pexec/status…`);
+ const deadline = Date.now() + 5 * 60_000;
+ while (Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 5_000));
+ const poll = await fetch(`${STATUS_URL}/${reqId}`, { headers: { ...auth, accept: 'application/json' } });
+ process.stdout.write(` poll → ${poll.status}\r`);
+ if (poll.status === 202) continue;
+ if (poll.ok) {
+ bytes = await extract(poll);
+ break;
+ }
+ throw new Error(`poll failed ${poll.status}: ${(await poll.text().catch(() => '')).slice(0, 300)}`);
+ }
+} else if (submit.ok) {
+ bytes = await extract(submit);
+} else {
+ throw new Error(`submit failed ${submit.status}: ${(await submit.text().catch(() => '')).slice(0, 400)}`);
+}
+
+if (!bytes || bytes.length < 1000) {
+ console.error('\n[cosmos] FAIL — no decodable MP4 came back. Check the response shape printed above.');
+ process.exit(2);
+}
+
+// MP4 files begin with an `ftyp` box; the type tag sits at bytes 4–8.
+const looksMp4 = bytes.length > 12 && bytes.toString('ascii', 4, 8) === 'ftyp';
+console.log(`\n[cosmos] PASS — received ${(bytes.length / 1024 / 1024).toFixed(2)} MB, ftyp box: ${looksMp4 ? 'yes' : 'no'}`);
+if (outPath) {
+ writeFileSync(outPath, bytes);
+ console.log(`[cosmos] wrote ${outPath}`);
+}
diff --git a/src/agent-detail-market.js b/src/agent-detail-market.js
index 865b19863..a39edec0b 100644
--- a/src/agent-detail-market.js
+++ b/src/agent-detail-market.js
@@ -121,6 +121,12 @@ export async function enrichAgentDetail(baseAgent) {
const preview = $('ad-preview-card');
if (preview) preview.hidden = false;
+ // Pay-per-minute of talking: a non-owner can open a money stream right under the
+ // chat preview to support the agent by the second while they converse. Owners
+ // don't stream to their own agent (their earnings live on the dedicated Money
+ // Stream card), so the meter is visitor-only here.
+ mountPreviewStream(market, baseAgent);
+
// Reuse the marketplace module's preview-form + creator-modal wiring. navTo
// routes the creator's mini-cards to the canonical /agents/:id page directly
// (skipping the legacy /marketplace redirect hop).
@@ -135,6 +141,37 @@ export async function enrichAgentDetail(baseAgent) {
bindPurchaseDelegation();
}
+let _previewStreamHandle = null;
+
+// Mount a compact pay-per-minute stream meter under the chat preview. Visitor-only:
+// the owner's streaming income is shown on the dedicated Money Stream card instead.
+function mountPreviewStream(market, baseAgent) {
+ const host = $('d-preview-stream');
+ if (!host) return;
+ if (_previewStreamHandle) { try { _previewStreamHandle.destroy(); } catch { /* idempotent */ } _previewStreamHandle = null; }
+ const address =
+ market?.meta?.solana_address || market?.solana_address ||
+ baseAgent?.meta?.solana_address || baseAgent?.solana_address || null;
+ const owner = !!(baseAgent?.isOwner || market?.isOwner || isOwner);
+ if (!address || owner) { host.hidden = true; return; }
+ host.hidden = false;
+ import('./shared/agent-money-stream.js').then(({ mountStreamMeter }) => {
+ _previewStreamHandle = mountStreamMeter(host, {
+ id: baseAgent.id,
+ name: market?.name || baseAgent?.name,
+ solana_address: address,
+ avatar_thumbnail_url: market?.avatar_thumbnail_url || baseAgent?.avatar || '',
+ meta: market?.meta || baseAgent?.meta || {},
+ }, { network: 'mainnet', isOwner: false, compact: true });
+ }).catch(() => { host.hidden = true; });
+}
+
+if (typeof window !== 'undefined') {
+ window.addEventListener('pagehide', () => {
+ try { _previewStreamHandle?.destroy?.(); } catch { /* idempotent */ } _previewStreamHandle = null;
+ }, { once: true });
+}
+
// Re-fetch owned-skills after a purchase / trial and re-render the pricing card.
async function reloadPurchases(agentId) {
try {
diff --git a/src/agent-detail.js b/src/agent-detail.js
index e66c3d0ae..c4ec403cb 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -13,6 +13,7 @@ import { walletChipEl } from './shared/agent-wallet-chip.js';
import { mountMoneyPulse } from './shared/money-pulse.js';
import { mountMirrorPanel } from './shared/agent-mirror-panel.js';
import { mountStrategyPanel } from './shared/agent-strategy-panel.js';
+import { mountPatronagePanel } from './shared/agent-patronage.js';
import { mountValidationBadge } from './shared/validation-badge.js';
import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';
import { hydrateAvatarWallet } from './shared/wallet-aura.js';
@@ -36,7 +37,9 @@ const coinStatusHandles = [];
// polling interval + observers don't leak.
let _pulseHandle = null;
let _mirrorHandle = null;
+let _streamHandle = null;
let _strategyHandle = null;
+let _patronageHandle = null;
// The hero's wallet aura controller — torn down on re-render/unload so its live
// poll + rAF never leak.
@@ -67,6 +70,9 @@ if (typeof window !== 'undefined') {
window.addEventListener('pagehide', () => {
adNetWorthAura?.destroy?.(); adNetWorthAura = null;
adNetWorthPanel?.destroy?.(); adNetWorthPanel = null;
+ // Stop any active money stream so a final settle fires and no charges accrue
+ // past navigation (the engine also guards this internally).
+ try { _streamHandle?.destroy?.(); } catch { /* idempotent */ } _streamHandle = null;
}, { once: true });
}
@@ -757,6 +763,36 @@ function render(agent) {
}
$('ad-holdings-sol').textContent = String(agent.solBalance ?? 0);
+ // Money Stream — pay-per-second income. A visitor gets the live meter (set a
+ // rate, sign a cap, watch the agent earn while they're here); the owner gets the
+ // live "earning now" + lifetime streaming earnings view. Mounted only when the
+ // agent has a custodial wallet to stream to / earn into.
+ {
+ const streamCard = $('ad-stream-card');
+ const streamMount = $('ad-stream-mount');
+ const streamSub = $('ad-stream-sub');
+ const streamTitle = $('ad-stream-title');
+ const wMeta = agent.rawMetadata?.meta || {};
+ if (_streamHandle) { try { _streamHandle.destroy(); } catch { /* idempotent */ } _streamHandle = null; }
+ if (streamCard && streamMount && wMeta.solana_address) {
+ streamCard.hidden = false;
+ if (streamTitle) streamTitle.textContent = agent.isOwner ? 'STREAM EARNINGS' : 'MONEY STREAM';
+ if (streamSub) streamSub.textContent = agent.isOwner ? 'earning by the second' : 'pay by the second';
+ import('./shared/agent-money-stream.js').then(({ mountStreamMeter }) => {
+ _streamHandle = mountStreamMeter(streamMount, {
+ id: agent.id,
+ name: agent.name,
+ solana_address: wMeta.solana_address,
+ avatar_thumbnail_url: agent.avatar || '',
+ isOwner: !!agent.isOwner,
+ meta: wMeta,
+ }, { network: 'mainnet', isOwner: !!agent.isOwner, compact: false });
+ }).catch(() => { if (streamCard) streamCard.hidden = true; });
+ } else if (streamCard) {
+ streamCard.hidden = true;
+ }
+ }
+
// Wallet story — this agent's public Money Pulse (tips, launches, trades,
// payments) scoped to it: the same real-data component as /pulse. Shown only
// when the agent has a custodial wallet; the component renders its own honest
@@ -813,6 +849,23 @@ function render(agent) {
}
}
+ // Patronage — tips/streams build a memory-backed relationship: the perk ladder,
+ // the visitor's level + progress, the public patron wall, season standings, and
+ // the owner's perk editor + patron CRM. The panel reveals its own card
+ // (#ad-patronage-card) only when there's a ladder, a wall, or the owner is here.
+ {
+ const patronagePanel = $('ad-patronage-panel');
+ if (_patronageHandle) { try { _patronageHandle.destroy(); } catch { /* idempotent */ } _patronageHandle = null; }
+ const wMeta = agent.rawMetadata?.meta || {};
+ if (patronagePanel && wMeta.solana_address) {
+ _patronageHandle = mountPatronagePanel({
+ mount: patronagePanel,
+ agent: { id: agent.id, name: agent.name, solana_address: wMeta.solana_address, rawMetadata: agent.rawMetadata },
+ isOwner: !!agent.isOwner,
+ });
+ }
+ }
+
// A re-render (avatar refresh) clears the token body below; tear down any
// coin-status widgets first so their refresh timers don't leak.
destroyCoinStatus();
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index 81206fca1..a9899323f 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -29,6 +29,7 @@ import './tabs/trade.js';
import './tabs/snipe.js';
import './tabs/earn.js';
import './tabs/autopilot.js';
+import './tabs/intents.js';
import './tabs/pay.js';
import './tabs/vanity.js';
import './tabs/withdraw.js';
diff --git a/src/avatar-embed.js b/src/avatar-embed.js
index b87ed7f73..c59dbd3d0 100644
--- a/src/avatar-embed.js
+++ b/src/avatar-embed.js
@@ -64,6 +64,7 @@ import { Viewer } from './viewer.js';
import { IdleAnimation } from './idle-animation.js';
import { LipsyncDriver, tapAudioElement } from './voice/lipsync-driver.js';
import { AvatarMouthTarget } from './voice/avatar-morph-target.js';
+import { A2FPlayer } from './voice/a2f-player.js';
import {
resolveMorphTargets,
setCanonicalMorph,
@@ -197,6 +198,25 @@ async function main() {
return audioCtx;
};
+ // ── Audio2Face-3D (server-side NVIDIA facial animation) ────────────────────
+ // Progressive enhancement over the amplitude lipsync above: when the platform
+ // has the A2F lane configured (NVIDIA_API_KEY → /api/a2f), the spoken audio is
+ // sent to Audio2Face-3D and the avatar's face is driven by the returned ARKit
+ // blendshape track instead of the audio envelope — real lip sync to the actual
+ // voice. Fully self-disabling: any failure (no key, 404, unsupported rig)
+ // leaves the amplitude path untouched, so this never blocks or freezes speech.
+ // Opt out per-embed with ?a2f=off.
+ const a2fEnabled = (params.get('a2f') || 'auto') !== 'off';
+ const a2fPlayer = new A2FPlayer();
+ a2fPlayer.attach(root);
+ let a2fAudio = null; // the <audio> element currently driven by an A2F track
+ // Per-frame: sample the track at the playing audio's time. Registered with the
+ // viewer's hook array (created below by the idle loop if absent).
+ if (!viewer._afterAnimateHooks) viewer._afterAnimateHooks = [];
+ viewer._afterAnimateHooks.push(() => {
+ if (a2fAudio && !a2fAudio.paused && !a2fAudio.ended) a2fPlayer.update(a2fAudio.currentTime);
+ });
+
// ── Idle-life loop ─────────────────────────────────────────────────────
const idle = new IdleAnimation({
getRoot: () => viewer.content,
diff --git a/src/cosmos.js b/src/cosmos.js
new file mode 100644
index 000000000..93d393865
--- /dev/null
+++ b/src/cosmos.js
@@ -0,0 +1,424 @@
+// Cosmos · Living Worlds — drive the /api/cosmos text→world video lane and
+// composite the result behind a live 3D avatar (Google <model-viewer>).
+//
+// Flow: pick an avatar → describe a world → POST /api/cosmos → poll the NVCF job
+// → play the returned MP4 as a full-bleed backdrop behind the transparent avatar
+// viewer. Every state is designed here: empty (living aurora + prompt ideas),
+// loading (real elapsed-driven progress, cancelable), success (video + tools),
+// error / unconfigured (actionable banner, aurora stays so the stage is never
+// blank). No fake timers — progress reflects the real poll lifecycle.
+
+const $ = (id) => document.getElementById(id);
+
+const els = {
+ stage: $('cz-stage'),
+ world: $('cz-world'),
+ avatar: $('cz-avatar'),
+ prompt: $('cz-prompt'),
+ chips: $('cz-chips'),
+ generate: $('cz-generate'),
+ secondary: $('cz-secondary'),
+ cancel: $('cz-cancel'),
+ regen: $('cz-regen'),
+ note: $('cz-note'),
+ avatars: $('cz-avatars'),
+ seed: $('cz-seed'),
+ download: $('cz-download'),
+ copy: $('cz-copy'),
+ toast: $('cz-toast'),
+ progLabel: $('cz-prog-label'),
+ progTime: $('cz-prog-time'),
+ progFill: $('cz-prog-fill'),
+ phases: $('cz-phases'),
+ statusBadge: $('cz-status-badge'),
+ statusText: $('cz-status-text'),
+};
+
+// Curated, visually-distinct world ideas — one tap fills the prompt.
+const IDEAS = [
+ 'a neon Tokyo street in the rain at night, reflections on the pavement',
+ 'a serene alpine lake at sunrise, mist drifting over the water',
+ 'a golden savanna at sunset, tall grass swaying in the wind',
+ 'a bioluminescent forest at midnight, glowing spores in the air',
+ 'a futuristic city skyline with flying traffic, volumetric haze',
+ 'an underwater coral reef, sun rays piercing the blue water',
+ 'a snowy mountain pass in a blizzard, dramatic clouds',
+ 'a desert canyon at dusk, warm light raking the red rock',
+];
+
+// Bundled humanoid avatars that ship in /public/avatars — instant, no fetch.
+const BUNDLED = [
+ { name: 'Aria', url: '/avatars/realistic-female.glb' },
+ { name: 'Kai', url: '/avatars/realistic-male.glb' },
+ { name: 'Michelle', url: '/avatars/michelle.glb' },
+ { name: 'X-Bot', url: '/avatars/xbot.glb' },
+ { name: 'Mona', url: '/avatars/selfie-girl.glb' },
+];
+const DEFAULT_AVATAR = BUNDLED[0].url;
+
+const POLL_INTERVAL_MS = 4000;
+const POLL_TIMEOUT_MS = 5 * 60 * 1000;
+
+let activeAvatarUrl = null;
+let job = null; // { id, startedAt }
+let pollTimer = null;
+let elapsedTimer = null;
+let lastVideoUrl = null;
+let lastPrompt = '';
+
+// ── helpers ────────────────────────────────────────────────────────────────
+function toast(msg) {
+ els.toast.textContent = msg;
+ els.toast.classList.add('show');
+ clearTimeout(toast._t);
+ toast._t = setTimeout(() => els.toast.classList.remove('show'), 2400);
+}
+
+function showNote(kind, html) {
+ els.note.className = `cz-note show ${kind}`;
+ els.note.innerHTML = html;
+}
+function clearNote() {
+ els.note.className = 'cz-note';
+ els.note.innerHTML = '';
+}
+
+function setBadge(on, text) {
+ els.statusBadge.classList.toggle('is-off', !on);
+ els.statusText.textContent = text;
+}
+
+// ── avatar selection ─────────────────────────────────────────────────────────
+function selectAvatar(url, { quiet = false } = {}) {
+ activeAvatarUrl = url;
+ els.avatar.setAttribute('src', url);
+ for (const tile of els.avatars.querySelectorAll('.cz-av')) {
+ tile.classList.toggle('is-active', tile.dataset.url === url);
+ tile.setAttribute('aria-pressed', tile.dataset.url === url ? 'true' : 'false');
+ }
+ if (!quiet) toast('Avatar set');
+}
+
+function avatarTile({ name, url, image }) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'cz-av';
+ btn.dataset.url = url;
+ btn.title = name;
+ btn.setAttribute('aria-label', `Use avatar ${name}`);
+ btn.setAttribute('aria-pressed', 'false');
+ if (image) {
+ const img = document.createElement('img');
+ img.src = image;
+ img.alt = '';
+ img.loading = 'lazy';
+ btn.appendChild(img);
+ } else {
+ const ph = document.createElement('span');
+ ph.className = 'ph';
+ ph.textContent = (name || '?').trim().charAt(0).toUpperCase();
+ btn.appendChild(ph);
+ }
+ btn.addEventListener('click', () => selectAvatar(url));
+ return btn;
+}
+
+function renderAvatars(list) {
+ els.avatars.innerHTML = '';
+ for (const a of list) els.avatars.appendChild(avatarTile(a));
+}
+
+// Pull recent community creations (real GLBs) to enrich the picker. Best-effort:
+// a disabled store or empty feed just leaves the bundled set.
+async function loadCommunityAvatars() {
+ try {
+ const res = await fetch('/api/forge-gallery?scope=community', { headers: { accept: 'application/json' } });
+ if (!res.ok) return;
+ const data = await res.json();
+ const creations = Array.isArray(data?.creations) ? data.creations : [];
+ const extra = creations
+ .filter((c) => typeof c?.glb_url === 'string' && c.glb_url)
+ .slice(0, 5)
+ .map((c, i) => ({
+ name: c.prompt ? c.prompt.split(/[\s,]/)[0] : `Forge ${i + 1}`,
+ url: c.glb_url,
+ image: c.preview_image_url || null,
+ }));
+ if (extra.length) {
+ const seen = new Set(BUNDLED.map((b) => b.url));
+ const merged = [...BUNDLED];
+ for (const e of extra) if (!seen.has(e.url)) merged.push(e);
+ renderAvatars(merged.slice(0, 10));
+ selectAvatar(activeAvatarUrl || DEFAULT_AVATAR, { quiet: true });
+ }
+ } catch {
+ /* keep bundled set */
+ }
+}
+
+// ── progress (driven by real elapsed time + poll phase, not a fake bar) ──────
+function phaseFor(elapsedSec, status) {
+ if (status === 'queued' || elapsedSec < 6) return { label: 'Submitting to NVIDIA Cosmos…', idx: 0, fill: 12 };
+ if (elapsedSec < 70) return { label: 'Rendering world frames…', idx: 1, fill: Math.min(85, 18 + elapsedSec) };
+ return { label: 'Finalizing the clip…', idx: 2, fill: 92 };
+}
+
+function renderProgress(status) {
+ const elapsed = job ? Math.round((Date.now() - job.startedAt) / 1000) : 0;
+ const p = phaseFor(elapsed, status);
+ els.progLabel.textContent = p.label;
+ els.progTime.textContent = `${elapsed}s`;
+ els.progFill.style.width = `${p.fill}%`;
+ const names = ['Submitting', 'Rendering frames', 'Finalizing'];
+ els.phases.innerHTML = names
+ .map((n, i) => {
+ const sep = i === 0 ? '' : '· ';
+ return i === p.idx ? `<b>${n}</b>` : `<span>${sep}${n}</span>`;
+ })
+ .join(' ');
+}
+
+// ── generation lifecycle ─────────────────────────────────────────────────────
+function setBusy(busy) {
+ els.generate.disabled = busy;
+ els.generate.classList.toggle('is-busy', busy);
+ els.stage.classList.toggle('is-loading', busy);
+ els.secondary.style.display = busy ? 'flex' : els.regen.style.display === 'inline-block' ? 'flex' : 'none';
+ els.cancel.style.display = busy ? 'block' : 'none';
+}
+
+function stopTimers() {
+ clearTimeout(pollTimer);
+ clearInterval(elapsedTimer);
+ pollTimer = null;
+ elapsedTimer = null;
+}
+
+async function generate() {
+ const prompt = els.prompt.value.trim();
+ if (prompt.length < 3) {
+ showNote('err', 'Describe a world first — even a few words is enough.');
+ els.prompt.focus();
+ return;
+ }
+ clearNote();
+ lastPrompt = prompt;
+ els.stage.classList.remove('is-done');
+ els.world.classList.remove('is-live');
+ els.regen.style.display = 'none';
+
+ const seedVal = els.seed.value.trim();
+ const payload = { prompt };
+ if (seedVal && Number.isFinite(Number(seedVal))) payload.seed = Math.trunc(Number(seedVal));
+
+ setBusy(true);
+ renderProgress('queued');
+ elapsedTimer = setInterval(() => renderProgress(job?.status || 'running'), 1000);
+
+ let res, data;
+ try {
+ res = await fetch('/api/cosmos', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ data = await res.json();
+ } catch {
+ return failGeneration(
+ res && res.status === 404
+ ? 'The Cosmos lane isn’t deployed on this environment yet.'
+ : 'Couldn’t reach the Cosmos service. Check your connection and try again.',
+ { unconfigured: true },
+ );
+ }
+
+ if (res.status === 503 || data?.error === 'unconfigured') {
+ setBadge(false, 'Cosmos offline');
+ return failGeneration(
+ 'NVIDIA Cosmos isn’t configured on this deployment yet. Your avatar still shines on the living backdrop above — check back soon for generated worlds.',
+ { unconfigured: true },
+ );
+ }
+ if (!res.ok) {
+ const retry = data?.retry_after ? ` Try again in ~${data.retry_after}s.` : '';
+ return failGeneration((data?.message || 'Cosmos couldn’t start this world.') + retry);
+ }
+
+ setBadge(true, 'NVIDIA Cosmos');
+
+ // Rare synchronous completion.
+ if (data.status === 'done' && data.video_url) {
+ return succeed(data.video_url);
+ }
+ if (!data.job_id) {
+ return failGeneration('Cosmos accepted the request but returned no job to track.');
+ }
+
+ job = { id: data.job_id, status: 'queued', startedAt: Date.now() };
+ pollTimer = setTimeout(poll, POLL_INTERVAL_MS);
+}
+
+async function poll() {
+ if (!job) return;
+ if (Date.now() - job.startedAt > POLL_TIMEOUT_MS) {
+ return failGeneration('This world is taking unusually long. Try a simpler prompt or generate again.');
+ }
+ let data;
+ try {
+ const res = await fetch(`/api/cosmos?job=${encodeURIComponent(job.id)}`, { headers: { accept: 'application/json' } });
+ data = await res.json();
+ } catch {
+ // transient network hiccup — keep the job alive
+ pollTimer = setTimeout(poll, POLL_INTERVAL_MS);
+ return;
+ }
+ job.status = data?.status || 'running';
+ renderProgress(job.status);
+
+ if (data?.status === 'done' && data.video_url) return succeed(data.video_url);
+ if (data?.status === 'failed') {
+ return failGeneration(data?.error || 'Cosmos couldn’t finish this world. Try a different prompt.');
+ }
+ pollTimer = setTimeout(poll, POLL_INTERVAL_MS);
+}
+
+function succeed(videoUrl) {
+ stopTimers();
+ lastVideoUrl = videoUrl;
+ const v = els.world;
+ v.src = videoUrl;
+ v.removeAttribute('aria-hidden');
+ const reveal = () => {
+ v.classList.add('is-live');
+ v.play().catch(() => {});
+ };
+ v.oncanplay = reveal;
+ // Safety: reveal even if canplay was missed (cache/seek edge).
+ setTimeout(reveal, 1200);
+
+ job = null;
+ setBusy(false);
+ els.stage.classList.add('is-done');
+ els.regen.style.display = 'inline-block';
+ els.secondary.style.display = 'flex';
+ clearNote();
+ toast('Your world is alive ✦');
+}
+
+function failGeneration(message, { unconfigured = false } = {}) {
+ stopTimers();
+ job = null;
+ setBusy(false);
+ els.regen.style.display = lastVideoUrl ? 'inline-block' : 'none';
+ els.secondary.style.display = lastVideoUrl ? 'flex' : 'none';
+ showNote(
+ unconfigured ? 'info' : 'err',
+ `${message}${unconfigured ? '' : ' <a href="#" id="cz-retry">Retry</a>'}`,
+ );
+ const retry = $('cz-retry');
+ if (retry) {
+ retry.addEventListener('click', (e) => {
+ e.preventDefault();
+ generate();
+ });
+ }
+}
+
+function cancelJob() {
+ stopTimers();
+ job = null;
+ setBusy(false);
+ els.regen.style.display = lastVideoUrl ? 'inline-block' : 'none';
+ showNote('info', 'Generation canceled. Tweak the prompt and try again.');
+}
+
+// ── result actions ───────────────────────────────────────────────────────────
+async function downloadClip() {
+ if (!lastVideoUrl) return;
+ try {
+ const res = await fetch(lastVideoUrl);
+ const blob = await res.blob();
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = `cosmos-world-${Date.now()}.mp4`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);
+ toast('Downloading MP4…');
+ } catch {
+ // Cross-origin blocked the blob — fall back to opening the durable URL.
+ window.open(lastVideoUrl, '_blank', 'noopener');
+ }
+}
+
+async function shareLink() {
+ if (!lastVideoUrl) return;
+ const url = new URL(window.location.href);
+ url.searchParams.set('prompt', lastPrompt);
+ if (activeAvatarUrl) url.searchParams.set('avatar', activeAvatarUrl);
+ const link = url.toString();
+ try {
+ await navigator.clipboard.writeText(link);
+ toast('Shareable link copied');
+ } catch {
+ window.prompt('Copy this link:', link);
+ }
+}
+
+// ── init ─────────────────────────────────────────────────────────────────────
+function init() {
+ // Prompt ideas
+ for (const idea of IDEAS) {
+ const chip = document.createElement('button');
+ chip.type = 'button';
+ chip.className = 'cz-chip';
+ chip.textContent = idea.split(',')[0];
+ chip.title = idea;
+ chip.addEventListener('click', () => {
+ els.prompt.value = idea;
+ els.prompt.focus();
+ });
+ els.chips.appendChild(chip);
+ }
+
+ // Avatars (bundled now; community enriches async)
+ renderAvatars(BUNDLED);
+
+ // Deep-link params: ?prompt= and ?avatar=/?model=
+ const params = new URLSearchParams(window.location.search);
+ const deepAvatar = params.get('avatar') || params.get('model');
+ const deepPrompt = params.get('prompt');
+ if (deepAvatar && /^https?:\/\/|^\//.test(deepAvatar)) {
+ renderAvatars([{ name: 'Yours', url: deepAvatar }, ...BUNDLED]);
+ selectAvatar(deepAvatar, { quiet: true });
+ } else {
+ selectAvatar(DEFAULT_AVATAR, { quiet: true });
+ }
+ if (deepPrompt) els.prompt.value = deepPrompt.slice(0, 300);
+
+ loadCommunityAvatars();
+
+ // Events
+ els.generate.addEventListener('click', generate);
+ els.regen.addEventListener('click', generate);
+ els.cancel.addEventListener('click', cancelJob);
+ els.download.addEventListener('click', downloadClip);
+ els.copy.addEventListener('click', shareLink);
+ els.prompt.addEventListener('keydown', (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') generate();
+ });
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && job) cancelJob();
+ });
+
+ // Model-viewer load resilience: if the chosen GLB fails, fall back to default.
+ els.avatar.addEventListener('error', () => {
+ if (activeAvatarUrl !== DEFAULT_AVATAR) {
+ showNote('info', 'That avatar couldn’t load — falling back to a default. Pick another below.');
+ selectAvatar(DEFAULT_AVATAR, { quiet: true });
+ }
+ });
+}
+
+init();
diff --git a/src/create.js b/src/create.js
index 59c44dcef..6ec78baf0 100644
--- a/src/create.js
+++ b/src/create.js
@@ -174,6 +174,9 @@ async function boot() {
}
window.location.href = '/create/video';
});
+ wireCard('card-cosmos', () => {
+ window.location.href = '/cosmos';
+ });
wireCard('card-upload-glb', (e) => {
// Tooltip anchors live inside the card; let them navigate normally.
if (e && e.target && e.target.closest('a')) return;
diff --git a/src/irl.js b/src/irl.js
index d68070940..48915cdbf 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -54,6 +54,8 @@ import { startOnboarding, ensurePermission, needsMotionGesture, setPermissionSta
import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
import { detectTier, BUDGETS, TIER_ORDER, shiftTier } from './irl/perf-budget.js';
import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';
+import { createWealthAura3D } from './shared/wealth-aura-3d.js';
+import { fetchWealthState } from './shared/agent-wealth-state.js';
import { roomOriginWorld, agentWorldPosition, localToGeo, calibrateRoomOrigin } from './irl/room-anchor.js';
import { anchorPoseToPin, yawDegFromQuat, roomPlacementFromHit, roomRelFromGeo } from './irl/floor-anchor.js';
import { initRoomMode } from './irl/room-mode.js';
@@ -928,6 +930,10 @@ const animMgr = new AnimationManager();
let avatar = null, avatarYaw = 0, avatarLean = 0, currentMotion = 'idle';
let _currentAvatarId = null;
let _currentAgentId = null;
+// Embodied-finance: the carried avatar wears its real wallet — a GPU-cheap glow
+// keyed to its live wealth tier/momentum, refreshed from the real custody flow.
+let wealthAura = null;
+let _stopWealthPoll = null;
// iOS AR Quick Look (capability 'quicklook'): the GLB actually loaded for the
// current avatar, the server-hosted USDZ companion (if the record carries one),
// and a lazily generated USDZ blob URL when it doesn't. The generated URL is
@@ -945,6 +951,9 @@ function _clearAvatar() {
// is idempotent, so a failed (re)load that never re-attaches leaves the manager
// clean (no nulled mixer holding stale clips) rather than half-torn-down.
animMgr.detach();
+ // Tear down the wealth aura + its live poll before the rig is reused.
+ if (_stopWealthPoll) { try { _stopWealthPoll(); } catch {} _stopWealthPoll = null; }
+ if (wealthAura) { try { wealthAura.dispose(); } catch {} wealthAura = null; }
if (avatar) {
avatarRig.remove(avatar);
// Free the previous avatar's geometry/materials/textures. Without this every
@@ -954,6 +963,42 @@ function _clearAvatar() {
}
}
+// Attach the embodied-finance glow to the carried avatar and start its live feed.
+// Only an agent-bound avatar has a real wallet to read; an anonymous GLB stays
+// un-glowed (honest — no wallet, no aura).
+function mountWealthAura(height) {
+ const agentId = _currentAgentId;
+ if (!agentId) return;
+ wealthAura = createWealthAura3D({ height });
+ avatarRig.add(wealthAura.object);
+ _stopWealthPoll = startWealthPoll(agentId);
+}
+
+// Poll the real custody-backed wealth state on a calm interval, push it into the
+// 3D aura, and fire the one-shot pulse only when a genuinely NEW tip lands or a
+// money stream opens (tracked across polls) — never on a bare timer.
+function startWealthPoll(agentId) {
+ let stopped = false, timer = 0, lastTipAt = null, lastStreaming = 0, primed = false;
+ const run = async () => {
+ if (stopped) return;
+ try {
+ const state = await fetchWealthState(agentId, { fresh: true });
+ if (state.ok && wealthAura) {
+ wealthAura.applyState(state);
+ const tipAdvanced = state.lastTipAt && state.lastTipAt !== lastTipAt;
+ const streamOpened = state.streamingNow > lastStreaming;
+ if (primed && (tipAdvanced || streamOpened)) wealthAura.pulse();
+ lastTipAt = state.lastTipAt;
+ lastStreaming = state.streamingNow;
+ primed = true;
+ }
+ } catch { /* transient — keep the last real glow, never invent a trend */ }
+ if (!stopped) timer = setTimeout(run, 30_000);
+ };
+ run();
+ return () => { stopped = true; if (timer) clearTimeout(timer); };
+}
+
async function loadAvatar(idOrUrl, nameOverride) {
// Resolve id/url — accepts: null (default), a UUID (look up), a direct URL
const id = idOrUrl !== undefined ? idOrUrl : avatarIdParam;
@@ -1015,6 +1060,10 @@ async function loadAvatar(idOrUrl, nameOverride) {
CAM_LOOK_OFFSET.set(0, height * 0.6, 0);
applyCameraImmediate();
+ // Embodied finance: glow the carried avatar by its real wallet wealth. Only an
+ // agent-bound avatar has a wallet to read; an anonymous GLB stays un-glowed.
+ mountWealthAura(height);
+
animMgr.attach(avatar);
const manifest = await fetch(ANIMATIONS_MANIFEST_URL, { cache: 'force-cache' }).then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
@@ -6517,6 +6566,9 @@ function tick() {
_radarAccum += dt;
if (_radarAccum >= RADAR_INTERVAL) { _radarAccum = 0; updateRadar(); }
+ // Embodied finance: advance the carried avatar's wealth glow (breath/pulse).
+ if (wealthAura) wealthAura.update(dt);
+
renderer.render(scene, camera);
frameWatchdog(dt);
// Decline to reschedule if a pause landed mid-frame (tab hidden / context lost),
diff --git a/src/shared/agent-money-stream.js b/src/shared/agent-money-stream.js
index ab65dec8c..a6296ca72 100644
--- a/src/shared/agent-money-stream.js
+++ b/src/shared/agent-money-stream.js
@@ -77,6 +77,27 @@ export class StreamError extends Error {
}
}
+/**
+ * Pure accrual math — the amount owed for a given rate over a span of *active*
+ * streaming time, hard-capped at the signed ceiling. This is the money-safety
+ * invariant: no matter how long a stream runs, the projected/owed amount can never
+ * exceed `maxTotal`. Exported so it can be unit-tested in isolation.
+ *
+ * @param {object} p
+ * @param {number} p.ratePerMinute Asset units charged per minute (> 0).
+ * @param {number} p.activeMs Accumulated active streaming time in ms (>= 0).
+ * @param {number} p.maxTotal Signed spend ceiling in asset units (> 0).
+ * @returns {number} owed asset units, never above maxTotal.
+ */
+export function accruedHuman({ ratePerMinute, activeMs, maxTotal }) {
+ const rate = Number(ratePerMinute);
+ const ms = Number(activeMs);
+ const cap = Number(maxTotal);
+ if (!(rate > 0) || !(ms > 0)) return 0;
+ const owed = (rate / 60_000) * ms;
+ return Number.isFinite(cap) && cap > 0 ? Math.min(cap, owed) : owed;
+}
+
function prefersReducedMotion() {
return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
}
@@ -204,8 +225,7 @@ class MoneyStreamEngine {
/** Total owed for the active time so far, hard-capped at the signed ceiling. */
owedHuman() {
- const owed = (this.ratePerMinute / 60_000) * this.activeMs();
- return Math.min(this.maxTotal, owed);
+ return accruedHuman({ ratePerMinute: this.ratePerMinute, activeMs: this.activeMs(), maxTotal: this.maxTotal });
}
/** Live projected amount the meter shows (settled + unsettled accrual). */
@@ -312,13 +332,15 @@ class MoneyStreamEngine {
_handleVisibility() {
if (typeof document === 'undefined') return;
if (document.visibilityState === 'hidden') {
- // Leaving the tab = no longer present. Bank the time, try a best-effort
- // final settle while the page is still alive, and freeze the meter so we
- // never accrue charges for time the streamer isn't watching.
+ // Leaving the tab = no longer present. Freeze the meter immediately so we
+ // never accrue charges for time the streamer isn't watching. We do NOT try
+ // to settle here: a wallet can't pop a signing prompt for a hidden tab, so
+ // the attempt would hang or fail. The accrued-but-unsettled amount simply
+ // settles on the next interval once they return, or on an explicit stop —
+ // and if they never return, it's never charged (fail-safe toward the user).
if (this.state === 'streaming') {
this._pauseAccrual();
this._setState('paused');
- this._maybeSettle('hidden');
}
} else if (document.visibilityState === 'visible' && this.state === 'paused') {
this._resumeAccrual();
@@ -343,8 +365,14 @@ class MoneyStreamEngine {
async _maybeSettle(reason) {
if (this._settleInFlight) return;
if (!this._conn || !this._wallet || !this._from) return;
+ // Never auto-settle while paused (tab hidden) — the wallet can't show a
+ // signing prompt. An explicit stop is the one exception (the tab is visible).
+ if (this.state === 'paused' && reason !== 'stop') return;
const unsettled = this._unsettled();
- const min = reason === 'interval' || reason === 'hidden' ? MIN_SETTLE[this.asset] : DUST[this.asset];
+ // Routine interval settles batch until a meaningful amount has accrued (so
+ // tiny rates don't pay a network fee on dust); a stop/ceiling settle flushes
+ // everything above true dust.
+ const min = reason === 'interval' ? MIN_SETTLE[this.asset] : DUST[this.asset];
if (unsettled < min) {
if (reason === 'ceiling' || reason === 'stop') this._finishIfCeiling(reason);
return;
diff --git a/src/shared/agent-patronage.js b/src/shared/agent-patronage.js
new file mode 100644
index 000000000..d9a030776
--- /dev/null
+++ b/src/shared/agent-patronage.js
@@ -0,0 +1,529 @@
+// Patronage — the Support surface (visitor + patron + owner)
+// ===========================================================
+// Tipping an agent on three.ws builds a real relationship. This panel renders the
+// living ladder of that relationship on an agent's profile: the perk ladder
+// ("Tip 0.5 SOL to unlock X"), the visitor's own level + progress, the public
+// patron wall, season standings, and — for the owner — a perk editor and a patron
+// CRM. Every figure is real, served by GET /api/agents/:id/solana/patronage, which
+// derives levels from the on-chain custody ledger. Gated perk content is released
+// only after the visitor signs a wallet-ownership challenge (op:'unlock').
+//
+// Single source of truth — import and mount it; never copy per page.
+// import { mountPatronagePanel } from './shared/agent-patronage.js';
+// const handle = mountPatronagePanel({ mount, agent, isOwner });
+// handle.destroy();
+
+import { apiFetch } from '../api.js';
+import { openTipModal } from './agent-tip-modal.js';
+import { detectSolanaWallet } from '../erc8004/solana-deploy.js';
+
+const STYLE_ID = 'tws-patronage-styles';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const shortAddr = (a, h = 4, t = 4) => (a && a.length > h + t + 1 ? `${a.slice(0, h)}…${a.slice(-t)}` : a || '');
+const fmtUsd = (n) => {
+ const v = Number(n) || 0;
+ if (v === 0) return '$0';
+ if (v < 0.01) return `$${v.toFixed(4)}`;
+ if (v < 1000) return `$${v.toFixed(2)}`;
+ return `$${Math.round(v).toLocaleString('en-US')}`;
+};
+const relTime = (iso) => {
+ if (!iso) return '';
+ const d = Date.now() - new Date(iso).getTime();
+ if (!Number.isFinite(d)) return '';
+ const s = Math.max(0, Math.round(d / 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 day = Math.round(h / 24);
+ if (day < 30) return `${day}d ago`;
+ return `${Math.round(day / 30)}mo ago`;
+};
+const PERK_GLYPH = { greeting: '✦', lore: '◈', skill: '⚡', launch_access: '🚀', badge: '✸' };
+const PERK_LABEL = { greeting: 'Exclusive greeting', lore: 'Hidden lore', skill: 'Free skill', launch_access: 'Early launch access', badge: 'Patron badge' };
+const explorerAddr = (w, network) => network === 'devnet'
+ ? `https://explorer.solana.com/address/${w}?cluster=devnet`
+ : `https://solscan.io/account/${w}`;
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.pat { --pa: var(--wallet-accent, #c4b5fd); display: flex; flex-direction: column; gap: var(--space-md, 1rem); font-family: var(--font-body, Inter, sans-serif); color: var(--ink, #e8e8e8); }
+.pat-sk { height: 64px; border-radius: var(--radius-lg, 14px); background: linear-gradient(100deg, var(--surface-1, rgba(255,255,255,.03)) 30%, var(--surface-3, rgba(255,255,255,.08)) 50%, var(--surface-1, rgba(255,255,255,.03)) 70%); background-size: 200% 100%; animation: pat-shimmer 1.4s linear infinite; }
+@keyframes pat-shimmer { to { background-position: -200% 0; } }
+.pat-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm, .6rem); flex-wrap: wrap; }
+.pat-head h3 { margin: 0; font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: var(--text-lg, 1.236rem); font-weight: 600; }
+.pat-season { font-size: var(--text-2xs, .6875rem); font-family: var(--font-mono, 'JetBrains Mono', monospace); color: var(--pa); border: 1px solid var(--wallet-stroke, rgba(139,92,246,.3)); background: var(--wallet-accent-soft, rgba(139,92,246,.1)); border-radius: var(--radius-pill, 999px); padding: 2px 10px; }
+.pat-sub { font-size: var(--text-sm, .764rem); color: var(--ink-dim, #888); margin: -4px 0 0; }
+.pat-you { border: 1px solid var(--wallet-stroke, rgba(139,92,246,.3)); background: var(--wallet-accent-soft, rgba(139,92,246,.1)); border-radius: var(--radius-lg, 14px); padding: var(--space-sm, .6rem) var(--space-md, 1rem); display: flex; flex-direction: column; gap: 6px; }
+.pat-you-row { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm, .6rem); }
+.pat-lvl { display: inline-flex; align-items: center; gap: 6px; font-weight: 600; font-size: var(--text-md, .8125rem); }
+.pat-lvl b { font-size: 1.1em; }
+.pat-amt { font-family: var(--font-mono, monospace); font-size: var(--text-sm, .764rem); color: var(--ink-dim, #888); }
+.pat-bar { height: 7px; border-radius: 999px; background: var(--surface-2, rgba(255,255,255,.05)); overflow: hidden; }
+.pat-bar > i { display: block; height: 100%; border-radius: 999px; background: linear-gradient(90deg, var(--pa), var(--wallet-accent-strong, #a78bfa)); transition: width var(--duration-slow, .42s) var(--ease-emphasized, cubic-bezier(.22,1,.36,1)); }
+.pat-next { font-size: var(--text-2xs, .6875rem); color: var(--ink-dim, #888); }
+.pat-ladder { display: flex; flex-direction: column; gap: 8px; }
+.pat-perk { display: flex; gap: var(--space-sm, .6rem); align-items: flex-start; padding: var(--space-sm, .6rem); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); transition: border-color var(--duration-fast, .14s) var(--ease-standard, ease); }
+.pat-perk.unlocked { border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); background: var(--wallet-accent-soft, rgba(139,92,246,.1)); }
+.pat-perk-ico { width: 30px; height: 30px; flex: none; display: grid; place-items: center; border-radius: var(--radius-sm, 6px); background: var(--surface-2, rgba(255,255,255,.05)); font-size: 15px; }
+.pat-perk.unlocked .pat-perk-ico { background: var(--pa); color: #14091f; }
+.pat-perk-main { flex: 1; min-width: 0; }
+.pat-perk-t { font-weight: 600; font-size: var(--text-md, .8125rem); display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.pat-perk-kind { font-size: var(--text-2xs, .6875rem); color: var(--ink-dim, #888); font-weight: 400; }
+.pat-perk-d { font-size: var(--text-sm, .764rem); color: var(--ink-dim, #888); margin: 2px 0 0; line-height: 1.4; }
+.pat-perk-meta { display: flex; align-items: center; gap: 10px; margin-top: 6px; flex-wrap: wrap; }
+.pat-thr { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .6875rem); color: var(--pa); white-space: nowrap; }
+.pat-reveal { margin-top: 8px; padding: var(--space-sm, .6rem); border-radius: var(--radius-sm, 6px); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px dashed var(--wallet-stroke, rgba(139,92,246,.3)); font-size: var(--text-sm, .764rem); line-height: 1.5; white-space: pre-wrap; }
+.pat-wall { display: flex; flex-direction: column; gap: 4px; }
+.pat-wall-h { font-size: var(--text-xs, .618rem); letter-spacing: .08em; text-transform: uppercase; color: var(--ink-dim, #888); margin-bottom: 4px; }
+.pat-row { display: flex; align-items: center; gap: var(--space-sm, .6rem); padding: 7px 8px; border-radius: var(--radius-sm, 6px); transition: background var(--duration-fast, .14s) var(--ease-standard, ease); }
+.pat-row:hover { background: var(--surface-1, rgba(255,255,255,.03)); }
+.pat-rank { width: 18px; text-align: center; font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .6875rem); color: var(--ink-dim, #888); flex: none; }
+.pat-face { width: 26px; height: 26px; flex: none; border-radius: 50%; display: grid; place-items: center; font-size: 13px; background: var(--surface-3, rgba(255,255,255,.08)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); }
+.pat-who { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+.pat-who a, .pat-who span.nm { font-size: var(--text-md, .8125rem); font-weight: 600; color: var(--ink, #e8e8e8); text-decoration: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.pat-who a:hover { color: var(--pa); }
+.pat-when { font-size: var(--text-2xs, .6875rem); color: var(--ink-faint, rgba(255,255,255,.45)); }
+.pat-pill { font-size: var(--text-2xs, .6875rem); padding: 1px 7px; border-radius: 999px; border: 1px solid currentColor; opacity: .9; white-space: nowrap; flex: none; }
+.pat-rowamt { font-family: var(--font-mono, monospace); font-size: var(--text-sm, .764rem); flex: none; min-width: 56px; text-align: right; }
+.pat-empty { text-align: center; padding: var(--space-lg, 1.6rem) var(--space-md, 1rem); color: var(--ink-dim, #888); font-size: var(--text-sm, .764rem); line-height: 1.5; border: 1px dashed var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); }
+.pat-actions { display: flex; gap: var(--space-sm, .6rem); flex-wrap: wrap; }
+.pat-btn { font: inherit; font-size: var(--text-md, .8125rem); font-weight: 600; cursor: pointer; border-radius: var(--radius-md, 10px); padding: 9px 16px; border: 1px solid var(--wallet-stroke-strong, rgba(139,92,246,.5)); background: var(--wallet-accent-fill, rgba(139,92,246,.15)); color: var(--ink-bright, #fff); transition: transform var(--duration-fast, .14s) var(--ease-standard, ease), background var(--duration-fast, .14s) var(--ease-standard, ease); }
+.pat-btn:hover { background: var(--wallet-accent-strong, #a78bfa); color: #14091f; }
+.pat-btn:active { transform: translateY(1px); }
+.pat-btn:focus-visible { outline: 2px solid var(--pa); outline-offset: 2px; }
+.pat-btn.ghost { background: transparent; border-color: var(--stroke-strong, rgba(255,255,255,.14)); color: var(--ink, #e8e8e8); }
+.pat-btn.ghost:hover { border-color: var(--pa); color: var(--pa); background: transparent; }
+.pat-btn.sm { padding: 5px 11px; font-size: var(--text-2xs, .6875rem); }
+.pat-btn[disabled] { opacity: .5; cursor: progress; }
+.pat-more { align-self: center; }
+.pat-err { color: var(--danger, #f87171); font-size: var(--text-sm, .764rem); display: flex; gap: 10px; align-items: center; justify-content: space-between; }
+.pat-edit { display: flex; flex-direction: column; gap: 10px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: var(--space-md, 1rem); background: var(--surface-1, rgba(255,255,255,.03)); }
+.pat-edit-row { display: grid; grid-template-columns: 120px 90px 1fr auto; gap: 8px; align-items: start; }
+.pat-edit input, .pat-edit select, .pat-edit textarea { font: inherit; font-size: var(--text-sm, .764rem); color: var(--ink, #e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-sm, 6px); padding: 7px 9px; width: 100%; }
+.pat-edit textarea { grid-column: 1 / -1; min-height: 54px; resize: vertical; font-family: var(--font-body, Inter); }
+.pat-edit input:focus, .pat-edit select:focus, .pat-edit textarea:focus { outline: none; border-color: var(--pa); }
+.pat-edit-x { background: transparent; border: 1px solid var(--stroke, rgba(255,255,255,.08)); color: var(--ink-dim, #888); border-radius: var(--radius-sm, 6px); cursor: pointer; padding: 7px 10px; }
+.pat-edit-x:hover { color: var(--danger, #f87171); border-color: var(--danger, #f87171); }
+.pat-edit-foot { display: flex; gap: 8px; justify-content: space-between; flex-wrap: wrap; }
+.pat-note { font-size: var(--text-2xs, .6875rem); color: var(--success, #4ade80); }
+@media (max-width: 560px) { .pat-edit-row { grid-template-columns: 1fr 1fr; } }
+@media (prefers-reduced-motion: reduce) { .pat-sk { animation: none; } .pat-bar > i, .pat-btn, .pat-perk, .pat-row { transition: none; } }
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+// Base64 of an ed25519 signature — verifySiwsSignature (server) accepts base64.
+function bytesToB64(bytes) {
+ const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+ let bin = '';
+ for (const b of arr) bin += String.fromCharCode(b);
+ return btoa(bin);
+}
+
+async function getConnectedWallet({ prompt = false } = {}) {
+ const p = detectSolanaWallet();
+ if (!p) return { provider: null, wallet: null };
+ let wallet = p.publicKey?.toString?.() || null;
+ if (!wallet) {
+ try {
+ const r = await p.connect(prompt ? undefined : { onlyIfTrusted: true });
+ wallet = (r?.publicKey || p.publicKey)?.toString?.() || null;
+ } catch { /* not connected / user declined silent connect */ }
+ }
+ return { provider: p, wallet };
+}
+
+function challengeMessage(agentId, wallet, action, extra = '') {
+ return `three.ws patron action\nAgent: ${agentId}\nWallet: ${wallet}\nAction: ${action}${extra}\nIssued At: ${new Date().toISOString()}`;
+}
+
+async function signChallenge(provider, message) {
+ const enc = new TextEncoder().encode(message);
+ const res = await provider.signMessage(enc, 'utf8');
+ return bytesToB64(res?.signature ?? res);
+}
+
+export function mountPatronagePanel({ mount, agent, isOwner = false }) {
+ if (!mount) return { destroy() {} };
+ ensureStyles();
+ const card = mount.closest('#ad-patronage-card') || mount.parentElement;
+ const agentId = agent.id;
+ const tipAddr = agent.solana_address || agent.rawMetadata?.meta?.solana_address || null;
+ let alive = true;
+ let data = null;
+ let connected = { provider: null, wallet: null };
+ let editing = false;
+ let editPerks = [];
+ const revealed = new Map(); // perkId → payload string
+
+ const root = document.createElement('div');
+ root.className = 'pat';
+ root.setAttribute('aria-busy', 'true');
+ mount.replaceChildren(root);
+ root.innerHTML = '<div class="pat-sk"></div><div class="pat-sk" style="height:120px"></div>';
+
+ const show = () => { if (card) card.hidden = false; };
+ const hide = () => { if (card) card.hidden = true; };
+
+ async function load() {
+ const network = data?.network || 'mainnet';
+ const qs = new URLSearchParams({ network });
+ if (connected.wallet) qs.set('viewer', connected.wallet);
+ try {
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/solana/patronage?${qs}`, { allowAnonymous: true });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ data = (await res.json()).data;
+ } catch (e) {
+ if (!alive) return;
+ renderError(e);
+ return;
+ }
+ if (!alive) return;
+ render();
+ }
+
+ function renderError(e) {
+ root.setAttribute('aria-busy', 'false');
+ // Nothing to anchor to yet — keep the card present only if it was already shown.
+ if (!data) { hide(); return; }
+ show();
+ root.innerHTML = `<div class="pat-err"><span>Couldn't load supporters — ${esc(e?.message || 'network error')}.</span><button class="pat-btn ghost sm" data-retry>Retry</button></div>`;
+ root.querySelector('[data-retry]')?.addEventListener('click', load);
+ }
+
+ function render() {
+ root.setAttribute('aria-busy', 'false');
+ const perks = data.perks || [];
+ const wall = data.wall || [];
+ const hasContent = perks.length || wall.length || isOwner;
+ if (!hasContent) { hide(); return; }
+ show();
+
+ if (editing) { renderEditor(); return; }
+
+ const viewer = data.viewer;
+ const totals = data.totals?.lifetime || { patrons: 0, usd: 0 };
+ const season = data.season || {};
+ const seasonUsd = data.totals?.season?.usd || 0;
+
+ const parts = [];
+ parts.push(`<div class="pat-head"><h3>Support ${esc(data.agent_name || 'this agent')}</h3>${season.label ? `<span class="pat-season" title="This season's support">${esc(season.label)} · ${esc(fmtUsd(seasonUsd))}</span>` : ''}</div>`);
+ parts.push(`<p class="pat-sub">${totals.patrons} ${totals.patrons === 1 ? 'patron has' : 'patrons have'} given ${esc(fmtUsd(totals.usd))} — support unlocks real perks and a place on the wall.</p>`);
+
+ parts.push(renderViewer(viewer));
+ if (perks.length) parts.push(renderLadder(perks, viewer));
+ parts.push(renderActions(viewer));
+ if (perks.length === 0 && isOwner) parts.push(renderOwnerEmpty());
+ parts.push(renderWall(wall, viewer, season));
+
+ root.innerHTML = parts.join('');
+ wire();
+ }
+
+ function renderViewer(viewer) {
+ if (!connected.wallet) {
+ return `<div class="pat-you"><div class="pat-you-row"><span class="pat-lvl">Connect your wallet to see your level</span><button class="pat-btn ghost sm" data-connect>Connect</button></div></div>`;
+ }
+ if (!viewer || !viewer.level) {
+ return `<div class="pat-you"><div class="pat-you-row"><span class="pat-lvl">You haven't supported yet</span><span class="pat-amt">${esc(shortAddr(connected.wallet))}</span></div><div class="pat-next">Send any tip to become a Supporter and start unlocking perks.</div></div>`;
+ }
+ const lvl = viewer.level;
+ const prog = viewer.progress || {};
+ const pct = Math.round((prog.pct ?? 1) * 100);
+ const nextLine = prog.next
+ ? `${esc(fmtUsd(prog.remainingUsd))} more to <b style="color:${esc(prog.next.accent || 'var(--pa)')}">${esc(prog.next.label)}</b>`
+ : `You're at the top tier — thank you.`;
+ return `<div class="pat-you">
+ <div class="pat-you-row">
+ <span class="pat-lvl" style="color:${esc(lvl.accent || 'var(--pa)')}">${esc(lvl.glyph || '◆')} <b>${esc(lvl.label)}</b></span>
+ <span class="pat-amt">${esc(fmtUsd(viewer.usd))} · ${viewer.supportCount} ${viewer.supportCount === 1 ? 'gift' : 'gifts'}</span>
+ </div>
+ <div class="pat-bar"><i style="width:${pct}%"></i></div>
+ <div class="pat-next">${nextLine}</div>
+ </div>`;
+ }
+
+ function renderLadder(perks, viewer) {
+ const earned = new Set(viewer?.earnedPerkIds || []);
+ const viewerUsd = viewer?.usd || 0;
+ const rows = perks.map((p) => {
+ const unlocked = earned.has(p.id);
+ const remaining = Math.max(0, p.threshold_usd - viewerUsd);
+ const kind = PERK_LABEL[p.perk_type] || p.perk_type;
+ const glyph = PERK_GLYPH[p.perk_type] || '◆';
+ const revealBtn = unlocked && (p.perk_type === 'greeting' || p.perk_type === 'lore')
+ ? `<button class="pat-btn ghost sm" data-reveal="${esc(p.id)}">${revealed.has(p.id) ? 'Hide' : 'Reveal'}</button>`
+ : '';
+ const status = unlocked
+ ? `<span class="pat-note">✓ Unlocked${p.perk_type === 'skill' ? ' — free in chat' : p.perk_type === 'badge' ? ' — on your wall' : p.perk_type === 'launch_access' ? ' — early access on' : ''}</span>`
+ : `<span class="pat-thr">${connected.wallet ? `${esc(fmtUsd(remaining))} to go` : `${esc(fmtUsd(p.threshold_usd))} to unlock`}</span>`;
+ const revealBox = revealed.has(p.id) ? `<div class="pat-reveal">${esc(revealed.get(p.id))}</div>` : '';
+ return `<div class="pat-perk ${unlocked ? 'unlocked' : ''}">
+ <div class="pat-perk-ico">${glyph}</div>
+ <div class="pat-perk-main">
+ <div class="pat-perk-t">${esc(p.title)} <span class="pat-perk-kind">${esc(kind)}</span></div>
+ ${p.description ? `<p class="pat-perk-d">${esc(p.description)}</p>` : ''}
+ <div class="pat-perk-meta">${status}${revealBtn}</div>
+ ${revealBox}
+ </div>
+ </div>`;
+ }).join('');
+ return `<div class="pat-ladder">${rows}</div>`;
+ }
+
+ function renderActions(viewer) {
+ if (!tipAddr) return '';
+ const label = viewer?.level ? '◎ Support more' : '◎ Support';
+ const hideMe = (viewer && viewer.level && connected.wallet)
+ ? `<button class="pat-btn ghost sm" data-optout="${viewer.hidden ? 'show' : 'hide'}">${viewer.hidden ? 'Show me on the wall' : 'Hide me from the wall'}</button>`
+ : '';
+ const edit = isOwner ? `<button class="pat-btn ghost" data-edit>Edit perks</button>` : '';
+ return `<div class="pat-actions"><button class="pat-btn" data-tip>${label}</button>${edit}${hideMe}</div>`;
+ }
+
+ function renderOwnerEmpty() {
+ return `<div class="pat-empty">You haven't set up any patron perks yet. Add a rung to the ladder — an exclusive greeting, hidden lore, a free skill, early launch access, or a badge — and supporters will have something real to unlock.<br><br><button class="pat-btn" data-edit>Add your first perk</button></div>`;
+ }
+
+ function renderWall(wall, viewer, season) {
+ if (!wall.length) {
+ const msg = isOwner
+ ? 'No supporters yet. Share your profile — when someone tips you, they appear here and the relationship begins.'
+ : 'No patrons yet. Be the first to support and claim the top of the wall.';
+ return `<div class="pat-wall"><div class="pat-wall-h">Patron wall</div><div class="pat-empty">${esc(msg)}</div></div>`;
+ }
+ const top = (data.season_top || []);
+ const topSet = new Set(top.map((t) => t.wallet));
+ const rows = wall.map((p, i) => {
+ const lvl = p.level || {};
+ const name = p.name || shortAddr(p.wallet);
+ const isYou = connected.wallet && p.wallet === connected.wallet;
+ const seasonMark = topSet.has(p.wallet) ? ' <span title="Top patron this season">★</span>' : '';
+ const thankBtn = isOwner ? `<button class="pat-btn ghost sm" data-thank="${esc(p.wallet)}" data-name="${esc(name)}" title="Thank ${esc(name)}">Thank</button>` : '';
+ return `<div class="pat-row">
+ <span class="pat-rank">${i + 1 + (data.wall_offset || 0)}</span>
+ <span class="pat-face" style="color:${esc(lvl.accent || 'var(--pa)')}">${esc(lvl.glyph || '◆')}</span>
+ <span class="pat-who">
+ <a href="${esc(explorerAddr(p.wallet, data.network))}" target="_blank" rel="noopener">${esc(name)}${isYou ? ' <span style="color:var(--pa)">(you)</span>' : ''}${seasonMark}</a>
+ <span class="pat-when">${p.supportCount} ${p.supportCount === 1 ? 'gift' : 'gifts'}${p.lastAt ? ` · ${esc(relTime(p.lastAt))}` : ''}</span>
+ </span>
+ <span class="pat-pill" style="color:${esc(lvl.accent || 'var(--pa)')}">${esc(lvl.label || 'Supporter')}</span>
+ <span class="pat-rowamt">${esc(fmtUsd(p.usd))}</span>
+ ${thankBtn}
+ </div>`;
+ }).join('');
+ const more = data.wall_has_more ? `<button class="pat-btn ghost sm pat-more" data-more>Show more</button>` : '';
+ return `<div class="pat-wall"><div class="pat-wall-h">Patron wall · ${data.totals?.lifetime?.patrons || wall.length} supporters</div>${rows}${more}</div>`;
+ }
+
+ // ── Owner perk editor ──────────────────────────────────────────────────────────
+ function renderEditor() {
+ const typeOpts = (sel) => ['greeting', 'lore', 'skill', 'launch_access', 'badge']
+ .map((t) => `<option value="${t}" ${t === sel ? 'selected' : ''}>${PERK_LABEL[t]}</option>`).join('');
+ const rows = editPerks.map((p, i) => {
+ const needsBody = p.perk_type === 'greeting' || p.perk_type === 'lore';
+ const payloadField = needsBody
+ ? `<textarea data-i="${i}" data-f="body" placeholder="${p.perk_type === 'greeting' ? 'The exclusive greeting your agent uses for this patron…' : 'The hidden lore revealed to this patron…'}">${esc(p.payload?.body || '')}</textarea>`
+ : p.perk_type === 'skill'
+ ? `<input data-i="${i}" data-f="skill" placeholder="skill name (e.g. deep_research)" value="${esc(p.payload?.skill || '')}" style="grid-column:1/-1">`
+ : p.perk_type === 'badge'
+ ? `<input data-i="${i}" data-f="label" placeholder="badge label" value="${esc(p.payload?.label || '')}" style="grid-column:1/-1">`
+ : '';
+ return `<div class="pat-edit-row">
+ <select data-i="${i}" data-f="perk_type" aria-label="Perk type">${typeOpts(p.perk_type)}</select>
+ <input data-i="${i}" data-f="threshold_usd" type="number" min="0" step="1" placeholder="USD" value="${esc(p.threshold_usd ?? '')}" aria-label="Threshold USD">
+ <input data-i="${i}" data-f="title" placeholder="Perk title" value="${esc(p.title || '')}" aria-label="Title">
+ <button class="pat-edit-x" data-del="${i}" title="Remove" aria-label="Remove perk">✕</button>
+ <input data-i="${i}" data-f="description" placeholder="Short description (optional)" value="${esc(p.description || '')}" style="grid-column:1/-1" aria-label="Description">
+ ${payloadField}
+ </div>`;
+ }).join('');
+ root.innerHTML = `<div class="pat-head"><h3>Patron perks</h3></div>
+ <p class="pat-sub">Define what supporters unlock at each USD threshold. Access is enforced server-side against real on-chain support — no one can unlock a perk they haven't earned.</p>
+ <div class="pat-edit">${rows || '<div class="pat-empty">No perks yet — add one.</div>'}
+ <div class="pat-edit-foot">
+ <button class="pat-btn ghost sm" data-add>+ Add perk</button>
+ <span style="display:flex;gap:8px"><button class="pat-btn ghost" data-cancel>Cancel</button><button class="pat-btn" data-save>Save ladder</button></span>
+ </div>
+ <div class="pat-err" data-edit-err hidden></div>
+ </div>`;
+ wireEditor();
+ }
+
+ function wireEditor() {
+ root.querySelectorAll('.pat-edit [data-i]').forEach((el) => {
+ el.addEventListener('input', () => {
+ const i = Number(el.dataset.i);
+ const f = el.dataset.f;
+ if (!editPerks[i]) return;
+ if (f === 'perk_type') {
+ editPerks[i].perk_type = el.value;
+ renderEditor(); // payload field shape depends on type
+ return;
+ }
+ if (f === 'threshold_usd') editPerks[i].threshold_usd = el.value === '' ? '' : Number(el.value);
+ else if (f === 'title' || f === 'description') editPerks[i][f] = el.value;
+ else { editPerks[i].payload = { ...(editPerks[i].payload || {}), [f]: el.value }; }
+ });
+ });
+ root.querySelector('[data-add]')?.addEventListener('click', () => {
+ editPerks.push({ perk_type: 'greeting', threshold_usd: 10, title: '', description: '', payload: {}, is_active: true });
+ renderEditor();
+ });
+ root.querySelectorAll('[data-del]').forEach((b) => b.addEventListener('click', () => {
+ editPerks.splice(Number(b.dataset.del), 1);
+ renderEditor();
+ }));
+ root.querySelector('[data-cancel]')?.addEventListener('click', () => { editing = false; render(); });
+ root.querySelector('[data-save]')?.addEventListener('click', savePerks);
+ }
+
+ async function savePerks() {
+ const errBox = root.querySelector('[data-edit-err]');
+ const saveBtn = root.querySelector('[data-save]');
+ const fail = (m) => { if (errBox) { errBox.hidden = false; errBox.textContent = m; } };
+ for (const p of editPerks) {
+ if (!String(p.title || '').trim()) return fail('Every perk needs a title.');
+ if (!(Number(p.threshold_usd) >= 0)) return fail('Every threshold must be $0 or more.');
+ if ((p.perk_type === 'greeting' || p.perk_type === 'lore') && !String(p.payload?.body || '').trim()) return fail(`"${p.title}" needs its ${p.perk_type} text.`);
+ if (p.perk_type === 'skill' && !String(p.payload?.skill || '').trim()) return fail(`"${p.title}" needs a skill name.`);
+ }
+ if (saveBtn) saveBtn.disabled = true;
+ try {
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/solana/patronage`, {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ perks: editPerks }),
+ });
+ if (!res.ok) {
+ const j = await res.json().catch(() => ({}));
+ throw new Error(j.error?.message || j.message || `HTTP ${res.status}`);
+ }
+ editing = false;
+ await load();
+ } catch (e) {
+ if (saveBtn) saveBtn.disabled = false;
+ fail(`Could not save: ${e.message}`);
+ }
+ }
+
+ // ── Wiring (view mode) ──────────────────────────────────────────────────────────
+ function wire() {
+ root.querySelector('[data-connect]')?.addEventListener('click', async (ev) => {
+ ev.currentTarget.disabled = true;
+ connected = await getConnectedWallet({ prompt: true });
+ await load();
+ });
+ root.querySelector('[data-tip]')?.addEventListener('click', () => {
+ openTipModal({ id: agentId, name: data.agent_name, solana_address: tipAddr }, { network: data.network });
+ });
+ root.querySelector('[data-edit]')?.addEventListener('click', () => {
+ editPerks = (data.perks || []).map((p) => ({
+ perk_type: p.perk_type, threshold_usd: p.threshold_usd, title: p.title,
+ description: p.description, payload: p.payload || {}, is_active: p.is_active !== false,
+ }));
+ if (!editPerks.length) editPerks.push({ perk_type: 'greeting', threshold_usd: 10, title: '', description: '', payload: {}, is_active: true });
+ editing = true;
+ render();
+ });
+ root.querySelector('[data-more]')?.addEventListener('click', async (ev) => {
+ ev.currentTarget.disabled = true;
+ // Page forward: refetch at the next offset and append client-side.
+ const next = (data.wall_offset || 0) + (data.wall?.length || 0);
+ try {
+ const qs = new URLSearchParams({ network: data.network, offset: String(next) });
+ if (connected.wallet) qs.set('viewer', connected.wallet);
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/solana/patronage?${qs}`, { allowAnonymous: true });
+ const more = (await res.json()).data;
+ data.wall = [...data.wall, ...(more.wall || [])];
+ data.wall_has_more = more.wall_has_more;
+ data.wall_offset = 0; // ranks already absolute via accumulated array
+ render();
+ } catch { ev.currentTarget.disabled = false; }
+ });
+ root.querySelectorAll('[data-reveal]').forEach((b) => b.addEventListener('click', () => revealPerk(b.dataset.reveal, b)));
+ root.querySelector('[data-optout]')?.addEventListener('click', (ev) => toggleOptOut(ev.currentTarget.dataset.optout === 'hide', ev.currentTarget));
+ root.querySelectorAll('[data-thank]').forEach((b) => b.addEventListener('click', () => thankPatron(b.dataset.thank, b.dataset.name)));
+ }
+
+ async function revealPerk(perkId, btn) {
+ if (revealed.has(perkId)) { revealed.delete(perkId); render(); return; }
+ if (!connected.wallet) { connected = await getConnectedWallet({ prompt: true }); if (!connected.wallet) return; }
+ if (!connected.provider) return;
+ btn.disabled = true;
+ try {
+ const msg = challengeMessage(agentId, connected.wallet, 'unlock');
+ const signature = await signChallenge(connected.provider, msg);
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/solana/patronage`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ op: 'unlock', wallet: connected.wallet, message: msg, signature, network: data.network }),
+ });
+ const j = await res.json();
+ if (!res.ok) throw new Error(j.error?.message || `HTTP ${res.status}`);
+ const perk = (j.data.unlocked || []).find((p) => p.id === perkId);
+ if (perk?.payload?.body) revealed.set(perkId, perk.payload.body);
+ else revealed.set(perkId, '(This perk has no readable content.)');
+ render();
+ } catch (e) {
+ btn.disabled = false;
+ btn.textContent = e?.message?.includes('User rejected') ? 'Reveal' : 'Retry';
+ }
+ }
+
+ async function toggleOptOut(hide, btn) {
+ if (!connected.wallet) { connected = await getConnectedWallet({ prompt: true }); if (!connected.wallet) return; }
+ if (!connected.provider) return;
+ btn.disabled = true;
+ try {
+ const msg = challengeMessage(agentId, connected.wallet, 'optout', `\nHidden: ${hide}`);
+ const signature = await signChallenge(connected.provider, msg);
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/solana/patronage`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ op: 'optout', wallet: connected.wallet, message: msg, signature, hidden: hide }),
+ });
+ if (!res.ok) { const j = await res.json().catch(() => ({})); throw new Error(j.error?.message || `HTTP ${res.status}`); }
+ await load();
+ } catch { btn.disabled = false; }
+ }
+
+ // Owner reciprocity: a real, shareable shout-out thanking a patron by name.
+ function thankPatron(wallet, name) {
+ const text = `Huge thanks to ${name || shortAddr(wallet)} for being a patron of ${data.agent_name} on @three_ws — support that builds a real relationship. ${location.origin}/agent/${agentId}`;
+ const url = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}`;
+ window.open(url, '_blank', 'noopener');
+ }
+
+ // Live refresh: when anyone tips/streams this agent from this tab, refetch so the
+ // level + wall update right after on-chain confirm + server record.
+ const onSupport = (ev) => {
+ if (!alive) return;
+ const d = ev.detail || {};
+ if (d.agentId && d.agentId !== agentId) return;
+ // Give the server a beat to record + verify, then refresh derived state.
+ setTimeout(() => { if (alive) load(); }, 1200);
+ };
+ window.addEventListener('three:patron-support', onSupport);
+
+ // Boot: detect an already-trusted wallet silently, then load.
+ (async () => {
+ connected = await getConnectedWallet({ prompt: false });
+ if (alive) await load();
+ })();
+
+ return {
+ destroy() {
+ alive = false;
+ window.removeEventListener('three:patron-support', onSupport);
+ try { mount.replaceChildren(); } catch { /* idempotent */ }
+ },
+ };
+}
diff --git a/src/shared/agent-tip-modal.js b/src/shared/agent-tip-modal.js
index f60310900..3f0bb68a1 100644
--- a/src/shared/agent-tip-modal.js
+++ b/src/shared/agent-tip-modal.js
@@ -25,16 +25,22 @@ const STYLE_ID = 'tws-tip-modal-styles';
// Fire-and-forget: the tip is already final on-chain, so this never blocks the
// success UI and a failure (e.g. no agent id, tx still finalizing) is silent.
function recordTip(agentId, signature, token, network) {
- if (!agentId || !signature) return;
+ if (!agentId || !signature) return Promise.resolve();
try {
- fetch(`/api/agents/${encodeURIComponent(agentId)}/solana/tip`, {
+ return fetch(`/api/agents/${encodeURIComponent(agentId)}/solana/tip`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ signature, asset: token || 'SOL', network: network || 'mainnet' }),
keepalive: true,
}).catch(() => {});
- } catch { /* never throws into the success path */ }
+ } catch { /* never throws into the success path */ return Promise.resolve(); }
+}
+
+// Broadcast a confirmed, server-recorded gift so live surfaces (the patronage
+// Support panel, money pulse) can refresh their derived state without a reload.
+function announceSupport(detail) {
+ try { window.dispatchEvent(new CustomEvent('three:patron-support', { detail })); } catch { /* best-effort */ }
}
function esc(s) {
@@ -280,7 +286,10 @@ export function openTipModal(agent, opts = {}) {
// agent's wallet story. The server INDEPENDENTLY re-verifies the signature
// on-chain before writing a row, so this is only a hint — a failure here
// never affects the (already-final) on-chain tip.
- recordTip(status.agentId || agent?.id, res.signature, state.token, network);
+ const agentId = status.agentId || agent?.id;
+ recordTip(agentId, res.signature, state.token, network).then(() => {
+ announceSupport({ agentId, signature: res.signature, asset: state.token, from: res.from, network });
+ });
try { opts.onSent?.(res); } catch { /* listener best-effort */ }
} catch (e) {
state.sending = false;
diff --git a/src/shared/wealth-aura-3d.js b/src/shared/wealth-aura-3d.js
new file mode 100644
index 000000000..7fa16d79d
--- /dev/null
+++ b/src/shared/wealth-aura-3d.js
@@ -0,0 +1,145 @@
+/**
+ * Embodied Finance — the 3D (WebGL) aura for full Three.js scenes (IRL/AR, the
+ * world). The 2D/CSS aura in wallet-aura.js wraps DOM avatars (<model-viewer>,
+ * cards); this is its GPU-cheap sibling for scenes where the avatar is a real
+ * mesh in a Three.js graph — so a well-funded agent you walk past in AR visibly
+ * glows, reading at the SAME wealth tier it shows everywhere else.
+ *
+ * Craft + budget:
+ * - One additive, billboarded Sprite per avatar (a soft radial-gradient glow),
+ * sharing a single canvas texture across all instances — no per-avatar
+ * allocation, no per-frame garbage. A Sprite faces the camera for free, so
+ * there is no manual billboard math in the host's render loop.
+ * - The look is a pure function of the REAL wealth state (tier → base opacity +
+ * scale + accent; momentum → intensity tilt; streaming → a slow breath; a
+ * fresh tip → a one-shot pulse). A dormant wallet renders nothing (opacity 0),
+ * never a fake shimmer.
+ * - prefers-reduced-motion: the steady glow stays, animation (breath/pulse) is
+ * suppressed.
+ *
+ * The colour vocabulary (tier → accent) is shared with the 2D aura via
+ * computeWalletVisual, so the galaxy star, the profile hero, the card, and the AR
+ * body never disagree.
+ */
+
+import { Sprite, SpriteMaterial, CanvasTexture, AdditiveBlending, Color, SRGBColorSpace } from 'three';
+import { computeWalletVisual } from './wallet-networth.js';
+import { computeWealthDynamics } from './agent-wealth-state.js';
+
+const REDUCED_MOTION =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+let _sharedTexture = null;
+
+/** A soft white radial-gradient glow, built once and shared by every aura. */
+function glowTexture() {
+ if (_sharedTexture) return _sharedTexture;
+ const size = 128;
+ const c = typeof document !== 'undefined' ? document.createElement('canvas') : null;
+ if (!c) return null;
+ c.width = c.height = size;
+ const ctx = c.getContext('2d');
+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
+ g.addColorStop(0, 'rgba(255,255,255,1)');
+ g.addColorStop(0.35, 'rgba(255,255,255,0.55)');
+ g.addColorStop(0.7, 'rgba(255,255,255,0.12)');
+ g.addColorStop(1, 'rgba(255,255,255,0)');
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, size, size);
+ _sharedTexture = new CanvasTexture(c);
+ _sharedTexture.colorSpace = SRGBColorSpace;
+ return _sharedTexture;
+}
+
+/**
+ * Create a 3D wealth aura. Add `object` to the avatar's group; call `update(dt)`
+ * each frame, `applyState(wealthState)` whenever fresh real data arrives, and
+ * `dispose()` on teardown.
+ *
+ * @param {object} [opts]
+ * @param {number} [opts.height=1.7] avatar height in world units (scales the glow)
+ * @returns {{ object: import('three').Sprite, applyState, pulse, setHeight, update, dispose }}
+ */
+export function createWealthAura3D(opts = {}) {
+ const material = new SpriteMaterial({
+ map: glowTexture(),
+ color: new Color('#c4b5fd'),
+ blending: AdditiveBlending,
+ depthWrite: false,
+ depthTest: true,
+ transparent: true,
+ opacity: 0,
+ });
+ const sprite = new Sprite(material);
+ sprite.name = 'wealth-aura-3d';
+ sprite.renderOrder = -1; // behind the avatar mesh
+
+ let height = Math.max(0.3, Number(opts.height) || 1.7);
+ let baseOpacity = 0;
+ let baseScale = 1;
+ let level = 0;
+ let streaming = false;
+ let clockT = 0;
+ let pulseT = 0; // 0..1, decays over ~1s
+ let disposed = false;
+
+ function position() {
+ // Sit the glow at the avatar's centre of mass and a touch wider than it.
+ sprite.position.set(0, height * 0.5, 0);
+ }
+ position();
+
+ function applyState(state) {
+ if (disposed || !state) return;
+ const usd = Number(state.balanceUsd) || 0;
+ const v = computeWalletVisual({ usdTotal: usd, mix: { sol: 1 }, hasThree: false });
+ const dyn = computeWealthDynamics(state);
+ level = v.level;
+ // Dormant → invisible (honest). Otherwise a tasteful, capped glow that grows
+ // with tier, nudged by real momentum.
+ baseOpacity = v.dormant ? 0 : Math.min(0.6, 0.14 + level * 0.075 + dyn.intensityDelta * 0.2);
+ baseScale = 1 + level * 0.16;
+ streaming = dyn.streaming;
+ // Accent in the wallet-violet family, warmed/cooled slightly by momentum.
+ material.color.set(v.accent);
+ if (dyn.recentTip) pulse();
+ }
+
+ function pulse() { if (!REDUCED_MOTION) pulseT = 1; }
+
+ function setHeight(h) {
+ height = Math.max(0.3, Number(h) || height);
+ position();
+ }
+
+ function update(dt) {
+ if (disposed) return;
+ clockT += dt || 0;
+ let op = baseOpacity;
+ let sc = baseScale;
+ // A live money stream breathes the glow gently (calm, ~0.3 Hz).
+ if (streaming && !REDUCED_MOTION && baseOpacity > 0) {
+ const b = 0.5 + 0.5 * Math.sin(clockT * 1.9);
+ op *= 0.82 + b * 0.36;
+ }
+ // One-shot tip pulse: a quick bloom that decays back to baseline.
+ if (pulseT > 0) {
+ pulseT = Math.max(0, pulseT - (dt || 0) / 1.0);
+ const e = pulseT;
+ op = Math.min(1, op + e * 0.5);
+ sc += e * 0.7;
+ }
+ material.opacity = op;
+ const s = sc * height * 1.6;
+ sprite.scale.set(s, s, 1);
+ }
+
+ function dispose() {
+ disposed = true;
+ sprite.removeFromParent?.();
+ material.dispose();
+ // The texture is shared — never disposed here.
+ }
+
+ return { object: sprite, applyState, pulse, setHeight, update, dispose };
+}
diff --git a/src/voice/a2f-player.js b/src/voice/a2f-player.js
new file mode 100644
index 000000000..ff99e8617
--- /dev/null
+++ b/src/voice/a2f-player.js
@@ -0,0 +1,251 @@
+/**
+ * Audio2Face-3D playback — drive a loaded GLB from an A2F blendshape track.
+ *
+ * NVIDIA Audio2Face-3D (api/_lib/a2f-nvidia.js) returns a per-frame ARKit-52
+ * blendshape track aligned to the spoken audio's timeline:
+ *
+ * { fps, blendShapeNames: ["EyeBlinkLeft", …, "JawOpen", …],
+ * frames: [{ t: <seconds>, w: [<weight per name>] }, …] }
+ *
+ * This class maps that track onto whatever morph-target convention the avatar's
+ * GLB actually ships — the SAME problem glb-canonicalize.js solves for bones,
+ * solved here for face morphs by reusing the cross-format vocabulary in
+ * arkit-blendshapes.js:
+ *
+ * • ARKit / RPM / Avaturn / MetaHuman (jawOpen, JawOpen, jaw_open, …)
+ * → driven DIRECTLY: each A2F shape writes to its canonical morph.
+ * • VRM / VRoid (A, I, U, E, O / Aa, Ih, Ou, Ee, Oh, Blink, emotions)
+ * and Oculus / Meta visemes (viseme_aa, viseme_O, …)
+ * → driven by DERIVING each expression's activation from the A2F ARKit
+ * frame (the inverse of arkit-blendshapes' VRM/Oculus→ARKit maps), so a
+ * rig that exposes only monolithic vowel shapes still lip-syncs.
+ *
+ * The avatar plays the ORIGINAL audio; `update(audioTimeSec)` samples the track
+ * by the audio element's currentTime (interpolating between the 30 fps A2F
+ * frames for smooth motion at display refresh), so the lips track the real
+ * voice. No rig allowlist: an unknown convention degrades to "no coverage", and
+ * the caller falls back to amplitude lipsync — never a frozen face.
+ */
+
+import {
+ canonicalARKitName,
+ VRM_TO_ARKIT,
+ OCULUS_TO_ARKIT,
+ ARKIT_GROUPS,
+} from './arkit-blendshapes.js';
+
+// Canonical ARKit shapes that move the mouth/jaw — used to decide whether a mesh
+// already has DIRECT mouth coverage (so we don't also drive its vowel morphs and
+// double-stack the lips).
+const MOUTH_SHAPES = new Set([...ARKIT_GROUPS.jaw, ...ARKIT_GROUPS.mouth]);
+
+// Expression morph names we know how to derive from an ARKit frame. Built from
+// the VRM + Oculus maps so the set stays in lockstep with arkit-blendshapes.js.
+const EXPRESSION_COMPONENTS = buildExpressionComponents();
+
+function buildExpressionComponents() {
+ const out = new Map(); // lowercased morph name → { arkitName: weight }
+ for (const [name, components] of Object.entries(VRM_TO_ARKIT)) {
+ out.set(name.toLowerCase(), components);
+ }
+ for (const [name, components] of Object.entries(OCULUS_TO_ARKIT)) {
+ out.set(name.toLowerCase(), components);
+ }
+ return out;
+}
+
+export class A2FPlayer {
+ constructor() {
+ /** @type {Array<{mesh:any, index:number, canonical:string}>} */
+ this._direct = [];
+ /** @type {Array<{mesh:any, index:number, components:Record<string,number>, denom:number}>} */
+ this._expression = [];
+ this._track = null; // { fps, names, frames, canonForName: (string|null)[] }
+ this._cursor = 0;
+ this._lastTime = -1;
+ this._attached = false;
+ }
+
+ /**
+ * Bind to a freshly loaded GLB scene. Re-callable after a model hot-swap.
+ * @param {import('three').Object3D} root
+ */
+ attach(root) {
+ this._direct = [];
+ this._expression = [];
+ this._attached = false;
+ if (!root || typeof root.traverse !== 'function') return;
+
+ const meshes = [];
+ root.traverse((node) => {
+ if (node.isMesh && node.morphTargetDictionary && node.morphTargetInfluences) {
+ meshes.push(node);
+ }
+ });
+
+ for (const mesh of meshes) {
+ const dict = mesh.morphTargetDictionary;
+ const directHere = [];
+ for (const [morphName, index] of Object.entries(dict)) {
+ const canonical = canonicalARKitName(morphName);
+ if (canonical) directHere.push({ mesh, index, canonical });
+ }
+ const hasDirectMouth = directHere.some((b) => MOUTH_SHAPES.has(b.canonical));
+ this._direct.push(...directHere);
+
+ // Only derive vowel/viseme expressions for a mesh that lacks direct
+ // mouth morphs — otherwise we'd fight the ARKit mouth shapes.
+ if (!hasDirectMouth) {
+ for (const [morphName, index] of Object.entries(dict)) {
+ const components = EXPRESSION_COMPONENTS.get(String(morphName).toLowerCase());
+ if (!components) continue;
+ const denom = Object.values(components).reduce((s, w) => s + w, 0);
+ if (denom > 0) this._expression.push({ mesh, index, components, denom });
+ }
+ }
+ }
+
+ this._attached = true;
+ }
+
+ /** True when at least one morph is wired and a track is loaded. */
+ hasCoverage() {
+ return this._attached && (this._direct.length > 0 || this._expression.length > 0);
+ }
+
+ /** Diagnostics: which morphs are wired and by which path. */
+ describe() {
+ return {
+ direct: this._direct.map((b) => `${b.mesh.name}:${b.canonical}`),
+ expression: this._expression.map((b) => `${b.mesh.name}:#${b.index}`),
+ frames: this._track?.frames.length ?? 0,
+ fps: this._track?.fps ?? 0,
+ };
+ }
+
+ /**
+ * Load an A2F animation track. Precomputes the canonical ARKit name for each
+ * blendshape column so per-frame sampling does no string work.
+ * @param {{ fps:number, blendShapeNames:string[], frames:Array<{t:number,w:number[]}> }} track
+ */
+ setTrack(track) {
+ if (!track || !Array.isArray(track.frames) || !track.frames.length) {
+ this._track = null;
+ return;
+ }
+ const names = Array.isArray(track.blendShapeNames) ? track.blendShapeNames : [];
+ this._track = {
+ fps: track.fps || 30,
+ names,
+ frames: track.frames,
+ canonForName: names.map((n) => canonicalARKitName(n)),
+ };
+ this._cursor = 0;
+ this._lastTime = -1;
+ }
+
+ get duration() {
+ const f = this._track?.frames;
+ return f && f.length ? f[f.length - 1].t : 0;
+ }
+
+ /**
+ * Sample the track at `timeSec` (the playing audio's currentTime) and write
+ * the resulting weights onto the bound morphs. Safe before attach/setTrack
+ * (no-op). Interpolates between the two bracketing A2F frames.
+ *
+ * @param {number} timeSec
+ */
+ update(timeSec) {
+ if (!this._attached || !this._track) return;
+ const frames = this._track.frames;
+ const t = Number(timeSec) || 0;
+
+ // Forward playback advances the cursor; a backward seek (replay) rewinds it.
+ if (t < this._lastTime) this._cursor = 0;
+ this._lastTime = t;
+ let i = this._cursor;
+ while (i < frames.length - 1 && frames[i + 1].t <= t) i++;
+ this._cursor = i;
+
+ const cur = frames[i];
+ const nxt = frames[i + 1];
+ let blend = 0;
+ if (nxt && nxt.t > cur.t) blend = Math.min(1, Math.max(0, (t - cur.t) / (nxt.t - cur.t)));
+
+ // Build the canonical ARKit frame (name → interpolated weight) once, then
+ // fan out to direct + derived bindings.
+ const arkit = this._arkit || (this._arkit = Object.create(null));
+ for (const k in arkit) arkit[k] = 0;
+ const { canonForName } = this._track;
+ const cw = cur.w;
+ const nw = nxt ? nxt.w : null;
+ for (let c = 0; c < canonForName.length; c++) {
+ const canon = canonForName[c];
+ if (!canon) continue;
+ const a = cw[c] || 0;
+ const b = nw ? (nw[c] || 0) : a;
+ arkit[canon] = a + (b - a) * blend;
+ }
+
+ for (const bind of this._direct) {
+ bind.mesh.morphTargetInfluences[bind.index] = arkit[bind.canonical] || 0;
+ }
+ for (const bind of this._expression) {
+ let sum = 0;
+ for (const name in bind.components) sum += (arkit[name] || 0) * bind.components[name];
+ bind.mesh.morphTargetInfluences[bind.index] = clamp01(sum / bind.denom);
+ }
+ }
+
+ /**
+ * Last sampled weight for a canonical ARKit shape (e.g. 'jawOpen') — for live
+ * activity meters / diagnostics. Returns 0 before the first update().
+ * @param {string} canonical
+ */
+ currentWeight(canonical) {
+ return (this._arkit && this._arkit[canonical]) || 0;
+ }
+
+ /** Settle every bound morph to rest. Call when playback ends/stops. */
+ reset() {
+ for (const bind of this._direct) {
+ if (bind.mesh.morphTargetInfluences) bind.mesh.morphTargetInfluences[bind.index] = 0;
+ }
+ for (const bind of this._expression) {
+ if (bind.mesh.morphTargetInfluences) bind.mesh.morphTargetInfluences[bind.index] = 0;
+ }
+ this._cursor = 0;
+ this._lastTime = -1;
+ }
+
+ dispose() {
+ this.reset();
+ this._direct = [];
+ this._expression = [];
+ this._track = null;
+ this._attached = false;
+ }
+}
+
+function clamp01(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return 0;
+ if (v < 0) return 0;
+ if (v > 1) return 1;
+ return v;
+}
+
+// Pure helper exported for tests: derive an expression morph's activation from a
+// canonical ARKit frame given its component weights (the inverse of the
+// VRM/Oculus→ARKit maps).
+export function deriveExpressionWeight(arkitFrame, components) {
+ let sum = 0;
+ let denom = 0;
+ for (const name in components) {
+ const w = components[name];
+ denom += w;
+ sum += (arkitFrame[name] || 0) * w;
+ }
+ return denom > 0 ? clamp01(sum / denom) : 0;
+}
diff --git a/tests/a2f-nvidia.test.js b/tests/a2f-nvidia.test.js
new file mode 100644
index 000000000..c9fd796a0
--- /dev/null
+++ b/tests/a2f-nvidia.test.js
@@ -0,0 +1,106 @@
+// Tests for the server-side Audio2Face-3D module — the audio normalization math
+// and the vendored proto descriptor's wire contract. The live gRPC round-trip is
+// exercised separately by scripts/verify-nvidia-a2f.mjs (needs NVIDIA_API_KEY).
+
+import { describe, it, expect } from 'vitest';
+import { createRequire } from 'module';
+import { _internals, resolveA2fFunctionId, A2F_DEFAULT_FUNCTION_ID } from '../api/_lib/a2f-nvidia.js';
+import a2fDescriptor from '../api/_lib/a2f-protos/descriptor.js';
+
+const require = createRequire(import.meta.url);
+
+describe('a2f audio normalization', () => {
+ it('downmixes interleaved stereo s16 to mono by averaging', () => {
+ // L = 100, R = 300 → mono 200, per frame.
+ const stereo = new Int16Array([100, 300, -100, -300]);
+ const buf = Buffer.from(stereo.buffer);
+ const mono = _internals.toMonoInt16(buf, 2);
+ expect(Array.from(mono)).toEqual([200, -200]);
+ });
+
+ it('passes mono through untouched', () => {
+ const m = new Int16Array([1, 2, 3, 4]);
+ const out = _internals.toMonoInt16(Buffer.from(m.buffer), 1);
+ expect(Array.from(out)).toEqual([1, 2, 3, 4]);
+ });
+
+ it('resamples to the target rate with the expected length and endpoints', () => {
+ // 8 samples @ 32 kHz → 16 kHz halves the length.
+ const src = new Int16Array([0, 1000, 2000, 3000, 4000, 5000, 6000, 7000]);
+ const out = _internals.resampleInt16(src, 32000, 16000);
+ expect(out.length).toBe(4);
+ expect(out[0]).toBe(0); // first sample preserved
+ });
+
+ it('returns the same array when rates match', () => {
+ const src = new Int16Array([1, 2, 3]);
+ expect(_internals.resampleInt16(src, 16000, 16000)).toBe(src);
+ });
+});
+
+describe('a2f function id resolution', () => {
+ it('defaults to the published James model id', () => {
+ const prev = process.env.NVIDIA_A2F_FUNCTION_ID;
+ delete process.env.NVIDIA_A2F_FUNCTION_ID;
+ expect(resolveA2fFunctionId()).toBe(A2F_DEFAULT_FUNCTION_ID);
+ expect(resolveA2fFunctionId('explicit-id')).toBe('explicit-id');
+ if (prev !== undefined) process.env.NVIDIA_A2F_FUNCTION_ID = prev;
+ });
+});
+
+describe('a2f proto descriptor wire contract', () => {
+ const protobuf = require('protobufjs');
+ const root = protobuf.Root.fromJSON(a2fDescriptor);
+
+ it('exposes the A2FControllerService.ProcessAudioStream surface', () => {
+ const svc = root.lookupService('nvidia_ace.services.a2f_controller.v1.A2FControllerService');
+ expect(svc.methods.ProcessAudioStream).toBeTruthy();
+ expect(svc.methods.ProcessAudioStream.requestStream).toBe(true);
+ expect(svc.methods.ProcessAudioStream.responseStream).toBe(true);
+ });
+
+ it('round-trips an AudioStream header the module sends', () => {
+ const AudioStream = root.lookupType('nvidia_ace.controller.v1.AudioStream');
+ // The module passes the enum by NAME ('AUDIO_FORMAT_PCM'); grpc-js/proto-
+ // loader serialize via fromObject(), which resolves enum names to numbers —
+ // so mirror that path here rather than create()/verify() (which want a number).
+ const msg = {
+ audio_stream_header: {
+ audio_header: {
+ audio_format: 'AUDIO_FORMAT_PCM',
+ channel_count: 1,
+ samples_per_second: 16000,
+ bits_per_sample: 16,
+ },
+ blendshape_params: { enable_clamping_bs_weight: true },
+ },
+ };
+ const decoded = AudioStream.toObject(
+ AudioStream.decode(AudioStream.encode(AudioStream.fromObject(msg)).finish()),
+ { enums: String, defaults: true, oneofs: true },
+ );
+ expect(decoded.audio_stream_header.audio_header.samples_per_second).toBe(16000);
+ expect(decoded.audio_stream_header.audio_header.audio_format).toBe('AUDIO_FORMAT_PCM');
+ expect(decoded.audio_stream_header.blendshape_params.enable_clamping_bs_weight).toBe(true);
+ });
+
+ it('decodes an AnimationDataStream blendshape frame the module reads', () => {
+ const ADS = root.lookupType('nvidia_ace.controller.v1.AnimationDataStream');
+ // Header carries the ordered blendshape names; a data frame carries weights
+ // with a time code — exactly the two fields a2f-nvidia.js consumes.
+ const headerBuf = ADS.encode(ADS.create({
+ animation_data_stream_header: { skel_animation_header: { blend_shapes: ['JawOpen', 'MouthSmileLeft'] } },
+ })).finish();
+ const frameBuf = ADS.encode(ADS.create({
+ animation_data: { skel_animation: { blend_shape_weights: [{ time_code: 0.5, values: [0.8, 0.2] }] } },
+ })).finish();
+
+ const header = ADS.toObject(ADS.decode(headerBuf), { defaults: true, oneofs: true, arrays: true });
+ const frame = ADS.toObject(ADS.decode(frameBuf), { defaults: true, oneofs: true, arrays: true });
+
+ expect(header.animation_data_stream_header.skel_animation_header.blend_shapes).toEqual(['JawOpen', 'MouthSmileLeft']);
+ const bsw = frame.animation_data.skel_animation.blend_shape_weights[0];
+ expect(bsw.time_code).toBeCloseTo(0.5, 5);
+ expect(bsw.values[0]).toBeCloseTo(0.8, 5);
+ });
+});
diff --git a/tests/a2f-player.test.js b/tests/a2f-player.test.js
new file mode 100644
index 000000000..14664ec78
--- /dev/null
+++ b/tests/a2f-player.test.js
@@ -0,0 +1,145 @@
+// Tests for the Audio2Face-3D → morph-target mapping + playback layer.
+//
+// No DOM / no real three.js: we hand A2FPlayer minimal stand-in meshes that
+// expose just morphTargetDictionary + morphTargetInfluences (the only surface it
+// touches) so vitest can exercise the cross-convention mapping directly. The
+// guarantee under test: an A2F ARKit track drives ARKit rigs DIRECTLY and
+// VRM/Oculus rigs by DERIVING vowel/viseme activation — with no rig allowlist.
+
+import { describe, it, expect } from 'vitest';
+import { A2FPlayer, deriveExpressionWeight } from '../src/voice/a2f-player.js';
+
+// Build a fake Object3D root whose traverse() visits the given meshes.
+function makeRoot(meshes) {
+ return {
+ traverse(cb) {
+ cb(this);
+ for (const m of meshes) cb(m);
+ },
+ };
+}
+
+function makeMesh(name, morphNames) {
+ const dict = {};
+ morphNames.forEach((n, i) => (dict[n] = i));
+ return {
+ isMesh: true,
+ name,
+ morphTargetDictionary: dict,
+ morphTargetInfluences: new Array(morphNames.length).fill(0),
+ };
+}
+
+// A track with a single column so the index math is obvious.
+function jawTrack(values, names = ['JawOpen']) {
+ return {
+ fps: 30,
+ blendShapeNames: names,
+ frames: values.map((row, i) => ({ t: i / 30, w: Array.isArray(row) ? row : [row] })),
+ };
+}
+
+describe('deriveExpressionWeight', () => {
+ it('returns the weighted average activation of an expression’s components', () => {
+ // VRM "Ou" = { mouthFunnel: 0.7, mouthPucker: 0.4, jawOpen: 0.2 }
+ const components = { mouthFunnel: 0.7, mouthPucker: 0.4, jawOpen: 0.2 };
+ // Fully-active components → activation 1.0
+ expect(deriveExpressionWeight({ mouthFunnel: 1, mouthPucker: 1, jawOpen: 1 }, components)).toBeCloseTo(1, 5);
+ // Nothing active → 0
+ expect(deriveExpressionWeight({}, components)).toBe(0);
+ // Only the dominant component half-active → ~ (0.7*0.5)/1.3
+ expect(deriveExpressionWeight({ mouthFunnel: 0.5 }, components)).toBeCloseTo((0.7 * 0.5) / 1.3, 5);
+ });
+
+ it('clamps to [0,1]', () => {
+ expect(deriveExpressionWeight({ jawOpen: 5 }, { jawOpen: 1 })).toBe(1);
+ });
+});
+
+describe('A2FPlayer · direct ARKit rig', () => {
+ it('writes each A2F shape onto its canonical morph, case/separator-insensitive', () => {
+ // Rig spells it "jaw_open"; A2F emits "JawOpen" — both normalize to jawOpen.
+ const mesh = makeMesh('Face', ['jaw_open', 'mouthSmileLeft']);
+ const player = new A2FPlayer();
+ player.attach(makeRoot([mesh]));
+ player.setTrack(jawTrack([0, 1]));
+ expect(player.hasCoverage()).toBe(true);
+
+ player.update(0);
+ expect(mesh.morphTargetInfluences[0]).toBeCloseTo(0, 5);
+ player.update(1 / 30); // second frame, JawOpen = 1
+ expect(mesh.morphTargetInfluences[0]).toBeCloseTo(1, 5);
+ });
+
+ it('interpolates between the 30 fps frames', () => {
+ const mesh = makeMesh('Face', ['jawOpen']);
+ const player = new A2FPlayer();
+ player.attach(makeRoot([mesh]));
+ player.setTrack(jawTrack([0, 1])); // frame0 t=0 → 0, frame1 t=1/30 → 1
+ player.update(0.5 / 30); // halfway
+ expect(mesh.morphTargetInfluences[0]).toBeCloseTo(0.5, 2);
+ });
+
+ it('does NOT derive vowel morphs when direct mouth morphs exist', () => {
+ // Mesh has both jawOpen (direct) and an "A" morph; the A morph must stay
+ // untouched so we never double-stack the lips.
+ const mesh = makeMesh('Face', ['jawOpen', 'A']);
+ const player = new A2FPlayer();
+ player.attach(makeRoot([mesh]));
+ player.setTrack(jawTrack([1]));
+ player.update(0);
+ expect(mesh.morphTargetInfluences[0]).toBeCloseTo(1, 5); // jawOpen driven
+ expect(mesh.morphTargetInfluences[1]).toBe(0); // A untouched
+ });
+});
+
+describe('A2FPlayer · VRM vowel-only rig', () => {
+ it('derives the VRM "A" vowel from the A2F JawOpen channel', () => {
+ // VRM_TO_ARKIT.A = { jawOpen: 1.0 } → A tracks JawOpen directly.
+ const mesh = makeMesh('VRMFace', ['A', 'I', 'O']);
+ const player = new A2FPlayer();
+ player.attach(makeRoot([mesh]));
+ player.setTrack(jawTrack([1])); // JawOpen = 1
+ player.update(0);
+ expect(mesh.morphTargetInfluences[0]).toBeCloseTo(1, 5); // A
+ });
+});
+
+describe('A2FPlayer · Oculus viseme rig', () => {
+ it('derives viseme_aa from JawOpen', () => {
+ // OCULUS_TO_ARKIT.viseme_aa = { jawOpen: 0.95 } → activation 1 at JawOpen=1.
+ const mesh = makeMesh('OculusFace', ['viseme_aa', 'viseme_O', 'viseme_PP']);
+ const player = new A2FPlayer();
+ player.attach(makeRoot([mesh]));
+ player.setTrack(jawTrack([1]));
+ player.update(0);
+ expect(mesh.morphTargetInfluences[0]).toBeCloseTo(1, 5); // viseme_aa
+ });
+});
+
+describe('A2FPlayer · lifecycle', () => {
+ it('reports no coverage for a rig with no recognizable face morphs', () => {
+ const mesh = makeMesh('Hair', ['hairWindLeft', 'hairWindRight']);
+ const player = new A2FPlayer();
+ player.attach(makeRoot([mesh]));
+ player.setTrack(jawTrack([1]));
+ expect(player.hasCoverage()).toBe(false);
+ });
+
+ it('reset settles every bound morph to zero', () => {
+ const mesh = makeMesh('Face', ['jawOpen']);
+ const player = new A2FPlayer();
+ player.attach(makeRoot([mesh]));
+ player.setTrack(jawTrack([1]));
+ player.update(0);
+ expect(mesh.morphTargetInfluences[0]).toBeGreaterThan(0);
+ player.reset();
+ expect(mesh.morphTargetInfluences[0]).toBe(0);
+ });
+
+ it('is a no-op before attach/setTrack', () => {
+ const player = new A2FPlayer();
+ expect(() => player.update(0)).not.toThrow();
+ expect(player.hasCoverage()).toBe(false);
+ });
+});
diff --git a/tests/agent-money-stream.test.js b/tests/agent-money-stream.test.js
new file mode 100644
index 000000000..3b556b37a
--- /dev/null
+++ b/tests/agent-money-stream.test.js
@@ -0,0 +1,48 @@
+// Money Streams — the accrual + ceiling math that backs pay-per-second income.
+//
+// The single money-safety invariant a streamer signs for is `maxTotal`: no matter
+// how long a stream runs or how high the rate, the amount projected/owed can never
+// exceed the ceiling. accruedHuman() is the pure function the live meter and the
+// settlement loop both derive from, so these tests pin that guarantee.
+
+import { describe, it, expect } from 'vitest';
+import { accruedHuman, STREAM_ASSETS } from '../src/shared/agent-money-stream.js';
+
+describe('accruedHuman · per-second accrual', () => {
+ it('accrues linearly with active time at the chosen rate', () => {
+ // 0.06 SOL/min = 0.001 SOL/sec. 30s of active time → 0.03 SOL.
+ expect(accruedHuman({ ratePerMinute: 0.06, activeMs: 30_000, maxTotal: 1 })).toBeCloseTo(0.03, 9);
+ // One full minute → exactly the per-minute rate.
+ expect(accruedHuman({ ratePerMinute: 0.25, activeMs: 60_000, maxTotal: 100 })).toBeCloseTo(0.25, 9);
+ });
+
+ it('never exceeds the signed ceiling, however long it runs', () => {
+ // 1 SOL/min for an hour would be 60 SOL, but the cap is 0.5.
+ expect(accruedHuman({ ratePerMinute: 1, activeMs: 3_600_000, maxTotal: 0.5 })).toBe(0.5);
+ // Exactly at the cap stays at the cap.
+ expect(accruedHuman({ ratePerMinute: 1, activeMs: 30_000, maxTotal: 0.5 })).toBe(0.5);
+ });
+
+ it('returns 0 before any active time and for a zero/negative rate', () => {
+ expect(accruedHuman({ ratePerMinute: 0.5, activeMs: 0, maxTotal: 10 })).toBe(0);
+ expect(accruedHuman({ ratePerMinute: 0, activeMs: 60_000, maxTotal: 10 })).toBe(0);
+ expect(accruedHuman({ ratePerMinute: -1, activeMs: 60_000, maxTotal: 10 })).toBe(0);
+ });
+
+ it('treats a missing/invalid cap as uncapped (the engine always passes a real cap)', () => {
+ expect(accruedHuman({ ratePerMinute: 0.1, activeMs: 60_000, maxTotal: 0 })).toBeCloseTo(0.1, 9);
+ expect(accruedHuman({ ratePerMinute: 0.1, activeMs: 60_000, maxTotal: NaN })).toBeCloseTo(0.1, 9);
+ });
+});
+
+describe('STREAM_ASSETS · supported rails', () => {
+ it('offers SOL and USDC with sane per-minute presets', () => {
+ const ids = STREAM_ASSETS.map((a) => a.id);
+ expect(ids).toContain('SOL');
+ expect(ids).toContain('USDC');
+ for (const a of STREAM_ASSETS) {
+ expect(a.ratePresets.length).toBeGreaterThan(0);
+ expect(a.ratePresets.every((p) => p > 0)).toBe(true);
+ }
+ });
+});
diff --git a/tests/agent-wealth-state.test.js b/tests/agent-wealth-state.test.js
new file mode 100644
index 000000000..ea94feeeb
--- /dev/null
+++ b/tests/agent-wealth-state.test.js
@@ -0,0 +1,132 @@
+// Unit tests for Embodied Finance — src/shared/agent-wealth-state.js.
+//
+// The wealth state is the DYNAMICS layer on top of the static net-worth aura:
+// real 24h momentum, active money streams, and tip recency turned into a small,
+// honest, DETERMINISTIC dynamics descriptor. These tests pin that contract —
+// the neutral fallback, the normalize mapping from the server `flow` block, the
+// momentum→trend/intensity/warmth mapping, the streaming + tip-recency flags
+// (with `now` injected so there is no time flakiness), and the momentum label.
+// No network: every input is a plain object.
+
+import { describe, it, expect } from 'vitest';
+import {
+ computeWealthDynamics,
+ formatMomentum,
+ _internals,
+} from '../src/shared/agent-wealth-state.js';
+
+const { normalizeWealth, neutralState, RECENT_TIP_MS } = _internals;
+
+describe('neutralState', () => {
+ it('is a coherent, honest dormant baseline (never a fake glow)', () => {
+ const s = neutralState('a1', 'mainnet');
+ expect(s.tier).toBe('dormant');
+ expect(s.level).toBe(0);
+ expect(s.balanceSol).toBe(0);
+ expect(s.balanceUsd).toBe(0);
+ expect(s.momentum).toBe(0);
+ expect(s.streamingNow).toBe(0);
+ expect(s.lastTipAt).toBeNull();
+ expect(s.ok).toBe(false);
+ });
+});
+
+describe('normalizeWealth', () => {
+ it('maps the server flow block onto the canonical wealth state', () => {
+ const data = {
+ tier: { key: 'glow', label: 'Glow', index: 3 },
+ is_owner: true,
+ portfolio: { usd: 420, sol: 2.1 },
+ flow: {
+ balance_usd: 420, balance_sol: 2.1, tier: 'glow',
+ momentum: 0.6, momentum_usd_24h: 80, inflow_usd_24h: 100, outflow_usd_24h: 20,
+ streaming_now: 2, last_tip_at: '2026-06-23T00:00:00.000Z',
+ },
+ };
+ const s = normalizeWealth('a1', 'mainnet', data, data.flow);
+ expect(s.tier).toBe('glow');
+ expect(s.level).toBe(3);
+ expect(s.balanceUsd).toBe(420);
+ expect(s.balanceSol).toBe(2.1);
+ expect(s.momentum).toBe(0.6);
+ expect(s.momentumUsd24h).toBe(80);
+ expect(s.streamingNow).toBe(2);
+ expect(s.lastTipAt).toBe('2026-06-23T00:00:00.000Z');
+ expect(s.isOwner).toBe(true);
+ expect(s.ok).toBe(true);
+ });
+
+ it('clamps momentum into [-1,1] and floors streaming at 0', () => {
+ const flow = { balance_usd: 0, momentum: 5, streaming_now: -3 };
+ const s = normalizeWealth('a1', 'mainnet', { flow }, flow);
+ expect(s.momentum).toBe(1);
+ expect(s.streamingNow).toBe(0);
+ });
+
+ it('derives the tier from balance when the server omits a tier object', () => {
+ const flow = { balance_usd: 30000 }; // ≥ $25k → luminous
+ const s = normalizeWealth('a1', 'mainnet', { flow }, flow);
+ expect(s.tier).toBe('luminous');
+ expect(s.level).toBe(5);
+ });
+});
+
+describe('computeWealthDynamics', () => {
+ const base = { momentum: 0, streamingNow: 0, lastTipAt: null };
+
+ it('a flat wallet reads neutral — no trend, no boost, no warmth', () => {
+ const d = computeWealthDynamics({ ...base });
+ expect(d.trend).toBe('flat');
+ expect(d.intensityDelta).toBe(0);
+ expect(d.warmth).toBe(0);
+ expect(d.streaming).toBe(false);
+ expect(d.recentTip).toBe(false);
+ });
+
+ it('positive momentum warms + lifts intensity; negative cools + dims', () => {
+ const up = computeWealthDynamics({ ...base, momentum: 0.5 });
+ expect(up.trend).toBe('up');
+ expect(up.warmth).toBe(0.5);
+ expect(up.intensityDelta).toBeGreaterThan(0);
+
+ const down = computeWealthDynamics({ ...base, momentum: -0.5 });
+ expect(down.trend).toBe('down');
+ expect(down.warmth).toBe(-0.5);
+ expect(down.intensityDelta).toBeLessThan(0);
+ });
+
+ it('intensity delta stays inside a tasteful band (never overpowers the tier)', () => {
+ expect(Math.abs(computeWealthDynamics({ ...base, momentum: 1 }).intensityDelta)).toBeLessThanOrEqual(0.16);
+ expect(Math.abs(computeWealthDynamics({ ...base, momentum: -1 }).intensityDelta)).toBeLessThanOrEqual(0.16);
+ });
+
+ it('streaming flips on only when a real stream is open', () => {
+ expect(computeWealthDynamics({ ...base, streamingNow: 0 }).streaming).toBe(false);
+ const d = computeWealthDynamics({ ...base, streamingNow: 3 });
+ expect(d.streaming).toBe(true);
+ expect(d.streamingCount).toBe(3);
+ });
+
+ it('a tip is "recent" only within the recency window (now injected)', () => {
+ const now = 1_000_000_000_000;
+ const fresh = new Date(now - 30_000).toISOString();
+ const stale = new Date(now - RECENT_TIP_MS - 1_000).toISOString();
+ expect(computeWealthDynamics({ ...base, lastTipAt: fresh }, now).recentTip).toBe(true);
+ expect(computeWealthDynamics({ ...base, lastTipAt: stale }, now).recentTip).toBe(false);
+ });
+
+ it('is deterministic — same (state, now) yields the same dynamics', () => {
+ const st = { momentum: 0.33, streamingNow: 1, lastTipAt: new Date(500).toISOString() };
+ expect(computeWealthDynamics(st, 1000)).toEqual(computeWealthDynamics(st, 1000));
+ });
+});
+
+describe('formatMomentum', () => {
+ it('renders signed, compact, honest figures (— when flat)', () => {
+ expect(formatMomentum({ momentumUsd24h: 0 })).toBe('—');
+ expect(formatMomentum({ momentumUsd24h: 12 })).toBe('+$12 today');
+ expect(formatMomentum({ momentumUsd24h: -4 })).toBe('−$4 today');
+ expect(formatMomentum({ momentumUsd24h: 2500 })).toBe('+$2.5k today');
+ expect(formatMomentum({ momentumUsd24h: 0.5 })).toBe('+$0.50 today');
+ });
+});
diff --git a/tests/patronage.test.js b/tests/patronage.test.js
new file mode 100644
index 000000000..b7ad6e55d
--- /dev/null
+++ b/tests/patronage.test.js
@@ -0,0 +1,97 @@
+// Patronage — the pure tier/progress/season/entitlement math that decides what a
+// supporter's REAL on-chain support unlocks. The DB aggregation lives behind these
+// functions; here we pin the documented thresholds and the gating logic so a
+// refactor can't silently move a tier boundary or hand out an unearned perk.
+
+import { describe, it, expect } from 'vitest';
+import {
+ PATRON_LEVELS,
+ levelForUsd,
+ levelIndex,
+ nextLevelForUsd,
+ progressForUsd,
+ currentSeason,
+ entitledPerks,
+} from '../api/_lib/patronage.js';
+
+describe('levelForUsd · documented thresholds', () => {
+ it('is null below any support and Supporter at the first cent', () => {
+ expect(levelForUsd(0)).toBe(null);
+ expect(levelForUsd(-5)).toBe(null);
+ expect(levelForUsd(0.01).key).toBe('supporter');
+ expect(levelForUsd(9.99).key).toBe('supporter');
+ });
+
+ it('promotes exactly at $10 / $50 / $250', () => {
+ expect(levelForUsd(10).key).toBe('patron');
+ expect(levelForUsd(49.99).key).toBe('patron');
+ expect(levelForUsd(50).key).toBe('champion');
+ expect(levelForUsd(249.99).key).toBe('champion');
+ expect(levelForUsd(250).key).toBe('benefactor');
+ expect(levelForUsd(1_000_000).key).toBe('benefactor');
+ });
+
+ it('exposes a strictly increasing, ordered ladder', () => {
+ const mins = PATRON_LEVELS.map((l) => l.minUsd);
+ expect(mins).toEqual([...mins].sort((a, b) => a - b));
+ expect(levelIndex('supporter')).toBe(0);
+ expect(levelIndex('benefactor')).toBe(PATRON_LEVELS.length - 1);
+ });
+});
+
+describe('progressForUsd · progress toward the next tier', () => {
+ it('reports the next tier and the remaining dollars', () => {
+ const p = progressForUsd(10); // a fresh Patron, $40 from Champion
+ expect(p.current.key).toBe('patron');
+ expect(p.next.key).toBe('champion');
+ expect(p.remainingUsd).toBeCloseTo(40, 6);
+ expect(p.pct).toBeGreaterThanOrEqual(0);
+ expect(p.pct).toBeLessThanOrEqual(1);
+ });
+
+ it('caps out at the top tier with no next level', () => {
+ const p = progressForUsd(500);
+ expect(p.next).toBe(null);
+ expect(p.pct).toBe(1);
+ expect(p.remainingUsd).toBe(0);
+ });
+
+ it('points an unsupported wallet at Supporter', () => {
+ expect(nextLevelForUsd(0).key).toBe('supporter');
+ });
+});
+
+describe('entitledPerks · server-side gating', () => {
+ const perks = [
+ { id: 'a', isActive: true, thresholdUsd: 0, perkType: 'badge' },
+ { id: 'b', isActive: true, thresholdUsd: 10, perkType: 'greeting' },
+ { id: 'c', isActive: true, thresholdUsd: 50, perkType: 'skill' },
+ { id: 'd', isActive: false, thresholdUsd: 5, perkType: 'lore' },
+ ];
+
+ it('grants only perks whose threshold the support clears', () => {
+ expect(entitledPerks(perks, 0).map((p) => p.id)).toEqual([]); // $0 earns nothing
+ expect(entitledPerks(perks, 9.99).map((p) => p.id)).toEqual(['a']);
+ expect(entitledPerks(perks, 10).map((p) => p.id)).toEqual(['a', 'b']);
+ expect(entitledPerks(perks, 100).map((p) => p.id)).toEqual(['a', 'b', 'c']);
+ });
+
+ it('never grants an inactive perk, even when the threshold is met', () => {
+ expect(entitledPerks(perks, 1000).find((p) => p.id === 'd')).toBeUndefined();
+ });
+});
+
+describe('currentSeason · monthly epoch', () => {
+ it('derives a UTC month window from a fixed date', () => {
+ const s = currentSeason(new Date('2026-06-23T12:00:00Z'));
+ expect(s.key).toBe('2026-06');
+ expect(s.startsAt).toBe('2026-06-01T00:00:00.000Z');
+ expect(s.endsAt).toBe('2026-07-01T00:00:00.000Z');
+ });
+
+ it('rolls the year over at December', () => {
+ const s = currentSeason(new Date('2026-12-31T23:59:59Z'));
+ expect(s.key).toBe('2026-12');
+ expect(s.endsAt).toBe('2027-01-01T00:00:00.000Z');
+ });
+});
diff --git a/tests/strategy-objects.test.js b/tests/strategy-objects.test.js
new file mode 100644
index 000000000..e207ac0a7
--- /dev/null
+++ b/tests/strategy-objects.test.js
@@ -0,0 +1,234 @@
+/**
+ * Strategy Objects — pure rule-engine tests.
+ *
+ * Money-adjacent: a strategy's config is the leash the autonomous runtime trades
+ * against, so every bound, every entry gate, and every exit trigger is pinned here.
+ * The same functions run in the live cron runtime and in any backtest, so locking
+ * them down locks down both. No DB, no chain — pure logic only.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ validateStrategyConfig,
+ normalizeStrategyConfig,
+ matchesEntry,
+ shouldExit,
+ slugifyStrategy,
+ STRATEGY_CONFIG_DEFAULTS,
+} from '../api/_lib/strategy-schema.js';
+
+const NOW = 1_700_000_000_000; // fixed epoch ms so age math is deterministic
+const minsAgo = (m) => NOW - m * 60_000;
+
+describe('normalizeStrategyConfig', () => {
+ it('fills a complete config from empty input (every key present)', () => {
+ const c = normalizeStrategyConfig({});
+ expect(c.network).toBe('mainnet');
+ expect(c.entry.trigger).toBe('new_launch');
+ expect(c.sizing.amount_sol).toBe(STRATEGY_CONFIG_DEFAULTS.sizing.amount_sol);
+ expect(c.exits.stop_loss_pct).toBe(STRATEGY_CONFIG_DEFAULTS.exits.stop_loss_pct);
+ expect(c.risk.max_concurrent_positions).toBe(STRATEGY_CONFIG_DEFAULTS.risk.max_concurrent_positions);
+ });
+
+ it('clamps per-trade size to the hard ceiling (never a runaway number)', () => {
+ expect(normalizeStrategyConfig({ sizing: { amount_sol: 9_999 } }).sizing.amount_sol).toBe(100);
+ expect(normalizeStrategyConfig({ sizing: { amount_sol: -5 } }).sizing.amount_sol).toBe(0.0001);
+ });
+
+ it('clamps slippage into [0, 10000] bps and rounds it', () => {
+ expect(normalizeStrategyConfig({ sizing: { max_slippage_bps: 50_000 } }).sizing.max_slippage_bps).toBe(10_000);
+ expect(normalizeStrategyConfig({ sizing: { max_slippage_bps: 123.7 } }).sizing.max_slippage_bps).toBe(124);
+ });
+
+ it('clamps stop-loss into [1, 99] and applies the default when invalid', () => {
+ expect(normalizeStrategyConfig({ exits: { stop_loss_pct: 250 } }).exits.stop_loss_pct).toBe(99);
+ expect(normalizeStrategyConfig({ exits: { stop_loss_pct: 'nonsense' } }).exits.stop_loss_pct).toBe(STRATEGY_CONFIG_DEFAULTS.exits.stop_loss_pct);
+ });
+
+ it('coerces empty-string optional fields to null, keeps real numbers', () => {
+ const c = normalizeStrategyConfig({ entry: { min_liquidity_sol: '', max_market_cap_usd: '50000' } });
+ expect(c.entry.min_liquidity_sol).toBeNull();
+ expect(c.entry.max_market_cap_usd).toBe(50_000);
+ });
+
+ it('rejects an unknown network / trigger and falls back to defaults', () => {
+ const c = normalizeStrategyConfig({ network: 'testnet', entry: { trigger: 'rug_pull' } });
+ expect(c.network).toBe('mainnet');
+ expect(c.entry.trigger).toBe('new_launch');
+ });
+
+ it('clamps max_concurrent_positions to >= 1 (never zero — a 0 would never trade)', () => {
+ expect(normalizeStrategyConfig({ risk: { max_concurrent_positions: 0 } }).risk.max_concurrent_positions).toBe(1);
+ expect(normalizeStrategyConfig({ risk: { max_concurrent_positions: 999 } }).risk.max_concurrent_positions).toBe(50);
+ });
+});
+
+describe('validateStrategyConfig', () => {
+ const good = {
+ sizing: { amount_sol: 0.2 },
+ exits: { take_profit_pct: 100, stop_loss_pct: 40 },
+ };
+
+ it('accepts a sane config and returns the normalized form', () => {
+ const { valid, errors, config } = validateStrategyConfig(good);
+ expect(valid).toBe(true);
+ expect(errors).toHaveLength(0);
+ expect(config.exits.stop_loss_pct).toBe(40);
+ });
+
+ it('requires at least one upside exit (TP, trailing, or max-hold)', () => {
+ const { valid, errors } = validateStrategyConfig({
+ sizing: { amount_sol: 0.1 },
+ exits: { take_profit_pct: null, trailing_stop_pct: null, max_hold_minutes: null, stop_loss_pct: 40 },
+ });
+ expect(valid).toBe(false);
+ expect(errors.some((e) => e.field === 'exits')).toBe(true);
+ });
+
+ it('accepts a trailing-stop-only upside (no fixed TP needed)', () => {
+ const { valid } = validateStrategyConfig({
+ sizing: { amount_sol: 0.1 },
+ exits: { take_profit_pct: null, trailing_stop_pct: 25, stop_loss_pct: 40 },
+ });
+ expect(valid).toBe(true);
+ });
+
+ it('flags an inverted market-cap band', () => {
+ const { valid, errors } = validateStrategyConfig({
+ ...good,
+ entry: { min_market_cap_usd: 100_000, max_market_cap_usd: 10_000 },
+ });
+ expect(valid).toBe(false);
+ expect(errors.some((e) => e.field === 'entry.max_market_cap_usd')).toBe(true);
+ });
+
+ it('always carries a stop-loss — the downside is never undefined', () => {
+ const { config } = validateStrategyConfig({ sizing: { amount_sol: 0.1 }, exits: { take_profit_pct: 100 } });
+ expect(config.exits.stop_loss_pct).toBeGreaterThan(0);
+ });
+});
+
+describe('matchesEntry', () => {
+ const cfg = normalizeStrategyConfig({
+ entry: {
+ max_age_minutes: 60,
+ min_liquidity_sol: 5,
+ min_market_cap_usd: 10_000,
+ max_market_cap_usd: 500_000,
+ require_socials: true,
+ max_creator_launches: 3,
+ },
+ });
+ const launch = (over = {}) => ({
+ mint: 'THREEsynthetic1111111111111111111111111111',
+ created_at: minsAgo(5),
+ market_cap_usd: 50_000,
+ liquidity_sol: 12,
+ creator_launches: 1,
+ twitter: 'x.com/agent',
+ is_usdc_pair: false,
+ ...over,
+ });
+
+ it('passes a launch that clears every gate', () => {
+ const r = matchesEntry(cfg, launch(), NOW);
+ expect(r.pass).toBe(true);
+ });
+
+ it('rejects a launch older than the age window', () => {
+ const r = matchesEntry(cfg, launch({ created_at: minsAgo(120) }), NOW);
+ expect(r.pass).toBe(false);
+ expect(r.reasons[0]).toMatch(/too_old/);
+ });
+
+ it('rejects below-min liquidity', () => {
+ expect(matchesEntry(cfg, launch({ liquidity_sol: 1 }), NOW).pass).toBe(false);
+ });
+
+ it('rejects a market cap outside the band on both ends', () => {
+ expect(matchesEntry(cfg, launch({ market_cap_usd: 1_000 }), NOW).pass).toBe(false);
+ expect(matchesEntry(cfg, launch({ market_cap_usd: 9_000_000 }), NOW).pass).toBe(false);
+ });
+
+ it('rejects a serial deployer over the creator-launch cap', () => {
+ expect(matchesEntry(cfg, launch({ creator_launches: 10 }), NOW).pass).toBe(false);
+ });
+
+ it('rejects when socials are required but absent', () => {
+ expect(matchesEntry(cfg, launch({ twitter: null, telegram: null, website: null }), NOW).pass).toBe(false);
+ });
+
+ it('rejects a non-SOL-quoted pair when the strategy requires SOL', () => {
+ const solOnly = normalizeStrategyConfig({ entry: { require_sol_quote: true } });
+ expect(matchesEntry(solOnly, launch({ is_usdc_pair: true }), NOW).pass).toBe(false);
+ });
+
+ it('rejects a launch with no mint outright', () => {
+ expect(matchesEntry(cfg, { mint: null }, NOW).pass).toBe(false);
+ });
+
+ it('treats clock-skewed (future) timestamps as fresh, not a hard reject', () => {
+ const r = matchesEntry(cfg, launch({ created_at: NOW + 60_000 }), NOW);
+ expect(r.pass).toBe(true);
+ });
+});
+
+describe('shouldExit', () => {
+ const cfg = normalizeStrategyConfig({
+ exits: { take_profit_pct: 100, stop_loss_pct: 40, trailing_stop_pct: 25, max_hold_minutes: 120 },
+ });
+ const pos = (over = {}) => ({ entry_lamports: 1_000_000, peak_value_lamports: 1_000_000, opened_at: minsAgo(10), ...over });
+
+ it('holds inside the band', () => {
+ expect(shouldExit(cfg, pos(), 1_200_000, NOW).exit).toBe(false);
+ });
+
+ it('takes profit at the +TP threshold (2x)', () => {
+ const r = shouldExit(cfg, pos(), 2_000_000, NOW);
+ expect(r.exit).toBe(true);
+ expect(r.reason).toBe('take_profit');
+ });
+
+ it('stops out at the -SL threshold', () => {
+ const r = shouldExit(cfg, pos(), 600_000, NOW);
+ expect(r.exit).toBe(true);
+ expect(r.reason).toBe('stop_loss');
+ });
+
+ it('trails: exits when value drops the trail % from the peak (below the TP line)', () => {
+ // peak +80% (under the +100% TP), now +30% → 27.8% off peak, past the 25% trail.
+ const r = shouldExit(cfg, pos({ peak_value_lamports: 1_800_000 }), 1_300_000, NOW);
+ expect(r.exit).toBe(true);
+ expect(r.reason).toBe('trailing_stop');
+ });
+
+ it('times out past max-hold even when price-flat', () => {
+ const r = shouldExit(cfg, pos({ opened_at: minsAgo(200) }), 1_000_000, NOW);
+ expect(r.exit).toBe(true);
+ expect(r.reason).toBe('timeout');
+ });
+
+ it('honest with no entry basis: only the time exit can fire', () => {
+ const noBasis = pos({ entry_lamports: 0 });
+ expect(shouldExit(cfg, noBasis, 5_000_000, NOW).exit).toBe(false);
+ expect(shouldExit(cfg, { ...noBasis, opened_at: minsAgo(200) }, 5_000_000, NOW).reason).toBe('timeout');
+ });
+
+ it('take-profit takes precedence over stop-loss when both could be argued', () => {
+ // A huge jump can only be TP; confirm TP fires (precedence ordering is TP→SL).
+ expect(shouldExit(cfg, pos(), 10_000_000, NOW).reason).toBe('take_profit');
+ });
+});
+
+describe('slugifyStrategy', () => {
+ it('produces a url-safe slug', () => {
+ expect(slugifyStrategy('Fresh-Launch Sniper!! 🚀')).toBe('fresh-launch-sniper');
+ });
+ it('falls back to "strategy" for empty / symbol-only names', () => {
+ expect(slugifyStrategy('')).toBe('strategy');
+ expect(slugifyStrategy('@@@')).toBe('strategy');
+ });
+ it('caps slug length so a very long name can never overflow', () => {
+ expect(slugifyStrategy('a'.repeat(200)).length).toBeLessThanOrEqual(48);
+ });
+});
diff --git a/tests/strip-reasoning.test.js b/tests/strip-reasoning.test.js
new file mode 100644
index 000000000..233508b60
--- /dev/null
+++ b/tests/strip-reasoning.test.js
@@ -0,0 +1,103 @@
+/**
+ * Reasoning-trace stripper — unit tests.
+ *
+ * Covers the full-string helper and the streaming filter, including the cases
+ * that matter for live chat: tags split across SSE chunk boundaries, partial
+ * closers, unterminated traces, and stray "<" characters in normal prose that
+ * must NOT be swallowed.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { stripReasoning, createReasoningStripper } from '../api/_lib/strip-reasoning.js';
+
+// Feed a string through the streaming filter one chunk at a time and collect the
+// emitted output, so we can assert that chunking never changes the result.
+function streamThrough(chunks) {
+ const s = createReasoningStripper();
+ let out = '';
+ for (const c of chunks) out += s.push(c);
+ out += s.flush();
+ return out;
+}
+
+describe('stripReasoning (full string)', () => {
+ it('leaves text with no reasoning tags untouched', () => {
+ expect(stripReasoning('Just a normal answer.')).toBe('Just a normal answer.');
+ });
+
+ it('removes a single <think> block and keeps the answer', () => {
+ expect(stripReasoning('<think>plan the reply</think>The answer is 42.')).toBe('The answer is 42.');
+ });
+
+ it('keeps text that comes before the trace', () => {
+ expect(stripReasoning('Sure. <think>hmm</think>Done.')).toBe('Sure. Done.');
+ });
+
+ it('handles <thinking>, <reason>, and <reasoning> variants', () => {
+ expect(stripReasoning('<thinking>x</thinking>A')).toBe('A');
+ expect(stripReasoning('<reason>y</reason>B')).toBe('B');
+ expect(stripReasoning('<reasoning>z</reasoning>C')).toBe('C');
+ });
+
+ it('is case-insensitive', () => {
+ expect(stripReasoning('<THINK>secret</THINK>Visible')).toBe('Visible');
+ });
+
+ it('removes multiple blocks', () => {
+ expect(stripReasoning('<think>a</think>One <think>b</think>Two')).toBe('One Two');
+ });
+
+ it('drops an unterminated trace (no closing tag)', () => {
+ expect(stripReasoning('<think>this never closes and is all scratch work')).toBe('');
+ });
+
+ it('does not swallow a stray "<" in normal prose', () => {
+ expect(stripReasoning('if a < b then ok')).toBe('if a < b then ok');
+ });
+
+ it('preserves a non-reasoning angle-bracket tag', () => {
+ expect(stripReasoning('use <div> for layout')).toBe('use <div> for layout');
+ });
+
+ it('handles multiline reasoning content', () => {
+ expect(stripReasoning('<think>line1\nline2\nline3</think>final')).toBe('final');
+ });
+});
+
+describe('createReasoningStripper (streaming)', () => {
+ it('catches an opening tag split across chunks', () => {
+ expect(streamThrough(['<thi', 'nk>hidden</thi', 'nk>shown'])).toBe('shown');
+ });
+
+ it('catches a closing tag split across chunks', () => {
+ expect(streamThrough(['<think>secret</thin', 'k>answer'])).toBe('answer');
+ });
+
+ it('emits leading real text before the trace promptly', () => {
+ const s = createReasoningStripper();
+ const first = s.push('Hello there <thi');
+ expect(first).toBe('Hello there '); // the partial "<thi" is held back
+ const rest = s.push('nk>scratch</think> world') + s.flush();
+ expect(first + rest).toBe('Hello there world');
+ });
+
+ it('matches the full-string helper for an arbitrary chunking', () => {
+ const full = 'Intro <think>reasoning A</think>middle <reasoning>reasoning B</reasoning>end';
+ const chunked = streamThrough(['Int', 'ro <th', 'ink>reason', 'ing A</think>mid', 'dle <reason', 'ing>reasoning B</reaso', 'ning>end']);
+ // stripReasoning trims; the raw streamed output should equal the untrimmed clean text.
+ expect(chunked).toBe('Intro middle end');
+ expect(stripReasoning(full)).toBe('Intro middle end');
+ });
+
+ it('drops an unterminated trace at flush', () => {
+ expect(streamThrough(['answer first... ', '<think>then it rambles forever'])).toBe('answer first... ');
+ });
+
+ it('passes a stray "<" through across chunks', () => {
+ expect(streamThrough(['a <', ' b'])).toBe('a < b');
+ });
+
+ it('handles a chunk boundary that lands exactly on a complete tag', () => {
+ expect(streamThrough(['pre <think>', 'mid', '</think> post'])).toBe('pre post');
+ });
+});
diff --git a/vercel.json b/vercel.json
index f18299d75..481614b70 100644
--- a/vercel.json
+++ b/vercel.json
@@ -958,6 +958,10 @@
"src": "/lipsync/?",
"dest": "/demos/lipsync-tts.html"
},
+ {
+ "src": "/audio2face/?",
+ "dest": "/demos/audio2face.html"
+ },
{
"src": "/launch-week/?",
"dest": "/three-ws-launch-week.html"
@@ -1573,6 +1577,14 @@
"src": "/avatar-studio/",
"dest": "/avatar-studio.html"
},
+ {
+ "src": "/cosmos",
+ "dest": "/cosmos.html"
+ },
+ {
+ "src": "/cosmos/",
+ "dest": "/cosmos.html"
+ },
{
"src": "/demos",
"dest": "/demos/index.html"
@@ -3912,6 +3924,10 @@
"path": "/api/cron/flush-usage-events",
"schedule": "* * * * *"
},
+ {
+ "path": "/api/cron/wallet-intents",
+ "schedule": "*/10 * * * *"
+ },
{
"path": "/api/cron/dead-man-switch",
"schedule": "0 5 * * *"
diff --git a/vite.config.js b/vite.config.js
index 022b7a25d..7e459331d 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -343,6 +343,7 @@ const appConfig = {
watchlist: resolve(__dirname, 'pages/watchlist.html'),
leaderboard: resolve(__dirname, 'pages/leaderboard.html'),
mirror: resolve(__dirname, 'pages/mirror.html'),
+ strategies: resolve(__dirname, 'pages/strategies.html'),
trader: resolve(__dirname, 'pages/trader.html'),
trades: resolve(__dirname, 'pages/trades.html'),
'claim-wallet': resolve(__dirname, 'pages/claim-wallet.html'),
@@ -393,6 +394,7 @@ const appConfig = {
'avatar-sdk': resolve(__dirname, 'pages/avatar-sdk.html'),
brain: resolve(__dirname, 'pages/brain.html'),
'agent-studio': resolve(__dirname, 'pages/agent-studio.html'),
+ cosmos: resolve(__dirname, 'pages/cosmos.html'),
voice: resolve(__dirname, 'pages/voice.html'),
galaxy: resolve(__dirname, 'pages/galaxy.html'),
'ar-page': resolve(__dirname, 'pages/ar.html'),
@@ -470,6 +472,7 @@ const appConfig = {
'demos-brain': resolve(__dirname, 'public/demos/brain.html'),
'demos-lipsync-tts': resolve(__dirname, 'public/demos/lipsync-tts.html'),
'demos-lipsync-mic': resolve(__dirname, 'public/demos/lipsync-mic.html'),
+ 'demos-audio2face': resolve(__dirname, 'public/demos/audio2face.html'),
'demos-erc8004': resolve(__dirname, 'public/demos/erc8004.html'),
'demos-button-jump': resolve(__dirname, 'public/demos/button-jump.html'),
'demos-button': resolve(__dirname, 'public/demos/button.html'),
@@ -773,6 +776,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/leaderboard/': resolve(root, 'pages/leaderboard.html'),
'/mirror': resolve(root, 'pages/mirror.html'),
'/mirror/': resolve(root, 'pages/mirror.html'),
+ '/strategies': resolve(root, 'pages/strategies.html'),
+ '/strategies/': resolve(root, 'pages/strategies.html'),
'/trader': resolve(root, 'pages/trader.html'),
'/trader/': resolve(root, 'pages/trader.html'),
'/trades': resolve(root, 'pages/trades.html'),