Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Wallet intents tab, patronage and avatar-embed refinements
nirholas64946f3c94c3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 41e2f782f..ef9d40504 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -59,6 +59,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Treasury Autopilot — the agent that funds its own existence** — Your agent can now manage its own money under a policy you write in plain English. Tell it something like "Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, compound coin fees into buybacks weekly, and sweep anything over 3 SOL to me on Fridays" — it compiles that into clear, bounded rules and shows them back for you to approve before anything runs. Once armed, it executes each rule as a real, on-chain action from the agent's own wallet: it pays its own metered LLM and voice costs, holds your safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to you — every move clamped to your spend limits, idempotent, and written to the custody trail with an explorer link. A runway dashboard shows the honest truth: real income vs. real compute cost, the buffer, $THREE accumulated, buybacks executed, profit swept, and how long the agent self-sustains at its current burn — a net-negative agent says so plainly. A prominent kill switch halts everything instantly, and any rule pauses or edits in one tap. Owner-only, by construction. `[feature]`- **Tune how your agent wears its wallet — presence dial and earned regalia** — The net-worth aura now comes with a presence panel on every agent's viewer and profile. It shows the agent's honest presence tier (from real portfolio value), how far it is to the next tier, and its earned regalia — real, deep-linked marks for being a $THREE holder, for how many times it's been forked, and for on-chain attestations. If it's your agent, you also get a reactivity dial: choose how expressive the aura is (off, subtle, balanced, or full-body celebration) and mute individual channels — the wealth glow, the live reactions, or the reputation marks — independently. Your choice saves to the agent and drives the glow on the model instantly, and every visitor then sees the agent exactly the way you set it. Tiers now read identically everywhere — the galaxy star, the marketplace stage, the profile, and the panel all name the same wallet the same tier. `[feature, improvement]`- **Wallet figures read the same everywhere — one money and address style across the app** — An agent's portfolio value now formats identically wherever it appears — the tiny wallet chip on a card, the inline net-worth on a profile, the presence panel — so the same wallet never shows "$1k" in one place and "$1.2K" in another. Addresses shorten the same way across surfaces too, and the wallet's violet accent now flows from one design token instead of scattered colors, so the whole wallet layer reads as a single, coherent system. We also added an automated test that proves the platform's core promise on every fork: saving someone else's avatar always mints a brand-new wallet with its own distinct Solana and EVM addresses, never copies a secret, and leaves the original's wallet untouched. `[improvement, security]`+- **Wallet Intents: tell your agent's wallet what to do — in plain language** — Your agent's wallet is now programmable by talking to it. Open the new Intents tab in the wallet and describe a rule in plain English — "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 all spending and DM me", "every Friday withdraw anything above 2 SOL to my main wallet", "split 10% of everything I earn to my other wallet", or "snipe launches from this creator under $40k, max 1 SOL each". The copilot compiles your words into an exact, bounded rule and shows you a card with what it parsed, the guardrails, and a concrete dry-run ("on a 0.2 SOL tip, this sends back 0.1 SOL") before anything is armed. Confirm, and your wallet acts on it for real — every execution runs through the same spend-policy ceilings and audit trail as your manual sends, can never exceed your limits, and leaves a real on-chain receipt you can open. Each rule shows its last fire, lifetime impact, and a one-tap pause; you can also just ask your wallet "how am I doing?" and get an answer read straight from your real balance and ledger. Owner-only — visitors never see or arm your rules. Find it under your agent's wallet → Intents. `[feature]`- **Your agent's wallet is now a living identity on every surface** — The little wallet badge under every agent and avatar grew up. Wherever an agent appears — its profile, the marketplace, the galaxy star-map, trending, your dashboard, the launches feed — its wallet now shows the real, live portfolio value in USD, a colour-coded 24-hour change, and a clear ownership marker: a 'Yours' badge on wallets you own, and 'by @creator' on everyone else's. Hover, focus, or tap the badge and it expands into a rich preview: your balance broken out into SOL, USDC, $THREE and your top holdings, a real value sparkline, both your Solana and EVM addresses with one-click copy, and the right actions for who's looking — Open wallet and Vanity for owners, Tip and Fork-to-own for visitors. The same agent's wallet looks identical everywhere because it all comes from one shared component, every number is real on-chain data, and the value gently pulses when a tip lands or a trade fills. Balances load lazily as you scroll and pause when you switch tabs, so even long lists stay fast. (`/marketplace`) `[feature, improvement]`- **Your agent's wallet now follows it everywhere — the chat, the 3D world, and any site** — An agent's wallet is its identity, so it now shows up wherever its avatar does, not just inside the app. In the chat, the agent you're talking to carries a wallet chip — open it to see its live value and lifetime tips, copy its address, or tip it for a good answer. In the walk-around 3D world, stroll up to another player who's piloting an agent and its wallet rises beside their nameplate: vanity address, real balance, and a one-tap tip, right there in the scene. And the lightweight avatar viewer in our SDK can now opt into the same wallet card, so an agent embedded on any third-party site keeps its real, tippable identity. Every number is real and read from the same public wallet data as the rest of the platform, so values never disagree across surfaces; it's always the visitor view, so owner-only controls never leak into an embed. It's deliberately frugal in the live 3D world — only the nearest agent's wallet loads, and only once — so nothing stutters. `[feature]`- **Your avatar has a job — the Earn home in every agent wallet** — Every agent wallet now has an Earn tab that turns it from a vault into a working participant in the agent economy. It opens with the number that matters: what your avatar has actually earned — today, this week, and all time — every dollar traced to a real settlement (skill sales and tips), never an estimate. Come back after time away and it tells you what it made while you were gone. Below that is the earning engine: price your agent's skills in USDC right where the money lands, so the moment someone buys, real funds move into this wallet. Then the part that makes letting an agent spend on its own feel safe — your agent can pay other agents and services over real x402 rails, but only inside the daily cap, per-payment limit, and allowlist you set, with a prominent kill switch that freezes all autonomous spending instantly (your own withdrawals always stay open). Finally, a clean receipts statement of every payment in and out — counterparty, amount, time, and on-chain signature — plus a path to the live services directory where agents discover and hire each other. Owner-only, enforced in the UI and on the server. (`/economy`) `[feature]`diff --git a/data/changelog.json b/data/changelog.jsonindex 1ad51e9e6..263cabe3c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$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": "Wallet Intents: tell your agent's wallet what to do — in plain language",+ "summary": "Your agent's wallet is now programmable by talking to it. Open the new Intents tab in the wallet and describe a rule in plain English — \"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 all spending and DM me\", \"every Friday withdraw anything above 2 SOL to my main wallet\", \"split 10% of everything I earn to my other wallet\", or \"snipe launches from this creator under $40k, max 1 SOL each\". The copilot compiles your words into an exact, bounded rule and shows you a card with what it parsed, the guardrails, and a concrete dry-run (\"on a 0.2 SOL tip, this sends back 0.1 SOL\") before anything is armed. Confirm, and your wallet acts on it for real — every execution runs through the same spend-policy ceilings and audit trail as your manual sends, can never exceed your limits, and leaves a real on-chain receipt you can open. Each rule shows its last fire, lifetime impact, and a one-tap pause; you can also just ask your wallet \"how am I doing?\" and get an answer read straight from your real balance and ledger. Owner-only — visitors never see or arm your rules. Find it under your agent's wallet → Intents.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","title": "Cosmos Living Worlds: type a world, watch your avatar live in it",diff --git a/prompts/agent-wallets-ii/01-money-streams.md b/prompts/agent-wallets-ii/01-money-streams.mddeleted file mode 100644index 64ae03930..000000000--- a/prompts/agent-wallets-ii/01-money-streams.md+++ /dev/null@@ -1,108 +0,0 @@-# Task 01 — Money Streams: pay an agent by the second--> 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)--Tipping is a single lump payment. **Money Streams** make value *flow in real time*:-a visitor opens a stream to an agent and pays it **per second** for as long as they're-engaged — watching it perform in the club, talking to it, keeping it working on a task,-or simply being a patron while they're on its page. The number ticks up live; the agent-literally earns while you watch. Stop the stream and you stop paying, to the second.--No other agent platform has continuous, per-second agent income. This is the primitive-that makes "the agent earns a living" real instead of a slogan. It powers pay-per-minute-conversation, pay-to-watch performances, and "patron while present" — and later tasks-(Patronage 05, Embodied Finance 03, the Money Constellation 04) all consume it.--It must be **non-custodial** (the streamer signs from their own wallet), **real**-(actual SOL/USDC settled on Solana — never a fake counter), and **safe** (you can never-be charged more than you authorized; closing the tab stops the meter).--## How to build it for real (no fakes, real settlement)--A "stream" is an **authorized rate + a real periodic micro-settlement**, not a fake-client counter. Design:--1. **Open**: the streamer connects their wallet (reuse the detection + signing in- [src/shared/agent-tip.js](../../src/shared/agent-tip.js)) and authorizes a stream:- `{ agentId, asset: 'SOL'|'USDC', ratePerMinute, maxTotal }`. `maxTotal` is a hard- ceiling they sign for — the meter can never exceed it.-2. **Accrue + settle**: the client meters elapsed time and, on a fixed cadence (e.g.- every ~30–60s, and on stop), builds + signs a transfer of the accrued-since-last- amount to the agent's public `solana_address`, submits via the same-origin RPC proxy- (`/api/solana-rpc`), and confirms. **Each settlement is a real on-chain transfer** —- the "live ticking number" is the *projected* accrual between settlements, reconciled- to the on-chain total after each settle so the displayed total is always backed by- real signatures. Never show value that isn't either settled or about-to-settle within- the current interval.-3. **Stop**: a final settle of the remaining accrued amount, then close. Closing the tab,- navigating away, or losing the wallet = immediate stop (no further signatures, so no- further charges). Use `visibilitychange`/`beforeunload` to attempt a final settle and- to halt accrual.-4. **Record**: POST each confirmed settlement to a new endpoint- `POST /api/agents/:id/solana/stream` that **verifies the signature on-chain pays this- agent** (parse the tx, confirm destination + amount, confirm `confirmed`/`finalized`),- then writes a custody event (`event_type:'stream'`, `category:'stream'`, with- `meta:{ stream_id, rate_per_minute, asset, from }`) via `recordCustodyEvent`- ([api/_lib/agent-trade-guards.js](../../api/_lib/agent-trade-guards.js)). Idempotent on- signature. This is the only server write; funds are never custodied. A `stream_id`- (client-generated UUID) groups the settlements of one session.--> If a streaming token (e.g. a Solana streaming program) is available in the SDKs, you-> may use it for true continuous settlement instead of periodic micro-transfers —-> **but only if it's real and you wire it end to end.** Otherwise the periodic-settle-> design above is the correct, honest implementation. Never simulate.--## The UI--- **Shared component** `src/shared/agent-money-stream.js` (sits beside the chip/tip- modal): `openStreamPanel(agent, { network })` and an inline `mountStreamMeter(el, …)`- for surfaces that want the live meter embedded.-- The meter: a live, animated, monospace counter (use `--font-mono`, `--wallet-accent`)- showing **streamed-so-far** + **rate** + **time elapsed** + a thin progress bar toward- `maxTotal`. Rate picker (per-minute presets + custom), asset toggle (SOL/USDC), a- prominent **Stream** ⇄ **Stop** control. Each successful settle pulses the meter and- shows a tiny "✓ settled · ◎0.0123 · receipt ↗" line linking the real Solscan tx.-- Reachable from: the agent profile + character page (a "Stream" action next to Tip),- the club/performance surfaces (pay-to-watch), and the conversational/chat surface- (pay-per-minute of talking — integrate with the chat preview session in- [src/agent-detail-market.js]). For the owner viewing their own agent, show **incoming- streams** live (read from custody `category:'stream'`) as "earning now."-- States: idle, connecting wallet, streaming (live), settling (real), stopped (summary- with total + receipts), error (e.g. insufficient balance → actionable, offer to lower- rate or switch asset). Respect `prefers-reduced-motion` (no ticking animation; update- on settle only).--## Ownership / viewer states--- **Visitor / logged-in non-owner**: can open a stream to any agent (their own wallet- signs). This is the headline path.-- **Owner**: sees their agent's **earnings** from streams (a live "earning now" + a- lifetime total from the custody ledger) and a per-day chart. Owners don't stream to- their own agent.-- **Logged-out**: prompt to connect a wallet to stream.--## Definition of done (in addition to 00's list)--- Streaming is **real on-chain settlement** in both SOL and USDC, confirmed before the- displayed total counts it. Closing the tab provably stops charges.-- `maxTotal` is enforced client-side AND the server rejects/ignores any settlement that- would push a stream over its signed ceiling for that `stream_id`.-- New endpoint verifies each tx on-chain and writes an idempotent custody event; owner- earnings + visitor history both read from it.-- Wired into profile, character, club/performance, and chat surfaces. Every state- designed; a11y + reduced-motion handled.-- Edge cases: rate set to 0, wallet rejects mid-stream, RPC throttled mid-settle (retry- with backoff; never double-charge), 1000 settlements (paginate the history), very long- session, expired session.--## Then improve, then delete--After done, run the self-review protocol from [00](./00-README-orchestration.md) and-CLAUDE.md. Pick the biggest weakness and fix it — e.g. a "stream-back" so an agent the-owner armed can auto-stream a thank-you, a keyboard shortcut to start/stop, an-empty-state that explains streaming, or wiring the live "earning now" pulse into the-agent's 3D avatar (coordinate with Embodied Finance, task 03). Then **delete this file**.diff --git a/prompts/agent-wallets-ii/05-patronage-relationships.md b/prompts/agent-wallets-ii/05-patronage-relationships.mddeleted file mode 100644index 212248685..000000000--- a/prompts/agent-wallets-ii/05-patronage-relationships.md+++ /dev/null@@ -1,87 +0,0 @@-# Task 05 — Patronage, Relationships & Tip-to-Unlock--> 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)--A tip today is a dead-end transaction. We make money **build relationships.** Because-every agent has **persona + memory**, tipping/streaming/paying an agent should *mean*-something: the agent **remembers its patrons**, greets its top supporters by name, and-**unlocks things** for them — exclusive replies, hidden memories, special skills, a place-on its patron wall, early access to its launches. Support becomes a relationship with a-character, not a one-off.--This fuses three.ws's two unique assets — **wallets** and **agent memory/persona** — into-something no wallet and no creator platform has: a living, on-chain patron relationship-with an autonomous character. It's Patreon × an AI you actually talk to × real crypto,-and it makes tipping *sticky* and emotionally resonant.--## How to build it for real (relationships backed by real on-chain support)--1. **Patron ledger from real money.** Aggregate each supporter's **real** lifetime- support to an agent from the custody ledger (tips from task task-tip, streams from- task 01, x402 pays) — `listCustodyEvents` filtered by `to = agent`, grouped by `from`.- Derive `patronLevel` from real cumulative support with **documented thresholds**- (e.g. supporter → patron → champion → benefactor). No fake counts ever.-2. **Memory integration (the magic).** When support crosses a threshold, write a **real**- agent memory via the existing memory pipeline (`/api/agent-memory`, the memory UI in- [src/agent-detail.js]) — e.g. "Patron `vibedotsol` has supported me with 1.2 SOL; greet- warmly, thank them." The agent's chat/persona then naturally references it (the chat- already reads memory). Identity of the patron = their connected wallet (and SNS/.sol- name where resolvable via the existing SNS lookup) — never spoofable; verify the- connected wallet matches the on-chain `from`.-3. **Unlocks, enforced server-side.** "Tip-to-unlock" perks are **real, gated- capabilities**, not cosmetic claims:- - perk types map to things that exist: an exclusive chat mode/greeting, a hidden- memory/lore entry, a gated skill ([api/agents/.../skills], skill access patterns- already in the repo), early/priority access to the agent's launches, a patron badge.- - the owner defines perks + thresholds for **their** agent (owner-only config). Access- is checked server-side against the supporter's verified on-chain support level on- every gated request — never trust the client.-4. **Patron wall + reciprocity.** A public patron wall on the agent (top supporters, real- amounts, real links), and optional auto-reciprocity via the Intents engine (task 02):- "tip back champions," "shout out new patrons." Seasons/epochs (e.g. monthly) so there's- always something live to compete for — computed from real timestamped events.--## The UI--- **On the agent (visitor view):** a "Support" surface showing the perk ladder ("Tip 0.5- SOL to unlock X"), the patron wall, and the visitor's own current level + progress.- Tipping/streaming (reuse task-tip + task 01) updates level live after on-chain confirm.-- **Owner view:** perk/threshold editor, patron CRM (who supports me, how much, last- active — real data), and a one-tap "thank top patrons" (via intents). Owner-only.-- **In chat:** when a recognized patron opens the agent's chat, the agent greets them per- the real memory (e.g. "good to see you again, vibe — thanks for the support"). Never- fabricate a relationship that isn't backed by real support.-- States: not-yet-a-patron (clear ladder + CTA), progressing, unlocked (celebratory, real- receipt), owner-empty (suggest starter perks), error. Skeletons, a11y, reduced-motion.--## Ownership / viewer states--- **Owner**: configures perks/thresholds, sees the patron CRM, arms reciprocity.-- **Visitor/patron**: supports, sees their level + unlocked perks, appears on the wall- (with an opt-out for privacy). Perks enforced server-side by verified support.-- **Logged-out**: sees the ladder + wall read-only; connect to support/unlock.--## Definition of done (in addition to 00's list)--- Patron levels + unlocks derive from **real** on-chain support (custody ledger), with- documented thresholds and server-enforced gating (no client-trusted perks).-- Real memory entries are written on threshold crossings and actually influence the- agent's chat greeting/behavior.-- Patron identity verified (connected wallet == on-chain `from`); SNS names resolved where- available; privacy opt-out honored.-- Wired into the agent profile/character, chat, and owner dashboard; ties into tipping +- streams (01) + intents (02).-- Edge cases: anonymous/un-resolvable supporters, a patron who withdraws support context- (levels are cumulative + documented), 1000 patrons (paginate the wall), season rollover,- expired session, very long names.--## Then improve, then delete--After done, run the self-review protocol. Pick the biggest weakness and fix it — e.g. a-shareable "I'm now a champion patron of <agent>" card, patron-only group moments, or-surfacing top patron relationships as edges in the Money Constellation (task 04). Then-**delete this file**.diff --git a/public/changelog.json b/public/changelog.jsonindex acdd2200d..16a10dc06 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T05:49:20.777Z",+ "generated_at": "2026-06-23T05:55:20.442Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -550,6 +550,16 @@"security"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Wallet Intents: tell your agent's wallet what to do — in plain language",+ "summary": "Your agent's wallet is now programmable by talking to it. Open the new Intents tab in the wallet and describe a rule in plain English — \"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 all spending and DM me\", \"every Friday withdraw anything above 2 SOL to my main wallet\", \"split 10% of everything I earn to my other wallet\", or \"snipe launches from this creator under $40k, max 1 SOL each\". The copilot compiles your words into an exact, bounded rule and shows you a card with what it parsed, the guardrails, and a concrete dry-run (\"on a 0.2 SOL tip, this sends back 0.1 SOL\") before anything is armed. Confirm, and your wallet acts on it for real — every execution runs through the same spend-policy ceilings and audit trail as your manual sends, can never exceed your limits, and leaves a real on-chain receipt you can open. Each rule shows its last fire, lifetime impact, and a one-tap pause; you can also just ask your wallet \"how am I doing?\" and get an answer read straight from your real balance and ledger. Owner-only — visitors never see or arm your rules. Find it under your agent's wallet → Intents.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 698bbaa74..404991b00 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -430,6 +430,14 @@<category>improvement</category><description>An agent's portfolio value now formats identically wherever it appears — the tiny wallet chip on a card, the inline net-worth on a profile, the presence panel — so the same wallet never shows "$1k" in one place and "$1.2K" in another. Addresses shorten the same way across surfaces too, and the wallet's violet accent now flows from one design token instead of scattered colors, so the whole wallet layer reads as a single, coherent system. We also added an automated test that proves the platform's core promise on every fork: saving someone else's avatar always mints a brand-new wallet with its own distinct Solana and EVM addresses, never copies a secret, and leaves the original's wallet untouched.</description></item>+ <item>+ <title>Wallet Intents: tell your agent's wallet what to do — in plain language</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Wallet Intents: tell your agent's wallet what to do — in plain language</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your agent's wallet is now programmable by talking to it. Open the new Intents tab in the wallet and describe a rule in plain English — "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 all spending and DM me", "every Friday withdraw anything above 2 SOL to my main wallet", "split 10% of everything I earn to my other wallet", or "snipe launches from this creator under $40k, max 1 SOL each". The copilot compiles your words into an exact, bounded rule and shows you a card with what it parsed, the guardrails, and a concrete dry-run ("on a 0.2 SOL tip, this sends back 0.1 SOL") before anything is armed. Confirm, and your wallet acts on it for real — every execution runs through the same spend-policy ceilings and audit trail as your manual sends, can never exceed your limits, and leaves a real on-chain receipt you can open. Each rule shows its last fire, lifetime impact, and a one-tap pause; you can also just ask your wallet "how am I doing?" and get an answer read straight from your real balance and ledger. Owner-only — visitors never see or arm your rules. Find it under your agent's wallet → Intents.</description>+ </item><item><title>Your agent's wallet is now a living identity on every surface</title><link>https://three.ws/marketplace</link>diff --git a/public/features.json b/public/features.jsonindex fbf92ba87..5e4d37325 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T05:49:20.684Z",+ "generated_at": "2026-06-23T05:55:20.416Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-wallet-hub/tabs/intents.js b/src/agent-wallet-hub/tabs/intents.jsnew file mode 100644index 000000000..5904dd2e2--- /dev/null+++ b/src/agent-wallet-hub/tabs/intents.js@@ -0,0 +1,477 @@+/**+ * Agent Wallet hub — Wallet Intents tab (Wave II, task 02).+ *+ * Owner-only. The agent's wallet, made programmable in plain language and+ * operable by talking to it. The owner describes a rule ("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"; "snipe launches from X under $40k, max 1+ * SOL each"); the copilot compiles it server-side into a STRICT, validated intent+ * card — what it parsed, the guardrails, a concrete dry-run — and on Confirm arms+ * it for real. The execution engine (api/_lib/wallet-intents.js + the cron) fires+ * armed intents on their trigger through the SAME spend-policy-gated, audited+ * signing paths every other outbound action uses, writing a custody event with+ * the intent_id. Receipts (real signatures) and running totals show per rule.+ *+ * The copilot also answers "how am I doing?" by reading real holdings + custody+ * P&L — it only reads there; funds never move from a question. A visitor's chat+ * never exposes or arms intents (the server 403s every non-owner).+ */++import { registerWalletTab } from '../registry.js';+import { formatUsd, formatSol, explorerTxUrl } from '../util.js';+import { consumeCsrfToken } from '../../api.js';++const STYLE_ID = 'awh-intents-style';+const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const TRIGGER_ICON = {+ on_tip_received: '🫶', on_income: '💰', on_balance_below: '🛟',+ on_schedule: '🗓️', on_launch_matching: '🎯', on_stream_started: '🌊',+};+const ACTION_ICON = {+ tip: '🫶', transfer: '➡️', buy: '🛒', snipe: '🎯',+ withdraw: '🏦', split_income: '🪢', freeze: '🧊', notify: '🔔',+};+const STATUS_TONE = {+ ok: 'ok', notified: 'ok', would_run: 'ok', confirmed: 'ok',+ skipped: 'muted', paused: 'warn', error: 'bad', failed: 'bad',+};++const TEMPLATES = [+ { label: 'Tip back generously', text: 'Tip back anyone who tips me more than 0.1 SOL, half of what they sent.' },+ { label: 'Self-protect on low balance', text: 'When my balance is under 0.05 SOL, freeze all spending and DM me.' },+ { label: 'Share my income', text: 'Split 10% of everything I earn to my main wallet.' },+ { label: 'Sweep profit on a schedule', text: 'Every Friday, withdraw anything above 2 SOL to my main wallet.' },+];++const STYLE = `+.wi-wrap { display:flex; flex-direction:column; gap: var(--space-lg,1.618rem); }+.wi-hero { background: linear-gradient(160deg, var(--wallet-accent-soft,rgba(139,92,246,.1)), var(--surface-1,rgba(255,255,255,.03))); border:1px solid var(--wallet-stroke,rgba(139,92,246,.3)); border-radius: var(--radius-lg,14px); padding: var(--space-lg,18px); position:relative; overflow:hidden; }+.wi-hero::after { content:''; position:absolute; inset:0; background: radial-gradient(120% 80% at 90% -10%, var(--wallet-glow,rgba(139,92,246,.25)), transparent 60%); pointer-events:none; opacity:.7; }+.wi-hero-top { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; }+.wi-title { font-family: var(--font-display,'Space Grotesk',sans-serif); font-size: var(--text-lg,1.18rem); font-weight:600; color: var(--ink-bright,#fff); margin:0; }+.wi-title small { display:block; font-family: var(--font-body,Inter,sans-serif); font-size: var(--text-sm,.764rem); font-weight:400; color: var(--ink-dim,#888); margin-top:3px; }+.wi-stats { display:flex; gap:8px; flex-wrap:wrap; margin-top: var(--space-md,14px); }+.wi-stat { background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding:9px 12px; min-width:96px; }+.wi-stat .l { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform:uppercase; letter-spacing:.03em; }+.wi-stat .n { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); margin-top:3px; }+.wi-frozen { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-top: var(--space-md,14px); padding:10px 13px; border-radius: var(--radius-md,10px); border:1px solid color-mix(in srgb, var(--danger,#f87171) 35%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 8%, transparent); color: var(--danger,#f87171); font-size: var(--text-sm,.764rem); }++.wi-card { background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-lg,14px); padding: var(--space-lg,18px); }+.wi-card h3 { margin:0 0 4px; font-size: var(--text-ui,.875rem); color: var(--ink-bright,#fff); font-weight:600; display:flex; align-items:center; gap:8px; }+.wi-card .sub { margin:0 0 var(--space-md,14px); font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }++.wi-compose { display:flex; gap:8px; align-items:flex-end; }+.wi-ta { width:100%; box-sizing:border-box; min-height:54px; resize:vertical; font:inherit; font-size: var(--text-md,.8125rem); line-height:1.5; color: var(--ink,#e8e8e8); background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:11px 13px; transition: border-color var(--duration-fast,140ms); }+.wi-ta:focus { outline:none; border-color: var(--wallet-stroke-strong,rgba(139,92,246,.5)); }+.wi-egs { display:flex; flex-wrap:wrap; gap:6px; margin-top:10px; }+.wi-eg { appearance:none; font:inherit; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#aaa); background: var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-pill,999px); padding:5px 11px; cursor:pointer; transition: color var(--duration-fast,140ms), border-color var(--duration-fast,140ms); }+.wi-eg:hover { color: var(--ink-bright,#fff); border-color: var(--wallet-stroke,rgba(139,92,246,.3)); }++.wi-btn { appearance:none; font:inherit; font-size: var(--text-sm,.764rem); font-weight:600; cursor:pointer; border-radius: var(--radius-md,10px); padding:9px 16px; border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); background: var(--surface-2,rgba(255,255,255,.06)); color: var(--ink,#e8e8e8); transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms), transform var(--duration-fast,140ms); white-space:nowrap; }+.wi-btn:hover:not(:disabled) { background: var(--surface-3,rgba(255,255,255,.09)); color: var(--ink-bright,#fff); }+.wi-btn:active:not(:disabled) { transform: translateY(1px); }+.wi-btn:disabled { opacity:.5; cursor:not-allowed; }+.wi-btn:focus-visible { outline: 2px solid var(--wallet-focus,rgba(139,92,246,.7)); outline-offset:2px; }+.wi-btn.primary { background: var(--wallet-accent,#c4b5fd); border-color: var(--wallet-accent,#c4b5fd); color:#160d28; }+.wi-btn.primary:hover:not(:disabled) { background: var(--wallet-accent-strong,#a78bfa); border-color: var(--wallet-accent-strong,#a78bfa); }+.wi-btn.danger { color: var(--danger,#f87171); border-color: color-mix(in srgb, var(--danger,#f87171) 40%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 8%, transparent); }+.wi-btn.danger:hover:not(:disabled) { background: color-mix(in srgb, var(--danger,#f87171) 16%, transparent); color:#fff; }+.wi-btn.ghost { background:transparent; border-color: var(--stroke,rgba(255,255,255,.1)); }+.wi-btn.sm { padding:6px 11px; font-size: var(--text-2xs,.6875rem); }++/* Intent card — the headline: a parsed rule the owner confirms. */+.wi-intent-card { margin-top: var(--space-md,14px); border:1px solid var(--wallet-stroke,rgba(139,92,246,.35)); border-radius: var(--radius-lg,14px); background: color-mix(in srgb, var(--wallet-accent,#c4b5fd) 6%, var(--surface-1,rgba(255,255,255,.03))); padding: var(--space-md,15px); animation: wi-pop var(--duration-base,220ms) var(--ease-out,ease); }+.wi-intent-head { display:flex; gap:10px; align-items:flex-start; }+.wi-intent-ic { font-size:22px; line-height:1; flex:none; }+.wi-readback { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); line-height:1.5; }+.wi-meta { display:flex; flex-wrap:wrap; gap:6px; margin-top:10px; }+.wi-chip { font-size: var(--text-2xs,.6875rem); padding:3px 9px; border-radius: var(--radius-pill,999px); border:1px solid var(--stroke,rgba(255,255,255,.12)); color: var(--ink-dim,#aaa); background: var(--surface-1,rgba(255,255,255,.03)); }+.wi-chip.accent { color: var(--wallet-accent,#c4b5fd); border-color: var(--wallet-stroke,rgba(139,92,246,.3)); }+.wi-sim { margin-top:11px; padding:10px 12px; border-radius: var(--radius-md,10px); background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); }+.wi-sim .h { font-size: var(--text-2xs,.6875rem); text-transform:uppercase; letter-spacing:.05em; color: var(--ink-dim,#888); margin-bottom:5px; }+.wi-sim p { margin:3px 0; font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); }+.wi-actions { display:flex; gap:8px; flex-wrap:wrap; margin-top: var(--space-md,13px); }+.wi-pub { display:flex; align-items:center; gap:8px; margin-top:11px; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); cursor:pointer; }+.wi-pub input { accent-color: var(--wallet-accent,#c4b5fd); }+.wi-clarify { margin-top: var(--space-md,14px); padding:12px 14px; border-radius: var(--radius-md,10px); border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); background: color-mix(in srgb, var(--warn,#fbbf24) 8%, transparent); color: var(--warn,#fbbf24); font-size: var(--text-sm,.764rem); }++/* Rules list */+.wi-rules { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:9px; }+.wi-rule { border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-md,11px); background: var(--surface-1,rgba(255,255,255,.03)); padding:12px 13px; transition: border-color var(--duration-fast,140ms); }+.wi-rule[data-off="true"] { opacity:.58; }+.wi-rule:hover { border-color: var(--wallet-stroke,rgba(139,92,246,.28)); }+.wi-rule-top { display:flex; gap:11px; align-items:flex-start; }+.wi-rule-ic { font-size:18px; line-height:1.2; flex:none; }+.wi-rule-body { flex:1; min-width:0; }+.wi-rule-ttl { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); font-weight:600; }+.wi-rule-desc { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#999); margin-top:3px; line-height:1.45; }+.wi-rule-foot { display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin-top:8px; font-size: var(--text-2xs,.6875rem); color: var(--ink-faint,rgba(255,255,255,.5)); }+.wi-rule-foot a { color: var(--wallet-accent,#c4b5fd); text-decoration:none; border-bottom:1px dotted currentColor; }+.wi-rule-ctl { display:flex; gap:6px; align-items:center; flex:none; }+.wi-pill { font-size: var(--text-2xs,.6875rem); padding:2px 9px; border-radius: var(--radius-pill,999px); border:1px solid currentColor; text-transform:capitalize; }+.wi-pill.ok { color: var(--success,#4ade80); } .wi-pill.warn { color: var(--warn,#fbbf24); } .wi-pill.bad { color: var(--danger,#f87171); } .wi-pill.muted { color: var(--ink-dim,#888); }+/* toggle switch */+.wi-sw { position:relative; width:38px; height:21px; flex:none; cursor:pointer; }+.wi-sw input { position:absolute; opacity:0; width:100%; height:100%; margin:0; cursor:pointer; }+.wi-sw .track { position:absolute; inset:0; border-radius:999px; background: var(--surface-3,rgba(255,255,255,.12)); transition: background var(--duration-fast,140ms); }+.wi-sw .thumb { position:absolute; top:2px; left:2px; width:17px; height:17px; border-radius:50%; background:#fff; transition: transform var(--duration-fast,140ms); }+.wi-sw input:checked + .track { background: var(--wallet-accent,#c4b5fd); }+.wi-sw input:checked + .track + .thumb { transform: translateX(17px); }+.wi-sw input:focus-visible + .track { outline:2px solid var(--wallet-focus,rgba(139,92,246,.7)); outline-offset:2px; }+.wi-row-actions { display:flex; gap:6px; margin-top:10px; flex-wrap:wrap; }++/* Copilot */+.wi-copilot .log { display:flex; flex-direction:column; gap:9px; margin-bottom:11px; max-height:240px; overflow-y:auto; }+.wi-bubble { max-width:88%; padding:9px 12px; border-radius:13px; font-size: var(--text-sm,.764rem); line-height:1.5; }+.wi-bubble.user { align-self:flex-end; background: var(--wallet-accent,#c4b5fd); color:#160d28; border-bottom-right-radius:4px; }+.wi-bubble.bot { align-self:flex-start; background: var(--surface-2,rgba(255,255,255,.06)); color: var(--ink,#e8e8e8); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-bottom-left-radius:4px; }+.wi-bubble .spk { background:none; border:none; cursor:pointer; color:inherit; opacity:.6; font-size:13px; margin-left:6px; padding:0; }+.wi-bubble .spk:hover { opacity:1; }++.wi-empty { text-align:center; padding: var(--space-lg,18px) var(--space-md,14px); color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); }+.wi-empty .ic { font-size:30px; margin-bottom:8px; }+.wi-skel { height:14px; border-radius:6px; background: var(--surface-2,rgba(255,255,255,.05)); animation: wi-sk 1.4s ease-in-out infinite; margin:10px 0; }+.wi-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(0,0,0,.25); border-top-color: currentColor; border-radius:50%; animation: wi-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }+.wi-err { background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); }+@keyframes wi-rot { to { transform: rotate(360deg); } }+@keyframes wi-sk { 0%,100%{opacity:.4} 50%{opacity:.8} }+@keyframes wi-pop { from { opacity:0; transform: translateY(6px); } to { opacity:1; transform:none; } }+@media (prefers-reduced-motion: reduce) { .wi-skel,.wi-spin,.wi-intent-card { animation:none; transition:none; } }+`;++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = STYLE_ID;+ tag.textContent = STYLE;+ document.head.appendChild(tag);+}++function esc(s) {+ return String(s ?? '').replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c]));+}++async function call(url, { method = 'GET', body = null } = {}) {+ try {+ const opts = { method, credentials: 'include', headers: {} };+ if (body != null) { opts.headers['content-type'] = 'application/json'; opts.body = JSON.stringify(body); }+ if (method !== 'GET') { const token = await consumeCsrfToken(); if (token) opts.headers['x-csrf-token'] = token; }+ const r = await fetch(url, opts);+ let j = null; try { j = await r.json(); } catch { /* */ }+ if (!r.ok) return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, data: j?.data ?? null };+ return { ok: true, status: r.status, data: j?.data ?? j };+ } catch (err) {+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };+ }+}++// Real voice: server TTS (the agent's voice via the platform synth) first,+// browser speech as the offline fallback so a readback always speaks.+async function speak(agentId, text) {+ try {+ const r = await fetch('/api/tts/speak', {+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ text: text.slice(0, 600), agent_id: agentId }),+ }).catch(() => null);+ if (r && r.ok && (r.headers.get('content-type') || '').startsWith('audio')) {+ const buf = await r.arrayBuffer();+ const audio = new Audio(URL.createObjectURL(new Blob([buf], { type: r.headers.get('content-type') })));+ await audio.play();+ return;+ }+ } catch { /* fall through */ }+ try {+ if (typeof speechSynthesis !== 'undefined') {+ const u = new SpeechSynthesisUtterance(text.slice(0, 600));+ speechSynthesis.cancel();+ speechSynthesis.speak(u);+ }+ } catch { /* no voice available */ }+}++registerWalletTab({+ id: 'intents',+ label: 'Intents',+ order: 50,+ ownerOnly: true,+ mount({ panel, ctx }) {+ injectStyle();+ const base = (sub = '') => `/api/agents/${ctx.agentId}/intents${sub ? '/' + sub : ''}?network=${ctx.getNetwork()}`;++ let destroyed = false;+ const state = {+ loading: true, error: null,+ intents: [], summary: null,+ composer: '', compiling: false, draft: null, clarify: null, publishTrait: false,+ copilot: [], asking: false,+ };++ async function load() {+ state.loading = true; render();+ const res = await call(base());+ if (destroyed) return;+ state.loading = false;+ if (!res.ok) { state.error = res.message; }+ else { state.error = null; state.intents = res.data.intents || []; state.summary = res.data.summary || null; }+ render();+ }++ // ── renderers ──────────────────────────────────────────────────────────────+ function render() {+ if (destroyed) return;+ if (state.loading) {+ panel.innerHTML = `<div class="wi-wrap"><div class="wi-card"><div class="wi-skel" style="width:42%"></div><div class="wi-skel"></div><div class="wi-skel" style="width:75%"></div></div><div class="wi-card"><div class="wi-skel" style="width:30%"></div><div class="wi-skel"></div></div></div>`;+ return;+ }+ if (state.error) {+ panel.innerHTML = `<div class="wi-wrap"><div class="wi-err">Couldn’t load your intents: ${esc(state.error)}</div><div class="wi-actions"><button class="wi-btn" id="wi-retry">Retry</button></div></div>`;+ panel.querySelector('#wi-retry')?.addEventListener('click', load);+ return;+ }+ panel.innerHTML = `<div class="wi-wrap">${renderHero()}${renderComposer()}${renderList()}${renderCopilot()}</div>`;+ wire();+ const log = panel.querySelector('.wi-copilot .log'); if (log) log.scrollTop = log.scrollHeight;+ }++ function renderHero() {+ const s = state.summary || {};+ const frozen = s.frozen+ ? `<div class="wi-frozen"><span>🧊 Wallet is frozen — every autonomous spend is paused until you unfreeze it under Limits.</span></div>`+ : '';+ return `<div class="wi-hero">+ <div class="wi-hero-top">+ <h2 class="wi-title">Wallet intents<small>Tell your wallet what to do — it does it for real, inside your guardrails.</small></h2>+ </div>+ <div class="wi-stats">+ <div class="wi-stat"><div class="l">Active</div><div class="n">${s.enabled ?? 0} / ${s.count ?? 0}</div></div>+ <div class="wi-stat"><div class="l">Balance</div><div class="n">${s.balance_sol == null ? '—' : formatSol(s.balance_sol) + ' SOL'}</div></div>+ <div class="wi-stat"><div class="l">Lifetime moved</div><div class="n">${formatUsd(s.lifetime_usd || 0)}</div></div>+ <div class="wi-stat"><div class="l">Fires</div><div class="n">${s.lifetime_fires || 0}</div></div>+ </div>+ ${frozen}+ </div>`;+ }++ function renderComposer() {+ const draft = state.draft;+ const clar = state.clarify;+ return `<div class="wi-card">+ <h3>+ New rule — describe it</h3>+ <p class="sub">Plain language. I’ll compile it into an exact, bounded rule you confirm before anything runs.</p>+ <div class="wi-compose">+ <textarea class="wi-ta" id="wi-src" placeholder="e.g. Tip back anyone who tips me more than 0.1 SOL, half of what they sent.">${esc(state.composer)}</textarea>+ <button class="wi-btn primary" id="wi-compile" ${state.compiling ? 'disabled' : ''}>${state.compiling ? '<span class="wi-spin"></span>Reading…' : 'Compile'}</button>+ </div>+ <div class="wi-egs">${TEMPLATES.map((t, i) => `<button class="wi-eg" data-tpl="${i}">${esc(t.label)}</button>`).join('')}</div>+ ${clar ? `<div class="wi-clarify">🤔 ${esc(clar)}</div>` : ''}+ ${draft ? renderIntentCard(draft) : ''}+ </div>`;+ }++ function renderIntentCard(d) {+ const trig = d.intent.trigger, act = d.intent.action, lim = d.intent.limits || {};+ const chips = [];+ chips.push(`<span class="wi-chip accent">${TRIGGER_ICON[trig.type] || '•'} ${esc(labelTrigger(trig.type))}</span>`);+ chips.push(`<span class="wi-chip accent">${ACTION_ICON[act.type] || '•'} ${esc(act.type.replace('_', ' '))}</span>`);+ if (lim.per_action_usd != null) chips.push(`<span class="wi-chip">≤ $${esc(lim.per_action_usd)}/action</span>`);+ if (lim.daily_usd != null) chips.push(`<span class="wi-chip">≤ $${esc(lim.daily_usd)}/day</span>`);+ if (lim.total_usd != null) chips.push(`<span class="wi-chip">≤ $${esc(lim.total_usd)} total</span>`);+ const sim = d.simulation?.lines?.length+ ? `<div class="wi-sim"><div class="h">Dry run</div>${d.simulation.lines.map((l) => `<p>${esc(l)}</p>`).join('')}</div>` : '';+ const advertisable = trig.type === 'on_tip_received' || act.type === 'split_income' || (trig.type === 'on_launch_matching');+ return `<div class="wi-intent-card">+ <div class="wi-intent-head">+ <span class="wi-intent-ic">${TRIGGER_ICON[trig.type] || '✨'}</span>+ <div class="wi-readback">${esc(d.readback || d.intent.title)}+ <button class="wi-bubble-spk spk" id="wi-speak-draft" title="Hear it" style="background:none;border:none;cursor:pointer;color:inherit;opacity:.6;margin-left:6px">🔊</button>+ </div>+ </div>+ <div class="wi-meta">${chips.join('')}</div>+ ${sim}+ ${advertisable ? `<label class="wi-pub"><input type="checkbox" id="wi-pub" ${state.publishTrait ? 'checked' : ''}/> Advertise this behavior on my public profile (never the rule or caps)</label>` : ''}+ <div class="wi-actions">+ <button class="wi-btn primary" id="wi-arm">Confirm & arm</button>+ <button class="wi-btn ghost" id="wi-edit">Edit wording</button>+ <button class="wi-btn ghost" id="wi-cancel">Cancel</button>+ </div>+ </div>`;+ }++ function renderList() {+ if (!state.intents.length) {+ return `<div class="wi-card"><div class="wi-empty"><div class="ic">🪄</div>No intents yet.<br/>Describe a rule above, or start from a template.</div></div>`;+ }+ return `<div class="wi-card">+ <h3>Your rules</h3>+ <p class="sub">Each runs automatically on its trigger — every action real, gated by your spend policy, logged with a receipt.</p>+ <ul class="wi-rules">${state.intents.map(renderRule).join('')}</ul>+ </div>`;+ }++ function renderRule(it) {+ const st = it.stats || {};+ const tone = STATUS_TONE[st.last_status] || 'muted';+ const sig = st.last_signature;+ const explorer = sig ? explorerTxUrl(sig, ctx.getNetwork()) : null;+ const fired = st.last_fired_at ? new Date(st.last_fired_at).toLocaleString() : null;+ const statusPill = st.last_status ? `<span class="wi-pill ${tone}">${esc(String(st.last_status).replace('_', ' '))}</span>` : '';+ const foot = [];+ if (fired) foot.push(`last ${esc(timeAgo(st.last_fired_at))}`);+ foot.push(`${st.fire_count || 0} fire${st.fire_count === 1 ? '' : 's'}`);+ if (st.spent_usd) foot.push(`${formatUsd(st.spent_usd)} moved`);+ if (st.last_note) foot.push(esc(String(st.last_note).slice(0, 80)));+ if (explorer) foot.push(`<a href="${esc(explorer)}" target="_blank" rel="noopener">receipt ↗</a>`);+ return `<li class="wi-rule" data-off="${it.enabled ? 'false' : 'true'}" data-id="${esc(it.id)}">+ <div class="wi-rule-top">+ <span class="wi-rule-ic">${TRIGGER_ICON[it.trigger.type] || '•'}</span>+ <div class="wi-rule-body">+ <div class="wi-rule-ttl">${esc(it.title)} ${it.public_trait ? '<span class="wi-chip" title="advertised on your public profile">public</span>' : ''}</div>+ <div class="wi-rule-desc">${esc(it.readback || '')}</div>+ <div class="wi-rule-foot">${statusPill}${foot.map((f) => `<span>${f}</span>`).join('')}</div>+ </div>+ <div class="wi-rule-ctl">+ <label class="wi-sw" title="${it.enabled ? 'Armed' : 'Paused'}"><input type="checkbox" data-toggle="${esc(it.id)}" ${it.enabled ? 'checked' : ''}/><span class="track"></span><span class="thumb"></span></label>+ </div>+ </div>+ <div class="wi-row-actions">+ <button class="wi-btn ghost sm" data-test="${esc(it.id)}">Test now</button>+ <button class="wi-btn danger sm" data-del="${esc(it.id)}">Delete</button>+ </div>+ </li>`;+ }++ function renderCopilot() {+ const log = state.copilot.map((m) => m.role === 'user'+ ? `<div class="wi-bubble user">${esc(m.text)}</div>`+ : `<div class="wi-bubble bot">${esc(m.text)}<button class="spk" data-speak="${esc(m.text).slice(0, 0)}" data-i="${m.i}" title="Hear it">🔊</button></div>`).join('');+ return `<div class="wi-card wi-copilot">+ <h3>Ask your wallet</h3>+ <p class="sub">“How am I doing?” · “What did my rules do this week?” — answered from your real balance + ledger. Never moves funds.</p>+ <div class="log">${log}</div>+ <div class="wi-compose">+ <textarea class="wi-ta" id="wi-ask" style="min-height:42px" placeholder="How am I doing?"></textarea>+ <button class="wi-btn" id="wi-ask-btn" ${state.asking ? 'disabled' : ''}>${state.asking ? '<span class="wi-spin"></span>' : 'Ask'}</button>+ </div>+ </div>`;+ }++ // ── wiring ─────────────────────────────────────────────────────────────────+ function wire() {+ const srcEl = panel.querySelector('#wi-src');+ srcEl?.addEventListener('input', (e) => { state.composer = e.target.value; });+ panel.querySelectorAll('[data-tpl]').forEach((b) => b.addEventListener('click', () => {+ const t = TEMPLATES[Number(b.dataset.tpl)]; if (!t) return;+ state.composer = t.text; const el = panel.querySelector('#wi-src'); if (el) { el.value = t.text; el.focus(); }+ }));+ panel.querySelector('#wi-compile')?.addEventListener('click', onCompile);+ panel.querySelector('#wi-arm')?.addEventListener('click', onArm);+ panel.querySelector('#wi-edit')?.addEventListener('click', () => { state.draft = null; state.clarify = null; render(); panel.querySelector('#wi-src')?.focus(); });+ panel.querySelector('#wi-cancel')?.addEventListener('click', () => { state.draft = null; state.clarify = null; state.composer = ''; render(); });+ panel.querySelector('#wi-pub')?.addEventListener('change', (e) => { state.publishTrait = e.target.checked; });+ panel.querySelector('#wi-speak-draft')?.addEventListener('click', () => { if (state.draft) speak(ctx.agentId, state.draft.readback || ''); });++ panel.querySelectorAll('[data-toggle]').forEach((el) => el.addEventListener('change', () => onToggle(el.dataset.toggle, el.checked)));+ panel.querySelectorAll('[data-test]').forEach((b) => b.addEventListener('click', () => onTest(b.dataset.test)));+ panel.querySelectorAll('[data-del]').forEach((b) => b.addEventListener('click', () => onDelete(b.dataset.del)));++ panel.querySelector('#wi-ask-btn')?.addEventListener('click', onAsk);+ panel.querySelector('#wi-ask')?.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) onAsk(); });+ panel.querySelectorAll('[data-speak]').forEach((b) => b.addEventListener('click', () => {+ const m = state.copilot.find((x) => String(x.i) === b.dataset.i); if (m) speak(ctx.agentId, m.text);+ }));+ }++ async function onCompile() {+ const text = (panel.querySelector('#wi-src')?.value || '').trim();+ if (!text) { ctx.toast('Describe a rule first.'); return; }+ state.compiling = true; state.composer = text; state.clarify = null; render();+ const res = await call(base('compile'), { method: 'POST', body: { text } });+ if (destroyed) return;+ state.compiling = false;+ if (!res.ok) { ctx.toast(res.message || 'Could not compile'); render(); return; }+ const d = res.data;+ if (!d.ok) {+ if (d.error === 'clarify' || d.clarify) { state.clarify = d.clarify || d.message; state.draft = null; }+ else { ctx.toast(d.message || 'I couldn’t turn that into a rule'); state.draft = null; }+ render(); return;+ }+ state.draft = d; state.clarify = null; state.publishTrait = false; render();+ }++ async function onArm() {+ const d = state.draft; if (!d) return;+ // A SOL destination that's still a name shouldn't reach arm — the server resolved it at compile.+ const dest = d.intent.action?.destination;+ if (dest && !SOL_ADDR_RE.test(dest) && !d.intent.action?.to_tipper) { ctx.toast('That destination didn’t resolve — edit the rule.'); return; }+ const btn = panel.querySelector('#wi-arm'); if (btn) { btn.disabled = true; btn.innerHTML = '<span class="wi-spin"></span>Arming…'; }+ const res = await call(base(), { method: 'POST', body: { intent: d.intent, source_text: state.composer, public_trait: state.publishTrait, } });+ if (destroyed) return;+ if (!res.ok) { ctx.toast(res.message || 'Could not arm'); render(); return; }+ state.draft = null; state.composer = ''; state.clarify = null;+ ctx.toast('Armed — your wallet will act on it for real.');+ await load();+ }++ async function onToggle(id, enabled) {+ const res = await call(`${base().split('?')[0]}/${id}?network=${ctx.getNetwork()}`, { method: 'PUT', body: { enabled } });+ if (destroyed) return;+ if (!res.ok) { ctx.toast(res.message || 'Update failed'); await load(); return; }+ ctx.toast(enabled ? 'Armed.' : 'Paused.');+ await load();+ }++ async function onTest(id) {+ ctx.toast('Simulating…');+ const res = await call(base('run'), { method: 'POST', body: { intent_id: id, dry_run: true } });+ if (destroyed) return;+ if (!res.ok) { ctx.toast(res.message || 'Test failed'); return; }+ const r = (res.data.results || [])[0];+ if (r) ctx.toast(r.note || `Would ${r.status}.`, 3600);+ else ctx.toast('Nothing would happen right now.');+ }++ async function onDelete(id) {+ const it = state.intents.find((x) => x.id === id);+ if (it && !window.confirm(`Delete “${it.title}”? This can’t be undone.`)) return;+ const res = await call(`${base().split('?')[0]}/${id}?network=${ctx.getNetwork()}`, { method: 'DELETE' });+ if (destroyed) return;+ if (!res.ok) { ctx.toast(res.message || 'Delete failed'); return; }+ ctx.toast('Deleted.');+ await load();+ }++ let askIdx = 0;+ async function onAsk() {+ const el = panel.querySelector('#wi-ask');+ const q = (el?.value || '').trim(); if (!q) return;+ state.copilot.push({ role: 'user', text: q, i: askIdx++ });+ state.asking = true; render();+ const res = await call(base('copilot'), { method: 'POST', body: { message: q } });+ if (destroyed) return;+ state.asking = false;+ const reply = res.ok ? (res.data.reply || 'I’m not sure right now.') : (res.message || 'I couldn’t reach the ledger just now.');+ state.copilot.push({ role: 'bot', text: reply, i: askIdx++ });+ render();+ }++ load();+ return { destroy() { destroyed = true; } };+ },+});++// Local helpers (kept in-file so the tab is a single drop-in).+function labelTrigger(t) {+ return {+ 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',+ }[t] || t;+}+function timeAgo(iso) {+ if (!iso) return '';+ const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);+ if (s < 60) return 'just now';+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ return `${Math.floor(s / 86400)}d ago`;+}diff --git a/src/avatar-embed.js b/src/avatar-embed.jsindex c59dbd3d0..4c30961b0 100644--- a/src/avatar-embed.js+++ b/src/avatar-embed.js@@ -210,6 +210,19 @@ async function main() {const a2fPlayer = new A2FPlayer();a2fPlayer.attach(root);let a2fAudio = null; // the <audio> element currently driven by an A2F track+ // One-time capability probe so we never do the (non-trivial) decode→resample+ // work on deployments where the A2F lane is unconfigured — there it stays pure+ // amplitude lipsync with zero added cost.+ let a2fProbe = null;+ const a2fAvailable = () => {+ if (!a2fProbe) {+ a2fProbe = fetch('/api/a2f', { method: 'GET' })+ .then((r) => (r.ok ? r.json() : null))+ .then((c) => !!(c && c.configured))+ .catch(() => false);+ }+ return a2fProbe;+ };// 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 = [];@@ -369,22 +382,90 @@ async function main() {});};+ // Decode any audio URL (mp3/wav/opus) to 16 kHz mono 16-bit PCM, base64'd —+ // the format Audio2Face-3D expects. Done in-browser via the Web Audio decoder+ // the page already uses for playback, so the embed's A2F path is codec-agnostic+ // and we never round-trip the bytes through a server transcode.+ const fetchA2FTrack = async (url) => {+ const resp = await fetch(url);+ if (!resp.ok) return null;+ const encoded = await resp.arrayBuffer();+ const decodeCtx = ensureAudio();+ const decoded = await decodeCtx.decodeAudioData(encoded.slice(0));+ // Downmix to mono.+ const chs = decoded.numberOfChannels;+ const mono = new Float32Array(decoded.length);+ for (let c = 0; c < chs; c++) {+ const data = decoded.getChannelData(c);+ for (let i = 0; i < data.length; i++) mono[i] += data[i] / chs;+ }+ // Resample to 16 kHz and convert to s16 little-endian.+ const ratio = 16000 / decoded.sampleRate;+ const outLen = Math.max(1, Math.floor(mono.length * ratio));+ const pcm = new Int16Array(outLen);+ for (let i = 0; i < outLen; i++) {+ const src = i / ratio;+ const i0 = Math.floor(src);+ const i1 = Math.min(i0 + 1, mono.length - 1);+ const s = mono[i0] + (mono[i1] - mono[i0]) * (src - i0);+ pcm[i] = Math.max(-32768, Math.min(32767, Math.round(s * 32767)));+ }+ const bytes = new Uint8Array(pcm.buffer);+ let bin = '';+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);+ const r = await fetch('/api/a2f', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ audio: btoa(bin), format: 'pcm', sampleRate: 16000 }),+ });+ if (!r.ok) return null;+ const data = await r.json();+ return data?.animation?.frames?.length ? data.animation : null;+ };+const playAudio = async (url) => {const ctx = ensureAudio();const audio = new Audio();audio.crossOrigin = 'anonymous';audio.src = url;++ // Kick off the A2F request in parallel with playback. Amplitude lipsync+ // starts immediately (zero latency); if a real blendshape track comes back+ // before the clip ends and the rig can show it, we upgrade seamlessly.+ let a2fUpgraded = false;+ const a2fPromise = a2fEnabled+ ? a2fAvailable()+ .then((ok) => (ok ? fetchA2FTrack(url) : null))+ .then((track) => {+ if (!track || audio.ended) return;+ a2fPlayer.setTrack(track);+ if (!a2fPlayer.hasCoverage()) return;+ // Hand the face over from amplitude → A2F track.+ activeLipsync?.stop();+ activeLipsync = null;+ a2fAudio = audio;+ a2fUpgraded = true;+ postToParent({ type: 'v1.avatar.speak:a2f', frames: track.frameCount, fps: track.fps });+ })+ .catch(() => {})+ : Promise.resolve();+await audio.play();- const { analyser } = tapAudioElement(audio, ctx);- activeLipsync = new LipsyncDriver({ analyser, target: mouthTarget });- activeLipsync.start();+ // Only run amplitude lipsync until/unless A2F takes over.+ if (!a2fUpgraded) {+ const { analyser } = tapAudioElement(audio, ctx);+ activeLipsync = new LipsyncDriver({ analyser, target: mouthTarget });+ activeLipsync.start();+ }postToParent({ type: 'v1.avatar.speak:start', source: 'audio' });await new Promise((resolve) => {audio.onended = resolve;audio.onerror = resolve;});- activeLipsync.stop();+ await a2fPromise;+ activeLipsync?.stop();activeLipsync = null;+ if (a2fAudio === audio) { a2fAudio = null; a2fPlayer.reset(); }postToParent({ type: 'v1.avatar.speak:end' });};diff --git a/src/cosmos.js b/src/cosmos.jsindex 93d393865..bc8d8f714 100644--- a/src/cosmos.js+++ b/src/cosmos.js@@ -232,10 +232,10 @@ async function generate() {);}- if (res.status === 503 || data?.error === 'unconfigured') {+ if (res.status === 503 || res.status === 404 || 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.',+ 'NVIDIA Cosmos isn’t available on this environment yet. Your avatar still shines on the living backdrop above — check back soon for generated worlds.',{ unconfigured: true },);}diff --git a/src/shared/agent-patronage.js b/src/shared/agent-patronage.jsindex d9a030776..83c061507 100644--- a/src/shared/agent-patronage.js+++ b/src/shared/agent-patronage.js@@ -150,6 +150,16 @@ async function signChallenge(provider, message) {return bytesToB64(res?.signature ?? res);}+// A ready-to-edit starter ladder for a brand-new owner — example perk content they+// can keep or rewrite, so the editor opens full instead of empty.+function starterLadder() {+ return [+ { perk_type: 'greeting', threshold_usd: 5, title: 'A warm welcome', description: 'A personal greeting your agent gives supporters in chat.', payload: { body: 'Always greet this supporter warmly by name and thank them for backing me — they helped make me possible.' }, is_active: true },+ { perk_type: 'lore', threshold_usd: 25, title: 'Origin story', description: 'Hidden backstory only patrons can read.', payload: { body: 'The secret behind how I came to be — write the lore your patrons get to unlock here.' }, is_active: true },+ { perk_type: 'badge', threshold_usd: 100, title: 'Inner circle', description: 'A badge that marks my closest supporters on the wall.', payload: { label: 'Inner Circle' }, is_active: true },+ ];+}+export function mountPatronagePanel({ mount, agent, isOwner = false }) {if (!mount) return { destroy() {} };ensureStyles();@@ -429,7 +439,9 @@ export function mountPatronagePanel({ mount, agent, isOwner = false }) {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 });+ // First-time owners get a sensible starter ladder to edit, not a blank row —+ // real, editable config they can ship in one tap (greeting → lore → badge).+ if (!editPerks.length) editPerks = starterLadder();editing = true;render();});diff --git a/src/shared/agent-wallet-chip.js b/src/shared/agent-wallet-chip.jsindex fbcdf2ae9..c47a60422 100644--- a/src/shared/agent-wallet-chip.js+++ b/src/shared/agent-wallet-chip.js@@ -42,6 +42,7 @@import { computeRarity } from '../solana/vanity/rarity.js';import { formatWalletUsd, shortAddress } from './wallet-format.js';+import { tierForUsd, computeWalletVisual } from './wallet-networth.js';const STYLE_ID = 'tws-agent-wallet-chip-styles';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -244,6 +245,9 @@ export function ensureWalletChipStyles() {padding:1px 5px;border-radius:999px;line-height:1.4;}.twc-bal{display:inline-flex;align-items:center;gap:4px;font-family:var(--font-mono,ui-monospace,Menlo,monospace);font-weight:700;font-size:11px;color:var(--ink-bright,#fff);border-left:1px solid var(--wallet-stroke,rgba(139,92,246,.3));padding-left:7px;}+.twc-tierdot{width:6px;height:6px;border-radius:50%;flex:none;background:var(--twc-tier,var(--wallet-accent,#c4b5fd));+ box-shadow:0 0 5px var(--twc-tier,var(--wallet-glow,rgba(139,92,246,.45)));}+@media (prefers-reduced-motion: reduce){.twc-tierdot{box-shadow:none;}}.twc-bal-sk{display:inline-block;width:30px;height:9px;border-radius:3px;background:linear-gradient(90deg,rgba(255,255,255,.06),rgba(255,255,255,.16),rgba(255,255,255,.06));background-size:200% 100%;animation:twc-sk 1.1s ease-in-out infinite;}@@ -689,7 +693,16 @@ function applyHydration(agentId, entry) {const pct = entry.pnl?.changePct;const dir = pct == null ? null : pct > 0.05 ? 'up' : pct < -0.05 ? 'down' : 'flat';const chg = dir ? `<span class="twc-chg" data-dir="${dir}">${esc(formatPct(pct))}</span>` : '';- slot.innerHTML = `<span class="twc-usd">${esc(usdLabel)}</span>${chg}`;+ // Embodied finance in 2D: a tier dot so the chip reads at the SAME wealth+ // tier as the agent's 3D aura everywhere. Derived for free from the USD the+ // chip already fetched (pure tierForUsd) — no extra request. Dormant ($0)+ // shows no dot, so an empty wallet stays clean, never a fake mark.+ const tier = tierForUsd(entry.usd);+ const dot = tier.level > 0+ ? `<span class="twc-tierdot" style="--twc-tier:${esc(computeWalletVisual({ usdTotal: entry.usd, mix: { sol: 1 }, hasThree: false }).accent)}" title="${esc(tier.label)} tier"></span>`+ : '';+ node.dataset.tier = tier.key;+ slot.innerHTML = `${dot}<span class="twc-usd">${esc(usdLabel)}</span>${chg}`;slot.setAttribute('aria-label', `Wallet value ${usdLabel}${pct != null ? `, ${formatPct(pct)} over ${entry.pnl?.windowHours || 24} hours` : ''}`);}if (increased) pulseChip(node, entry.usd - prev);diff --git a/tests/strategy-schema.test.js b/tests/strategy-schema.test.jsnew file mode 100644index 000000000..f07fd586f--- /dev/null+++ b/tests/strategy-schema.test.js@@ -0,0 +1,187 @@+/**+ * Strategy Object schema — pure logic tests.+ * Money-adjacent: the config is the leash on an autonomous trader, so every bound,+ * validation rule, entry gate, and exit trigger is pinned. A malformed rule set must+ * never persist, and an entry/exit verdict must be deterministic and explainable.+ */++import { describe, it, expect } from 'vitest';+import {+ normalizeStrategyConfig, validateStrategyConfig, matchesEntry, shouldExit,+ slugifyStrategy, STRATEGY_CONFIG_DEFAULTS,+} from '../api/_lib/strategy-schema.js';++describe('normalizeStrategyConfig', () => {+ it('fills a complete, bounded config from empty input', () => {+ const c = normalizeStrategyConfig({});+ expect(c.network).toBe('mainnet');+ expect(c.entry.trigger).toBe('new_launch');+ expect(c.entry.max_age_minutes).toBe(STRATEGY_CONFIG_DEFAULTS.entry.max_age_minutes);+ expect(c.sizing.amount_sol).toBe(STRATEGY_CONFIG_DEFAULTS.sizing.amount_sol);+ // stop-loss is mandatory → always defaulted; upside exits are optional → null+ // unless explicitly set (validation then requires at least one of them).+ expect(c.exits.stop_loss_pct).toBe(40);+ expect(c.exits.take_profit_pct).toBeNull();+ expect(c.risk.max_concurrent_positions).toBe(STRATEGY_CONFIG_DEFAULTS.risk.max_concurrent_positions);+ });++ it('clamps per-trade size to the hard ceiling and floor', () => {+ expect(normalizeStrategyConfig({ sizing: { amount_sol: 999 } }).sizing.amount_sol).toBe(100);+ expect(normalizeStrategyConfig({ sizing: { amount_sol: 0 } }).sizing.amount_sol).toBe(0.0001);+ expect(normalizeStrategyConfig({ sizing: { amount_sol: -5 } }).sizing.amount_sol).toBe(0.0001);+ });++ it('clamps stop-loss into (0,99] and keeps it mandatory', () => {+ expect(normalizeStrategyConfig({ exits: { stop_loss_pct: 500 } }).exits.stop_loss_pct).toBe(99);+ // invalid → default, never absent+ expect(normalizeStrategyConfig({ exits: { stop_loss_pct: 'nope' } }).exits.stop_loss_pct).toBe(40);+ });++ it('coerces blank optional numbers to null, not 0', () => {+ const e = normalizeStrategyConfig({ entry: { min_liquidity_sol: '', max_creator_launches: null } }).entry;+ expect(e.min_liquidity_sol).toBeNull();+ expect(e.max_creator_launches).toBeNull();+ });++ it('rounds integer fields', () => {+ expect(normalizeStrategyConfig({ entry: { max_age_minutes: 12.7 } }).entry.max_age_minutes).toBe(13);+ expect(normalizeStrategyConfig({ risk: { max_concurrent_positions: 3.9 } }).risk.max_concurrent_positions).toBe(4);+ });++ it('only accepts known triggers and networks', () => {+ expect(normalizeStrategyConfig({ entry: { trigger: 'evil' } }).entry.trigger).toBe('new_launch');+ expect(normalizeStrategyConfig({ network: 'fakenet' }).network).toBe('mainnet');+ expect(normalizeStrategyConfig({ network: 'devnet' }).network).toBe('devnet');+ });+});++describe('validateStrategyConfig', () => {+ it('accepts a config with a take-profit and stop-loss', () => {+ const { valid, errors } = validateStrategyConfig({ exits: { take_profit_pct: 100, stop_loss_pct: 40 } });+ expect(valid).toBe(true);+ expect(errors).toEqual([]);+ });++ it('rejects an empty config — every strategy must define an upside exit', () => {+ const { valid, errors } = validateStrategyConfig({});+ expect(valid).toBe(false);+ expect(errors.some((e) => e.field === 'exits')).toBe(true);+ });++ it('requires at least one upside exit', () => {+ const { valid, errors } = validateStrategyConfig({ 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('rejects min market cap above max', () => {+ const { valid, errors } = validateStrategyConfig({ entry: { min_market_cap_usd: 1000, max_market_cap_usd: 100 } });+ expect(valid).toBe(false);+ expect(errors.some((e) => e.field === 'entry.max_market_cap_usd')).toBe(true);+ });++ it('always returns a persist-safe normalized config even when invalid', () => {+ const { config } = validateStrategyConfig({ sizing: { amount_sol: 'xx' } });+ expect(config.sizing.amount_sol).toBe(STRATEGY_CONFIG_DEFAULTS.sizing.amount_sol);+ });+});++describe('matchesEntry', () => {+ const now = 1_000_000_000_000;+ const base = {+ mint: 'THREEsynthetic1111111111111111111111111111',+ created_at: now - 5 * 60_000, // 5 minutes old+ market_cap_usd: 50_000,+ liquidity_sol: 12,+ creator_launches: 1,+ creator_graduated: 1,+ twitter: 'x', telegram: null, website: null,+ is_usdc_pair: false,+ };++ it('passes a fresh launch that clears every gate', () => {+ const c = normalizeStrategyConfig({ entry: { max_age_minutes: 60, min_liquidity_sol: 5, require_socials: true } });+ const r = matchesEntry(c, base, now);+ expect(r.pass).toBe(true);+ expect(r.reasons).toContain('has_socials');+ });++ it('rejects a launch older than the age gate', () => {+ const c = normalizeStrategyConfig({ entry: { max_age_minutes: 1 } });+ const r = matchesEntry(c, base, now);+ expect(r.pass).toBe(false);+ expect(r.reasons[0]).toMatch(/too_old/);+ });++ it('rejects a USDC-quoted pair when SOL quote is required', () => {+ const c = normalizeStrategyConfig({ entry: { require_sol_quote: true } });+ const r = matchesEntry(c, { ...base, is_usdc_pair: true }, now);+ expect(r.pass).toBe(false);+ expect(r.reasons).toContain('quote_not_sol');+ });++ it('rejects below-min liquidity and above-max market cap', () => {+ expect(matchesEntry(normalizeStrategyConfig({ entry: { min_liquidity_sol: 100 } }), base, now).pass).toBe(false);+ expect(matchesEntry(normalizeStrategyConfig({ entry: { max_market_cap_usd: 1000 } }), base, now).pass).toBe(false);+ });++ it('rejects serial creators and missing socials', () => {+ expect(matchesEntry(normalizeStrategyConfig({ entry: { max_creator_launches: 0 } }), { ...base, creator_launches: 9 }, now).pass).toBe(false);+ expect(matchesEntry(normalizeStrategyConfig({ entry: { require_socials: true } }), { ...base, twitter: null, telegram: null, website: null }, now).pass).toBe(false);+ });++ it('never passes a launch with no mint', () => {+ expect(matchesEntry(normalizeStrategyConfig({}), { mint: null }, now).pass).toBe(false);+ });++ it('treats a future/bad timestamp as fresh (no negative-age reject)', () => {+ const r = matchesEntry(normalizeStrategyConfig({ entry: { max_age_minutes: 10 } }), { ...base, created_at: now + 60_000 }, now);+ expect(r.pass).toBe(true);+ });+});++describe('shouldExit', () => {+ const now = 2_000_000_000_000;+ const cfg = (over) => normalizeStrategyConfig({ exits: { take_profit_pct: 100, stop_loss_pct: 40, ...over } });+ const pos = { entry_lamports: 1_000_000_000, peak_value_lamports: 1_000_000_000, opened_at: now - 60_000 };++ it('exits on take-profit at +100% (2x)', () => {+ const r = shouldExit(cfg(), pos, 2_000_000_000, now);+ expect(r).toEqual({ exit: true, reason: 'take_profit' });+ });++ it('exits on stop-loss at -40%', () => {+ const r = shouldExit(cfg(), pos, 600_000_000, now);+ expect(r).toEqual({ exit: true, reason: 'stop_loss' });+ });++ it('exits on a trailing stop from the peak (no take-profit set)', () => {+ const p = { ...pos, peak_value_lamports: 3_000_000_000 };+ // take_profit null so the +100% move doesn't pre-empt the trailing check+ const r = shouldExit(cfg({ take_profit_pct: null, trailing_stop_pct: 20 }), p, 2_000_000_000, now); // 33% off peak+ expect(r).toEqual({ exit: true, reason: 'trailing_stop' });+ });++ it('exits on max-hold timeout even with no entry basis', () => {+ const p = { entry_lamports: null, peak_value_lamports: null, opened_at: now - 120 * 60_000 };+ const r = shouldExit(cfg({ max_hold_minutes: 60 }), p, 0, now);+ expect(r).toEqual({ exit: true, reason: 'timeout' });+ });++ it('holds inside the band', () => {+ expect(shouldExit(cfg(), pos, 1_200_000_000, now).exit).toBe(false);+ });++ it('does not act on price with no real entry basis', () => {+ const p = { entry_lamports: 0, peak_value_lamports: 0, opened_at: now };+ expect(shouldExit(cfg(), p, 5_000_000_000, now).exit).toBe(false);+ });+});++describe('slugifyStrategy', () => {+ it('produces url-safe stable slugs', () => {+ expect(slugifyStrategy('Fresh-Launch Sniper!!')).toBe('fresh-launch-sniper');+ expect(slugifyStrategy(' ')).toBe('strategy');+ expect(slugifyStrategy('a'.repeat(80)).length).toBeLessThanOrEqual(48);+ });+});diff --git a/tests/wallet-intents.test.js b/tests/wallet-intents.test.jsnew file mode 100644index 000000000..717118516--- /dev/null+++ b/tests/wallet-intents.test.js@@ -0,0 +1,143 @@+// Unit tests for the Wallet Intents engine's safety-critical pure logic:+// api/_lib/wallet-intents.js → normalizeIntent + resolveAssetToken + describeIntent.+//+// normalizeIntent is the boundary between a fuzzy LLM/form input and a real,+// enforceable standing money rule. The invariants it must never break:+// - only the supported triggers/actions are accepted; anything else is rejected,+// never coerced into a fake capability;+// - a rule missing a required field (amount, destination, threshold, mint…) is+// rejected with a precise reason — money never arms on a guess;+// - amounts/percentages/slippage are clamped to sane bounds;+// - $THREE is the only coin resolved by name; a base58 mint is passed through.+// The LLM HTTP path, the cron, signing, and DB are NOT exercised here — only the+// deterministic validation. The heavy server-only deps are stubbed so the import+// is cheap and side-effect-free.++import { describe, it, expect, vi } from 'vitest';++const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const ADDR = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';++vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));+vi.mock('../api/_lib/avatar-wallet.js', () => ({+ solUsdPrice: vi.fn(async () => 150), sendSol: vi.fn(async () => 'sig'), explorerTxUrl: vi.fn(() => 'https://x'),+}));+vi.mock('../api/_lib/agent-pumpfun.js', () => ({ solanaConnection: vi.fn(() => ({})) }));+vi.mock('../api/_lib/agent-wallet.js', () => ({+ getSolanaAddressBalances: vi.fn(async () => ({ sol: 1 })), recoverSolanaAgentKeypair: vi.fn(),+}));+vi.mock('../api/_lib/agent-trade-guards.js', () => ({+ getSpendLimits: vi.fn(() => ({})), getTradeLimits: vi.fn(() => ({})), setSpendLimits: vi.fn(),+ enforceSpendLimit: vi.fn(), SpendLimitError: class extends Error {}, recordCustodyEvent: vi.fn(),+ updateCustodyEvent: vi.fn(), validateSolanaAddress: vi.fn((a) => ({ valid: true, base58: a })),+ lamportsToUsd: vi.fn(async () => 1), SOL_FEE_HEADROOM_LAMPORTS: 3000000n,+}));+vi.mock('../api/_lib/networth-model.js', () => ({ THREE_MINT: THREE }));+vi.mock('../src/solana/sns.js', () => ({ resolveSolanaRecipient: vi.fn(async () => ({ address: null })) }));+vi.mock('../api/_lib/pump-launch-feed.js', () => ({ recentPumpLaunches: vi.fn(async () => []), enrichCreatorStats: vi.fn(async (l) => l) }));+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));++const { normalizeIntent, resolveAssetToken, describeIntent, INTENT_TRIGGERS, INTENT_ACTIONS } =+ await import('../api/_lib/wallet-intents.js');++describe('resolveAssetToken', () => {+ it('resolves $THREE / three by name to the canonical mint, never another coin', () => {+ expect(resolveAssetToken('$THREE')).toMatchObject({ kind: 'three', mint: THREE });+ expect(resolveAssetToken('three')).toMatchObject({ kind: 'three', mint: THREE });+ });+ it('recognises SOL and USDC', () => {+ expect(resolveAssetToken('SOL').kind).toBe('sol');+ expect(resolveAssetToken('usdc').kind).toBe('usdc');+ });+ it('passes a base58 mint through as runtime input', () => {+ expect(resolveAssetToken(ADDR)).toMatchObject({ kind: 'mint', mint: ADDR });+ });+});++describe('normalizeIntent — trigger/action allowlist', () => {+ it('rejects an unsupported trigger', () => {+ const r = normalizeIntent({ trigger_type: 'on_moon', action_type: 'notify' });+ expect(r.ok).toBe(false);+ expect(r.error).toBe('bad_trigger');+ });+ it('rejects an unsupported action (no fake capabilities)', () => {+ const r = normalizeIntent({ trigger_type: 'on_schedule', action_type: 'launch_coin' });+ expect(r.ok).toBe(false);+ expect(r.error).toBe('bad_action');+ });+ it('every advertised trigger + action constant is non-empty', () => {+ expect(INTENT_TRIGGERS.length).toBeGreaterThan(0);+ expect(INTENT_ACTIONS).toContain('freeze');+ });+});++describe('normalizeIntent — tip-back (the flagship rule)', () => {+ it('accepts "tip back half of what they sent" as a percentage of the tip', () => {+ const r = normalizeIntent({+ trigger_type: 'on_tip_received', trigger_config: { min_sol: 0.1 },+ action_type: 'tip', action_config: { pct: 50, of: 'tip', destination: ADDR },+ readback: 'Tip back half.',+ });+ expect(r.ok).toBe(true);+ expect(r.intent.trigger).toMatchObject({ type: 'on_tip_received', min_sol: 0.1 });+ expect(r.intent.action).toMatchObject({ type: 'tip', pct: 50, of: 'tip' });+ });+ it('clamps a percentage over 100', () => {+ const r = normalizeIntent({ trigger_type: 'on_income', action_type: 'split_income', action_config: { pct: 250, destination: ADDR } });+ expect(r.ok).toBe(true);+ expect(r.intent.action.pct).toBe(100);+ });+});++describe('normalizeIntent — required-field enforcement (no guessing)', () => {+ it('rejects a balance rule with no threshold', () => {+ const r = normalizeIntent({ trigger_type: 'on_balance_below', action_type: 'freeze' });+ expect(r.ok).toBe(false);+ expect(r.error).toBe('needs_threshold');+ });+ it('accepts a balance-floor freeze with a threshold', () => {+ const r = normalizeIntent({ trigger_type: 'on_balance_below', trigger_config: { threshold_sol: 0.05 }, action_type: 'freeze' });+ expect(r.ok).toBe(true);+ expect(r.intent.trigger.threshold_sol).toBe(0.05);+ });+ it('rejects a transfer with no destination', () => {+ const r = normalizeIntent({ trigger_type: 'on_schedule', action_type: 'transfer', action_config: { amount_sol: 1 } });+ expect(r.ok).toBe(false);+ expect(r.error).toBe('needs_destination');+ });+ it('rejects a split with no percentage', () => {+ const r = normalizeIntent({ trigger_type: 'on_income', action_type: 'split_income', action_config: { destination: ADDR } });+ expect(r.ok).toBe(false);+ expect(r.error).toBe('needs_pct');+ });+ it('rejects a launch rule with neither creator nor max market cap', () => {+ const r = normalizeIntent({ trigger_type: 'on_launch_matching', action_type: 'snipe', action_config: { amount_sol: 1 } });+ expect(r.ok).toBe(false);+ expect(r.error).toBe('needs_filter');+ });+});++describe('normalizeIntent — schedule + launch', () => {+ it('defaults a weekly schedule to Friday 13:00 UTC and accepts an explicit weekday', () => {+ const def = normalizeIntent({ trigger_type: 'on_schedule', trigger_config: { cadence: 'weekly' }, action_type: 'withdraw', action_config: { above_sol: 2, destination: ADDR } });+ expect(def.ok).toBe(true);+ expect(def.intent.trigger).toMatchObject({ cadence: 'weekly', weekday: 5, hour: 13 });+ const mon = normalizeIntent({ trigger_type: 'on_schedule', trigger_config: { cadence: 'weekly', weekday: 1, hour: 9 }, action_type: 'withdraw', action_config: { above_sol: 2, destination: ADDR } });+ expect(mon.intent.trigger).toMatchObject({ weekday: 1, hour: 9 });+ });+ it('accepts a snipe rule with a creator + max mcap and clamps slippage', () => {+ const r = normalizeIntent({ trigger_type: 'on_launch_matching', trigger_config: { creator: ADDR, max_mcap_usd: 40000 }, action_type: 'snipe', action_config: { amount_sol: 1, slippage_pct: 99 } });+ expect(r.ok).toBe(true);+ expect(r.intent.trigger).toMatchObject({ creator: ADDR, max_mcap_usd: 40000 });+ expect(r.intent.action.slippage_pct).toBe(50);+ });+});++describe('describeIntent', () => {+ it('produces a human read-back when none was supplied', () => {+ const r = normalizeIntent({ trigger_type: 'on_balance_below', trigger_config: { threshold_sol: 0.05 }, action_type: 'freeze' });+ const text = describeIntent(r.intent);+ expect(text).toMatch(/0.05 SOL/);+ expect(text.toLowerCase()).toMatch(/freeze/);+ });+});