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
Agent money stream, vision endpoint, and strategies page
nirholasb7a29bc93d8b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa1c5a752..2cbee3d43 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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.- **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]`+- **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]`- **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]`@@ -41,6 +42,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`- **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]`- **The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time** — The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct. (`/marketplace`) `[improvement, fix]`- **The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas** — The three avatars that walk and talk over a page got a polish pass focused on the moments before and around them. The corner companion now greets you with a soft loading shimmer instead of an empty box while its 3D body streams in, and the guided tour opens with an honest 'waking your guide' loader — a real readiness cue, never a fake bar — instead of a frozen page. All four 3D surfaces (the corner companion, the full-page walk playground, the drop-in page narrator, and the feature tour) now pause their animation the instant you switch to another tab, and the page narrator also pauses when it scrolls out of view — so a living avatar never quietly burns your laptop battery in a background tab. The narrator's mute button now shows the correct state from the very first frame, the tour's loader always clears cleanly when you exit, and several small resource leaks (timers and drag handlers left running after a companion or narrator was dismissed) are fixed. Reduced-motion preferences are honored throughout. (`/walk`) `[improvement, fix]`- **three.ws opens cleanly inside in-app browsers** — Opening a three.ws link from inside the X (Twitter) app, and other in-app browsers that sandbox local storage, could throw an error before the page finished setting up its language — leaving some visitors on a broken first screen. Language preference now degrades gracefully when storage is blocked instead of failing, so the site loads normally everywhere. We also quieted a class of harmless background network blips (an expired draft model link, a dropped request) that were being logged as errors even though the viewer already shows its designed "couldn't load" card and recovers. `[fix]`diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex cc4af7c8b..67c309653 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -652,6 +652,14 @@ 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 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+ // without Redis in prod.+ visionUser: (userId) =>+ getLimiter('vision:user', { limit: 60, window: '1 h', critical: true }).limit(userId),+ visionIp: (ip) =>+ getLimiter('vision:ip', { limit: 15, window: '1 h', critical: true }).limit(ip),// /brain multi-LLM proxy. Paid flagship models (Claude/GPT-4o) run on the// server keys, so meter per principal: authenticated users get a generous// per-user bucket, anonymous callers a tighter per-IP one. Both critical so adiff --git a/api/agents.js b/api/agents.jsindex fd6929bd4..3580bd289 100644--- a/api/agents.js+++ b/api/agents.js@@ -186,6 +186,42 @@ async function handleList(req, res) {return json(res, 200, { agents: rows.map((row) => decorate(row)) });}+// Mint the agent's custodial EVM + Solana wallets for the initial INSERT.+//+// Minting can fail when the at-rest encryption key is unavailable — in+// production secret-box.js fails CLOSED rather than encrypt custodial secrets+// under the JWT_SECRET fallback (see api/_lib/secret-box.js). That must never+// brick the core product action of creating an agent. The platform already mints+// wallets lazily and idempotently on first use (ensureAgentWallet /+// getOrCreateAgentEvmWallet), so a walletless identity self-heals the next time+// it touches a wallet once the key is configured — exactly how the avatar-agent+// path degrades. On failure we create the agent with a null wallet_address and+// no encrypted keys, and log a warning (never the secret-box internals as an+// unhandled 500). Returns { walletAddress, meta } for the INSERT.+async function mintAgentWalletMeta() {+ try {+ const [wallet, sol] = await Promise.all([+ generateAgentWallet(),+ generateSolanaAgentWallet(),+ ]);+ return {+ walletAddress: wallet.address,+ meta: {+ encrypted_wallet_key: wallet.encrypted_key,+ solana_address: sol.address,+ encrypted_solana_secret: sol.encrypted_secret,+ },+ };+ } catch (err) {+ console.warn(+ '[agents] wallet provisioning deferred — minting failed at create time, ' ++ 'agent will be provisioned lazily on first wallet use:',+ err?.message,+ );+ return { walletAddress: null, meta: {} };+ }+}+// ── Get-or-create default agent ───────────────────────────────────────────async function handleGetOrCreateMe(req, res, auth) {@@ -204,20 +240,15 @@ async function handleGetOrCreateMe(req, res, auth) {`;if (!agent) {- const wallet = await generateAgentWallet();- const sol = await generateSolanaAgentWallet();+ const { walletAddress, meta } = await mintAgentWalletMeta();await sql`INSERT INTO agent_identities (user_id, name, skills, wallet_address, meta)SELECT${auth.userId},${'Agent'},${['greet', 'present-model', 'validate-model', 'remember', 'think']},- ${wallet.address},- ${JSON.stringify({- encrypted_wallet_key: wallet.encrypted_key,- solana_address: sol.address,- encrypted_solana_secret: sol.encrypted_secret,- })}::jsonb+ ${walletAddress},+ ${JSON.stringify(meta)}::jsonbWHERE NOT EXISTS (SELECT 1 FROM agent_identitiesWHERE user_id = ${auth.userId} AND deleted_at IS NULL@@ -311,13 +342,10 @@ async function handleCreate(req, res) {integrity = null;}- const wallet = await generateAgentWallet();- const sol = await generateSolanaAgentWallet();+ const { walletAddress, meta: walletMeta } = await mintAgentWalletMeta();const meta = {...(body.meta || {}),- encrypted_wallet_key: wallet.encrypted_key,- solana_address: sol.address,- encrypted_solana_secret: sol.encrypted_secret,+ ...walletMeta,};// Stamp the integrity verdict onto the identity so the profile/editor can show// a "distinct identity" signal and reviewers can see what was checked at birth.@@ -340,7 +368,7 @@ async function handleCreate(req, res) {${name},${body.description ? String(body.description).slice(0, 500) : null},${body.skills || ['greet', 'present-model', 'validate-model', 'remember', 'think']},- ${wallet.address},+ ${walletAddress},${JSON.stringify(meta)}::jsonb,${avatarId})diff --git a/api/vision.js b/api/vision.jsnew file mode 100644index 000000000..93318ad91--- /dev/null+++ b/api/vision.js@@ -0,0 +1,150 @@+// POST /api/vision — free multimodal image understanding for the platform.+//+// Hand a hosted NVIDIA VLM an image and a question, get back text. Net-new,+// purely additive capability on the same free nvapi key that already powers+// chat, embeddings, TTS, and 3D generation. Product uses: describe / critique a+// 3D-model render, write alt text for a launch thumbnail, auto-tag an avatar's+// style, sanity-check a generated texture.+//+// Lane: NVIDIA NIM VLM over the OpenAI-compatible REST surface+// (api/_lib/vision-nvidia.js). Small images ride inline; large ones are uploaded+// to the NVCF asset store and referenced — the lib handles the switch.+//+// Request: raw image bytes as the body (Content-Type sets the image type), or a+// JSON body { image: <base64 or data URI>, prompt?, model?, maxTokens? }.+// Query/JSON params: prompt (the question; defaults to a concise describe),+// model (a VISION_MODELS id), maxTokens.+// Response: { text, model, usedAssetUpload }.++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 {+ describeImage,+ visionConfigured,+ resolveVisionModel,+ VISION_MODELS,+ DEFAULT_VISION_MODEL,+ DEFAULT_VISION_PROMPT,+} from './_lib/vision-nvidia.js';++export const maxDuration = 60;++// 12 MiB — comfortably covers a high-res viewer screenshot or photo while+// bounding the in-memory buffer. Larger images route through the NVCF asset+// store inside the lib, but the request body itself is still capped here.+const MAX_IMAGE_BYTES = 12 * 1024 * 1024;+const VISION_TIMEOUT_MS = 50_000;++const ACCEPTED_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];++function isAcceptedImageType(ct) {+ const type = String(ct || '').split(';')[0].trim().toLowerCase();+ return ACCEPTED_TYPES.includes(type) ? type : 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 a UI decide whether to offer "describe / critique"+ // affordances without guessing. Cheap, unauthenticated, briefly cacheable.+ if (req.method === 'GET' || req.method === 'HEAD') {+ return json(+ res,+ 200,+ {+ configured: visionConfigured(),+ models: [...VISION_MODELS],+ defaultModel: DEFAULT_VISION_MODEL,+ imageTypes: ACCEPTED_TYPES,+ },+ { 'cache-control': 'public, max-age=60' },+ );+ }++ if (!visionConfigured()) {+ return error(res, 503, 'not_configured', 'Vision is not configured (set NVIDIA_API_KEY)');+ }++ // Metered like the other free NVIDIA lanes.+ 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.visionUser(userId);+ if (!rl.success) return rateLimited(res, rl, 'Vision rate limit exceeded, try again later');+ } else {+ const rl = await limits.visionIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'Vision 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';++ let imageBytes;+ let imageType = 'image/jpeg';+ let prompt = q.get('prompt') || DEFAULT_VISION_PROMPT;+ let model = resolveVisionModel(q.get('model') || DEFAULT_VISION_MODEL);+ let maxTokens = Number(q.get('maxTokens')) || 512;++ try {+ if (isJson) {+ const body = await readJson(req, Math.ceil(MAX_IMAGE_BYTES * 1.4)); // base64 inflates ~33%+ const raw = typeof body.image === 'string' ? body.image : '';+ if (!raw) return error(res, 400, 'bad_request', 'image (base64 or data URI) is required');+ // Honor the data-URI mime if present; otherwise default to jpeg.+ const dataUri = raw.match(/^data:(image\/[a-z+]+);base64,(.*)$/i);+ const b64 = dataUri ? dataUri[2] : raw.replace(/^data:[^,]*,/, '');+ imageType = dataUri ? dataUri[1].toLowerCase() : (isAcceptedImageType(body.imageType) || 'image/jpeg');+ imageBytes = Buffer.from(b64, 'base64');+ if (typeof body.prompt === 'string' && body.prompt.trim()) prompt = body.prompt;+ if (typeof body.model === 'string') model = resolveVisionModel(body.model);+ if (Number(body.maxTokens)) maxTokens = Number(body.maxTokens);+ } else {+ const t = isAcceptedImageType(contentType);+ if (!t) {+ return error(+ res,+ 415,+ 'unsupported_media_type',+ `Unsupported image Content-Type "${contentType.split(';')[0] || 'none'}". Send image/jpeg, image/png, image/webp, or image/gif (or a JSON body with a base64 image).`,+ );+ }+ imageType = t;+ imageBytes = await readBody(req, MAX_IMAGE_BYTES);+ }+ } catch (e) {+ if (e?.status === 413) return error(res, 413, 'payload_too_large', 'image exceeds the 12 MB limit');+ return error(res, e?.status || 400, 'bad_request', e?.message || 'could not read request body');+ }++ if (!imageBytes?.length) return error(res, 400, 'bad_request', 'no image bytes received');++ try {+ const out = await describeImage({+ imageBytes,+ contentType: imageType,+ prompt,+ model,+ maxTokens,+ timeoutMs: VISION_TIMEOUT_MS,+ });+ return json(+ res,+ 200,+ { text: out.text, model: out.model, usedAssetUpload: Boolean(out.assetId) },+ { '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 :+ 502;+ return error(res, status, code, `Image understanding failed: ${e?.message || 'unknown error'}`);+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex 936f39eeb..5a11dd612 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,22 @@{"$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": "Creating an agent never dead-ends on wallet setup",+ "summary": "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.",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-06-23",+ "title": "Talk to your avatar out loud — in any browser",+ "summary": "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.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","title": "IRL: pinned agents now hold their exact spot indoors instead of drifting",diff --git a/public/changelog.json b/public/changelog.jsonindex 9fb9bbd51..3e99b22bd 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T05:18:04.424Z",+ "generated_at": "2026-06-23T05:30:50.227Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -47,6 +47,16 @@"improvement"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Creating an agent never dead-ends on wallet setup",+ "summary": "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.",+ "link": null,+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-23","type": "update",@@ -366,6 +376,16 @@"feature"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Talk to your avatar out loud — in any browser",+ "summary": "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.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 4ea8d5020..fe0864dd4 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -38,6 +38,14 @@<category>improvement</category><description>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.</description></item>+ <item>+ <title>Creating an agent never dead-ends on wallet setup</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Creating an agent never dead-ends on wallet setup</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>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.</description>+ </item><item><title>Embedded widgets never hang on a blank frame</title><link>https://three.ws/changelog</link>@@ -286,6 +294,14 @@<category>feature</category><description>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.</description></item>+ <item>+ <title>Talk to your avatar out loud — in any browser</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Talk to your avatar out loud — in any browser</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item><item><title>The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time</title><link>https://three.ws/marketplace</link>diff --git a/public/features.json b/public/features.jsonindex ef71af6a4..c9c4f6c75 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T05:18:04.345Z",+ "generated_at": "2026-06-23T05:30:50.215Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/avatar-page.js b/src/avatar-page.jsindex c46a66697..9dbd3def5 100644--- a/src/avatar-page.js+++ b/src/avatar-page.js@@ -576,7 +576,7 @@ function mountNetWorthAura() {const agentId = avatar?.agent_id;if (!stage || !agentId || netWorthAura) return;- hydrateAvatarWallet(stage, avatar, { lod: 'full', live: true, network: 'mainnet', fetchPrefs: false })+ hydrateAvatarWallet(stage, avatar, { lod: 'full', live: true, wealth: true, network: 'mainnet', fetchPrefs: false }).then((controller) => {if (!controller) return;netWorthAura = controller;diff --git a/src/shared/agent-money-stream.js b/src/shared/agent-money-stream.jsnew file mode 100644index 000000000..ab65dec8c--- /dev/null+++ b/src/shared/agent-money-stream.js@@ -0,0 +1,1174 @@+/**+ * Money Streams — pay an agent by the second, settled for real on Solana.+ *+ * A "stream" is an authorized rate + a real periodic micro-settlement, never a+ * fake counter. The streamer connects their own browser wallet (Phantom /+ * Backpack / Solflare — same detection as ./agent-tip.js), authorizes a+ * { rate-per-minute, asset, max-total } session, and from then on their browser:+ *+ * 1. Meters the *active* streaming time (paused when the tab is hidden, so you+ * never pay while you're not watching).+ * 2. On a fixed cadence (and on stop) builds + signs a transfer of the+ * accrued-since-last amount to the agent's PUBLIC solana_address, submits it+ * through the same-origin RPC proxy, and waits for confirmation. Each+ * settlement is a REAL on-chain transfer — three.ws never custodies the funds.+ * 3. POSTs each confirmed signature to /api/agents/:id/solana/stream, which+ * re-verifies on-chain that the agent was credited and records a public+ * custody event grouped by a client-generated stream_id.+ *+ * The live "ticking" number is the *projected* accrual between settlements; after+ * every settle it is reconciled to the server-confirmed on-chain total, so the+ * displayed figure is always backed by real signatures. `maxTotal` is a hard+ * ceiling the streamer signs for — enforced here (the meter can never project past+ * it and a final settle never exceeds it) AND on the server (it refuses any+ * settlement that would push a session over its signed ceiling). Closing the tab,+ * navigating away, or losing the wallet stops the meter to the second: no further+ * signatures means no further charges.+ *+ * Public API:+ * openStreamPanel(agent, { network }) → modal with the live meter + controls,+ * or the owner's live earnings view.+ * mountStreamMeter(el, agent, { network, compact }) → embed the meter inline+ * (chat pay-per-minute, club pay-to-watch).+ */++import {+ Connection,+ PublicKey,+ SystemProgram,+ Transaction,+ LAMPORTS_PER_SOL,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddress,+ getAccount,+ createAssociatedTokenAccountInstruction,+ createTransferCheckedInstruction,+ TOKEN_PROGRAM_ID,+} from '@solana/spl-token';+import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';+import { USDC_MINT } from './agent-tip.js';+import { getWalletStatus } from './agent-wallet-chip.js';++const STYLE_ID = 'tws-money-stream-styles';+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// Settle cadence + batching. We settle every SETTLE_INTERVAL_MS of active time,+// but only when at least MIN_SETTLE of the asset has accrued — so tiny rates batch+// up instead of paying a network fee on dust. A stop always does a final settle of+// whatever is left above true dust.+const SETTLE_INTERVAL_MS = 45_000;+const TICK_MS = 100;+const MIN_SETTLE = { SOL: 0.0005, USDC: 0.01 };+const DUST = { SOL: 0.000001, USDC: 0.000001 };++/** Supported stream assets + per-minute rate presets and sensible budget caps. */+export const STREAM_ASSETS = Object.freeze([+ { id: 'SOL', label: 'SOL', symbol: '◎', decimals: 9, ratePresets: [0.002, 0.005, 0.01, 0.05] },+ { id: 'USDC', label: 'USDC', symbol: '$', decimals: 6, ratePresets: [0.1, 0.25, 0.5, 1] },+]);++/** A stream error that carries a machine code so the UI can tailor recovery copy. */+export class StreamError extends Error {+ constructor(message, code = 'stream_failed') {+ super(message);+ this.name = 'StreamError';+ this.code = code;+ }+}++function prefersReducedMotion() {+ return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;+}++function uuid() {+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();+ // RFC4122-ish fallback for older webviews — only used as a grouping id.+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {+ const r = (Math.random() * 16) | 0;+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);+ });+}++function esc(s) {+ return String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function assetMeta(id) {+ return STREAM_ASSETS.find((a) => a.id === id) || STREAM_ASSETS[0];+}++/** Format an asset amount with enough precision for tiny per-second values. */+function fmtAmount(n, asset) {+ const v = Number(n) || 0;+ if (asset === 'USDC') return v.toFixed(v < 1 ? 4 : 2);+ // SOL — show up to 6 dp but trim trailing zeros past 4.+ return v.toFixed(6).replace(/(\.\d{4}?)0+$/, '$1');+}++function fmtUsd(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return null;+ if (v === 0) return '$0.00';+ if (v < 0.01) return `$${v.toFixed(4)}`;+ if (v < 1) return `$${v.toFixed(3)}`;+ return `$${v.toFixed(2)}`;+}++function fmtClock(ms) {+ const s = Math.max(0, Math.floor(ms / 1000));+ const h = Math.floor(s / 3600);+ const m = Math.floor((s % 3600) / 60);+ const sec = s % 60;+ const pad = (x) => String(x).padStart(2, '0');+ return h > 0 ? `${h}:${pad(m)}:${pad(sec)}` : `${pad(m)}:${pad(sec)}`;+}++// Poll signature status over HTTP (the proxy refuses WebSocket subscriptions).+// Returns 'confirmed' on success, throws StreamError('onchain_error') on tx error,+// throws StreamError('timeout') if it never resolves in the window.+async function confirmSignature(conn, signature, timeoutMs = 60_000) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ let value;+ try {+ ({ value } = await conn.getSignatureStatuses([signature]));+ } catch {+ value = null;+ }+ const status = value?.[0];+ if (status) {+ if (status.err) throw new StreamError(`Settlement failed on-chain: ${JSON.stringify(status.err)}`, 'onchain_error');+ if (status.confirmationStatus === 'confirmed' || status.confirmationStatus === 'finalized') return true;+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ throw new StreamError('Settlement timed out — it may still land; the meter is paused until it confirms.', 'timeout');+}++// ── the stream engine ───────────────────────────────────────────────────────────++class MoneyStreamEngine {+ constructor({ agentId, toAddress, asset, ratePerMinute, maxTotal, network }) {+ this.agentId = agentId || null;+ this.toAddress = toAddress;+ this.asset = asset === 'USDC' ? 'USDC' : 'SOL';+ this.ratePerMinute = Number(ratePerMinute);+ this.maxTotal = Number(maxTotal);+ this.network = network === 'devnet' ? 'devnet' : 'mainnet';+ this.streamId = uuid();++ this.state = 'idle'; // idle | connecting | streaming | paused | settling | stopped | error+ this.error = null;++ this.settledHuman = 0; // reconciled to on-chain confirmations+ this.settledUsd = 0;+ this.receipts = []; // { signature, explorerUrl, amount, usd, at, pending }+ this.usdPerAsset = null; // derived from settle responses for live USD projection++ this._bankedMs = 0; // active streaming ms banked before the current segment+ this._activeSince = null; // timestamp the current active segment started (null when paused)+ this._wallet = null;+ this._from = null;+ this._conn = null;+ this._settleTimer = null;+ this._tickTimer = null;+ this._settleInFlight = false;++ this._listeners = { tick: [], settle: [], state: [], error: [] };+ this._onVisibility = this._handleVisibility.bind(this);+ this._onPageHide = this._handlePageHide.bind(this);+ }++ on(evt, fn) {+ (this._listeners[evt] ||= []).push(fn);+ return () => { this._listeners[evt] = this._listeners[evt].filter((f) => f !== fn); };+ }+ _emit(evt, ...args) {+ for (const fn of this._listeners[evt] || []) {+ try { fn(...args); } catch { /* listener best-effort */ }+ }+ }+ _setState(s, err = null) {+ this.state = s;+ this.error = err;+ this._emit('state', s, err);+ }++ activeMs() {+ return this._bankedMs + (this._activeSince != null ? Date.now() - this._activeSince : 0);+ }++ /** 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);+ }++ /** Live projected amount the meter shows (settled + unsettled accrual). */+ projectedHuman() {+ return Math.max(this.settledHuman, this.owedHuman());+ }++ projectedUsd() {+ if (this.usdPerAsset == null) return null;+ return this.projectedHuman() * this.usdPerAsset;+ }++ atCeiling() {+ return this.settledHuman >= this.maxTotal - DUST[this.asset];+ }++ async start() {+ if (this.state === 'streaming' || this.state === 'connecting') return;+ if (!this.toAddress || !BASE58_RE.test(String(this.toAddress))) {+ throw new StreamError('This agent has no valid wallet to stream to.', 'no_address');+ }+ if (!(this.ratePerMinute > 0)) throw new StreamError('Set a rate above zero to start streaming.', 'bad_rate');+ if (!(this.maxTotal > 0)) throw new StreamError('Set a spend cap above zero.', 'bad_cap');++ this._setState('connecting');+ const wallet = detectSolanaWallet();+ if (!wallet) {+ this._setState('error', new StreamError('No Solana wallet found. Install Phantom, Backpack, or Solflare to stream.', 'no_wallet'));+ throw this.error;+ }+ let fromPubkey;+ try {+ const conn = await wallet.connect();+ fromPubkey = conn?.publicKey || wallet.publicKey;+ } catch (e) {+ const err = (e?.code === 4001 || /reject|cancel/i.test(e?.message || ''))+ ? new StreamError('Wallet connection cancelled.', 'cancelled')+ : new StreamError(e?.message || 'Could not connect your wallet.', 'connect_failed');+ this._setState('error', err);+ throw err;+ }+ if (!fromPubkey) {+ const err = new StreamError('Could not read your wallet address.', 'connect_failed');+ this._setState('error', err);+ throw err;+ }+ this._wallet = wallet;+ this._from = new PublicKey(fromPubkey.toString());+ if (this._from.equals(new PublicKey(String(this.toAddress)))) {+ const err = new StreamError('That wallet is the agent itself — stream from a different wallet.', 'self_stream');+ this._setState('error', err);+ throw err;+ }+ this._conn = new Connection(SOLANA_RPC[this.network] || SOLANA_RPC.mainnet, 'confirmed');++ this._bankedMs = 0;+ this._activeSince = Date.now();+ this._setState('streaming');+ this._startTimers();+ if (typeof document !== 'undefined') {+ document.addEventListener('visibilitychange', this._onVisibility);+ window.addEventListener('pagehide', this._onPageHide);+ window.addEventListener('beforeunload', this._onPageHide);+ }+ this._emit('tick');+ return this.fromAddress();+ }++ fromAddress() {+ return this._from ? this._from.toBase58() : null;+ }++ _startTimers() {+ this._stopTimers();+ // Settle cadence runs on real wall-clock; it no-ops while paused/at ceiling.+ this._settleTimer = setInterval(() => { this._maybeSettle('interval'); }, SETTLE_INTERVAL_MS);+ // Smooth counter — skipped under reduced-motion (the meter then updates on+ // settle only, which the renderer also redraws).+ if (!prefersReducedMotion()) {+ this._tickTimer = setInterval(() => {+ if (this.state === 'streaming') this._emit('tick');+ // Self-stop the instant projection reaches the ceiling.+ if (this.state === 'streaming' && this.owedHuman() >= this.maxTotal - DUST[this.asset]) {+ this._maybeSettle('ceiling');+ }+ }, TICK_MS);+ }+ }+ _stopTimers() {+ if (this._settleTimer) { clearInterval(this._settleTimer); this._settleTimer = null; }+ if (this._tickTimer) { clearInterval(this._tickTimer); this._tickTimer = null; }+ }++ _pauseAccrual() {+ if (this._activeSince != null) {+ this._bankedMs += Date.now() - this._activeSince;+ this._activeSince = null;+ }+ }+ _resumeAccrual() {+ if (this._activeSince == null) this._activeSince = Date.now();+ }++ _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.+ if (this.state === 'streaming') {+ this._pauseAccrual();+ this._setState('paused');+ this._maybeSettle('hidden');+ }+ } else if (document.visibilityState === 'visible' && this.state === 'paused') {+ this._resumeAccrual();+ this._setState('streaming');+ this._emit('tick');+ }+ }++ // On hard unload we cannot reliably pop a signing prompt, so we simply halt+ // accrual. No further signatures can be produced, so no further charges — the+ // safety guarantee holds without any unload-time signing hack.+ _handlePageHide() {+ this._pauseAccrual();+ this._stopTimers();+ }++ /** Amount currently unsettled (owed minus what's been confirmed on-chain). */+ _unsettled() {+ return Math.max(0, this.owedHuman() - this.settledHuman);+ }++ async _maybeSettle(reason) {+ if (this._settleInFlight) return;+ if (!this._conn || !this._wallet || !this._from) return;+ const unsettled = this._unsettled();+ const min = reason === 'interval' || reason === 'hidden' ? MIN_SETTLE[this.asset] : DUST[this.asset];+ if (unsettled < min) {+ if (reason === 'ceiling' || reason === 'stop') this._finishIfCeiling(reason);+ return;+ }+ await this._settle(unsettled, reason);+ }++ async _settle(amountHuman, reason) {+ this._settleInFlight = true;+ const wasState = this.state;+ // Don't flip the visible state to "settling" for routine interval settles —+ // keep the meter live; only a stop/ceiling settle shows the settling state.+ if (reason === 'stop' || reason === 'ceiling') this._setState('settling');+ let result;+ try {+ result = await this._sendSettlement(amountHuman);+ } catch (e) {+ this._settleInFlight = false;+ const err = e instanceof StreamError ? e : new StreamError(e?.message || 'Settlement failed.', 'settle_failed');+ // A rejected/failed settle never increments settled — no double charge.+ // Stop the stream so we don't keep prompting against a broken wallet/RPC.+ this._setState('error', err);+ this._emit('error', err);+ this._teardown();+ return;+ }++ // The transfer confirmed on-chain — count it locally even if the server+ // record (best-effort, idempotent) fails. Funds have moved.+ this.settledHuman += amountHuman;+ const receipt = { signature: result.signature, explorerUrl: result.explorerUrl, amount: amountHuman, usd: null, at: Date.now(), pending: true };+ this.receipts.push(receipt);+ this._settleInFlight = false;++ // Record + reconcile to the server's on-chain-verified total.+ try {+ const rec = await this._record(result.signature);+ if (rec) {+ if (rec.usd != null && Number(rec.amount) > 0) {+ this.usdPerAsset = Number(rec.usd) / Number(rec.amount);+ receipt.usd = Number(rec.usd);+ }+ if (Number.isFinite(rec.settled_so_far)) {+ // Reconcile the display to the on-chain-confirmed cumulative total.+ this.settledHuman = Math.max(this.settledHuman, Number(rec.settled_so_far));+ }+ receipt.pending = false;+ }+ } catch { /* already counted locally; record is a best-effort hint */ }++ if (this.usdPerAsset != null) this.settledUsd = this.settledHuman * this.usdPerAsset;++ this._emit('settle', receipt);+ this._emit('tick');+ // Broadcast so other surfaces (the agent's 3D avatar, money map) can react.+ if (typeof window !== 'undefined') {+ try {+ window.dispatchEvent(new CustomEvent('tws:money-stream-settle', {+ detail: { agentId: this.agentId, amount: amountHuman, asset: this.asset, usd: receipt.usd, signature: result.signature, streamId: this.streamId },+ }));+ } catch { /* no-op */ }+ }++ // Resolve the post-settle state.+ if (this.atCeiling() || reason === 'ceiling') {+ this._finishIfCeiling(reason);+ } else if (reason === 'stop') {+ this._setState('stopped');+ this._teardown();+ } else if (wasState === 'paused') {+ this._setState('paused');+ } else {+ this._setState('streaming');+ }+ }++ _finishIfCeiling(reason) {+ this._setState('stopped', reason === 'ceiling' ? new StreamError('Spend cap reached — the stream stopped automatically.', 'ceiling_reached') : null);+ this._teardown();+ }++ async _sendSettlement(amountHuman) {+ const conn = this._conn;+ const from = this._from;+ const to = new PublicKey(String(this.toAddress));+ const tx = new Transaction();+ if (this.asset === 'USDC') {+ const mint = new PublicKey(USDC_MINT[this.network] || USDC_MINT.mainnet);+ const fromAta = await getAssociatedTokenAddress(mint, from);+ const toAta = await getAssociatedTokenAddress(mint, to);+ try {+ await getAccount(conn, fromAta);+ } catch {+ throw new StreamError('Your wallet has no USDC. Switch to SOL or fund your wallet with USDC.', 'no_usdc');+ }+ let toExists = true;+ try { await getAccount(conn, toAta); } catch { toExists = false; }+ if (!toExists) tx.add(createAssociatedTokenAccountInstruction(from, toAta, to, mint));+ const raw = BigInt(Math.round(amountHuman * 1e6));+ if (raw <= 0n) throw new StreamError('Accrued amount is below one atomic unit.', 'dust');+ tx.add(createTransferCheckedInstruction(fromAta, mint, toAta, from, raw, 6, [], TOKEN_PROGRAM_ID));+ } else {+ const lamports = Math.round(amountHuman * LAMPORTS_PER_SOL);+ if (lamports <= 0) throw new StreamError('Accrued amount is below one lamport.', 'dust');+ tx.add(SystemProgram.transfer({ fromPubkey: from, toPubkey: to, lamports }));+ }++ let blockhashCtx;+ try {+ blockhashCtx = await conn.getLatestBlockhash('confirmed');+ } catch {+ throw new StreamError('Network is busy — could not fetch a blockhash. The meter is paused.', 'rpc_error');+ }+ tx.recentBlockhash = blockhashCtx.blockhash;+ tx.lastValidBlockHeight = blockhashCtx.lastValidBlockHeight;+ tx.feePayer = from;++ let signed;+ try {+ signed = await this._wallet.signTransaction(tx);+ } catch (e) {+ if (e?.code === 4001 || /reject|cancel/i.test(e?.message || '')) {+ throw new StreamError('You declined the settlement — the stream stopped.', 'cancelled');+ }+ throw new StreamError(e?.message || 'Signing failed.', 'sign_failed');+ }++ // Submit with a couple of retries for transient RPC throttling. We only ever+ // send THIS blockhash-bound tx — never a second tx for the same accrual — so a+ // retry can't double-charge (a duplicate is the same signature).+ let signature;+ let lastErr;+ for (let attempt = 0; attempt < 3; attempt++) {+ try {+ signature = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, preflightCommitment: 'confirmed', maxRetries: 5 });+ break;+ } catch (e) {+ lastErr = e;+ const msg = e?.message || '';+ if (/insufficient|0x1\b/i.test(msg)) {+ throw new StreamError('Insufficient balance for the next settlement plus fees. Lower the rate or add funds.', 'insufficient');+ }+ if (attempt < 2) await new Promise((r) => setTimeout(r, 600 * (attempt + 1)));+ }+ }+ if (!signature) throw new StreamError(lastErr?.message || 'The settlement could not be submitted.', 'send_failed');++ await confirmSignature(conn, signature);+ return { signature, explorerUrl: solanaTxExplorerUrl(this.network, signature) };+ }++ async _record(signature) {+ if (!this.agentId) return null;+ const res = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/solana/stream`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ signature,+ stream_id: this.streamId,+ asset: this.asset,+ network: this.network,+ rate_per_minute: this.ratePerMinute,+ max_total: this.maxTotal,+ from: this.fromAddress(),+ }),+ keepalive: true,+ });+ if (!res.ok) return null;+ const { data } = await res.json().catch(() => ({}));+ return data || null;+ }++ /** Stop the stream: a final settle of the remaining accrued, then close. */+ async stop() {+ if (this.state === 'stopped' || this.state === 'idle') return;+ this._pauseAccrual();+ this._stopTimers();+ await this._maybeSettle('stop');+ if (this.state !== 'stopped') { this._setState('stopped'); this._teardown(); }+ }++ _teardown() {+ this._stopTimers();+ if (typeof document !== 'undefined') {+ document.removeEventListener('visibilitychange', this._onVisibility);+ window.removeEventListener('pagehide', this._onPageHide);+ window.removeEventListener('beforeunload', this._onPageHide);+ }+ }++ destroy() {+ // Hard teardown without a settle (caller is dismounting). Any accrued-but-+ // unsettled amount is simply never charged — fail-safe toward the streamer.+ this._pauseAccrual();+ this._teardown();+ if (this.state === 'streaming' || this.state === 'paused') this._setState('stopped');+ }+}++// ── styles ───────────────────────────────────────────────────────────────────────++function ensureStyles() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+.tms-backdrop{position:fixed;inset:0;z-index:10000;display:flex;align-items:center;justify-content:center;+ padding:16px;background:rgba(8,8,12,.66);backdrop-filter:blur(4px);animation:tms-fade .18s ease;}+.tms{width:100%;max-width:420px;background:var(--bg-1,#16161c);color:var(--ink,#e8e8ea);+ border:1px solid var(--stroke-strong,rgba(255,255,255,.12));border-radius:16px;+ box-shadow:0 24px 64px rgba(0,0,0,.5);overflow:hidden;+ font:14px/1.45 var(--font-body,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif);+ animation:tms-rise .2s cubic-bezier(.2,.8,.2,1);}+.tms-card{background:var(--surface-1,rgba(255,255,255,.03));border:1px solid var(--stroke,rgba(255,255,255,.08));+ border-radius:14px;overflow:hidden;}+.tms-hd{display:flex;align-items:center;gap:11px;padding:15px 18px;border-bottom:1px solid var(--stroke,rgba(255,255,255,.07));}+.tms-av{width:38px;height:38px;border-radius:10px;object-fit:cover;flex:none;+ background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);}+.tms-hd-txt{min-width:0;flex:1;}+.tms-hd-k{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--wallet-accent,#c4b5fd);font-weight:700;display:flex;align-items:center;gap:6px;}+.tms-hd-n{font-size:15px;font-weight:600;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}+.tms-x{appearance:none;background:none;border:none;color:var(--ink-dim,#888);font-size:22px;line-height:1;+ cursor:pointer;padding:2px 4px;border-radius:6px;flex:none;transition:color .15s,background .15s;}+.tms-x:hover{color:#fff;background:rgba(255,255,255,.06);}+.tms-bd{padding:16px 18px 18px;}+.tms-live-dot{width:7px;height:7px;border-radius:50%;background:var(--success,#4ade80);box-shadow:0 0 0 0 rgba(74,222,128,.6);animation:tms-ping 1.4s ease-out infinite;}+.tms-live-dot[data-paused="1"]{background:var(--warn,#fbbf24);animation:none;}+@keyframes tms-ping{0%{box-shadow:0 0 0 0 rgba(74,222,128,.5)}70%{box-shadow:0 0 0 6px rgba(74,222,128,0)}100%{box-shadow:0 0 0 0 rgba(74,222,128,0)}}++/* meter */+.tms-meter{text-align:center;padding:18px 8px 14px;background:radial-gradient(120% 120% at 50% 0%,rgba(139,92,246,.12),transparent 70%);+ border-radius:12px;border:1px solid var(--wallet-stroke,rgba(139,92,246,.22));margin-bottom:14px;}+.tms-num{font:800 38px/1 var(--font-mono,ui-monospace,"JetBrains Mono",Menlo,monospace);color:#fff;+ letter-spacing:-.02em;font-feature-settings:"tnum";display:inline-flex;align-items:baseline;gap:7px;}+.tms-num .tms-sym{font-size:24px;color:var(--wallet-accent,#c4b5fd);}+.tms-num .tms-unit{font-size:14px;color:var(--ink-dim,#9a9aa2);font-weight:600;}+.tms-usd{margin-top:5px;font:600 13px/1 var(--font-mono,ui-monospace,Menlo,monospace);color:var(--ink-dim,#9a9aa2);}+.tms-sub{display:flex;align-items:center;justify-content:center;gap:14px;margin-top:11px;font-size:11.5px;color:var(--ink-dim,#9a9aa2);}+.tms-sub b{color:var(--ink-bright,#fff);font-family:var(--font-mono,ui-monospace,Menlo,monospace);font-weight:700;}+.tms-bar{height:5px;border-radius:999px;background:rgba(255,255,255,.08);margin-top:12px;overflow:hidden;}+.tms-bar-fill{height:100%;border-radius:999px;background:linear-gradient(90deg,var(--wallet-accent,#c4b5fd),var(--wallet-accent-strong,#a78bfa));+ width:0;transition:width .2s linear;}+.tms-cap-line{margin-top:6px;font-size:10.5px;color:var(--ink-faint,rgba(255,255,255,.5));text-align:right;}+.tms-meter.tms-pulse{animation:tms-flash .5s ease-out;}+@keyframes tms-flash{0%{box-shadow:0 0 0 0 rgba(139,92,246,.5)}100%{box-shadow:0 0 0 10px rgba(139,92,246,0)}}++/* controls */+.tms-toggle{display:flex;gap:6px;background:rgba(255,255,255,.04);border:1px solid var(--stroke,rgba(255,255,255,.08));+ border-radius:10px;padding:4px;margin-bottom:12px;}+.tms-tok{flex:1;appearance:none;font:inherit;font-weight:600;font-size:13px;color:var(--ink-dim,#9a9aa2);+ background:none;border:none;border-radius:7px;padding:7px 0;cursor:pointer;transition:background .15s,color .15s;}+.tms-tok[aria-pressed="true"]{background:rgba(139,92,246,.22);color:#c4b5fd;}+.tms-lbl{font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-dim,#888);margin:2px 0 7px;font-weight:600;}+.tms-presets{display:grid;grid-template-columns:repeat(4,1fr);gap:7px;margin-bottom:8px;}+.tms-pre{appearance:none;font:inherit;font-size:12.5px;color:var(--ink,#e8e8ea);background:rgba(255,255,255,.04);+ border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:8px;padding:8px 0;cursor:pointer;+ transition:border-color .15s,background .15s,transform .1s;font-family:var(--font-mono,ui-monospace,Menlo,monospace);}+.tms-pre:hover{background:rgba(255,255,255,.07);}+.tms-pre[aria-pressed="true"]{border-color:rgba(139,92,246,.6);background:rgba(139,92,246,.16);color:#c4b5fd;}+.tms-pre:active{transform:translateY(1px);}+.tms-field{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.04);+ border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:10px;padding:2px 12px;margin-bottom:12px;transition:border-color .15s;}+.tms-field:focus-within{border-color:rgba(139,92,246,.55);}+.tms-field input{flex:1;min-width:0;appearance:none;-moz-appearance:textfield;font:inherit;font-size:16px;font-weight:600;+ color:#fff;background:none;border:none;padding:9px 0;font-family:var(--font-mono,ui-monospace,Menlo,monospace);}+.tms-field input::-webkit-outer-spin-button,.tms-field input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0;}+.tms-field input:focus{outline:none;}+.tms-field .tms-unit{font-size:12px;font-weight:600;color:var(--ink-dim,#888);flex:none;font-family:var(--font-mono,ui-monospace,Menlo,monospace);}+.tms-go{width:100%;appearance:none;font:inherit;font-weight:700;font-size:14px;color:#0a0a0a;+ background:linear-gradient(180deg,#c4b5fd,#a78bfa);border:none;border-radius:11px;padding:13px 0;cursor:pointer;+ display:inline-flex;align-items:center;justify-content:center;gap:8px;transition:filter .15s,transform .1s,opacity .15s;}+.tms-go:hover:not(:disabled){filter:brightness(1.08);}+.tms-go:active:not(:disabled){transform:translateY(1px);}+.tms-go:disabled{opacity:.55;cursor:not-allowed;}+.tms-go[data-variant="stop"]{background:linear-gradient(180deg,#fda4af,#f87171);color:#0a0a0a;}+.tms-go[data-variant="ghost"]{background:rgba(255,255,255,.06);color:var(--ink,#e8e8ea);border:1px solid var(--stroke,rgba(255,255,255,.12));}+.tms-spin{width:14px;height:14px;border-radius:50%;border:2px solid rgba(10,10,10,.35);border-top-color:#0a0a0a;+ animation:tms-spin .7s linear infinite;flex:none;}+.tms-msg{font-size:12.5px;margin-top:11px;line-height:1.45;}+.tms-msg.err{color:#fca5a5;}+.tms-note{font-size:11px;color:var(--ink-dim,#6f6f78);margin-top:12px;text-align:center;line-height:1.4;}+.tms-kbd{font-family:var(--font-mono,ui-monospace,Menlo,monospace);font-size:10px;background:rgba(255,255,255,.07);+ border:1px solid var(--stroke,rgba(255,255,255,.12));border-radius:4px;padding:1px 5px;color:var(--ink-dim,#aaa);}++/* receipts */+.tms-receipts{margin-top:13px;display:flex;flex-direction:column;gap:5px;max-height:132px;overflow-y:auto;}+.tms-receipt{display:flex;align-items:center;gap:8px;font-size:11.5px;color:var(--ink-dim,#9a9aa2);+ background:rgba(74,222,128,.07);border:1px solid rgba(74,222,128,.16);border-radius:8px;padding:6px 9px;animation:tms-rise .25s ease;}+.tms-receipt .tms-rc-ok{color:var(--success,#4ade80);font-weight:700;}+.tms-receipt[data-pending="1"]{background:rgba(255,255,255,.04);border-color:var(--stroke,rgba(255,255,255,.1));}+.tms-receipt .tms-rc-amt{font-family:var(--font-mono,ui-monospace,Menlo,monospace);color:var(--ink-bright,#fff);font-weight:600;}+.tms-receipt a{margin-left:auto;color:var(--wallet-accent,#c4b5fd);text-decoration:none;font-weight:600;white-space:nowrap;}+.tms-receipt a:hover{text-decoration:underline;}++/* earnings (owner) */+.tms-earn-now{display:flex;align-items:center;gap:12px;background:radial-gradient(120% 120% at 0% 0%,rgba(74,222,128,.14),transparent 70%);+ border:1px solid rgba(74,222,128,.25);border-radius:12px;padding:14px 16px;margin-bottom:14px;}+.tms-earn-big{font:800 26px/1 var(--font-mono,ui-monospace,Menlo,monospace);color:#fff;font-feature-settings:"tnum";}+.tms-earn-k{font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-dim,#9a9aa2);font-weight:600;}+.tms-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px;}+.tms-stat{background:rgba(255,255,255,.04);border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:10px;padding:10px;text-align:center;}+.tms-stat-v{font:700 17px/1 var(--font-mono,ui-monospace,Menlo,monospace);color:#fff;}+.tms-stat-k{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--ink-dim,#888);margin-top:4px;}+.tms-chart{display:flex;align-items:flex-end;gap:3px;height:54px;margin:4px 0 14px;}+.tms-chart-bar{flex:1;min-width:2px;border-radius:3px 3px 0 0;background:linear-gradient(180deg,var(--wallet-accent,#c4b5fd),rgba(139,92,246,.3));+ transition:height .3s ease;min-height:2px;}+.tms-empty{text-align:center;color:var(--ink-dim,#9a9aa2);font-size:12.5px;padding:22px 10px;line-height:1.5;}+.tms-empty b{color:var(--ink-bright,#fff);}+.tms-skwrap{display:flex;flex-direction:column;gap:8px;padding:8px 0;}+.tms-sk{height:48px;border-radius:10px;background:linear-gradient(90deg,rgba(255,255,255,.05),rgba(255,255,255,.12),rgba(255,255,255,.05));+ background-size:200% 100%;animation:tms-sk 1.1s ease-in-out infinite;}+@keyframes tms-sk{0%{background-position:200% 0}100%{background-position:-200% 0}}++/* inline / compact */+.tms-inline{border:1px solid var(--wallet-stroke,rgba(139,92,246,.22));border-radius:12px;padding:12px 14px;+ background:var(--surface-1,rgba(255,255,255,.03));}+.tms-inline .tms-meter{padding:10px 4px 8px;margin-bottom:10px;}+.tms-inline .tms-num{font-size:28px;}+.tms-inline-row{display:flex;align-items:center;gap:8px;}+.tms-inline-row .tms-go{flex:1;}++@keyframes tms-fade{from{opacity:0;}to{opacity:1;}}+@keyframes tms-rise{from{opacity:0;transform:translateY(10px) scale(.99);}to{opacity:1;transform:none;}}+@keyframes tms-spin{to{transform:rotate(360deg);}}+@media (prefers-reduced-motion:reduce){+ .tms-backdrop,.tms,.tms-spin,.tms-receipt,.tms-live-dot,.tms-meter.tms-pulse{animation:none;}+ .tms-bar-fill,.tms-chart-bar{transition:none;}+}+`;+ (document.head || document.documentElement).appendChild(style);+}++// ── earnings fetch ─────────────────────────────────────────────────────────────++async function fetchEarnings(agentId, network, from) {+ const qs = new URLSearchParams({ network });+ if (from) qs.set('from', from);+ const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/solana/stream?${qs}`, { credentials: 'include' });+ if (!res.ok) throw new StreamError('Could not load streaming earnings.', 'earnings_failed');+ const { data } = await res.json();+ return data;+}++// ── streamer controller (shared by modal + inline) ───────────────────────────────++const WALLET_SVG = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4Z"/></svg>';++/**+ * Build a self-contained streamer UI (asset/rate/cap pickers, live meter,+ * Stream⇄Stop, receipts, every state). Returns { el, destroy }. Used by both the+ * modal and the inline mount.+ */+function createStreamerUI(agent, opts = {}) {+ ensureStyles();+ const status = getWalletStatus(agent);+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';+ const compact = !!opts.compact;+ const name = agent?.name || status?.name || 'this agent';+ const agentId = status?.agentId || agent?.id || agent?.agent_id || null;+ const toAddress = status?.address || agent?.solana_address || null;++ // Default asset honors an agent's advertised payment preference (same as tips).+ const accepted = (agent?.meta?.payments?.accepted_tokens || agent?.payments?.accepted_tokens || []).map((t) => String(t).toUpperCase());+ const initialAsset = accepted.includes('USDC') && !accepted.includes('SOL') ? 'USDC' : 'SOL';++ const cfg = {+ asset: initialAsset,+ rate: assetMeta(initialAsset).ratePresets[1],+ // Default cap = ~15 minutes at the chosen rate, the user can change it.+ capMode: 'auto',+ cap: assetMeta(initialAsset).ratePresets[1] * 15,+ };++ let engine = null;+ let pulseTimer = null;+ const root = document.createElement('div');+ root.className = compact ? 'tms-card tms-inline' : 'tms-card';++ function destroy() {+ if (engine) { try { engine.destroy(); } catch { /* idempotent */ } engine = null; }+ if (pulseTimer) { clearTimeout(pulseTimer); pulseTimer = null; }+ }++ if (!toAddress || !BASE58_RE.test(String(toAddress))) {+ root.innerHTML = `<div class="tms-bd"><div class="tms-empty">${esc(name)} doesn't have a wallet to stream to yet.<br><b>Fork it</b> or check back once its wallet is provisioned.</div></div>`;+ return { el: root, destroy };+ }++ // ── setup view (no active stream) ──+ function renderSetup(errMsg) {+ const am = assetMeta(cfg.asset);+ const capPresets = [+ { label: '~10 min', mult: 10 }, { label: '~30 min', mult: 30 },+ { label: '~1 hr', mult: 60 }, { label: 'custom', mult: null },+ ];+ root.innerHTML = `+ <div class="tms-bd">+ <div class="tms-toggle" role="group" aria-label="Stream asset">+ ${STREAM_ASSETS.map((a) => `<button class="tms-tok" type="button" data-asset="${a.id}" aria-pressed="${cfg.asset === a.id}">${esc(a.label)}</button>`).join('')}+ </div>+ <div class="tms-lbl">Rate · per minute</div>+ <div class="tms-presets">+ ${am.ratePresets.map((p) => `<button class="tms-pre" type="button" data-rate="${p}" aria-pressed="${Number(p) === Number(cfg.rate)}">${am.symbol}${fmtAmount(p, cfg.asset)}</button>`).join('')}+ </div>+ <div class="tms-field">+ <input type="number" inputmode="decimal" min="0" step="any" placeholder="0.00" value="${esc(cfg.rate)}" data-rate-input aria-label="Custom rate per minute"/>+ <span class="tms-unit">${esc(am.label)}/min</span>+ </div>+ <div class="tms-lbl">Spend cap · you sign for this ceiling</div>+ <div class="tms-presets">+ ${capPresets.map((c) => `<button class="tms-pre" type="button" data-cap-mult="${c.mult ?? ''}" aria-pressed="${(c.mult == null && cfg.capMode === 'custom') || (c.mult != null && cfg.capMode === 'auto' && Math.abs(cfg.cap - cfg.rate * c.mult) < 1e-9)}">${esc(c.label)}</button>`).join('')}+ </div>+ <div class="tms-field">+ <input type="number" inputmode="decimal" min="0" step="any" placeholder="0.00" value="${esc(Number(cfg.cap).toFixed(am.decimals === 6 ? 2 : 4))}" data-cap-input aria-label="Spend cap total"/>+ <span class="tms-unit">${esc(am.label)} max</span>+ </div>+ <button class="tms-go" type="button" data-start ${cfg.rate > 0 && cfg.cap > 0 ? '' : 'disabled'}>+ ${WALLET_SVG}<span>Stream ${am.symbol}${fmtAmount(cfg.rate, cfg.asset)}/min</span>+ </button>+ ${errMsg ? `<div class="tms-msg err" role="alert">${esc(errMsg)}</div>` : ''}+ <div class="tms-note">Pays ${esc(name)} live from your wallet, settling on-chain every ~45s. Stop anytime — you're charged only for the seconds you stream.${network === 'devnet' ? ' · Devnet' : ''}<br><span class="tms-kbd">S</span> to start/stop</div>+ </div>`;+ wireSetup();+ }++ function syncCap() {+ // Keep the auto cap tied to the rate until the user types a custom cap.+ if (cfg.capMode === 'auto') cfg.cap = cfg.rate * 15;+ }++ function wireSetup() {+ for (const b of root.querySelectorAll('[data-asset]')) {+ b.addEventListener('click', () => {+ cfg.asset = b.dataset.asset === 'USDC' ? 'USDC' : 'SOL';+ cfg.rate = assetMeta(cfg.asset).ratePresets[1];+ cfg.capMode = 'auto'; syncCap();+ renderSetup();+ });+ }+ for (const b of root.querySelectorAll('[data-rate]')) {+ b.addEventListener('click', () => { cfg.rate = Number(b.dataset.rate); syncCap(); renderSetup(); });+ }+ const rateInput = root.querySelector('[data-rate-input]');+ rateInput?.addEventListener('input', () => {+ cfg.rate = Number(rateInput.value) || 0; syncCap();+ const go = root.querySelector('[data-start]');+ if (go) go.disabled = !(cfg.rate > 0 && cfg.cap > 0);+ for (const b of root.querySelectorAll('[data-rate]')) b.setAttribute('aria-pressed', String(Number(b.dataset.rate) === Number(cfg.rate)));+ });+ for (const b of root.querySelectorAll('[data-cap-mult]')) {+ b.addEventListener('click', () => {+ const mult = b.dataset.capMult;+ if (mult === '') { cfg.capMode = 'custom'; const ci = root.querySelector('[data-cap-input]'); ci?.focus(); }+ else { cfg.capMode = 'auto'; cfg.cap = cfg.rate * Number(mult); }+ renderSetup();+ });+ }+ const capInput = root.querySelector('[data-cap-input]');+ capInput?.addEventListener('input', () => {+ cfg.capMode = 'custom';+ cfg.cap = Number(capInput.value) || 0;+ const go = root.querySelector('[data-start]');+ if (go) go.disabled = !(cfg.rate > 0 && cfg.cap > 0);+ });+ root.querySelector('[data-start]')?.addEventListener('click', startStream);+ }++ // ── live view (active stream) ──+ function renderLive() {+ const am = assetMeta(cfg.asset);+ const projected = engine.projectedHuman();+ const usd = engine.projectedUsd();+ const pct = Math.min(100, (engine.settledHuman / engine.maxTotal) * 100);+ const paused = engine.state === 'paused';+ const settling = engine.state === 'settling';+ root.innerHTML = `+ <div class="tms-bd">+ <div class="tms-meter" data-meter>+ <div class="tms-num"><span class="tms-sym">${am.symbol}</span><span data-num>${fmtAmount(projected, cfg.asset)}</span><span class="tms-unit">${esc(am.label)}</span></div>+ ${usd != null ? `<div class="tms-usd" data-usd>${esc(fmtUsd(usd))}</div>` : '<div class="tms-usd" data-usd></div>'}+ <div class="tms-sub">+ <span>rate <b>${am.symbol}${fmtAmount(cfg.rate, cfg.asset)}/min</b></span>+ <span>elapsed <b data-clock>${fmtClock(engine.activeMs())}</b></span>+ <span data-settled>settled <b>${am.symbol}${fmtAmount(engine.settledHuman, cfg.asset)}</b></span>+ </div>+ <div class="tms-bar"><div class="tms-bar-fill" data-bar style="width:${pct.toFixed(1)}%"></div></div>+ <div class="tms-cap-line">cap ${am.symbol}${fmtAmount(engine.maxTotal, cfg.asset)} · <span data-remain>${fmtAmount(Math.max(0, engine.maxTotal - engine.settledHuman), cfg.asset)}</span> left</div>+ </div>+ <button class="tms-go" type="button" data-variant="stop" data-stop ${settling ? 'disabled' : ''}>+ ${settling ? '<span class="tms-spin" aria-hidden="true"></span>Settling final…' : (paused ? '■ Stop (paused — tab hidden)' : '■ Stop streaming')}+ </button>+ <div class="tms-receipts" data-receipts>${renderReceipts()}</div>+ <div class="tms-note"><span class="tms-live-dot" data-dot ${paused ? 'data-paused="1"' : ''} style="display:inline-block;vertical-align:middle;margin-right:5px"></span>${paused ? 'Paused — you left the tab, so the meter is frozen. Come back to resume.' : 'Live — each ~45s a real on-chain settlement is signed from your wallet.'}<br><span class="tms-kbd">S</span> to stop</div>+ </div>`;+ root.querySelector('[data-stop]')?.addEventListener('click', stopStream);+ }++ function renderReceipts() {+ if (!engine || !engine.receipts.length) return '';+ const am = assetMeta(cfg.asset);+ return engine.receipts.slice(-6).reverse().map((r) => `+ <div class="tms-receipt" data-pending="${r.pending ? '1' : '0'}">+ <span class="tms-rc-ok">${r.pending ? '⋯' : '✓'}</span>+ <span>settled</span>+ <span class="tms-rc-amt">${am.symbol}${fmtAmount(r.amount, cfg.asset)}</span>+ ${r.usd != null ? `<span>· ${esc(fmtUsd(r.usd))}</span>` : ''}+ <a href="${esc(r.explorerUrl)}" target="_blank" rel="noopener">receipt ↗</a>+ </div>`).join('');+ }++ // Lightweight live updates without a full re-render (keeps focus + scroll).+ function tick() {+ if (!engine) return;+ const am = assetMeta(cfg.asset);+ const numEl = root.querySelector('[data-num]');+ if (numEl) numEl.textContent = fmtAmount(engine.projectedHuman(), cfg.asset);+ const usdEl = root.querySelector('[data-usd]');+ const usd = engine.projectedUsd();+ if (usdEl) usdEl.textContent = usd != null ? fmtUsd(usd) : '';+ const clockEl = root.querySelector('[data-clock]');+ if (clockEl) clockEl.textContent = fmtClock(engine.activeMs());+ const barEl = root.querySelector('[data-bar]');+ if (barEl) barEl.style.width = `${Math.min(100, (engine.settledHuman / engine.maxTotal) * 100).toFixed(1)}%`;+ const remainEl = root.querySelector('[data-remain]');+ if (remainEl) remainEl.textContent = fmtAmount(Math.max(0, engine.maxTotal - engine.settledHuman), cfg.asset);+ const settledEl = root.querySelector('[data-settled]');+ if (settledEl) settledEl.innerHTML = `settled <b>${am.symbol}${fmtAmount(engine.settledHuman, cfg.asset)}</b>`;+ }++ function onSettle() {+ // Refresh receipts + pulse the meter on a confirmed settlement.+ const rcWrap = root.querySelector('[data-receipts]');+ if (rcWrap) rcWrap.innerHTML = renderReceipts();+ const meter = root.querySelector('[data-meter]');+ if (meter && !prefersReducedMotion()) {+ meter.classList.remove('tms-pulse'); void meter.offsetWidth; meter.classList.add('tms-pulse');+ }+ tick();+ }++ function onState(s, err) {+ if (s === 'stopped') { renderSummary(err); return; }+ if (s === 'error') { renderSetup(err?.message || 'Streaming failed.'); return; }+ // streaming / paused / settling / connecting → full live re-render (state copy changes).+ if (engine) renderLive();+ const dot = root.querySelector('[data-dot]');+ if (dot) { if (s === 'paused') dot.setAttribute('data-paused', '1'); else dot.removeAttribute('data-paused'); }+ }++ function renderSummary(err) {+ const am = assetMeta(cfg.asset);+ const total = engine ? engine.settledHuman : 0;+ const usd = engine && engine.usdPerAsset != null ? engine.settledUsd : null;+ const receipts = engine ? engine.receipts : [];+ root.innerHTML = `+ <div class="tms-bd">+ <div class="tms-meter">+ <div class="tms-hd-k" style="justify-content:center;margin-bottom:8px">Stream ended</div>+ <div class="tms-num"><span class="tms-sym">${am.symbol}</span><span>${fmtAmount(total, cfg.asset)}</span><span class="tms-unit">${esc(am.label)}</span></div>+ ${usd != null ? `<div class="tms-usd">${esc(fmtUsd(usd))} streamed to ${esc(name)}</div>` : `<div class="tms-usd">streamed to ${esc(name)}</div>`}+ <div class="tms-sub"><span>${receipts.length} settlement${receipts.length === 1 ? '' : 's'}</span><span>elapsed <b>${fmtClock(engine ? engine.activeMs() : 0)}</b></span></div>+ </div>+ ${err && err.code !== 'ceiling_reached' ? `<div class="tms-msg err">${esc(err.message)}</div>` : ''}+ ${err && err.code === 'ceiling_reached' ? `<div class="tms-msg">${esc(err.message)}</div>` : ''}+ <div class="tms-receipts">${receipts.slice(-6).reverse().map((r) => `+ <div class="tms-receipt" data-pending="${r.pending ? '1' : '0'}"><span class="tms-rc-ok">${r.pending ? '⋯' : '✓'}</span><span>settled</span><span class="tms-rc-amt">${am.symbol}${fmtAmount(r.amount, cfg.asset)}</span><a href="${esc(r.explorerUrl)}" target="_blank" rel="noopener">receipt ↗</a></div>`).join('') || '<div class="tms-empty">No settlements — you stopped before the first one cleared. Nothing was charged.</div>'}+ </div>+ <button class="tms-go" type="button" data-variant="ghost" data-restart style="margin-top:13px">Stream again</button>+ </div>`;+ root.querySelector('[data-restart]')?.addEventListener('click', () => {+ if (engine) { try { engine.destroy(); } catch { /* noop */ } }+ engine = null;+ cfg.capMode = 'auto'; syncCap();+ renderSetup();+ });+ if (typeof opts.onEnded === 'function') { try { opts.onEnded({ total, usd, receipts: receipts.length }); } catch { /* noop */ } }+ }++ async function startStream() {+ if (engine && (engine.state === 'streaming' || engine.state === 'connecting')) return;+ engine = new MoneyStreamEngine({ agentId, toAddress, asset: cfg.asset, ratePerMinute: cfg.rate, maxTotal: cfg.cap, network });+ engine.on('tick', tick);+ engine.on('settle', onSettle);+ engine.on('state', onState);+ engine.on('error', () => { /* surfaced via state */ });+ // Show a connecting state immediately.+ root.querySelector('[data-start]') && (root.querySelector('[data-start]').innerHTML = `<span class="tms-spin" aria-hidden="true"></span>Connecting wallet…`);+ root.querySelector('[data-start]') && (root.querySelector('[data-start]').disabled = true);+ try {+ await engine.start();+ } catch (e) {+ // State listener already rendered the error view for known StreamErrors.+ if (!(e instanceof StreamError)) renderSetup(e?.message || 'Could not start the stream.');+ }+ }++ async function stopStream() {+ if (!engine) return;+ await engine.stop();+ }++ // Keyboard: S toggles start/stop when focus isn't in an input.+ function onKey(e) {+ if (e.defaultPrevented) return;+ const t = e.target;+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;+ if (e.key === 's' || e.key === 'S') {+ e.preventDefault();+ if (engine && (engine.state === 'streaming' || engine.state === 'paused')) stopStream();+ else if (!engine || engine.state === 'stopped' || engine.state === 'idle' || engine.state === 'error') {+ if (root.querySelector('[data-start]')) startStream();+ }+ }+ }+ root.addEventListener('keydown', onKey);++ renderSetup();+ return {+ el: root,+ destroy,+ stop: stopStream,+ getEngine: () => engine,+ };+}++// ── owner earnings UI ────────────────────────────────────────────────────────────++function createEarningsUI(agent, opts = {}) {+ ensureStyles();+ const status = getWalletStatus(agent);+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';+ const agentId = status?.agentId || agent?.id || agent?.agent_id || null;+ const name = agent?.name || status?.name || 'your agent';+ const root = document.createElement('div');+ root.className = 'tms-card';+ let refreshTimer = null;+ let destroyed = false;++ function destroy() {+ destroyed = true;+ if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; }+ }++ function renderLoading() {+ root.innerHTML = `<div class="tms-bd"><div class="tms-skwrap"><div class="tms-sk"></div><div class="tms-sk"></div><div class="tms-sk" style="height:54px"></div></div></div>`;+ }++ function renderError() {+ root.innerHTML = `<div class="tms-bd"><div class="tms-empty">Couldn't load streaming earnings right now.<br><button class="tms-go" data-variant="ghost" data-retry style="margin-top:12px;max-width:180px">Try again</button></div></div>`;+ root.querySelector('[data-retry]')?.addEventListener('click', load);+ }++ function renderData(d) {+ const life = d.lifetime || {};+ const now = d.earning_now || {};+ const daily = d.daily || [];+ const hasAny = (life.settlements || 0) > 0;+ if (!hasAny) {+ root.innerHTML = `<div class="tms-bd"><div class="tms-empty">No one has streamed to <b>${esc(name)}</b> yet.<br>Streaming lets visitors pay ${esc(name)} <b>by the second</b> while they watch or talk to it — share its page to start earning.</div></div>`;+ return;+ }+ const maxUsd = Math.max(...daily.map((x) => x.usd), 0.0001);+ const bars = daily.map((x) => `<div class="tms-chart-bar" style="height:${Math.max(2, (x.usd / maxUsd) * 100)}%" title="${esc(x.day)} · ${esc(fmtUsd(x.usd))}"></div>`).join('');+ const activeNow = now.active_streams || 0;+ root.innerHTML = `+ <div class="tms-bd">+ <div class="tms-earn-now">+ <span class="tms-live-dot" ${activeNow ? '' : 'data-paused="1"'} style="flex:none"></span>+ <div style="flex:1;min-width:0">+ <div class="tms-earn-k">Earning now</div>+ <div class="tms-earn-big">${activeNow ? `${esc(fmtUsd(now.usd_per_min))}/min` : '—'}</div>+ </div>+ <div style="text-align:right">+ <div class="tms-earn-k">Live streams</div>+ <div class="tms-earn-big">${activeNow}</div>+ </div>+ </div>+ <div class="tms-stats">+ <div class="tms-stat"><div class="tms-stat-v">${esc(fmtUsd(life.usd) || '$0')}</div><div class="tms-stat-k">Lifetime</div></div>+ <div class="tms-stat"><div class="tms-stat-v">${life.streamers || 0}</div><div class="tms-stat-k">Patrons</div></div>+ <div class="tms-stat"><div class="tms-stat-v">${life.sessions || 0}</div><div class="tms-stat-k">Sessions</div></div>+ </div>+ <div class="tms-lbl">Last 30 days</div>+ <div class="tms-chart">${bars || '<div class="tms-empty" style="padding:8px">No daily history yet.</div>'}</div>+ <div class="tms-receipts">${(d.recent || []).slice(0, 6).map((r) => `+ <div class="tms-receipt"><span class="tms-rc-ok">✓</span><span>${esc((r.from || 'someone').slice(0, 4))}…</span><span class="tms-rc-amt">${r.asset === 'USDC' ? '$' : '◎'}${fmtAmount(r.amount, r.asset === 'USDC' ? 'USDC' : 'SOL')}</span>${r.usd != null ? `<span>· ${esc(fmtUsd(r.usd))}</span>` : ''}<a href="${esc(r.explorer)}" target="_blank" rel="noopener">↗</a></div>`).join('')}</div>+ <div class="tms-note">Streamed income settles to ${esc(name)}'s wallet on-chain. Every figure here is backed by a real signature.</div>+ </div>`;+ }++ async function load() {+ if (!agentId) { renderError(); return; }+ try {+ const d = await fetchEarnings(agentId, network, null);+ if (destroyed) return;+ renderData(d);+ } catch {+ if (!destroyed) renderError();+ }+ }++ renderLoading();+ load();+ // Live-refresh the "earning now" figure every 20s while the panel is open.+ refreshTimer = setInterval(() => { if (typeof document === 'undefined' || document.visibilityState === 'visible') load(); }, 20_000);+ return { el: root, destroy };+}++// ── public API ──────────────────────────────────────────────────────────────────++/**+ * Open the Money Stream panel for an agent.+ *+ * @param {object} agent Any agent record shape (must resolve a public solana_address).+ * @param {object} [opts]+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']+ * @param {boolean} [opts.isOwner] Force the owner earnings view (auto-detected from+ * the agent record's ownership flags when omitted).+ * @param {'stream'|'earnings'} [opts.mode] Explicit view override.+ * @returns {{ close: () => void } | null} null when the agent has no wallet at all.+ */+export function openStreamPanel(agent, opts = {}) {+ if (typeof document === 'undefined') return null;+ ensureStyles();+ const status = getWalletStatus(agent);+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';+ const name = agent?.name || status?.name || 'this agent';+ const avatar = agent?.avatar_thumbnail_url || agent?.avatar_url || agent?.profile_image_url || status?.avatarUrl || '';+ const isOwner = opts.mode === 'earnings' || (opts.mode !== 'stream' && (opts.isOwner ?? !!(agent?.isOwner || agent?.is_owner)));+ const mode = isOwner ? 'earnings' : 'stream';++ const backdrop = document.createElement('div');+ backdrop.className = 'tms-backdrop';+ backdrop.setAttribute('role', 'dialog');+ backdrop.setAttribute('aria-modal', 'true');+ backdrop.setAttribute('aria-label', mode === 'earnings' ? `${name} streaming earnings` : `Stream to ${name}`);++ const prevActive = document.activeElement;+ let controller = null;++ function close() {+ document.removeEventListener('keydown', onKey, true);+ try { controller?.destroy?.(); } catch { /* idempotent */ }+ backdrop.remove();+ try { prevActive?.focus?.(); } catch { /* noop */ }+ }+ function onKey(e) {+ // Don't let Escape silently kill an active paid stream — confirm via Stop.+ const engine = controller?.getEngine?.();+ if (e.key === 'Escape') {+ if (engine && (engine.state === 'streaming' || engine.state === 'paused' || engine.state === 'settling')) return;+ e.preventDefault(); close();+ }+ }++ const shell = document.createElement('div');+ shell.className = 'tms';+ shell.innerHTML = `+ <div class="tms-hd">+ ${avatar ? `<img loading="lazy" decoding="async" class="tms-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="tms-av"></div>'}+ <div class="tms-hd-txt">+ <div class="tms-hd-k">${mode === 'earnings' ? '◎ Stream earnings' : '◎ Money Stream'}</div>+ <div class="tms-hd-n" title="${esc(name)}">${esc(name)}</div>+ </div>+ <button class="tms-x" type="button" data-x aria-label="Close">×</button>+ </div>`;++ controller = mode === 'earnings'+ ? createEarningsUI(agent, { network })+ : createStreamerUI(agent, { network });+ // Unwrap the inner card's body into the modal shell for a seamless look.+ controller.el.classList.remove('tms-card');+ shell.appendChild(controller.el);+ backdrop.appendChild(shell);++ shell.querySelector('[data-x]')?.addEventListener('click', () => {+ const engine = controller?.getEngine?.();+ if (engine && (engine.state === 'streaming' || engine.state === 'paused')) {+ // Stop the stream (final settle) before closing so we never abandon an+ // active paid session silently.+ controller.stop?.().finally(() => close());+ } else { close(); }+ });++ backdrop.addEventListener('click', (e) => {+ if (e.target !== backdrop) return;+ const engine = controller?.getEngine?.();+ if (engine && (engine.state === 'streaming' || engine.state === 'paused' || engine.state === 'settling')) return;+ close();+ });+ document.addEventListener('keydown', onKey, true);+ document.body.appendChild(backdrop);+ shell.querySelector('[data-x]')?.focus();++ return { close };+}++/**+ * Mount a live stream meter inline on a surface (chat pay-per-minute, club+ * pay-to-watch). Returns a handle with destroy(). For the owner's own agent it+ * mounts the earnings view instead — owners don't stream to themselves.+ *+ * @param {HTMLElement} el Container to render into.+ * @param {object} agent+ * @param {object} [opts] { network, isOwner, compact, onEnded }+ */+export function mountStreamMeter(el, agent, opts = {}) {+ if (!el || typeof document === 'undefined') return { destroy() {} };+ ensureStyles();+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';+ const isOwner = opts.isOwner ?? !!(agent?.isOwner || agent?.is_owner);+ const controller = isOwner+ ? createEarningsUI(agent, { network })+ : createStreamerUI(agent, { network, compact: opts.compact !== false, onEnded: opts.onEnded });+ el.replaceChildren(controller.el);+ return {+ el: controller.el,+ stop: () => controller.stop?.(),+ getEngine: () => controller.getEngine?.(),+ destroy: () => { try { controller.destroy?.(); } catch { /* idempotent */ } },+ };+}++if (typeof window !== 'undefined') {+ window.twsMoneyStream = { openStreamPanel, mountStreamMeter, STREAM_ASSETS };+}diff --git a/src/shared/networth-presence.js b/src/shared/networth-presence.jsindex 2781253af..3bbd510ad 100644--- a/src/shared/networth-presence.js+++ b/src/shared/networth-presence.js@@ -52,6 +52,14 @@ function ensureStyles() {.nwp-sub a:hover{text-decoration:underline;}.nwp-next{height:5px;border-radius:999px;background:rgba(255,255,255,.07);overflow:hidden;}.nwp-next i{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,var(--nw-accent),var(--nw-accent-ink));transition:width .6s var(--ease-standard,cubic-bezier(.4,0,.2,1));}+.nwp-flow{display:flex;flex-wrap:wrap;gap:6px;align-items:center;}+.nwp-flow-item{display:inline-flex;align-items:center;gap:4px;font:600 11px/1 var(--font-mono,JetBrains Mono,monospace);+ padding:3px 8px;border-radius:999px;background:var(--surface-2,rgba(255,255,255,.05));border:1px solid var(--stroke,rgba(255,255,255,.08));color:var(--ink-dim,#9a9aa3);}+.nwp-flow-item.is-up{color:var(--success,#4ade80);border-color:color-mix(in srgb,var(--success,#4ade80) 35%,transparent);}+.nwp-flow-item.is-down{color:var(--danger,#f87171);border-color:color-mix(in srgb,var(--danger,#f87171) 35%,transparent);}+.nwp-flow-item.is-stream{color:var(--nw-accent-ink);border-color:var(--nw-accent-line);}+.nwp-flow-item.is-tip{color:var(--nw-accent-ink);border-color:var(--nw-accent-line);background:var(--nw-accent-soft);}+.nwp-flow-cap{opacity:.6;font-weight:500;}.nwp-marks{display:flex;flex-wrap:wrap;gap:6px;}.nwp-mark{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;padding:4px 9px;border-radius:999px;background:var(--nw-accent-soft);border:1px solid var(--nw-accent-line);color:var(--nw-accent-ink);text-decoration:none;diff --git a/src/strategies.js b/src/strategies.jsnew file mode 100644index 000000000..a9ae78720--- /dev/null+++ b/src/strategies.js@@ -0,0 +1,209 @@+// /strategies — the Strategy Object library: a marketplace of HOW agents trade.+//+// Three real surfaces, one page:+// • Marketplace — every published strategy, ranked honestly (proven first). Fork+// into your library or equip on your own agent.+// • Leaderboard — proven strategies ranked by REAL live ROI from on-chain fills.+// • My library — your strategies: create, edit, publish, equip, delete.+//+// Every number traces to a real fill (agent_strategy_positions). A strategy with no+// closed trades is honestly "Unproven" — never a fabricated backtest curve.++import { apiFetch } from './api.js';+import {+ esc, shortAddr, fmtSol, timeAgo, toast, configSummary,+ openStrategyEditor, openEquipPicker,+} from './shared/strategy-forms.js';++const grid = document.getElementById('sp-grid');+const scopeSeg = document.getElementById('sp-scope');+const searchInput = document.getElementById('sp-search');++let scope = new URL(location.href).searchParams.get('scope') || 'published';+let query = '';+let authed = null; // resolved lazily+let _seq = 0;++function perfBadge(p) {+ return p?.proven+ ? '<span class="sp-badge proven">Proven</span>'+ : '<span class="sp-badge unproven">Unproven</span>';+}+function statsLine(p) {+ if (!p || !p.proven) return '<span>No closed trades yet — equip it to build a record</span>';+ const roi = p.roi_pct != null ? `<span class="${p.roi_pct >= 0 ? 'pos' : 'neg'}">${p.roi_pct >= 0 ? '+' : ''}${p.roi_pct}% ROI</span>` : '';+ const pnl = `<span class="${p.pnl_sol >= 0 ? 'pos' : 'neg'}">${p.pnl_sol >= 0 ? '+' : ''}◎${fmtSol(p.pnl_sol)}</span>`;+ const win = p.win_rate != null ? `<span>${p.win_rate}% win</span>` : '';+ const dd = p.worst_sol != null && p.worst_sol < 0 ? `<span class="neg">worst ◎${fmtSol(p.worst_sol)}</span>` : '';+ return `${roi}${pnl}${win}<span>${p.trades} trades</span>${dd}`;+}++function card(s, isMine) {+ const lineage = s.forked_from ? `<span title="Forked from ${esc(s.forked_from.name || '')}">🍴 from ${esc(s.forked_from.owner_name || shortAddr(s.forked_from.owner_id))}</span>` : '';+ const rank = s.rank ? `<div class="sp-rank" title="Rank #${s.rank} by live ROI">#${s.rank}</div>` : '';+ let actions;+ if (isMine) {+ actions = `+ <button class="sp-btn sp-btn-primary" data-act="equip" data-id="${esc(s.id)}">Equip</button>+ <button class="sp-btn" data-act="edit" data-id="${esc(s.id)}">Edit</button>+ <button class="sp-btn" data-act="publish" data-id="${esc(s.id)}">${s.published ? 'Unpublish' : 'Publish'}</button>+ <button class="sp-btn" data-act="delete" data-id="${esc(s.id)}" title="Delete strategy" aria-label="Delete strategy">✕</button>`;+ } else {+ actions = `+ <button class="sp-btn sp-btn-primary" data-act="equip" data-id="${esc(s.id)}">Equip</button>+ <button class="sp-btn" data-act="fork" data-id="${esc(s.id)}" title="Copy the rules into your library">🍴 Fork</button>`;+ }+ return `<div class="sp-card" data-id="${esc(s.id)}">+ ${rank}+ <div class="sp-card-top">+ <div class="sp-card-name">${esc(s.name)}</div>+ ${perfBadge(s.performance)}+ </div>+ ${s.description ? `<div class="sp-desc">${esc(s.description)}</div>` : '<div class="sp-desc"></div>'}+ <div class="sp-rules">${configSummary(s.config)}</div>+ <div class="sp-stats">${statsLine(s.performance)}</div>+ <div class="sp-meta">by ${esc(s.owner_name || shortAddr(s.owner_id))}${lineage ? ' · ' + lineage : ''}${s.forks_count ? ` · ${s.forks_count} fork${s.forks_count === 1 ? '' : 's'}` : ''}${s.equips_count ? ` · ${s.equips_count} equipped` : ''}${s.updated_at ? ` · ${timeAgo(s.updated_at)}` : ''}</div>+ <div class="sp-actions">${actions}</div>+ </div>`;+}++function renderEmpty() {+ if (scope === 'mine') {+ grid.innerHTML = `<div class="sp-empty"><strong>No strategies yet</strong>Build your first rule-based plan — entry, sizing, take-profit, stop-loss — then equip it on your agent.<br><br><button class="sp-btn sp-btn-primary" id="sp-empty-new" style="max-width:220px;margin:0 auto">+ Create a strategy</button></div>`;+ document.getElementById('sp-empty-new')?.addEventListener('click', createNew);+ } else if (scope === 'leaderboard') {+ grid.innerHTML = `<div class="sp-empty"><strong>No proven strategies yet</strong>The leaderboard ranks strategies by real, on-chain live performance. As equipped strategies close their first trades, they appear here — ranked by verified ROI, not promises.</div>`;+ } else {+ grid.innerHTML = `<div class="sp-empty"><strong>No published strategies yet</strong>Be the first: build a strategy, prove it on real chain data, and publish it for others to fork and equip.<br><br><button class="sp-btn sp-btn-primary" id="sp-empty-new" style="max-width:220px;margin:0 auto">+ Create a strategy</button></div>`;+ document.getElementById('sp-empty-new')?.addEventListener('click', createNew);+ }+}++async function load() {+ const seq = ++_seq;+ grid.innerHTML = '<div class="sp-sk"></div><div class="sp-sk"></div><div class="sp-sk"></div>';+ let strategies = [];+ try {+ let path;+ if (scope === 'leaderboard') path = '/api/strategies/leaderboard?limit=30';+ else path = `/api/strategies?scope=${scope}&limit=40${query ? `&q=${encodeURIComponent(query)}` : ''}`;+ const res = await apiFetch(path, { allowAnonymous: true });+ if (res.status === 401 && scope === 'mine') {+ grid.innerHTML = `<div class="sp-empty"><strong>Sign in to see your library</strong>Your strategies live in your account — sign in to create, edit, and equip them.<br><br><a class="sp-btn sp-btn-primary" href="/login?next=${encodeURIComponent('/strategies')}" style="max-width:200px;margin:0 auto;text-decoration:none;display:block">Sign in</a></div>`;+ return;+ }+ if (!res.ok) throw new Error('load failed');+ const data = (await res.json()).data;+ strategies = scope === 'leaderboard' ? data.leaders || [] : data.strategies || [];+ } catch (e) {+ if (e?.redirected) return;+ if (seq !== _seq) return;+ grid.innerHTML = `<div class="sp-empty"><strong>Couldn't load strategies</strong>Something went wrong reaching the strategy library.<br><br><button class="sp-btn" id="sp-retry" style="max-width:160px;margin:0 auto">Retry</button></div>`;+ document.getElementById('sp-retry')?.addEventListener('click', load);+ return;+ }+ if (seq !== _seq) return;+ if (!strategies.length) { renderEmpty(); return; }+ const isMine = scope === 'mine';+ grid.innerHTML = strategies.map((s) => card(s, isMine || s.is_owner)).join('');+ wireCards(strategies);+}++function wireCards(strategies) {+ grid.querySelectorAll('[data-act]').forEach((btn) => {+ btn.addEventListener('click', async (e) => {+ e.preventDefault();+ const id = btn.dataset.id;+ const s = strategies.find((x) => x.id === id);+ if (!s) return;+ const act = btn.dataset.act;+ if (act === 'equip') return doEquip(s);+ if (act === 'fork') return doFork(s, btn);+ if (act === 'edit') return doEdit(s);+ if (act === 'publish') return doPublish(s, btn);+ if (act === 'delete') return doDelete(s);+ });+ });+}++async function doEquip(s) {+ if (!(await ensureAuthed())) { location.href = `/login?next=${encodeURIComponent('/strategies')}`; return; }+ await openEquipPicker({ strategy: s });+}++async function doFork(s, btn) {+ if (!(await ensureAuthed())) { location.href = `/login?next=${encodeURIComponent('/strategies')}`; return; }+ btn.disabled = true; btn.textContent = 'Forking…';+ try {+ const res = await apiFetch(`/api/strategies/${s.id}/fork`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });+ const j = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(j?.error?.message || 'Fork failed');+ toast(`Forked “${s.name}” into your library — yours to tweak and equip`);+ } catch (e) { if (!e?.redirected) toast(e.message || 'Fork failed'); }+ finally { btn.disabled = false; btn.textContent = '🍴 Fork'; }+}++async function doEdit(s) {+ const updated = await openStrategyEditor({ existing: s });+ if (updated) load();+}++async function doPublish(s, btn) {+ btn.disabled = true;+ try {+ const res = await apiFetch(`/api/strategies/${s.id}/publish`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ published: !s.published }) });+ const j = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(j?.error?.message || 'Could not update');+ toast(j.data?.published ? 'Published — others can fork & equip it' : 'Unpublished');+ load();+ } catch (e) { if (!e?.redirected) toast(e.message || 'Could not update'); btn.disabled = false; }+}++async function doDelete(s) {+ if (!confirm(`Delete “${s.name}”? Equipped agents stop running it; open positions stay yours to manage. This can't be undone.`)) return;+ try {+ const res = await apiFetch(`/api/strategies/${s.id}`, { method: 'DELETE' });+ if (!res.ok) { const j = await res.json().catch(() => ({})); throw new Error(j?.error?.message || 'Delete failed'); }+ toast('Strategy deleted');+ load();+ } catch (e) { if (!e?.redirected) toast(e.message || 'Delete failed'); }+}++async function createNew() {+ if (!(await ensureAuthed())) { location.href = `/login?next=${encodeURIComponent('/strategies')}`; return; }+ const created = await openStrategyEditor({});+ if (created) { scope = 'mine'; syncSeg(); load(); }+}++async function ensureAuthed() {+ if (authed != null) return authed;+ try {+ const res = await apiFetch('/api/auth/me', { allowAnonymous: true });+ authed = res.ok;+ } catch { authed = false; }+ return authed;+}++function syncSeg() {+ scopeSeg.querySelectorAll('button').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.scope === scope)));+}++scopeSeg.addEventListener('click', (e) => {+ const btn = e.target.closest('button[data-scope]');+ if (!btn) return;+ scope = btn.dataset.scope;+ syncSeg();+ const u = new URL(location.href); u.searchParams.set('scope', scope); history.replaceState(null, '', u);+ load();+});++let _searchTimer = null;+searchInput?.addEventListener('input', () => {+ clearTimeout(_searchTimer);+ _searchTimer = setTimeout(() => { query = searchInput.value.trim(); load(); }, 250);+});++document.getElementById('sp-new')?.addEventListener('click', createNew);++syncSeg();+load();diff --git a/tests/agent-trade-endpoint.test.js b/tests/agent-trade-endpoint.test.jsindex b31b5a9e3..66e5300a5 100644--- a/tests/agent-trade-endpoint.test.js+++ b/tests/agent-trade-endpoint.test.js@@ -426,7 +426,14 @@ describe('POST /api/agents/:id/trade — execution', () => {const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1, idempotency_key: 'live-1' });expect(res.statusCode).toBe(200);expect(res.json.data.replayed).toBe(false);- expect(res.json.data.signature).toBe('SIG_LIVE_123');+ // The protected execution engine derives the signature from the signed v0 tx+ // (bs58 of its first signature), not from sendRawTransaction's return — so it is+ // a real base58 signature echoed consistently into the explorer link (the same+ // value the custody row records), rather than the RPC mock's stand-in return.+ const sig = res.json.data.signature;+ expect(typeof sig).toBe('string');+ expect(sig).toMatch(/^[1-9A-HJ-NP-Za-km-z]{64,}$/);+ expect(res.json.data.explorer).toContain(sig);expect(res.json.data.tokens_received).toBe('1000000');expect(res.json.data.side).toBe('buy');// The decrypted secret must never surface in the response.diff --git a/tests/agent-wallet-deposit-tab.test.js b/tests/agent-wallet-deposit-tab.test.jsindex 493cbc23b..efe7cc4c8 100644--- a/tests/agent-wallet-deposit-tab.test.js+++ b/tests/agent-wallet-deposit-tab.test.js@@ -16,7 +16,11 @@ vi.mock('../src/agent-solana-wallet.js', () => ({fetchAgentSolanaActivity: (...a) => fetchAgentSolanaActivity(...a),}));-const { buildSolanaPayUri } = await import('../src/agent-wallet-hub/tabs/deposit.js');+// The Deposit tab renders its QR from the shared Solana-Pay builder, which is the+// one canonical source every surface (deposit tab, IRL/AR, portable embed) shares.+const { buildSolanaPayUri } = await import('../src/shared/solana-pay.js');+// Importing the deposit tab module still registers it for the tab-registry assertions.+await import('../src/agent-wallet-hub/tabs/deposit.js');const { getRegisteredTabs } = await import('../src/agent-wallet-hub/registry.js');const depositTab = getRegisteredTabs().find((t) => t.id === 'deposit');diff --git a/tests/economy-ticker-core.test.js b/tests/economy-ticker-core.test.jsindex 4508f167d..5c4ab7dc7 100644--- a/tests/economy-ticker-core.test.js+++ b/tests/economy-ticker-core.test.js@@ -51,7 +51,7 @@ describe('relTime', () => {it('renders compact ages against an injected now', () => {const now = new Date('2026-06-23T12:00:30.000Z').getTime();expect(relTime('2026-06-23T12:00:00.000Z', now)).toBe('30s');- expect(relTime('2026-06-23T11:55:00.000Z', now)).toBe('5m');+ expect(relTime('2026-06-23T11:55:30.000Z', now)).toBe('5m');expect(relTime('2026-06-23T09:00:00.000Z', now)).toBe('3h');expect(relTime('bad-date', now)).toBe('');});