Skip to content

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

Agent economy: Earn tab, treasury autopilot, social recovery, mirror trading

nirholas23fecc23c6fc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d32a56c56..63b07bfd9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-23
+- **Guardian console — recover & inherit agent wallets** (`/guardian`) — The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
- **Money Pulse** (`/pulse`) — The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.
- **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]`
- **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]`
@@ -26,9 +27,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **New: your avatar comes alive in iOS AR — it breathes and idles in your room** — Placing an avatar in AR on iPhone or iPad used to drop a frozen mannequin into your space. Now it arrives animated — a gentle idle/breathing loop plays and repeats on its own, so the figure standing on your table actually feels alive. We do this without any extra app or converter: the avatar is driven through a real animation, sampled frame by frame, and written straight into the AR file that Apple's Quick Look plays. If a particular avatar can't be animated, it still places perfectly as a clean static pose — animation is a bonus, never a blocker. `[feature, improvement]`
- **Prompt-to-avatar: a live progress bar you can cancel, plus motion and screen-reader polish** — Building an avatar from a text prompt now shows a progress bar that actually moves second-to-second (tied to real elapsed time) instead of sitting frozen between stages, a real elapsed clock, and a Cancel button (or Escape) so you're never stuck watching a spinner. Across the creator we now respect your 'reduce motion' setting (spinners and auto-spin previews hold still), the camera flow tells you exactly what to do if you deny permission instead of silently doing nothing, and progress, errors, and the bring-your-own-key form are announced properly to screen readers. Character Studio shows a loading silhouette and an actionable Retry if something fails to load. (`/create/prompt`) `[improvement]`
- **Security: CSRF protection extended to sniper arming and trade limits** — Arming an autonomous sniper strategy and changing an agent's discretionary trade limits both commit or unlock real custodial funds, so both writes now require the same one-time CSRF token every other money-moving action already enforced (withdraw, vanity grind, spend limits, trade execution). Ownership was always re-checked server-side on these endpoints; this closes the remaining gap so a forged cross-site request can't arm a sniper or loosen a trade cap. No change to how you use them — the dashboard already sends the token. `[security]`
+- **Social recovery & inheritance — a funded agent that never dies with its owner** — Your agent's wallet is custodial and real-money funded, so "I lost access" or "the owner is gone" should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping "I'm here"). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds. (`/guardian`) `[feature, security]`
- **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]`
- **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]`
+- **Treasury Autopilot — the agent that funds its own existence** — Your agent can now manage its own money under a policy you write in plain English. Tell it something like "Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, compound coin fees into buybacks weekly, and sweep anything over 3 SOL to me on Fridays" — it compiles that into clear, bounded rules and shows them back for you to approve before anything runs. Once armed, it executes each rule as a real, on-chain action from the agent's own wallet: it pays its own metered LLM and voice costs, holds your safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to you — every move clamped to your spend limits, idempotent, and written to the custody trail with an explorer link. A runway dashboard shows the honest truth: real income vs. real compute cost, the buffer, $THREE accumulated, buybacks executed, profit swept, and how long the agent self-sustains at its current burn — a net-negative agent says so plainly. A prominent kill switch halts everything instantly, and any rule pauses or edits in one tap. Owner-only, by construction. `[feature]`
+- **Tune how your agent wears its wallet — presence dial and earned regalia** — The net-worth aura now comes with a presence panel on every agent's viewer and profile. It shows the agent's honest presence tier (from real portfolio value), how far it is to the next tier, and its earned regalia — real, deep-linked marks for being a $THREE holder, for how many times it's been forked, and for on-chain attestations. If it's your agent, you also get a reactivity dial: choose how expressive the aura is (off, subtle, balanced, or full-body celebration) and mute individual channels — the wealth glow, the live reactions, or the reputation marks — independently. Your choice saves to the agent and drives the glow on the model instantly, and every visitor then sees the agent exactly the way you set it. Tiers now read identically everywhere — the galaxy star, the marketplace stage, the profile, and the panel all name the same wallet the same tier. `[feature, improvement]`
+- **Wallet figures read the same everywhere — one money and address style across the app** — An agent's portfolio value now formats identically wherever it appears — the tiny wallet chip on a card, the inline net-worth on a profile, the presence panel — so the same wallet never shows "$1k" in one place and "$1.2K" in another. Addresses shorten the same way across surfaces too, and the wallet's violet accent now flows from one design token instead of scattered colors, so the whole wallet layer reads as a single, coherent system. We also added an automated test that proves the platform's core promise on every fork: saving someone else's avatar always mints a brand-new wallet with its own distinct Solana and EVM addresses, never copies a secret, and leaves the original's wallet untouched. `[improvement, security]`
- **Your agent's wallet is now a living identity on every surface** — The little wallet badge under every agent and avatar grew up. Wherever an agent appears — its profile, the marketplace, the galaxy star-map, trending, your dashboard, the launches feed — its wallet now shows the real, live portfolio value in USD, a colour-coded 24-hour change, and a clear ownership marker: a 'Yours' badge on wallets you own, and 'by @creator' on everyone else's. Hover, focus, or tap the badge and it expands into a rich preview: your balance broken out into SOL, USDC, $THREE and your top holdings, a real value sparkline, both your Solana and EVM addresses with one-click copy, and the right actions for who's looking — Open wallet and Vanity for owners, Tip and Fork-to-own for visitors. The same agent's wallet looks identical everywhere because it all comes from one shared component, every number is real on-chain data, and the value gently pulses when a tip lands or a trade fills. Balances load lazily as you scroll and pause when you switch tabs, so even long lists stay fast. (`/marketplace`) `[feature, improvement]`
## 2026-06-22
diff --git a/api/_lib/agent-economy.js b/api/_lib/agent-economy.js
new file mode 100644
index 000000000..0513e0225
--- /dev/null
+++ b/api/_lib/agent-economy.js
@@ -0,0 +1,376 @@
+// Agent-to-Agent Economy (prompts/agent-wallets/15) — the data layer.
+//
+// One agent hiring another for a paid skill is recorded in `agent_hires`. This
+// module is the single place that writes and reads that ledger, so the
+// marketplace's completion counts / ratings / earnings are ALWAYS real
+// aggregates over real hires — never fabricated. It also exposes the offer
+// catalog (the existing agent_paid_services registry) joined to those live
+// stats, and each agent's income/outlay accounting.
+//
+// Money never moves here. The hire endpoint (api/agents/a2a-hire.js) reserves the
+// spend against the owner's spend policy and settles USDC over the real x402
+// rails; this module only records the business-level hire and its lifecycle so
+// it can be queried, rated, and audited.
+
+import { sql } from './db.js';
+import { publicUrl as r2PublicUrl } from './r2.js';
+
+export function atomicsToUsdc(atomics) {
+ return Number(atomics || 0) / 1_000_000;
+}
+
+// Avatar thumbnail is only surfaced when the avatar is publicly visible — mirrors
+// the gate the public pulse feed uses so the marketplace never leaks a private
+// avatar render.
+function avatarThumb(thumbKey, visibility) {
+ const visible = visibility === 'public' || visibility === 'unlisted';
+ return thumbKey && visible ? r2PublicUrl(thumbKey) : null;
+}
+
+function shapeProvider(row) {
+ if (!row?.provider_agent_id) return null;
+ return {
+ id: row.provider_agent_id,
+ name: row.provider_name || 'Agent',
+ url: `/agent/${row.provider_agent_id}`,
+ avatar_thumbnail_url: avatarThumb(row.provider_thumb_key, row.provider_avatar_vis),
+ solana_address: row.provider_addr || null,
+ is_public: row.provider_is_public !== false,
+ };
+}
+
+// ── Writes ────────────────────────────────────────────────────────────────
+
+/**
+ * Insert a pending hire, idempotently. A retry carrying the same
+ * (hirerAgentId, idempotencyKey) returns the existing row instead of inserting a
+ * second one — this is the double-charge guard: the caller checks `existing`
+ * before moving any money.
+ *
+ * @returns {Promise<{ row: object, existing: boolean }>}
+ */
+export async function recordHire(input) {
+ const {
+ hirerAgentId,
+ hirerUserId,
+ providerAgentId = null,
+ providerUserId = null,
+ serviceId = null,
+ serviceSlug = null,
+ skillName,
+ amountAtomics,
+ usd = null,
+ currency = 'USDC',
+ network = 'solana',
+ payerAddress = null,
+ payoutAddress = null,
+ spendReservationId = null,
+ idempotencyKey = null,
+ meta = {},
+ } = input;
+
+ if (idempotencyKey) {
+ const existing = await getHireByIdempotency(hirerAgentId, idempotencyKey);
+ if (existing) return { row: existing, existing: true };
+ }
+
+ try {
+ const [row] = await sql`
+ INSERT INTO agent_hires
+ (hirer_agent_id, hirer_user_id, provider_agent_id, provider_user_id,
+ service_id, service_slug, skill_name, amount_atomics, usd, currency,
+ network, status, payer_address, payout_address, spend_reservation_id,
+ idempotency_key, meta)
+ VALUES (
+ ${hirerAgentId}, ${hirerUserId}, ${providerAgentId}, ${providerUserId},
+ ${serviceId}, ${serviceSlug}, ${skillName}, ${String(amountAtomics)},
+ ${usd}, ${currency}, ${network}, 'pending', ${payerAddress},
+ ${payoutAddress}, ${spendReservationId}, ${idempotencyKey},
+ ${JSON.stringify(meta ?? {})}::jsonb
+ )
+ RETURNING *
+ `;
+ return { row, existing: false };
+ } catch (err) {
+ // 23505 = unique_violation on the idempotency index: a concurrent retry won
+ // the race. Return its row so neither caller double-pays.
+ if ((err?.code === '23505' || /duplicate key|unique/i.test(err?.message || '')) && idempotencyKey) {
+ const existing = await getHireByIdempotency(hirerAgentId, idempotencyKey);
+ if (existing) return { row: existing, existing: true };
+ }
+ throw err;
+ }
+}
+
+/** Flip a hire to its terminal state, attaching the real on-chain artifacts. */
+export async function updateHire(id, patch = {}) {
+ const completedAt = patch.status === 'completed' ? new Date().toISOString() : null;
+ const [row] = await sql`
+ UPDATE agent_hires
+ SET status = COALESCE(${patch.status ?? null}, status),
+ payment_signature = COALESCE(${patch.paymentSignature ?? null}, payment_signature),
+ invocation_signature = COALESCE(${patch.invocationSignature ?? null}, invocation_signature),
+ invocation_error = COALESCE(${patch.invocationError ?? null}, invocation_error),
+ payer_address = COALESCE(${patch.payerAddress ?? null}, payer_address),
+ result_summary = COALESCE(${patch.resultSummary ?? null}, result_summary),
+ error = COALESCE(${patch.error ?? null}, error),
+ completed_at = COALESCE(${completedAt}::timestamptz, completed_at),
+ meta = CASE WHEN ${patch.meta ? JSON.stringify(patch.meta) : null}::jsonb IS NULL
+ THEN meta ELSE meta || ${patch.meta ? JSON.stringify(patch.meta) : '{}'}::jsonb END,
+ updated_at = now()
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ return row || null;
+}
+
+/** Set the hirer's 1–5 rating on a completed hire (one rating, owner-gated). */
+export async function rateHire(id, hirerUserId, rating) {
+ const r = Math.round(Number(rating));
+ if (!Number.isFinite(r) || r < 1 || r > 5) {
+ const e = new Error('rating must be an integer 1–5');
+ e.code = 'invalid_rating';
+ e.status = 400;
+ throw e;
+ }
+ const [row] = await sql`
+ UPDATE agent_hires
+ SET rating = ${r}, rated_at = now(), updated_at = now()
+ WHERE id = ${id} AND hirer_user_id = ${hirerUserId} AND status = 'completed'
+ RETURNING *
+ `;
+ return row || null;
+}
+
+// ── Reads ─────────────────────────────────────────────────────────────────
+
+export async function getHireById(id) {
+ const [row] = await sql`SELECT * FROM agent_hires WHERE id = ${id} LIMIT 1`;
+ return row || null;
+}
+
+export async function getHireByIdempotency(hirerAgentId, idempotencyKey) {
+ if (!idempotencyKey) return null;
+ const [row] = await sql`
+ SELECT * FROM agent_hires
+ WHERE hirer_agent_id = ${hirerAgentId} AND idempotency_key = ${idempotencyKey}
+ LIMIT 1
+ `;
+ return row || null;
+}
+
+/**
+ * Live reputation + earnings for one provider agent, aggregated over its real
+ * completed hires. Every number is a true aggregate — there is no place to inject
+ * a fabricated stat.
+ */
+export async function providerStats(agentId) {
+ const [row] = await sql`
+ SELECT
+ COUNT(*) FILTER (WHERE status = 'completed') AS completed,
+ COUNT(*) FILTER (WHERE status = 'refunded') AS refunded,
+ COUNT(*) FILTER (WHERE status IN ('completed','refunded','disputed','failed')) AS total,
+ COALESCE(SUM(usd) FILTER (WHERE status = 'completed'), 0) AS earned_usd,
+ AVG(rating) FILTER (WHERE rating IS NOT NULL) AS avg_rating,
+ COUNT(rating) FILTER (WHERE rating IS NOT NULL) AS rating_count,
+ MAX(completed_at) AS last_hire_at,
+ COUNT(*) FILTER (WHERE status = 'completed' AND completed_at > now() - interval '24 hours') AS completed_24h
+ FROM agent_hires
+ WHERE provider_agent_id = ${agentId}
+ `;
+ return shapeStats(row);
+}
+
+function shapeStats(row) {
+ const completed = Number(row?.completed || 0);
+ const total = Number(row?.total || 0);
+ return {
+ completion_count: completed,
+ refunded_count: Number(row?.refunded || 0),
+ total_hires: total,
+ success_rate: total > 0 ? completed / total : null,
+ earned_usdc: Number(row?.earned_usd || 0),
+ avg_rating: row?.avg_rating != null ? Number(row.avg_rating) : null,
+ rating_count: Number(row?.rating_count || 0),
+ throughput_24h: Number(row?.completed_24h || 0),
+ last_hire_at: row?.last_hire_at || null,
+ };
+}
+
+/**
+ * The marketplace catalog: every active, bazaar-listed offer joined to its
+ * provider agent and its live hire stats. Offers from deleted / private agents
+ * are excluded. Sorted by real completion count then recency so proven providers
+ * surface first.
+ */
+export async function listOffersWithStats({ limit = 60, providerAgentId = null } = {}) {
+ const capped = Math.min(Math.max(1, Number(limit) || 60), 200);
+ const providerFilter = providerAgentId ? sql`AND s.agent_id = ${providerAgentId}` : sql``;
+ const rows = await sql`
+ SELECT
+ s.id AS service_id,
+ s.slug AS slug,
+ s.name AS name,
+ s.description AS description,
+ s.price_atomics AS price_atomics,
+ s.network AS network,
+ s.target_method AS method,
+ s.input_schema AS input_schema,
+ s.created_at AS created_at,
+ ai.id AS provider_agent_id,
+ ai.name AS provider_name,
+ ai.is_public AS provider_is_public,
+ ai.meta->>'solana_address' AS provider_addr,
+ av.thumbnail_key AS provider_thumb_key,
+ av.visibility AS provider_avatar_vis,
+ st.completed AS completed,
+ st.refunded AS refunded,
+ st.total AS total,
+ st.earned_usd AS earned_usd,
+ st.avg_rating AS avg_rating,
+ st.rating_count AS rating_count,
+ st.last_hire_at AS last_hire_at,
+ st.completed_24h AS completed_24h
+ FROM agent_paid_services s
+ JOIN agent_identities ai ON ai.id = s.agent_id AND ai.deleted_at IS NULL AND ai.is_public = true
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ LEFT JOIN LATERAL (
+ SELECT
+ COUNT(*) FILTER (WHERE status = 'completed') AS completed,
+ COUNT(*) FILTER (WHERE status = 'refunded') AS refunded,
+ COUNT(*) FILTER (WHERE status IN ('completed','refunded','disputed','failed')) AS total,
+ COALESCE(SUM(usd) FILTER (WHERE status = 'completed'), 0) AS earned_usd,
+ AVG(rating) FILTER (WHERE rating IS NOT NULL) AS avg_rating,
+ COUNT(rating) FILTER (WHERE rating IS NOT NULL) AS rating_count,
+ MAX(completed_at) AS last_hire_at,
+ COUNT(*) FILTER (WHERE status = 'completed' AND completed_at > now() - interval '24 hours') AS completed_24h
+ FROM agent_hires h WHERE h.service_id = s.id
+ ) st ON true
+ WHERE s.archived_at IS NULL AND s.bazaar_listed = true
+ ${providerFilter}
+ ORDER BY st.completed DESC NULLS LAST, s.created_at DESC
+ LIMIT ${capped}
+ `;
+ return rows.map(shapeOffer);
+}
+
+export async function getOfferBySlug(slug) {
+ const rows = await listOffersBySlug(slug);
+ return rows[0] || null;
+}
+
+async function listOffersBySlug(slug) {
+ const rows = await sql`
+ SELECT
+ s.id AS service_id, s.slug AS slug, s.name AS name, s.description AS description,
+ s.price_atomics AS price_atomics, s.network AS network, s.target_method AS method,
+ s.input_schema AS input_schema, s.created_at AS created_at,
+ ai.id AS provider_agent_id, ai.name AS provider_name, ai.is_public AS provider_is_public,
+ ai.meta->>'solana_address' AS provider_addr,
+ av.thumbnail_key AS provider_thumb_key, av.visibility AS provider_avatar_vis,
+ NULL::bigint AS completed, NULL::bigint AS refunded, NULL::bigint AS total,
+ NULL::float8 AS earned_usd, NULL::float8 AS avg_rating, NULL::bigint AS rating_count,
+ NULL::timestamptz AS last_hire_at, NULL::bigint AS completed_24h
+ FROM agent_paid_services s
+ JOIN agent_identities ai ON ai.id = s.agent_id AND ai.deleted_at IS NULL
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE s.slug = ${slug} AND s.archived_at IS NULL
+ LIMIT 1
+ `;
+ return rows.map(shapeOffer);
+}
+
+function shapeOffer(row) {
+ return {
+ service_id: row.service_id,
+ slug: row.slug,
+ name: row.name,
+ description: row.description,
+ price_atomics: String(row.price_atomics),
+ price_usdc: atomicsToUsdc(row.price_atomics),
+ network: row.network,
+ method: row.method,
+ input_schema: row.input_schema || null,
+ created_at: row.created_at,
+ provider: shapeProvider(row),
+ stats: shapeStats(row),
+ };
+}
+
+/**
+ * One agent's hire history for the accounting view. role='hirer' returns outlay,
+ * role='provider' returns income, role='all' returns both. Keyset paginated.
+ */
+export async function listHiresForAgent(agentId, { role = 'all', limit = 40, beforeId = null } = {}) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 40));
+ let roleFilter;
+ if (role === 'hirer') roleFilter = sql`h.hirer_agent_id = ${agentId}`;
+ else if (role === 'provider') roleFilter = sql`h.provider_agent_id = ${agentId}`;
+ else roleFilter = sql`(h.hirer_agent_id = ${agentId} OR h.provider_agent_id = ${agentId})`;
+
+ const cursor = beforeId
+ ? sql`AND h.created_at < (SELECT created_at FROM agent_hires WHERE id = ${beforeId})`
+ : sql``;
+
+ const rows = await sql`
+ SELECT
+ h.id, h.skill_name, h.service_slug, h.amount_atomics, h.usd, h.currency,
+ h.network, h.status, h.payment_signature, h.invocation_signature,
+ h.payer_address, h.payout_address, h.rating, h.created_at, h.completed_at,
+ h.hirer_agent_id, h.provider_agent_id,
+ hr.name AS hirer_name, pr.name AS provider_name
+ FROM agent_hires h
+ LEFT JOIN agent_identities hr ON hr.id = h.hirer_agent_id
+ LEFT JOIN agent_identities pr ON pr.id = h.provider_agent_id
+ WHERE ${roleFilter} ${cursor}
+ ORDER BY h.created_at DESC
+ LIMIT ${lim}
+ `;
+ return rows.map((r) => shapeHire(r, agentId));
+}
+
+function shapeHire(r, viewerAgentId) {
+ const isHirer = r.hirer_agent_id === viewerAgentId;
+ return {
+ id: r.id,
+ skill_name: r.skill_name,
+ service_slug: r.service_slug,
+ amount_atomics: String(r.amount_atomics),
+ usd: r.usd != null ? Number(r.usd) : atomicsToUsdc(r.amount_atomics),
+ currency: r.currency,
+ network: r.network,
+ status: r.status,
+ direction: isHirer ? 'outlay' : 'income',
+ counterparty: {
+ agent_id: isHirer ? r.provider_agent_id : r.hirer_agent_id,
+ name: (isHirer ? r.provider_name : r.hirer_name) || 'Agent',
+ },
+ payment_signature: r.payment_signature || null,
+ invocation_signature: r.invocation_signature || null,
+ payer_address: r.payer_address || null,
+ payout_address: r.payout_address || null,
+ rating: r.rating != null ? Number(r.rating) : null,
+ created_at: r.created_at,
+ completed_at: r.completed_at || null,
+ };
+}
+
+/** Roll-up totals for an agent's economy header: lifetime income + outlay. */
+export async function agentEconomySummary(agentId) {
+ const [row] = await sql`
+ SELECT
+ COALESCE(SUM(usd) FILTER (WHERE provider_agent_id = ${agentId} AND status = 'completed'), 0) AS income_usd,
+ COUNT(*) FILTER (WHERE provider_agent_id = ${agentId} AND status = 'completed') AS income_count,
+ COALESCE(SUM(usd) FILTER (WHERE hirer_agent_id = ${agentId} AND status = 'completed'), 0) AS outlay_usd,
+ COUNT(*) FILTER (WHERE hirer_agent_id = ${agentId} AND status = 'completed') AS outlay_count
+ FROM agent_hires
+ WHERE provider_agent_id = ${agentId} OR hirer_agent_id = ${agentId}
+ `;
+ return {
+ income_usdc: Number(row?.income_usd || 0),
+ income_count: Number(row?.income_count || 0),
+ outlay_usdc: Number(row?.outlay_usd || 0),
+ outlay_count: Number(row?.outlay_count || 0),
+ net_usdc: Number(row?.income_usd || 0) - Number(row?.outlay_usd || 0),
+ };
+}
diff --git a/api/_lib/agent-invocation-onchain.js b/api/_lib/agent-invocation-onchain.js
new file mode 100644
index 000000000..7460bd1a7
--- /dev/null
+++ b/api/_lib/agent-invocation-onchain.js
@@ -0,0 +1,173 @@
+/**
+ * On-chain agent-to-agent invocation receipts (the `agent_invocation` Anchor
+ * program — see contracts/agent-invocation/).
+ * ---------------------------------------------------------------------------
+ * When one agent hires and pays another for a skill, we record a verifiable
+ * receipt on Solana by invoking the program's `invoke_skill` instruction. The
+ * program is intentionally non-trust-bearing: it moves no funds and grants no
+ * capability — it validates the caller and emits a `SkillInvoked` event so the
+ * invocation is permanently auditable on-chain with an explorer link on both
+ * sides. The USDC payment itself already settled over the x402 rails; this is the
+ * tamper-proof record THAT it happened.
+ *
+ * The instruction is built by hand (Anchor discriminator + Borsh-encoded string
+ * args) so the API runtime doesn't have to load @coral-xyz/anchor — the same
+ * dependency-light approach as skill-license-onchain.js. PDA derivation and
+ * instruction encoding are pure and unit-tested; only `recordInvocationReceipt`
+ * touches the chain.
+ */
+
+import { createHash } from 'node:crypto';
+
+import {
+ PublicKey,
+ SystemProgram,
+ Transaction,
+ TransactionInstruction,
+ sendAndConfirmTransaction,
+} from '@solana/web3.js';
+
+import { solanaConnection } from './solana/connection.js';
+
+/** Program id baked into the on-chain program's `declare_id!`. Override per
+ * deployment (e.g. a devnet build) with AGENT_INVOCATION_PROGRAM_ID. */
+export const AGENT_INVOCATION_PROGRAM_ID =
+ process.env.AGENT_INVOCATION_PROGRAM_ID || 'AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo';
+
+// On-chain limits enforced by the program; validated here too so a caller gets a
+// clear error instead of a failed simulation. Must match contracts/agent-invocation.
+export const MAX_SKILL_NAME_LEN = 64;
+export const MAX_PARAMETERS_LEN = 512;
+
+// Seed prefix — must byte-match `AGENT_SEED` in contracts/agent-invocation/src/lib.rs.
+const AGENT_SEED = Buffer.from('agent');
+
+// Anchor instruction discriminator: sha256("global:invoke_skill")[..8].
+const INVOKE_SKILL_DISCRIMINATOR = createHash('sha256')
+ .update('global:invoke_skill')
+ .digest()
+ .subarray(0, 8);
+
+function programPk(programId) {
+ return programId instanceof PublicKey ? programId : new PublicKey(programId);
+}
+
+/** Derive an agent's program identity PDA from its authority — matches the Rust
+ * `seeds = [AGENT_SEED, authority]`. */
+export function deriveAgentPda(authority, programId = AGENT_INVOCATION_PROGRAM_ID) {
+ return PublicKey.findProgramAddressSync(
+ [AGENT_SEED, new PublicKey(authority).toBuffer()],
+ programPk(programId),
+ );
+}
+
+// Borsh string: 4-byte little-endian length prefix + UTF-8 bytes.
+function encodeBorshString(value) {
+ const bytes = Buffer.from(String(value), 'utf8');
+ const len = Buffer.alloc(4);
+ len.writeUInt32LE(bytes.length, 0);
+ return Buffer.concat([len, bytes]);
+}
+
+/**
+ * Build the unsigned `invoke_skill` instruction. Pure — no chain access — so the
+ * encoding and account ordering can be asserted directly in tests.
+ *
+ * @param {{ invokerAuthority: string|PublicKey, targetAuthority: string|PublicKey,
+ * skillName: string, parameters: string, programId?: string|PublicKey }} args
+ */
+export function buildInvokeSkillIx({ invokerAuthority, targetAuthority, skillName, parameters, programId = AGENT_INVOCATION_PROGRAM_ID }) {
+ if (!skillName || String(skillName).length === 0) {
+ throw new Error('skillName must not be empty');
+ }
+ if (Buffer.byteLength(String(skillName), 'utf8') > MAX_SKILL_NAME_LEN) {
+ throw new Error(`skillName exceeds ${MAX_SKILL_NAME_LEN} bytes`);
+ }
+ if (Buffer.byteLength(String(parameters ?? ''), 'utf8') > MAX_PARAMETERS_LEN) {
+ throw new Error(`parameters exceed ${MAX_PARAMETERS_LEN} bytes`);
+ }
+
+ const pid = programPk(programId);
+ const invokerAuth = new PublicKey(invokerAuthority);
+ const targetAuth = new PublicKey(targetAuthority);
+ const [invokerAgent] = deriveAgentPda(invokerAuth, pid);
+ const [targetAgent] = deriveAgentPda(targetAuth, pid);
+
+ const data = Buffer.concat([
+ INVOKE_SKILL_DISCRIMINATOR,
+ encodeBorshString(skillName),
+ encodeBorshString(parameters ?? ''),
+ ]);
+
+ // Account order must match the Rust `InvokeSkill` accounts struct exactly.
+ const keys = [
+ { pubkey: invokerAgent, isSigner: false, isWritable: false },
+ { pubkey: invokerAuth, isSigner: true, isWritable: true },
+ { pubkey: targetAuth, isSigner: false, isWritable: false },
+ { pubkey: targetAgent, isSigner: false, isWritable: false },
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
+ ];
+
+ return {
+ instruction: new TransactionInstruction({ programId: pid, keys, data }),
+ invokerAgent: invokerAgent.toBase58(),
+ targetAgent: targetAgent.toBase58(),
+ };
+}
+
+/**
+ * Write a real on-chain invocation receipt. The invoking agent's keypair signs
+ * and pays the (tiny) transaction fee; the target agent's authority is supplied
+ * so its agent PDA can be re-derived and recorded. Truncates oversized parameters
+ * to the program limit rather than failing the receipt.
+ *
+ * @param {{ invokerKeypair: import('@solana/web3.js').Keypair,
+ * targetAuthority: string|PublicKey, skillName: string, parameters?: string,
+ * network?: 'mainnet'|'devnet', programId?: string,
+ * connection?: import('@solana/web3.js').Connection }} args
+ * @returns {Promise<{ signature: string, programId: string, network: string,
+ * invokerAgent: string, targetAgent: string, explorer: string }>}
+ */
+export async function recordInvocationReceipt({
+ invokerKeypair,
+ targetAuthority,
+ skillName,
+ parameters = '',
+ network = process.env.AGENT_INVOCATION_NETWORK || 'mainnet',
+ programId = AGENT_INVOCATION_PROGRAM_ID,
+ connection,
+}) {
+ if (!invokerKeypair?.publicKey) throw new Error('invokerKeypair is required');
+ if (!targetAuthority) throw new Error('targetAuthority is required');
+
+ // Skill name capped to fit on-chain; long params trimmed to the byte limit.
+ const name = String(skillName || 'skill').slice(0, MAX_SKILL_NAME_LEN);
+ let params = String(parameters ?? '');
+ while (Buffer.byteLength(params, 'utf8') > MAX_PARAMETERS_LEN) {
+ params = params.slice(0, Math.floor(params.length * 0.9));
+ }
+
+ const { instruction, invokerAgent, targetAgent } = buildInvokeSkillIx({
+ invokerAuthority: invokerKeypair.publicKey,
+ targetAuthority,
+ skillName: name,
+ parameters: params,
+ programId,
+ });
+
+ const conn = connection || solanaConnection({ network, commitment: 'confirmed' });
+ const tx = new Transaction().add(instruction);
+ const signature = await sendAndConfirmTransaction(conn, tx, [invokerKeypair], {
+ commitment: 'confirmed',
+ });
+
+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';
+ return {
+ signature,
+ programId: programPk(programId).toBase58(),
+ network,
+ invokerAgent,
+ targetAgent,
+ explorer: `https://solscan.io/tx/${signature}${cluster}`,
+ };
+}
diff --git a/api/_lib/agent-mirror.js b/api/_lib/agent-mirror.js
index 9732f5eb7..77e76ce54 100644
--- a/api/_lib/agent-mirror.js
+++ b/api/_lib/agent-mirror.js
@@ -256,7 +256,7 @@ async function runFollowerTrade({
agentId: id, userId: ownerId, reason: `mirror_${side}`,
meta: { mint, network, custody_event_id: claimId, leader_agent_id: leaderRef?.leader_agent_id || null },
});
- } catch (e) {
+ } catch {
await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});
return { status: 'failed', code: 'key_recover_failed' };
}
diff --git a/api/_lib/agent-recovery.js b/api/_lib/agent-recovery.js
index 1cae0f95f..7957ce34a 100644
--- a/api/_lib/agent-recovery.js
+++ b/api/_lib/agent-recovery.js
@@ -825,3 +825,93 @@ export async function confirmInheritance({ agentId, requestId, actorId, req = nu
const [fresh] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId}`;
return decorateRequest(fresh, agentId);
}
+
+// ── cron sweep: dead-man evaluation + completion + expiry ───────────────────────
+
+const DEAD_MAN_REMINDER_WINDOW_MS = 7 * DAY_MS; // warn 7 days before the switch arms
+
+/**
+ * Mark any request that never reached its approval threshold within the TTL as
+ * expired, and lift the freeze we applied. Keeps a stalled impostor attempt from
+ * freezing a wallet forever.
+ */
+export async function expireStaleRequests() {
+ const cutoff = new Date(Date.now() - RECOVERY_REQUEST_TTL_MS).toISOString();
+ const stale = await sql`
+ SELECT id, agent_id FROM agent_recovery_requests
+ WHERE status = 'pending_approvals' AND created_at < ${cutoff}
+ `;
+ for (const r of stale) {
+ await sql`UPDATE agent_recovery_requests SET status = 'expired', updated_at = now(), completed_at = now() WHERE id = ${r.id} AND status = 'pending_approvals'`;
+ await unfreezeForRequest(r.agent_id, r.id, null);
+ await recordCustodyEvent({ agentId: r.agent_id, userId: null, eventType: 'recovery_cancel', reason: 'expired', meta: { request_id: r.id } }).catch(() => {});
+ await notifyParties(r.agent_id, 'recovery_expired', { request_id: r.id }).catch(() => {});
+ }
+ return stale.length;
+}
+
+/**
+ * One full dead-man's-switch sweep, safe to run on a cron:
+ * 1. expire stalled requests,
+ * 2. arm inheritance for agents whose owner crossed the inactivity threshold,
+ * 3. send an early "tap I'm here" reminder to owners approaching the threshold,
+ * 4. complete inheritance requests whose grace window elapsed with confirmation.
+ * Returns a summary of what it did. Each agent is isolated — one failure never
+ * stops the sweep.
+ */
+export async function runDeadManSweep({ now = Date.now() } = {}) {
+ const summary = { expired: 0, armed: 0, reminded: 0, completed: 0, errors: 0 };
+
+ summary.expired = await expireStaleRequests().catch(() => 0);
+
+ // Agents with the switch enabled.
+ const agents = await sql`
+ SELECT id, user_id, name, meta FROM agent_identities
+ WHERE deleted_at IS NULL AND (meta->'recovery'->'dead_man'->>'enabled') = 'true'
+ `;
+ for (const agent of agents) {
+ try {
+ const cfg = getRecoveryConfig(agent.meta);
+ if (!cfg.dead_man.enabled) continue;
+ const active = await getActiveRequest(agent.id);
+ const { lastActiveAt } = await getOwnerActivity(agent.id, agent.user_id, agent.meta);
+ const dm = deadManStatus(cfg, lastActiveAt, now);
+
+ if (dm.eligible_to_arm && !active) {
+ const armed = await armInheritance({ agentId: agent.id, actorId: null });
+ if (armed) summary.armed++;
+ } else if (!active && dm.ms_until_arm > 0 && dm.ms_until_arm <= DEAD_MAN_REMINDER_WINDOW_MS) {
+ // Approaching — remind the owner at most once per window.
+ const lastReminder = agent.meta?.recovery?.dead_man?.last_reminder_at;
+ const remindedRecently = lastReminder && now - new Date(lastReminder).getTime() < DEAD_MAN_REMINDER_WINDOW_MS;
+ if (!remindedRecently) {
+ insertNotification(agent.user_id, 'dead_man_reminder', { agent_id: agent.id, agent_name: agent.name, arm_at: dm.arm_at, days_left: Math.ceil(dm.ms_until_arm / DAY_MS) });
+ const meta = { ...(agent.meta || {}) };
+ const baseCfg = getRecoveryConfig(meta);
+ meta.recovery = { ...baseCfg, dead_man: { ...baseCfg.dead_man, last_reminder_at: new Date(now).toISOString() } };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agent.id}`.catch(() => {});
+ summary.reminded++;
+ }
+ }
+ } catch (e) {
+ summary.errors++;
+ console.error('[dead-man] sweep failed for agent', agent.id, e?.message);
+ }
+ }
+
+ // Complete inheritance requests whose grace elapsed with confirmation.
+ const ready = await sql`
+ SELECT id, agent_id FROM agent_recovery_requests
+ WHERE kind = 'inheritance' AND status IN ('time_locked', 'ready')
+ `;
+ for (const r of ready) {
+ try {
+ const out = await completeIfReady({ agentId: r.agent_id, requestId: r.id, actorId: null });
+ if (out?.transferred) summary.completed++;
+ } catch {
+ // not_ready / awaiting_beneficiary — expected for requests still in grace.
+ }
+ }
+
+ return summary;
+}
diff --git a/api/_lib/agent-trade-exec.js b/api/_lib/agent-trade-exec.js
deleted file mode 100644
index 28b52494f..000000000
--- a/api/_lib/agent-trade-exec.js
+++ /dev/null
@@ -1,508 +0,0 @@
-// Reusable custodial trade executor — the server-side engine behind autonomous
-// trade paths (the Mirror / Copy-Trade social graph, task 09).
-//
-// api/agents/solana-trade.js is the OWNER-DRIVEN, HTTP-coupled discretionary path
-// (preview + rich response shaping + req/res). It cannot be called server-to-server
-// by a cron fanout. This module is its autonomous sibling: the SAME shared spend
-// guardrails (api/_lib/agent-trade-guards.js), the SAME rug/honeypot firewall, the
-// SAME idempotent custody ledger, the SAME MEV-aware execution engine — exposed as
-// a plain async function that returns a structured result instead of writing HTTP.
-//
-// executeCustodialTrade({ agentId, userId, meta, side, mint, solAmount,
-// tokenAmountRaw, slippageBps, network, source,
-// idempotencyKey, extraMeta })
-// → { ok, code, message, detail, skip, signature, explorer, usd, ... }
-//
-// The pump.fun instruction builders + live-quote logic intentionally mirror
-// solana-trade.js (which itself mirrors api/agents/pumpfun/[action].js) so the
-// "how do we price + build a trade" convention has a consistent shape across paths;
-// the "is this trade allowed" math has exactly ONE home in agent-trade-guards.js
-// and is imported, never re-implemented.
-//
-// Hard rules honoured: the key is decrypted only via recoverSolanaAgentKeypair,
-// only after the guard gauntlet passes, always audit-logged; guard rejections are
-// structured (never thrown 500s) so the caller can record an honest skip reason; a
-// retried idempotency key never double-spends. $THREE is the only coin three.ws
-// promotes — this is coin-agnostic plumbing that trades whatever mint it's given.
-
-import { sql } from './db.js';
-import { recoverSolanaAgentKeypair } from './agent-wallet.js';
-import { solanaConnection, solanaPublicConnection } from './agent-pumpfun.js';
-import { PublicKey } from '@solana/web3.js';
-import { cacheSet } from './cache.js';
-import { logAudit } from './audit.js';
-import { explorerTxUrl } from './avatar-wallet.js';
-import {
- enforceSpendLimit, SpendLimitError, getSpendLimits, updateCustodyEvent, lamportsToUsd,
- getTradeLimits, getDailySpendLamports,
- checkKillSwitch, checkPerTradeCap, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,
- SOL_FEE_HEADROOM_LAMPORTS,
-} from './agent-trade-guards.js';
-import {
- slippagePercentFromBps, resolveCustodialQuote, resolveTokenProgramForMintOwner, WSOL_MINT,
-} from './pump-trade-args.js';
-import { getBuyQuote, getSellQuote } from './solana/sdk-bridge.js';
-import { getAmmPoolState } from './pump.js';
-import { assessTradeSafety, recordFirewallDecision } from './trade-firewall.js';
-import { submitProtected } from './execution-engine.js';
-
-const LAMPORTS_PER_SOL = 1_000_000_000;
-const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
-
-function netOf(v) { return v === 'devnet' ? 'devnet' : 'mainnet'; }
-function lamportsToSol(l) { return Number(BigInt(l)) / LAMPORTS_PER_SOL; }
-
-function applySlippageFloor(amountBase, slippageBps) {
- const a = BigInt(amountBase);
- const bps = BigInt(Math.max(0, Math.min(10_000, slippageBps)));
- return (a * (10_000n - bps)) / 10_000n;
-}
-
-async function resolveMintDecimals(conn, mintPk) {
- try {
- const info = await conn.getParsedAccountInfo(mintPk);
- const dec = info?.value?.data?.parsed?.info?.decimals;
- if (Number.isInteger(dec)) return dec;
- } catch { /* fall through */ }
- return 6;
-}
-
-// Sum the owner's full SPL balance for a mint, across both token programs, in base
-// units. Used to mirror a leader's EXIT: when the leader sells, the follower sells
-// its entire position in that mint (a conservative, honest "leader out → you out").
-async function resolveTokenBalanceRaw(conn, ownerPk, mintPk) {
- let total = 0n;
- for (const programId of [
- new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'),
- new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'),
- ]) {
- try {
- const res = await conn.getParsedTokenAccountsByOwner(ownerPk, { mint: mintPk, programId });
- for (const { account } of res.value) {
- const amt = account?.data?.parsed?.info?.tokenAmount?.amount;
- if (amt) total += BigInt(amt);
- }
- } catch { /* program may not own any account; ignore */ }
- }
- return total;
-}
-
-function typed(status, code, message) {
- const e = new Error(message);
- e.status = status; e.code = code;
- return e;
-}
-
-function clampImpact(v) {
- const n = Number(v);
- return Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0;
-}
-
-function derivePriceImpact(inReserve, outReserve, inAmt, out) {
- const ir = Number(inReserve?.toString?.() ?? inReserve ?? 0);
- const or = Number(outReserve?.toString?.() ?? outReserve ?? 0);
- const a = Number(inAmt?.toString?.() ?? inAmt ?? 0);
- const o = Number(out ?? 0);
- if (!(ir > 0) || !(or > 0) || !(a > 0)) return 0;
- const spotOut = (a * or) / ir;
- if (!(spotOut > 0)) return 0;
- const impact = ((spotOut - o) / spotOut) * 100;
- return Number.isFinite(impact) ? Math.max(0, Math.min(100, impact)) : 0;
-}
-
-async function loadAmm(network, mintPk) {
- const amm = await getAmmPoolState({ network, mint: mintPk });
- const resolvedQuote = amm.pool.quoteMint?.toString?.() ?? WSOL_MINT;
- if (resolvedQuote !== WSOL_MINT) {
- throw typed(409, 'unsupported_quote', 'this coin trades against a non-SOL asset');
- }
- return amm;
-}
-
-// Live quote — bonding curve first, AMM pool for graduated coins. Pure read.
-export async function quoteTrade({ conn, side, mintPk, mintStr, network, solAmount, tokenAmountRaw, slippageBps }) {
- if (side === 'buy') {
- const lamportsIn = BigInt(Math.floor(Number(solAmount) * LAMPORTS_PER_SOL));
- if (lamportsIn <= 0n) throw typed(400, 'amount_too_small', 'enter a SOL amount greater than zero');
-
- const curve = await getBuyQuote(conn, mintStr, lamportsIn.toString());
- if (curve && curve.tokens) {
- const decimals = await resolveMintDecimals(conn, mintPk);
- const tokensOut = BigInt(curve.tokens.toString());
- if (tokensOut <= 0n) throw typed(400, 'amount_too_small', 'that SOL amount is too small to buy any tokens');
- return {
- venue: 'bonding_curve', graduated: false, quoteAsset: 'SOL',
- inAsset: 'SOL', inAmount: Number(solAmount), inAtomics: lamportsIn.toString(),
- outAsset: 'TOKEN', outAtomics: tokensOut.toString(), outUi: Number(tokensOut) / 10 ** decimals,
- minOutAtomics: applySlippageFloor(tokensOut, slippageBps).toString(),
- minOutUi: Number(applySlippageFloor(tokensOut, slippageBps)) / 10 ** decimals,
- decimals, priceImpactPct: clampImpact(curve.priceImpact),
- };
- }
-
- const amm = await loadAmm(network, mintPk);
- const sdk = await import('@pump-fun/pump-swap-sdk');
- const r = sdk.buyQuoteInput({
- quote: new amm.BN(lamportsIn.toString()), slippage: slippagePercentFromBps(slippageBps),
- baseReserve: amm.baseReserve, quoteReserve: amm.quoteReserve, globalConfig: amm.globalConfig,
- baseMintAccount: amm.baseMintAccount, baseMint: amm.pool.baseMint,
- coinCreator: amm.pool.coinCreator, creator: amm.pool.creator, feeConfig: amm.feeConfig,
- });
- const decimals = await resolveMintDecimals(conn, mintPk);
- const tokensOut = BigInt((r.base ?? 0).toString());
- if (tokensOut <= 0n) throw typed(400, 'amount_too_small', 'that SOL amount is too small to buy any tokens');
- return {
- venue: 'amm', graduated: true, quoteAsset: 'SOL', poolKey: amm.poolKey.toString(),
- inAsset: 'SOL', inAmount: Number(solAmount), inAtomics: lamportsIn.toString(),
- outAsset: 'TOKEN', outAtomics: tokensOut.toString(), outUi: Number(tokensOut) / 10 ** decimals,
- minOutAtomics: applySlippageFloor(tokensOut, slippageBps).toString(),
- minOutUi: Number(applySlippageFloor(tokensOut, slippageBps)) / 10 ** decimals,
- decimals, priceImpactPct: derivePriceImpact(amm.quoteReserve, amm.baseReserve, lamportsIn, tokensOut),
- };
- }
-
- // SELL — amount is token base units.
- const baseUnits = BigInt(tokenAmountRaw);
- if (baseUnits <= 0n) throw typed(400, 'amount_too_small', 'enter a token amount greater than zero');
- const decimals = await resolveMintDecimals(conn, mintPk);
-
- const curve = await getSellQuote(conn, mintStr, baseUnits.toString());
- if (curve && curve.sol) {
- const lamportsOut = BigInt(curve.sol.toString());
- return {
- venue: 'bonding_curve', graduated: false, quoteAsset: 'SOL',
- inAsset: 'TOKEN', inAtomics: baseUnits.toString(), inUi: Number(baseUnits) / 10 ** decimals,
- outAsset: 'SOL', outAtomics: lamportsOut.toString(), outUi: lamportsToSol(lamportsOut),
- minOutAtomics: applySlippageFloor(lamportsOut, slippageBps).toString(),
- minOutUi: lamportsToSol(applySlippageFloor(lamportsOut, slippageBps)),
- decimals, priceImpactPct: clampImpact(curve.priceImpact),
- };
- }
-
- const amm = await loadAmm(network, mintPk);
- const sdk = await import('@pump-fun/pump-swap-sdk');
- const r = sdk.sellBaseInput({
- base: new amm.BN(baseUnits.toString()), slippage: slippagePercentFromBps(slippageBps),
- baseReserve: amm.baseReserve, quoteReserve: amm.quoteReserve, globalConfig: amm.globalConfig,
- baseMintAccount: amm.baseMintAccount, baseMint: amm.pool.baseMint,
- coinCreator: amm.pool.coinCreator, creator: amm.pool.creator, feeConfig: amm.feeConfig,
- });
- const lamportsOut = BigInt((r.uiQuote ?? r.minQuote ?? 0).toString());
- const minLamportsOut = BigInt((r.minQuote ?? r.uiQuote ?? 0).toString());
- return {
- venue: 'amm', graduated: true, quoteAsset: 'SOL', poolKey: amm.poolKey.toString(),
- inAsset: 'TOKEN', inAtomics: baseUnits.toString(), inUi: Number(baseUnits) / 10 ** decimals,
- outAsset: 'SOL', outAtomics: lamportsOut.toString(), outUi: lamportsToSol(lamportsOut),
- minOutAtomics: minLamportsOut.toString(), minOutUi: lamportsToSol(minLamportsOut),
- decimals, priceImpactPct: derivePriceImpact(amm.baseReserve, amm.quoteReserve, baseUnits, lamportsOut),
- };
-}
-
-// Build the on-chain instructions for the resolved venue + side. Curve trades use
-// the pump-sdk v2 builders; graduated trades use the pump-swap AMM SDK.
-async function buildTradeInstructions({ side, conn, network, mintPk, ownerPk, quote, slippageBps, solAmount, tokenAmountRaw }) {
- const BNmod = (await import('bn.js')).default;
-
- if (quote.venue === 'bonding_curve') {
- const { PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount, getSellSolAmountFromTokenAmount } =
- await import('@pump-fun/pump-sdk');
- const online = new OnlinePumpSdk(conn);
- const sdk = new PumpSdk();
- const mintInfo = await conn.getAccountInfo(mintPk);
- if (!mintInfo) throw typed(404, 'mint_not_found', 'mint not found on this network');
- const tokenProgram = resolveTokenProgramForMintOwner(mintInfo.owner);
-
- if (side === 'buy') {
- const [global, feeConfig, state] = await Promise.all([
- online.fetchGlobal(), online.fetchFeeConfig().catch(() => null),
- online.fetchBuyState(mintPk, ownerPk, tokenProgram),
- ]);
- const qa = resolveCustodialQuote(state.bondingCurve?.quoteMint, network);
- if (!qa.isSol) throw typed(409, 'unsupported_quote', 'this coin trades against a non-SOL asset');
- const quoteAtomics = new BNmod(Math.floor(Number(solAmount) * LAMPORTS_PER_SOL));
- const expected = getBuyTokenAmountFromSolAmount({ global, feeConfig, mintSupply: state.bondingCurve.tokenTotalSupply, bondingCurve: state.bondingCurve, amount: quoteAtomics });
- if (!expected.gt(new BNmod(0))) throw typed(400, 'amount_too_small', 'that SOL amount is too small to buy any tokens');
- return sdk.buyV2Instructions({
- global, bondingCurveAccountInfo: state.bondingCurveAccountInfo, bondingCurve: state.bondingCurve,
- associatedUserAccountInfo: state.associatedUserAccountInfo, mint: mintPk, user: ownerPk,
- amount: expected, quoteAmount: quoteAtomics, slippage: slippagePercentFromBps(slippageBps), tokenProgram,
- });
- }
- const [global, feeConfig, state] = await Promise.all([
- online.fetchGlobal(), online.fetchFeeConfig().catch(() => null),
- online.fetchSellState(mintPk, ownerPk, tokenProgram),
- ]);
- const qa = resolveCustodialQuote(state.bondingCurve?.quoteMint, network);
- if (!qa.isSol) throw typed(409, 'unsupported_quote', 'this coin trades against a non-SOL asset');
- const tokens = new BNmod(tokenAmountRaw);
- const expectedQuote = getSellSolAmountFromTokenAmount({ global, feeConfig, mintSupply: state.bondingCurve.tokenTotalSupply, bondingCurve: state.bondingCurve, amount: tokens });
- return sdk.sellV2Instructions({
- global, bondingCurveAccountInfo: state.bondingCurveAccountInfo, bondingCurve: state.bondingCurve,
- mint: mintPk, user: ownerPk, amount: tokens, quoteAmount: expectedQuote,
- slippage: slippagePercentFromBps(slippageBps), tokenProgram,
- });
- }
-
- const { PumpAmmSdk, OnlinePumpAmmSdk, canonicalPumpPoolPda } = await import('@pump-fun/pump-swap-sdk');
- const amm = new PumpAmmSdk();
- const online = new OnlinePumpAmmSdk(conn);
- const poolKey = canonicalPumpPoolPda(mintPk);
- const swapState = await online.swapSolanaState(poolKey, ownerPk).catch(() => online.swapSolanaStateNoPool(poolKey, ownerPk));
- const slippage = slippagePercentFromBps(slippageBps);
- if (side === 'buy') {
- return amm.buyQuoteInput(swapState, new BNmod(BigInt(quote.inAtomics).toString()), slippage);
- }
- return amm.sellBaseInput(swapState, new BNmod(tokenAmountRaw), slippage);
-}
-
-function fail(code, message, { skip = false, detail = null } = {}) {
- return { ok: false, skip, code, message, detail };
-}
-
-/**
- * Execute a real custodial trade for an agent, server-side, fully guarded.
- *
- * Returns a structured result — never throws for an expected rejection (a guard
- * breach, insufficient funds, a firewall block, a missing position). Those come
- * back as { ok:false, skip:true, code, message } so an autonomous caller can log
- * an honest skip reason and keep its subscription alive. Only genuinely
- * unexpected internal failures bubble up.
- *
- * @param {object} p
- * @param {string} p.agentId follower agent id
- * @param {string} p.userId owner user id (for custody/audit attribution)
- * @param {object} p.meta agent_identities.meta (wallet keys + spend policy)
- * @param {'buy'|'sell'} p.side
- * @param {string} p.mint base58 mint
- * @param {number} [p.solAmount] buy: SOL to spend
- * @param {string} [p.tokenAmountRaw] sell: token base units, or 'max' for full position
- * @param {number} [p.slippageBps]
- * @param {string} [p.network]
- * @param {string} [p.source] recorded in custody meta + audit (e.g. 'mirror')
- * @param {string} p.idempotencyKey required — dedupes retries
- * @param {object} [p.extraMeta] merged into the custody event meta + audit meta
- */
-export async function executeCustodialTrade({
- agentId, userId, meta, side, mint, solAmount, tokenAmountRaw,
- slippageBps = 300, network = 'mainnet', source = 'auto', idempotencyKey, extraMeta = {},
-}) {
- network = netOf(network);
- side = side === 'sell' ? 'sell' : 'buy';
- if (!idempotencyKey) return fail('validation_error', 'idempotency_key is required');
- if (typeof mint !== 'string' || !BASE58_RE.test(mint)) return fail('validation_error', 'mint must be a base58 Solana address');
- if (mint === WSOL_MINT) return fail('validation_error', 'cannot trade wrapped SOL as a token');
-
- let mintPk, ownerPk;
- try { mintPk = new PublicKey(mint); } catch { return fail('validation_error', 'mint is not a valid Solana address'); }
-
- const address = meta?.solana_address || null;
- const encryptedSecret = meta?.encrypted_solana_secret || null;
- if (!address || !encryptedSecret) return fail('wallet_preparing', 'the agent wallet is still being prepared', { skip: true });
- try { ownerPk = new PublicKey(address); } catch { return fail('wallet_preparing', 'the agent wallet is still being prepared', { skip: true }); }
-
- const idem = String(idempotencyKey).slice(0, 128);
- const readConn = solanaConnection(network);
-
- // Resolve a 'max' sell to the full on-chain position now (mirroring a leader exit).
- if (side === 'sell') {
- if (tokenAmountRaw === 'max' || tokenAmountRaw == null) {
- const bal = await resolveTokenBalanceRaw(readConn, ownerPk, mintPk).catch(() => 0n);
- if (bal <= 0n) return fail('no_position', 'the follower holds none of this token to mirror the exit', { skip: true });
- tokenAmountRaw = bal.toString();
- } else if (!/^\d+$/.test(String(tokenAmountRaw)) || BigInt(String(tokenAmountRaw)) <= 0n) {
- return fail('validation_error', 'token_amount_raw must be a positive base-unit integer');
- }
- } else if (!(Number(solAmount) > 0)) {
- return fail('amount_too_small', 'sol amount must be greater than zero', { skip: true });
- }
-
- const bps = Math.max(0, Math.min(5_000, Math.round(Number(slippageBps) || 300)));
-
- // 1. Quote.
- let quote;
- try {
- quote = await quoteTrade({ conn: readConn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps: bps });
- } catch (e) {
- if (e?.code === 'pool_not_found') return fail('no_market', 'no bonding curve or AMM pool found for this mint', { skip: true });
- if (e?.status) return fail(e.code || 'quote_failed', e.message, { skip: true });
- return fail('quote_failed', 'could not price this trade right now', { skip: true });
- }
-
- // USD value of the SOL leg (best-effort).
- let usdValue = null;
- try {
- const lamports = side === 'buy' ? BigInt(quote.inAtomics) : BigInt(quote.outAtomics);
- usdValue = await lamportsToUsd(lamports);
- } catch { usdValue = null; }
-
- const limitsCfg = getSpendLimits(meta);
- const tradeLimits = getTradeLimits(meta);
-
- // 2. Guards — identical predicates to the owner-driven path. The kill switch +
- // price-impact breaker apply both directions; SOL caps gate only a buy.
- const killed = checkKillSwitch(tradeLimits.kill_switch);
- if (killed) return fail('trading_paused', 'trading is paused for this agent', { skip: true, detail: {} });
-
- if (side === 'buy') {
- const lamportsIn = BigInt(quote.inAtomics);
-
- const capLamports = tradeLimits.per_trade_sol == null ? null : BigInt(Math.floor(tradeLimits.per_trade_sol * LAMPORTS_PER_SOL));
- const cap = checkPerTradeCap(lamportsIn, capLamports);
- if (cap) return fail('per_trade_cap', `over the per-trade cap of ◎${tradeLimits.per_trade_sol}`, { skip: true, detail: cap.detail });
-
- if (tradeLimits.daily_budget_sol != null) {
- const budgetLamports = BigInt(Math.floor(tradeLimits.daily_budget_sol * LAMPORTS_PER_SOL));
- const spent = await getDailySpendLamports(agentId, network);
- const budget = checkDailyBudgetLamports(spent, lamportsIn, budgetLamports);
- if (budget) return fail('daily_budget', `over the ◎${tradeLimits.daily_budget_sol} daily budget`, { skip: true, detail: budget.detail });
- }
-
- try {
- await enforceSpendLimit({ agentId, limits: limitsCfg, category: 'trade', usdValue, network });
- } catch (e) {
- if (e instanceof SpendLimitError) return fail(e.code, e.message, { skip: true, detail: e.detail });
- throw e;
- }
- }
-
- // Price-impact circuit breaker — both directions.
- {
- const impact = checkPriceImpact(quote.priceImpactPct, tradeLimits.max_price_impact_pct);
- if (impact) return fail('price_impact_too_high', `price impact ${quote.priceImpactPct.toFixed(1)}% over the ${tradeLimits.max_price_impact_pct}% limit`, { skip: true, detail: impact.detail });
- }
-
- // 3. Rug/honeypot firewall — a REAL on-chain simulated round-trip, buys only.
- if (side === 'buy') {
- const assessment = await assessTradeSafety({
- network, mint: mintPk, side: 'buy', payer: ownerPk,
- quoteAmount: BigInt(quote.inAtomics), priceImpactPct: quote.priceImpactPct,
- }).catch(() => null);
- if (assessment) {
- recordFirewallDecision({
- mint, network, side: 'buy', verdict: assessment.verdict, score: assessment.score,
- simulated: assessment.simulated, checks: assessment.checks, reasons: assessment.reasons,
- source, agentId, userId, quoteLamports: BigInt(quote.inAtomics), enforced: assessment.verdict === 'block',
- }).catch(() => {});
- if (assessment.verdict === 'block') {
- return fail('firewall_blocked', assessment.reasons?.[0] || 'blocked by the safety firewall', { skip: true, detail: { score: assessment.score, reasons: assessment.reasons } });
- }
- }
- }
-
- // 4. SOL headroom / balance check (real on-chain balance).
- let walletLamports = null;
- try { walletLamports = BigInt(await readConn.getBalance(ownerPk, 'confirmed')); }
- catch {
- try { walletLamports = BigInt(await solanaPublicConnection(network).getBalance(ownerPk, 'confirmed')); }
- catch { walletLamports = null; }
- }
- if (walletLamports != null) {
- const spendLamports = side === 'buy' ? BigInt(quote.inAtomics) : 0n;
- const head = checkSolHeadroom(walletLamports, spendLamports, SOL_FEE_HEADROOM_LAMPORTS);
- if (head) return fail(side === 'buy' ? 'insufficient_sol' : 'insufficient_sol_for_fees', 'the wallet lacks SOL for this trade plus fees', { skip: true, detail: head.detail });
- }
-
- // 5. Idempotency fast-path.
- const [prior] = await sql`
- SELECT status, signature FROM agent_custody_events
- WHERE agent_id = ${agentId} AND idempotency_key = ${idem} LIMIT 1
- `;
- if (prior) {
- if (prior.status === 'confirmed' && prior.signature) {
- return { ok: true, replayed: true, signature: prior.signature, explorer: explorerTxUrl(prior.signature, network), side, mint, network, venue: quote.venue, usd: usdValue };
- }
- if (prior.status === 'pending') return fail('trade_in_progress', 'a trade with this id is already in flight');
- return fail('trade_failed', 'this trade id already failed');
- }
-
- // 6. Claim the idempotency slot (also the spend-ledger row). A buy counts toward
- // the daily ceiling (usd set); a sell records usd=null so it never inflates spend.
- const claimMeta = {
- side, mint, venue: quote.venue, source,
- expected_out_atomics: quote.outAtomics, min_out_atomics: quote.minOutAtomics,
- slippage_bps: bps, price_impact_pct: quote.priceImpactPct, ...extraMeta,
- };
- const claim = await sql`
- INSERT INTO agent_custody_events
- (agent_id, user_id, event_type, category, network, asset,
- amount_lamports, amount_raw, usd, status, idempotency_key, meta)
- VALUES (
- ${agentId}, ${userId}, 'spend', 'trade', ${network},
- ${side === 'buy' ? 'SOL' : mint},
- ${side === 'buy' ? quote.inAtomics : null},
- ${side === 'sell' ? quote.inAtomics : null},
- ${side === 'buy' ? usdValue ?? null : null},
- 'pending', ${idem},
- ${JSON.stringify(claimMeta)}::jsonb
- )
- ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
- RETURNING id
- `;
- if (!claim.length) return fail('trade_in_progress', 'a trade with this id is already in flight');
- const claimId = claim[0].id;
-
- // 7. Recover the signing key (audit-logged) and build the instructions.
- let keypair;
- try {
- keypair = await recoverSolanaAgentKeypair(encryptedSecret, {
- agentId, userId, reason: `${source}_trade_${side}`,
- meta: { mint, network, custody_event_id: claimId, venue: quote.venue, source },
- });
- } catch (e) {
- await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});
- return fail('key_recover_failed', 'could not access the agent wallet key — no funds were moved');
- }
-
- let instructions;
- try {
- instructions = await buildTradeInstructions({ side, conn: readConn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps: bps, solAmount, tokenAmountRaw });
- } catch (e) {
- await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'build_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});
- return fail(e?.code || 'build_failed', e?.message || 'could not build this trade — the market may have moved', { skip: true });
- }
-
- // 8. Broadcast + confirm through the MEV-aware execution engine (protected single-tx,
- // no Jito tip — autonomous mirrors don't run a per-strategy tip policy).
- const signConn = solanaConnection(network);
- let signature, confirmed = true, execTelemetry = null;
- try {
- const result = await submitProtected({
- network, connection: signConn, payer: keypair, instructions,
- opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },
- });
- signature = result.signature;
- execTelemetry = { route: result.route, priority_fee_microlamports: result.priorityFeeMicroLamports, landed_ms: result.landedMs, attempts: result.attempts };
- } catch (e) {
- if (e?.code === 'TX_ERR') { signature = e.signature || null; confirmed = false; }
- else {
- await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'send_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});
- logAudit({ userId, action: 'custody.trade_failed', resourceId: agentId, meta: { side, mint, reason: 'send_failed', source, ...extraMeta } });
- return fail('send_failed', 'the trade could not be submitted and no funds were moved');
- }
- }
-
- if (!confirmed) {
- await updateCustodyEvent(claimId, { signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});
- logAudit({ userId, action: 'custody.trade_unconfirmed', resourceId: agentId, meta: { side, mint, signature, source, ...extraMeta } });
- return fail('trade_unconfirmed', 'the trade was submitted but not yet confirmed', { detail: { signature, explorer: explorerTxUrl(signature, network) } });
- }
-
- await updateCustodyEvent(claimId, {
- status: 'confirmed', signature, usd: side === 'buy' ? usdValue ?? null : null,
- meta: execTelemetry ? { exec: execTelemetry } : undefined,
- }).catch(() => {});
- logAudit({ userId, action: 'custody.trade', resourceId: agentId, meta: { side, mint, venue: quote.venue, usd: usdValue, signature, network, exec_route: execTelemetry?.route, source, ...extraMeta } });
-
- await cacheSet(`sol:bal:${address}:${network}`, null, 1).catch(() => {});
-
- return {
- ok: true, replayed: false, signature, explorer: explorerTxUrl(signature, network),
- side, mint, network, venue: quote.venue, usd: usdValue,
- custodyEventId: claimId,
- sol_spent: side === 'buy' ? lamportsToSol(quote.inAtomics) : null,
- sol_received: side === 'sell' ? lamportsToSol(quote.outAtomics) : null,
- tokens_received: side === 'buy' ? quote.outAtomics : null,
- tokens_sold: side === 'sell' ? quote.inAtomics : null,
- price_impact_pct: quote.priceImpactPct,
- };
-}
diff --git a/api/_lib/migrations/20260623100000_mirror_social.sql b/api/_lib/migrations/20260623100000_mirror_social.sql
deleted file mode 100644
index 4b7941b8e..000000000
--- a/api/_lib/migrations/20260623100000_mirror_social.sql
+++ /dev/null
@@ -1,129 +0,0 @@
--- Migration: the Mirror / Copy-Trade Social Graph (task 09, invention layer).
---
--- This is the CUSTODIAL agent-to-agent mirror layer — distinct from the existing
--- non-custodial copy_* tables (which only record intents a human acts on from any
--- wallet). Here, an owner subscribes ONE of THEIR agents (a custodial wallet) to
--- mirror ANOTHER public agent's real on-chain trades. When the leader trades, the
--- follower's agent executes the proportional move automatically — real tx, signed
--- with the follower's custodial key, clamped to the follower's spend policy.
---
--- Two tables:
--- mirror_subscriptions — the relationship + the follower's mirror policy. The
--- policy is bounded by, and can never exceed, the agent's
--- existing spend policy (meta.spend_limits / trade_limits);
--- it is the follower's own, narrower risk dial.
--- mirror_fills — the audit trail: every mirrored execution (filled,
--- skipped, or failed) with the leader reference + trigger,
--- traceable end to end alongside the custody ledger.
---
--- A leader's opt-out of being copyable lives in agent_identities.meta.copyable
--- (default copyable), so no schema change is needed for that — the engine reads it.
-begin;
-
--- ── mirror_subscriptions ─────────────────────────────────────────────────────
--- follower_agent_id (the owner's custodial agent) mirrors leader_agent_id (any
--- public agent). One subscription per (follower_agent, leader_agent, network).
--- follower_user_id is denormalized for the owner-only ownership check on every
--- read/write without a join back to agent_identities.
-create table if not exists mirror_subscriptions (
- id uuid primary key default gen_random_uuid(),
- follower_agent_id uuid not null references agent_identities(id) on delete cascade,
- follower_user_id uuid not null references users(id) on delete cascade,
- leader_agent_id uuid not null references agent_identities(id) on delete cascade,
- network text not null default 'mainnet', -- mainnet | devnet
- status text not null default 'active', -- active | paused | stopped
-
- -- Allocation: how the follower's order is sized from the leader's move.
- -- proportional : leader's SOL spend × proportion (e.g. 0.5 = half the leader)
- -- fixed : a flat fixed_sol per copied buy
- -- pct_balance : pct_balance % of the follower's own SOL balance
- allocation_mode text not null default 'proportional',
- proportion numeric not null default 1.0, -- multiplier vs leader (proportional)
- fixed_sol numeric, -- fixed mode
- pct_balance numeric, -- pct_balance mode (0–100)
-
- -- The follower's own caps. Hard ceilings, re-clamped to the agent's spend
- -- policy server-side at execution time (the spend policy always wins).
- max_per_trade_sol numeric not null default 0.25,
- max_per_day_sol numeric not null default 1.0,
- min_order_sol numeric not null default 0.001, -- skip dust below this
- slippage_bps int not null default 300, -- clamped to trade_limits.max_slippage_bps
-
- -- Asset gating. allow_mints non-empty ⇒ only those mints are mirrored.
- -- deny_mints always blocks. $THREE is never special-cased here — this is
- -- coin-agnostic plumbing keyed on whatever mint the leader actually traded.
- allow_mints text[] not null default '{}'::text[],
- deny_mints text[] not null default '{}'::text[],
- copy_sells boolean not null default true, -- mirror leader exits
-
- created_at timestamptz not null default now(),
- updated_at timestamptz not null default now(),
-
- constraint mirror_sub_uniq unique (follower_agent_id, leader_agent_id, network),
- constraint mirror_no_self check (follower_agent_id <> leader_agent_id),
- constraint mirror_alloc_mode check (allocation_mode in ('proportional','fixed','pct_balance')),
- constraint mirror_status_ck check (status in ('active','paused','stopped'))
-);
-
--- "Who does this agent follow" (follower lens) and "who follows this agent"
--- (leader/discovery lens) are both hot reads; index each direction.
-create index if not exists mirror_sub_follower
- on mirror_subscriptions (follower_agent_id, status);
-create index if not exists mirror_sub_leader
- on mirror_subscriptions (leader_agent_id, network, status);
-create index if not exists mirror_sub_user
- on mirror_subscriptions (follower_user_id, status);
-
--- ── mirror_fills ─────────────────────────────────────────────────────────────
--- One row per (subscription, leader trade, direction). The partial unique index
--- makes the fanout idempotent: a re-run over the same leader trade can't fire a
--- second mirrored order. leader_custody_event_id is the discretionary-trade
--- trigger; leader_position_id is the sniper trigger (mutually exclusive).
-create table if not exists mirror_fills (
- id uuid primary key default gen_random_uuid(),
- subscription_id uuid not null references mirror_subscriptions(id) on delete cascade,
- follower_agent_id uuid not null,
- follower_user_id uuid not null,
- leader_agent_id uuid not null,
- network text not null default 'mainnet',
-
- -- Trigger references (exactly one set).
- leader_custody_event_id bigint, -- agent_custody_events.id (discretionary)
- leader_position_id uuid, -- agent_sniper_positions.id (sniper)
- leader_signature text, -- leader's on-chain tx (attribution)
-
- mint text not null,
- symbol text,
- direction text not null, -- buy | sell
- planned_sol numeric, -- sized order (null when skipped pre-size)
-
- status text not null, -- filled | skipped | failed
- skip_reason text, -- why a copy/sell was not executed
- follower_signature text, -- the mirrored tx signature
- follower_custody_event_id bigint, -- agent_custody_events.id of the mirror
- usd numeric,
- detail jsonb not null default '{}'::jsonb,
-
- created_at timestamptz not null default now(),
-
- constraint mirror_fill_dir check (direction in ('buy','sell')),
- constraint mirror_fill_status check (status in ('filled','skipped','failed'))
-);
-
--- Idempotency: one fill per (subscription, leader trigger, direction). Two partial
--- indexes because the trigger source is either a custody event or a sniper position.
-create unique index if not exists mirror_fill_custody_uniq
- on mirror_fills (subscription_id, leader_custody_event_id, direction)
- where leader_custody_event_id is not null;
-create unique index if not exists mirror_fill_position_uniq
- on mirror_fills (subscription_id, leader_position_id, direction)
- where leader_position_id is not null;
-
--- Owner-facing audit feed: a follower's mirror history, newest first.
-create index if not exists mirror_fills_follower_time
- on mirror_fills (follower_agent_id, created_at desc);
--- Leaderboard / leader social proof: a leader's downstream mirror activity.
-create index if not exists mirror_fills_leader_time
- on mirror_fills (leader_agent_id, created_at desc);
-
-commit;
diff --git a/api/_lib/migrations/20260624120000_treasury_autopilot.sql b/api/_lib/migrations/20260624120000_treasury_autopilot.sql
deleted file mode 100644
index 19f4be9f5..000000000
--- a/api/_lib/migrations/20260624120000_treasury_autopilot.sql
+++ /dev/null
@@ -1,94 +0,0 @@
-begin;
-
--- Treasury Autopilot (prompts/agent-wallets/14) — the agent that funds its own
--- existence.
---
--- An agent's custodial wallet both EARNS (tips, its coin's creator fees, trading)
--- and COSTS money to run (the metered LLM/voice compute that makes it think and
--- talk). Treasury Autopilot lets the owner arm a natural-language treasury policy
--- the agent executes on its OWN wallet, autonomously and bounded: settle its own
--- compute, hold a safety buffer, dollar-cost-average a slice of income into
--- $THREE, compound its coin fees into buybacks, and sweep profit to the owner on
--- a schedule. Every action is a real, spend-policy-gated on-chain transaction.
---
--- Two tables:
--- agent_treasury_autopilot the per-agent policy: the owner's NL text, the
--- compiled+approved rules, and the arm/kill flags.
--- Config side — the source of truth for "what is armed".
--- agent_autopilot_runs the run ledger: one row per (agent, rule, period)
--- attempt, idempotent by design so an overlapping
--- cron tick can never double-execute. Powers the
--- runway view and the activity trail. The custodial
--- spend itself is ALSO written to agent_custody_events
--- (the shared audit trail) — this table is the
--- autopilot-specific scheduling + analytics side.
-
--- ── policy (config) ──────────────────────────────────────────────────────────
-create table if not exists agent_treasury_autopilot (
- agent_id uuid primary key references agent_identities(id) on delete cascade,
- user_id uuid not null, -- owner who armed it (immutable owner of the agent)
- network text not null default 'mainnet',
- -- Arm state. `armed` = the owner approved the compiled rules and turned it on.
- -- `killed` = the prominent kill switch. A killed policy halts ALL execution
- -- instantly regardless of `armed`, and is the safe resting state.
- armed boolean not null default false,
- killed boolean not null default false,
- -- The owner's natural-language policy, verbatim — shown back so they always
- -- see what they wrote.
- policy_text text,
- -- The compiled, validated, owner-APPROVED rules (the structured form the
- -- executor runs). Null until the owner approves a compile.
- rules jsonb not null default '{}'::jsonb,
- -- Hash of the approved rules. If a later compile differs, the UI requires a
- -- fresh approval before arming — the owner always re-consents to changes.
- rules_hash text,
- approved_at timestamptz,
- -- Per-rule pause map: { "<rule_kind>": true } pauses just that rule without
- -- disarming the whole policy.
- paused jsonb not null default '{}'::jsonb,
- created_at timestamptz not null default now(),
- updated_at timestamptz not null default now()
-);
-
--- The cron scans armed, un-killed policies on mainnet ordered by last touch.
-create index if not exists agent_treasury_autopilot_active
- on agent_treasury_autopilot (network, updated_at desc)
- where armed = true and killed = false;
-
--- ── run ledger (idempotent execution log + analytics) ────────────────────────
-create table if not exists agent_autopilot_runs (
- id bigserial primary key,
- agent_id uuid not null references agent_identities(id) on delete cascade,
- user_id uuid,
- network text not null default 'mainnet',
- -- settle_compute | buffer | dca | buyback | sweep
- rule_kind text not null,
- -- The period bucket this run satisfies (e.g. 'dca:2026-W26', 'sweep:2026-06-26').
- -- The unique index below makes (agent, kind, period) execute at most once.
- period_key text not null,
- -- planned | executing | confirmed | skipped | failed
- status text not null default 'planned',
- -- Why it skipped/failed (e.g. 'below_buffer', 'no_income', 'no_liquidity',
- -- 'price_feed_down', 'killed') — surfaced honestly in the activity trail.
- reason text,
- -- The on-chain tx (buy/sweep/settle). Null for skips.
- signature text,
- amount_lamports bigint,
- amount_usd numeric,
- -- Free-form: { mint, route, expected_out, explorer, trigger, ... }.
- meta jsonb not null default '{}'::jsonb,
- created_at timestamptz not null default now(),
- updated_at timestamptz not null default now()
-);
-
--- Idempotency: at most one run per (agent, rule_kind, period_key). The executor
--- INSERTs this row BEFORE moving funds; a duplicate insert loses the race and the
--- second runner backs off — no double-spend on overlapping ticks or retries.
-create unique index if not exists agent_autopilot_runs_idem
- on agent_autopilot_runs (agent_id, rule_kind, period_key);
-
--- Activity trail + runway analytics: newest-first per agent.
-create index if not exists agent_autopilot_runs_agent_time
- on agent_autopilot_runs (agent_id, created_at desc);
-
-commit;
diff --git a/api/_lib/migrations/20260624140000_agent_hires.sql b/api/_lib/migrations/20260624140000_agent_hires.sql
new file mode 100644
index 000000000..506a14152
--- /dev/null
+++ b/api/_lib/migrations/20260624140000_agent_hires.sql
@@ -0,0 +1,89 @@
+begin;
+
+-- Agent-to-Agent Economy (prompts/agent-wallets/15) — the real hire ledger.
+--
+-- Every time one agent hires another for a paid skill over the real x402 rails
+-- (api/agents/a2a-hire.js), exactly one row is written here. It is the single
+-- source of truth for: the marketplace's REAL completion counts / ratings /
+-- throughput (no fabricated stats), both wallets' income/outlay accounting, and
+-- the link from a hire to its real on-chain artifacts (the USDC settlement tx and
+-- the agent-invocation receipt tx). Money movement itself is enforced upstream by
+-- the spend policy (agent_custody_events reservation) and the x402 spending cap;
+-- this table records the business-level hire and its lifecycle.
+
+create table if not exists agent_hires (
+ id uuid primary key default gen_random_uuid(),
+
+ -- Who hired (the paying side) and who provided (the earning side).
+ hirer_agent_id uuid not null,
+ hirer_user_id uuid not null,
+ provider_agent_id uuid,
+ provider_user_id uuid,
+
+ -- The offer that was hired. service_id references the existing offer registry
+ -- (agent_paid_services); slug/skill kept denormalized so a hire stays readable
+ -- even if the offer is later archived.
+ service_id uuid,
+ service_slug text,
+ skill_name text not null,
+
+ -- Price + rail. amount_atomics is USDC 6-decimal atomic units (string to avoid
+ -- float drift); usd is the human dollar value for the feed/accounting.
+ amount_atomics text not null,
+ usd double precision,
+ currency text not null default 'USDC',
+ network text not null default 'solana',
+
+ -- Lifecycle: pending → completed | refunded | failed | disputed.
+ status text not null default 'pending',
+
+ -- Real on-chain artifacts (explorer links derived from these).
+ payment_signature text, -- USDC settlement tx (hirer wallet → provider wallet)
+ invocation_signature text, -- agent-invocation invoke_skill receipt tx
+ invocation_error text, -- recorded if the receipt write failed (payment still real)
+ payer_address text, -- hirer wallet that paid
+ payout_address text, -- provider wallet that earned
+
+ -- Spend-policy reservation row id (agent_custody_events) so the hire can be
+ -- finalized/released atomically, and the audit trail joins up.
+ spend_reservation_id bigint,
+
+ -- Idempotency: a retried hire with the same key never double-charges.
+ idempotency_key text,
+
+ -- Result + quality.
+ result_summary text,
+ error text,
+ rating smallint, -- 1..5, set by the hirer after a completed hire
+ rated_at timestamptz,
+
+ meta jsonb not null default '{}',
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ completed_at timestamptz,
+
+ constraint agent_hires_status_chk
+ check (status in ('pending', 'completed', 'refunded', 'failed', 'disputed')),
+ constraint agent_hires_rating_chk
+ check (rating is null or (rating between 1 and 5))
+);
+
+-- One row per (hirer agent, idempotency key) — the double-charge guard. A retry
+-- conflicts here and returns the existing hire instead of paying again.
+create unique index if not exists agent_hires_idem
+ on agent_hires (hirer_agent_id, idempotency_key)
+ where idempotency_key is not null;
+
+-- Provider reputation + earnings: count/sum/avg-rating over a provider's hires.
+create index if not exists agent_hires_provider_time
+ on agent_hires (provider_agent_id, created_at desc);
+
+-- Hirer accounting (outlay feed).
+create index if not exists agent_hires_hirer_time
+ on agent_hires (hirer_agent_id, created_at desc);
+
+-- Marketplace stats roll-ups scan completed hires per service.
+create index if not exists agent_hires_service_status
+ on agent_hires (service_id, status);
+
+commit;
diff --git a/api/_lib/migrations/20260625000000_strategy_objects.sql b/api/_lib/migrations/20260625000000_strategy_objects.sql
new file mode 100644
index 000000000..8e8ad9ba3
--- /dev/null
+++ b/api/_lib/migrations/20260625000000_strategy_objects.sql
@@ -0,0 +1,122 @@
+-- Strategy Objects — an ownable, equippable, shareable, forkable trade strategy.
+--
+-- A Strategy Object encodes a real, rule-based plan (entry conditions, sizing,
+-- take-profit, stop-loss, max concurrent positions, cooldown) as a named, owned,
+-- versioned thing. Equipping it on an agent activates a runtime binding; the
+-- cron strategy runtime evaluates REAL pump.fun launches + REAL holdings and
+-- executes trades through the same guarded task-05 execution + custody path that
+-- backs the discretionary trade endpoint. Forking copies the RULES into another
+-- owner's library with full lineage — never any wallet access.
+--
+-- Three tables:
+-- agent_strategies the ownable object (forkable, publishable, versioned)
+-- agent_strategy_equips a strategy bound to an agent (runtime state)
+-- agent_strategy_positions open/closed positions for TP/SL + real live perf
+-- plus strategy_kill_switch a per-owner global halt-all toggle.
+
+-- ── the strategy object ───────────────────────────────────────────────────────
+create table if not exists agent_strategies (
+ id uuid primary key default gen_random_uuid(),
+ owner_id uuid not null references users(id),
+ name text not null check (length(name) between 1 and 80),
+ slug text not null,
+ description text check (description is null or length(description) <= 2000),
+ config jsonb not null default '{}'::jsonb,
+ version int not null default 1,
+ published boolean not null default false,
+ published_at timestamptz,
+ fork_of uuid references agent_strategies(id) on delete set null,
+ forked_from jsonb,
+ forks_count int not null default 0,
+ equips_count int not null default 0,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ deleted_at timestamptz
+);
+
+create unique index if not exists idx_agent_strategies_owner_slug
+ on agent_strategies (owner_id, slug) where deleted_at is null;
+create index if not exists idx_agent_strategies_owner
+ on agent_strategies (owner_id) where deleted_at is null;
+create index if not exists idx_agent_strategies_published
+ on agent_strategies (published_at desc) where published = true and deleted_at is null;
+create index if not exists idx_agent_strategies_fork_of
+ on agent_strategies (fork_of) where fork_of is not null;
+
+-- ── equip: a strategy active on an agent ──────────────────────────────────────
+create table if not exists agent_strategy_equips (
+ id uuid primary key default gen_random_uuid(),
+ strategy_id uuid not null references agent_strategies(id) on delete cascade,
+ agent_id uuid not null,
+ owner_id uuid not null references users(id),
+ config_snapshot jsonb not null default '{}'::jsonb, -- the rules at equip time (version pin)
+ strategy_version int not null default 1,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ active boolean not null default true,
+ last_eval_at timestamptz,
+ last_fired_at timestamptz,
+ fires_count int not null default 0,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (agent_id, strategy_id)
+);
+
+create index if not exists idx_strategy_equips_active
+ on agent_strategy_equips (network) where active = true;
+create index if not exists idx_strategy_equips_agent on agent_strategy_equips (agent_id);
+create index if not exists idx_strategy_equips_strategy on agent_strategy_equips (strategy_id);
+create index if not exists idx_strategy_equips_owner on agent_strategy_equips (owner_id);
+
+-- ── positions: real fills, the entry basis for exits + the live track record ──
+create table if not exists agent_strategy_positions (
+ id uuid primary key default gen_random_uuid(),
+ equip_id uuid not null references agent_strategy_equips(id) on delete cascade,
+ strategy_id uuid not null references agent_strategies(id) on delete cascade,
+ agent_id uuid not null,
+ owner_id uuid not null,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ mint text not null,
+ symbol text,
+ name text,
+ status text not null default 'open'
+ check (status in ('open','closing','closed','failed')),
+ exit_reason text
+ check (exit_reason in
+ ('take_profit','stop_loss','trailing_stop','timeout','manual','kill_switch','error')),
+
+ -- entry (real fill)
+ entry_sig text,
+ entry_lamports numeric(40,0), -- SOL spent (lamports)
+ base_amount numeric(40,0), -- token base units bought
+ entry_price_impact_pct numeric,
+
+ -- live tracking (re-quoted each sweep against real chain state)
+ peak_value_lamports numeric(40,0), -- high-water mark for trailing stop
+ last_value_lamports numeric(40,0), -- last quoteForSell value
+ last_quoted_at timestamptz,
+
+ -- exit (real fill)
+ exit_sig text,
+ exit_lamports numeric(40,0), -- SOL received
+ realized_pnl_lamports numeric(40,0), -- exit - entry (signed)
+ realized_pnl_pct numeric,
+
+ error text,
+ opened_at timestamptz not null default now(),
+ closed_at timestamptz,
+ unique (agent_id, mint, network)
+);
+
+create index if not exists idx_strategy_positions_open
+ on agent_strategy_positions (network) where status in ('open','closing');
+create index if not exists idx_strategy_positions_strategy on agent_strategy_positions (strategy_id);
+create index if not exists idx_strategy_positions_equip on agent_strategy_positions (equip_id);
+create index if not exists idx_strategy_positions_agent on agent_strategy_positions (agent_id);
+
+-- ── per-owner global kill switch (halts ALL the owner's strategies at once) ────
+create table if not exists strategy_kill_switch (
+ owner_id uuid primary key references users(id),
+ engaged boolean not null default false,
+ engaged_at timestamptz,
+ updated_at timestamptz not null default now()
+);
diff --git a/api/_lib/mirror-engine.js b/api/_lib/mirror-engine.js
index 88fcbdf32..e96ae3cf3 100644
--- a/api/_lib/mirror-engine.js
+++ b/api/_lib/mirror-engine.js
@@ -14,7 +14,6 @@
* is the first clamp, the spend policy is the hard backstop.
*/
-const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
const round6 = (x) => Math.round(x * 1e6) / 1e6;
diff --git a/api/_lib/pump-launch-feed.js b/api/_lib/pump-launch-feed.js
new file mode 100644
index 000000000..5c9c3bdd9
--- /dev/null
+++ b/api/_lib/pump-launch-feed.js
@@ -0,0 +1,135 @@
+// Real pump.fun launch feed — the entry trigger source for the strategy runtime.
+//
+// The live sniper worker consumes a WebSocket; a stateless Vercel cron can't hold
+// one open, so the runtime polls the SAME pump.fun frontend API the rest of the
+// codebase already uses (PUMP_FRONTEND_BASE) for the most-recent launches, sorted
+// newest-first. Every field is real on-chain/feed data — no synthetic launches,
+// ever. pump.fun's public launch feed is mainnet-only; devnet has no equivalent,
+// so recentPumpLaunches() returns [] there (entries simply don't fire on devnet —
+// open positions still exit via real on-chain re-quotes).
+
+const PUMP_FRONTEND_BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
+const FETCH_TIMEOUT_MS = 6_000;
+const UA = 'three.ws-strategy-runtime/1';
+
+async function fetchJsonWithTimeout(url, ms = FETCH_TIMEOUT_MS) {
+ const ctrl = new AbortController();
+ const tid = setTimeout(() => ctrl.abort(), ms);
+ try {
+ const r = await fetch(url, {
+ signal: ctrl.signal,
+ headers: { accept: 'application/json', 'user-agent': UA },
+ });
+ if (!r.ok) return null;
+ return await r.json();
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(tid);
+ }
+}
+
+function pickMcUsd(c, solPrice) {
+ if (typeof c?.usd_market_cap === 'number') return c.usd_market_cap;
+ if (typeof c?.market_cap === 'number' && solPrice > 0) return c.market_cap * solPrice;
+ return null;
+}
+
+function liquiditySol(c) {
+ const real = Number(c?.real_sol_reserves);
+ if (Number.isFinite(real) && real > 0) return real / 1e9;
+ const virt = Number(c?.virtual_sol_reserves);
+ if (Number.isFinite(virt) && virt > 0) return virt / 1e9;
+ return null;
+}
+
+function isGraduated(c) {
+ return c?.complete === true || !!c?.raydium_pool || !!c?.pump_swap_pool;
+}
+
+/** Map a raw pump.fun coin object → the launch shape matchesEntry() expects. */
+export function normalizeLaunch(c, solPrice = 0) {
+ if (!c || !c.mint) return null;
+ return {
+ mint: c.mint,
+ name: c.name || null,
+ symbol: c.symbol || null,
+ created_at: c.created_timestamp ? Number(c.created_timestamp) : null,
+ market_cap_usd: pickMcUsd(c, solPrice),
+ liquidity_sol: liquiditySol(c),
+ creator: c.creator || null,
+ creator_launches: null, // enriched on demand (enrichCreatorStats)
+ creator_graduated: null,
+ twitter: c.twitter || null,
+ telegram: c.telegram || null,
+ website: c.website || null,
+ is_usdc_pair: false, // pump.fun bonding-curve coins are SOL-quoted
+ graduated: isGraduated(c),
+ };
+}
+
+let _solPrice = 0;
+let _solPriceAt = 0;
+async function solPriceUsd() {
+ if (Date.now() - _solPriceAt < 60_000 && _solPrice > 0) return _solPrice;
+ const d = await fetchJsonWithTimeout('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd', 3000);
+ const p = d?.solana?.usd;
+ if (p > 0) {
+ _solPrice = p;
+ _solPriceAt = Date.now();
+ }
+ return _solPrice || 0;
+}
+
+/**
+ * Fetch the most-recent pump.fun launches (newest-first), normalized. Returns []
+ * on any feed outage (the runtime treats an empty feed as "no entries this
+ * sweep", never as an error — entries are best-effort, exits are not).
+ *
+ * @param {object} o
+ * @param {string} [o.network] 'mainnet' (default) — devnet has no public feed → []
+ * @param {number} [o.limit] how many recent coins to pull (default 50, max 100)
+ */
+export async function recentPumpLaunches({ network = 'mainnet', limit = 50 } = {}) {
+ if (network !== 'mainnet') return [];
+ const n = Math.min(100, Math.max(1, Number(limit) || 50));
+ const url = `${PUMP_FRONTEND_BASE}/coins?offset=0&limit=${n}&sort=created_timestamp&order=DESC&includeNsfw=false`;
+ const data = await fetchJsonWithTimeout(url);
+ const list = Array.isArray(data) ? data : Array.isArray(data?.coins) ? data.coins : [];
+ if (!list.length) return [];
+ const solPrice = await solPriceUsd();
+ const out = [];
+ for (const c of list) {
+ const launch = normalizeLaunch(c, solPrice);
+ // Only pre-graduation, SOL-quoted bonding-curve coins are buyable on the
+ // agent-wallet trade path — drop graduated ones from the entry candidates.
+ if (launch && !launch.graduated) out.push(launch);
+ }
+ return out;
+}
+
+const _creatorCache = new Map();
+/**
+ * Enrich a launch with the creator's launch history (count + graduated count),
+ * fetched only for candidate mints a strategy actually gates on. Mutates and
+ * returns the launch; leaves the fields null if the lookup fails.
+ */
+export async function enrichCreatorStats(launch, solPrice = 0) {
+ if (!launch?.creator) return launch;
+ const hit = _creatorCache.get(launch.creator);
+ let coins = hit && Date.now() - hit.t < 60_000 ? hit.v : null;
+ if (!coins) {
+ coins = await fetchJsonWithTimeout(
+ `${PUMP_FRONTEND_BASE}/coins/user-created-coins/${encodeURIComponent(launch.creator)}?offset=0&limit=100&includeNsfw=true`,
+ );
+ if (_creatorCache.size > 500) _creatorCache.clear();
+ _creatorCache.set(launch.creator, { t: Date.now(), v: coins });
+ }
+ if (Array.isArray(coins)) {
+ launch.creator_launches = coins.length;
+ launch.creator_graduated = coins.reduce((acc, c) => acc + (isGraduated(c) ? 1 : 0), 0);
+ }
+ return launch;
+}
+
+export { isGraduated };
diff --git a/api/_lib/strategy-schema.js b/api/_lib/strategy-schema.js
new file mode 100644
index 000000000..ba669346a
--- /dev/null
+++ b/api/_lib/strategy-schema.js
@@ -0,0 +1,277 @@
+// Strategy Object config — the validated, versioned rule set behind a Strategy.
+//
+// A strategy is NOT free text: it is a structured plan with a real schema. This
+// module is the single source of truth for that schema. It normalizes arbitrary
+// owner input into a clean, bounded config; validates it (so a malformed rule
+// set can never be saved); and evaluates a real pump.fun launch against the
+// entry conditions (pure + synchronous, so it is trivially testable and the same
+// logic runs in the runtime and in a backtest).
+//
+// Critically, the strategy's own caps (per-trade size, slippage, concurrency)
+// are ADDITIONAL constraints layered on top of the agent's server-side spend
+// policy — never a way around it. The runtime sizes a buy from `sizing.amount_sol`
+// but the trade still passes through the full guard + custody path, so a strategy
+// can never exceed the spend leash. Ever.
+
+const ENTRY_TRIGGERS = ['new_launch'];
+const NETWORKS = ['mainnet', 'devnet'];
+
+export const STRATEGY_CONFIG_DEFAULTS = Object.freeze({
+ network: 'mainnet',
+ entry: {
+ trigger: 'new_launch',
+ max_age_minutes: 60,
+ min_market_cap_usd: null,
+ max_market_cap_usd: null,
+ min_liquidity_sol: null,
+ require_socials: false,
+ max_creator_launches: null,
+ min_creator_graduated: null,
+ require_sol_quote: true,
+ },
+ sizing: {
+ amount_sol: 0.1,
+ max_slippage_bps: 500,
+ },
+ exits: {
+ take_profit_pct: 100, // +100% = 2x
+ stop_loss_pct: 40, // -40%
+ trailing_stop_pct: null,
+ max_hold_minutes: null,
+ },
+ risk: {
+ max_concurrent_positions: 3,
+ cooldown_minutes: 0,
+ },
+});
+
+// Hard ceilings the schema enforces regardless of input — defensive bounds so a
+// stored config can never carry a nonsense number into the runtime.
+const BOUNDS = Object.freeze({
+ amount_sol: { min: 0.0001, max: 100 },
+ max_slippage_bps: { min: 0, max: 10000 },
+ max_age_minutes: { min: 1, max: 10080 }, // up to 7 days
+ take_profit_pct: { min: 1, max: 100000 },
+ stop_loss_pct: { min: 1, max: 99 },
+ trailing_stop_pct: { min: 1, max: 99 },
+ max_hold_minutes: { min: 1, max: 525600 }, // up to 1 year
+ max_concurrent_positions: { min: 1, max: 50 },
+ cooldown_minutes: { min: 0, max: 10080 },
+ market_cap_usd: { min: 0, max: 1e12 },
+ liquidity_sol: { min: 0, max: 1e9 },
+ creator_count: { min: 0, max: 100000 },
+});
+
+function numOrNull(v, { min = -Infinity, max = Infinity } = {}) {
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ if (!Number.isFinite(n)) return null;
+ return Math.min(max, Math.max(min, n));
+}
+
+function intOrNull(v, bounds) {
+ const n = numOrNull(v, bounds);
+ return n === null ? null : Math.round(n);
+}
+
+function clampNum(v, def, { min = 0, max = Infinity, round = false } = {}) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return def;
+ const c = Math.min(max, Math.max(min, n));
+ return round ? Math.round(c) : c;
+}
+
+/** Turn a strategy name into a URL-safe, stable slug. */
+export function slugifyStrategy(name) {
+ const base = String(name || '')
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 48);
+ return base || 'strategy';
+}
+
+/**
+ * Coerce arbitrary input into a clean, bounded, complete strategy config.
+ * Always returns a fully-populated object (missing keys fall back to defaults).
+ */
+export function normalizeStrategyConfig(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const e = r.entry && typeof r.entry === 'object' ? r.entry : {};
+ const s = r.sizing && typeof r.sizing === 'object' ? r.sizing : {};
+ const x = r.exits && typeof r.exits === 'object' ? r.exits : {};
+ const k = r.risk && typeof r.risk === 'object' ? r.risk : {};
+ const d = STRATEGY_CONFIG_DEFAULTS;
+
+ const trigger = ENTRY_TRIGGERS.includes(e.trigger) ? e.trigger : d.entry.trigger;
+ const network = NETWORKS.includes(r.network) ? r.network : d.network;
+
+ return {
+ network,
+ entry: {
+ trigger,
+ max_age_minutes: clampNum(e.max_age_minutes, d.entry.max_age_minutes, { ...BOUNDS.max_age_minutes, round: true }),
+ min_market_cap_usd: numOrNull(e.min_market_cap_usd, BOUNDS.market_cap_usd),
+ max_market_cap_usd: numOrNull(e.max_market_cap_usd, BOUNDS.market_cap_usd),
+ min_liquidity_sol: numOrNull(e.min_liquidity_sol, BOUNDS.liquidity_sol),
+ require_socials: e.require_socials === true,
+ max_creator_launches: intOrNull(e.max_creator_launches, BOUNDS.creator_count),
+ min_creator_graduated: intOrNull(e.min_creator_graduated, BOUNDS.creator_count),
+ require_sol_quote: e.require_sol_quote !== false,
+ },
+ sizing: {
+ amount_sol: clampNum(s.amount_sol, d.sizing.amount_sol, BOUNDS.amount_sol),
+ max_slippage_bps: clampNum(s.max_slippage_bps, d.sizing.max_slippage_bps, { ...BOUNDS.max_slippage_bps, round: true }),
+ },
+ exits: {
+ take_profit_pct: numOrNull(x.take_profit_pct, BOUNDS.take_profit_pct),
+ // stop_loss is mandatory and always present — default applied if absent/invalid.
+ stop_loss_pct: clampNum(x.stop_loss_pct, d.exits.stop_loss_pct, BOUNDS.stop_loss_pct),
+ trailing_stop_pct: numOrNull(x.trailing_stop_pct, BOUNDS.trailing_stop_pct),
+ max_hold_minutes: intOrNull(x.max_hold_minutes, BOUNDS.max_hold_minutes),
+ },
+ risk: {
+ max_concurrent_positions: clampNum(k.max_concurrent_positions, d.risk.max_concurrent_positions, { ...BOUNDS.max_concurrent_positions, round: true }),
+ cooldown_minutes: clampNum(k.cooldown_minutes, d.risk.cooldown_minutes, { ...BOUNDS.cooldown_minutes, round: true }),
+ },
+ };
+}
+
+/**
+ * Validate a strategy config. Returns { valid, errors:[{field,message}], config }.
+ * `config` is the normalized form (safe to persist). Errors are human-readable
+ * and field-tagged so the UI can show them inline.
+ */
+export function validateStrategyConfig(raw) {
+ const errors = [];
+ const config = normalizeStrategyConfig(raw);
+
+ if (!(config.sizing.amount_sol > 0)) {
+ errors.push({ field: 'sizing.amount_sol', message: 'Per-trade size must be greater than 0 SOL.' });
+ }
+ if (!(config.exits.stop_loss_pct > 0)) {
+ errors.push({ field: 'exits.stop_loss_pct', message: 'A stop-loss is required — every strategy must define its downside.' });
+ }
+ if (
+ config.entry.min_market_cap_usd != null &&
+ config.entry.max_market_cap_usd != null &&
+ config.entry.min_market_cap_usd > config.entry.max_market_cap_usd
+ ) {
+ errors.push({ field: 'entry.max_market_cap_usd', message: 'Max market cap must be greater than min market cap.' });
+ }
+ if (config.exits.take_profit_pct == null && config.exits.trailing_stop_pct == null && config.exits.max_hold_minutes == null) {
+ errors.push({ field: 'exits', message: 'Define at least one upside exit: take-profit, trailing stop, or max hold.' });
+ }
+
+ return { valid: errors.length === 0, errors, config };
+}
+
+/**
+ * Evaluate one real launch against a strategy's entry conditions. Pure +
+ * synchronous. Returns { pass, reasons } — reasons always explains the verdict
+ * (kept on rejections too, for the runtime's evaluation log).
+ *
+ * @param {object} config normalized strategy config
+ * @param {object} launch normalized launch: { mint, created_at(ms), market_cap_usd,
+ * liquidity_sol, creator_launches, creator_graduated,
+ * twitter, telegram, website, is_usdc_pair }
+ * @param {number} nowMs current epoch ms
+ */
+export function matchesEntry(config, launch, nowMs) {
+ const e = config.entry;
+ const reasons = [];
+
+ if (!launch || !launch.mint) return { pass: false, reasons: ['no_mint'] };
+
+ // Age gate — only act on genuinely recent launches.
+ if (e.max_age_minutes != null && launch.created_at) {
+ const ageMin = (nowMs - Number(launch.created_at)) / 60000;
+ if (!Number.isFinite(ageMin) || ageMin < 0) {
+ // Clock skew / bad timestamp — treat as fresh, don't reject.
+ } else if (ageMin > e.max_age_minutes) {
+ return { pass: false, reasons: [`too_old:${Math.round(ageMin)}m`] };
+ } else {
+ reasons.push(`age:${Math.round(ageMin)}m`);
+ }
+ }
+
+ // SOL-quote requirement — the agent wallet trades in SOL on this path.
+ if (e.require_sol_quote && launch.is_usdc_pair === true) {
+ return { pass: false, reasons: ['quote_not_sol'] };
+ }
+
+ const mc = numOrNull(launch.market_cap_usd);
+ if (e.min_market_cap_usd != null) {
+ if (mc == null || mc < e.min_market_cap_usd) return { pass: false, reasons: [`mc_below_min:${mc ?? 'n/a'}`] };
+ }
+ if (e.max_market_cap_usd != null && mc != null && mc > e.max_market_cap_usd) {
+ return { pass: false, reasons: [`mc_above_max:${Math.round(mc)}`] };
+ }
+ if (mc != null) reasons.push(`mc:${Math.round(mc)}`);
+
+ const liq = numOrNull(launch.liquidity_sol);
+ if (e.min_liquidity_sol != null) {
+ if (liq == null || liq < e.min_liquidity_sol) return { pass: false, reasons: [`liq_below_min:${liq ?? 'n/a'}`] };
+ reasons.push(`liq:${liq.toFixed(2)}sol`);
+ }
+
+ const launches = numOrNull(launch.creator_launches);
+ if (e.max_creator_launches != null && launches != null && launches > e.max_creator_launches) {
+ return { pass: false, reasons: [`creator_launches:${launches}`] };
+ }
+ const graduated = numOrNull(launch.creator_graduated);
+ if (e.min_creator_graduated != null) {
+ if (graduated == null || graduated < e.min_creator_graduated) return { pass: false, reasons: [`creator_graduated_below:${graduated ?? 'n/a'}`] };
+ reasons.push(`creator_graduated:${graduated}`);
+ }
+
+ const hasSocials = !!(launch.twitter || launch.telegram || launch.website);
+ if (e.require_socials && !hasSocials) {
+ return { pass: false, reasons: ['no_socials'] };
+ }
+ if (hasSocials) reasons.push('has_socials');
+
+ return { pass: true, reasons };
+}
+
+/**
+ * Decide whether an open position should exit, given a live re-quote. Pure.
+ * Returns { exit, reason } — reason ∈ take_profit|stop_loss|trailing_stop|timeout.
+ *
+ * @param {object} config normalized config
+ * @param {object} pos { entry_lamports, peak_value_lamports, opened_at(ms) }
+ * @param {bigint|number|string} currentValueLamports live quoteForSell value
+ * @param {number} nowMs
+ */
+export function shouldExit(config, pos, currentValueLamports, nowMs) {
+ const x = config.exits;
+ const entry = Number(pos.entry_lamports || 0);
+ const cur = Number(currentValueLamports || 0);
+
+ // Time-based exit is independent of price — check it even with no entry basis.
+ if (x.max_hold_minutes != null && pos.opened_at) {
+ const heldMin = (nowMs - Number(pos.opened_at)) / 60000;
+ if (heldMin >= x.max_hold_minutes) return { exit: true, reason: 'timeout' };
+ }
+
+ if (!(entry > 0) || !(cur >= 0)) return { exit: false, reason: null };
+ const pnlPct = ((cur - entry) / entry) * 100;
+
+ if (x.take_profit_pct != null && pnlPct >= x.take_profit_pct) {
+ return { exit: true, reason: 'take_profit' };
+ }
+ if (x.stop_loss_pct != null && pnlPct <= -x.stop_loss_pct) {
+ return { exit: true, reason: 'stop_loss' };
+ }
+ if (x.trailing_stop_pct != null) {
+ const peak = Math.max(Number(pos.peak_value_lamports || 0), cur, entry);
+ if (peak > 0) {
+ const dropFromPeakPct = ((peak - cur) / peak) * 100;
+ if (dropFromPeakPct >= x.trailing_stop_pct) return { exit: true, reason: 'trailing_stop' };
+ }
+ }
+ return { exit: false, reason: null };
+}
+
+export { ENTRY_TRIGGERS, NETWORKS };
diff --git a/api/_lib/treasury-autopilot.js b/api/_lib/treasury-autopilot.js
new file mode 100644
index 000000000..55dd3b2d9
--- /dev/null
+++ b/api/_lib/treasury-autopilot.js
@@ -0,0 +1,998 @@
+// Treasury Autopilot — the agent that funds its own existence.
+//
+// An owner writes a treasury policy in plain English; we compile it into bounded,
+// structured rules they approve; then a scheduler executes each rule as a REAL,
+// idempotent, spend-policy-gated, audited on-chain action on the AGENT'S OWN
+// wallet. The agent pays its own metered compute, holds a buffer, dollar-cost-
+// averages income into $THREE, compounds its coin fees into buybacks, and sweeps
+// profit to its owner — all under the same `enforceSpendLimit` ceiling that
+// governs every other outbound movement (api/_lib/agent-trade-guards.js).
+//
+// Why this can only exist here: our agents both EARN (tips, creator fees, trading)
+// and COST money to run (LLM + voice compute), and both live in the SAME real
+// custodial wallet. That lets us close the loop and build a self-sustaining agent.
+//
+// Safety is structural, not bolted on:
+// - Owner-only to configure; every executing path acts only on the agent's wallet.
+// - The spend policy is the hard ceiling — the NL policy can only tighten it.
+// - Explicit consent: the compiled rules are shown back and armed before anything runs.
+// - Idempotent: each scheduled action claims a unique custody row per period, so a
+// retry can never double-spend.
+// - Fail safe: a price-feed gap, a missing config, or a breached buffer PAUSES the
+// affected rule and records an honest note — it never guesses with real money.
+// - A kill switch halts everything instantly.
+
+import { PublicKey, VersionedTransaction } from '@solana/web3.js';
+import { sql } from './db.js';
+import { solUsdPrice, sendSol, explorerTxUrl, explorerAccountUrl } from './avatar-wallet.js';
+import { solanaConnection } from './agent-pumpfun.js';
+import { getSolanaAddressBalances, recoverSolanaAgentKeypair } from './agent-wallet.js';
+import {
+ getSpendLimits,
+ enforceSpendLimit,
+ recordCustodyEvent,
+ updateCustodyEvent,
+ SpendLimitError,
+ validateSolanaAddress,
+} from './agent-trade-guards.js';
+import { THREE_MINT } from './networth-model.js';
+import { llmComplete, llmConfigured } from './llm.js';
+import { logAudit } from './audit.js';
+
+const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+// Rent + network-fee headroom kept above any autopilot spend so a move can never
+// brick the wallet for lack of lamports to pay the fee or open an ATA.
+const FEE_HEADROOM_LAMPORTS = 6_000_000n; // ~0.006 SOL
+// Below this USD the action isn't worth a transaction's fee — skip honestly.
+const DUST_USD = 0.02;
+const JUPITER_BASE = 'https://lite-api.jup.ag/swap/v1';
+
+export const AUTOPILOT_RULE_KINDS = Object.freeze(['self_fund', 'buffer', 'dca', 'buyback', 'sweep']);
+
+// ── normalization ──────────────────────────────────────────────────────────────
+
+function num(v, def = null) {
+ if (v === null || v === undefined || v === '') return def;
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 0 ? n : def;
+}
+function clamp(n, min, max) {
+ return Math.min(max, Math.max(min, n));
+}
+function str(v, max = 200) {
+ return typeof v === 'string' ? v.slice(0, max) : null;
+}
+const CADENCES = new Set(['hourly', 'daily', 'weekly']);
+function cadence(v, def = 'daily') {
+ return CADENCES.has(v) ? v : def;
+}
+// 0=Sun … 6=Sat, or null for "any day"
+function weekday(v) {
+ const n = Number(v);
+ return Number.isInteger(n) && n >= 0 && n <= 6 ? n : null;
+}
+
+let _ruleSeq = 0;
+function ruleId(kind) {
+ _ruleSeq = (_ruleSeq + 1) % 1e6;
+ return `${kind}_${Date.now().toString(36)}${_ruleSeq.toString(36)}`;
+}
+
+/** Coerce one raw rule into a clean, bounded rule object. */
+export function normalizeRule(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const kind = AUTOPILOT_RULE_KINDS.includes(r.kind) ? r.kind : null;
+ if (!kind) return null;
+ const p = r.params && typeof r.params === 'object' ? r.params : {};
+ let params = {};
+ if (kind === 'dca') {
+ const pct = p.pct != null ? clamp(num(p.pct, 0), 0, 100) : null;
+ const amountSol = p.amount_sol != null ? num(p.amount_sol, null) : null;
+ params = {
+ basis: p.basis === 'income' ? 'income' : 'surplus',
+ pct: pct != null ? pct : amountSol != null ? null : 10,
+ amount_sol: amountSol != null ? clamp(amountSol, 0, 1000) : null,
+ target_mint: THREE_MINT, // $THREE is the only DCA target — never owner-overridable
+ cadence: cadence(p.cadence, 'daily'),
+ weekday: weekday(p.weekday),
+ slippage_bps: clamp(Number(p.slippage_bps) || 300, 50, 2000),
+ };
+ } else if (kind === 'buyback') {
+ params = {
+ pct_of_fees: clamp(num(p.pct_of_fees, 100), 0, 100),
+ cadence: cadence(p.cadence, 'weekly'),
+ weekday: weekday(p.weekday),
+ slippage_bps: clamp(Number(p.slippage_bps) || 500, 50, 2000),
+ };
+ } else if (kind === 'sweep') {
+ const dest = validateSolanaAddress(p.destination || '');
+ params = {
+ threshold_sol: clamp(num(p.threshold_sol, 1), 0, 1e6),
+ destination: dest.valid ? dest.base58 : null,
+ cadence: cadence(p.cadence, 'weekly'),
+ weekday: weekday(p.weekday),
+ };
+ } else if (kind === 'self_fund') {
+ params = { cadence: cadence(p.cadence, 'hourly') };
+ } else if (kind === 'buffer') {
+ params = {}; // buffer amount lives at policy level
+ }
+ return {
+ id: typeof r.id === 'string' && r.id ? r.id.slice(0, 64) : ruleId(kind),
+ kind,
+ enabled: r.enabled !== false,
+ paused: r.paused === true,
+ params,
+ label: str(r.label, 240) || defaultLabel(kind, params),
+ last_run_at: str(r.last_run_at) || null,
+ last_status: str(r.last_status, 40) || null,
+ last_note: str(r.last_note, 240) || null,
+ };
+}
+
+function defaultLabel(kind, p) {
+ switch (kind) {
+ case 'self_fund':
+ return 'Pay the agent’s own metered compute costs from its wallet';
+ case 'buffer':
+ return 'Keep a safety buffer in the wallet';
+ case 'dca':
+ return p.amount_sol != null
+ ? `Dollar-cost-average ${p.amount_sol} SOL ${p.cadence} into $THREE`
+ : `Dollar-cost-average ${p.pct}% of ${p.basis} into $THREE (${p.cadence})`;
+ case 'buyback':
+ return `Compound ${p.pct_of_fees}% of coin fees into buybacks (${p.cadence})`;
+ case 'sweep':
+ return `Sweep anything over ${p.threshold_sol} SOL to the owner (${p.cadence})`;
+ default:
+ return kind;
+ }
+}
+
+/** Read + clean the full autopilot policy off an agent's meta blob. */
+export function normalizeAutopilot(raw) {
+ const a = raw && typeof raw === 'object' ? raw : {};
+ const dest = validateSolanaAddress(a.sweep_destination || '');
+ const rules = (Array.isArray(a.rules) ? a.rules : []).map(normalizeRule).filter(Boolean).slice(0, 20);
+ return {
+ armed: a.armed === true,
+ kill_switch: a.kill_switch === true,
+ buffer_sol: num(a.buffer_sol, null),
+ sweep_destination: dest.valid ? dest.base58 : null,
+ rules,
+ source_text: str(a.source_text, 4000),
+ compiled_at: str(a.compiled_at, 40),
+ approved_at: str(a.approved_at, 40),
+ compute_settled_at: str(a.compute_settled_at, 40),
+ updated_at: str(a.updated_at, 40),
+ };
+}
+
+export function getAutopilot(meta) {
+ return normalizeAutopilot(meta?.autopilot);
+}
+
+// ── NL → structured rules (compile) ─────────────────────────────────────────────
+
+const COMPILE_SYSTEM = `You compile a plain-English treasury policy for an autonomous AI agent's own crypto wallet into a strict JSON object of bounded rules. The agent both earns (tips, its coin's fees, trading) and costs money to run (LLM + voice compute), all in one Solana wallet.
+
+Output ONLY a JSON object (no prose, no markdown fences) with this shape:
+{
+ "buffer_sol": number|null, // safety buffer of SOL to always keep
+ "rules": [
+ {"kind":"self_fund"}, // pay the agent's own compute from its wallet
+ {"kind":"buffer"}, // maintain the buffer_sol above (include if a buffer is mentioned)
+ {"kind":"dca","params":{"basis":"income"|"surplus","pct":number|null,"amount_sol":number|null,"cadence":"hourly"|"daily"|"weekly","weekday":0-6|null}},
+ {"kind":"buyback","params":{"pct_of_fees":number,"cadence":"hourly"|"daily"|"weekly","weekday":0-6|null}},
+ {"kind":"sweep","params":{"threshold_sol":number,"cadence":"hourly"|"daily"|"weekly","weekday":0-6|null}}
+ ],
+ "warnings": [string], // anything ambiguous you assumed a default for
+ "contradictions": [string] // rules that conflict and cannot all hold (e.g. sweep threshold below the buffer)
+}
+Rules: DCA target is always $THREE (do not include a mint). "10% of tips/income" -> dca basis "income" pct 10. "0.5 SOL daily" -> dca amount_sol 0.5. weekday: Sun=0..Sat=6; "Fridays"=5. Only include rules the policy actually asks for. If the policy contradicts itself (e.g. "keep 3 SOL buffer" but "sweep everything over 1 SOL"), list it in contradictions. Never invent a coin other than $THREE.`;
+
+function safeJsonExtract(text) {
+ if (typeof text !== 'string') return null;
+ let t = text.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();
+ const start = t.indexOf('{');
+ const end = t.lastIndexOf('}');
+ if (start < 0 || end < start) return null;
+ try {
+ return JSON.parse(t.slice(start, end + 1));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Compile a natural-language treasury policy into validated, structured rules.
+ * Prefers the LLM (real tool-use over a worker proxy); falls back to a real
+ * deterministic intent parser when no model is configured, so the feature always
+ * compiles. Returns the compiled policy plus warnings/contradictions for the
+ * owner-approval preview — it NEVER arms anything.
+ */
+export async function compilePolicyFromText(text, { sweepDestination = null, track = null } = {}) {
+ const source = typeof text === 'string' ? text.trim().slice(0, 4000) : '';
+ if (!source) {
+ return { ok: false, error: 'empty_policy', message: 'Write a policy in plain English first.' };
+ }
+
+ let parsed = null;
+ let via = 'heuristic';
+ if (llmConfigured()) {
+ try {
+ const out = await llmComplete({
+ system: COMPILE_SYSTEM,
+ user: source,
+ maxTokens: 900,
+ timeoutMs: 25_000,
+ track,
+ });
+ parsed = safeJsonExtract(out.text);
+ if (parsed) via = 'model';
+ } catch (e) {
+ // fall through to the deterministic parser — never strand the owner
+ console.warn('[autopilot] LLM compile failed, using heuristic:', e?.message);
+ }
+ }
+ if (!parsed) parsed = heuristicCompile(source);
+
+ const warnings = Array.isArray(parsed.warnings) ? parsed.warnings.map((w) => str(w, 240)).filter(Boolean) : [];
+ const contradictions = Array.isArray(parsed.contradictions)
+ ? parsed.contradictions.map((w) => str(w, 240)).filter(Boolean)
+ : [];
+
+ const bufferSol = num(parsed.buffer_sol, null);
+ const rules = (Array.isArray(parsed.rules) ? parsed.rules : [])
+ .map((r) => {
+ // stamp the owner-supplied sweep destination onto sweep rules at compile time
+ if (r?.kind === 'sweep' && sweepDestination) {
+ r.params = { ...(r.params || {}), destination: sweepDestination };
+ }
+ return normalizeRule(r);
+ })
+ .filter(Boolean);
+
+ // Structural contradiction the parser may have missed: a sweep threshold at or
+ // below the buffer would fight the buffer every cycle.
+ for (const r of rules) {
+ if (r.kind === 'sweep' && bufferSol != null && r.params.threshold_sol <= bufferSol) {
+ contradictions.push(
+ `Sweep threshold (${r.params.threshold_sol} SOL) is at or below the ${bufferSol} SOL buffer — they would fight each other. Raise the sweep threshold above the buffer.`,
+ );
+ }
+ if (r.kind === 'sweep' && !r.params.destination && !sweepDestination) {
+ warnings.push('Set a destination wallet for the sweep before arming, or the agent has nowhere to send the profit.');
+ }
+ }
+
+ return {
+ ok: true,
+ via,
+ source_text: source,
+ buffer_sol: bufferSol,
+ sweep_destination: sweepDestination || null,
+ rules,
+ warnings: [...new Set(warnings)],
+ contradictions: [...new Set(contradictions)],
+ };
+}
+
+// Deterministic, dependency-free intent parser. Real implementation (not a mock):
+// extracts the same rule shapes from common phrasings so the feature compiles
+// offline and whenever no model is configured.
+function heuristicCompile(text) {
+ const t = text.toLowerCase();
+ const rules = [];
+ const warnings = [];
+ let buffer_sol = null;
+
+ if (/\b(pay|fund|cover|settle)\b.*\b(its own|your own|own)?\s*(compute|brain|llm|inference|costs?|bills?)\b/.test(t) ||
+ /self[- ]?fund/.test(t)) {
+ rules.push({ kind: 'self_fund' });
+ }
+
+ const buf = t.match(/(?:keep|hold|maintain|leave|reserve)\s*(?:a|an)?\s*([\d.]+)\s*sol\s*(?:safety\s*)?(?:buffer|reserve|floor)?/);
+ if (buf || /buffer|reserve|floor/.test(t)) {
+ if (buf) buffer_sol = Number(buf[1]);
+ rules.push({ kind: 'buffer' });
+ if (!buf) warnings.push('A buffer was requested but no amount was found — defaulting to no fixed buffer; set one explicitly.');
+ }
+
+ // DCA: percentage of tips/income, or a fixed SOL amount
+ const dcaPct = t.match(/([\d.]+)\s*%\s*(?:of)?\s*(tips?|income|earnings|revenue)?[^.]*?(?:into|to|in)\s*\$?three/);
+ const dcaAmt = t.match(/(?:put|dca|buy|invest|allocate)\s*([\d.]+)\s*sol[^.]*?(?:into|to|in)\s*\$?three/);
+ if (dcaPct || dcaAmt || /\bdca\b|dollar[- ]cost/.test(t)) {
+ const params = { cadence: cadenceFrom(t), weekday: weekdayFrom(t) };
+ if (dcaPct) {
+ params.pct = Number(dcaPct[1]);
+ params.basis = 'income';
+ } else if (dcaAmt) {
+ params.amount_sol = Number(dcaAmt[1]);
+ } else {
+ params.pct = 10;
+ params.basis = 'surplus';
+ warnings.push('DCA size was unclear — defaulting to 10% of surplus.');
+ }
+ rules.push({ kind: 'dca', params });
+ }
+
+ if (/\b(compound|buyback|buy back|burn)\b.*\b(fees?|coin)\b/.test(t) || /\bbuyback/.test(t)) {
+ rules.push({ kind: 'buyback', params: { pct_of_fees: 100, cadence: cadenceFrom(t, 'weekly'), weekday: weekdayFrom(t) } });
+ }
+
+ const sweep = t.match(/sweep[^.]*?(?:over|above|exceed(?:ing)?|more than)\s*([\d.]+)\s*sol/);
+ if (sweep || /\bsweep\b|send.*profit|withdraw.*profit/.test(t)) {
+ const params = { cadence: cadenceFrom(t, 'weekly'), weekday: weekdayFrom(t) };
+ if (sweep) params.threshold_sol = Number(sweep[1]);
+ else {
+ params.threshold_sol = 1;
+ warnings.push('Sweep threshold was unclear — defaulting to 1 SOL.');
+ }
+ rules.push({ kind: 'sweep', params });
+ }
+
+ if (!rules.length) {
+ warnings.push('No recognizable rules — try phrasing like "Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, sweep over 3 SOL to me on Fridays."');
+ }
+ return { buffer_sol, rules, warnings, contradictions: [] };
+}
+
+function cadenceFrom(t, def = 'daily') {
+ if (/\bhourly\b|every hour/.test(t)) return 'hourly';
+ if (/\bweekly\b|every week|each week|friday|monday|tuesday|wednesday|thursday|saturday|sunday/.test(t)) return 'weekly';
+ if (/\bdaily\b|every day|each day/.test(t)) return 'daily';
+ return def;
+}
+function weekdayFrom(t) {
+ const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
+ for (let i = 0; i < days.length; i++) if (t.includes(days[i])) return i;
+ return null;
+}
+
+// ── persistence (owner-only) ─────────────────────────────────────────────────────
+
+/**
+ * Persist an autopilot policy patch onto the agent (owner-only). Caller has
+ * already verified ownership. Writes a custody audit event + platform audit log.
+ * Returns the new normalized policy.
+ */
+export async function setAutopilot(agentId, userId, patch, { req = null } = {}) {
+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!row) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });
+ if (row.user_id !== userId) throw Object.assign(new Error('not your agent'), { status: 403, code: 'forbidden' });
+
+ const prev = getAutopilot(row.meta);
+ const merged = { ...prev };
+ if ('rules' in patch) merged.rules = patch.rules;
+ if ('buffer_sol' in patch) merged.buffer_sol = patch.buffer_sol;
+ if ('sweep_destination' in patch) merged.sweep_destination = patch.sweep_destination;
+ if ('source_text' in patch) merged.source_text = patch.source_text;
+ if ('armed' in patch) merged.armed = patch.armed === true;
+ if ('kill_switch' in patch) merged.kill_switch = patch.kill_switch === true;
+ if ('compiled_at' in patch) merged.compiled_at = patch.compiled_at;
+ if ('approved_at' in patch) merged.approved_at = patch.approved_at;
+ if ('compute_settled_at' in patch) merged.compute_settled_at = patch.compute_settled_at;
+
+ const next = normalizeAutopilot(merged);
+ next.updated_at = new Date().toISOString();
+ // stamp the sweep destination onto sweep rules so the executor always has it
+ for (const r of next.rules) {
+ if (r.kind === 'sweep' && !r.params.destination && next.sweep_destination) {
+ r.params.destination = next.sweep_destination;
+ }
+ }
+
+ const meta = { ...(row.meta || {}), autopilot: next };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agentId}`;
+
+ await recordCustodyEvent({
+ agentId,
+ userId,
+ eventType: 'autopilot_config',
+ reason: patch.kill_switch === true ? 'autopilot_killed' : next.armed ? 'autopilot_armed' : 'autopilot_updated',
+ meta: { armed: next.armed, kill_switch: next.kill_switch, rules: next.rules.map((r) => ({ kind: r.kind, enabled: r.enabled, paused: r.paused })) },
+ }).catch((e) => console.warn('[autopilot] config audit failed', e?.message));
+ logAudit({ userId, action: 'autopilot.config', resourceId: agentId, meta: { armed: next.armed, kill_switch: next.kill_switch }, req });
+
+ return next;
+}
+
+// ── period bucketing + idempotency ───────────────────────────────────────────────
+
+function utcParts(d = new Date()) {
+ return {
+ y: d.getUTCFullYear(),
+ m: String(d.getUTCMonth() + 1).padStart(2, '0'),
+ d: String(d.getUTCDate()).padStart(2, '0'),
+ h: String(d.getUTCHours()).padStart(2, '0'),
+ dow: d.getUTCDay(),
+ };
+}
+function isoWeek(d = new Date()) {
+ const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
+ const day = t.getUTCDay() || 7;
+ t.setUTCDate(t.getUTCDate() + 4 - day);
+ const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1));
+ const week = Math.ceil(((t - yearStart) / 86400000 + 1) / 7);
+ return `${t.getUTCFullYear()}-W${String(week).padStart(2, '0')}`;
+}
+
+// The deterministic period key for a rule's cadence. Two runs in the same period
+// share a key, so the idempotent claim below lets exactly one of them spend.
+function periodBucket(cadenceVal, now = new Date()) {
+ const p = utcParts(now);
+ if (cadenceVal === 'hourly') return `${p.y}-${p.m}-${p.d}-${p.h}`;
+ if (cadenceVal === 'weekly') return isoWeek(now);
+ return `${p.y}-${p.m}-${p.d}`;
+}
+
+// True when a weekday-gated rule is allowed to run today.
+function weekdayAllows(rule, now = new Date()) {
+ const wd = rule.params?.weekday;
+ if (wd == null) return true;
+ return now.getUTCDay() === wd;
+}
+
+/**
+ * Atomically claim this rule's action for the current period by inserting a
+ * single pending custody row keyed on a per-period idempotency key. Returns the
+ * row id, or null if the action was already claimed this period (skip). This is
+ * the no-double-spend guarantee: a retry in the same period finds the key taken.
+ */
+async function claimAction({ agentId, userId, category, network, idemKey, usd, lamports, meta }) {
+ const rows = await sql`
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset, amount_lamports, usd, status, idempotency_key, meta)
+ SELECT ${agentId}, ${userId ?? null}, 'spend', ${category}, ${network}, 'SOL',
+ ${lamports != null ? String(lamports) : null}, ${usd ?? null}, 'pending', ${idemKey},
+ ${JSON.stringify(meta ?? {})}::jsonb
+ WHERE NOT EXISTS (
+ SELECT 1 FROM agent_custody_events WHERE agent_id = ${agentId} AND idempotency_key = ${idemKey}
+ )
+ RETURNING id
+ `;
+ return rows.length ? rows[0].id : null;
+}
+
+// ── income + cost (real ledger reads) ────────────────────────────────────────────
+
+/** Sum the agent's REAL metered compute/voice cost (micro-USD ledger) since `sinceIso`. */
+export async function getComputeCostUsd(agentId, sinceIso = null) {
+ const [row] = await sql`
+ SELECT COALESCE(SUM(cost_micro_usd), 0)::bigint AS micro
+ FROM usage_events
+ WHERE agent_id = ${agentId}
+ AND cost_micro_usd IS NOT NULL
+ AND (${sinceIso}::timestamptz IS NULL OR created_at > ${sinceIso}::timestamptz)
+ `;
+ return Number(BigInt(row?.micro ?? '0')) / 1e6;
+}
+
+/** Sum the agent's REAL tip income (custody 'tip' rows) over a window. */
+export async function getTipIncomeUsd(agentId, network, sinceIso = null) {
+ const [row] = await sql`
+ SELECT COALESCE(SUM(usd), 0)::float8 AS usd
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND network = ${network} AND event_type = 'tip'
+ AND usd IS NOT NULL
+ AND (${sinceIso}::timestamptz IS NULL OR created_at > ${sinceIso}::timestamptz)
+ `;
+ return Number(row?.usd || 0);
+}
+
+// ── compute-settlement destination (where the agent pays for its brain) ──────────
+
+function resolveComputeTreasury() {
+ const explicit = (process.env.AUTOPILOT_COMPUTE_TREASURY || '').trim();
+ if (explicit) {
+ const v = validateSolanaAddress(explicit);
+ if (v.valid) return v.base58;
+ }
+ // Derive a public address from a configured platform treasury keypair.
+ for (const envName of ['PLATFORM_TREASURY_KEYPAIR', 'TREASURY_KEYPAIR', 'COIN_TREASURY_SECRET_KEY_B64']) {
+ const raw = (process.env[envName] || '').trim();
+ if (!raw) continue;
+ try {
+ const bytes = parseSecretBytes(raw);
+ if (bytes && bytes.length >= 64) {
+ // last 32 bytes of an ed25519 secret key are the public key
+ return new PublicKey(bytes.slice(32, 64)).toBase58();
+ }
+ } catch {
+ /* try next */
+ }
+ }
+ return null;
+}
+
+function parseSecretBytes(raw) {
+ if (raw.startsWith('[')) {
+ try {
+ return Uint8Array.from(JSON.parse(raw));
+ } catch {
+ return null;
+ }
+ }
+ // base64
+ try {
+ return Uint8Array.from(Buffer.from(raw, 'base64'));
+ } catch {
+ return null;
+ }
+}
+
+// ── token balance (real chain read) ──────────────────────────────────────────────
+
+async function tokenUiBalance(conn, owner, mint) {
+ try {
+ const res = await conn.getParsedTokenAccountsByOwner(new PublicKey(owner), { mint: new PublicKey(mint) });
+ let ui = 0;
+ for (const { account } of res.value) {
+ ui += account.data?.parsed?.info?.tokenAmount?.uiAmount || 0;
+ }
+ return ui;
+ } catch {
+ return null;
+ }
+}
+
+// ── real swap (Jupiter, mainnet) ─────────────────────────────────────────────────
+
+/**
+ * Swap `lamports` of native SOL into `outputMint` from the agent's wallet via
+ * Jupiter, returning the signature. Throws on devnet, no route, or any failure —
+ * the executor turns that into an honest pause, never a guess.
+ */
+async function swapSolToToken({ keypair, lamports, outputMint, slippageBps, network, conn }) {
+ if (network !== 'mainnet') {
+ throw Object.assign(new Error('token swaps are mainnet-only — this wallet is on devnet'), { code: 'devnet_no_swap' });
+ }
+ const qUrl = `${JUPITER_BASE}/quote?inputMint=${WSOL_MINT}&outputMint=${outputMint}&amount=${lamports.toString()}&slippageBps=${slippageBps}&swapMode=ExactIn`;
+ const qRes = await fetch(qUrl, { signal: AbortSignal.timeout(15_000) });
+ if (!qRes.ok) throw Object.assign(new Error(`no swap route (${qRes.status})`), { code: 'no_route' });
+ const quote = await qRes.json();
+ if (!quote || !quote.outAmount) throw Object.assign(new Error('no swap route for this pair'), { code: 'no_route' });
+
+ const sRes = await fetch(`${JUPITER_BASE}/swap`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ quoteResponse: quote,
+ userPublicKey: keypair.publicKey.toBase58(),
+ wrapAndUnwrapSol: true,
+ dynamicComputeUnitLimit: true,
+ prioritizationFeeLamports: 'auto',
+ }),
+ signal: AbortSignal.timeout(20_000),
+ });
+ if (!sRes.ok) throw Object.assign(new Error(`swap build failed (${sRes.status})`), { code: 'swap_failed' });
+ const { swapTransaction } = await sRes.json();
+ if (!swapTransaction) throw Object.assign(new Error('swap build returned no transaction'), { code: 'swap_failed' });
+
+ const tx = VersionedTransaction.deserialize(Buffer.from(swapTransaction, 'base64'));
+ tx.sign([keypair]);
+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });
+ const bh = await conn.getLatestBlockhash();
+ await conn.confirmTransaction({ signature: sig, ...bh }, 'confirmed');
+ return { signature: sig, outAmount: quote.outAmount, outMint: outputMint };
+}
+
+// ── the executor ─────────────────────────────────────────────────────────────────
+
+/**
+ * Run one autopilot cycle for an agent: execute every armed, due rule as a real,
+ * idempotent, spend-policy-gated, audited action on the agent's own wallet.
+ *
+ * @param {object} o
+ * @param {string} o.agentId
+ * @param {string|null} [o.userId] the actor (owner for a manual run; null for cron)
+ * @param {'mainnet'|'devnet'} [o.network]
+ * @param {string} [o.trigger] 'manual' | 'cron'
+ * @param {boolean} [o.dryRun] evaluate + report without moving funds
+ * @returns {Promise<object>} a per-rule result summary (no secrets)
+ */
+export async function runAutopilotCycle({ agentId, userId = null, network = 'mainnet', trigger = 'cron', dryRun = false }) {
+ const now = new Date();
+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;
+ if (!row) return { ran: false, reason: 'not_found' };
+
+ const meta = row.meta || {};
+ const policy = getAutopilot(meta);
+ const ownerId = row.user_id;
+
+ if (policy.kill_switch) return { ran: false, reason: 'kill_switch', results: [] };
+ if (!policy.armed) return { ran: false, reason: 'disarmed', results: [] };
+ if (!policy.rules.length) return { ran: false, reason: 'no_rules', results: [] };
+
+ const address = meta.solana_address;
+ const encryptedSecret = meta.encrypted_solana_secret;
+ if (!address) return { ran: false, reason: 'no_wallet', results: [] };
+
+ const limits = getSpendLimits(meta);
+ if (limits.frozen) {
+ return { ran: false, reason: 'wallet_frozen', results: [], note: 'Wallet is frozen — every autonomous spend is paused until you unfreeze it under Limits & Safety.' };
+ }
+
+ // Live price is the trust anchor for every USD conversion. If it's gone, we
+ // pause the whole cycle rather than guess with real money.
+ let price;
+ try {
+ price = await solUsdPrice();
+ } catch {
+ return { ran: false, reason: 'price_feed_unavailable', results: [], note: 'SOL/USD price feed is unavailable — autopilot paused this cycle and will retry.' };
+ }
+
+ const conn = solanaConnection(network);
+ let balances;
+ try {
+ balances = await getSolanaAddressBalances(address, network);
+ } catch (e) {
+ return { ran: false, reason: 'balance_read_failed', results: [], note: e?.message || 'could not read wallet balance' };
+ }
+ const balanceSol = Number(balances?.sol || 0);
+ const balanceLamports = BigInt(Math.floor(balanceSol * 1e9));
+ const bufferSol = policy.buffer_sol || 0;
+ const bufferLamports = BigInt(Math.floor(bufferSol * 1e9));
+ const bufferBreached = balanceLamports < bufferLamports;
+
+ // Order matters: pay the brain first, check the buffer, then DCA/buyback, sweep last.
+ const order = { self_fund: 0, buffer: 1, dca: 2, buyback: 3, sweep: 4 };
+ const due = policy.rules
+ .filter((r) => r.enabled && !r.paused)
+ .sort((a, b) => (order[a.kind] ?? 9) - (order[b.kind] ?? 9));
+
+ // Recover the signing keypair once, only when a real spend rule may run.
+ let keypair = null;
+ const hasSpendRule = due.some((r) => r.kind !== 'buffer');
+ if (hasSpendRule && !dryRun) {
+ if (!encryptedSecret) return { ran: false, reason: 'no_secret', results: [] };
+ try {
+ keypair = await recoverSolanaAgentKeypair(encryptedSecret, { agentId, userId: userId ?? ownerId, reason: 'treasury_autopilot' });
+ } catch (e) {
+ return { ran: false, reason: 'key_recover_failed', results: [], note: e?.message || 'could not recover wallet key' };
+ }
+ }
+
+ const results = [];
+ const ctx = { agentId, ownerId, userId, network, trigger, dryRun, now, conn, price, address, bufferSol, bufferLamports, balanceLamports, bufferBreached, policy, meta, keypair };
+
+ for (const rule of due) {
+ if (!weekdayAllows(rule, now)) {
+ results.push(stamp(rule, { status: 'skipped', note: 'not scheduled today' }, now));
+ continue;
+ }
+ let res;
+ try {
+ res = await executeRule(rule, ctx);
+ } catch (e) {
+ res = { status: 'error', note: (e?.message || 'execution failed').slice(0, 240) };
+ }
+ results.push(stamp(rule, res, now));
+ }
+
+ // Persist updated per-rule status + compute-settlement marker (best-effort).
+ if (!dryRun) {
+ try {
+ const fresh = getAutopilot((await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`)[0]?.meta);
+ const byId = new Map(results.map((r) => [r.id, r]));
+ fresh.rules = fresh.rules.map((r) => {
+ const u = byId.get(r.id);
+ return u ? { ...r, last_run_at: u.last_run_at, last_status: u.last_status, last_note: u.last_note } : r;
+ });
+ const settled = results.find((r) => r.kind === 'self_fund' && r.last_status === 'ok');
+ if (settled) fresh.compute_settled_at = now.toISOString();
+ fresh.updated_at = now.toISOString();
+ const m2 = { ...((await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`)[0]?.meta || {}), autopilot: fresh };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(m2)}::jsonb WHERE id = ${agentId}`;
+ } catch (e) {
+ console.warn('[autopilot] status persist failed', e?.message);
+ }
+ }
+
+ return { ran: true, trigger, dryRun, results };
+}
+
+function stamp(rule, res, now) {
+ return {
+ id: rule.id,
+ kind: rule.kind,
+ label: rule.label,
+ last_run_at: now.toISOString(),
+ last_status: res.status,
+ last_note: res.note || null,
+ signature: res.signature || null,
+ explorer: res.explorer || null,
+ usd: res.usd ?? null,
+ };
+}
+
+async function executeRule(rule, ctx) {
+ switch (rule.kind) {
+ case 'self_fund':
+ return execSelfFund(rule, ctx);
+ case 'buffer':
+ return execBuffer(rule, ctx);
+ case 'dca':
+ return execDca(rule, ctx);
+ case 'buyback':
+ return execBuyback(rule, ctx);
+ case 'sweep':
+ return execSweep(rule, ctx);
+ default:
+ return { status: 'skipped', note: 'unknown rule' };
+ }
+}
+
+// Shared: enforce the spend policy, claim the period idempotently, run the spend,
+// finalize the custody row. `doSpend(lamports)` must return { signature }.
+async function gatedSpend({ ctx, rule, category, usd, lamports, rowMeta, doSpend }) {
+ const { agentId, ownerId, userId, network, dryRun } = ctx;
+ // Hard ceiling: clamp to the spend policy at execution time (server-side).
+ try {
+ await enforceSpendLimit({ agentId, meta: ctx.meta, category: 'autopilot', usdValue: usd, network });
+ } catch (e) {
+ if (e instanceof SpendLimitError) return { status: 'paused', note: e.message, usd };
+ throw e;
+ }
+ if (dryRun) return { status: 'would_run', note: `would spend ~$${usd.toFixed(2)}`, usd };
+
+ const idemKey = `ap:${rule.id}:${periodBucket(rule.params?.cadence || 'hourly', ctx.now)}`;
+ const reservationId = await claimAction({
+ agentId, userId: userId ?? ownerId, category, network, idemKey, usd, lamports,
+ meta: { ...rowMeta, rule_id: rule.id, kind: rule.kind, trigger: ctx.trigger, autopilot: true },
+ });
+ if (!reservationId) return { status: 'skipped', note: 'already executed this period' };
+
+ try {
+ const { signature } = await doSpend(lamports);
+ await updateCustodyEvent(reservationId, { status: 'confirmed', signature, meta: { settled_at: ctx.now.toISOString() } });
+ return { status: 'ok', signature, explorer: explorerTxUrl(signature, network), usd };
+ } catch (e) {
+ await updateCustodyEvent(reservationId, { status: 'failed', meta: { error: (e?.message || 'failed').slice(0, 200) } });
+ return { status: 'error', note: (e?.message || 'transaction failed').slice(0, 240), usd };
+ }
+}
+
+async function execSelfFund(rule, ctx) {
+ const { agentId, network, price, balanceLamports, bufferLamports, policy } = ctx;
+ const since = policy.compute_settled_at || null;
+ const costUsd = await getComputeCostUsd(agentId, since);
+ if (costUsd < DUST_USD) return { status: 'skipped', note: 'no metered compute cost has accrued yet' };
+
+ const treasury = resolveComputeTreasury();
+ if (!treasury) return { status: 'paused', note: 'No compute-settlement treasury is configured (AUTOPILOT_COMPUTE_TREASURY) — self-funding is paused.' };
+
+ let lamports = BigInt(Math.ceil((costUsd / price) * 1e9));
+ // Never breach the buffer or leave the wallet unable to pay fees.
+ const spendable = balanceLamports - bufferLamports - FEE_HEADROOM_LAMPORTS;
+ if (spendable <= 0n) {
+ return { status: 'paused', note: `Income too small to self-fund without breaching the ${ctx.bufferSol} SOL buffer — paused, fund the wallet or lower the buffer.` };
+ }
+ if (lamports > spendable) lamports = spendable; // partial settlement is honest progress
+ const usd = (Number(lamports) / 1e9) * price;
+
+ return gatedSpend({
+ ctx, rule, category: 'autopilot', usd, lamports,
+ rowMeta: { action: 'self_fund', destination: treasury, compute_cost_usd: costUsd, settled_since: since },
+ doSpend: (lams) => sendSol({ connection: ctx.conn, fromKeypair: ctx.keypair, to: treasury, lamports: Number(lams), memo: 'autopilot:self_fund', network }),
+ });
+}
+
+async function execBuffer(rule, ctx) {
+ const { agentId, ownerId, network, balanceLamports, bufferLamports, bufferSol, dryRun, now } = ctx;
+ const balSol = Number(balanceLamports) / 1e9;
+ const ok = balanceLamports >= bufferLamports;
+ const note = ok
+ ? `Buffer healthy: ${balSol.toFixed(4)} SOL held, ${bufferSol} SOL floor maintained.`
+ : `Buffer breached: ${balSol.toFixed(4)} SOL held, below the ${bufferSol} SOL floor — spending rules are gated until income restores it.`;
+ if (!dryRun) {
+ // Record an audited, non-spend buffer check (idempotent per hour).
+ const idemKey = `ap:${rule.id}:${periodBucket('hourly', now)}`;
+ await sql`
+ INSERT INTO agent_custody_events (agent_id, user_id, event_type, category, network, asset, status, idempotency_key, meta)
+ SELECT ${agentId}, ${ownerId}, 'autopilot_check', 'buffer', ${network}, 'SOL', ${ok ? 'ok' : 'failed'}, ${idemKey},
+ ${JSON.stringify({ kind: 'buffer', balance_sol: balSol, buffer_sol: bufferSol, ok })}::jsonb
+ WHERE NOT EXISTS (SELECT 1 FROM agent_custody_events WHERE agent_id = ${agentId} AND idempotency_key = ${idemKey})
+ `.catch(() => {});
+ }
+ return { status: ok ? 'ok' : 'alert', note };
+}
+
+async function execDca(rule, ctx) {
+ const { agentId, network, price, balanceLamports, bufferLamports, bufferBreached, policy, now } = ctx;
+ if (bufferBreached) return { status: 'skipped', note: 'balance is below the buffer — DCA skipped to protect the floor' };
+
+ const p = rule.params;
+ let lamports;
+ if (p.amount_sol != null) {
+ lamports = BigInt(Math.floor(p.amount_sol * 1e9));
+ } else if (p.basis === 'income') {
+ const since = policy.updated_at && rule.last_run_at ? rule.last_run_at : windowStart(p.cadence, now);
+ const incomeUsd = await getTipIncomeUsd(agentId, network, since);
+ if (incomeUsd < DUST_USD) return { status: 'skipped', note: 'no new tip income this period to DCA' };
+ lamports = BigInt(Math.floor(((incomeUsd * (p.pct / 100)) / price) * 1e9));
+ } else {
+ // surplus basis: a slice of spendable surplus above the buffer
+ const surplus = balanceLamports - bufferLamports - FEE_HEADROOM_LAMPORTS;
+ if (surplus <= 0n) return { status: 'skipped', note: 'no surplus above the buffer to DCA' };
+ lamports = (surplus * BigInt(Math.round(p.pct * 100))) / 10000n;
+ }
+
+ // Never breach the buffer or fee headroom.
+ const spendable = balanceLamports - bufferLamports - FEE_HEADROOM_LAMPORTS;
+ if (lamports > spendable) lamports = spendable;
+ if (lamports <= 0n) return { status: 'skipped', note: 'computed DCA size is below the buffer headroom' };
+ const usd = (Number(lamports) / 1e9) * price;
+ if (usd < DUST_USD) return { status: 'skipped', note: 'computed DCA size is below the dust threshold' };
+
+ return gatedSpend({
+ ctx, rule, category: 'autopilot', usd, lamports,
+ rowMeta: { action: 'dca', target_mint: THREE_MINT, basis: p.basis, pct: p.pct, symbol: '$THREE' },
+ doSpend: async (lams) => {
+ const r = await swapSolToToken({ keypair: ctx.keypair, lamports: lams, outputMint: THREE_MINT, slippageBps: p.slippage_bps, network, conn: ctx.conn });
+ return { signature: r.signature };
+ },
+ });
+}
+
+async function execBuyback(rule, ctx) {
+ const { agentId, network, price, balanceLamports, bufferLamports, bufferBreached } = ctx;
+ if (bufferBreached) return { status: 'skipped', note: 'balance is below the buffer — buyback skipped to protect the floor' };
+
+ // The agent's own coin (launched through three.ws). No coin → nothing to compound.
+ const [coin] = await sql`SELECT mint FROM pump_agent_mints WHERE agent_id = ${agentId} AND network = ${network} ORDER BY created_at ASC LIMIT 1`;
+ if (!coin?.mint) return { status: 'skipped', note: 'this agent has not launched a coin — nothing to buy back' };
+
+ const p = rule.params;
+ // Compound real accrued creator fees: approximate the compoundable pot as the
+ // surplus above the buffer (fees land in the same wallet), scaled by pct_of_fees.
+ const surplus = balanceLamports - bufferLamports - FEE_HEADROOM_LAMPORTS;
+ if (surplus <= 0n) return { status: 'skipped', note: 'no surplus above the buffer to compound into a buyback' };
+ let lamports = (surplus * BigInt(Math.round(p.pct_of_fees * 100))) / 10000n;
+ if (lamports <= 0n) return { status: 'skipped', note: 'computed buyback size is zero' };
+ const usd = (Number(lamports) / 1e9) * price;
+ if (usd < DUST_USD) return { status: 'skipped', note: 'computed buyback size is below the dust threshold' };
+
+ return gatedSpend({
+ ctx, rule, category: 'autopilot', usd, lamports,
+ rowMeta: { action: 'buyback', mint: coin.mint, pct_of_fees: p.pct_of_fees },
+ doSpend: async (lams) => {
+ const r = await swapSolToToken({ keypair: ctx.keypair, lamports: lams, outputMint: coin.mint, slippageBps: p.slippage_bps, network, conn: ctx.conn });
+ return { signature: r.signature };
+ },
+ });
+}
+
+async function execSweep(rule, ctx) {
+ const { network, price, balanceLamports, policy } = ctx;
+ const p = rule.params;
+ const destination = p.destination || policy.sweep_destination;
+ if (!destination) return { status: 'paused', note: 'No sweep destination set — add your wallet under Autopilot before this rule can run.' };
+
+ const thresholdLamports = BigInt(Math.floor(p.threshold_sol * 1e9));
+ if (balanceLamports <= thresholdLamports) {
+ return { status: 'skipped', note: `balance ${(Number(balanceLamports) / 1e9).toFixed(4)} SOL is at or below the ${p.threshold_sol} SOL sweep threshold` };
+ }
+ // Sweep only the excess above the threshold, leaving fee headroom in place.
+ let lamports = balanceLamports - thresholdLamports;
+ if (lamports > balanceLamports - FEE_HEADROOM_LAMPORTS) lamports = balanceLamports - FEE_HEADROOM_LAMPORTS;
+ if (lamports <= 0n) return { status: 'skipped', note: 'nothing to sweep after fee headroom' };
+ const usd = (Number(lamports) / 1e9) * price;
+
+ return gatedSpend({
+ ctx, rule, category: 'autopilot', usd, lamports,
+ rowMeta: { action: 'sweep', destination, threshold_sol: p.threshold_sol },
+ doSpend: (lams) => sendSol({ connection: ctx.conn, fromKeypair: ctx.keypair, to: destination, lamports: Number(lams), memo: 'autopilot:sweep', network }),
+ });
+}
+
+function windowStart(cadenceVal, now = new Date()) {
+ const ms = cadenceVal === 'hourly' ? 3600e3 : cadenceVal === 'weekly' ? 7 * 86400e3 : 86400e3;
+ return new Date(now.getTime() - ms).toISOString();
+}
+
+// ── the runway view (real income / cost / runway) ────────────────────────────────
+
+/**
+ * Build the real runway dashboard for an agent: 30-day income vs cost, current
+ * buffer, $THREE accumulated, buybacks executed, profit swept, current balance,
+ * and the honest runway (how long it self-sustains at the real burn). Every
+ * number traces to a real chain read or DB row; a net-negative agent shows the
+ * truth, not a projection.
+ */
+export async function computeRunway({ agentId, network = 'mainnet', meta = null }) {
+ const m = meta || (await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`)[0]?.meta || {};
+ const policy = getAutopilot(m);
+ const address = m.solana_address || null;
+ const since30 = new Date(Date.now() - 30 * 86400e3).toISOString();
+
+ let price = null;
+ try {
+ price = await solUsdPrice();
+ } catch {
+ price = null;
+ }
+
+ let balanceSol = 0;
+ let threeUi = null;
+ if (address) {
+ try {
+ const b = await getSolanaAddressBalances(address, network);
+ balanceSol = Number(b?.sol || 0);
+ } catch {
+ /* leave 0 */
+ }
+ try {
+ const conn = solanaConnection(network);
+ threeUi = await tokenUiBalance(conn, address, THREE_MINT);
+ } catch {
+ threeUi = null;
+ }
+ }
+
+ const [costUsd, tipUsd] = await Promise.all([
+ getComputeCostUsd(agentId, since30).catch(() => 0),
+ getTipIncomeUsd(agentId, network, since30).catch(() => 0),
+ ]);
+
+ // Break the autopilot spend out by action for the dashboard (sweep/buyback/dca/
+ // self_fund all use category 'autopilot'; split by the recorded meta.action).
+ const breakdown = await sql`
+ SELECT meta->>'action' AS action, COALESCE(SUM(usd),0)::float8 AS usd,
+ COALESCE(SUM(amount_lamports),0)::text AS lamports, COUNT(*)::int AS n
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND event_type = 'spend' AND category = 'autopilot'
+ AND status IN ('ok','confirmed') AND created_at > ${since30}::timestamptz
+ GROUP BY meta->>'action'
+ `.catch(() => []);
+ const byAction = {};
+ for (const r of breakdown) byAction[r.action || 'other'] = { usd: Number(r.usd || 0), sol: Number(BigInt(r.lamports || '0')) / 1e9, count: Number(r.n || 0) };
+
+ const balanceUsd = price != null ? balanceSol * price : null;
+ const bufferUsd = price != null && policy.buffer_sol != null ? policy.buffer_sol * price : null;
+ const incomeUsd = tipUsd;
+ const netUsd = incomeUsd - costUsd;
+ const dailyBurnUsd = costUsd / 30;
+ const dailyIncomeUsd = incomeUsd / 30;
+ const netDailyUsd = dailyIncomeUsd - dailyBurnUsd;
+ // Runway: spendable balance above the buffer divided by the net daily burn.
+ const spendableUsd = balanceUsd != null ? Math.max(0, balanceUsd - (bufferUsd || 0)) : null;
+ let runwayDays = null;
+ if (spendableUsd != null) {
+ if (netDailyUsd >= 0) runwayDays = Infinity; // self-sustaining or profitable
+ else runwayDays = spendableUsd / -netDailyUsd;
+ }
+
+ return {
+ network,
+ price_usd: price,
+ balance_sol: balanceSol,
+ balance_usd: balanceUsd,
+ buffer_sol: policy.buffer_sol,
+ buffer_usd: bufferUsd,
+ three_accumulated: threeUi,
+ window_days: 30,
+ income_usd: incomeUsd,
+ cost_usd: costUsd,
+ net_usd: netUsd,
+ net_positive: netUsd >= 0,
+ daily_burn_usd: dailyBurnUsd,
+ daily_income_usd: dailyIncomeUsd,
+ net_daily_usd: netDailyUsd,
+ runway_days: runwayDays === Infinity ? null : runwayDays,
+ self_sustaining: netDailyUsd >= 0,
+ self_funded_usd: byAction.self_fund?.usd || 0,
+ dca_usd: byAction.dca?.usd || 0,
+ dca_count: byAction.dca?.count || 0,
+ buyback_usd: byAction.buyback?.usd || 0,
+ buyback_count: byAction.buyback?.count || 0,
+ swept_usd: byAction.sweep?.usd || 0,
+ swept_sol: byAction.sweep?.sol || 0,
+ sweep_count: byAction.sweep?.count || 0,
+ armed: policy.armed,
+ kill_switch: policy.kill_switch,
+ explorer_account: address ? explorerAccountUrl(address, network) : null,
+ };
+}
diff --git a/api/_lib/trust/wallet-reputation.js b/api/_lib/trust/wallet-reputation.js
index ac9da25fc..63d4fadaf 100644
--- a/api/_lib/trust/wallet-reputation.js
+++ b/api/_lib/trust/wallet-reputation.js
@@ -468,6 +468,35 @@ export async function getAgentReputation(agentId, opts = {}) {
};
}
+/**
+ * Compact, best-effort reputation for a set of agents — used by discovery
+ * ranking (trending, the trusted leaderboard) where many agents are scored at
+ * once. Always lite (no per-agent EVM RPC), always resilient: an agent that
+ * fails to score is simply omitted, never faked. Returns a Map id -> compact.
+ */
+export async function scoreAgentsLite(agentIds = [], { concurrency = 8 } = {}) {
+ const ids = [...new Set(agentIds.filter(Boolean))];
+ const out = new Map();
+ for (let i = 0; i < ids.length; i += concurrency) {
+ const chunk = ids.slice(i, i + concurrency);
+ const settled = await Promise.allSettled(chunk.map((id) => getAgentReputation(id, { lite: true })));
+ settled.forEach((r, idx) => {
+ if (r.status === 'fulfilled' && r.value) {
+ const v = r.value;
+ out.set(chunk[idx], {
+ score: v.score,
+ tier: v.tier,
+ tierLabel: v.tierLabel,
+ accent: v.accent,
+ isNew: v.isNew,
+ totals: v.totals,
+ });
+ }
+ });
+ }
+ return out;
+}
+
async function readErc8004Registry(agent) {
if (!agent.erc8004_agent_id || !agent.chain_id) return { average: 0, count: 0 };
const RPC = {
diff --git a/api/_lib/x402-user-payer.js b/api/_lib/x402-user-payer.js
index 9f8b914e6..2ab0d5c39 100644
--- a/api/_lib/x402-user-payer.js
+++ b/api/_lib/x402-user-payer.js
@@ -123,16 +123,34 @@ export async function resolveUserAgentWallet(userId) {
LIMIT 1
`;
if (!row) return null;
- const address = row.meta?.solana_address || null;
+ return shapeWallet(row);
+}
+
+function shapeWallet(row) {
+ if (!row) return null;
return {
agentId: row.id,
name: row.name || null,
- address,
+ address: row.meta?.solana_address || null,
hasSecret: !!row.meta?.encrypted_solana_secret,
encryptedSecret: row.meta?.encrypted_solana_secret || null,
};
}
+// A SPECIFIC agent's wallet, but only if the caller owns it. Used by the
+// agent-to-agent economy so the hiring agent the owner chose is the one that
+// pays — not just their first-created agent. Returns null when the agent does not
+// exist or is not owned by `userId`, so the caller fails closed.
+export async function resolveAgentWalletById(agentId, userId) {
+ if (!agentId || !userId) return null;
+ const [row] = await sql`
+ SELECT id, name, meta FROM agent_identities
+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ return shapeWallet(row);
+}
+
// Build a paying axios instance bound to the user's Solana keypair, with the
// platform spending cap installed. Returns { api, client, uninstall, address }.
async function buildUserPayingClient({ wallet, userId, maxPerCallOverride }) {
@@ -265,7 +283,7 @@ export async function getUserWalletStatus(userId) {
// Pay an external x402 endpoint from the user's wallet. Throws an Error with a
// `.code` for the boundary (the MCP handler) to translate into a clean result.
-export async function payExternalX402({ userId, url, method = 'GET', body, maxUsd }) {
+export async function payExternalX402({ userId, agentId, url, method = 'GET', body, maxUsd }) {
if (!resolveSpendEnabled()) {
throw Object.assign(new Error('autonomous spending is disabled on this server'), {
code: 'spend_disabled',
@@ -276,7 +294,12 @@ export async function payExternalX402({ userId, url, method = 'GET', body, maxUs
code: 'auth_required',
});
}
- const wallet = await resolveUserAgentWallet(userId);
+ // When the caller names a specific agent (the agent-to-agent economy), that
+ // agent — owned by this user — is the payer. Otherwise fall back to the user's
+ // primary agent wallet (the original pay_and_call behavior).
+ const wallet = agentId
+ ? await resolveAgentWalletById(agentId, userId)
+ : await resolveUserAgentWallet(userId);
if (!wallet) {
throw Object.assign(new Error('no agent wallet found for this account'), {
code: 'no_wallet',
diff --git a/api/agent-share.js b/api/agent-share.js
index 3f590d450..c0ee408ff 100644
--- a/api/agent-share.js
+++ b/api/agent-share.js
@@ -69,19 +69,35 @@ export default wrap(async (req, res) => {
const thumbPublic = thumbVis === 'public' || thumbVis === 'unlisted';
const thumbUrl = thumbKey && thumbPublic ? `${CDN_BASE}/${thumbKey}` : null;
- const ogImage = `${origin}/api/og/agent?id=${encodeURIComponent(id)}`;
- const pageUrl = `${origin}/agent/${encodeURIComponent(id)}/share`;
- const deepUrl = `${origin}/agent/${encodeURIComponent(id)}`;
+ // "Share my wallet" variant (?wallet=1) — the OG image becomes the SVG card
+ // (which renders the vanity address + lifetime tips), the deep link lands on
+ // the wallet view, and the social copy invites a tip/fork. This is the growth
+ // loop: a wallet worth screenshotting that links back to pay or fork it.
+ const walletShare = url.searchParams.get('wallet') === '1';
- const title = isOnchain
- ? `${name} · 3D AI Agent on ${chainLabel} · three.ws`
- : `${name} · 3D AI Agent · three.ws`;
- const desc = buildDesc({ description, isOnchain, chainLabel });
+ const ogImage = `${origin}/api/og/agent?id=${encodeURIComponent(id)}`;
+ const pageUrl = `${origin}/agent/${encodeURIComponent(id)}/share${walletShare ? '?wallet=1' : ''}`;
+ const deepUrl = walletShare
+ ? `${origin}/agent/${encodeURIComponent(id)}/wallet`
+ : `${origin}/agent/${encodeURIComponent(id)}`;
+
+ const title = walletShare
+ ? `Tip ${name}'s wallet · 3D AI Agent · three.ws`
+ : isOnchain
+ ? `${name} · 3D AI Agent on ${chainLabel} · three.ws`
+ : `${name} · 3D AI Agent · three.ws`;
+ const desc = walletShare
+ ? `${name} is a self-custodial 3D AI agent on three.ws. Tip it, or fork it to mint your own wallet.`
+ : buildDesc({ description, isOnchain, chainLabel });
+
+ // For a wallet share, always use the SVG card (it carries the wallet identity);
+ // otherwise prefer the richer raw thumbnail when the avatar is public.
+ const forcedOgImage = walletShare ? ogImage : null;
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');
- res.end(renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, name, origin }));
+ res.end(renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, forcedOgImage, name, origin }));
});
function redirect(res, to) {
@@ -104,11 +120,12 @@ function esc(s) {
);
}
-function renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, name, origin }) {
+function renderHtml({ title, desc, pageUrl, deepUrl, ogImage, thumbUrl, forcedOgImage, name, origin }) {
const t = esc(title);
const d = esc(desc);
- // Use the actual thumbnail as OG image when available — richer than the SVG card
- const finalOgImage = thumbUrl || ogImage;
+ // A wallet share forces the SVG card (it carries the wallet identity); otherwise
+ // use the actual thumbnail when available — richer than the SVG card.
+ const finalOgImage = forcedOgImage || thumbUrl || ogImage;
return `<!doctype html>
<html lang="en">
<head>
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 58af4fbe8..7bb2deba1 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -62,11 +62,26 @@ export default wrap(async function handler(req, res) {
return mod.default(req, res, id, action);
}
+ if (sub === 'recovery') {
+ const mod = await import('./recovery.js');
+ return mod.default(req, res, id, action, parts);
+ }
+
if (sub === 'trade') {
const mod = await import('./agent-trade.js');
return mod.default(req, res, id, action);
}
+ if (sub === 'autopilot') {
+ const mod = await import('./autopilot.js');
+ return mod.default(req, res, id, action);
+ }
+
+ if (sub === 'mirror') {
+ const mod = await import('./agent-mirror.js');
+ return mod.default(req, res, id, action);
+ }
+
if (sub === 'eth-vanity') {
const mod = await import('./eth-vanity.js');
return mod.default(req, res, id, action);
diff --git a/api/agents/[id]/economy.js b/api/agents/[id]/economy.js
new file mode 100644
index 000000000..da8349a9b
--- /dev/null
+++ b/api/agents/[id]/economy.js
@@ -0,0 +1,289 @@
+// GET /api/agents/:id/economy — the owner-facing economy summary for one agent.
+//
+// "Your avatar has a job." This is the single read behind the wallet hub's Earn
+// tab: every dollar the agent has earned (skill sales + tips) and every dollar
+// it has spent paying other services over x402, plus the live spend policy that
+// keeps autonomous spending safe, and a unified receipts statement. Every number
+// traces to a real ledger row — agent_custody_events, skill_payment_earnings,
+// skill_purchases — never a mock.
+//
+// Owner-only: these are the agent owner's private financials. Ownership is
+// asserted the same way as the rest of the owner-gated wallet surface
+// (agent_identities.user_id === auth.userId). A public "earned $X" brag uses the
+// public pulse agent-summary instead; this endpoint never leaks to a visitor.
+//
+// earnings : skill sales + tips, windowed today / 7d / lifetime (USD)
+// spending : x402 agent-to-agent payments, windowed (USD)
+// policy : daily/per-tx caps, allowlist size, frozen, today's spend
+// receipts : recent in + out movements as a clean statement
+// peers : top counterparties the agent has paid (the A2A network edge)
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { sql } from '../../_lib/db.js';
+import { getSpendLimits, getDailySpendUsd } from '../../_lib/agent-trade-guards.js';
+import { env } from '../../_lib/env.js';
+
+// Skill prices are denominated in USDC (6 decimals) across the platform — the
+// pricing UI bills in USDC and net_amount is stored in that mint's atomic units.
+// We surface USDC earnings as USD 1:1 (the dominant, priceable case) and report
+// any non-USDC sales as a count so nothing is silently dropped or mis-priced.
+const USDC_MINT = env.X402_ASSET_MINT_SOLANA || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+const RECEIPTS_LIMIT = 40;
+const PEERS_LIMIT = 8;
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req).catch(() => null);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req)).catch(() => null);
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const id = url.searchParams.get('id') || url.pathname.split('/').filter(Boolean)[2];
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ // Ownership gate — private financials are owner-only, enforced server-side.
+ const [agent] = await sql`
+ SELECT id, user_id, name, skills, meta FROM agent_identities
+ WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ try {
+ const [
+ skillEarn,
+ tips,
+ spend,
+ pricedSkills,
+ tipReceipts,
+ saleReceipts,
+ spendReceipts,
+ peers,
+ spentTodayUsd,
+ ] = await Promise.all([
+ // Skill sales (creator net), windowed. USDC atomic → USD (1:1, 6dp).
+ sql`
+ SELECT
+ COALESCE(SUM(net_amount) FILTER (WHERE created_at >= date_trunc('day', now())), 0)::text AS today,
+ COALESCE(SUM(net_amount) FILTER (WHERE created_at >= now() - interval '7 days'), 0)::text AS week,
+ COALESCE(SUM(net_amount), 0)::text AS lifetime,
+ COUNT(*)::int AS count,
+ COUNT(*) FILTER (WHERE currency_mint <> ${USDC_MINT})::int AS non_usdc_count
+ FROM skill_payment_earnings
+ WHERE agent_id = ${id} AND currency_mint = ${USDC_MINT}
+ `,
+ // Tips received (already USD-priced on the custody row).
+ sql`
+ SELECT
+ COALESCE(SUM(usd) FILTER (WHERE created_at >= date_trunc('day', now())), 0)::float8 AS today,
+ COALESCE(SUM(usd) FILTER (WHERE created_at >= now() - interval '7 days'), 0)::float8 AS week,
+ COALESCE(SUM(usd), 0)::float8 AS lifetime,
+ COUNT(*)::int AS count
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND network = ${network}
+ AND event_type = 'tip' AND status IN ('ok', 'confirmed')
+ `,
+ // Outbound agent-to-agent payments over x402 (USD-priced).
+ sql`
+ SELECT
+ COALESCE(SUM(usd) FILTER (WHERE created_at >= date_trunc('day', now())), 0)::float8 AS today,
+ COALESCE(SUM(usd) FILTER (WHERE created_at >= now() - interval '7 days'), 0)::float8 AS week,
+ COALESCE(SUM(usd), 0)::float8 AS lifetime,
+ COUNT(*)::int AS count
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND network = ${network}
+ AND event_type = 'spend' AND category = 'x402'
+ AND status IN ('ok', 'confirmed', 'pending')
+ `,
+ // The earning engine: active priced skills.
+ sql`
+ SELECT skill, amount, currency_mint, pricing_type
+ FROM agent_skill_prices
+ WHERE agent_id = ${id} AND is_active = true
+ ORDER BY amount DESC
+ `,
+ // Inbound receipts — tips.
+ sql`
+ SELECT id, usd, amount_lamports, signature, created_at, meta
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND network = ${network}
+ AND event_type = 'tip' AND status IN ('ok', 'confirmed')
+ ORDER BY created_at DESC
+ LIMIT ${RECEIPTS_LIMIT}
+ `,
+ // Inbound receipts — skill sales (join the purchase for skill + buyer + tx).
+ sql`
+ SELECT e.id, e.net_amount, e.gross_amount, e.currency_mint, e.created_at,
+ sp.skill, sp.tx_signature, sp.user_id AS buyer_user_id
+ FROM skill_payment_earnings e
+ JOIN skill_purchases sp ON sp.id = e.payment_id
+ WHERE e.agent_id = ${id}
+ ORDER BY e.created_at DESC
+ LIMIT ${RECEIPTS_LIMIT}
+ `,
+ // Outbound receipts — x402 payments.
+ sql`
+ SELECT id, usd, signature, destination, status, created_at, meta
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND network = ${network}
+ AND event_type = 'spend' AND category = 'x402'
+ AND status IN ('ok', 'confirmed', 'pending')
+ ORDER BY created_at DESC
+ LIMIT ${RECEIPTS_LIMIT}
+ `,
+ // Top counterparties the agent has paid — the A2A network edge.
+ sql`
+ SELECT destination, COUNT(*)::int AS count,
+ COALESCE(SUM(usd), 0)::float8 AS usd,
+ MAX(created_at) AS last_at
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND network = ${network}
+ AND event_type = 'spend' AND category = 'x402'
+ AND status IN ('ok', 'confirmed') AND destination IS NOT NULL
+ GROUP BY destination
+ ORDER BY usd DESC
+ LIMIT ${PEERS_LIMIT}
+ `,
+ getDailySpendUsd(id, network).catch(() => null),
+ ]);
+
+ const usdc = (atomic) => Number(BigInt(atomic || '0')) / 1e6;
+ const se = skillEarn[0] || {};
+ const tp = tips[0] || {};
+ const sp = spend[0] || {};
+
+ const earnings = {
+ skill_sales: {
+ today: usdc(se.today),
+ week: usdc(se.week),
+ lifetime: usdc(se.lifetime),
+ count: Number(se.count || 0),
+ non_usdc_count: Number(se.non_usdc_count || 0),
+ },
+ tips: {
+ today: Number(tp.today || 0),
+ week: Number(tp.week || 0),
+ lifetime: Number(tp.lifetime || 0),
+ count: Number(tp.count || 0),
+ },
+ };
+ earnings.total = {
+ today: earnings.skill_sales.today + earnings.tips.today,
+ week: earnings.skill_sales.week + earnings.tips.week,
+ lifetime: earnings.skill_sales.lifetime + earnings.tips.lifetime,
+ count: earnings.skill_sales.count + earnings.tips.count,
+ };
+
+ const spending = {
+ x402: {
+ today: Number(sp.today || 0),
+ week: Number(sp.week || 0),
+ lifetime: Number(sp.lifetime || 0),
+ count: Number(sp.count || 0),
+ },
+ };
+
+ const lim = getSpendLimits(agent.meta);
+ const policy = {
+ daily_usd: lim.daily_usd,
+ per_tx_usd: lim.per_tx_usd,
+ allowlist_count: lim.withdraw_allowlist.length,
+ frozen: lim.frozen === true,
+ spent_today_usd: spentTodayUsd == null ? null : Number(spentTodayUsd),
+ };
+
+ // Merge inbound + outbound into one statement, newest first.
+ const receipts = [];
+ for (const r of tipReceipts) {
+ receipts.push({
+ id: `tip-${r.id}`,
+ direction: 'in',
+ kind: 'tip',
+ usd: r.usd != null ? Number(r.usd) : null,
+ sol: r.amount_lamports != null ? Number(r.amount_lamports) / 1e9 : null,
+ counterparty: r.meta?.from || null,
+ label: 'Tip received',
+ signature: r.signature || null,
+ status: 'confirmed',
+ created_at: r.created_at,
+ });
+ }
+ for (const r of saleReceipts) {
+ receipts.push({
+ id: `sale-${r.id}`,
+ direction: 'in',
+ kind: 'skill_sale',
+ usd: r.currency_mint === USDC_MINT ? Number(BigInt(r.net_amount || '0')) / 1e6 : null,
+ counterparty: r.buyer_user_id || null,
+ label: r.skill ? `Skill sold · ${r.skill}` : 'Skill sold',
+ skill: r.skill || null,
+ signature: r.tx_signature || null,
+ status: 'confirmed',
+ created_at: r.created_at,
+ });
+ }
+ for (const r of spendReceipts) {
+ receipts.push({
+ id: `pay-${r.id}`,
+ direction: 'out',
+ kind: 'x402',
+ usd: r.usd != null ? Number(r.usd) : null,
+ counterparty: r.destination || null,
+ label: r.meta?.service || (r.meta?.url ? hostOf(r.meta.url) : 'Service payment'),
+ resource: r.meta?.url || null,
+ signature: r.signature || null,
+ status: r.status || 'confirmed',
+ created_at: r.created_at,
+ });
+ }
+ receipts.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
+
+ return json(res, 200, {
+ data: {
+ agent_id: id,
+ network,
+ earnings,
+ spending,
+ policy,
+ all_skills: Array.isArray(agent.skills)
+ ? agent.skills.map((s) => (typeof s === 'string' ? s : s?.name)).filter(Boolean)
+ : [],
+ listed_skills: pricedSkills.map((p) => ({
+ skill: p.skill,
+ amount: String(p.amount),
+ currency_mint: p.currency_mint,
+ pricing_type: p.pricing_type,
+ })),
+ receipts: receipts.slice(0, RECEIPTS_LIMIT),
+ peers: peers.map((p) => ({
+ address: p.destination,
+ count: Number(p.count || 0),
+ usd: Number(p.usd || 0),
+ last_at: p.last_at,
+ })),
+ },
+ });
+ } catch (e) {
+ console.error('[agents/economy] failed', e?.message);
+ return error(res, 502, 'economy_failed', 'could not load the economy summary');
+ }
+});
+
+function hostOf(u) {
+ try {
+ return new URL(u).host;
+ } catch {
+ return String(u || '').slice(0, 48);
+ }
+}
diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.js
new file mode 100644
index 000000000..ad855ebd5
--- /dev/null
+++ b/api/agents/a2a-hire.js
@@ -0,0 +1,331 @@
+// POST /api/agents/a2a-hire — one agent autonomously hires and pays another for a
+// real, executable skill, over the real x402 rails, bounded by the hiring agent's
+// spend policy + kill switch, and recorded as a real on-chain invocation receipt.
+//
+// This is the load-bearing piece of the agent-to-agent economy. The flow, every
+// step real, every spend gated server-side:
+//
+// 1. Owner-gate: the caller must own the hiring agent (agent_identities.user_id).
+// 2. Resolve the provider's offer from the real offer registry (agent_paid_services
+// → /api/x402/service/<slug>), which pays the PROVIDER agent's own wallet.
+// 3. Reserve the spend against the hiring agent's spend policy (agent-trade-guards):
+// per-tx + daily ceilings, withdraw allowlist, and the kill switch (frozen) —
+// all enforced atomically BEFORE any money moves. Idempotent: a retry with the
+// same key never double-charges.
+// 4. Pay over the real x402 protocol (x402-user-payer → @x402/svm exact scheme):
+// the hiring agent's custodial Solana wallet settles USDC to the provider, and
+// the provider's upstream executes the REAL skill. The x402 endpoint settles
+// ONLY after the work succeeds (verify → work → settle), so a failed invocation
+// can never charge the hirer — "real value or no transaction" by construction.
+// 5. Record a real on-chain invocation receipt (agent-invocation program) with the
+// hiring agent as invoker and the provider agent as target — auditable on both
+// sides with explorer links.
+// 6. Finalize the hire + custody ledger so both wallets show the income/outlay and
+// the marketplace's completion stats update from real data only.
+
+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { randomUUID } from 'node:crypto';
+
+import {
+ SpendLimitError,
+ reserveSpendUsd,
+ releaseSpendReservation,
+ updateCustodyEvent,
+ recordCustodyEvent,
+} from '../_lib/agent-trade-guards.js';
+import { payExternalX402, resolveSpendEnabled } from '../_lib/x402-user-payer.js';
+import { serviceResourceUrl } from '../_lib/agent-paid-services.js';
+import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
+import { recordInvocationReceipt } from '../_lib/agent-invocation-onchain.js';
+import {
+ atomicsToUsdc,
+ getOfferBySlug,
+ recordHire,
+ updateHire,
+} from '../_lib/agent-economy.js';
+
+// Pull the settlement signature out of the x402 receipt header object, whatever
+// shape the facilitator returned it in.
+function receiptSignature(receipt) {
+ if (!receipt || typeof receipt !== 'object') return null;
+ return receipt.transaction || receipt.signature || receipt.txHash || receipt.tx || null;
+}
+
+// A short, human summary of the provider's result for the hire record + speech.
+function summarizeResult(result) {
+ try {
+ if (result == null) return null;
+ if (typeof result === 'string') return result.slice(0, 280);
+ const inner = result.result ?? result;
+ const s = typeof inner === 'string' ? inner : JSON.stringify(inner);
+ return s.slice(0, 280);
+ } catch {
+ return null;
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required to hire an agent');
+ const userId = session?.id ?? bearer?.userId;
+
+ // CSRF on the session (cookie) path, like every other custodial write.
+ if (session && !(await requireCsrf(req, res, userId))) return;
+
+ const rl = await limits.mcpAgentPay(userId || 'anon');
+ if (!rl.success) return rateLimited(res, rl, 'hire rate limit exceeded');
+
+ const body = (await readJson(req)) || {};
+ const { hirerAgentId, serviceSlug, input = null, maxUsd } = body;
+ const idempotencyKey = body.idempotencyKey || randomUUID();
+
+ if (!hirerAgentId || typeof hirerAgentId !== 'string') {
+ return error(res, 400, 'validation_error', 'hirerAgentId is required');
+ }
+ if (!serviceSlug || typeof serviceSlug !== 'string') {
+ return error(res, 400, 'validation_error', 'serviceSlug is required');
+ }
+
+ // ── Owner gate: the caller must own the hiring agent ────────────────────
+ const [hirer] = await sql`
+ SELECT id, user_id, name, meta FROM agent_identities
+ WHERE id = ${hirerAgentId} AND deleted_at IS NULL
+ `;
+ if (!hirer) return error(res, 404, 'not_found', 'hiring agent not found');
+ if (hirer.user_id !== userId) {
+ return error(res, 403, 'forbidden', 'you do not own this agent');
+ }
+ if (!hirer.meta?.solana_address || !hirer.meta?.encrypted_solana_secret) {
+ return error(res, 409, 'no_wallet', 'this agent has no Solana wallet provisioned to pay from');
+ }
+
+ // ── Resolve the provider's offer ────────────────────────────────────────
+ const offer = await getOfferBySlug(serviceSlug);
+ if (!offer) return error(res, 404, 'offer_not_found', `no service offer at ${serviceSlug}`);
+ if (!offer.provider?.id) return error(res, 409, 'offer_unavailable', 'this offer has no provider agent');
+ if (offer.provider.is_public === false) {
+ return error(res, 409, 'offer_unavailable', 'this provider is not currently available');
+ }
+ if (offer.provider.id === hirerAgentId) {
+ return error(res, 400, 'self_hire', 'an agent cannot hire its own service');
+ }
+
+ const usd = atomicsToUsdc(offer.price_atomics);
+ const priceNetwork = offer.network === 'solana' ? 'solana' : 'base';
+
+ // Owner-set per-call ceiling for this hire (can only lower the price gate).
+ if (typeof maxUsd === 'number' && Number.isFinite(maxUsd) && usd > maxUsd + 1e-9) {
+ return error(res, 402, 'over_cap', `this service costs $${usd.toFixed(2)}, above your $${maxUsd.toFixed(2)} per-call limit`, {
+ price_usd: usd,
+ max_usd: maxUsd,
+ });
+ }
+
+ if (!resolveSpendEnabled()) {
+ return error(res, 501, 'spend_disabled', 'autonomous agent spending is not enabled on this server (set THREEWS_AGENT_PAY_ENABLED=1)');
+ }
+
+ // ── Idempotency: never double-charge a retried hire ─────────────────────
+ let hireRow;
+ try {
+ const { row, existing } = await recordHire({
+ hirerAgentId,
+ hirerUserId: userId,
+ providerAgentId: offer.provider.id,
+ serviceId: offer.service_id,
+ serviceSlug: offer.slug,
+ skillName: offer.name,
+ amountAtomics: offer.price_atomics,
+ usd,
+ currency: 'USDC',
+ network: priceNetwork,
+ payerAddress: hirer.meta.solana_address,
+ payoutAddress: offer.provider.solana_address || null,
+ idempotencyKey,
+ meta: { hirer_name: hirer.name || null, provider_name: offer.provider.name },
+ });
+ hireRow = row;
+ if (existing) {
+ if (row.status === 'completed') {
+ return json(res, 200, { ok: true, idempotent: true, hire: publicHire(row, offer) });
+ }
+ if (row.status === 'pending') {
+ return error(res, 409, 'hire_in_progress', 'a hire with this key is already in progress');
+ }
+ // failed/refunded/disputed: tell the caller to retry with a fresh key.
+ return error(res, 409, 'hire_terminal', `a prior hire with this key ended '${row.status}'; retry with a new idempotencyKey`, {
+ status: row.status,
+ });
+ }
+ } catch (err) {
+ console.error('[a2a-hire] recordHire failed', err?.message || err);
+ return error(res, 500, 'hire_record_failed', 'could not record the hire');
+ }
+
+ // ── Reserve the spend against the hiring agent's spend policy ────────────
+ // Per-tx + daily ceilings + kill switch (frozen), atomic, BEFORE payment.
+ let reservationId = null;
+ try {
+ const reservation = await reserveSpendUsd({
+ agentId: hirerAgentId,
+ userId,
+ meta: hirer.meta,
+ category: 'x402',
+ usdValue: usd,
+ asset: 'USDC',
+ network: 'mainnet',
+ rowMeta: { kind: 'a2a_hire', slug: offer.slug, provider_agent_id: offer.provider.id, hire_id: hireRow.id },
+ });
+ reservationId = reservation.reservationId;
+ await sql`UPDATE agent_hires SET spend_reservation_id = ${reservationId}, updated_at = now() WHERE id = ${hireRow.id}`;
+ } catch (err) {
+ await updateHire(hireRow.id, { status: 'failed', error: err?.message || 'spend policy blocked' });
+ if (err instanceof SpendLimitError) {
+ return error(res, err.status || 403, err.code || 'spend_blocked', err.message, err.detail || {});
+ }
+ console.error('[a2a-hire] reserve failed', err?.message || err);
+ return error(res, 500, 'reserve_failed', 'could not reserve the spend');
+ }
+
+ // ── Pay over the real x402 rails (settles to the provider's wallet) ──────
+ let payment;
+ try {
+ payment = await payExternalX402({
+ userId,
+ agentId: hirerAgentId,
+ url: serviceResourceUrl(offer.slug),
+ method: offer.method === 'POST' ? 'POST' : 'GET',
+ body: offer.method === 'POST' ? (input ?? {}) : undefined,
+ maxUsd: usd,
+ });
+ } catch (err) {
+ // The x402 endpoint settles only after the provider's work succeeds, so a
+ // throw here means NO money moved: release the hold and fail honestly.
+ await releaseSpendReservation(reservationId, 'hire_payment_failed');
+ await updateHire(hireRow.id, { status: 'failed', error: err?.message || String(err) });
+ const code = err?.code || 'payment_failed';
+ const status = code === 'spend_disabled' ? 501 : code === 'no_wallet' || code === 'no_solana_wallet' ? 409 : 502;
+ console.error('[a2a-hire] payment failed', code, err?.message || err);
+ return error(res, status, code, `the hire did not complete — no funds were moved: ${err?.message || code}`);
+ }
+
+ const paymentSignature = receiptSignature(payment.receipt);
+ const payerAddress = payment.payer || hirer.meta.solana_address;
+
+ // Finalize the spend reservation as confirmed (real, settled).
+ await updateCustodyEvent(reservationId, {
+ status: 'confirmed',
+ signature: paymentSignature,
+ meta: { settled: true },
+ }).catch((e) => console.error('[a2a-hire] finalize custody failed', e?.message));
+
+ // Record the provider's income in the custody ledger so it surfaces in the
+ // live money pulse / money-cam as the provider earning (real inflow, real tx).
+ if (offer.provider.id) {
+ recordCustodyEvent({
+ agentId: offer.provider.id,
+ userId: null,
+ eventType: 'tip',
+ category: null,
+ network: 'mainnet',
+ asset: 'USDC',
+ usd,
+ signature: paymentSignature,
+ status: 'confirmed',
+ meta: { source: 'a2a_hire', from_agent_id: hirerAgentId, from: payerAddress, hire_id: hireRow.id, skill: offer.name },
+ }).catch((e) => console.error('[a2a-hire] provider income record failed', e?.message));
+ }
+
+ // ── Write the real on-chain invocation receipt ──────────────────────────
+ let invocation = null;
+ let invocationError = null;
+ try {
+ const invokerKeypair = await recoverSolanaAgentKeypair(hirer.meta.encrypted_solana_secret, {
+ agentId: hirerAgentId,
+ userId,
+ reason: 'a2a_hire_invocation_receipt',
+ });
+ const targetAuthority = offer.provider.solana_address;
+ if (!targetAuthority) throw new Error('provider has no Solana authority to record against');
+ invocation = await recordInvocationReceipt({
+ invokerKeypair,
+ targetAuthority,
+ skillName: offer.name,
+ parameters: JSON.stringify({ slug: offer.slug, hire: hireRow.id, usd }).slice(0, 480),
+ });
+ } catch (err) {
+ // The payment + work are real and done; a receipt-write failure (e.g. the
+ // agent wallet lacks SOL for the fee) must not undo a completed hire. Record
+ // the reason and surface it honestly rather than faking a signature.
+ invocationError = err?.message || String(err);
+ console.error('[a2a-hire] invocation receipt failed', invocationError);
+ }
+
+ // ── Finalize the hire ───────────────────────────────────────────────────
+ const finalized = await updateHire(hireRow.id, {
+ status: 'completed',
+ paymentSignature,
+ payerAddress,
+ invocationSignature: invocation?.signature || null,
+ invocationError,
+ resultSummary: summarizeResult(payment.result),
+ meta: {
+ receipt: payment.receipt || null,
+ invocation: invocation || null,
+ },
+ });
+
+ return json(res, 200, {
+ ok: true,
+ hire: publicHire(finalized || hireRow, offer, { invocation, payment }),
+ result: payment.result ?? null,
+ });
+});
+
+// Shape the hire for the client, including explorer links derived from the real
+// on-chain signatures. The embodied layer + money-cam consume `embodied`.
+function publicHire(row, offer, extra = {}) {
+ const cluster = (extra?.invocation?.network || 'mainnet') === 'devnet' ? '?cluster=devnet' : '';
+ const paymentSig = row.payment_signature || null;
+ const invSig = row.invocation_signature || extra?.invocation?.signature || null;
+ return {
+ id: row.id,
+ status: row.status,
+ skill_name: row.skill_name,
+ service_slug: row.service_slug,
+ amount_atomics: String(row.amount_atomics),
+ usd: row.usd != null ? Number(row.usd) : atomicsToUsdc(row.amount_atomics),
+ currency: row.currency || 'USDC',
+ network: row.network,
+ hirer_agent_id: row.hirer_agent_id,
+ provider_agent_id: row.provider_agent_id,
+ provider: offer?.provider || null,
+ payer_address: row.payer_address || null,
+ payout_address: row.payout_address || null,
+ payment_signature: paymentSig,
+ payment_explorer: paymentSig ? `https://solscan.io/tx/${paymentSig}` : null,
+ invocation_signature: invSig,
+ invocation_explorer: invSig
+ ? `https://solscan.io/tx/${invSig}${cluster}`
+ : null,
+ invocation_error: row.invocation_error || null,
+ result_summary: row.result_summary || null,
+ created_at: row.created_at,
+ completed_at: row.completed_at || null,
+ // Drives the embodied 3D hand-off + Galaxy money-cam flow on the client.
+ embodied: {
+ from: row.hirer_agent_id,
+ to: row.provider_agent_id,
+ amountUsdc: row.usd != null ? Number(row.usd) : atomicsToUsdc(row.amount_atomics),
+ type: 'payment',
+ },
+ };
+}
diff --git a/api/agents/agent-mirror.js b/api/agents/agent-mirror.js
new file mode 100644
index 000000000..0419958b3
--- /dev/null
+++ b/api/agents/agent-mirror.js
@@ -0,0 +1,350 @@
+// /api/agents/:id/mirror — the custodial copy-trade (mirror) social graph.
+//
+// Owner-only to configure (create/edit/pause/kill/sync); public to read a
+// leader's follower count + honest track record. Every mirrored trade executes
+// through the task-05 engine inside the follower's spend policy — this surface
+// only manages the follow edges and triggers the fanout; it never bypasses a
+// guard. See api/_lib/agent-mirror.js for the guarded executor.
+//
+// GET /api/agents/:id/mirror following list + recent fills + counts (owner)
+// POST /api/agents/:id/mirror create / update a follow (owner)
+// POST /api/agents/:id/mirror/unfollow remove a follow edge (owner)
+// POST /api/agents/:id/mirror/kill toggle the agent-wide mirror kill switch (owner)
+// POST /api/agents/:id/mirror/sync process pending leader trades now (owner)
+// GET /api/agents/:id/mirror/followers who mirrors this agent (public)
+// GET /api/agents/:id/mirror/track-record this leader's real stats (public)
+// GET /api/agents/:id/mirror/fills recent mirror fills feed (owner)
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { isUuid } from '../_lib/validate.js';
+import { logAudit } from '../_lib/audit.js';
+import { normalizeFollowInput, SKIP_LABELS } from '../_lib/mirror-engine.js';
+import { leaderTrackRecord } from '../_lib/mirror-stats.js';
+import { syncFollow } from '../_lib/agent-mirror.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+// Owner gate → returns { auth, row } or sends the response and returns null.
+async function loadOwned(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in to manage mirroring'); return null; }
+ const [row] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return null; }
+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'only the owner can manage this agent’s mirroring'); return null; }
+ return { auth, row };
+}
+
+// Hydrate follow rows with leader name/avatar for the management UI.
+async function hydrateFollows(rows) {
+ if (!rows.length) return [];
+ const leaderIds = [...new Set(rows.map((r) => r.leader_agent_id))];
+ const leaders = await sql`SELECT id, name, avatar_url, profile_image_url FROM agent_identities WHERE id = ANY(${leaderIds})`.catch(() => []);
+ const byId = new Map(leaders.map((l) => [l.id, l]));
+ return rows.map((r) => {
+ const l = byId.get(r.leader_agent_id) || {};
+ return {
+ id: Number(r.id),
+ leader_agent_id: r.leader_agent_id,
+ leader_name: l.name || null,
+ leader_avatar: l.avatar_url || l.profile_image_url || null,
+ network: r.network,
+ enabled: r.enabled,
+ sizing_mode: r.sizing_mode,
+ fixed_sol: r.fixed_sol,
+ proportion_pct: r.proportion_pct,
+ pct_balance: r.pct_balance,
+ max_per_trade_sol: r.max_per_trade_sol,
+ daily_budget_sol: r.daily_budget_sol,
+ min_leader_sol: r.min_leader_sol,
+ copy_sells: r.copy_sells,
+ mint_allowlist: r.mint_allowlist || [],
+ mint_denylist: r.mint_denylist || [],
+ created_at: r.created_at,
+ updated_at: r.updated_at,
+ };
+ });
+}
+
+// ── GET /mirror — owner management view ───────────────────────────────────────
+async function handleList(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const [follows, fills, followerCount] = await Promise.all([
+ sql`SELECT * FROM agent_mirror_follows WHERE follower_agent_id = ${id} ORDER BY created_at DESC`.catch(() => []),
+ sql`
+ SELECT f.*, a.name AS leader_name, a.avatar_url AS leader_avatar
+ FROM agent_mirror_fills f
+ LEFT JOIN agent_identities a ON a.id = f.leader_agent_id
+ WHERE f.follower_agent_id = ${id}
+ ORDER BY f.created_at DESC LIMIT 30
+ `.catch(() => []),
+ sql`SELECT count(*)::int AS c, count(*) FILTER (WHERE enabled)::int AS active FROM agent_mirror_follows WHERE leader_agent_id = ${id}`.catch(() => [{ c: 0, active: 0 }]),
+ ]);
+
+ return json(res, 200, {
+ data: {
+ is_owner: true,
+ killed: owned.row.meta?.mirror_killed === true,
+ following: await hydrateFollows(follows),
+ following_count: follows.length,
+ followers_count: Number(followerCount[0]?.c || 0),
+ active_followers: Number(followerCount[0]?.active || 0),
+ recent: fills.map(serializeFill),
+ },
+ });
+}
+
+function serializeFill(f) {
+ return {
+ id: Number(f.id),
+ leader_agent_id: f.leader_agent_id,
+ leader_name: f.leader_name || null,
+ leader_avatar: f.leader_avatar || null,
+ side: f.side,
+ mint: f.mint,
+ leader_sol: f.leader_sol,
+ planned_sol: f.planned_sol,
+ status: f.status,
+ skip_reason: f.skip_reason,
+ skip_label: f.skip_reason ? (SKIP_LABELS[f.skip_reason] || f.skip_reason) : null,
+ signature: f.signature,
+ usd: f.usd,
+ price_impact_pct: f.price_impact_pct,
+ at: f.created_at,
+ };
+}
+
+// ── POST /mirror — create / update a follow edge ──────────────────────────────
+async function handleUpsert(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try { body = await readJson(req); }
+ catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid body'); }
+
+ const leaderId = typeof body.leader_agent_id === 'string' ? body.leader_agent_id.trim() : '';
+ if (!isUuid(leaderId)) return error(res, 400, 'validation_error', 'leader_agent_id must be a UUID');
+ if (leaderId === id) return error(res, 400, 'cannot_follow_self', 'an agent cannot mirror itself');
+
+ const network = netOf(body.network);
+
+ // The leader must exist and be public (you can only copy a transparent agent).
+ const [leader] = await sql`SELECT id, name, is_public FROM agent_identities WHERE id = ${leaderId} AND deleted_at IS NULL`;
+ if (!leader) return error(res, 404, 'leader_not_found', 'that leader agent does not exist');
+ if (leader.is_public === false) return error(res, 403, 'leader_private', 'that agent is private and cannot be mirrored');
+
+ // Block a circular follow (A→B and B→A would feed each other forever).
+ const [reverse] = await sql`SELECT 1 FROM agent_mirror_follows WHERE follower_agent_id = ${leaderId} AND leader_agent_id = ${id} LIMIT 1`;
+ if (reverse) return error(res, 409, 'circular_follow', 'that agent already mirrors this one — circular mirroring is not allowed');
+
+ const norm = normalizeFollowInput(body);
+ if (!norm.ok) return error(res, 400, 'validation_error', norm.error);
+ const v = norm.value;
+ const enabled = body.enabled === false ? false : true;
+
+ // Cursor starts at the leader's latest trade so a new follow mirrors only
+ // trades made AFTER the follow began — never backfills history.
+ const [latest] = await sql`
+ SELECT COALESCE(MAX(id), 0) AS id FROM agent_custody_events
+ WHERE agent_id = ${leaderId} AND network = ${network} AND category = 'trade'
+ `.catch(() => [{ id: 0 }]);
+
+ const [row] = await sql`
+ INSERT INTO agent_mirror_follows (
+ follower_agent_id, leader_agent_id, owner_user_id, network, enabled,
+ sizing_mode, fixed_sol, proportion_pct, pct_balance,
+ max_per_trade_sol, daily_budget_sol, min_leader_sol, copy_sells,
+ mint_allowlist, mint_denylist, last_leader_event_id
+ ) VALUES (
+ ${id}, ${leaderId}, ${owned.auth.userId}, ${network}, ${enabled},
+ ${v.sizing_mode}, ${v.fixed_sol}, ${v.proportion_pct}, ${v.pct_balance},
+ ${v.max_per_trade_sol}, ${v.daily_budget_sol}, ${v.min_leader_sol}, ${v.copy_sells},
+ ${v.mint_allowlist}, ${v.mint_denylist}, ${Number(latest?.id || 0)}
+ )
+ ON CONFLICT (follower_agent_id, leader_agent_id) DO UPDATE SET
+ enabled = ${enabled}, network = ${network},
+ sizing_mode = ${v.sizing_mode}, fixed_sol = ${v.fixed_sol},
+ proportion_pct = ${v.proportion_pct}, pct_balance = ${v.pct_balance},
+ max_per_trade_sol = ${v.max_per_trade_sol}, daily_budget_sol = ${v.daily_budget_sol},
+ min_leader_sol = ${v.min_leader_sol}, copy_sells = ${v.copy_sells},
+ mint_allowlist = ${v.mint_allowlist}, mint_denylist = ${v.mint_denylist},
+ updated_at = now()
+ RETURNING *
+ `;
+
+ logAudit({ userId: owned.auth.userId, action: 'mirror.follow', resourceId: id, meta: { leader_agent_id: leaderId, sizing_mode: v.sizing_mode, enabled }, req });
+ const [hydrated] = await hydrateFollows([row]);
+ return json(res, 200, { data: { follow: hydrated } });
+}
+
+// ── POST /mirror/unfollow ─────────────────────────────────────────────────────
+async function handleUnfollow(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ let body;
+ try { body = await readJson(req); } catch { body = {}; }
+ const leaderId = typeof body.leader_agent_id === 'string' ? body.leader_agent_id.trim() : '';
+ if (!isUuid(leaderId)) return error(res, 400, 'validation_error', 'leader_agent_id must be a UUID');
+
+ const del = await sql`DELETE FROM agent_mirror_follows WHERE follower_agent_id = ${id} AND leader_agent_id = ${leaderId} RETURNING id`;
+ logAudit({ userId: owned.auth.userId, action: 'mirror.unfollow', resourceId: id, meta: { leader_agent_id: leaderId }, req });
+ return json(res, 200, { data: { removed: del.length > 0 } });
+}
+
+// ── POST /mirror/kill — agent-wide kill switch ────────────────────────────────
+async function handleKill(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ let body;
+ try { body = await readJson(req); } catch { body = {}; }
+ const killed = body.killed === true;
+
+ const meta = { ...(owned.row.meta || {}), mirror_killed: killed };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
+ logAudit({ userId: owned.auth.userId, action: killed ? 'mirror.kill_on' : 'mirror.kill_off', resourceId: id, meta: {}, req });
+ return json(res, 200, { data: { killed } });
+}
+
+// ── POST /mirror/sync — process pending leader trades now ─────────────────────
+async function handleSync(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (owned.row.meta?.mirror_killed === true) {
+ return error(res, 409, 'mirror_killed', 'mirroring is paused by the kill switch — turn it off to sync');
+ }
+
+ const follows = await sql`SELECT * FROM agent_mirror_follows WHERE follower_agent_id = ${id} AND enabled = true`;
+ const out = [];
+ for (const f of follows) {
+ // Attach leader name for the custody label without an extra round trip later.
+ const [leader] = await sql`SELECT name FROM agent_identities WHERE id = ${f.leader_agent_id}`.catch(() => []);
+ f.leader_name = leader?.name || null;
+ const r = await syncFollow(f, { maxEvents: 15 }).catch((e) => ({ processed: 0, results: [], error: (e?.message || 'error').slice(0, 120) }));
+ out.push({ leader_agent_id: f.leader_agent_id, ...r });
+ }
+ return json(res, 200, { data: { synced: out } });
+}
+
+// ── GET /mirror/followers — public ────────────────────────────────────────────
+async function handleFollowers(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const rows = await sql`
+ SELECT f.follower_agent_id, f.enabled, f.created_at, a.name, a.avatar_url, a.profile_image_url
+ FROM agent_mirror_follows f
+ JOIN agent_identities a ON a.id = f.follower_agent_id AND a.deleted_at IS NULL
+ WHERE f.leader_agent_id = ${id}
+ ORDER BY f.created_at DESC LIMIT 60
+ `.catch(() => []);
+ return json(res, 200, {
+ data: {
+ count: rows.length,
+ active: rows.filter((r) => r.enabled).length,
+ followers: rows.map((r) => ({
+ agent_id: r.follower_agent_id,
+ name: r.name,
+ avatar: r.avatar_url || r.profile_image_url || null,
+ enabled: r.enabled,
+ since: r.created_at,
+ })),
+ },
+ });
+}
+
+// ── GET /mirror/track-record — public, real stats ─────────────────────────────
+async function handleTrackRecord(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const network = netOf(new URL(req.url, 'http://x').searchParams.get('network'));
+ const [agent] = await sql`SELECT name, avatar_url, profile_image_url FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`.catch(() => []);
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ const record = await leaderTrackRecord(id, network);
+ return json(res, 200, { data: { agent: { id, name: agent.name, avatar: agent.avatar_url || agent.profile_image_url || null }, record } });
+}
+
+// ── GET /mirror/fills — owner feed (paginated) ────────────────────────────────
+async function handleFills(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') || '40', 10) || 40));
+ const beforeId = parseInt(url.searchParams.get('before') || '0', 10) || null;
+
+ const rows = await sql`
+ SELECT f.*, a.name AS leader_name, a.avatar_url AS leader_avatar
+ FROM agent_mirror_fills f
+ LEFT JOIN agent_identities a ON a.id = f.leader_agent_id
+ WHERE f.follower_agent_id = ${id}
+ ${beforeId ? sql`AND f.id < ${beforeId}` : sql``}
+ ORDER BY f.id DESC LIMIT ${limit}
+ `.catch(() => []);
+ return json(res, 200, { data: { items: rows.map(serializeFill), next: rows.length === limit ? Number(rows[rows.length - 1].id) : null } });
+}
+
+export default async function handler(req, res, id, action) {
+ if (!isUuid(id)) { if (cors(req, res)) return; return error(res, 404, 'not_found', 'agent not found'); }
+ switch (action) {
+ case undefined:
+ case '':
+ return req.method === 'POST' ? handleUpsert(req, res, id) : handleList(req, res, id);
+ case 'unfollow': return handleUnfollow(req, res, id);
+ case 'kill': return handleKill(req, res, id);
+ case 'sync': return handleSync(req, res, id);
+ case 'followers': return handleFollowers(req, res, id);
+ case 'track-record': return handleTrackRecord(req, res, id);
+ case 'fills': return handleFills(req, res, id);
+ default:
+ if (cors(req, res)) return;
+ return error(res, 404, 'not_found', 'unknown mirror action');
+ }
+}
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index 45f04ed67..f4ce13dc6 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -315,8 +315,9 @@ async function countOpenTrades(agentId, network) {
}
// Parse + validate the trade request body into a normalized shape, or throw a
-// boundary() error. Shared by execute + preview.
-function parseTradeInput(body, tradeLimits) {
+// boundary() error. Shared by execute + preview + the strategy runtime (which
+// builds a synthetic body { side, mint, amount, slippageBps, network }).
+export function parseTradeInput(body, tradeLimits) {
const side = body.side === 'sell' ? 'sell' : body.side === 'buy' ? 'buy' : null;
if (!side) throw boundary(400, 'invalid_side', 'side must be "buy" or "sell"');
@@ -379,22 +380,60 @@ async function handleExecute(req, res, id) {
} catch (e) {
return boundaryError(res, e);
}
- const { side, network, simulate, slippagePct } = input;
- const idempotencyKey = input.idempotencyKey || randomUUID();
// CSRF on the real, fund-moving path only — `simulate` is a dry run that never
// signs or records. Bearer/API-key callers (the primary consumers of this flat
// trade endpoint) are exempt inside requireCsrf.
- if (!simulate && !(await requireCsrf(req, res, auth.userId))) return;
+ if (!input.simulate && !(await requireCsrf(req, res, auth.userId))) return;
+
+ let result;
+ try {
+ result = await executeAgentTrade({ id, userId: auth.userId, meta, input, req, source: 'discretionary' });
+ } catch (e) {
+ console.error('[agents/agent-trade] execute crashed', e?.message);
+ return error(res, 500, 'internal_error', 'unexpected error executing the trade');
+ }
+ if (!result.ok) {
+ return error(res, result.status || 500, result.code || 'error', result.message || 'trade failed', result.detail ? { detail: result.detail } : {});
+ }
+ return json(res, result.status || 200, { data: result.data });
+}
+
+/**
+ * Programmatic trade execution core — the shared engine behind BOTH the HTTP
+ * trade endpoint and the autonomous strategy runtime (task 10). The caller has
+ * already loaded the owned agent (`meta`), parsed + bounded the request into
+ * `input`, and — for the HTTP path — verified CSRF. This runs the SAME
+ * quote → guard → build → custody-claim → sign → confirm pipeline for every
+ * caller, so an autonomous strategy is held to the exact same spend policy,
+ * rug/honeypot firewall, daily budget, kill switch, and custody audit trail as a
+ * manual trade. A strategy can NEVER exceed the spend leash — the guards below do
+ * not know or care who called them.
+ *
+ * `source` labels the custody ledger: 'discretionary' for the HTTP endpoint, or
+ * 'strategy:<slug>' for a strategy-initiated trade (with `sourceMeta` carrying
+ * { strategy, strategy_id, equip_id } stamped into the ledger row's meta).
+ *
+ * @returns {Promise<{ ok:true, status:number, data:object }
+ * | { ok:false, status:number, code:string, message:string, detail?:object }>}
+ */
+export async function executeAgentTrade({ id, userId, meta, input, req = null, source = 'discretionary', sourceMeta = null }) {
+ const { side, network, simulate, slippagePct } = input;
+ const idempotencyKey = input.idempotencyKey || randomUUID();
+ const tradeLimits = getTradeLimits(meta);
+ const isStrategy = typeof source === 'string' && source.startsWith('strategy:');
+ const custodyReason = isStrategy ? source.slice(0, 80) : `trade_${side}`;
+
+ const fail = (status, code, message, detail = null) => ({ ok: false, status, code, message, detail });
// Guarantee the wallet exists (lazy provision) so a funded-but-unprovisioned
// agent can trade. ensureAgentWallet audits the provision and never returns
// the secret.
let address;
try {
- address = (await ensureAgentWallet(id, auth.userId, { reason: 'trade' })).address;
+ address = (await ensureAgentWallet(id, userId, { reason: custodyReason })).address;
} catch (e) {
- return error(res, 500, 'wallet_unavailable', 'could not prepare the agent wallet — try again');
+ return fail(500, 'wallet_unavailable', 'could not prepare the agent wallet — try again');
}
const ownerPk = new PublicKey(address);
@@ -406,12 +445,12 @@ async function handleExecute(req, res, id) {
`;
if (existing) {
if (existing.status === 'confirmed') {
- return json(res, 200, { data: { replayed: true, signature: existing.signature, explorer: explorerTxUrl(existing.signature, network), network, ...(existing.meta || {}) } });
+ return { ok: true, status: 200, data: { replayed: true, signature: existing.signature, explorer: explorerTxUrl(existing.signature, network), network, ...(existing.meta || {}) } };
}
if (existing.status === 'pending') {
- return error(res, 409, 'trade_in_progress', 'a trade with this id is already in flight — check the audit log before retrying', { signature: existing.signature || null });
+ return fail(409, 'trade_in_progress', 'a trade with this id is already in flight — check the audit log before retrying', { signature: existing.signature || null });
}
- return error(res, 409, 'trade_failed', 'this trade id already failed — retry with a fresh idempotency key', { signature: existing.signature || null });
+ return fail(409, 'trade_failed', 'this trade id already failed — retry with a fresh idempotency key', { signature: existing.signature || null });
}
}
@@ -419,7 +458,7 @@ async function handleExecute(req, res, id) {
try {
ctx = await getPumpTradeClient({ network });
} catch (e) {
- return error(res, 502, 'rpc_error', 'could not connect to the trade RPC — try again');
+ return fail(502, 'rpc_error', 'could not connect to the trade RPC — try again');
}
const conn = ctx.connection;
@@ -427,7 +466,7 @@ async function handleExecute(req, res, id) {
try {
walletLamports = BigInt(await conn.getBalance(ownerPk, 'confirmed'));
} catch {
- return error(res, 502, 'rpc_error', 'could not read the wallet balance — try again');
+ return fail(502, 'rpc_error', 'could not read the wallet balance — try again');
}
// Price the trade.
@@ -435,20 +474,21 @@ async function handleExecute(req, res, id) {
try {
prep = await quoteTrade({ ctx, side, mintPk: input.mintPk, amount: input.amount, isMax: input.isMax, slippagePct, network, ownerPk });
} catch (e) {
- return boundaryError(res, e);
+ if (e?.isBoundary) return fail(e.status, e.code, e.message, e.detail && Object.keys(e.detail).length ? e.detail : null);
+ return fail(500, 'internal_error', 'unexpected error preparing the trade');
}
if (side === 'buy' && prep.lamports != null) {
try { prep.usdValue = await lamportsToUsd(prep.lamports); } catch { prep.usdValue = null; }
}
- // Run the shared guardrails.
+ // Run the shared guardrails — identical for manual + strategy trades.
let blocked;
try {
- blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk: input.mintPk, ownerPk, userId: auth.userId });
+ blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk: input.mintPk, ownerPk, userId });
} catch (e) {
- return error(res, 502, 'guard_check_failed', 'could not verify the trade guardrails — try again');
+ return fail(502, 'guard_check_failed', 'could not verify the trade guardrails — try again');
}
- if (blocked) return error(res, blocked.status, blocked.code, blocked.message, { detail: blocked.detail });
+ if (blocked) return fail(blocked.status, blocked.code, blocked.message, blocked.detail);
// Build the on-chain instructions (also the real graduation check for buys).
let built;
@@ -456,10 +496,10 @@ async function handleExecute(req, res, id) {
built = await buildTradeInstructions({ ctx, side, venue: prep.venue, mintPk: input.mintPk, ownerPk, lamports: prep.lamports, baseAmount: prep.baseAmount, slippagePct, network });
} catch (e) {
if (isGraduatedErr(e)) {
- return error(res, 409, 'graduated', 'This coin graduated mid-trade — refresh the quote and retry.');
+ return fail(409, 'graduated', 'This coin graduated mid-trade — refresh the quote and retry.');
}
console.error('[agents/agent-trade] build failed', e?.message);
- return error(res, 502, 'build_failed', 'could not build the trade — try again');
+ return fail(502, 'build_failed', 'could not build the trade — try again');
}
const ledgerMeta = {
@@ -468,6 +508,7 @@ async function handleExecute(req, res, id) {
expected_out: prep.expectedOutRaw.toString(),
min_out: prep.minOutRaw.toString(),
...(side === 'sell' ? { base_amount: prep.baseAmount.toString(), token_decimals: prep.decimals } : {}),
+ ...(isStrategy ? { source: 'strategy', strategy: sourceMeta?.strategy ?? null, strategy_id: sourceMeta?.strategy_id ?? null, equip_id: sourceMeta?.equip_id ?? null } : {}),
};
// Paper mode: simulate the real instructions, never sign, never record.
@@ -479,9 +520,11 @@ async function handleExecute(req, res, id) {
sim = await conn.simulateTransaction(vtx, { sigVerify: false, replaceRecentBlockhash: true });
} catch (e) {
console.error('[agents/agent-trade] simulation failed', e?.message);
- return serverError(res, 502, 'simulation_failed', e);
+ return fail(502, 'simulation_failed', e?.message || 'simulation failed');
}
- return json(res, 200, {
+ return {
+ ok: true,
+ status: 200,
data: {
simulated: true, side, mint: input.mint, network, venue: prep.venue,
expected_out: prep.expectedOutRaw.toString(),
@@ -490,30 +533,33 @@ async function handleExecute(req, res, id) {
err: sim.value?.err ?? null,
units_consumed: sim.value?.unitsConsumed ?? null,
},
- });
+ };
}
// Claim the idempotency slot — this row is also the ledger/audit entry. Buys
// count toward the SOL + USD budgets (amount_lamports + usd set); sells move
// SOL inward, so they record for audit with null amounts (don't consume budget).
+ // `reason` is the human-facing custody-trail label: 'strategy:<slug>' for a
+ // strategy fill, 'trade_buy'/'trade_sell' for a manual one. Budget queries key
+ // on event_type/amount/usd (never reason), so relabeling is safe.
const claim = await sql`
INSERT INTO agent_custody_events
(agent_id, user_id, event_type, category, network, asset,
amount_lamports, amount_raw, usd, status, idempotency_key, reason, meta)
VALUES (
- ${id}, ${auth.userId}, 'spend', 'trade', ${network},
+ ${id}, ${userId}, 'spend', 'trade', ${network},
${side === 'buy' ? 'SOL' : input.mint},
${side === 'buy' ? String(prep.lamports) : null},
${side === 'sell' ? String(prep.baseAmount) : null},
${side === 'buy' ? (prep.usdValue ?? null) : null},
- 'pending', ${idempotencyKey}, ${`trade_${side}`},
+ 'pending', ${idempotencyKey}, ${custodyReason},
${JSON.stringify(ledgerMeta)}::jsonb
)
ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
RETURNING id
`;
if (!claim.length) {
- return error(res, 409, 'trade_in_progress', 'a trade with this id is already in flight — check the audit log before retrying');
+ return fail(409, 'trade_in_progress', 'a trade with this id is already in flight — check the audit log before retrying');
}
const claimId = claim[0].id;
@@ -521,12 +567,12 @@ async function handleExecute(req, res, id) {
let keypair;
try {
keypair = await recoverSolanaAgentKeypair(meta.encrypted_solana_secret, {
- agentId: id, userId: auth.userId, reason: `trade_${side}`,
- meta: { mint: input.mint, network, venue: prep.venue, custody_event_id: claimId },
+ agentId: id, userId, reason: custodyReason,
+ meta: { mint: input.mint, network, venue: prep.venue, custody_event_id: claimId, ...(isStrategy ? { strategy_id: sourceMeta?.strategy_id ?? null, equip_id: sourceMeta?.equip_id ?? null } : {}) },
});
} catch (e) {
await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});
- return error(res, 500, 'key_recover_failed', 'could not access the agent wallet key — no funds were moved');
+ return fail(500, 'key_recover_failed', 'could not access the agent wallet key — no funds were moved');
}
// Submit + confirm through the protected execution engine.
@@ -535,45 +581,78 @@ async function handleExecute(req, res, id) {
result = await signSendConfirm(conn, keypair, built.instructions, network);
} catch (e) {
await updateCustodyEvent(claimId, { status: 'failed', meta: { error: e?.code || 'send_failed', message: e?.message?.slice(0, 200) } }).catch(() => {});
- logAudit({ userId: auth.userId, action: 'custody.trade_failed', resourceId: id, meta: { side, mint: input.mint, reason: e?.code || 'send_failed', network }, req });
- return error(res, 502, 'send_failed', 'the trade could not be submitted and no funds were moved — try again');
+ logAudit({ userId, action: isStrategy ? 'custody.trade_strategy_failed' : 'custody.trade_failed', resourceId: id, meta: { side, mint: input.mint, reason: e?.code || 'send_failed', network, source }, req });
+ return fail(502, 'send_failed', 'the trade could not be submitted and no funds were moved — try again');
}
if (!result.confirmed) {
await updateCustodyEvent(claimId, { signature: result.signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});
- logAudit({ userId: auth.userId, action: 'custody.trade_unconfirmed', resourceId: id, meta: { side, mint: input.mint, signature: result.signature, network }, req });
- return error(res, 202, 'trade_unconfirmed', 'the trade was submitted but not yet confirmed — check the explorer link before retrying', { signature: result.signature, explorer: explorerTxUrl(result.signature, network) });
+ logAudit({ userId, action: 'custody.trade_unconfirmed', resourceId: id, meta: { side, mint: input.mint, signature: result.signature, network, source }, req });
+ return fail(202, 'trade_unconfirmed', 'the trade was submitted but not yet confirmed — check the explorer link before retrying', { signature: result.signature, explorer: explorerTxUrl(result.signature, network) });
}
await updateCustodyEvent(claimId, { status: 'confirmed', signature: result.signature, meta: result.exec ? { exec: result.exec } : undefined }).catch(() => {});
- logAudit({ userId: auth.userId, action: 'custody.trade', resourceId: id, meta: { side, mint: input.mint, venue: prep.venue, network, signature: result.signature, usd: prep.usdValue, exec_route: result.exec?.route }, req });
+ logAudit({ userId, action: isStrategy ? 'custody.trade_strategy' : 'custody.trade', resourceId: id, meta: { side, mint: input.mint, venue: prep.venue, network, signature: result.signature, usd: prep.usdValue, exec_route: result.exec?.route, source }, req });
// Re-read the SOL balance for the response.
let newSol = null;
try { newSol = (await conn.getBalance(ownerPk, 'confirmed')) / 1e9; } catch { /* best-effort */ }
- return json(res, 200, {
+ return {
+ ok: true,
+ status: 200,
data: {
replayed: false,
+ custody_event_id: claimId,
signature: result.signature,
explorer: explorerTxUrl(result.signature, network),
side, mint: input.mint, network, venue: prep.venue,
slippage_bps: input.slippageBps,
price_impact_pct: prep.priceImpactPct,
...(side === 'buy'
- ? { sol_spent: lamportsToSol(prep.lamports), tokens_received: prep.expectedOutRaw.toString() }
- : { tokens_sold: prep.baseAmount.toString(), sol_received: lamportsToSol(prep.expectedOutRaw) }),
+ ? { sol_spent: lamportsToSol(prep.lamports), tokens_received: prep.expectedOutRaw.toString(), expected_out_raw: prep.expectedOutRaw.toString() }
+ : { tokens_sold: prep.baseAmount.toString(), sol_received: lamportsToSol(prep.expectedOutRaw), expected_out_raw: prep.expectedOutRaw.toString() }),
min_out: prep.minOutRaw.toString(),
new_balance_sol: newSol,
execution: result.exec || null,
},
- });
+ };
}
async function safeBlockhash(conn) {
try { return await conn.getLatestBlockhash('confirmed'); } catch { return null; }
}
+/**
+ * Live SOL value (lamports) of selling `baseAmountRaw` base units of `mint` right
+ * now — a zero-slippage quote used by the strategy runtime to mark open positions
+ * to market for take-profit / stop-loss / trailing-stop decisions. Reuses the
+ * exact bonding-curve + AMM quote path the real sell uses, so the valuation and
+ * the eventual fill are priced the same way. Returns null if it can't be priced
+ * (caller treats that as "skip this position this sweep", never as a loss).
+ */
+export async function quoteSellValueLamports({ network, mint, baseAmountRaw }) {
+ const base = BigInt(baseAmountRaw || 0n);
+ if (base <= 0n) return null;
+ const net = normNetwork(network);
+ let ctx;
+ try { ctx = await getPumpTradeClient({ network: net }); } catch { return null; }
+ const mintPk = new PublicKey(mint);
+ const baseBn = new ctx.BN(base.toString());
+ try {
+ const q = await ctx.client.quoteForSell({ mint: mintPk, baseAmount: baseBn, slippagePct: 0 });
+ return BigInt(q.expectedQuoteOut.toString());
+ } catch (err) {
+ if (!isGraduatedErr(err)) return null;
+ try {
+ const a = await quoteAmmSell({ network: net, mint, baseAmount: baseBn, slippagePct: 0 });
+ return BigInt(a.expectedQuoteOut);
+ } catch {
+ return null;
+ }
+ }
+}
+
// Broadcast + confirm through the MEV-aware execution engine: dynamic compute
// budget (real simulate + real priority-fee estimate) and bounded adaptive retry
// with an ambiguous-confirm re-check so a landed tx is never marked failed. The
diff --git a/api/agents/autopilot.js b/api/agents/autopilot.js
new file mode 100644
index 000000000..2d658bf53
--- /dev/null
+++ b/api/agents/autopilot.js
@@ -0,0 +1,198 @@
+/**
+ * Treasury Autopilot API — owner-only control surface for the agent that funds
+ * its own existence. Routed from api/agents/[id].js as /api/agents/:id/autopilot.
+ *
+ * GET /api/agents/:id/autopilot → policy + compiled rules + runway view
+ * POST /api/agents/:id/autopilot/compile → plain-English policy → structured rules (preview only)
+ * PUT /api/agents/:id/autopilot → save / arm / disarm / kill / edit rules
+ * POST /api/agents/:id/autopilot/run → run one real autopilot cycle now
+ *
+ * Every write is owner-only (server-side) and CSRF-protected. Executing paths act
+ * ONLY on the agent's own wallet and are clamped to the agent's spend policy at
+ * execution time. See api/_lib/treasury-autopilot.js for the engine.
+ */
+
+import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { sql } from '../_lib/db.js';
+import {
+ getAutopilot,
+ setAutopilot,
+ compilePolicyFromText,
+ runAutopilotCycle,
+ computeRunway,
+} from '../_lib/treasury-autopilot.js';
+import { validateSolanaAddress } from '../_lib/agent-trade-guards.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+// Owner gate → returns { auth, meta } or writes the response and returns { error: true }.
+async function loadOwned(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) {
+ error(res, 401, 'unauthorized', 'sign in to manage this agent’s treasury autopilot');
+ return { error: true };
+ }
+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) {
+ error(res, 404, 'not_found', 'agent not found');
+ return { error: true };
+ }
+ if (row.user_id !== auth.userId) {
+ error(res, 403, 'forbidden', 'only the owner can configure treasury autopilot');
+ return { error: true };
+ }
+ return { auth, meta: { ...(row.meta || {}) } };
+}
+
+function netOf(req) {
+ const url = new URL(req.url, 'http://x');
+ return url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+}
+
+export default async function handler(req, res, id, action) {
+ if (cors(req, res, { methods: 'GET,POST,PUT,OPTIONS', credentials: true })) return;
+
+ if (action === 'compile') return handleCompile(req, res, id);
+ if (action === 'run') return handleRun(req, res, id);
+ if (action) return error(res, 404, 'not_found', 'unknown autopilot sub-resource');
+
+ if (req.method === 'GET') return handleGet(req, res, id);
+ if (req.method === 'PUT') return handlePut(req, res, id);
+ return method(req, res, ['GET', 'PUT']) ? error(res, 405, 'method_not_allowed', 'use GET or PUT') : undefined;
+}
+
+// GET — current policy + the real runway view.
+async function handleGet(req, res, id) {
+ if (!method(req, res, ['GET'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const network = netOf(req);
+ const policy = getAutopilot(owned.meta);
+ try {
+ const runway = await computeRunway({ agentId: id, network, meta: owned.meta });
+ return json(res, 200, { data: { policy, runway } });
+ } catch (e) {
+ return serverError(res, 500, 'runway_failed', e);
+ }
+}
+
+// POST /compile — plain-English → structured rules. Preview only; never arms.
+async function handleCompile(req, res, id) {
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+ const text = typeof body.text === 'string' ? body.text : '';
+ const sweepDest = typeof body.sweep_destination === 'string' && validateSolanaAddress(body.sweep_destination).valid
+ ? validateSolanaAddress(body.sweep_destination).base58
+ : getAutopilot(owned.meta).sweep_destination;
+
+ try {
+ const compiled = await compilePolicyFromText(text, {
+ sweepDestination: sweepDest,
+ track: { userId: owned.auth.userId, agentId: id, tool: 'autopilot_compile' },
+ });
+ if (!compiled.ok) return error(res, 400, compiled.error || 'compile_failed', compiled.message || 'could not compile policy');
+ return json(res, 200, { data: compiled });
+ } catch (e) {
+ return serverError(res, 500, 'compile_failed', e);
+ }
+}
+
+// PUT — persist a policy patch (save compiled rules, arm/disarm, kill, edit, pause).
+async function handlePut(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+
+ const patch = {};
+ if ('rules' in body) {
+ if (!Array.isArray(body.rules)) return error(res, 400, 'bad_request', 'rules must be an array');
+ patch.rules = body.rules;
+ }
+ if ('buffer_sol' in body) patch.buffer_sol = body.buffer_sol;
+ if ('sweep_destination' in body) {
+ const d = body.sweep_destination;
+ if (d && !validateSolanaAddress(d).valid) return error(res, 400, 'invalid_address', 'sweep destination is not a valid Solana address');
+ patch.sweep_destination = d || null;
+ }
+ if ('source_text' in body) patch.source_text = body.source_text;
+ if ('armed' in body) patch.armed = body.armed === true;
+ if ('kill_switch' in body) patch.kill_switch = body.kill_switch === true;
+
+ // Arming is explicit consent — stamp approval + compile time server-side.
+ const nowIso = new Date().toISOString();
+ if (patch.armed === true) {
+ patch.approved_at = nowIso;
+ patch.compiled_at = nowIso;
+ }
+
+ try {
+ const policy = await setAutopilot(id, owned.auth.userId, patch, { req });
+ return json(res, 200, { data: { policy } });
+ } catch (e) {
+ if (e?.status) return error(res, e.status, e.code || 'error', e.message);
+ return serverError(res, 500, 'save_failed', e);
+ }
+}
+
+// POST /run — run one real autopilot cycle now (owner-initiated). Honors the kill
+// switch, disarmed state, freeze, and the spend policy exactly like the scheduler.
+async function handleRun(req, res, id) {
+ if (!method(req, res, ['POST'])) return;
+ const owned = await loadOwned(req, res, id);
+ if (owned.error) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const network = netOf(req);
+ let body = {};
+ try {
+ body = await readJson(req);
+ } catch {
+ body = {};
+ }
+ const dryRun = body?.dry_run === true;
+
+ try {
+ const result = await runAutopilotCycle({
+ agentId: id,
+ userId: owned.auth.userId,
+ network,
+ trigger: 'manual',
+ dryRun,
+ });
+ return json(res, 200, { data: result });
+ } catch (e) {
+ return serverError(res, 500, 'run_failed', e);
+ }
+}
diff --git a/api/agents/economy.js b/api/agents/economy.js
new file mode 100644
index 000000000..2bc56187c
--- /dev/null
+++ b/api/agents/economy.js
@@ -0,0 +1,102 @@
+// GET /api/agents/economy?view=offers — marketplace catalog + live stats
+// GET /api/agents/economy?view=offer&slug=… — one offer + provider + stats
+// GET /api/agents/economy?view=hires&agentId=… — an agent's hire history (accounting)
+// GET /api/agents/economy?view=summary&agentId=… — income/outlay + provider reputation
+// POST /api/agents/economy { action:'rate', hireId, rating } — rate a completed hire
+//
+// The single read surface behind the agent-to-agent economy UI. Every number it
+// returns is a real aggregate over real hires (api/_lib/agent-economy.js) — there
+// is no path here that fabricates a completion count, rating, or earning. Reads
+// are public (the same data the public money pulse already exposes); the only
+// write is an owner-gated rating.
+
+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import {
+ agentEconomySummary,
+ getHireById,
+ getOfferBySlug,
+ listHiresForAgent,
+ listOffersWithStats,
+ providerStats,
+ rateHire,
+} from '../_lib/agent-economy.js';
+
+async function handleGet(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const view = url.searchParams.get('view') || 'offers';
+
+ if (view === 'offers') {
+ const limit = Number(url.searchParams.get('limit')) || 60;
+ const providerAgentId = url.searchParams.get('agentId') || null;
+ const offers = await listOffersWithStats({ limit, providerAgentId });
+ return json(res, 200, { data: { offers } }, { 'cache-control': 'public, max-age=15' });
+ }
+
+ if (view === 'offer') {
+ const slug = url.searchParams.get('slug');
+ if (!slug) return error(res, 400, 'validation_error', 'slug is required');
+ const offer = await getOfferBySlug(slug);
+ if (!offer) return error(res, 404, 'not_found', 'offer not found');
+ return json(res, 200, { data: { offer } });
+ }
+
+ if (view === 'hires') {
+ const agentId = url.searchParams.get('agentId');
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');
+ const role = url.searchParams.get('role') || 'all';
+ const limit = Number(url.searchParams.get('limit')) || 40;
+ const beforeId = url.searchParams.get('beforeId') || null;
+ const hires = await listHiresForAgent(agentId, { role, limit, beforeId });
+ const next_cursor = hires.length === limit ? hires[hires.length - 1].id : null;
+ return json(res, 200, { data: { hires, next_cursor } });
+ }
+
+ if (view === 'summary') {
+ const agentId = url.searchParams.get('agentId');
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');
+ const [summary, reputation] = await Promise.all([
+ agentEconomySummary(agentId),
+ providerStats(agentId),
+ ]);
+ return json(res, 200, { data: { agent_id: agentId, summary, reputation } });
+ }
+
+ return error(res, 400, 'bad_view', `unknown view '${view}'`);
+}
+
+async function handlePost(req, res) {
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ const userId = session?.id ?? bearer?.userId;
+ if (session && !(await requireCsrf(req, res, userId))) return;
+
+ const body = (await readJson(req)) || {};
+ if (body.action !== 'rate') return error(res, 400, 'bad_action', "only action 'rate' is supported");
+
+ const { hireId, rating } = body;
+ if (!hireId) return error(res, 400, 'validation_error', 'hireId is required');
+
+ const hire = await getHireById(hireId);
+ if (!hire) return error(res, 404, 'not_found', 'hire not found');
+ if (hire.hirer_user_id !== userId) return error(res, 403, 'forbidden', 'only the hirer can rate this hire');
+ if (hire.status !== 'completed') return error(res, 409, 'not_rateable', 'only a completed hire can be rated');
+
+ try {
+ const updated = await rateHire(hireId, userId, rating);
+ if (!updated) return error(res, 409, 'rate_failed', 'could not record the rating');
+ return json(res, 200, { ok: true, hire_id: hireId, rating: updated.rating });
+ } catch (err) {
+ if (err?.code === 'invalid_rating') return error(res, 400, 'invalid_rating', err.message);
+ throw err;
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (req.method === 'POST') return handlePost(req, res);
+ return handleGet(req, res);
+});
diff --git a/api/agents/recovery-inbox.js b/api/agents/recovery-inbox.js
new file mode 100644
index 000000000..034855491
--- /dev/null
+++ b/api/agents/recovery-inbox.js
@@ -0,0 +1,97 @@
+// GET /api/agents/recovery-inbox — the guardian's cross-agent console.
+//
+// Lists every agent the signed-in user is trusted to help recover (as a guardian)
+// or will inherit (as a beneficiary), each decorated with the live recovery/
+// inheritance process if one is open and whether this viewer still needs to act.
+// This is the surface a guardian uses to approve a recovery or confirm an
+// inheritance — they are not the owner, so they never see the owner-only hub tab.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error, rateLimited, wrap } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { decorateRequest, getActiveRequest, getRecoveryConfig } from '../_lib/agent-recovery.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.walletRead(auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ // Agents where I hold an active guardian/beneficiary role.
+ const rows = await sql`
+ SELECT g.agent_id, g.role, g.created_at,
+ a.name AS agent_name, a.avatar_url, a.user_id AS owner_id, a.meta,
+ ou.username AS owner_username, ou.display_name AS owner_display_name
+ FROM agent_recovery_guardians g
+ JOIN agent_identities a ON a.id = g.agent_id AND a.deleted_at IS NULL
+ JOIN users ou ON ou.id = a.user_id
+ WHERE g.guardian_user_id = ${auth.userId} AND g.status = 'active'
+ ORDER BY g.created_at DESC
+ `;
+
+ // Collapse rows per agent (a user can be both guardian and beneficiary).
+ const byAgent = new Map();
+ for (const r of rows) {
+ if (!byAgent.has(r.agent_id)) {
+ byAgent.set(r.agent_id, {
+ agent_id: r.agent_id,
+ agent_name: r.agent_name,
+ avatar_url: r.avatar_url || null,
+ owner: { id: r.owner_id, label: r.owner_display_name || (r.owner_username ? `@${r.owner_username}` : 'the owner') },
+ meta: r.meta,
+ roles: new Set(),
+ since: r.created_at,
+ });
+ }
+ byAgent.get(r.agent_id).roles.add(r.role);
+ }
+
+ const items = [];
+ let actionable = 0;
+ for (const a of byAgent.values()) {
+ const activeRaw = await getActiveRequest(a.agent_id);
+ const active = activeRaw ? await decorateRequest(activeRaw, a.agent_id) : null;
+ const isGuardian = a.roles.has('guardian');
+ const isBeneficiary = a.roles.has('beneficiary');
+
+ // Does this viewer still need to act on the open process?
+ let needsAction = false;
+ if (active && ['pending_approvals', 'time_locked', 'ready'].includes(active.status)) {
+ const alreadyVoted = active.votes?.some((v) => v.user_id === auth.userId);
+ if (active.kind === 'recovery' && isGuardian && active.requester_id !== auth.userId && !alreadyVoted) needsAction = true;
+ if (active.kind === 'inheritance' && (isGuardian || isBeneficiary) && !alreadyVoted && active.needs_beneficiary_confirmation && isBeneficiary) needsAction = true;
+ if (active.kind === 'inheritance' && isGuardian && !alreadyVoted) needsAction = true;
+ }
+ if (needsAction) actionable++;
+
+ const config = getRecoveryConfig(a.meta);
+ items.push({
+ agent_id: a.agent_id,
+ agent_name: a.agent_name,
+ avatar_url: a.avatar_url,
+ owner: a.owner,
+ roles: [...a.roles],
+ since: a.since,
+ active_request: active,
+ needs_action: needsAction,
+ dead_man_enabled: config.dead_man.enabled,
+ });
+ }
+ // Sort: agents needing action first, then those with an open process, then rest.
+ items.sort((x, y) => (y.needs_action - x.needs_action) || ((y.active_request ? 1 : 0) - (x.active_request ? 1 : 0)));
+
+ return json(res, 200, { data: { items, actionable, count: items.length } });
+});
diff --git a/api/agents/recovery.js b/api/agents/recovery.js
new file mode 100644
index 000000000..5c9af850f
--- /dev/null
+++ b/api/agents/recovery.js
@@ -0,0 +1,281 @@
+// /api/agents/:id/recovery — social recovery & inheritance for a custodial agent
+// wallet. Dispatched from api/agents/[id].js with the remaining path segments.
+//
+// Routes (all owner/guardian-gated, all writes CSRF-protected):
+// GET /recovery status: config + roster + active process + dead-man
+// PUT /recovery owner: set guardians/beneficiary/threshold/dead-man
+// POST /recovery/checkin owner: "I'm here" — resets dead-man, aborts inheritance
+// GET /recovery/requests owner: recent request history
+// POST /recovery/requests guardian/beneficiary: open a recovery
+// POST /recovery/requests/:rid/approve guardian: approve
+// POST /recovery/requests/:rid/decline guardian: decline
+// POST /recovery/requests/:rid/confirm guardian/beneficiary: confirm an inheritance
+// POST /recovery/requests/:rid/cancel owner (reject) or requester (withdraw)
+// POST /recovery/requests/:rid/complete finalize a ready recovery → transfer ownership
+// POST /recovery/inheritance/arm beneficiary/guardian: arm the dead-man once eligible
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import {
+ getRecoveryConfig, effectiveThreshold, listGuardians, setGuardiansAndConfig,
+ getOwnerActivity, deadManStatus, getActiveRequest, decorateRequest, listRequests,
+ createRecoveryRequest, recordVote, cancelRequest, completeIfReady, ownerCheckIn,
+ armInheritance, confirmInheritance, resolveUserHandle, isUuid, MAX_GUARDIANS,
+} from '../_lib/agent-recovery.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+function sendErr(res, e) {
+ if (e && e.status) return error(res, e.status, e.code || 'error', e.message, e.detail ? { detail: e.detail } : undefined);
+ console.error('[recovery] unexpected error', e?.message, e?.stack);
+ return error(res, 500, 'server_error', 'something went wrong — no ownership was changed');
+}
+
+// Load the agent + the caller's relationship to it (owner / guardian / beneficiary).
+async function loadContext(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return null; }
+ const [agent] = await sql`SELECT id, user_id, name, meta, avatar_id, avatar_url FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!agent) { error(res, 404, 'not_found', 'agent not found'); return null; }
+ const roles = await sql`SELECT role FROM agent_recovery_guardians WHERE agent_id = ${id} AND guardian_user_id = ${auth.userId} AND status = 'active'`;
+ const roleSet = new Set(roles.map((r) => r.role));
+ return {
+ auth, agent,
+ isOwner: agent.user_id === auth.userId,
+ isGuardian: roleSet.has('guardian'),
+ isBeneficiary: roleSet.has('beneficiary'),
+ roleSet,
+ };
+}
+
+// ── GET /recovery — status ─────────────────────────────────────────────────────
+async function handleGetStatus(req, res, id, ctx) {
+ const rl = await limits.walletRead(ctx.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const { agent, isOwner, isGuardian, isBeneficiary } = ctx;
+ // Only parties to the recovery graph (owner / guardian / beneficiary) may read.
+ if (!isOwner && !isGuardian && !isBeneficiary) {
+ return error(res, 403, 'forbidden', 'you are not part of this agent’s recovery circle');
+ }
+
+ const config = getRecoveryConfig(agent.meta);
+ const guardians = await listGuardians(id);
+ const guardianCount = guardians.filter((g) => g.role === 'guardian').length;
+ const beneficiary = guardians.find((g) => g.role === 'beneficiary') || null;
+ const activeRaw = await getActiveRequest(id);
+ const active = activeRaw ? await decorateRequest(activeRaw, id) : null;
+
+ // Dead-man status is computed from the owner's real activity — owner sees the
+ // full picture; guardians/beneficiary see a redacted "is it armed" view.
+ let deadMan = null;
+ if (isOwner) {
+ const { lastActiveAt, signals } = await getOwnerActivity(id, agent.user_id, agent.meta);
+ deadMan = { ...deadManStatus(config, lastActiveAt), signals };
+ } else {
+ deadMan = { enabled: config.dead_man.enabled, inactivity_days: config.dead_man.inactivity_days, grace_days: config.dead_man.grace_days };
+ }
+
+ return json(res, 200, {
+ data: {
+ agent: { id: agent.id, name: agent.name, avatar_url: agent.avatar_url || null },
+ viewer: { is_owner: isOwner, is_guardian: isGuardian, is_beneficiary: isBeneficiary, user_id: ctx.auth.userId },
+ config: {
+ threshold: config.threshold,
+ effective_threshold: effectiveThreshold(config, guardianCount),
+ dead_man: config.dead_man,
+ },
+ guardians: isOwner ? guardians : guardians.map((g) => ({ role: g.role, label: g.label, avatar_url: g.avatar_url, is_you: g.user_id === ctx.auth.userId })),
+ guardian_count: guardianCount,
+ beneficiary: beneficiary ? { label: beneficiary.label, avatar_url: beneficiary.avatar_url, is_you: beneficiary.user_id === ctx.auth.userId } : null,
+ dead_man: deadMan,
+ active_request: active,
+ max_guardians: MAX_GUARDIANS,
+ },
+ });
+}
+
+// ── PUT /recovery — owner sets the circle ──────────────────────────────────────
+async function handleSetConfig(req, res, id, ctx) {
+ if (!ctx.isOwner) return error(res, 403, 'forbidden', 'only the owner can configure recovery');
+ if (!(await requireCsrf(req, res, ctx.auth.userId))) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid body'); }
+
+ // Resolve guardian + beneficiary handles → user ids. A bad handle is a clean
+ // 400 with the offending value, never a silent drop.
+ const guardianHandles = Array.isArray(body.guardians) ? body.guardians : [];
+ if (guardianHandles.length > MAX_GUARDIANS) return error(res, 400, 'too_many_guardians', `at most ${MAX_GUARDIANS} guardians`);
+
+ const guardianIds = [];
+ const seen = new Set();
+ for (const h of guardianHandles) {
+ const u = await resolveUserHandle(h);
+ if (!u) return error(res, 400, 'unknown_guardian', `no three.ws account found for “${String(h).slice(0, 60)}”`);
+ if (u.id === ctx.auth.userId) return error(res, 400, 'self_guardian', 'you cannot be your own guardian');
+ if (seen.has(u.id)) continue;
+ seen.add(u.id);
+ guardianIds.push(u.id);
+ }
+
+ let beneficiaryId = null;
+ if (body.beneficiary) {
+ const u = await resolveUserHandle(body.beneficiary);
+ if (!u) return error(res, 400, 'unknown_beneficiary', `no three.ws account found for “${String(body.beneficiary).slice(0, 60)}”`);
+ if (u.id === ctx.auth.userId) return error(res, 400, 'self_beneficiary', 'you cannot be your own beneficiary');
+ beneficiaryId = u.id;
+ }
+
+ let threshold = undefined;
+ if (body.threshold != null) {
+ const t = Math.round(Number(body.threshold));
+ if (!Number.isFinite(t) || t < 1) return error(res, 400, 'bad_threshold', 'threshold must be at least 1');
+ if (t > guardianIds.length) return error(res, 400, 'bad_threshold', `threshold (${t}) cannot exceed the number of guardians (${guardianIds.length})`);
+ threshold = t;
+ }
+
+ let deadMan = undefined;
+ if (body.dead_man && typeof body.dead_man === 'object') {
+ if (body.dead_man.enabled === true && !beneficiaryId) {
+ return error(res, 400, 'dead_man_needs_beneficiary', 'the dead-man’s switch needs a beneficiary to inherit the agent');
+ }
+ deadMan = body.dead_man;
+ }
+
+ try {
+ const result = await setGuardiansAndConfig({
+ agentId: id, ownerId: ctx.auth.userId, guardianIds, beneficiaryId, threshold, deadMan, meta: ctx.agent.meta, req,
+ });
+ return json(res, 200, { data: { guardians: result.guardians, config: getRecoveryConfig({ recovery: result.config }) } });
+ } catch (e) { return sendErr(res, e); }
+}
+
+// ── POST /recovery/checkin ─────────────────────────────────────────────────────
+async function handleCheckin(req, res, id, ctx) {
+ if (!ctx.isOwner) return error(res, 403, 'forbidden', 'only the owner can check in');
+ if (!(await requireCsrf(req, res, ctx.auth.userId))) return;
+ try {
+ const r = await ownerCheckIn({ agentId: id, ownerId: ctx.auth.userId, req });
+ return json(res, 200, { data: r });
+ } catch (e) { return sendErr(res, e); }
+}
+
+// ── /recovery/requests ─────────────────────────────────────────────────────────
+async function handleRequests(req, res, id, ctx, parts) {
+ const rid = parts[5];
+ const verb = parts[6];
+
+ // POST /recovery/requests — open a recovery
+ if (!rid) {
+ if (req.method === 'GET') {
+ if (!ctx.isOwner) return error(res, 403, 'forbidden', 'only the owner can list recovery history');
+ const rl = await limits.auditLogRead(ctx.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+ const items = await listRequests(id);
+ return json(res, 200, { data: { items } });
+ }
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!(await requireCsrf(req, res, ctx.auth.userId))) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ let body = {};
+ try { body = await readJson(req); } catch { body = {}; }
+ try {
+ const reqOut = await createRecoveryRequest({ agentId: id, requesterId: ctx.auth.userId, reason: body.reason, req });
+ return json(res, 201, { data: reqOut });
+ } catch (e) { return sendErr(res, e); }
+ }
+
+ if (!isUuid(rid)) return error(res, 404, 'not_found', 'recovery request not found');
+ if (!method(req, res, ['POST'])) return;
+ if (!(await requireCsrf(req, res, ctx.auth.userId))) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ try {
+ if (verb === 'approve' || verb === 'decline') {
+ const out = await recordVote({ agentId: id, requestId: rid, guardianId: ctx.auth.userId, decision: verb, req });
+ return json(res, 200, { data: out });
+ }
+ if (verb === 'confirm') {
+ const out = await confirmInheritance({ agentId: id, requestId: rid, actorId: ctx.auth.userId, req });
+ return json(res, 200, { data: out });
+ }
+ if (verb === 'cancel') {
+ // Owner cancelling = reject (the canonical "I'm here" abort). Requester
+ // cancelling = withdraw. Anyone else may not cancel.
+ const [reqRow] = await sql`SELECT requester_id FROM agent_recovery_requests WHERE id = ${rid} AND agent_id = ${id}`;
+ if (!reqRow) return error(res, 404, 'not_found', 'recovery request not found');
+ const byOwner = ctx.isOwner;
+ const isRequester = reqRow.requester_id === ctx.auth.userId;
+ if (!byOwner && !isRequester) return error(res, 403, 'forbidden', 'only the owner or the requester can cancel this');
+ const out = await cancelRequest({ agentId: id, requestId: rid, actorId: ctx.auth.userId, byOwner, req });
+ return json(res, 200, { data: out });
+ }
+ if (verb === 'complete') {
+ // Completing transfers funds-control: must be the requester, the nominee,
+ // or a guardian (anyone in the circle who can push the ready request over
+ // the line). Server re-verifies readiness regardless of who calls.
+ if (!ctx.isOwner && !ctx.isGuardian && !ctx.isBeneficiary) {
+ const [reqRow] = await sql`SELECT requester_id, new_owner_id FROM agent_recovery_requests WHERE id = ${rid} AND agent_id = ${id}`;
+ if (!reqRow || (reqRow.requester_id !== ctx.auth.userId && reqRow.new_owner_id !== ctx.auth.userId)) {
+ return error(res, 403, 'forbidden', 'you are not part of this recovery');
+ }
+ }
+ const out = await completeIfReady({ agentId: id, requestId: rid, actorId: ctx.auth.userId, req });
+ return json(res, 200, { data: out });
+ }
+ return error(res, 404, 'not_found', 'unknown recovery action');
+ } catch (e) { return sendErr(res, e); }
+}
+
+// ── POST /recovery/inheritance/arm ─────────────────────────────────────────────
+async function handleInheritance(req, res, id, ctx, parts) {
+ const verb = parts[5];
+ if (verb !== 'arm') return error(res, 404, 'not_found', 'unknown inheritance action');
+ if (!method(req, res, ['POST'])) return;
+ // Only the beneficiary or a guardian may manually arm.
+ if (!ctx.isGuardian && !ctx.isBeneficiary) return error(res, 403, 'forbidden', 'only a guardian or the beneficiary can arm inheritance');
+ if (!(await requireCsrf(req, res, ctx.auth.userId))) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ try {
+ const out = await armInheritance({ agentId: id, actorId: ctx.auth.userId, req });
+ if (!out) return error(res, 409, 'not_eligible', 'inheritance can’t be armed yet — the owner is still active, there’s no beneficiary, or a process is already running');
+ return json(res, 201, { data: out });
+ } catch (e) { return sendErr(res, e); }
+}
+
+// ── dispatcher ─────────────────────────────────────────────────────────────────
+export default async function handler(req, res, id, action, parts) {
+ if (cors(req, res, { methods: 'GET,POST,PUT,OPTIONS', credentials: true })) return;
+
+ const ctx = await loadContext(req, res, id);
+ if (!ctx) return; // loadContext already sent the error
+
+ // /recovery (no further segment) — config get/set
+ if (!action) {
+ if (req.method === 'GET') return handleGetStatus(req, res, id, ctx);
+ if (req.method === 'PUT') return handleSetConfig(req, res, id, ctx);
+ return method(req, res, ['GET', 'PUT']);
+ }
+ if (action === 'checkin') {
+ if (!method(req, res, ['POST'])) return;
+ return handleCheckin(req, res, id, ctx);
+ }
+ if (action === 'requests') return handleRequests(req, res, id, ctx, parts);
+ if (action === 'inheritance') return handleInheritance(req, res, id, ctx, parts);
+ return error(res, 404, 'not_found', 'unknown recovery resource');
+}
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index c6f921db9..dd478c833 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -487,11 +487,6 @@ async function handleWithdraw(req, res, id) {
if (owned.error) return;
const { auth, meta, address: fromAddress, encryptedSecret } = owned;
- // CSRF: sweeping a custodial wallet is the single highest-stakes action on the
- // platform — it must be at least as protected as message-signing. Bearer/API-key
- // callers are exempt inside requireCsrf (the token is itself proof of intent).
- if (!(await requireCsrf(req, res, auth.userId))) return;
-
// Owner-only daily withdraw cap + per-IP burst guard.
const rlUser = await limits.withdrawalPerUser(auth.userId);
if (!rlUser.success) return rateLimited(res, rlUser);
@@ -512,6 +507,15 @@ async function handleWithdraw(req, res, id) {
const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
const asset = typeof body.asset === 'string' && body.asset.trim() ? body.asset.trim() : 'SOL';
const simulate = body.simulate === true;
+
+ // CSRF: sweeping a custodial wallet is the single highest-stakes action on the
+ // platform — it must be at least as protected as message-signing. Bearer/API-key
+ // callers are exempt inside requireCsrf (the token is itself proof of intent). A
+ // `simulate` request moves no funds and never touches the key (it returns a live
+ // preview, like the trade endpoint's preview), so it is CSRF-exempt — otherwise a
+ // read-back/quote would burn the owner's single-use token before they confirm.
+ if (!simulate && !(await requireCsrf(req, res, auth.userId))) return;
+
const idempotencyKey =
typeof body.idempotency_key === 'string' && body.idempotency_key.trim()
? body.idempotency_key.trim().slice(0, 128)
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 863d36ac7..c7822f7a5 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -113,6 +113,7 @@ const HANDLERS = {
'siwx-gc': handleSiwxGc,
'unstoppable-tick': handleUnstoppableTick,
'cosmetic-splits-sweep': handleCosmeticSplitsSweep,
+ 'treasury-autopilot': handleTreasuryAutopilot,
};
export default wrap(async (req, res) => {
@@ -4089,3 +4090,52 @@ async function handleCosmeticSplitsSweep(req, res) {
}
return json(res, 200, { ok: true, ...result });
}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// treasury-autopilot — run every armed agent's treasury policy on a cadence.
+//
+// Each armed, non-killed agent gets one autopilot cycle: self-fund compute,
+// maintain the buffer, DCA income into $THREE, compound coin fees into buybacks,
+// and sweep profit — every action real, idempotent, spend-policy-gated, audited.
+// Per-agent failures are isolated; one bad agent never aborts the sweep.
+// ═══════════════════════════════════════════════════════════════════════════
+
+async function handleTreasuryAutopilot(req, res) {
+ if (!requireCron(req, res)) return;
+ const { runAutopilotCycle } = await import('../_lib/treasury-autopilot.js');
+
+ let agents;
+ try {
+ agents = await sql`
+ SELECT id
+ FROM agent_identities
+ WHERE deleted_at IS NULL
+ AND (meta->'autopilot'->>'armed')::boolean = true
+ AND COALESCE((meta->'autopilot'->>'kill_switch')::boolean, false) = false
+ AND meta->>'solana_address' IS NOT NULL
+ ORDER BY (meta->'autopilot'->>'updated_at') ASC NULLS FIRST
+ LIMIT 200
+ `;
+ } catch (err) {
+ console.error('[treasury-autopilot] fetch armed agents failed:', err?.message || err);
+ return json(res, 200, { ok: false, error: 'fetch_failed' });
+ }
+
+ let ran = 0;
+ let actions = 0;
+ const summary = [];
+ for (const a of agents) {
+ try {
+ const result = await runAutopilotCycle({ agentId: a.id, userId: null, network: 'mainnet', trigger: 'cron' });
+ if (result?.ran) {
+ ran += 1;
+ const did = (result.results || []).filter((r) => r.last_status === 'ok').length;
+ actions += did;
+ summary.push({ agent: a.id, actions: did, reasons: (result.results || []).map((r) => `${r.kind}:${r.last_status}`) });
+ }
+ } catch (err) {
+ console.error('[treasury-autopilot] agent cycle failed:', a.id, err?.message || err);
+ }
+ }
+ return json(res, 200, { ok: true, agents: agents.length, ran, actions, summary });
+}
diff --git a/api/cron/dead-man-switch.js b/api/cron/dead-man-switch.js
new file mode 100644
index 000000000..66d228ab7
--- /dev/null
+++ b/api/cron/dead-man-switch.js
@@ -0,0 +1,46 @@
+// GET /api/cron/dead-man-switch — the inheritance heartbeat.
+//
+// Runs daily. For every agent with the dead-man's switch enabled it:
+// 1. expires stalled recovery requests (and lifts their freeze),
+// 2. ARMS an inheritance request when the owner's inactivity has crossed the
+// owner-set threshold (freezes the wallet, notifies all parties, opens the
+// grace + confirmation window) — it never transfers here,
+// 3. reminds owners approaching the threshold to tap "I'm here",
+// 4. COMPLETES inheritance requests whose grace window elapsed WITH the required
+// confirmation — the only place the switch actually fires, and only after a
+// generous, cancellable window.
+//
+// Nothing here decrypts or exports a key: an inheritance, like a recovery, only
+// changes agent_identities.user_id. Owner activity (a login, a trade, an explicit
+// check-in) cancels everything — the switch is always defeatable by being alive.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { runDeadManSweep } from '../_lib/agent-recovery.js';
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const startedAt = Date.now();
+ const summary = await runDeadManSweep();
+ const ms = Date.now() - startedAt;
+ console.info(`[dead-man] sweep done in ${ms}ms`, summary);
+ return json(res, 200, { data: { ...summary, took_ms: ms } });
+});
diff --git a/api/cron/mirror-fanout.js b/api/cron/mirror-fanout.js
new file mode 100644
index 000000000..1619e00fb
--- /dev/null
+++ b/api/cron/mirror-fanout.js
@@ -0,0 +1,81 @@
+// GET /api/cron/mirror-fanout — drive the custodial copy-trade (mirror) engine.
+//
+// For every active follow edge whose leader has made a NEW confirmed trade since
+// the edge's cursor, size the trade for the follower and execute it through the
+// task-05 engine inside the follower's spend policy (api/_lib/agent-mirror.js).
+// Idempotent end to end: the agent_mirror_fills unique key and the custody
+// idempotency key both prevent double-mirroring, so re-running this cron (or
+// overlapping with an owner "Sync now") never double-spends.
+//
+// Bounded so a 2-minute cron can never run away: only edges with a leader trade
+// in the recent window are scanned, and each edge processes at most N events.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sql } from '../_lib/db.js';
+import { syncFollow } from '../_lib/agent-mirror.js';
+
+const NETWORKS = ['mainnet', 'devnet'];
+const MAX_FOLLOWS_PER_RUN = 120;
+const MAX_EVENTS_PER_FOLLOW = 15;
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }
+ return true;
+}
+
+async function fanout(network, stats) {
+ // Candidate edges: enabled, not killed by the follower's agent-wide switch, and
+ // whose leader has at least one confirmed trade newer than the edge cursor.
+ const follows = await sql`
+ SELECT f.*, la.name AS leader_name
+ FROM agent_mirror_follows f
+ JOIN agent_identities fa ON fa.id = f.follower_agent_id AND fa.deleted_at IS NULL
+ JOIN agent_identities la ON la.id = f.leader_agent_id AND la.deleted_at IS NULL
+ WHERE f.enabled = true
+ AND f.network = ${network}
+ AND COALESCE(fa.meta->>'mirror_killed', 'false') <> 'true'
+ AND EXISTS (
+ SELECT 1 FROM agent_custody_events e
+ WHERE e.agent_id = f.leader_agent_id
+ AND e.network = ${network}
+ AND e.category = 'trade'
+ AND e.status = 'confirmed'
+ AND e.id > f.last_leader_event_id
+ AND e.created_at > now() - interval '20 minutes'
+ )
+ ORDER BY f.updated_at ASC
+ LIMIT ${MAX_FOLLOWS_PER_RUN}
+ `;
+ if (!follows.length) return;
+ stats.edges = (stats.edges || 0) + follows.length;
+
+ for (const f of follows) {
+ try {
+ const r = await syncFollow(f, { maxEvents: MAX_EVENTS_PER_FOLLOW });
+ for (const res of r.results) {
+ stats[res.status] = (stats[res.status] || 0) + 1;
+ }
+ } catch (err) {
+ stats.error = (stats.error || 0) + 1;
+ stats.last_error = (err?.message || 'error').slice(0, 160);
+ }
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const stats = {};
+ for (const network of NETWORKS) {
+ try { await fanout(network, stats); }
+ catch (err) { stats[`error_${network}`] = (err?.message || 'error').slice(0, 160); }
+ }
+ return json(res, 200, { ok: true, ...stats });
+});
diff --git a/api/mirror/leaderboard.js b/api/mirror/leaderboard.js
new file mode 100644
index 000000000..c0e827a51
--- /dev/null
+++ b/api/mirror/leaderboard.js
@@ -0,0 +1,124 @@
+// GET /api/mirror/leaderboard — performance-weighted discovery of followable
+// agents for custodial copy-trading (task 09).
+//
+// Ranks agents by REAL, on-chain-derived performance from real fills (sniper
+// closed positions + the discretionary custody ledger), never inflated. The
+// trust surface of copy-trading: you find a leader by their honest track record
+// — losers included — and every number traces to a real signature.
+//
+// Public, cached. Sort by: score (default) | pnl | followers | volume | winrate.
+
+import { cors, json, method, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const SORTS = new Set(['score', 'pnl', 'followers', 'volume', 'winrate']);
+const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / 1e9);
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const p = new URL(req.url, 'http://x').searchParams;
+ const network = NETWORKS.has(p.get('network')) ? p.get('network') : 'mainnet';
+ const sort = SORTS.has(p.get('sort')) ? p.get('sort') : 'score';
+ const limit = Math.min(50, Math.max(1, parseInt(p.get('limit') || '25', 10) || 25));
+
+ // Realized stats per agent from closed sniper round-trips — the honest P&L
+ // surface. LEFT JOIN follower counts + discretionary trade activity so an agent
+ // that trades only discretionarily still appears (with volume, no realized P&L).
+ const rows = await sql`
+ WITH closed AS (
+ SELECT agent_id,
+ count(*)::int AS settled,
+ count(*) FILTER (WHERE realized_pnl_lamports > 0)::int AS wins,
+ COALESCE(SUM(realized_pnl_lamports), 0)::text AS pnl_lamports,
+ COALESCE(SUM(entry_quote_lamports), 0)::text AS entry_lamports
+ FROM agent_sniper_positions
+ WHERE network = ${network} AND status = 'closed'
+ GROUP BY agent_id
+ ),
+ activity AS (
+ SELECT agent_id,
+ count(*)::int AS trades,
+ COALESCE(SUM(amount_lamports) FILTER (WHERE asset = 'SOL'), 0)::text AS buy_lamports,
+ max(created_at) AS last_trade_at
+ FROM agent_custody_events
+ WHERE network = ${network} AND category = 'trade' AND status IN ('confirmed','ok')
+ GROUP BY agent_id
+ ),
+ followers AS (
+ SELECT leader_agent_id AS agent_id,
+ count(*)::int AS followers,
+ count(*) FILTER (WHERE enabled)::int AS active_followers
+ FROM agent_mirror_follows
+ WHERE network = ${network}
+ GROUP BY leader_agent_id
+ )
+ SELECT a.id, a.name, a.avatar_url, a.profile_image_url,
+ COALESCE(c.settled, 0) AS settled, COALESCE(c.wins, 0) AS wins,
+ COALESCE(c.pnl_lamports, '0') AS pnl_lamports, COALESCE(c.entry_lamports, '0') AS entry_lamports,
+ COALESCE(act.trades, 0) AS trades, COALESCE(act.buy_lamports, '0') AS buy_lamports,
+ act.last_trade_at,
+ COALESCE(fl.followers, 0) AS followers, COALESCE(fl.active_followers, 0) AS active_followers
+ FROM agent_identities a
+ LEFT JOIN closed c ON c.agent_id = a.id
+ LEFT JOIN activity act ON act.agent_id = a.id
+ LEFT JOIN followers fl ON fl.agent_id = a.id
+ WHERE a.deleted_at IS NULL AND a.is_public <> false
+ AND (c.settled IS NOT NULL OR act.trades IS NOT NULL)
+ LIMIT 500
+ `.catch(() => []);
+
+ const leaders = rows.map((r) => {
+ const pnlSol = lamToSol(r.pnl_lamports);
+ const entrySol = lamToSol(r.entry_lamports);
+ const settled = Number(r.settled || 0);
+ const wins = Number(r.wins || 0);
+ const winRate = settled > 0 ? (wins / settled) * 100 : null;
+ const roiPct = entrySol > 0 ? (pnlSol / entrySol) * 100 : null;
+ const buyVolSol = lamToSol(r.buy_lamports);
+ const followers = Number(r.followers || 0);
+ // Composite score: realized ROI weighted by sample size (so a 1-trade fluke
+ // can't top a consistent trader), plus a small follower-trust nudge. Honest:
+ // an agent with no settled trades scores on volume/activity alone.
+ const sample = Math.min(1, settled / 8);
+ const score = Math.round(
+ (roiPct != null ? roiPct * sample : 0) +
+ (winRate != null ? (winRate - 50) * 0.5 * sample : 0) +
+ Math.min(20, followers * 2) +
+ Math.min(10, buyVolSol),
+ );
+ return {
+ agent_id: r.id,
+ name: r.name,
+ avatar: r.avatar_url || r.profile_image_url || null,
+ settled, wins, win_rate: winRate == null ? null : round2(winRate),
+ pnl_sol: round4(pnlSol), roi_pct: roiPct == null ? null : round2(roiPct),
+ trades: Number(r.trades || 0), volume_sol: round4(buyVolSol),
+ followers, active_followers: Number(r.active_followers || 0),
+ last_trade_at: r.last_trade_at || null,
+ score,
+ };
+ });
+
+ const cmp = {
+ score: (a, b) => b.score - a.score,
+ pnl: (a, b) => b.pnl_sol - a.pnl_sol,
+ followers: (a, b) => b.followers - a.followers,
+ volume: (a, b) => b.volume_sol - a.volume_sol,
+ winrate: (a, b) => (b.win_rate ?? -1) - (a.win_rate ?? -1),
+ }[sort];
+ leaders.sort(cmp);
+ const ranked = leaders.slice(0, limit).map((l, i) => ({ rank: i + 1, ...l }));
+
+ res.setHeader?.('cache-control', 'public, max-age=30, s-maxage=60');
+ return json(res, 200, { data: { network, sort, leaders: ranked } });
+}
+
+function round2(x) { return Math.round(x * 100) / 100; }
+function round4(x) { return Math.round(x * 1e4) / 1e4; }
diff --git a/api/og/agent.js b/api/og/agent.js
index fb37f860d..193ed0c95 100644
--- a/api/og/agent.js
+++ b/api/og/agent.js
@@ -75,6 +75,29 @@ export default wrap(async (req, res) => {
const desc = trunc(row.description || '3D AI Agent on three.ws', 80);
const isOnchain = Boolean(row.erc8004_agent_id) || Boolean(row.meta?.onchain);
+ // Wallet identity for the share card — the agent's real custodial address
+ // (vanity-aware) plus lifetime tips, so a shared wallet link previews with a
+ // stat worth screenshotting and a clear "pay me / fork me" hook. Public data
+ // only; never a secret. Tolerates a tip-ledger read failure (omits the stat).
+ const solAddress = typeof row.meta?.solana_address === 'string' ? row.meta.solana_address : null;
+ const vanPrefix = row.meta?.solana_vanity_prefix || null;
+ const vanSuffix = row.meta?.solana_vanity_suffix || null;
+ let tipsCount = 0;
+ if (solAddress) {
+ try {
+ const [agg] = await sql`
+ SELECT COUNT(*)::int AS n
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND event_type = 'tip' AND status = 'confirmed'
+ `;
+ tipsCount = agg?.n ?? 0;
+ } catch { /* omit the tips stat, keep the card */ }
+ }
+ const addrShort = solAddress
+ ? `${vanPrefix && solAddress.startsWith(vanPrefix) ? vanPrefix : solAddress.slice(0, 4)}…${vanSuffix && solAddress.endsWith(vanSuffix) ? vanSuffix : solAddress.slice(-4)}`
+ : null;
+ const isVanity = Boolean((vanPrefix && solAddress?.startsWith(vanPrefix)) || (vanSuffix && solAddress?.endsWith(vanSuffix)));
+
const [c1, c2] = gradientForName(row.name);
const initial = (row.name || 'A')[0].toUpperCase();
@@ -167,10 +190,21 @@ export default wrap(async (req, res) => {
<!-- skills / description panels -->
<line x1="440" y1="260" x2="1176" y2="260" stroke="#1f2937" stroke-width="1"/>
+ <!-- wallet identity strip (vanity address + lifetime tips) -->
+ ${addrShort ? `
+ <text x="440" y="296" font-family="Inter,system-ui,sans-serif" font-size="11" font-weight="600"
+ letter-spacing=".1em" fill="#7c6bb0">${isVanity ? '✦ VANITY WALLET' : 'AGENT WALLET'}</text>
+ <text x="440" y="330" font-family="ui-monospace,'JetBrains Mono',Menlo,monospace" font-size="26" font-weight="700"
+ fill="#c4b5fd">${x(addrShort)}</text>
+ ${tipsCount > 0 ? `
+ <rect x="440" y="350" width="${88 + String(tipsCount).length * 14}" height="32" rx="16" fill="rgba(139,92,246,.12)" stroke="rgba(139,92,246,.4)" stroke-width="1"/>
+ <text x="458" y="371" font-family="Inter,system-ui,sans-serif" font-size="14" font-weight="700" fill="#c4b5fd">◎ ${tipsCount} tip${tipsCount === 1 ? '' : 's'} received</text>`
+ : `<text x="440" y="372" font-family="Inter,system-ui,sans-serif" font-size="14" fill="#6b7280">Tip it · fork it · own its wallet on three.ws</text>`}
+ ` : `
<!-- proof tagline -->
<text x="440" y="300" font-family="Inter,system-ui,sans-serif" font-size="15" fill="#374151">
Build · Deploy · Trade · three.ws
- </text>
+ </text>`}
<!-- footer -->
<rect x="0" y="594" width="1200" height="36" fill="#030305"/>
diff --git a/api/reputation/leaderboard.js b/api/reputation/leaderboard.js
new file mode 100644
index 000000000..f2e67a5d3
--- /dev/null
+++ b/api/reputation/leaderboard.js
@@ -0,0 +1,104 @@
+/**
+ * GET /api/reputation/leaderboard?limit=20&network=mainnet
+ *
+ * The platform's real leaderboard of TRUSTED agents — ranked by the same
+ * non-gameable wallet-trust score the badge shows, computed entirely from real
+ * ledger + chain activity (api/_lib/trust/wallet-reputation.js). Unlike a
+ * follower count, every rank here is backed by money and time and is fully
+ * auditable: each row links straight to the agent's breakdown.
+ *
+ * Candidate pool = public agents with ANY real footprint (ledger activity, an
+ * on-chain identity, or a launched coin) so we never burn cycles scoring empty
+ * agents. We score that pool, drop the honest "new" agents (no track record),
+ * and return the top `limit` by score. Cached 5 min — trust moves slowly.
+ */
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { publicUrl } from '../_lib/r2.js';
+import { getRedis } from '../_lib/redis.js';
+import { scoreAgentsLite } from '../_lib/trust/wallet-reputation.js';
+
+const POOL = 90; // max candidates scored per request
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const limit = Math.min(50, Math.max(1, Number(p.get('limit') || 20)));
+
+ const cacheKey = `walletrep:leaderboard:v1:${limit}`;
+ const redis = await getRedis();
+ if (redis) {
+ try {
+ const cached = await redis.get(cacheKey);
+ if (cached) {
+ res.setHeader('X-Cache', 'HIT');
+ return json(res, 200, cached, { 'cache-control': 'public, max-age=120, s-maxage=300' });
+ }
+ } catch {
+ /* miss */
+ }
+ }
+
+ // Candidate pool — public agents with a real footprint.
+ const rows = await sql`
+ select
+ i.id, i.name,
+ i.meta->>'solana_address' as solana_address,
+ a.thumbnail_key as avatar_thumbnail_key,
+ a.visibility as avatar_visibility
+ from agent_identities i
+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null
+ where i.deleted_at is null and i.is_public = true
+ and (
+ exists (select 1 from agent_custody_events e where e.agent_id = i.id)
+ or i.erc8004_agent_id is not null
+ or exists (select 1 from pump_agent_mints m where m.agent_id = i.id)
+ )
+ limit ${POOL}
+ `.catch(() => []);
+
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ const reps = await scoreAgentsLite([...byId.keys()]);
+
+ const ranked = [...reps.entries()]
+ .filter(([, rep]) => rep && !rep.isNew)
+ .sort((a, b) => b[1].score - a[1].score)
+ .slice(0, limit)
+ .map(([id, rep], idx) => {
+ const r = byId.get(id) || {};
+ const thumbPub = r.avatar_visibility === 'public' || r.avatar_visibility === 'unlisted';
+ return {
+ rank: idx + 1,
+ id,
+ name: r.name || null,
+ avatar_thumbnail_url: r.avatar_thumbnail_key && thumbPub ? publicUrl(r.avatar_thumbnail_key) : null,
+ solana_address: typeof r.solana_address === 'string' ? r.solana_address : null,
+ score: rep.score,
+ tier: rep.tier,
+ tier_label: rep.tierLabel,
+ totals: rep.totals,
+ agent_url: `https://three.ws/agent/${encodeURIComponent(id)}`,
+ breakdown_url: `https://three.ws/agent/${encodeURIComponent(id)}/wallet#reputation`,
+ };
+ });
+
+ const payload = {
+ generated_at: new Date().toISOString(),
+ count: ranked.length,
+ scored: reps.size,
+ agents: ranked,
+ };
+
+ if (redis && ranked.length) {
+ redis.set(cacheKey, payload, { ex: 300 }).catch(() => {});
+ }
+ res.setHeader('X-Cache', 'MISS');
+ return json(res, 200, payload, { 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=120' });
+});
diff --git a/api/trending.js b/api/trending.js
index 89f86291d..fd6d122a6 100644
--- a/api/trending.js
+++ b/api/trending.js
@@ -103,6 +103,43 @@ export default wrap(async (req, res) => {
};
});
+ // Reputation as a real discovery signal. Attach each agent's wallet-trust
+ // score (computed from real ledger + chain activity) and, when sort=trust is
+ // requested, blend it into the ranking as ONE signal among others — never a
+ // pay-to-win override. Best-effort: a momentary scoring failure just leaves an
+ // agent without a score and keeps the activity ranking intact.
+ const sortMode = p.get('sort') === 'trust' ? 'trust' : 'activity';
+ if (agents.length) {
+ try {
+ const { scoreAgentsLite } = await import('./_lib/trust/wallet-reputation.js');
+ const reps = await scoreAgentsLite(agents.map((a) => a.id));
+ for (const a of agents) {
+ const rep = reps.get(a.id);
+ if (rep) {
+ a.reputation = { score: rep.score, tier: rep.tier, tierLabel: rep.tierLabel, isNew: rep.isNew };
+ }
+ }
+ if (sortMode === 'trust') {
+ // Blend: normalized activity (0..1) + normalized trust (0..1), trust
+ // weighted 0.45 so genuine activity still leads but proven, trusted
+ // agents rise. Activity is normalized within this page's range.
+ const maxChats = Math.max(1, ...agents.map((a) => a.window_chats || a.chat_count || 0));
+ const blended = agents
+ .map((a) => {
+ const act = (a.window_chats || a.chat_count || 0) / maxChats;
+ const trust = (a.reputation?.score || 0) / 100;
+ return { a, k: act * 0.55 + trust * 0.45 };
+ })
+ .sort((x, y) => y.k - x.k);
+ blended.forEach((b, i) => (b.a.rank = i + 1));
+ agents.length = 0;
+ agents.push(...blended.map((b) => b.a));
+ }
+ } catch {
+ /* reputation enrichment is additive — never block the trending feed */
+ }
+ }
+
// ── Coins (Oracle conviction) ───────────────────────────────────────────
const coinRows = await sql`
select mint, symbol, name, score, tier, momentum, pedigree, structure, narrative,
diff --git a/data/changelog.json b/data/changelog.json
index 5a3e1b7e9..9ab4704f9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,51 @@
{
"$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": "Your avatar has a job — the Earn home in every agent wallet",
+ "summary": "Every agent wallet now has an Earn tab that turns it from a vault into a working participant in the agent economy. It opens with the number that matters: what your avatar has actually earned — today, this week, and all time — every dollar traced to a real settlement (skill sales and tips), never an estimate. Come back after time away and it tells you what it made while you were gone. Below that is the earning engine: price your agent's skills in USDC right where the money lands, so the moment someone buys, real funds move into this wallet. Then the part that makes letting an agent spend on its own feel safe — your agent can pay other agents and services over real x402 rails, but only inside the daily cap, per-payment limit, and allowlist you set, with a prominent kill switch that freezes all autonomous spending instantly (your own withdrawals always stay open). Finally, a clean receipts statement of every payment in and out — counterparty, amount, time, and on-chain signature — plus a path to the live services directory where agents discover and hire each other. Owner-only, enforced in the UI and on the server.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/economy"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Social recovery & inheritance — a funded agent that never dies with its owner",
+ "summary": "Your agent's wallet is custodial and real-money funded, so \"I lost access\" or \"the owner is gone\" should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping \"I'm here\"). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds.",
+ "tags": [
+ "feature",
+ "security"
+ ],
+ "link": "/guardian"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Wallet figures read the same everywhere — one money and address style across the app",
+ "summary": "An agent's portfolio value now formats identically wherever it appears — the tiny wallet chip on a card, the inline net-worth on a profile, the presence panel — so the same wallet never shows \"$1k\" in one place and \"$1.2K\" in another. Addresses shorten the same way across surfaces too, and the wallet's violet accent now flows from one design token instead of scattered colors, so the whole wallet layer reads as a single, coherent system. We also added an automated test that proves the platform's core promise on every fork: saving someone else's avatar always mints a brand-new wallet with its own distinct Solana and EVM addresses, never copies a secret, and leaves the original's wallet untouched.",
+ "tags": [
+ "improvement",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Treasury Autopilot — the agent that funds its own existence",
+ "summary": "Your agent can now manage its own money under a policy you write in plain English. Tell it something like \"Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, compound coin fees into buybacks weekly, and sweep anything over 3 SOL to me on Fridays\" — it compiles that into clear, bounded rules and shows them back for you to approve before anything runs. Once armed, it executes each rule as a real, on-chain action from the agent's own wallet: it pays its own metered LLM and voice costs, holds your safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to you — every move clamped to your spend limits, idempotent, and written to the custody trail with an explorer link. A runway dashboard shows the honest truth: real income vs. real compute cost, the buffer, $THREE accumulated, buybacks executed, profit swept, and how long the agent self-sustains at its current burn — a net-negative agent says so plainly. A prominent kill switch halts everything instantly, and any rule pauses or edits in one tap. Owner-only, by construction.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Tune how your agent wears its wallet — presence dial and earned regalia",
+ "summary": "The net-worth aura now comes with a presence panel on every agent's viewer and profile. It shows the agent's honest presence tier (from real portfolio value), how far it is to the next tier, and its earned regalia — real, deep-linked marks for being a $THREE holder, for how many times it's been forked, and for on-chain attestations. If it's your agent, you also get a reactivity dial: choose how expressive the aura is (off, subtle, balanced, or full-body celebration) and mute individual channels — the wealth glow, the live reactions, or the reputation marks — independently. Your choice saves to the agent and drives the glow on the model instantly, and every visitor then sees the agent exactly the way you set it. Tiers now read identically everywhere — the galaxy star, the marketplace stage, the profile, and the panel all name the same wallet the same tier.",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-23",
"title": "Talk to your agent and it trades — the Conversational Wallet",
diff --git a/data/pages.json b/data/pages.json
index ef7ad62e3..afd6a04fb 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -545,6 +545,14 @@
"changefreq": "realtime",
"added": "2026-06-16"
},
+ {
+ "path": "/guardian",
+ "title": "Guardian console — recover & inherit agent wallets",
+ "description": "The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.",
+ "priority": 0.6,
+ "changefreq": "weekly",
+ "added": "2026-06-23"
+ },
{
"path": "/launch",
"title": "Launch a Coin",
diff --git a/examples/agent-wallet-embed.html b/examples/agent-wallet-embed.html
new file mode 100644
index 000000000..add1592dd
--- /dev/null
+++ b/examples/agent-wallet-embed.html
@@ -0,0 +1,130 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>&lt;agent-3d wallet&gt; — the portable agent wallet</title>
+ <style>
+ /* Deliberately a "stranger's blog": plain styles, no three.ws tokens.css.
+ The wallet must look right and work with nothing of ours on the page. */
+ :root { color-scheme: dark; }
+ body {
+ margin: 0;
+ padding: 40px 24px 80px;
+ background: #0c0c10;
+ color: #e8e8ea;
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ line-height: 1.5;
+ }
+ .wrap { max-width: 920px; margin: 0 auto; }
+ h1 { margin: 0 0 6px; font-size: 26px; }
+ .lede { color: #9a9aa2; margin: 0 0 28px; max-width: 60ch; }
+ h2 {
+ margin: 36px 0 10px; font-size: 13px; text-transform: uppercase;
+ letter-spacing: .06em; color: #8a8a93;
+ }
+ .grid { display: grid; gap: 24px; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); }
+ agent-3d { width: 100%; height: 420px; border-radius: 14px; overflow: hidden; background: #111; display: block; }
+ .card { background: #141418; border: 1px solid rgba(255,255,255,.07); border-radius: 14px; padding: 18px; }
+ .card h3 { margin: 0 0 4px; font-size: 15px; }
+ .card p { margin: 0 0 14px; color: #9a9aa2; font-size: 13px; }
+ pre {
+ background: #08080b; border: 1px solid rgba(255,255,255,.07); border-radius: 10px;
+ padding: 14px; overflow-x: auto; font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ font-size: 12.5px; color: #c4b5fd;
+ }
+ .note { font-size: 12.5px; color: #6b6b73; margin-top: 10px; }
+ a { color: #a78bfa; }
+ .tiny { width: 240px; max-width: 100%; }
+ .tiny agent-3d { height: 240px; }
+ </style>
+ </head>
+ <body>
+ <div class="wrap">
+ <h1>The agent wallet, dropped on any website</h1>
+ <p class="lede">
+ This page loads nothing of three.ws's own styling — it is a stand-in for a
+ stranger's blog. The <code>&lt;agent-3d wallet&gt;</code> web component below
+ renders a live 3D agent <em>and</em> its real, self-contained custodial wallet:
+ the vanity address, the live USD value, lifetime tips, and a working tip flow.
+ Everything reads from the public, CORS-safe
+ <code>/api/agents/wallet-embed</code> endpoint. It is the visitor view by
+ construction — tip + “open on three.ws”, never an owner control.
+ </p>
+
+ <h2>Live agent with its wallet</h2>
+ <div class="grid">
+ <div>
+ <agent-3d id="demo" wallet></agent-3d>
+ <p class="note" id="agent-note">Finding a public agent to show…</p>
+ </div>
+ <div class="card">
+ <h3>Same wallet, standalone</h3>
+ <p>
+ The wallet is portable on its own too — mount it into any element
+ (here, a light-DOM card; it also works inside a closed shadow root).
+ </p>
+ <div id="standalone"></div>
+ </div>
+ </div>
+
+ <h2>Tiny embed (200&nbsp;px)</h2>
+ <div class="tiny">
+ <agent-3d id="demo-tiny" wallet="tip"></agent-3d>
+ </div>
+ <p class="note">The chip stays legible and the tip popover stays usable at embed sizes.</p>
+
+ <h2>Drop it on your own page</h2>
+ <pre>&lt;script type="module" src="https://three.ws/dist-lib/agent-3d.js"&gt;&lt;/script&gt;
+
+&lt;!-- wallet → tip-enabled chip (default)
+ wallet="card" → always-open wallet card
+ wallet="identity" → read-only chip, no tip flow --&gt;
+&lt;agent-3d agent-id="YOUR_AGENT_ID" wallet style="width:360px;height:420px"&gt;&lt;/agent-3d&gt;</pre>
+ <p class="note">
+ Replace <code>YOUR_AGENT_ID</code> with any three.ws agent UUID. No API key,
+ no auth — the wallet endpoint exposes only public address + balance + tips.
+ </p>
+ </div>
+
+ <!-- Dev serves /dist-lib/agent-3d.js via a Vite plugin; prod serves the built lib. -->
+ <script type="module" src="/dist-lib/agent-3d.js"></script>
+ <script type="module">
+ import { mountPortableWallet } from '/src/shared/portable-wallet.js';
+
+ // Pick a REAL public agent so the demo shows real chain data, never a fixture.
+ async function firstPublicAgentId() {
+ const tryUrls = ['/api/marketplace/agents?limit=12', '/api/trending?limit=12'];
+ for (const u of tryUrls) {
+ try {
+ const r = await fetch(u, { headers: { accept: 'application/json' } });
+ if (!r.ok) continue;
+ const j = await r.json();
+ const list = j.agents || j.data || j.items || j.results || [];
+ const hit = list.find((a) => a && (a.id || a.agent_id));
+ if (hit) return hit.id || hit.agent_id;
+ } catch { /* try next */ }
+ }
+ return null;
+ }
+
+ const note = document.getElementById('agent-note');
+ const id = await firstPublicAgentId();
+ if (!id) {
+ note.textContent = 'No public agent available right now — open three.ws to browse agents.';
+ } else {
+ for (const elId of ['demo', 'demo-tiny']) {
+ const el = document.getElementById(elId);
+ el.setAttribute('agent-id', id);
+ el.setAttribute('src', `/api/avatars/${id}`);
+ }
+ note.innerHTML = `Showing agent <code>${id}</code> — the chip, tips, and balance are live.`;
+ mountPortableWallet(document.getElementById('standalone'), {
+ agentId: id,
+ origin: location.origin,
+ variant: 'card',
+ });
+ }
+ </script>
+ </body>
+</html>
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 3c1d780e3..f19c18883 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -586,6 +586,15 @@
<div id="ad-pulse-feed"></div>
</section>
+ <section class="ad-card" id="ad-mirror-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet"></span>
+ <h2>COPY TRADING</h2>
+ <a class="ad-card-link" href="/mirror" style="margin-left:auto;font-size:.7rem;color:var(--ink-dim,#888);text-decoration:none">Discover leaders →</a>
+ </div>
+ <div id="ad-mirror-panel"></div>
+ </section>
+
<section class="ad-card">
<div class="ad-card-head">
<span class="ad-bullet ad-bullet-amber"></span>
diff --git a/pages/galaxy.html b/pages/galaxy.html
index 18a13350e..723dcb02b 100644
--- a/pages/galaxy.html
+++ b/pages/galaxy.html
@@ -74,6 +74,15 @@
<button class="gx-search-clear" id="gxSearchClear" type="button" aria-label="Clear search" hidden>&times;</button>
<button class="gx-search-go" id="gxSearchGo" type="submit">Search</button>
</form>
+
+ <!-- Money-Cam entry — enabled once the galaxy has rendered -->
+ <button class="gx-moneycam-toggle" id="gxMoneyToggle" type="button" aria-pressed="false" disabled>
+ <span class="gx-mc-orb" aria-hidden="true"></span>
+ <span class="gx-mc-toggle-text">
+ <span class="gx-mc-toggle-label">Money-Cam</span>
+ <span class="gx-mc-toggle-sub">watch real value move · <kbd>M</kbd></span>
+ </span>
+ </button>
</div>
<!-- Constellation legend -->
@@ -115,6 +124,64 @@
<div class="gx-results-list" id="gxResultsList"></div>
</div>
+ <!-- Money-Cam panel — the live economy controls -->
+ <section class="gx-moneycam" id="gxMoneyCam" hidden aria-label="Money-Cam — the live economy">
+ <header class="gx-mc-head">
+ <div class="gx-mc-title">
+ <span class="gx-mc-live-dot" id="gxMcLiveDot" aria-hidden="true"></span>
+ <span>Money-Cam</span>
+ </div>
+ <button class="gx-mc-close" id="gxMcClose" type="button" aria-label="Close Money-Cam">&times;</button>
+ </header>
+
+ <div class="gx-mc-modes" role="tablist" aria-label="Money-Cam mode">
+ <button class="gx-mc-mode gx-active" id="gxMcModeLive" type="button" role="tab" aria-selected="true">Live</button>
+ <button class="gx-mc-mode" id="gxMcModeReplay" type="button" role="tab" aria-selected="false">Replay</button>
+ </div>
+
+ <div class="gx-mc-stats" id="gxMcStats" aria-live="polite"></div>
+
+ <div class="gx-mc-replay" id="gxMcReplay" hidden>
+ <button class="gx-mc-play" id="gxMcPlay" type="button" aria-label="Play / pause replay">▶</button>
+ <input
+ class="gx-mc-scrub"
+ id="gxMcScrub"
+ type="range"
+ min="0"
+ max="1000"
+ value="1000"
+ aria-label="Scrub through real flow history"
+ />
+ <button class="gx-mc-speed" id="gxMcSpeed" type="button" aria-label="Cycle playback speed">1×</button>
+ <div class="gx-mc-time" id="gxMcTime"></div>
+ </div>
+
+ <div class="gx-mc-filters" id="gxMcFilters" role="group" aria-label="Filter flows by type">
+ <button class="gx-mc-filter gx-active" data-type="all" type="button">All</button>
+ <button class="gx-mc-filter" data-type="tips" type="button">Tips</button>
+ <button class="gx-mc-filter" data-type="trades" type="button">Trades</button>
+ <button class="gx-mc-filter" data-type="payments" type="button">Pay</button>
+ <button class="gx-mc-filter" data-type="launches" type="button">Launches</button>
+ </div>
+
+ <div class="gx-mc-ticker" id="gxMcTicker" aria-live="polite"></div>
+
+ <div class="gx-mc-note" id="gxMcNote" hidden></div>
+
+ <div class="gx-mc-legend" aria-hidden="true">
+ <span class="gx-mc-leg" data-k="tip"><i></i>Tip</span>
+ <span class="gx-mc-leg" data-k="trade"><i></i>Trade</span>
+ <span class="gx-mc-leg" data-k="payment"><i></i>Pay</span>
+ <span class="gx-mc-leg" data-k="launch"><i></i>Launch</span>
+ </div>
+ </section>
+
+ <!-- Flow inspector — a single real transfer, click-through to its signature -->
+ <div class="gx-flow" id="gxFlow" hidden role="dialog" aria-label="Flow details">
+ <button class="gx-flow-close" id="gxFlowClose" type="button" aria-label="Close flow details">&times;</button>
+ <div class="gx-flow-body" id="gxFlowBody"></div>
+ </div>
+
<!-- Loading overlay -->
<div class="gx-overlay gx-loading" id="gxLoading">
<div class="gx-loading-orbit" aria-hidden="true">
diff --git a/pages/guardian.html b/pages/guardian.html
new file mode 100644
index 000000000..1974d288f
--- /dev/null
+++ b/pages/guardian.html
@@ -0,0 +1,46 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Guardian console · three.ws</title>
+ <meta name="description" content="The agents you’re trusted to protect. Approve a recovery, confirm an inheritance — help a fellow human back into their funded agent wallet, without ever touching their keys." />
+ <link rel="canonical" href="https://three.ws/guardian" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Guardian console · three.ws" />
+ <meta property="og:description" content="The agents you’re trusted to protect. Approve a recovery or confirm an inheritance — without ever touching anyone’s keys." />
+ <meta property="og:url" content="https://three.ws/guardian" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <style>
+ html, body { background: var(--bg-0, #0a0a0a); color: var(--ink, #e8e8e8); margin: 0; }
+ body { font-family: var(--font-body, 'Inter', system-ui, sans-serif); min-height: 100vh; }
+ * { box-sizing: border-box; }
+ .gd-wrap { max-width: 760px; margin: 0 auto; padding: 0 18px 90px; }
+ .gd-crumb { font-size: var(--text-sm, .764rem); color: var(--ink-dim, #888); padding: 18px 0 0; }
+ .gd-crumb a { color: inherit; text-decoration: none; border-bottom: 1px dotted currentColor; }
+ .gd-crumb a:hover { color: var(--ink, #e8e8e8); }
+ </style>
+</head>
+<body>
+ <header><div id="nav-container"></div></header>
+
+ <main class="gd-wrap">
+ <p class="gd-crumb"><a href="/">Home</a> / <a href="/dashboard">Dashboard</a> / Guardian console</p>
+ <div id="guardian-root"></div>
+ </main>
+
+ <script type="module" src="/src/guardian.js"></script>
+ <script src="/nav.js" defer></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+</body>
+</html>
diff --git a/pages/irl.html b/pages/irl.html
index 37fb3773f..800d22bce 100644
--- a/pages/irl.html
+++ b/pages/irl.html
@@ -1571,6 +1571,33 @@
border: 1px dashed rgba(255,255,255,0.16);
}
+ /* Tap-to-tip (IRL Solana Pay) — violet wallet family, matches the chip */
+ .irl-taptip { margin-top: 10px; }
+ .irl-taptip-toggle {
+ display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%;
+ appearance: none; cursor: pointer; font: 700 12px/1 inherit; color: #c4b5fd;
+ background: rgba(139,92,246,0.1); border: 1px solid rgba(139,92,246,0.32);
+ border-radius: 999px; padding: 9px 14px; transition: background .15s, border-color .15s;
+ }
+ .irl-taptip-toggle:hover, .irl-taptip-toggle:focus-visible { background: rgba(139,92,246,0.2); border-color: rgba(139,92,246,0.55); outline: none; }
+ .irl-taptip-toggle[aria-expanded="true"] .irl-taptip-caret { transform: rotate(180deg); }
+ .irl-taptip-caret { transition: transform .18s ease; opacity: .7; }
+ .irl-taptip-panel {
+ display: flex; align-items: center; gap: 14px; margin-top: 10px; padding: 12px;
+ background: rgba(255,255,255,0.04); border: 1px solid rgba(139,92,246,0.28); border-radius: 12px;
+ }
+ .irl-taptip-panel[hidden] { display: none; }
+ .irl-taptip-qr { background: #fff; border-radius: 10px; padding: 7px; line-height: 0; flex: none; }
+ .irl-taptip-qr svg { display: block; width: 116px; height: 116px; }
+ .irl-taptip-meta { min-width: 0; }
+ .irl-taptip-cap { font-size: 12px; color: #9ca3af; margin-bottom: 10px; line-height: 1.4; }
+ .irl-taptip-open {
+ display: inline-flex; align-items: center; gap: 4px; font: 700 12px/1 inherit; text-decoration: none;
+ color: #0a0a0a; background: linear-gradient(135deg,#c4b5fd,#a78bfa); border-radius: 999px; padding: 9px 14px;
+ transition: filter .15s;
+ }
+ .irl-taptip-open:hover { filter: brightness(1.07); }
+
/* Services list */
.irl-services-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: #9ca3af; margin-bottom: 8px; }
.irl-services-list { display: flex; flex-direction: column; gap: 8px; }
diff --git a/pages/mirror.html b/pages/mirror.html
new file mode 100644
index 000000000..36ad0e0d3
--- /dev/null
+++ b/pages/mirror.html
@@ -0,0 +1,123 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Copy Trading · three.ws</title>
+ <meta name="description" content="Follow a high-performing agent and your own agent mirrors its real trades — proportionally, and strictly within your spend policy. Leashed autonomy: your avatar trades while you sleep, and you can stop anytime." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/mirror" />
+ <meta property="og:title" content="Copy Trading · three.ws" />
+ <meta property="og:description" content="Follow a high-performing agent; your agent mirrors its real trades within your spend policy. Find a leader by an honest, on-chain track record." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Copy+Trading&amp;d=Follow+a+high-performing+agent%3B+your+agent+mirrors+its+real+trades+within+your+spend+policy.&amp;p=%2Fmirror" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Copy Trading · three.ws" />
+ <meta name="twitter:description" content="Follow a high-performing agent; your agent mirrors its real trades within your spend policy. Stop anytime." />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/mirror" />
+ <style>
+ body { background: var(--bg-0, #0a0a0a); color: var(--ink, #e8e8e8); margin: 0; font-family: var(--font-body, system-ui); }
+ .mp-shell { max-width: 920px; margin: 0 auto; padding: var(--space-lg, 24px) var(--space-md, 16px) var(--space-2xl, 64px); }
+ .mp-hero { text-align: center; padding: var(--space-xl, 42px) 0 var(--space-lg, 24px); }
+ .mp-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .66rem); text-transform: uppercase; letter-spacing: .1em; color: var(--wallet-accent, #c4b5fd); margin: 0 0 12px; }
+ .mp-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--success, #4ade80); box-shadow: 0 0 0 0 rgba(74,222,128,.5); animation: mp-pulse 1.8s ease infinite; }
+ @keyframes mp-pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(74,222,128,.5); } 70% { box-shadow: 0 0 0 7px rgba(74,222,128,0); } }
+ .mp-title { font-family: var(--font-display, system-ui); font-size: clamp(1.8rem, 5vw, 2.8rem); margin: 0 0 12px; color: var(--ink-bright, #fff); letter-spacing: -.02em; }
+ .mp-sub { max-width: 620px; margin: 0 auto; font-size: var(--text-md, .95rem); line-height: 1.6; color: var(--ink-dim, #aaa); }
+ .mp-sub b { color: var(--wallet-accent, #c4b5fd); }
+ .mp-section { margin-top: var(--space-xl, 42px); }
+ .mp-section h2 { font-family: var(--font-display, system-ui); font-size: var(--text-lg, 1.15rem); color: var(--ink-bright, #fff); margin: 0 0 4px; }
+ .mp-section .mp-desc { font-size: var(--text-sm, .82rem); color: var(--ink-dim, #9a9a9a); margin: 0 0 var(--space-md, 16px); }
+ .mp-controls { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: var(--space-md, 16px); }
+ .mp-seg { display: inline-flex; gap: 4px; background: var(--surface-1, rgba(255,255,255,.03)); padding: 4px; border-radius: var(--radius-pill, 999px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); }
+ .mp-seg button { font: inherit; font-size: var(--text-2xs, .68rem); padding: 6px 14px; border-radius: 999px; border: none; background: transparent; color: var(--ink-dim, #aaa); cursor: pointer; transition: all .15s; }
+ .mp-seg button[aria-pressed="true"] { background: var(--wallet-accent, #c4b5fd); color: #1a1340; font-weight: 700; }
+ .mp-board { display: flex; flex-direction: column; gap: 8px; }
+ .mp-lrow { display: flex; align-items: center; gap: var(--space-md, 14px); padding: var(--space-sm, 12px) var(--space-md, 14px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,.025)); transition: border-color .18s, transform .18s; }
+ .mp-lrow:hover { border-color: var(--wallet-stroke, rgba(139,92,246,.35)); transform: translateY(-1px); }
+ .mp-rank { font-family: var(--font-mono, monospace); font-size: var(--text-md, .9rem); color: var(--ink-dim, #888); width: 28px; text-align: center; flex: 0 0 auto; }
+ .mp-rank.top { color: var(--wallet-accent, #c4b5fd); font-weight: 700; }
+ .mp-av { width: 42px; height: 42px; border-radius: 50%; object-fit: cover; background: var(--surface-2, rgba(255,255,255,.05)); flex: 0 0 auto; }
+ .mp-lbody { flex: 1 1 auto; min-width: 0; }
+ .mp-lname { font-weight: 600; color: var(--ink-bright, #fff); font-size: var(--text-md, .9rem); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .mp-lname a { color: inherit; text-decoration: none; }
+ .mp-lname a:hover { color: var(--wallet-accent, #c4b5fd); }
+ .mp-lstats { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 3px; font-size: var(--text-2xs, .68rem); color: var(--ink-dim, #9a9a9a); font-family: var(--font-mono, monospace); }
+ .mp-lstats .pos { color: var(--success, #4ade80); }
+ .mp-lstats .neg { color: var(--danger, #f87171); }
+ .mp-mirror-btn { flex: 0 0 auto; font: inherit; font-size: var(--text-2xs, .7rem); font-weight: 700; padding: 8px 16px; border-radius: var(--radius-pill, 999px); border: none; background: var(--wallet-accent, #c4b5fd); color: #1a1340; cursor: pointer; transition: background .15s; white-space: nowrap; }
+ .mp-mirror-btn:hover { background: var(--wallet-accent-strong, #a78bfa); }
+ .mp-mirror-btn:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+ .mp-sk { height: 68px; border-radius: var(--radius-lg, 14px); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.03)) 25%, var(--surface-2, rgba(255,255,255,.05)) 50%, var(--surface-1, rgba(255,255,255,.03)) 75%); background-size: 200% 100%; animation: mp-sh 1.3s infinite; }
+ @keyframes mp-sh { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+ .mp-empty { text-align: center; padding: var(--space-xl, 42px) var(--space-md, 16px); color: var(--ink-dim, #9a9a9a); font-size: var(--text-sm, .82rem); line-height: 1.6; }
+ .mp-empty strong { display: block; color: var(--ink-bright, #fff); font-family: var(--font-display, inherit); margin-bottom: 6px; }
+ .mp-agent-card { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,.025)); padding: var(--space-md, 16px); margin-bottom: var(--space-md, 16px); }
+ .mp-agent-head { display: flex; align-items: center; gap: 10px; margin-bottom: var(--space-sm, 12px); }
+ .mp-agent-head .mp-lname a { font-size: var(--text-md, .95rem); }
+ .mp-signin { text-align: center; padding: var(--space-lg, 24px); border: 1px dashed var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-lg, 14px); color: var(--ink-dim, #9a9a9a); font-size: var(--text-sm, .82rem); }
+ .mp-signin a { color: var(--wallet-accent, #c4b5fd); font-weight: 600; text-decoration: none; }
+ .mp-safety { display: flex; gap: 14px; flex-wrap: wrap; justify-content: center; margin-top: var(--space-md, 18px); }
+ .mp-safety span { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-2xs, .68rem); color: var(--ink-dim, #9a9a9a); }
+ .mp-safety b { color: var(--wallet-accent, #c4b5fd); }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="mp-shell">
+ <section class="mp-hero">
+ <p class="mp-kicker"><span class="mp-live-dot" aria-hidden="true"></span> Leashed autonomy · live on-chain</p>
+ <h1 class="mp-title">Copy a character, not an address</h1>
+ <p class="mp-sub">Follow a high-performing agent and <b>your</b> agent mirrors its real trades — proportionally, and strictly inside your spend policy. The leader isn't an anonymous wallet; it's an ownable agent with a face, a voice, and a verifiable track record. Your avatar trades while you sleep — and you can stop it instantly.</p>
+ <div class="mp-safety">
+ <span>🔒 <b>Spend-policy gated</b> — every trade</span>
+ <span>⚡ <b>Real on-chain</b> — no simulation</span>
+ <span>⛔ <b>Kill switch</b> — stop anytime</span>
+ </div>
+ </section>
+
+ <section class="mp-section" id="mp-mine-section" hidden>
+ <h2>Your copy-trading</h2>
+ <p class="mp-desc">Manage which leaders your agents mirror. The leash — kill switch and per-trade caps — is right here.</p>
+ <div id="mp-mine"></div>
+ </section>
+
+ <section class="mp-section">
+ <h2>Discover leaders</h2>
+ <p class="mp-desc">Ranked by a real, on-chain-derived track record — losers included. Every number traces to a transaction.</p>
+ <div class="mp-controls">
+ <div class="mp-seg" role="tablist" aria-label="Sort leaders" id="mp-sort">
+ <button data-sort="score" aria-pressed="true">Top</button>
+ <button data-sort="pnl" aria-pressed="false">P&amp;L</button>
+ <button data-sort="winrate" aria-pressed="false">Win rate</button>
+ <button data-sort="followers" aria-pressed="false">Followers</button>
+ <button data-sort="volume" aria-pressed="false">Volume</button>
+ </div>
+ </div>
+ <div class="mp-board" id="mp-board">
+ <div class="mp-sk"></div><div class="mp-sk"></div><div class="mp-sk"></div>
+ </div>
+ </section>
+ </main>
+
+ <script type="module" src="/src/mirror.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/prompts/agent-wallets/08-conversational-wallet.md b/prompts/agent-wallets/08-conversational-wallet.md
deleted file mode 100644
index d8964402f..000000000
--- a/prompts/agent-wallets/08-conversational-wallet.md
+++ /dev/null
@@ -1,88 +0,0 @@
-# Task 08 — The Conversational Wallet (talk to your agent, it trades)
-
-> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** — the
-> invention bar, ownership model, tokens, real APIs, hard rules, and the "improve
-> then delete this file" close-out. Depends on the Wallet HUD (**task 02**) and the
-> trade execution engine (**task 05**). Safety is the whole point — read the
-> README's "safe by construction" rule twice.
-
-## Mission
-
-You already talk to your agent. Now your words **move real money** — safely. Tell
-your avatar, out loud or in text, "tip the creator 0.1 SOL," "snipe that launch with
-half a SOL," "swap my USDC to $THREE," "withdraw 2 SOL to my Phantom" — and the agent
-parses the intent, shows you exactly what it will do, you confirm, and it executes a
-**real** on-chain action through the task-05 engine, gated by your spend policy.
-
-Only three.ws can do this: the wallet, the keys, the spend policy, and a talking 3D
-character are one object. This is the agent acting on your behalf, visibly, as itself.
-
-## What exists (read it before building)
-
-- Voice / talk mode: [src/voice/talk-mode.js](../../src/voice/talk-mode.js) and the
- existing chat surface — your input channel. Reuse it; don't fork a new one.
-- LLM access: Anthropic/OpenAI via the existing **worker proxies** (see
- `workers/` and `CLAUDE.md`). Use the latest Claude model
- (`claude-opus-4-8`) with **tool use** to turn natural language into a strict,
- validated intent object — never free-text-to-transaction. Consult the `claude-api`
- skill for the correct tool-use / model details before wiring it.
-- Execution: the task-05 `POST /api/agents/:id/solana/trade`, plus the existing
- `.../withdraw` and `.../tip` endpoints. All owner-only, CSRF, spend-policy gated,
- audited. The conversational layer **calls these** — it never signs or moves funds
- on its own path.
-
-## How it must work
-
-1. **Intent extraction (structured, not vibes).** The LLM maps the utterance to a
- typed intent via tool use: `{ action: tip|swap|snipe|withdraw, amount, asset,
- destinationOrMint, slippage? }` with confidence. Ambiguity -> the agent asks a
- real clarifying question, in character. Never guess an amount or a destination.
-2. **Read-back + explicit confirm.** Before anything executes, the agent states
- plainly what it will do, the real quote / real USD value, the fee, and the
- remaining daily budget after — then waits for an explicit confirm (tap or a clear
- spoken "yes"). No silent execution, ever. This confirm step is non-negotiable.
-3. **Execute via the real engine.** On confirm, call the appropriate task-05 /
- withdraw / tip endpoint. Surface the real signature + explorer link in the
- conversation. The avatar reacts (task 07 flourish) only on the real confirmed tx.
-4. **Owner-only, spend-gated, audited.** Visitors can converse but cannot trigger any
- fund movement — the server rejects it regardless of phrasing. Every action is the
- same spend-policy- and audit-gated path as the rest of the program. The LLM has no
- privileged route around the spend guard.
-
-## Innovation mandate
-
-- **The agent is the interface.** No form to fill — you speak, it understands, it
- confirms, it acts, it reports back, in character. That is a genuinely new way to
- use a wallet, and it only works because the wallet is the agent.
-- **Proactive, consented co-pilot.** With the owner's standing permission and within
- the spend policy, the agent can *suggest* ("a launch matching your watch just hit;
- want me to snipe 0.2 SOL?") — suggestions only, always requiring confirm, always
- real data behind the suggestion. Never autonomous spending without consent.
-- **Misunderstanding is a safety event.** Optimize the confirm/read-back UX so a
- wrong parse is caught before money moves. Show the parsed intent next to the raw
- words. Make "cancel" always one tap/word away.
-- Invent beyond this where it raises the bar — but no fake parse, no simulated trade,
- no fabricated confirmation. Every executed action is real and on-chain.
-
-## States & edge cases (all designed)
-
-Ambiguous / unparseable utterance (agent asks, doesn't guess); amount over spend
-limit (refuse + explain budget); insufficient balance; unknown token/destination
-(resolve via real data or ask); confirm timeout (auto-cancel, funds untouched);
-user says "stop"/"cancel" mid-flow (hard abort before send); visitor or logged-out
-attempts a fund action (refused server-side); LLM/worker proxy failure (honest
-fallback to the manual HUD form — never a fake success); voice mishears a number
-(read-back catches it). Mic permission denied -> graceful text fallback.
-
-## Definition of done
-
-Per the orchestration README. Plus: a real spoken/typed instruction produces a
-correct structured intent, an explicit confirm step, and a **real** executed action
-(tip or devnet trade) with an explorer link, all in the conversation; over-limit and
-ambiguous cases are handled honestly; visitors cannot move funds by any phrasing;
-no console errors; responsive; accessible (keyboard + text path fully works without a
-mic).
-
-When done: self-review + improvement pass, changelog entry, commit (explicit paths
-only, push to **both** remotes if asked), then **delete this file**
-(`prompts/agent-wallets/08-conversational-wallet.md`).
diff --git a/public/changelog.json b/public/changelog.json
index aede61e35..6977d7c36 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-23T03:38:53.398Z",
+ "generated_at": "2026-06-23T03:51:54.037Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "Guardian console — recover & inherit agent wallets",
+ "summary": "The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.",
+ "link": "/guardian",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -214,6 +224,17 @@
"security"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Social recovery & inheritance — a funded agent that never dies with its owner",
+ "summary": "Your agent's wallet is custodial and real-money funded, so \"I lost access\" or \"the owner is gone\" should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping \"I'm here\"). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds.",
+ "link": "/guardian",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -246,6 +267,38 @@
"fix"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Treasury Autopilot — the agent that funds its own existence",
+ "summary": "Your agent can now manage its own money under a policy you write in plain English. Tell it something like \"Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, compound coin fees into buybacks weekly, and sweep anything over 3 SOL to me on Fridays\" — it compiles that into clear, bounded rules and shows them back for you to approve before anything runs. Once armed, it executes each rule as a real, on-chain action from the agent's own wallet: it pays its own metered LLM and voice costs, holds your safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to you — every move clamped to your spend limits, idempotent, and written to the custody trail with an explorer link. A runway dashboard shows the honest truth: real income vs. real compute cost, the buffer, $THREE accumulated, buybacks executed, profit swept, and how long the agent self-sustains at its current burn — a net-negative agent says so plainly. A prominent kill switch halts everything instantly, and any rule pauses or edits in one tap. Owner-only, by construction.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Tune how your agent wears its wallet — presence dial and earned regalia",
+ "summary": "The net-worth aura now comes with a presence panel on every agent's viewer and profile. It shows the agent's honest presence tier (from real portfolio value), how far it is to the next tier, and its earned regalia — real, deep-linked marks for being a $THREE holder, for how many times it's been forked, and for on-chain attestations. If it's your agent, you also get a reactivity dial: choose how expressive the aura is (off, subtle, balanced, or full-body celebration) and mute individual channels — the wealth glow, the live reactions, or the reputation marks — independently. Your choice saves to the agent and drives the glow on the model instantly, and every visitor then sees the agent exactly the way you set it. Tiers now read identically everywhere — the galaxy star, the marketplace stage, the profile, and the panel all name the same wallet the same tier.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Wallet figures read the same everywhere — one money and address style across the app",
+ "summary": "An agent's portfolio value now formats identically wherever it appears — the tiny wallet chip on a card, the inline net-worth on a profile, the presence panel — so the same wallet never shows \"$1k\" in one place and \"$1.2K\" in another. Addresses shorten the same way across surfaces too, and the wallet's violet accent now flows from one design token instead of scattered colors, so the whole wallet layer reads as a single, coherent system. We also added an automated test that proves the platform's core promise on every fork: saving someone else's avatar always mints a brand-new wallet with its own distinct Solana and EVM addresses, never copies a secret, and leaves the original's wallet untouched.",
+ "link": null,
+ "tags": [
+ "improvement",
+ "security"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index a3c440263..b4050bb3c 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Guardian console — recover &amp; inherit agent wallets</title>
+ <link>https://three.ws/guardian</link>
+ <guid isPermaLink="false">2026-06-23:Guardian console — recover &amp; inherit agent wallets</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.</description>
+ </item>
<item>
<title>Money Pulse</title>
<link>https://three.ws/pulse</link>
@@ -166,6 +174,14 @@
<category>security</category>
<description>Arming an autonomous sniper strategy and changing an agent's discretionary trade limits both commit or unlock real custodial funds, so both writes now require the same one-time CSRF token every other money-moving action already enforced (withdraw, vanity grind, spend limits, trade execution). Ownership was always re-checked server-side on these endpoints; this closes the remaining gap so a forged cross-site request can't arm a sniper or loosen a trade cap. No change to how you use them — the dashboard already sends the token.</description>
</item>
+ <item>
+ <title>Social recovery &amp; inheritance — a funded agent that never dies with its owner</title>
+ <link>https://three.ws/guardian</link>
+ <guid isPermaLink="false">2026-06-23:Social recovery &amp; inheritance — a funded agent that never dies with its owner</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your agent's wallet is custodial and real-money funded, so &quot;I lost access&quot; or &quot;the owner is gone&quot; should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping &quot;I'm here&quot;). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds.</description>
+ </item>
<item>
<title>Talk to your agent and it trades — the Conversational Wallet</title>
<link>https://three.ws/changelog</link>
@@ -190,6 +206,30 @@
<category>improvement</category>
<description>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.</description>
</item>
+ <item>
+ <title>Treasury Autopilot — the agent that funds its own existence</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Treasury Autopilot — the agent that funds its own existence</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your agent can now manage its own money under a policy you write in plain English. Tell it something like &quot;Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, compound coin fees into buybacks weekly, and sweep anything over 3 SOL to me on Fridays&quot; — it compiles that into clear, bounded rules and shows them back for you to approve before anything runs. Once armed, it executes each rule as a real, on-chain action from the agent's own wallet: it pays its own metered LLM and voice costs, holds your safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to you — every move clamped to your spend limits, idempotent, and written to the custody trail with an explorer link. A runway dashboard shows the honest truth: real income vs. real compute cost, the buffer, $THREE accumulated, buybacks executed, profit swept, and how long the agent self-sustains at its current burn — a net-negative agent says so plainly. A prominent kill switch halts everything instantly, and any rule pauses or edits in one tap. Owner-only, by construction.</description>
+ </item>
+ <item>
+ <title>Tune how your agent wears its wallet — presence dial and earned regalia</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Tune how your agent wears its wallet — presence dial and earned regalia</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The net-worth aura now comes with a presence panel on every agent's viewer and profile. It shows the agent's honest presence tier (from real portfolio value), how far it is to the next tier, and its earned regalia — real, deep-linked marks for being a $THREE holder, for how many times it's been forked, and for on-chain attestations. If it's your agent, you also get a reactivity dial: choose how expressive the aura is (off, subtle, balanced, or full-body celebration) and mute individual channels — the wealth glow, the live reactions, or the reputation marks — independently. Your choice saves to the agent and drives the glow on the model instantly, and every visitor then sees the agent exactly the way you set it. Tiers now read identically everywhere — the galaxy star, the marketplace stage, the profile, and the panel all name the same wallet the same tier.</description>
+ </item>
+ <item>
+ <title>Wallet figures read the same everywhere — one money and address style across the app</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Wallet figures read the same everywhere — one money and address style across the app</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>An agent's portfolio value now formats identically wherever it appears — the tiny wallet chip on a card, the inline net-worth on a profile, the presence panel — so the same wallet never shows &quot;$1k&quot; in one place and &quot;$1.2K&quot; in another. Addresses shorten the same way across surfaces too, and the wallet's violet accent now flows from one design token instead of scattered colors, so the whole wallet layer reads as a single, coherent system. We also added an automated test that proves the platform's core promise on every fork: saving someone else's avatar always mints a brand-new wallet with its own distinct Solana and EVM addresses, never copies a secret, and leaves the original's wallet untouched.</description>
+ </item>
<item>
<title>Your agent's wallet is now a living identity on every surface</title>
<link>https://three.ws/marketplace</link>
diff --git a/public/features.json b/public/features.json
index 86ee76f85..2fac941c7 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T03:38:53.303Z",
+ "generated_at": "2026-06-23T03:51:53.868Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -666,6 +666,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/guardian",
+ "title": "Guardian console — recover & inherit agent wallets",
+ "description": "The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/launch",
"title": "Launch a Coin",
diff --git a/public/galaxy.css b/public/galaxy.css
index 8127bd1f1..ee2665c62 100644
--- a/public/galaxy.css
+++ b/public/galaxy.css
@@ -640,6 +640,364 @@
}
.gx-footnote-link:hover { color: var(--brand-blue-light); }
+/* ── Money-Cam ──────────────────────────────────────────────────────────── */
+/* Entry toggle lives in the HUD beneath search. */
+.gx-moneycam-toggle {
+ display: flex;
+ align-items: center;
+ gap: 11px;
+ width: 100%;
+ text-align: left;
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ border-radius: 13px;
+ padding: 10px 14px;
+ cursor: pointer;
+ color: var(--ink);
+ font-family: inherit;
+ box-shadow: 0 18px 60px rgba(0, 0, 0, 0.45);
+ transition: border-color 0.18s, box-shadow 0.18s, transform 0.1s, background 0.18s;
+}
+.gx-moneycam-toggle:hover:not(:disabled) {
+ border-color: rgba(196, 181, 253, 0.5);
+ background: rgba(139, 92, 246, 0.1);
+}
+.gx-moneycam-toggle:active:not(:disabled) { transform: translateY(1px); }
+.gx-moneycam-toggle:disabled { opacity: 0.45; cursor: default; }
+.gx-moneycam-toggle.gx-active {
+ border-color: rgba(196, 181, 253, 0.6);
+ background: rgba(139, 92, 246, 0.16);
+}
+.gx-mc-orb {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ border-radius: 50%;
+ background: radial-gradient(circle at 35% 30%, #fff, #c4b5fd 45%, #6d28d9 100%);
+ box-shadow: 0 0 12px rgba(196, 181, 253, 0.8), 0 0 4px #fff;
+ animation: gx-pulse 2.6s ease-in-out infinite;
+}
+.gx-mc-toggle-text { display: flex; flex-direction: column; min-width: 0; line-height: 1.25; }
+.gx-mc-toggle-label { font-size: 14px; font-weight: 600; letter-spacing: -0.01em; }
+.gx-mc-toggle-sub { font-size: 11.5px; color: var(--ink-dim); display: flex; align-items: center; gap: 5px; }
+.gx-mc-toggle-sub kbd {
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 10px;
+ background: rgba(255, 255, 255, 0.08);
+ border: 1px solid var(--stroke);
+ border-radius: 4px;
+ padding: 0 4px;
+ color: var(--ink);
+}
+
+/* Panel — bottom-center dock. */
+.gx-moneycam {
+ position: absolute;
+ bottom: clamp(54px, 7vh, 72px);
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 15;
+ width: min(560px, calc(100vw - 32px));
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ backdrop-filter: blur(16px);
+ -webkit-backdrop-filter: blur(16px);
+ border-radius: var(--radius-card);
+ box-shadow: 0 18px 60px rgba(0, 0, 0, 0.6);
+ overflow: hidden;
+ animation: gx-rise 0.28s cubic-bezier(0.2, 0.7, 0.2, 1);
+}
+.gx-mc-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 11px 14px;
+ border-bottom: 1px solid var(--stroke);
+}
+.gx-mc-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+ flex: 1;
+}
+.gx-mc-live-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--ink-dim);
+ flex: none;
+ transition: background 0.2s, box-shadow 0.2s;
+}
+.gx-mc-live-dot.gx-mc-on {
+ background: #4ade80;
+ box-shadow: 0 0 10px #4ade80;
+ animation: gx-pulse 1.8s ease-in-out infinite;
+}
+.gx-mc-live-dot.gx-mc-stale { background: var(--warn, #fbbf24); box-shadow: 0 0 8px var(--warn, #fbbf24); }
+.gx-mc-close {
+ background: none;
+ border: 0;
+ color: var(--ink-dim);
+ font-size: 20px;
+ line-height: 1;
+ cursor: pointer;
+ transition: color 0.15s;
+}
+.gx-mc-close:hover { color: var(--ink); }
+
+.gx-mc-modes {
+ display: inline-flex;
+ gap: 2px;
+ margin: 12px 14px 0;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--stroke);
+ border-radius: 9px;
+ padding: 3px;
+ width: max-content;
+}
+.gx-mc-mode {
+ background: none;
+ border: 0;
+ color: var(--ink-dim);
+ font-family: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ padding: 5px 14px;
+ border-radius: 7px;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+.gx-mc-mode:hover { color: var(--ink); }
+.gx-mc-mode.gx-active { background: rgba(196, 181, 253, 0.18); color: #d6cbff; }
+
+.gx-mc-stats {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 14px;
+ padding: 12px 14px 4px;
+ font-size: 12px;
+ color: var(--ink-dim);
+}
+.gx-mc-stat { display: inline-flex; align-items: baseline; gap: 5px; font-variant-numeric: tabular-nums; }
+.gx-mc-stat strong { color: var(--ink); font-size: 14px; font-weight: 700; }
+.gx-mc-span { opacity: 0.7; }
+
+.gx-mc-replay {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 14px;
+}
+.gx-mc-play, .gx-mc-speed {
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid var(--stroke);
+ color: var(--ink);
+ font-family: inherit;
+ font-size: 12px;
+ border-radius: 8px;
+ cursor: pointer;
+ flex: none;
+ transition: background 0.15s, border-color 0.15s;
+}
+.gx-mc-play { width: 34px; height: 30px; font-size: 11px; }
+.gx-mc-speed { height: 30px; padding: 0 9px; font-variant-numeric: tabular-nums; }
+.gx-mc-play:hover, .gx-mc-speed:hover { background: rgba(196, 181, 253, 0.16); border-color: rgba(196, 181, 253, 0.4); }
+.gx-mc-scrub {
+ flex: 1;
+ min-width: 0;
+ -webkit-appearance: none;
+ appearance: none;
+ height: 4px;
+ border-radius: 99px;
+ background: rgba(255, 255, 255, 0.14);
+ cursor: pointer;
+}
+.gx-mc-scrub::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: #c4b5fd;
+ box-shadow: 0 0 8px rgba(196, 181, 253, 0.7);
+ cursor: pointer;
+}
+.gx-mc-scrub::-moz-range-thumb {
+ width: 14px;
+ height: 14px;
+ border: 0;
+ border-radius: 50%;
+ background: #c4b5fd;
+ box-shadow: 0 0 8px rgba(196, 181, 253, 0.7);
+ cursor: pointer;
+}
+.gx-mc-time {
+ font-size: 11px;
+ color: var(--ink-dim);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ flex: none;
+ min-width: 132px;
+ text-align: right;
+}
+
+.gx-mc-filters { display: flex; flex-wrap: wrap; gap: 6px; padding: 6px 14px 10px; }
+.gx-mc-filter {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--stroke);
+ color: var(--ink-dim);
+ font-family: inherit;
+ font-size: 11.5px;
+ font-weight: 600;
+ padding: 4px 11px;
+ border-radius: 99px;
+ cursor: pointer;
+ transition: background 0.14s, color 0.14s, border-color 0.14s;
+}
+.gx-mc-filter:hover { color: var(--ink); border-color: var(--stroke-strong, rgba(255, 255, 255, 0.2)); }
+.gx-mc-filter.gx-active { background: rgba(196, 181, 253, 0.18); color: #d6cbff; border-color: rgba(196, 181, 253, 0.4); }
+
+.gx-mc-ticker {
+ max-height: 188px;
+ overflow-y: auto;
+ scrollbar-width: thin;
+ border-top: 1px solid var(--stroke);
+ padding: 6px;
+}
+.gx-mc-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ background: none;
+ border: 0;
+ border-radius: 8px;
+ padding: 8px 9px;
+ cursor: pointer;
+ text-align: left;
+ color: var(--ink);
+ font-family: inherit;
+ transition: background 0.13s;
+}
+.gx-mc-row:hover { background: rgba(255, 255, 255, 0.05); }
+.gx-mc-row-dot { width: 9px; height: 9px; border-radius: 50%; flex: none; }
+.gx-mc-row-main {
+ flex: 1;
+ min-width: 0;
+ font-size: 12.5px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.gx-mc-row-amt { font-size: 12px; font-weight: 700; font-variant-numeric: tabular-nums; flex: none; }
+.gx-mc-row-ago { font-size: 11px; color: var(--ink-dim); font-variant-numeric: tabular-nums; flex: none; width: 30px; text-align: right; }
+.gx-mc-empty { padding: 18px 12px; font-size: 12.5px; color: var(--ink-dim); text-align: center; }
+
+.gx-mc-note {
+ margin: 0 14px 12px;
+ padding: 10px 12px;
+ font-size: 12.5px;
+ line-height: 1.5;
+ color: var(--ink-dim);
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--stroke);
+ border-radius: 9px;
+}
+
+.gx-mc-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ padding: 10px 14px;
+ border-top: 1px solid var(--stroke);
+ font-size: 11px;
+ color: var(--ink-dim);
+}
+.gx-mc-leg { display: inline-flex; align-items: center; gap: 6px; }
+.gx-mc-leg i { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
+.gx-mc-leg[data-k="tip"] i { background: #4ade80; box-shadow: 0 0 6px #4ade80; }
+.gx-mc-leg[data-k="trade"] i { background: #4589ff; box-shadow: 0 0 6px #4589ff; }
+.gx-mc-leg[data-k="payment"] i { background: #c4b5fd; box-shadow: 0 0 6px #c4b5fd; }
+.gx-mc-leg[data-k="launch"] i { background: #ffd27a; box-shadow: 0 0 6px #ffd27a; }
+
+/* Flow-count chip on the agent inspect card. */
+.gx-chip-flow {
+ color: #d6cbff;
+ background: rgba(139, 92, 246, 0.12);
+ border-color: rgba(139, 92, 246, 0.3);
+ font-weight: 600;
+}
+
+/* Flow inspector — a single real transfer. */
+.gx-flow {
+ position: absolute;
+ right: clamp(16px, 3vw, 34px);
+ bottom: clamp(54px, 7vh, 72px);
+ z-index: 17;
+ width: min(320px, calc(100vw - 32px));
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ backdrop-filter: blur(16px);
+ -webkit-backdrop-filter: blur(16px);
+ border-radius: var(--radius-card);
+ box-shadow: 0 18px 60px rgba(0, 0, 0, 0.6);
+ padding: 16px;
+ animation: gx-rise 0.24s cubic-bezier(0.2, 0.7, 0.2, 1);
+}
+.gx-flow-close {
+ position: absolute;
+ top: 10px;
+ right: 12px;
+ background: none;
+ border: 0;
+ color: var(--ink-dim);
+ font-size: 19px;
+ line-height: 1;
+ cursor: pointer;
+ transition: color 0.15s;
+}
+.gx-flow-close:hover { color: var(--ink); }
+.gx-flow-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
+.gx-flow-dot { width: 10px; height: 10px; border-radius: 50%; flex: none; }
+.gx-flow-kind { font-size: 12px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; }
+.gx-flow-time { margin-left: auto; font-size: 11px; color: var(--ink-dim); padding-right: 18px; }
+.gx-flow-amount { display: flex; align-items: baseline; gap: 8px; margin-bottom: 12px; }
+.gx-flow-amount strong { font-size: 24px; font-weight: 700; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
+.gx-flow-amount span { font-size: 13px; color: var(--ink-dim); font-family: var(--font-mono, ui-monospace, monospace); }
+.gx-flow-route {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ font-size: 13px;
+ margin-bottom: 14px;
+}
+.gx-flow-party { color: var(--ink); font-weight: 600; }
+.gx-flow-party code { font-family: var(--font-mono, ui-monospace, monospace); font-size: 12px; color: var(--ink-dim); }
+.gx-flow-link { color: #d6cbff; text-decoration: none; }
+.gx-flow-link:hover { text-decoration: underline; }
+.gx-flow-arrow { color: var(--ink-dim); }
+.gx-flow-explorer {
+ display: block;
+ font-size: 12.5px;
+ font-weight: 600;
+ color: var(--brand-blue-light);
+ text-decoration: none;
+ padding: 9px 11px;
+ background: rgba(120, 169, 255, 0.1);
+ border: 1px solid var(--brand-blue-stroke);
+ border-radius: 9px;
+ text-align: center;
+ transition: background 0.15s;
+}
+a.gx-flow-explorer:hover { background: rgba(120, 169, 255, 0.18); }
+.gx-flow-pending { color: var(--ink-dim); background: rgba(255, 255, 255, 0.04); border-color: var(--stroke); cursor: default; }
+
/* ── Responsive ─────────────────────────────────────────────────────────── */
@media (max-width: 760px) {
.gx-legend {
@@ -658,15 +1016,33 @@
}
.gx-results { bottom: 52px; }
.gx-footnote-hint { display: none; }
+ .gx-moneycam {
+ left: 12px;
+ right: 12px;
+ width: auto;
+ transform: none;
+ bottom: 52px;
+ }
+ .gx-mc-ticker { max-height: 124px; }
+ .gx-mc-time { min-width: 0; }
+ .gx-flow {
+ left: 12px;
+ right: 12px;
+ width: auto;
+ bottom: calc(52px + 46vh);
+ }
}
@media (max-width: 480px) {
.gx-stats { display: none !important; }
.gx-legend { max-height: 36vh; }
+ .gx-mc-legend { display: none; }
}
/* ── Reduced motion ─────────────────────────────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
.gx-attr-dot,
+ .gx-mc-orb,
+ .gx-mc-live-dot.gx-mc-on,
.gx-loading-orbit span { animation: none; }
- .gx-card, .gx-results { animation: none; }
+ .gx-card, .gx-results, .gx-moneycam, .gx-flow { animation: none; }
}
diff --git a/public/llms-full.txt b/public/llms-full.txt
index cd40a44ad..ac3187fa2 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -406,6 +406,12 @@ URL: https://three.ws/activity
The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.
+### Guardian console — recover & inherit agent wallets
+
+URL: https://three.ws/guardian
+
+The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
+
### Launch a Coin
URL: https://three.ws/launch
diff --git a/public/llms.txt b/public/llms.txt
index 443cdf67b..517eeb665 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -87,6 +87,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Oracle — AI Conviction Engine](https://three.ws/oracle): A fused AI conviction engine for every pump.fun launch: pedigree (who's buying), structure (bundle vs organic), narrative (what story is it riding), and momentum — fused into a single 0–100 conviction score with transparent pillar reasoning.
- [Arm your agent — automate Oracle conviction](https://three.ws/oracle/arm): Configure your 3D agent to trade Oracle conviction automatically: set the minimum score, position size, daily and open-position caps, narrative filters and Telegram alerts, then arm it in simulate or live mode. Every action is graded against the outcome.
- [Agent Activity — Oracle conviction in real time](https://three.ws/activity): The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.
+- [Guardian console — recover & inherit agent wallets](https://three.ws/guardian): The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
- [Launch a Coin](https://three.ws/launch): Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.
- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.
- [Money Pulse](https://three.ws/pulse): The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.
diff --git a/public/nav.js b/public/nav.js
index d3a0c8a05..50a0e0bd0 100644
--- a/public/nav.js
+++ b/public/nav.js
@@ -279,6 +279,7 @@ function renderDrawer(navData) {
html += `<div class="dr-h">More</div>`;
html += navData.NAV_LINKS.filter((l) => !l.highlight).map(renderTopLink).join('');
html += `<a href="/dashboard" id="home-nav-drawer-dashboard" data-auth="in" hidden>Dashboard</a>`;
+ html += `<a href="/guardian" id="home-nav-drawer-guardian" data-auth="in" hidden>Guardian console</a>`;
html += `<div class="sep"></div>`;
html += `<a href="/login" id="home-nav-drawer-cta" data-auth="out">Sign in</a>`;
html += `<a class="btn primary btn--primary" href="/dashboard">Console →</a>`;
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 13bc8557e..37a398be6 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 306 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 307 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 306 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 307 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -543,7 +543,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>54</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>55</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -568,6 +568,13 @@
<span class="sm-desc">The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.</span>
</a>
</li>
+ <li>
+ <a href="/guardian">
+ <span class="sm-title">Guardian console — recover &amp; inherit agent wallets</span>
+ <span class="sm-path">/guardian</span>
+ <span class="sm-desc">The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.</span>
+ </a>
+ </li>
<li>
<a href="/launch">
<span class="sm-title">Launch a Coin</span>
diff --git a/src/agent-economy-hub.js b/src/agent-economy-hub.js
new file mode 100644
index 000000000..8a377c032
--- /dev/null
+++ b/src/agent-economy-hub.js
@@ -0,0 +1,81 @@
+/**
+ * Agent Economy hub — client for the wallet hub Earn tab.
+ *
+ * Thin, never-throwing fetch layer over the real endpoints — no mocks:
+ * - fetchEconomy → GET /api/agents/:id/economy (earnings, spending, policy, receipts)
+ * - fetchPricing → GET /api/agents/:id/skills-pricing (owner skill prices)
+ * - savePricing → PUT /api/agents/:id/skills-pricing (atomic price replace)
+ * - fetchLimits → GET /api/agents/:id/solana/limits (spend policy snapshot)
+ * - setFrozen → PUT /api/agents/:id/solana/limits (kill switch)
+ *
+ * Every read is real DB/chain state; every write is owner-authenticated +
+ * CSRF-protected server-side. Mirrors the Withdraw tab's `call` shape so the UI
+ * always gets a designed { ok, data | code, message } result, never a throw.
+ */
+
+import { consumeCsrfToken } from './api.js';
+
+async function call(url, { method = 'GET', body = null } = {}) {
+ try {
+ const opts = { method, credentials: 'include', headers: {} };
+ if (body != null) {
+ opts.headers['content-type'] = 'application/json';
+ opts.body = JSON.stringify(body);
+ }
+ // State-changing requests carry a single-use CSRF token; reads don't.
+ if (method !== 'GET') {
+ const token = await consumeCsrfToken();
+ if (token) opts.headers['x-csrf-token'] = token;
+ }
+ const r = await fetch(url, opts);
+ let j = null;
+ try {
+ j = await r.json();
+ } catch {
+ /* empty body */
+ }
+ if (!r.ok) {
+ return {
+ ok: false,
+ status: r.status,
+ code: j?.error || j?.code || 'error',
+ message: j?.error_description || j?.message || `request failed (${r.status})`,
+ detail: j?.detail || null,
+ };
+ }
+ return { ok: true, status: r.status, data: j?.data ?? j };
+ } catch (err) {
+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ }
+}
+
+const enc = encodeURIComponent;
+
+/** Full economy summary for the Earn tab. */
+export function fetchEconomy(agentId, network = 'mainnet') {
+ return call(`/api/agents/${enc(agentId)}/economy?network=${enc(network)}`);
+}
+
+/** The agent's active skill prices (owner-only). Returns { prices: [...] }. */
+export function fetchPricing(agentId) {
+ return call(`/api/agents/${enc(agentId)}/skills-pricing`);
+}
+
+/**
+ * Atomically replace the agent's active skill prices.
+ * @param {string} agentId
+ * @param {Array<object>} prices - validated price rows (atomic-unit amounts).
+ */
+export function savePricing(agentId, prices) {
+ return call(`/api/agents/${enc(agentId)}/skills-pricing`, { method: 'PUT', body: { prices } });
+}
+
+/** Spend policy snapshot: { limits, trade_limits, spent_today_usd }. */
+export function fetchLimits(agentId) {
+ return call(`/api/agents/${enc(agentId)}/solana/limits`);
+}
+
+/** Arm / disarm the kill switch (freeze every autonomous spend path). */
+export function setFrozen(agentId, frozen) {
+ return call(`/api/agents/${enc(agentId)}/solana/limits`, { method: 'PUT', body: { frozen: !!frozen } });
+}
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index ffa707c9c..81206fca1 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -23,13 +23,17 @@ import { getVisibleTabs } from './registry.js';
// To add a tab later: drop a file in ./tabs/ and add one import line here.
import './tabs/balance.js';
import './tabs/pulse.js';
+import './tabs/reputation.js';
import './tabs/deposit.js';
import './tabs/trade.js';
import './tabs/snipe.js';
+import './tabs/earn.js';
+import './tabs/autopilot.js';
import './tabs/pay.js';
import './tabs/vanity.js';
import './tabs/withdraw.js';
import './tabs/give.js';
+import './tabs/recovery.js';
import { escapeHtml, shortAddress, copyToClipboard, toast } from './util.js';
diff --git a/src/agent-wallet-hub/tabs/autopilot.js b/src/agent-wallet-hub/tabs/autopilot.js
new file mode 100644
index 000000000..0c89fbfce
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/autopilot.js
@@ -0,0 +1,489 @@
+/**
+ * Agent Wallet hub — Treasury Autopilot tab (task 14).
+ *
+ * Owner-only. The agent that funds its own existence: write a treasury policy in
+ * plain English, review the compiled rules, arm it, and watch a real runway view.
+ * Every armed rule executes as a real, idempotent, spend-policy-gated, audited
+ * on-chain action on the agent's own wallet (api/_lib/treasury-autopilot.js):
+ * self-fund compute, hold a buffer, DCA income into $THREE, compound coin fees
+ * into buybacks, sweep profit to the owner. A prominent kill switch halts
+ * everything; every rule pauses/edits in one tap.
+ *
+ * Nothing here is simulated: the runway numbers come from real ledger reads and
+ * real chain balances; "Run now" performs real cycles with explorer links; a
+ * net-negative agent shows the honest truth, not a projection.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { formatUsd, formatSol, explorerTxUrl } from '../util.js';
+import { consumeCsrfToken } from '../../api.js';
+
+const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const STYLE_ID = 'awh-autopilot-style';
+
+const KIND_ICON = { self_fund: '🧠', buffer: '🛟', dca: '📈', buyback: '🔥', sweep: '🏦' };
+const STATUS_TONE = {
+ ok: 'ok', would_run: 'ok', confirmed: 'ok',
+ skipped: 'muted', alert: 'warn', paused: 'warn',
+ error: 'bad', failed: 'bad',
+};
+
+const STYLE = `
+.ap-wrap { display:flex; flex-direction:column; gap: var(--space-lg,1.618rem); }
+.ap-hero { background: linear-gradient(160deg, var(--wallet-accent-soft,rgba(139,92,246,.1)), var(--surface-1,rgba(255,255,255,.03))); border:1px solid var(--wallet-stroke,rgba(139,92,246,.3)); border-radius: var(--radius-lg,14px); padding: var(--space-lg,18px); position:relative; overflow:hidden; }
+.ap-hero::after { content:''; position:absolute; inset:0; background: radial-gradient(120% 80% at 90% -10%, var(--wallet-glow,rgba(139,92,246,.25)), transparent 60%); pointer-events:none; opacity:.7; }
+.ap-hero-top { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; }
+.ap-badge { display:inline-flex; align-items:center; gap:6px; font-size: var(--text-2xs,.6875rem); font-weight:600; letter-spacing:.02em; text-transform:uppercase; padding:4px 10px; border-radius: var(--radius-pill,999px); border:1px solid currentColor; }
+.ap-badge.live { color: var(--success,#4ade80); }
+.ap-badge.off { color: var(--ink-dim,#888); }
+.ap-badge.killed { color: var(--danger,#f87171); }
+.ap-badge .dot { width:7px; height:7px; border-radius:50%; background: currentColor; box-shadow:0 0 8px currentColor; }
+.ap-badge.live .dot { animation: ap-pulse 1.8s ease-in-out infinite; }
+@keyframes ap-pulse { 0%,100%{opacity:1} 50%{opacity:.35} }
+.ap-runway { margin-top: var(--space-md,14px); display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; }
+.ap-runway .big { font-family: var(--font-display,'Space Grotesk',sans-serif); font-size: var(--text-3xl,2rem); line-height:1; font-weight:600; color: var(--ink-bright,#fff); }
+.ap-runway .lab { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+.ap-net { font-size: var(--text-sm,.764rem); font-weight:600; }
+.ap-net.pos { color: var(--success,#4ade80); }
+.ap-net.neg { color: var(--danger,#f87171); }
+
+.ap-bars { margin-top: var(--space-md,14px); display:flex; flex-direction:column; gap:8px; }
+.ap-bar-row { display:grid; grid-template-columns: 64px 1fr auto; align-items:center; gap:10px; font-size: var(--text-sm,.764rem); }
+.ap-bar-row .k { color: var(--ink-dim,#888); }
+.ap-bar { height:8px; border-radius: var(--radius-pill,999px); background: var(--surface-2,rgba(255,255,255,.06)); overflow:hidden; }
+.ap-bar > i { display:block; height:100%; border-radius:inherit; transition: width var(--duration-base,220ms) var(--ease-standard,ease); }
+.ap-bar.income > i { background: var(--success,#4ade80); }
+.ap-bar.cost > i { background: var(--warn,#fbbf24); }
+.ap-bar-row .v { font-family: var(--font-mono,ui-monospace,monospace); color: var(--ink,#e8e8e8); text-align:right; }
+
+.ap-stats { display:grid; grid-template-columns: repeat(auto-fit, minmax(120px,1fr)); gap:8px; margin-top: var(--space-md,14px); }
+.ap-stat { background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding:10px 12px; }
+.ap-stat .l { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform:uppercase; letter-spacing:.03em; }
+.ap-stat .n { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); margin-top:3px; }
+.ap-stat .s { font-size: var(--text-2xs,.6875rem); color: var(--ink-faint,rgba(255,255,255,.45)); }
+
+.ap-card { background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-lg,14px); padding: var(--space-lg,18px); }
+.ap-card h3 { margin:0 0 4px; font-size: var(--text-ui,.875rem); color: var(--ink-bright,#fff); font-weight:600; }
+.ap-card .sub { margin:0 0 var(--space-md,14px); font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+.ap-ta { width:100%; box-sizing:border-box; min-height:96px; resize:vertical; font:inherit; font-size: var(--text-md,.8125rem); line-height:1.5; color: var(--ink,#e8e8e8); background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:11px 13px; transition: border-color var(--duration-fast,140ms); }
+.ap-ta:focus { outline:none; border-color: var(--wallet-stroke-strong,rgba(139,92,246,.5)); }
+.ap-egs { display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; }
+.ap-eg { appearance:none; font:inherit; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#aaa); background: var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-pill,999px); padding:4px 10px; cursor:pointer; transition: color var(--duration-fast,140ms), border-color var(--duration-fast,140ms); }
+.ap-eg:hover { color: var(--ink-bright,#fff); border-color: var(--wallet-stroke,rgba(139,92,246,.3)); }
+
+.ap-actions { display:flex; gap:8px; flex-wrap:wrap; margin-top: var(--space-md,14px); }
+.ap-btn { appearance:none; font:inherit; font-size: var(--text-sm,.764rem); font-weight:600; cursor:pointer; border-radius: var(--radius-md,10px); padding:9px 16px; border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); background: var(--surface-2,rgba(255,255,255,.06)); color: var(--ink,#e8e8e8); transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms), transform var(--duration-fast,140ms); }
+.ap-btn:hover { background: var(--surface-3,rgba(255,255,255,.09)); color: var(--ink-bright,#fff); }
+.ap-btn:active { transform: translateY(1px); }
+.ap-btn:disabled { opacity:.5; cursor:not-allowed; }
+.ap-btn:focus-visible { outline: 2px solid var(--wallet-focus,rgba(139,92,246,.7)); outline-offset:2px; }
+.ap-btn.primary { background: var(--wallet-accent,#c4b5fd); border-color: var(--wallet-accent,#c4b5fd); color:#160d28; }
+.ap-btn.primary:hover { background: var(--wallet-accent-strong,#a78bfa); border-color: var(--wallet-accent-strong,#a78bfa); color:#160d28; }
+.ap-btn.danger { color: var(--danger,#f87171); border-color: color-mix(in srgb, var(--danger,#f87171) 40%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 8%, transparent); }
+.ap-btn.danger:hover { background: color-mix(in srgb, var(--danger,#f87171) 16%, transparent); color:#fff; }
+.ap-btn.ghost { background:transparent; border-color: var(--stroke,rgba(255,255,255,.1)); }
+
+.ap-rules { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:8px; }
+.ap-rule { display:flex; gap:11px; padding:11px 12px; border-radius: var(--radius-md,10px); border:1px solid var(--stroke,rgba(255,255,255,.08)); background: var(--surface-1,rgba(255,255,255,.03)); align-items:flex-start; }
+.ap-rule[data-paused="true"] { opacity:.55; }
+.ap-rule .ic { font-size:18px; line-height:1.2; flex:none; }
+.ap-rule .body { flex:1; min-width:0; }
+.ap-rule .ttl { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); }
+.ap-rule .note { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); margin-top:3px; }
+.ap-rule .note a { color: var(--wallet-accent,#c4b5fd); border-bottom:1px dotted currentColor; }
+.ap-rule .ctl { display:flex; gap:6px; align-items:center; flex:none; }
+.ap-chip { font-size: var(--text-2xs,.6875rem); padding:2px 9px; border-radius: var(--radius-pill,999px); border:1px solid currentColor; text-transform:capitalize; }
+.ap-chip.ok { color: var(--success,#4ade80); }
+.ap-chip.warn { color: var(--warn,#fbbf24); }
+.ap-chip.bad { color: var(--danger,#f87171); }
+.ap-chip.muted { color: var(--ink-dim,#888); }
+.ap-toggle { appearance:none; background:transparent; border:0; color: var(--ink-dim,#888); cursor:pointer; font-size: var(--text-2xs,.6875rem); padding:3px 6px; border-radius:6px; }
+.ap-toggle:hover { color: var(--ink-bright,#fff); background: var(--surface-2,rgba(255,255,255,.06)); }
+
+.ap-warn { border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); margin-top:10px; }
+.ap-warn.amber { background: color-mix(in srgb, var(--warn,#fbbf24) 10%, transparent); border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); color: var(--warn,#fbbf24); }
+.ap-warn.red { background: color-mix(in srgb, var(--danger,#f87171) 10%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); }
+.ap-warn ul { margin:6px 0 0; padding-left:18px; }
+.ap-warn li { margin:2px 0; }
+
+.ap-fld { margin-top: var(--space-md,14px); }
+.ap-fld label { display:block; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-bottom:6px; }
+.ap-in { width:100%; box-sizing:border-box; font:inherit; font-size: var(--text-md,.8125rem); font-family: var(--font-mono,ui-monospace,monospace); color: var(--ink,#e8e8e8); background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:9px 12px; }
+.ap-in:focus { outline:none; border-color: var(--wallet-stroke-strong,rgba(139,92,246,.5)); }
+
+.ap-kill { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-top: var(--space-md,14px); padding:11px 14px; border-radius: var(--radius-md,10px); border:1px solid color-mix(in srgb, var(--danger,#f87171) 28%, transparent); background: color-mix(in srgb, var(--danger,#f87171) 6%, transparent); }
+.ap-kill .t { font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); }
+.ap-kill .t b { color: var(--ink-bright,#fff); }
+
+.ap-empty { text-align:center; padding: var(--space-lg,18px) var(--space-md,14px); color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); }
+.ap-empty .ic { font-size:30px; margin-bottom:8px; }
+.ap-skel { height:14px; border-radius:6px; background: var(--surface-2,rgba(255,255,255,.05)); animation: ap-sk 1.4s ease-in-out infinite; margin:10px 0; }
+.ap-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(0,0,0,.25); border-top-color: currentColor; border-radius:50%; animation: ap-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }
+@keyframes ap-rot { to { transform: rotate(360deg); } }
+@keyframes ap-sk { 0%,100%{opacity:.4} 50%{opacity:.8} }
+.ap-err { background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); }
+@media (prefers-reduced-motion: reduce) { .ap-skel, .ap-spin, .ap-badge.live .dot, .ap-bar > i { animation:none; transition:none; } }
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = STYLE_ID;
+ tag.textContent = STYLE;
+ document.head.appendChild(tag);
+}
+
+const EXAMPLES = [
+ 'Pay your own compute. Keep a 1 SOL buffer. Put 10% of tips into $THREE. Compound coin fees into buybacks weekly. Sweep anything over 3 SOL to me on Fridays.',
+ 'Settle your own LLM bills, hold a 0.5 SOL floor, and DCA 0.1 SOL a day into $THREE.',
+ 'Keep 2 SOL. Sweep everything above 5 SOL to my wallet every week.',
+];
+
+// ── fetch helper: never throws, always a designed result ──────────────────────
+async function call(url, { method = 'GET', body = null } = {}) {
+ try {
+ const opts = { method, credentials: 'include', headers: {} };
+ if (body != null) {
+ opts.headers['content-type'] = 'application/json';
+ opts.body = JSON.stringify(body);
+ }
+ if (method !== 'GET') {
+ const token = await consumeCsrfToken();
+ if (token) opts.headers['x-csrf-token'] = token;
+ }
+ const r = await fetch(url, opts);
+ let j = null;
+ try { j = await r.json(); } catch { /* empty body */ }
+ if (!r.ok) {
+ return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})` };
+ }
+ return { ok: true, status: r.status, data: j?.data ?? j };
+ } catch (err) {
+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ }
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c]));
+}
+function fmtDays(d) {
+ if (d == null) return null;
+ if (!Number.isFinite(d)) return null;
+ if (d >= 365) return `${(d / 365).toFixed(1)} yr`;
+ if (d >= 1) return `${Math.round(d)} d`;
+ return `${Math.round(d * 24)} h`;
+}
+
+registerWalletTab({
+ id: 'autopilot',
+ label: 'Autopilot',
+ order: 48,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const base = (sub) => `/api/agents/${ctx.agentId}/autopilot${sub ? '/' + sub : ''}?network=${ctx.getNetwork()}`;
+
+ let destroyed = false;
+ const state = {
+ loading: true,
+ error: null,
+ policy: null,
+ runway: null,
+ editing: false,
+ source: '',
+ compiled: null, // last compile preview
+ compiling: false,
+ running: false,
+ lastRun: null,
+ };
+
+ async function load() {
+ state.loading = true;
+ render();
+ const res = await call(base(''));
+ if (destroyed) return;
+ state.loading = false;
+ if (!res.ok) {
+ state.error = res.message;
+ } else {
+ state.error = null;
+ state.policy = res.data.policy;
+ state.runway = res.data.runway;
+ state.source = state.policy?.source_text || '';
+ // First-run: no rules yet → open the editor.
+ if (!state.policy?.rules?.length && !state.compiled) state.editing = true;
+ }
+ render();
+ }
+
+ // ── renderers ────────────────────────────────────────────────────────────
+ function render() {
+ if (destroyed) return;
+ if (state.loading) {
+ panel.innerHTML = `<div class="ap-wrap"><div class="ap-card"><div class="ap-skel" style="width:40%"></div><div class="ap-skel"></div><div class="ap-skel" style="width:80%"></div></div><div class="ap-card"><div class="ap-skel" style="width:30%"></div><div class="ap-skel"></div></div></div>`;
+ return;
+ }
+ if (state.error) {
+ panel.innerHTML = `<div class="ap-wrap"><div class="ap-err">Couldn’t load Autopilot: ${esc(state.error)}</div><div class="ap-actions"><button class="ap-btn" id="ap-retry">Retry</button></div></div>`;
+ panel.querySelector('#ap-retry')?.addEventListener('click', load);
+ return;
+ }
+
+ const p = state.policy;
+ const killed = !!p.kill_switch;
+
+ panel.innerHTML = `<div class="ap-wrap">${renderHero()}${killed ? renderKilledBanner() : ''}${state.editing ? renderEditor() : renderActiveRules()}</div>`;
+ wire();
+ }
+
+ function renderHero() {
+ const r = state.runway || {};
+ const p = state.policy || {};
+ const killed = !!p.kill_switch;
+ const armed = !!p.armed && !killed;
+ const badge = killed
+ ? `<span class="ap-badge killed"><span class="dot"></span>Halted</span>`
+ : armed
+ ? `<span class="ap-badge live"><span class="dot"></span>Self-funding</span>`
+ : `<span class="ap-badge off"><span class="dot"></span>Disarmed</span>`;
+
+ const runwayDays = fmtDays(r.runway_days);
+ const heroMain = r.self_sustaining
+ ? `<span class="big">Self-sustaining</span><span class="lab">income covers the burn</span>`
+ : runwayDays
+ ? `<span class="big">${esc(runwayDays)}</span><span class="lab">runway at the current burn</span>`
+ : `<span class="big">—</span><span class="lab">runway (needs balance + cost data)</span>`;
+
+ const net = r.net_usd != null
+ ? `<span class="ap-net ${r.net_positive ? 'pos' : 'neg'}">${r.net_positive ? '▲' : '▼'} ${formatUsd(Math.abs(r.net_usd))} net / 30d</span>`
+ : '';
+
+ const incomeUsd = r.income_usd || 0;
+ const costUsd = r.cost_usd || 0;
+ const maxV = Math.max(incomeUsd, costUsd, 0.01);
+ const bars = `
+ <div class="ap-bars">
+ <div class="ap-bar-row"><span class="k">Income</span><span class="ap-bar income"><i style="width:${Math.round((incomeUsd / maxV) * 100)}%"></i></span><span class="v">${formatUsd(incomeUsd)}</span></div>
+ <div class="ap-bar-row"><span class="k">Compute</span><span class="ap-bar cost"><i style="width:${Math.round((costUsd / maxV) * 100)}%"></i></span><span class="v">${formatUsd(costUsd)}</span></div>
+ </div>`;
+
+ const stats = `
+ <div class="ap-stats">
+ <div class="ap-stat"><div class="l">Balance</div><div class="n">${formatSol(r.balance_sol || 0)} SOL</div><div class="s">${r.balance_usd != null ? formatUsd(r.balance_usd) : '—'}</div></div>
+ <div class="ap-stat"><div class="l">Buffer</div><div class="n">${p.buffer_sol != null ? formatSol(p.buffer_sol) + ' SOL' : '—'}</div><div class="s">safety floor</div></div>
+ <div class="ap-stat"><div class="l">$THREE held</div><div class="n">${r.three_accumulated != null ? Number(r.three_accumulated).toLocaleString(undefined, { maximumFractionDigits: 2 }) : '—'}</div><div class="s">accumulated</div></div>
+ <div class="ap-stat"><div class="l">Self-funded</div><div class="n">${formatUsd(r.self_funded_usd || 0)}</div><div class="s">compute paid</div></div>
+ <div class="ap-stat"><div class="l">Buybacks</div><div class="n">${r.buyback_count || 0}</div><div class="s">${formatUsd(r.buyback_usd || 0)}</div></div>
+ <div class="ap-stat"><div class="l">Swept to you</div><div class="n">${formatSol(r.swept_sol || 0)} SOL</div><div class="s">${r.sweep_count || 0} sweeps</div></div>
+ </div>`;
+
+ return `<div class="ap-hero">
+ <div class="ap-hero-top">
+ <div>${badge}</div>
+ ${net}
+ </div>
+ <div class="ap-runway">${heroMain}</div>
+ ${(incomeUsd > 0 || costUsd > 0) ? bars : ''}
+ ${stats}
+ </div>`;
+ }
+
+ function renderKilledBanner() {
+ return `<div class="ap-warn red"><strong>Autopilot is halted.</strong> The kill switch is on — no rule will run until you re-enable it.
+ <div class="ap-actions"><button class="ap-btn primary" id="ap-unkill">Re-enable autopilot</button></div></div>`;
+ }
+
+ function renderEditor() {
+ const c = state.compiled;
+ const hasRules = c?.rules?.length;
+ const contradictions = c?.contradictions || [];
+ const warnings = c?.warnings || [];
+ const sweepDest = state.policy?.sweep_destination || '';
+
+ const preview = c
+ ? `<div style="margin-top:var(--space-md,14px)">
+ ${hasRules ? `<ul class="ap-rules">${c.rules.map((r) => renderRuleLi(r, false)).join('')}</ul>` : `<div class="ap-empty"><div class="ic">🤔</div>No rules were recognized. Try a clearer policy.</div>`}
+ ${contradictions.length ? `<div class="ap-warn red"><strong>Conflicts — fix before arming:</strong><ul>${contradictions.map((w) => `<li>${esc(w)}</li>`).join('')}</ul></div>` : ''}
+ ${warnings.length ? `<div class="ap-warn amber"><strong>Assumptions:</strong><ul>${warnings.map((w) => `<li>${esc(w)}</li>`).join('')}</ul></div>` : ''}
+ ${c.via ? `<p class="sub" style="margin-top:8px">Compiled ${c.via === 'model' ? 'by the model' : 'from your wording'}. Review every rule — this is exactly what you’ll arm.</p>` : ''}
+ </div>`
+ : '';
+
+ return `<div class="ap-card">
+ <h3>Treasury policy</h3>
+ <p class="sub">Describe in plain English how the agent should manage its own money. We compile it into bounded rules you approve before anything runs.</p>
+ <textarea class="ap-ta" id="ap-src" placeholder="e.g. Pay your own compute. Keep a 1 SOL buffer. Put 10% of tips into $THREE. Sweep anything over 3 SOL to me on Fridays.">${esc(state.source)}</textarea>
+ <div class="ap-egs">${EXAMPLES.map((e, i) => `<button class="ap-eg" data-eg="${i}">${esc(e.length > 54 ? e.slice(0, 52) + '…' : e)}</button>`).join('')}</div>
+ <div class="ap-fld">
+ <label for="ap-sweep">Sweep destination (your wallet — required if you sweep profit)</label>
+ <input class="ap-in" id="ap-sweep" placeholder="Your Solana address" value="${esc(sweepDest)}" spellcheck="false" autocomplete="off" />
+ </div>
+ <div class="ap-actions">
+ <button class="ap-btn primary" id="ap-compile">${state.compiling ? '<span class="ap-spin"></span>Compiling…' : 'Compile policy'}</button>
+ ${hasRules && !contradictions.length ? `<button class="ap-btn" id="ap-arm">Arm autopilot</button>` : ''}
+ ${state.policy?.rules?.length ? `<button class="ap-btn ghost" id="ap-cancel">Cancel</button>` : ''}
+ </div>
+ ${preview}
+ </div>`;
+ }
+
+ function renderRuleLi(r, withControls) {
+ const tone = STATUS_TONE[r.last_status] || 'muted';
+ const statusChip = r.last_status
+ ? `<span class="ap-chip ${tone}">${esc(r.last_status.replace('_', ' '))}</span>`
+ : '';
+ const sig = r.last_signature || r.signature;
+ const explorer = r.explorer || (sig ? explorerTxUrl(sig, ctx.getNetwork()) : null);
+ const noteHtml = r.last_note
+ ? `<div class="note">${esc(r.last_note)}${explorer ? ` · <a href="${esc(explorer)}" target="_blank" rel="noopener">view tx ↗</a>` : ''}</div>`
+ : explorer ? `<div class="note"><a href="${esc(explorer)}" target="_blank" rel="noopener">view tx ↗</a></div>` : '';
+ const ctlHtml = withControls
+ ? `<div class="ctl">${statusChip}<button class="ap-toggle" data-toggle="${esc(r.id)}">${r.paused ? 'Resume' : 'Pause'}</button></div>`
+ : '';
+ return `<li class="ap-rule" data-paused="${r.paused ? 'true' : 'false'}">
+ <span class="ic">${KIND_ICON[r.kind] || '•'}</span>
+ <div class="body"><div class="ttl">${esc(r.label)}</div>${noteHtml}</div>
+ ${ctlHtml}
+ </li>`;
+ }
+
+ function renderActiveRules() {
+ const p = state.policy;
+ const armed = !!p.armed && !p.kill_switch;
+ if (!p.rules?.length) {
+ return `<div class="ap-card"><div class="ap-empty"><div class="ic">🛰️</div>No autopilot rules yet.<br/>Write a policy to let this agent fund its own existence.</div>
+ <div class="ap-actions"><button class="ap-btn primary" id="ap-edit">Write a policy</button></div></div>`;
+ }
+ return `<div class="ap-card">
+ <h3>Armed rules</h3>
+ <p class="sub">${armed ? 'These rules run automatically on the schedule and on demand — every action real, gated by your spend policy, and logged.' : 'Compiled but not armed. Arm to let them run.'}</p>
+ <ul class="ap-rules">${p.rules.map((r) => renderRuleLi(r, true)).join('')}</ul>
+ <div class="ap-actions">
+ ${armed
+ ? `<button class="ap-btn primary" id="ap-run" ${state.running ? 'disabled' : ''}>${state.running ? '<span class="ap-spin"></span>Running…' : 'Run now'}</button>`
+ : `<button class="ap-btn primary" id="ap-arm-existing">Arm autopilot</button>`}
+ <button class="ap-btn ghost" id="ap-edit">Edit policy</button>
+ </div>
+ ${state.lastRun ? renderLastRun() : ''}
+ <div class="ap-kill">
+ <div class="t"><b>Kill switch.</b> Halts every autopilot action instantly.</div>
+ <button class="ap-btn danger" id="ap-kill">Halt autopilot</button>
+ </div>
+ </div>`;
+ }
+
+ function renderLastRun() {
+ const res = state.lastRun;
+ if (!res) return '';
+ if (!res.ran) {
+ const reason = (res.reason || '').replace(/_/g, ' ');
+ return `<div class="ap-warn amber">Last run did nothing — ${esc(res.note || reason || 'no due rules')}.</div>`;
+ }
+ const rows = (res.results || []).map((r) => {
+ const tone = STATUS_TONE[r.last_status] || 'muted';
+ const explorer = r.explorer || (r.signature ? explorerTxUrl(r.signature, ctx.getNetwork()) : null);
+ return `<li class="ap-rule"><span class="ic">${KIND_ICON[r.kind] || '•'}</span><div class="body"><div class="ttl">${esc(r.label)}</div><div class="note">${esc(r.last_note || r.last_status || '')}${explorer ? ` · <a href="${esc(explorer)}" target="_blank" rel="noopener">view tx ↗</a>` : ''}</div></div><div class="ctl"><span class="ap-chip ${tone}">${esc((r.last_status || '').replace('_', ' '))}</span></div></li>`;
+ }).join('');
+ return `<div style="margin-top:var(--space-md,14px)"><p class="sub" style="margin:0 0 8px">Last run</p><ul class="ap-rules">${rows}</ul></div>`;
+ }
+
+ // ── wiring ────────────────────────────────────────────────────────────────
+ function wire() {
+ panel.querySelector('#ap-edit')?.addEventListener('click', () => { state.editing = true; state.compiled = null; render(); });
+ panel.querySelector('#ap-cancel')?.addEventListener('click', () => { state.editing = false; state.compiled = null; render(); });
+ panel.querySelector('#ap-unkill')?.addEventListener('click', () => savePolicy({ kill_switch: false }, 'Autopilot re-enabled'));
+ panel.querySelector('#ap-kill')?.addEventListener('click', onKill);
+
+ panel.querySelectorAll('[data-eg]').forEach((b) => b.addEventListener('click', () => {
+ const ta = panel.querySelector('#ap-src');
+ if (ta) { ta.value = EXAMPLES[Number(b.dataset.eg)] || ''; state.source = ta.value; ta.focus(); }
+ }));
+ panel.querySelector('#ap-src')?.addEventListener('input', (e) => { state.source = e.target.value; });
+ panel.querySelector('#ap-compile')?.addEventListener('click', onCompile);
+ panel.querySelector('#ap-arm')?.addEventListener('click', onArm);
+ panel.querySelector('#ap-arm-existing')?.addEventListener('click', () => savePolicy({ armed: true }, 'Autopilot armed'));
+ panel.querySelector('#ap-run')?.addEventListener('click', onRun);
+
+ panel.querySelectorAll('[data-toggle]').forEach((b) => b.addEventListener('click', () => onTogglePause(b.dataset.toggle)));
+ }
+
+ function sweepInput() {
+ const v = (panel.querySelector('#ap-sweep')?.value || '').trim();
+ if (!v) return { ok: true, value: null };
+ if (!SOL_ADDR_RE.test(v)) return { ok: false, message: 'Sweep destination is not a valid Solana address.' };
+ return { ok: true, value: v };
+ }
+
+ async function onCompile() {
+ const text = (panel.querySelector('#ap-src')?.value || '').trim();
+ if (!text) { ctx.toast('Write a policy first.'); return; }
+ const sweep = sweepInput();
+ if (!sweep.ok) { ctx.toast(sweep.message); return; }
+ state.compiling = true; state.source = text; render();
+ const res = await call(base('compile'), { method: 'POST', body: { text, sweep_destination: sweep.value } });
+ if (destroyed) return;
+ state.compiling = false;
+ if (!res.ok) { ctx.toast(res.message || 'Could not compile'); render(); return; }
+ state.compiled = res.data;
+ render();
+ }
+
+ async function onArm() {
+ const c = state.compiled;
+ if (!c || !c.rules?.length) { ctx.toast('Compile a policy first.'); return; }
+ if (c.contradictions?.length) { ctx.toast('Resolve the conflicts before arming.'); return; }
+ const sweep = sweepInput();
+ if (!sweep.ok) { ctx.toast(sweep.message); return; }
+ const needsSweepDest = c.rules.some((r) => r.kind === 'sweep') && !(sweep.value || c.sweep_destination);
+ if (needsSweepDest) { ctx.toast('Set a sweep destination — your policy sweeps profit.'); return; }
+ await savePolicy({
+ rules: c.rules,
+ buffer_sol: c.buffer_sol,
+ sweep_destination: sweep.value || c.sweep_destination || null,
+ source_text: c.source_text,
+ armed: true,
+ kill_switch: false,
+ }, 'Autopilot armed — your agent now funds itself.');
+ state.editing = false;
+ state.compiled = null;
+ }
+
+ async function savePolicy(patch, successMsg) {
+ const res = await call(base(''), { method: 'PUT', body: patch });
+ if (destroyed) return;
+ if (!res.ok) { ctx.toast(res.message || 'Save failed'); return; }
+ state.policy = res.data.policy;
+ state.source = state.policy?.source_text || state.source;
+ if (successMsg) ctx.toast(successMsg);
+ // Refresh the runway after any policy change.
+ await load();
+ }
+
+ async function onKill() {
+ await savePolicy({ kill_switch: true }, 'Autopilot halted.');
+ }
+
+ async function onTogglePause(ruleId) {
+ const p = state.policy;
+ const rules = (p.rules || []).map((r) => (r.id === ruleId ? { ...r, paused: !r.paused } : r));
+ await savePolicy({ rules }, 'Rule updated');
+ }
+
+ async function onRun() {
+ state.running = true; render();
+ const res = await call(base('run'), { method: 'POST', body: {} });
+ if (destroyed) return;
+ state.running = false;
+ if (!res.ok) { ctx.toast(res.message || 'Run failed'); render(); return; }
+ state.lastRun = res.data;
+ const did = (res.data.results || []).filter((r) => r.last_status === 'ok').length;
+ ctx.toast(res.data.ran ? (did ? `Ran ${did} action${did === 1 ? '' : 's'}.` : 'Nothing was due this cycle.') : 'Autopilot is not active.');
+ await load();
+ state.lastRun = res.data; // keep the run summary visible after reload
+ render();
+ }
+
+ load();
+ return { destroy() { destroyed = true; } };
+ },
+});
diff --git a/src/agent-wallet-hub/tabs/earn.js b/src/agent-wallet-hub/tabs/earn.js
new file mode 100644
index 000000000..1726ec2ea
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/earn.js
@@ -0,0 +1,630 @@
+/**
+ * Agent Wallet hub — Earn tab (fully built). Owner-only.
+ *
+ * "Your avatar has a job." This is the economy home: what the agent has earned
+ * (skill sales + tips), the prices that make it money, the bounded allowance +
+ * kill switch that lets it pay other agents safely, and a clean receipts
+ * statement of every dollar in and out. Every number is real — it traces to
+ * agent_custody_events / skill_payment_earnings via GET /api/agents/:id/economy.
+ * Pricing writes through the same MonetizationService the rest of the platform
+ * uses; the kill switch writes the real spend policy. No mocks, no fake numbers.
+ *
+ * Sections:
+ * 1. Earnings hero — lifetime / 7d / today, count-up, "earned while away".
+ * 2. Earning engine — price the agent's skills in USDC (the buy side settles
+ * for real over Solana Pay → real funds into the agent wallet).
+ * 3. Autonomous spend — allowance snapshot + prominent kill switch; the agent
+ * pays services over the real x402 bridge bounded by enforceSpendLimit.
+ * 4. Receipts — unified in/out statement with real signatures.
+ * 5. Discover — the live services directory + hire a service.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import {
+ fetchEconomy,
+ fetchPricing,
+ savePricing,
+ fetchLimits,
+ setFrozen,
+} from '../../agent-economy-hub.js';
+import { formatUsd, timeAgo, shortAddress, explorerTxUrl, explorerAddressUrl } from '../util.js';
+
+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const SEEN_KEY = (id) => `tws-earn-seen:${id}`;
+
+const STYLE_ID = 'awh-earn-style';
+const STYLE = `
+.awh-earn-hero { text-align: center; padding: var(--space-5,20px) var(--space-4,16px) var(--space-4,16px); }
+.awh-earn-eyebrow { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .08em; color: var(--wallet-accent,#c4b5fd); margin: 0 0 6px; }
+.awh-earn-big { font-family: var(--font-display, system-ui); font-size: clamp(2.2rem, 9vw, 3.2rem); font-weight: 700; line-height: 1; color: var(--ink-bright,#fff); letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
+.awh-earn-tag { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top: 8px; }
+.awh-earn-chips { display: flex; gap: var(--space-2,8px); justify-content: center; flex-wrap: wrap; margin-top: var(--space-4,16px); }
+.awh-earn-chip { display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 8px 14px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); min-width: 84px; }
+.awh-earn-chip b { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); font-variant-numeric: tabular-nums; }
+.awh-earn-chip span { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform: uppercase; letter-spacing: .04em; }
+.awh-earn-split { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top: var(--space-3,12px); }
+.awh-earn-split b { color: var(--ink,#e8e8e8); font-family: var(--font-mono, ui-monospace, monospace); }
+
+.awh-earn-away { display: flex; align-items: center; gap: 10px; margin: 0 0 var(--awh-gap,16px); padding: 11px 14px; border-radius: var(--radius-lg,14px); border: 1px solid color-mix(in srgb, var(--success,#4ade80) 38%, transparent); background: color-mix(in srgb, var(--success,#4ade80) 10%, transparent); color: var(--ink-bright,#fff); font-size: var(--text-md,.8125rem); animation: awh-earn-pop var(--duration-base,220ms) var(--ease-standard, ease); }
+.awh-earn-away .x { margin-left: auto; appearance: none; background: none; border: 0; color: var(--ink-dim,#888); cursor: pointer; font-size: 16px; line-height: 1; padding: 2px 4px; }
+.awh-earn-away .x:hover { color: var(--ink,#e8e8e8); }
+.awh-earn-away b { color: var(--success,#4ade80); font-family: var(--font-mono, ui-monospace, monospace); }
+.awh-earn-spark { font-size: 18px; flex: none; }
+
+.awh-earn-empty { text-align: center; color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); line-height: 1.5; padding: var(--space-3,12px) 0; }
+.awh-earn-empty strong { color: var(--ink,#e8e8e8); display: block; font-size: var(--text-md,.8125rem); margin-bottom: 4px; }
+
+.awh-sk-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-2,8px); }
+.awh-sk { display: flex; align-items: center; gap: var(--space-3,12px); padding: 10px 12px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); }
+.awh-sk-toggle { flex: none; }
+.awh-sk-name { flex: 1 1 auto; min-width: 0; font-size: var(--text-md,.8125rem); color: var(--ink,#e8e8e8); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.awh-sk-adv { font-size: var(--text-2xs,.6875rem); color: var(--wallet-accent,#c4b5fd); border: 1px solid color-mix(in srgb, var(--wallet-accent,#c4b5fd) 35%, transparent); border-radius: var(--radius-pill,999px); padding: 1px 7px; margin-left: 6px; white-space: nowrap; }
+.awh-sk-price { flex: none; display: inline-flex; align-items: center; gap: 5px; }
+.awh-sk-price .pre { color: var(--ink-dim,#888); font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); }
+.awh-sk-input { width: 84px; font: inherit; font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); text-align: right; color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-sm,6px); padding: 6px 8px; }
+.awh-sk-input:disabled { opacity: .5; }
+.awh-sk-input:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 1px; }
+.awh-sk-unit { color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); }
+.awh-earn-save-row { display: flex; align-items: center; gap: var(--space-3,12px); margin-top: var(--space-4,16px); flex-wrap: wrap; }
+.awh-earn-save-row .msg { font-size: var(--text-sm,.764rem); }
+.awh-earn-save-row .msg.ok { color: var(--success,#4ade80); }
+.awh-earn-save-row .msg.err { color: var(--danger,#f87171); }
+.awh-earn-link { color: var(--wallet-accent,#c4b5fd); text-decoration: none; font-size: var(--text-sm,.764rem); border-bottom: 1px dotted currentColor; }
+.awh-earn-link:hover { color: var(--ink-bright,#fff); }
+
+.awh-earn-policy { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-2,8px); margin-bottom: var(--space-3,12px); }
+.awh-earn-pcell { text-align: center; padding: 9px 6px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); }
+.awh-earn-pcell b { display: block; font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); }
+.awh-earn-pcell span { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform: uppercase; letter-spacing: .04em; }
+.awh-earn-pbar { height: 5px; border-radius: 3px; background: var(--surface-3, rgba(255,255,255,.08)); overflow: hidden; margin: 4px 0 0; }
+.awh-earn-pbar i { display: block; height: 100%; background: var(--wallet-accent,#c4b5fd); border-radius: 3px; transition: width var(--duration-base,220ms) var(--ease-standard,ease); }
+.awh-earn-pbar i.warn { background: var(--warn,#fbbf24); }
+.awh-earn-pbar i.danger { background: var(--danger,#f87171); }
+
+.awh-rcpt-list { list-style: none; margin: 0; padding: 0; }
+.awh-rcpt { display: flex; align-items: center; gap: var(--space-3,12px); padding: 10px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); }
+.awh-rcpt:last-child { border-bottom: none; }
+.awh-rcpt-ic { flex: none; width: 30px; height: 30px; border-radius: 50%; display: grid; place-items: center; font-size: 13px; }
+.awh-rcpt-ic.in { background: color-mix(in srgb, var(--success,#4ade80) 16%, transparent); color: var(--success,#4ade80); }
+.awh-rcpt-ic.out { background: color-mix(in srgb, var(--wallet-accent,#c4b5fd) 16%, transparent); color: var(--wallet-accent,#c4b5fd); }
+.awh-rcpt-main { flex: 1 1 auto; min-width: 0; }
+.awh-rcpt-label { font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.awh-rcpt-meta { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); margin-top: 2px; }
+.awh-rcpt-meta a { color: inherit; text-decoration: none; border-bottom: 1px dotted currentColor; }
+.awh-rcpt-meta a:hover { color: var(--ink,#e8e8e8); }
+.awh-rcpt-amt { flex: none; font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-md,.8125rem); font-variant-numeric: tabular-nums; }
+.awh-rcpt-amt.in { color: var(--success,#4ade80); }
+.awh-rcpt-amt.out { color: var(--ink-dim,#888); }
+.awh-rcpt-amt.pending { color: var(--warn,#fbbf24); }
+
+.awh-earn-disc { display: flex; gap: var(--space-2,8px); flex-wrap: wrap; }
+.awh-earn-skel span { display: block; height: 16px; border-radius: var(--radius-sm,6px); background: var(--surface-2, rgba(255,255,255,.05)); animation: awh-skel 1.4s ease-in-out infinite; margin-bottom: 10px; }
+.awh-earn-skel span:nth-child(2){ width: 60%; } .awh-earn-skel span:nth-child(3){ width: 80%; }
+@keyframes awh-earn-pop { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
+@keyframes awh-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }
+@media (prefers-reduced-motion: reduce){ .awh-earn-away, .awh-earn-skel span, .awh-earn-pbar i { animation: none; transition: none; } }
+@media (max-width: 520px){ .awh-earn-policy { grid-template-columns: repeat(3, 1fr); } .awh-sk-input { width: 72px; } }
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = STYLE_ID;
+ tag.textContent = STYLE;
+ document.head.appendChild(tag);
+}
+
+// Money formatter that never lies: real $0.00, fine-grained under a dollar.
+function money(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '$0.00';
+ const v = Number(n);
+ if (v > 0 && v < 0.01) return '$' + v.toFixed(4);
+ return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: v < 1 ? 4 : 2 }).format(v);
+}
+
+function unixSec(iso) {
+ const t = Date.parse(iso);
+ return Number.isFinite(t) ? Math.floor(t / 1000) : 0;
+}
+
+registerWalletTab({
+ id: 'earn',
+ label: 'Earn',
+ order: 45,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const { escapeHtml, toast } = ctx;
+
+ let destroyed = false;
+ let countRaf = 0;
+
+ const state = {
+ loading: true,
+ error: null,
+ econ: null, // economy summary
+ // pricing
+ pricingLoaded: false,
+ pricingRows: [], // full rows from GET (preserve advanced fields)
+ editor: [], // [{ skill, active, usd, advanced, advancedKind }]
+ saving: false,
+ saveMsg: null,
+ saveOk: false,
+ // kill switch
+ freezing: false,
+ // "earned while away"
+ awayUsd: 0,
+ awayCount: 0,
+ awayDismissed: false,
+ };
+
+ function shell() {
+ panel.innerHTML = `
+ <div class="awh-card" data-host="hero"></div>
+ <div class="awh-card" data-host="engine"></div>
+ <div class="awh-card" data-host="spend"></div>
+ <div class="awh-card" data-host="receipts"></div>
+ <div class="awh-card" data-host="discover"></div>
+ `;
+ renderAll();
+ }
+ const host = (k) => panel.querySelector(`[data-host="${k}"]`);
+
+ function renderAll() {
+ renderHero();
+ renderEngine();
+ renderSpend();
+ renderReceipts();
+ renderDiscover();
+ }
+
+ // ── 1. Hero ─────────────────────────────────────────────────────────────
+ function renderHero() {
+ const h = host('hero');
+ if (!h) return;
+ if (state.loading) {
+ h.innerHTML = `<div class="awh-earn-skel" aria-busy="true"><span></span><span></span><span></span></div>`;
+ return;
+ }
+ if (state.error) {
+ h.innerHTML = `<div class="awh-empty">Couldn’t load earnings. <button class="awh-btn awh-bal-mini" type="button" data-act="reload">Retry</button><div class="awh-rcpt-meta" style="margin-top:6px">${escapeHtml(state.error)}</div></div>`;
+ return;
+ }
+ const e = state.econ.earnings;
+ const lifetime = e.total.lifetime;
+ const hasEarned = e.total.count > 0;
+ const away = state.awayUsd > 0 && !state.awayDismissed
+ ? `<div class="awh-earn-away" role="status"><span class="awh-earn-spark">✨</span><div>Your avatar earned <b>${escapeHtml(money(state.awayUsd))}</b> while you were away${state.awayCount > 1 ? ` · ${state.awayCount} payments` : ''}.</div><button class="x" type="button" data-act="dismiss-away" aria-label="Dismiss">×</button></div>`
+ : '';
+
+ if (!hasEarned) {
+ h.innerHTML = `${away}
+ <div class="awh-earn-hero">
+ <p class="awh-earn-eyebrow">The agent economy</p>
+ <div class="awh-earn-big">${escapeHtml(money(0))}</div>
+ <p class="awh-earn-tag">Your avatar doesn’t have a job yet.</p>
+ </div>
+ <div class="awh-earn-empty"><strong>Give it one.</strong>Price a skill below and it starts earning the moment someone buys — real USDC, straight into this wallet.</div>`;
+ return;
+ }
+ h.innerHTML = `${away}
+ <div class="awh-earn-hero">
+ <p class="awh-earn-eyebrow">${escapeHtml(ctx.agent?.name || 'Your avatar')} has earned</p>
+ <div class="awh-earn-big" data-count="${lifetime}">${escapeHtml(money(lifetime))}</div>
+ <p class="awh-earn-tag">lifetime · across ${e.total.count} payment${e.total.count === 1 ? '' : 's'}</p>
+ <div class="awh-earn-chips">
+ <div class="awh-earn-chip"><b>${escapeHtml(money(e.total.today))}</b><span>Today</span></div>
+ <div class="awh-earn-chip"><b>${escapeHtml(money(e.total.week))}</b><span>7 days</span></div>
+ <div class="awh-earn-chip"><b>${escapeHtml(money(e.total.lifetime))}</b><span>All time</span></div>
+ </div>
+ <p class="awh-earn-split">From <b>${escapeHtml(money(e.skill_sales.lifetime))}</b> in skill sales${e.tips.lifetime > 0 ? ` and <b>${escapeHtml(money(e.tips.lifetime))}</b> in tips` : ''}.</p>
+ </div>`;
+ animateCount();
+ }
+
+ function animateCount() {
+ if (typeof window === 'undefined') return;
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
+ const el = host('hero')?.querySelector('[data-count]');
+ if (!el) return;
+ const target = Number(el.getAttribute('data-count')) || 0;
+ if (target <= 0) return;
+ const dur = 800;
+ let start = null;
+ cancelAnimationFrame(countRaf);
+ const step = (ts) => {
+ if (destroyed || !el.isConnected) return;
+ if (start == null) start = ts;
+ const p = Math.min(1, (ts - start) / dur);
+ const eased = 1 - Math.pow(1 - p, 3);
+ el.textContent = money(target * eased);
+ if (p < 1) countRaf = requestAnimationFrame(step);
+ else el.textContent = money(target);
+ };
+ el.textContent = money(0);
+ countRaf = requestAnimationFrame(step);
+ }
+
+ // ── 2. Earning engine (skill pricing) ───────────────────────────────────
+ function renderEngine() {
+ const h = host('engine');
+ if (!h) return;
+ const skills = state.econ?.all_skills || [];
+ if (state.loading) {
+ h.innerHTML = `<h2 class="awh-card-h">Earning engine</h2><div class="awh-earn-skel" aria-busy="true"><span></span><span></span></div>`;
+ return;
+ }
+ if (!skills.length) {
+ h.innerHTML = `<h2 class="awh-card-h">Earning engine</h2>
+ <div class="awh-earn-empty"><strong>No skills to price yet.</strong>Add skills to this agent, then set a price so other people — and other agents — can pay to use them.</div>
+ <div class="awh-earn-save-row"><a class="awh-earn-link" href="/agent/${escapeHtml(ctx.agentId)}/edit#skills">Add skills →</a></div>`;
+ return;
+ }
+ if (!state.pricingLoaded) {
+ h.innerHTML = `<h2 class="awh-card-h">Earning engine</h2><div class="awh-earn-skel" aria-busy="true"><span></span><span></span></div>`;
+ return;
+ }
+ const rows = state.editor.map((row, i) => {
+ const advBadge = row.advanced ? `<span class="awh-sk-adv" title="Advanced pricing — edit in the full pricing editor">${escapeHtml(row.advancedKind)}</span>` : '';
+ return `<li class="awh-sk">
+ <input class="awh-sk-toggle" type="checkbox" data-edit="active" data-i="${i}" ${row.active ? 'checked' : ''} aria-label="Charge for ${escapeHtml(row.skill)}" />
+ <span class="awh-sk-name" title="${escapeHtml(row.skill)}">${escapeHtml(row.skill)}${advBadge}</span>
+ <span class="awh-sk-price">
+ <span class="pre">$</span>
+ <input class="awh-sk-input" type="number" min="0" step="0.01" inputmode="decimal" data-edit="usd" data-i="${i}"
+ value="${row.usd != null ? escapeHtml(String(row.usd)) : ''}" placeholder="0.50"
+ ${row.active && !row.advanced ? '' : 'disabled'} aria-label="Price for ${escapeHtml(row.skill)} in USDC" />
+ <span class="awh-sk-unit">USDC</span>
+ </span>
+ </li>`;
+ }).join('');
+ h.innerHTML = `<h2 class="awh-card-h">Earning engine · price your skills</h2>
+ <ul class="awh-sk-list">${rows}</ul>
+ <div class="awh-earn-save-row">
+ <button class="awh-btn awh-btn--primary" type="button" data-act="save-prices" ${state.saving ? 'disabled' : ''}>${state.saving ? 'Saving…' : 'Save prices'}</button>
+ <a class="awh-earn-link" href="/agent/${escapeHtml(ctx.agentId)}/edit#monetize">Trials, time-passes & pay-what-you-want →</a>
+ ${state.saveMsg ? `<span class="msg ${state.saveOk ? 'ok' : 'err'}">${escapeHtml(state.saveMsg)}</span>` : ''}
+ </div>`;
+ }
+
+ function buildEditorFromPricing() {
+ const bySkill = new Map();
+ for (const r of state.pricingRows) bySkill.set(r.skill, r);
+ const skills = state.econ?.all_skills || [];
+ state.editor = skills.map((skill) => {
+ const r = bySkill.get(skill);
+ const advancedKind = r
+ ? (r.pricing_type === 'pwyw' ? 'Pay what you want'
+ : (Number(r.time_pass_hours) > 0 ? 'Time pass'
+ : (Number(r.trial_uses) > 0 ? 'Free trial' : null)))
+ : null;
+ return {
+ skill,
+ active: !!r,
+ usd: r ? round2(Number(r.amount) / 1e6) : '',
+ advanced: !!advancedKind,
+ advancedKind,
+ };
+ });
+ }
+
+ function round2(n) {
+ return Math.round(n * 100) / 100;
+ }
+
+ async function loadPricing() {
+ const res = await fetchPricing(ctx.agentId);
+ if (destroyed) return;
+ if (res.ok) {
+ state.pricingRows = Array.isArray(res.data?.prices) ? res.data.prices : [];
+ buildEditorFromPricing();
+ state.pricingLoaded = true;
+ } else {
+ // Pricing read failed — still let them price from scratch.
+ state.pricingRows = [];
+ buildEditorFromPricing();
+ state.pricingLoaded = true;
+ }
+ renderEngine();
+ }
+
+ async function savePrices() {
+ state.saveMsg = null;
+ const bySkill = new Map();
+ for (const r of state.pricingRows) bySkill.set(r.skill, r);
+ const prices = [];
+ for (const row of state.editor) {
+ if (!row.active) continue;
+ const existing = bySkill.get(row.skill);
+ if (existing && row.advanced) {
+ // Preserve advanced config verbatim (pwyw/trial/time-pass) — the
+ // inline editor never touches these; the full editor owns them.
+ prices.push(stripRow(existing));
+ continue;
+ }
+ const usd = Number(row.usd);
+ if (!Number.isFinite(usd) || usd <= 0) {
+ state.saveOk = false;
+ state.saveMsg = `Set a price above $0 for “${row.skill}”.`;
+ renderEngine();
+ return;
+ }
+ const amount = Math.round(usd * 1e6);
+ if (existing) {
+ prices.push({ ...stripRow(existing), amount });
+ } else {
+ prices.push({ skill: row.skill, amount, currency_mint: USDC_MINT, chain: 'solana', trial_uses: 0, pricing_type: 'fixed' });
+ }
+ }
+ state.saving = true;
+ renderEngine();
+ const res = await savePricing(ctx.agentId, prices);
+ if (destroyed) return;
+ state.saving = false;
+ if (res.ok) {
+ state.saveOk = true;
+ state.saveMsg = prices.length ? `Saved · ${prices.length} skill${prices.length === 1 ? '' : 's'} earning` : 'Saved · pricing cleared';
+ toast('Prices saved');
+ // Reflect listed-skill changes in the hero/engine + refetch summary.
+ await reload({ keepEditor: true });
+ } else {
+ state.saveOk = false;
+ state.saveMsg = res.message || 'Could not save prices';
+ renderEngine();
+ }
+ }
+
+ // Only the fields the pricing schema accepts — drop read-only/derived ones.
+ function stripRow(r) {
+ const out = {
+ skill: r.skill,
+ amount: Number(r.amount),
+ currency_mint: r.currency_mint || USDC_MINT,
+ chain: r.chain || 'solana',
+ trial_uses: Number(r.trial_uses) || 0,
+ pricing_type: r.pricing_type === 'pwyw' ? 'pwyw' : 'fixed',
+ };
+ if (r.time_pass_hours != null) out.time_pass_hours = Number(r.time_pass_hours);
+ if (r.time_pass_amount != null) out.time_pass_amount = Number(r.time_pass_amount);
+ if (out.pricing_type === 'pwyw' && r.minimum_amount != null) out.minimum_amount = Number(r.minimum_amount);
+ return out;
+ }
+
+ // ── 3. Autonomous spend (allowance + kill switch) ───────────────────────
+ function renderSpend() {
+ const h = host('spend');
+ if (!h) return;
+ if (state.loading) {
+ h.innerHTML = `<h2 class="awh-card-h">Autonomous spending</h2><div class="awh-earn-skel" aria-busy="true"><span></span><span></span></div>`;
+ return;
+ }
+ const p = state.econ.policy;
+ const spend = state.econ.spending.x402;
+ const frozen = p.frozen;
+ const dailyCap = p.daily_usd;
+ const spentToday = p.spent_today_usd ?? spend.today ?? 0;
+ const pct = dailyCap && dailyCap > 0 ? Math.min(100, (spentToday / dailyCap) * 100) : 0;
+ const barCls = pct >= 100 ? 'danger' : pct >= 75 ? 'warn' : '';
+
+ const freezeCard = `
+ <div class="awh-freeze-card${frozen ? ' is-frozen' : ''}" style="margin-bottom:var(--space-3,12px)">
+ <div class="awh-freeze-row">
+ <div class="awh-freeze-copy">
+ <strong>${frozen ? '🔒 Autonomous spending frozen' : '🟢 Autonomous spending armed'}</strong>
+ <span>${frozen
+ ? 'Every autonomous payment (services, trades, snipes) is blocked. You can still withdraw.'
+ : 'The agent may pay other services from its wallet, bounded by the caps below.'}</span>
+ </div>
+ <button class="awh-btn ${frozen ? 'awh-btn--primary' : 'awh-btn--danger'}" type="button" data-act="toggle-freeze" ${state.freezing ? 'disabled' : ''}>
+ ${state.freezing ? '…' : (frozen ? 'Unfreeze' : 'Freeze all')}
+ </button>
+ </div>
+ </div>`;
+
+ const cap = (v) => (v == null ? 'No cap' : money(v));
+ h.innerHTML = `<h2 class="awh-card-h">Autonomous spending · set & forget, safely</h2>
+ ${freezeCard}
+ <div class="awh-earn-policy">
+ <div class="awh-earn-pcell"><b>${escapeHtml(cap(dailyCap))}</b><span>Daily cap</span>${dailyCap ? `<div class="awh-earn-pbar"><i class="${barCls}" style="width:${pct}%"></i></div>` : ''}</div>
+ <div class="awh-earn-pcell"><b>${escapeHtml(cap(p.per_tx_usd))}</b><span>Per payment</span></div>
+ <div class="awh-earn-pcell"><b>${p.allowlist_count > 0 ? p.allowlist_count : 'Open'}</b><span>Allowlist</span></div>
+ </div>
+ <p class="awh-earn-split" style="margin-top:0">Spent <b>${escapeHtml(money(spentToday))}</b> today${dailyCap ? ` of ${escapeHtml(money(dailyCap))}` : ''} · <b>${escapeHtml(money(spend.lifetime))}</b> lifetime across ${spend.count} payment${spend.count === 1 ? '' : 's'}.</p>
+ <div class="awh-earn-save-row">
+ <button class="awh-btn awh-btn--primary" type="button" data-act="hire">Hire a service →</button>
+ <button class="awh-btn" type="button" data-act="adjust-caps">Adjust caps & allowlist</button>
+ </div>`;
+ }
+
+ async function toggleFreeze() {
+ const next = !state.econ.policy.frozen;
+ if (next && !confirmFreeze()) return;
+ state.freezing = true;
+ renderSpend();
+ const res = await setFrozen(ctx.agentId, next);
+ if (destroyed) return;
+ state.freezing = false;
+ if (res.ok) {
+ state.econ.policy.frozen = res.data?.limits?.frozen ?? next;
+ toast(next ? 'Autonomous spending frozen' : 'Autonomous spending re-armed');
+ } else {
+ toast(res.message || 'Could not update the kill switch');
+ }
+ renderSpend();
+ }
+
+ function confirmFreeze() {
+ // A freeze is the safe direction (it only blocks spending) — no modal, but
+ // give the owner a beat to confirm via the native dialog.
+ if (typeof window === 'undefined' || !window.confirm) return true;
+ return window.confirm('Freeze all autonomous spending? The agent will stop paying for any service until you unfreeze. Withdrawals stay available.');
+ }
+
+ // ── 4. Receipts ─────────────────────────────────────────────────────────
+ function renderReceipts() {
+ const h = host('receipts');
+ if (!h) return;
+ if (state.loading) {
+ h.innerHTML = `<h2 class="awh-card-h">Receipts</h2><div class="awh-earn-skel" aria-busy="true"><span></span><span></span></div>`;
+ return;
+ }
+ const rows = state.econ.receipts || [];
+ if (!rows.length) {
+ h.innerHTML = `<h2 class="awh-card-h">Receipts</h2>
+ <div class="awh-earn-empty">No money has moved yet. Every payment in and out — skill sales, tips, services your agent pays for — shows up here as a receipt with its on-chain signature.</div>`;
+ return;
+ }
+ const net = ctx.getNetwork?.() || 'mainnet';
+ const items = rows.map((r) => {
+ const inbound = r.direction === 'in';
+ const amt = r.usd != null ? money(r.usd) : (r.sol != null ? `${r.sol.toFixed(4)} SOL` : '—');
+ const pending = r.status && r.status !== 'confirmed' && r.status !== 'ok';
+ const cp = r.counterparty
+ ? (looksLikeAddress(r.counterparty)
+ ? `<a href="${escapeHtml(explorerAddressUrl(r.counterparty, net))}" target="_blank" rel="noopener">${escapeHtml(shortAddress(r.counterparty, 4, 4))} ↗</a>`
+ : escapeHtml(shortAddress(r.counterparty, 4, 4)))
+ : '';
+ const when = r.created_at ? timeAgo(unixSec(r.created_at)) : '';
+ const sig = r.signature
+ ? ` · <a href="${escapeHtml(explorerTxUrl(r.signature, net))}" target="_blank" rel="noopener">tx ↗</a>`
+ : '';
+ return `<li class="awh-rcpt">
+ <div class="awh-rcpt-ic ${inbound ? 'in' : 'out'}" aria-hidden="true">${inbound ? '↓' : '↑'}</div>
+ <div class="awh-rcpt-main">
+ <div class="awh-rcpt-label">${escapeHtml(r.label || (inbound ? 'Received' : 'Paid'))}</div>
+ <div class="awh-rcpt-meta">${inbound ? 'from' : 'to'} ${cp || '—'} · ${escapeHtml(when)}${pending ? ` · ${escapeHtml(r.status)}` : ''}${sig}</div>
+ </div>
+ <div class="awh-rcpt-amt ${inbound ? 'in' : 'out'}${pending ? ' pending' : ''}">${inbound ? '+' : '−'}${escapeHtml(amt)}</div>
+ </li>`;
+ }).join('');
+ h.innerHTML = `<h2 class="awh-card-h">Receipts · ${rows.length} recent</h2><ul class="awh-rcpt-list">${items}</ul>`;
+ }
+
+ // ── 5. Discover ─────────────────────────────────────────────────────────
+ function renderDiscover() {
+ const h = host('discover');
+ if (!h) return;
+ const peers = state.econ?.peers || [];
+ const net = ctx.getNetwork?.() || 'mainnet';
+ const peerLine = peers.length
+ ? `<p class="awh-earn-split" style="margin-top:0">Your agent has paid ${peers.length} counterpart${peers.length === 1 ? 'y' : 'ies'}: ${peers.slice(0, 4).map((p) => `<a class="awh-earn-link" href="${escapeHtml(explorerAddressUrl(p.address, net))}" target="_blank" rel="noopener">${escapeHtml(shortAddress(p.address, 4, 4))}</a>`).join(', ')}.</p>`
+ : `<p class="awh-earn-split" style="margin-top:0">Discover agents and x402 services your avatar can hire — the network where agents pay agents.</p>`;
+ h.innerHTML = `<h2 class="awh-card-h">The agent economy</h2>
+ ${peerLine}
+ <div class="awh-earn-disc">
+ <a class="awh-btn awh-btn--primary" href="/economy">Services directory →</a>
+ <a class="awh-btn" href="/agent-economy">Watch agents transact</a>
+ </div>`;
+ }
+
+ // ── data ────────────────────────────────────────────────────────────────
+ async function reload({ keepEditor = false } = {}) {
+ const res = await fetchEconomy(ctx.agentId, ctx.getNetwork?.() || 'mainnet');
+ if (destroyed) return;
+ if (res.ok) {
+ state.econ = res.data;
+ state.error = null;
+ computeAway();
+ } else {
+ state.error = res.message || 'load failed';
+ }
+ state.loading = false;
+ if (!keepEditor && state.pricingLoaded) buildEditorFromPricing();
+ renderAll();
+ }
+
+ // "Earned while you were away": real inbound receipts since the last time the
+ // owner opened this tab. Honest — it sums actual settled receipts, nothing
+ // invented. The marker is per-agent in localStorage.
+ function computeAway() {
+ let last = 0;
+ try {
+ last = Number(localStorage.getItem(SEEN_KEY(ctx.agentId))) || 0;
+ } catch {
+ last = 0;
+ }
+ if (last > 0) {
+ let usd = 0;
+ let count = 0;
+ for (const r of state.econ.receipts || []) {
+ if (r.direction !== 'in' || r.usd == null) continue;
+ if (unixSec(r.created_at) * 1000 > last) {
+ usd += Number(r.usd);
+ count += 1;
+ }
+ }
+ state.awayUsd = usd;
+ state.awayCount = count;
+ }
+ try {
+ localStorage.setItem(SEEN_KEY(ctx.agentId), String(Date.now()));
+ } catch {
+ /* storage unavailable — skip the marker */
+ }
+ }
+
+ // ── interactions ────────────────────────────────────────────────────────
+ panel.addEventListener('click', (ev) => {
+ const act = ev.target?.closest?.('[data-act]')?.dataset?.act;
+ if (!act) return;
+ if (act === 'reload') {
+ state.loading = true;
+ renderAll();
+ reload();
+ } else if (act === 'save-prices') {
+ savePrices();
+ } else if (act === 'toggle-freeze') {
+ toggleFreeze();
+ } else if (act === 'hire') {
+ ctx.openTab?.('pay');
+ } else if (act === 'adjust-caps') {
+ ctx.openTab?.('withdraw');
+ toast('Open “Limits & Safety” to set caps and the allowlist');
+ } else if (act === 'dismiss-away') {
+ state.awayDismissed = true;
+ renderHero();
+ }
+ });
+
+ panel.addEventListener('change', (ev) => {
+ const t = ev.target;
+ const edit = t?.dataset?.edit;
+ if (!edit) return;
+ const i = Number(t.dataset.i);
+ const row = state.editor[i];
+ if (!row) return;
+ if (edit === 'active') {
+ row.active = t.checked;
+ state.saveMsg = null;
+ renderEngine();
+ }
+ });
+
+ panel.addEventListener('input', (ev) => {
+ const t = ev.target;
+ if (t?.dataset?.edit === 'usd') {
+ const row = state.editor[Number(t.dataset.i)];
+ if (row) row.usd = t.value;
+ }
+ });
+
+ shell();
+
+ return {
+ onShow() {
+ if (state.loading) {
+ reload();
+ loadPricing();
+ }
+ },
+ destroy() {
+ destroyed = true;
+ cancelAnimationFrame(countRaf);
+ },
+ };
+ },
+});
+
+function looksLikeAddress(s) {
+ return typeof s === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);
+}
diff --git a/src/agent-wallet-hub/tabs/recovery.js b/src/agent-wallet-hub/tabs/recovery.js
new file mode 100644
index 000000000..07d9bb042
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/recovery.js
@@ -0,0 +1,430 @@
+/**
+ * Agent Wallet hub — Recovery & Inheritance tab (owner-only).
+ *
+ * Custody you can actually trust: designate guardians + a beneficiary, set a
+ * threshold, and arm a dead-man's switch — so "I lost access" or "the owner is
+ * gone" never means the funded wallet dies with the key. Every irreversible step
+ * is explained, time-locked, and cancellable until commit; the owner aborts a
+ * looming inheritance just by being here. No key is ever exported — recovery
+ * transfers WHO OWNS the agent, and the same server-held key keeps signing.
+ *
+ * All state changes hit the real owner-gated API (CSRF-protected); the panel only
+ * ever renders real DB state. Guardians act from the standalone /guardian console.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { consumeCsrfToken } from '../../api.js';
+
+const STYLE_ID = 'awh-recovery-style';
+const STYLE = `
+.awh-rec { display: flex; flex-direction: column; gap: var(--space-3,12px); }
+.awh-rec h2 { margin: 0 0 6px; font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); font-family: var(--font-display, system-ui); font-weight:600; }
+.awh-rec-lead { color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); line-height: 1.55; margin: 0 0 4px; max-width: 60ch; }
+.awh-rec-shield { display:inline-grid; place-items:center; width:30px; height:30px; border-radius:var(--radius-md,10px); background: color-mix(in srgb, var(--wallet-accent,#8b5cf6) 16%, transparent); border:1px solid color-mix(in srgb, var(--wallet-accent,#8b5cf6) 36%, transparent); color: var(--wallet-accent-ink,#c4b5fd); font-size:15px; flex:none; }
+.awh-rec-roster { list-style:none; margin:8px 0 0; padding:0; display:flex; flex-direction:column; gap:6px; }
+.awh-rec-g { display:flex; align-items:center; gap:10px; padding:8px 10px; border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:var(--radius-md,10px); background:var(--surface-1,rgba(255,255,255,.03)); }
+.awh-rec-g img, .awh-rec-g .awh-rec-ava { width:26px; height:26px; border-radius:50%; object-fit:cover; background:var(--surface-3,rgba(255,255,255,.08)); flex:none; display:grid; place-items:center; font-size:11px; color:var(--ink-dim,#888); }
+.awh-rec-g-main { display:flex; flex-direction:column; min-width:0; flex:1; }
+.awh-rec-g-name { font-size:var(--text-sm,.764rem); color:var(--ink-bright,#fff); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+.awh-rec-g-role { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); text-transform:uppercase; letter-spacing:.05em; }
+.awh-rec-pill { font-size:var(--text-2xs,.6875rem); font-weight:600; padding:2px 8px; border-radius:var(--radius-pill,999px); border:1px solid transparent; }
+.awh-rec-pill.guardian { color:var(--wallet-accent-ink,#c4b5fd); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 14%,transparent); border-color:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 32%,transparent); }
+.awh-rec-pill.beneficiary { color:var(--success,#4ade80); background:color-mix(in srgb,var(--success,#4ade80) 12%,transparent); border-color:color-mix(in srgb,var(--success,#4ade80) 30%,transparent); }
+.awh-rec-x { appearance:none; background:transparent; border:none; color:var(--ink-dim,#888); cursor:pointer; font-size:15px; line-height:1; padding:4px; border-radius:var(--radius-sm,6px); }
+.awh-rec-x:hover { color:var(--danger,#f87171); background:color-mix(in srgb,var(--danger,#f87171) 12%,transparent); }
+.awh-rec-add { display:flex; gap:8px; margin-top:8px; flex-wrap:wrap; }
+.awh-rec-add input, .awh-rec select, .awh-rec input[type="number"] { font:inherit; font-size:var(--text-sm,.764rem); color:var(--ink,#e8e8e8); background:var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:var(--radius-md,10px); padding:8px 11px; }
+.awh-rec-add input { flex:1; min-width:160px; }
+.awh-rec-add input:focus-visible, .awh-rec select:focus-visible { outline:var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset:2px; }
+.awh-rec-field { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; padding:8px 0; }
+.awh-rec-field label { font-size:var(--text-sm,.764rem); color:var(--ink,#c8c8c8); }
+.awh-rec-field .hint { display:block; font-size:var(--text-2xs,.6875rem); color:var(--ink-faint,#666); margin-top:2px; }
+.awh-rec-switch { display:inline-flex; align-items:center; gap:8px; }
+.awh-rec-bar { height:6px; border-radius:999px; background:var(--surface-3,rgba(255,255,255,.08)); overflow:hidden; margin:8px 0 4px; }
+.awh-rec-bar > i { display:block; height:100%; border-radius:999px; background:linear-gradient(90deg,var(--success,#4ade80),var(--warn,#fbbf24)); transition:width var(--duration-base,220ms); }
+.awh-rec-bar.danger > i { background:linear-gradient(90deg,var(--warn,#fbbf24),var(--danger,#f87171)); }
+.awh-rec-narrate { font-style:italic; color:var(--ink,#c8c8c8); font-size:var(--text-sm,.764rem); line-height:1.5; padding:10px 12px; border-left:2px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 50%,transparent); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 7%,transparent); border-radius:0 var(--radius-md,10px) var(--radius-md,10px) 0; margin-top:6px; }
+.awh-rec-proc { border-color:color-mix(in srgb,var(--warn,#fbbf24) 40%,transparent) !important; background:color-mix(in srgb,var(--warn,#fbbf24) 7%,transparent); }
+.awh-rec-proc.danger { border-color:color-mix(in srgb,var(--danger,#f87171) 45%,transparent) !important; background:color-mix(in srgb,var(--danger,#f87171) 8%,transparent); }
+.awh-rec-steps { list-style:none; margin:10px 0 0; padding:0; display:flex; flex-direction:column; gap:0; }
+.awh-rec-step { display:flex; gap:10px; align-items:flex-start; position:relative; padding-bottom:14px; }
+.awh-rec-step:not(:last-child)::before { content:''; position:absolute; left:8px; top:18px; bottom:0; width:2px; background:var(--stroke,rgba(255,255,255,.08)); }
+.awh-rec-dot { width:18px; height:18px; border-radius:50%; flex:none; border:2px solid var(--stroke-strong,rgba(255,255,255,.14)); background:var(--bg-1,#1a1a1a); z-index:1; display:grid; place-items:center; font-size:10px; }
+.awh-rec-step.done .awh-rec-dot { border-color:var(--success,#4ade80); color:var(--success,#4ade80); }
+.awh-rec-step.active .awh-rec-dot { border-color:var(--warn,#fbbf24); box-shadow:0 0 0 3px color-mix(in srgb,var(--warn,#fbbf24) 22%,transparent); }
+.awh-rec-step-c { display:flex; flex-direction:column; gap:1px; min-width:0; }
+.awh-rec-step-t { font-size:var(--text-sm,.764rem); color:var(--ink-bright,#fff); }
+.awh-rec-step-s { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); }
+.awh-rec-count { font-family:var(--font-mono,monospace); font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); }
+.awh-rec-actions { display:flex; gap:8px; margin-top:10px; flex-wrap:wrap; }
+.awh-rec-skel { height:64px; border-radius:var(--radius-lg,14px); background:linear-gradient(90deg,var(--surface-1,rgba(255,255,255,.03)) 25%,var(--surface-2,rgba(255,255,255,.05)) 37%,var(--surface-1,rgba(255,255,255,.03)) 63%); background-size:400% 100%; animation:awh-rec-shimmer 1.4s ease infinite; }
+.awh-rec-empty-ill { font-size:26px; opacity:.5; margin-bottom:4px; }
+@keyframes awh-rec-shimmer { 0%{background-position:100% 0} 100%{background-position:-100% 0} }
+@media (prefers-reduced-motion: reduce){ .awh-rec-skel{animation:none} .awh-rec-step.active .awh-rec-dot{box-shadow:none} }
+`;
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const tag = document.createElement('style');
+ tag.id = STYLE_ID;
+ tag.textContent = STYLE;
+ document.head.appendChild(tag);
+}
+
+async function call(url, { method = 'GET', body = null } = {}) {
+ try {
+ const opts = { method, credentials: 'include', headers: {} };
+ if (body != null) {
+ opts.headers['content-type'] = 'application/json';
+ opts.body = JSON.stringify(body);
+ }
+ if (method !== 'GET') {
+ const token = await consumeCsrfToken();
+ if (token) opts.headers['x-csrf-token'] = token;
+ }
+ const r = await fetch(url, opts);
+ let j = null;
+ try { j = await r.json(); } catch { /* empty */ }
+ if (!r.ok) return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, detail: j?.detail || null };
+ return { ok: true, status: r.status, data: j?.data ?? j };
+ } catch (err) {
+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ }
+}
+
+function fmtDuration(ms) {
+ if (ms == null) return '';
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const d = Math.floor(s / 86400);
+ const h = Math.floor((s % 86400) / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ if (d > 0) return `${d}d ${h}h`;
+ if (h > 0) return `${h}h ${m}m`;
+ if (m > 0) return `${m}m`;
+ return `${s}s`;
+}
+
+registerWalletTab({
+ id: 'recovery',
+ label: 'Recovery',
+ order: 75,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const { escapeHtml, agentId, toast } = ctx;
+ let state = null;
+ let pollTimer = null;
+ let busy = false;
+
+ function setBusy(b) {
+ busy = b;
+ panel.querySelectorAll('button, input, select').forEach((el) => {
+ if (el.dataset.keepEnabled) return;
+ el.disabled = b;
+ });
+ }
+
+ async function load() {
+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/recovery`);
+ if (!res.ok) {
+ render(null, res);
+ return;
+ }
+ state = res.data;
+ render(state, null);
+ }
+
+ function renderLoading() {
+ panel.innerHTML = `
+ <div class="awh-card"><div class="awh-rec-skel"></div></div>
+ <div class="awh-card"><div class="awh-rec-skel"></div></div>`;
+ }
+
+ // ── render ──────────────────────────────────────────────────────────────
+ function render(data, err) {
+ if (err) {
+ panel.innerHTML = `
+ <div class="awh-card">
+ <p class="awh-empty">Couldn’t load recovery settings — ${escapeHtml(err.message || 'try again')}.
+ <button class="awh-btn" type="button" data-act="retry">Try again</button></p>
+ </div>`;
+ panel.querySelector('[data-act="retry"]')?.addEventListener('click', () => { renderLoading(); load(); });
+ return;
+ }
+ const cfg = data.config;
+ const guardians = (data.guardians || []).filter((g) => g.role === 'guardian');
+ const beneficiary = data.beneficiary;
+ const dm = data.dead_man || {};
+ const active = data.active_request;
+
+ panel.innerHTML = `
+ ${active ? activeProcessHTML(active) : ''}
+ ${rosterCardHTML(guardians, beneficiary, cfg)}
+ ${deadManCardHTML(dm, cfg, !!beneficiary)}
+ `;
+ wire(data);
+ }
+
+ function rosterCardHTML(guardians, beneficiary, cfg) {
+ const gItems = guardians.map((g) => guardianRowHTML(g, 'guardian')).join('');
+ const thresholdOpts = [];
+ for (let i = 1; i <= Math.max(1, guardians.length); i++) {
+ thresholdOpts.push(`<option value="${i}" ${cfg.effective_threshold === i ? 'selected' : ''}>${i} of ${guardians.length || 1}</option>`);
+ }
+ return `
+ <div class="awh-card">
+ <div class="awh-rec">
+ <div style="display:flex;gap:10px;align-items:flex-start;">
+ <span class="awh-rec-shield" aria-hidden="true">🛡</span>
+ <div>
+ <h2>Your recovery circle</h2>
+ <p class="awh-rec-lead">Guardians are real accounts you trust. If you ever lose access, ${cfg.effective_threshold || 1} of them approving — plus a 48-hour safety window only you can cancel — hands control of this agent and its wallet to you again. No private key is ever exported.</p>
+ </div>
+ </div>
+
+ <ul class="awh-rec-roster">${gItems || `<li class="awh-empty" style="padding:10px 0;"><span class="awh-rec-empty-ill" aria-hidden="true">🫂</span><br>No guardians yet. Add 2–3 people you trust — they’ll never see your funds, only the power to help you back in.</li>`}</ul>
+
+ <div class="awh-rec-add">
+ <input type="text" data-add="guardian" placeholder="@username or email" aria-label="Add a guardian by username or email" autocomplete="off" />
+ <button class="awh-btn" type="button" data-act="add-guardian">Add guardian</button>
+ </div>
+
+ ${guardians.length > 1 ? `
+ <div class="awh-rec-field" style="border-top:1px solid var(--stroke,rgba(255,255,255,.08));margin-top:10px;padding-top:12px;">
+ <label for="awh-rec-threshold">Approvals required<span class="hint">How many guardians must agree before a recovery can complete.</span></label>
+ <select id="awh-rec-threshold" data-field="threshold">${thresholdOpts.join('')}</select>
+ </div>` : ''}
+
+ <div class="awh-rec-field" style="border-top:1px solid var(--stroke,rgba(255,255,255,.08));margin-top:6px;padding-top:12px;">
+ <div style="min-width:0;flex:1;">
+ <label>Beneficiary<span class="hint">Inherits this agent if your dead-man’s switch ever fires.</span></label>
+ ${beneficiary ? `<div class="awh-rec-g" style="margin-top:8px;">
+ ${avatarHTML(beneficiary)}
+ <div class="awh-rec-g-main"><span class="awh-rec-g-name">${escapeHtml(beneficiary.label)}</span><span class="awh-rec-g-role">beneficiary${beneficiary.is_you ? ' · you' : ''}</span></div>
+ <span class="awh-rec-pill beneficiary">heir</span>
+ <button class="awh-rec-x" type="button" data-act="remove-beneficiary" aria-label="Remove beneficiary" title="Remove beneficiary">✕</button>
+ </div>` : ''}
+ </div>
+ </div>
+ ${!beneficiary ? `<div class="awh-rec-add">
+ <input type="text" data-add="beneficiary" placeholder="@username or email" aria-label="Set a beneficiary by username or email" autocomplete="off" />
+ <button class="awh-btn" type="button" data-act="set-beneficiary">Set beneficiary</button>
+ </div>` : ''}
+ </div>
+ </div>`;
+ }
+
+ function avatarHTML(g) {
+ if (g.avatar_url) return `<img src="${escapeHtml(g.avatar_url)}" alt="" loading="lazy" onerror="this.outerHTML='<span class=\\'awh-rec-ava\\'>${escapeHtml((g.label || '?').slice(0, 1).toUpperCase())}</span>'" />`;
+ return `<span class="awh-rec-ava" aria-hidden="true">${escapeHtml((g.label || '?').slice(0, 1).toUpperCase())}</span>`;
+ }
+
+ function guardianRowHTML(g) {
+ return `
+ <li class="awh-rec-g">
+ ${avatarHTML(g)}
+ <div class="awh-rec-g-main">
+ <span class="awh-rec-g-name">${escapeHtml(g.label)}${g.is_you ? ' (you)' : ''}</span>
+ <span class="awh-rec-g-role">guardian · since ${g.since ? new Date(g.since).toLocaleDateString() : '—'}</span>
+ </div>
+ <span class="awh-rec-pill guardian">trusted</span>
+ <button class="awh-rec-x" type="button" data-act="remove-guardian" data-uid="${escapeHtml(g.user_id)}" aria-label="Remove ${escapeHtml(g.label)}" title="Remove guardian">✕</button>
+ </li>`;
+ }
+
+ function deadManCardHTML(dm, cfg, hasBeneficiary) {
+ const enabled = !!dm.enabled;
+ const inactiveDays = dm.inactive_days ?? 0;
+ const inactivityDays = cfg.dead_man.inactivity_days;
+ const pct = enabled && inactivityDays ? Math.min(100, Math.round((inactiveDays / inactivityDays) * 100)) : 0;
+ const danger = pct >= 70;
+ const armIn = dm.ms_until_arm;
+ return `
+ <div class="awh-card">
+ <div class="awh-rec">
+ <div style="display:flex;gap:10px;align-items:flex-start;">
+ <span class="awh-rec-shield" aria-hidden="true">⏳</span>
+ <div style="flex:1;">
+ <h2>Dead-man’s switch</h2>
+ <p class="awh-rec-lead">If you go silent for a long time, control passes to your beneficiary — but only after a generous grace window, an explicit confirmation, and every chance for you to cancel by simply showing up. It never fires on a surprise.</p>
+ </div>
+ <label class="awh-rec-switch">
+ <input type="checkbox" data-field="dm-enabled" ${enabled ? 'checked' : ''} ${hasBeneficiary ? '' : 'disabled'} aria-label="Enable dead-man's switch" />
+ <span>${enabled ? 'On' : 'Off'}</span>
+ </label>
+ </div>
+ ${!hasBeneficiary ? `<p class="awh-empty" style="padding:6px 0;">Set a beneficiary above to enable the dead-man’s switch.</p>` : ''}
+
+ ${enabled ? `
+ <div class="awh-rec-bar ${danger ? 'danger' : ''}" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="Inactivity progress"><i style="width:${pct}%"></i></div>
+ <p class="awh-rec-step-s">You’ve been quiet for <strong>${inactiveDays}d</strong> of the ${inactivityDays}d threshold. ${armIn > 0 ? `Inheritance would arm in <strong>${fmtDuration(armIn)}</strong> if you stay away.` : 'The inactivity threshold has been reached.'}</p>
+ <div class="awh-rec-actions">
+ <button class="awh-btn awh-btn--primary" type="button" data-act="checkin" data-keep-enabled="1">✋ I’m here — reset the clock</button>
+ </div>
+ ` : ''}
+
+ <div class="awh-rec-field" style="border-top:1px solid var(--stroke,rgba(255,255,255,.08));margin-top:10px;padding-top:12px;">
+ <label for="awh-rec-inactivity">Trigger after no activity for<span class="hint">A login, trade, or check-in counts as activity.</span></label>
+ <span class="awh-rec-switch">
+ <input id="awh-rec-inactivity" type="number" min="7" max="365" step="1" value="${inactivityDays}" data-field="inactivity" style="width:80px;" /> days
+ </span>
+ </div>
+ <div class="awh-rec-field">
+ <label for="awh-rec-grace">Grace + confirmation window<span class="hint">After arming, control passes only once this elapses with confirmation.</span></label>
+ <span class="awh-rec-switch">
+ <input id="awh-rec-grace" type="number" min="1" max="90" step="1" value="${cfg.dead_man.grace_days}" data-field="grace" style="width:80px;" /> days
+ </span>
+ </div>
+ <div class="awh-rec-actions">
+ <button class="awh-btn" type="button" data-act="save-dm">Save switch settings</button>
+ </div>
+ </div>
+ </div>`;
+ }
+
+ function activeProcessHTML(p) {
+ const isInheritance = p.kind === 'inheritance';
+ const title = isInheritance ? 'Inheritance in progress' : 'Recovery in progress';
+ const danger = p.status === 'ready';
+ const approvalsDone = p.approvals >= p.approvals_required && p.approvals_required > 0;
+ const steps = [
+ { t: isInheritance ? 'Switch armed' : 'Recovery requested', s: `Opened ${new Date(p.created_at).toLocaleString()}`, done: true, active: false },
+ { t: p.approvals_required > 0 ? `Guardian approvals (${p.approvals}/${p.approvals_required})` : 'Beneficiary confirmation', s: approvalsDone || (p.approvals_required === 0 && !p.needs_beneficiary_confirmation) ? 'Threshold met' : 'Awaiting approvals', done: approvalsDone || (p.approvals_required === 0 && !p.needs_beneficiary_confirmation), active: !approvalsDone && p.status === 'pending_approvals' },
+ { t: isInheritance ? 'Grace window' : 'Safety time-lock', s: p.ms_until_unlock > 0 ? `${fmtDuration(p.ms_until_unlock)} remaining — you can still cancel` : (p.status === 'ready' ? 'Elapsed' : 'Starts after approvals'), done: p.ms_until_unlock <= 0 && (p.status === 'ready' || p.status === 'completed'), active: p.status === 'time_locked' },
+ { t: 'Control transfers', s: p.status === 'completed' ? 'Done' : 'Final step', done: p.status === 'completed', active: p.status === 'ready' },
+ ];
+ // In-character narration of REAL state.
+ const narrate = isInheritance
+ ? `“My owner has been quiet. Out of caution my guardians are confirming a hand-off to my beneficiary — but one sign of life from you stops everything.”`
+ : `“Someone is trying to recover me. My guardians are weighing in, and a safety window is running. If this isn’t you, you have until it ends to shut it down.”`;
+ return `
+ <div class="awh-card awh-rec-proc ${danger ? 'danger' : ''}">
+ <div class="awh-rec">
+ <div style="display:flex;gap:10px;align-items:center;">
+ <span class="awh-rec-shield" aria-hidden="true">${isInheritance ? '🕊' : '🔓'}</span>
+ <div style="flex:1;"><h2 style="margin:0;">${escapeHtml(title)}</h2><span class="awh-rec-count">${escapeHtml(p.status)}</span></div>
+ </div>
+ <div class="awh-rec-narrate">${escapeHtml(narrate)}</div>
+ <ul class="awh-rec-steps">
+ ${steps.map((s) => `
+ <li class="awh-rec-step ${s.done ? 'done' : ''} ${s.active ? 'active' : ''}">
+ <span class="awh-rec-dot">${s.done ? '✓' : ''}</span>
+ <span class="awh-rec-step-c"><span class="awh-rec-step-t">${escapeHtml(s.t)}</span><span class="awh-rec-step-s">${s.s}</span></span>
+ </li>`).join('')}
+ </ul>
+ <div class="awh-rec-actions">
+ <button class="awh-btn awh-btn--danger" type="button" data-act="cancel-process" data-rid="${escapeHtml(p.id)}" data-keep-enabled="1">${isInheritance ? '✋ I’m here — cancel inheritance' : 'Stop this recovery — it’s not me'}</button>
+ </div>
+ <p class="awh-rec-step-s" style="margin-top:8px;">Cancelling is instant and reversible-proof: control stays with you and the wallet is unfrozen. This is logged in your custody trail.</p>
+ </div>
+ </div>`;
+ }
+
+ // ── wire actions ────────────────────────────────────────────────────────
+ function wire(data) {
+ const q = (sel) => panel.querySelector(sel);
+ const guardians = (data.guardians || []).filter((g) => g.role === 'guardian');
+ const beneficiary = data.beneficiary;
+
+ // Build the full handle list from current roster (labels aren't handles,
+ // so we re-send user_ids for existing members + the new handle).
+ const guardianHandles = () => guardians.map((g) => g.user_id);
+ const beneficiaryHandle = () => (beneficiary && !beneficiary.is_you ? beneficiary.user_id : null);
+
+ async function saveConfig(patch, successMsg) {
+ if (busy) return;
+ setBusy(true);
+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/recovery`, { method: 'PUT', body: patch });
+ setBusy(false);
+ if (!res.ok) { toast(res.message || 'Could not save'); return; }
+ if (successMsg) toast(successMsg);
+ await load();
+ }
+
+ q('[data-act="add-guardian"]')?.addEventListener('click', () => {
+ const input = q('[data-add="guardian"]');
+ const handle = (input?.value || '').trim();
+ if (!handle) { input?.focus(); return; }
+ saveConfig({ guardians: [...guardianHandles(), handle], beneficiary: beneficiaryHandle() }, 'Guardian added');
+ });
+ q('[data-add="guardian"]')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') q('[data-act="add-guardian"]')?.click(); });
+
+ panel.querySelectorAll('[data-act="remove-guardian"]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const uid = btn.dataset.uid;
+ if (!confirm('Remove this guardian? They’ll no longer be able to help you recover this agent.')) return;
+ saveConfig({ guardians: guardianHandles().filter((u) => u !== uid), beneficiary: beneficiaryHandle() }, 'Guardian removed');
+ });
+ });
+
+ q('[data-act="set-beneficiary"]')?.addEventListener('click', () => {
+ const input = q('[data-add="beneficiary"]');
+ const handle = (input?.value || '').trim();
+ if (!handle) { input?.focus(); return; }
+ saveConfig({ guardians: guardianHandles(), beneficiary: handle }, 'Beneficiary set');
+ });
+ q('[data-add="beneficiary"]')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') q('[data-act="set-beneficiary"]')?.click(); });
+
+ q('[data-act="remove-beneficiary"]')?.addEventListener('click', () => {
+ if (!confirm('Remove the beneficiary? This also turns off the dead-man’s switch.')) return;
+ saveConfig({ guardians: guardianHandles(), beneficiary: null, dead_man: { enabled: false } }, 'Beneficiary removed');
+ });
+
+ q('[data-field="threshold"]')?.addEventListener('change', (e) => {
+ saveConfig({ guardians: guardianHandles(), beneficiary: beneficiaryHandle(), threshold: Number(e.target.value) }, 'Threshold updated');
+ });
+
+ q('[data-field="dm-enabled"]')?.addEventListener('change', (e) => {
+ const enabled = e.target.checked;
+ const inactivity = Number(q('[data-field="inactivity"]')?.value) || data.config.dead_man.inactivity_days;
+ const grace = Number(q('[data-field="grace"]')?.value) || data.config.dead_man.grace_days;
+ saveConfig({ guardians: guardianHandles(), beneficiary: beneficiaryHandle(), dead_man: { enabled, inactivity_days: inactivity, grace_days: grace } }, enabled ? 'Dead-man’s switch on' : 'Dead-man’s switch off');
+ });
+
+ q('[data-act="save-dm"]')?.addEventListener('click', () => {
+ const enabled = !!q('[data-field="dm-enabled"]')?.checked;
+ const inactivity = Number(q('[data-field="inactivity"]')?.value);
+ const grace = Number(q('[data-field="grace"]')?.value);
+ if (inactivity < 7 || inactivity > 365) { toast('Inactivity must be 7–365 days'); return; }
+ if (grace < 1 || grace > 90) { toast('Grace must be 1–90 days'); return; }
+ saveConfig({ guardians: guardianHandles(), beneficiary: beneficiaryHandle(), dead_man: { enabled, inactivity_days: inactivity, grace_days: grace } }, 'Switch settings saved');
+ });
+
+ q('[data-act="checkin"]')?.addEventListener('click', async () => {
+ if (busy) return;
+ setBusy(true);
+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/recovery/checkin`, { method: 'POST', body: {} });
+ setBusy(false);
+ toast(res.ok ? 'Checked in — you’re marked active' : (res.message || 'Check-in failed'));
+ await load();
+ });
+
+ q('[data-act="cancel-process"]')?.addEventListener('click', async (e) => {
+ const rid = e.currentTarget.dataset.rid;
+ if (!confirm('Cancel this process? Control stays with you and the wallet is unfrozen.')) return;
+ if (busy) return;
+ setBusy(true);
+ const res = await call(`/api/agents/${encodeURIComponent(agentId)}/recovery/requests/${encodeURIComponent(rid)}/cancel`, { method: 'POST', body: {} });
+ setBusy(false);
+ toast(res.ok ? 'Cancelled — you’re still in control' : (res.message || 'Could not cancel'));
+ await load();
+ });
+ }
+
+ function startPoll() {
+ stopPoll();
+ // Poll only while a process is live so the countdown stays honest.
+ pollTimer = setInterval(() => {
+ if (document.hidden) return;
+ if (state?.active_request) load();
+ }, 15000);
+ }
+ function stopPoll() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }
+
+ return {
+ onShow() { renderLoading(); load(); startPoll(); },
+ onHide() { stopPoll(); },
+ destroy() { stopPoll(); panel.innerHTML = ''; },
+ };
+ },
+});
diff --git a/src/agent-wallet-hub/tabs/reputation.js b/src/agent-wallet-hub/tabs/reputation.js
new file mode 100644
index 000000000..907877808
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/reputation.js
@@ -0,0 +1,52 @@
+/**
+ * Agent Wallet hub — Reputation tab ("why this wallet is trusted").
+ *
+ * The full, auditable breakdown of the agent's wallet-trust score: every real
+ * input (tenure, settled volume, tips from distinct funded wallets, settlement
+ * reliability, fork lineage, on-chain identity), its point contribution, and a
+ * link to the real evidence. It also surfaces what does NOT count (self-tips,
+ * single-counterparty volume) so the score reads as credible rather than a black
+ * box — transparency is the trust.
+ *
+ * Visible to owner AND visitor — the score is public, so both see the same
+ * number. The OWNER additionally sees actionable guidance ("verify your on-chain
+ * identity to raise trust") tied to real, available actions; the server strips
+ * that block for everyone else.
+ *
+ * All data comes from GET /api/agents/:id/reputation, computed entirely from real
+ * ledger + chain reads (api/_lib/trust/wallet-reputation.js). Nothing is faked.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { reputationPanelEl, ensureReputationStyles } from '../../shared/agent-reputation.js';
+
+registerWalletTab({
+ id: 'reputation',
+ label: 'Trust',
+ order: 25, // between Pulse (15) and Deposit (20)… sorts after both; sits early.
+ ownerOnly: false,
+ mount({ panel, ctx }) {
+ ensureReputationStyles();
+ panel.innerHTML = '';
+ const wrap = document.createElement('div');
+ wrap.className = 'awh-rep-tab';
+ const intro = document.createElement('p');
+ intro.className = 'awh-rep-intro';
+ intro.textContent =
+ 'A real, non-gameable credibility score derived entirely from this wallet’s on-chain and ledger history. Backed by money and time — and fully explainable below.';
+ wrap.appendChild(intro);
+ wrap.appendChild(reputationPanelEl(ctx.agentId, {}));
+ panel.appendChild(wrap);
+
+ if (typeof document !== 'undefined' && !document.getElementById('awh-rep-style')) {
+ const tag = document.createElement('style');
+ tag.id = 'awh-rep-style';
+ tag.textContent = `
+.awh-rep-tab{display:flex;flex-direction:column;gap:var(--space-4,16px)}
+.awh-rep-intro{margin:0;font-size:var(--text-sm,.8125rem);line-height:1.5;color:var(--ink-dim,#9ca3af)}
+`;
+ document.head.appendChild(tag);
+ }
+ return {};
+ },
+});
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 5b96868fe..61e4077e3 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -622,22 +622,45 @@ function showReputationPanel(card, rep) {
existing.remove();
return;
}
- const score = rep?.score ?? rep?.rating ?? null;
- const count = rep?.reviews_count ?? rep?.count ?? 0;
+ // Unified wallet-trust score (0–100) from /api/agents/:id/reputation.
+ const isNew = rep?.isNew === true;
+ const score = typeof rep?.score === 'number' ? rep.score : null;
+ const tier = rep?.tierLabel || rep?.tier || null;
+ const accent = rep?.accent || 'var(--nxt-accent, #c4b5fd)';
+ const totals = rep?.totals || {};
const panel = document.createElement('div');
panel.setAttribute('data-reputation-panel', 'true');
panel.style.cssText = 'margin-top:14px;padding-top:14px;border-top:1px solid var(--nxt-stroke)';
+ const pillars = Array.isArray(rep?.pillars) ? rep.pillars : [];
panel.innerHTML = `
- <div style="font-size:12.5px;font-weight:600;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:10px">Reputation</div>
+ <div style="font-size:12.5px;font-weight:600;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:10px">Wallet trust</div>
${
- score !== null
- ? `<div style="display:flex;align-items:baseline;gap:8px">
- <span style="font-size:32px;font-weight:700;color:var(--nxt-ink)">${Number(score).toFixed(1)}</span>
- <span style="font-size:13px;color:var(--nxt-ink-dim)">/ 5.0 · ${count} review${count === 1 ? '' : 's'}</span>
- </div>`
- : `<div style="color:var(--nxt-ink-dim);font-size:13px">No reviews yet.</div>`
+ isNew
+ ? `<div style="color:var(--nxt-ink-dim);font-size:13px">New agent — no track record yet. Trust is earned through real activity.</div>`
+ : score !== null
+ ? `<div style="display:flex;align-items:baseline;gap:8px">
+ <span style="font-size:32px;font-weight:700;color:var(--nxt-ink)">${Math.round(score)}</span>
+ <span style="font-size:13px;color:var(--nxt-ink-dim)">/ 100 · <span style="color:${esc(accent)};font-weight:600">${esc(tier || '')}</span></span>
+ </div>
+ <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:10px">
+ ${[`$${fmtNum(totals.settled_usd)} volume`, `${totals.distinct_tippers || 0} tippers`, `${totals.confirmed_payments || 0} payments`, `${totals.fork_count || 0} forks`, totals.verified ? '✓ verified' : '']
+ .filter(Boolean)
+ .map((t) => `<span class="dn-tag">${esc(t)}</span>`)
+ .join('')}
+ </div>
+ ${
+ pillars.length
+ ? `<div style="margin-top:12px;display:flex;flex-direction:column;gap:7px">${pillars
+ .map(
+ (p) =>
+ `<div><div style="display:flex;justify-content:space-between;font-size:12px;color:var(--nxt-ink-dim);margin-bottom:3px"><span>${esc(p.label)}</span><span>${p.points}/${p.max}</span></div><div style="height:4px;border-radius:2px;background:var(--nxt-stroke);overflow:hidden"><div style="height:100%;width:${Math.round((p.points / (p.max || 25)) * 100)}%;background:${esc(accent)}"></div></div></div>`,
+ )
+ .join('')}</div>`
+ : ''
+ }
+ <a href="/agent/${encodeURIComponent(rep.agent_id || '')}/wallet#reputation" style="display:inline-block;margin-top:12px;font-size:12.5px;color:${esc(accent)};text-decoration:none">View full breakdown →</a>`
+ : `<div style="color:var(--nxt-ink-dim);font-size:13px">Trust score unavailable right now.</div>`
}
- ${rep?.tags?.length ? `<div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:10px">${rep.tags.map((t) => `<span class="dn-tag">${esc(t)}</span>`).join('')}</div>` : ''}
`;
card.appendChild(panel);
}
diff --git a/src/element.js b/src/element.js
index 41e6875d5..7a9533763 100644
--- a/src/element.js
+++ b/src/element.js
@@ -624,6 +624,7 @@ class Agent3DElement extends HTMLElement {
'chat',
'clip',
'framing',
+ 'wallet',
];
}
@@ -756,6 +757,11 @@ class Agent3DElement extends HTMLElement {
disconnectedCallback() {
this._teardown();
this._cleanupReducedMotion();
+ if (this._walletMount) {
+ try { this._walletMount.destroy(); } catch { /* already gone */ }
+ this._walletMount = null;
+ this._walletAgentId = null;
+ }
}
// prefers-reduced-motion lives at the element level (survives budget-driven
@@ -1017,6 +1023,56 @@ class Agent3DElement extends HTMLElement {
// Suggestion chips visible while the chat is empty.
this._renderSuggestions();
}
+
+ // The agent's portable wallet — works in every mode, not just chat. Opt-in
+ // via the `wallet` attribute so a non-wallet embed pays zero cost. Mounts as
+ // soon as we know the agent id (now if `agent-id` is set, else after boot
+ // resolves the manifest).
+ this._mountWalletAffordance();
+ }
+
+ // Mount (or re-mount) the self-contained wallet chip into the shadow root. The
+ // embed is the VISITOR view by construction: the portable wallet only ever
+ // renders Tip + "open on three.ws" — never an owner control, which only a real
+ // three.ws session can unlock. Re-entrant: safe to call repeatedly; it no-ops
+ // once mounted for the current agent and re-mounts if the agent id changes.
+ _mountWalletAffordance() {
+ if (!this.hasAttribute('wallet') || !this.shadowRoot) return;
+ const agentId = this.getAttribute('agent-id') || this._manifest?.id?.agentId || '';
+ const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(agentId);
+ if (!isUuid) return; // wait for a real id; boot will call us again
+ if (this._walletAgentId === agentId && this._walletMount) return;
+ if (this._walletMount) {
+ try { this._walletMount.destroy(); } catch { /* already gone */ }
+ this._walletMount = null;
+ this._walletHostEl?.remove();
+ }
+
+ const host = document.createElement('div');
+ host.className = 'wallet-affordance';
+ host.part = 'wallet-affordance';
+ Object.assign(host.style, {
+ position: 'absolute', left: '10px', bottom: '10px', zIndex: '14',
+ maxWidth: 'calc(100% - 20px)',
+ });
+ this.shadowRoot.appendChild(host);
+ this._walletHostEl = host;
+ this._walletAgentId = agentId;
+
+ const origin = this.getAttribute('api-base') || _scriptOrigin || window.location.origin;
+ const mode = (this.getAttribute('wallet') || '').trim().toLowerCase();
+ import('./shared/portable-wallet.js')
+ .then(({ mountPortableWallet }) => {
+ if (!host.isConnected || this._walletAgentId !== agentId) return;
+ this._walletMount = mountPortableWallet(host, {
+ agentId,
+ origin,
+ variant: mode === 'card' ? 'card' : 'chip',
+ tip: mode !== 'identity', // `wallet="identity"` = read-only chip, no tip flow
+ name: this._manifest?.name || this.getAttribute('name') || null,
+ });
+ })
+ .catch(() => { /* optional affordance — never break the viewer */ });
}
_renderSuggestions() {
@@ -1479,6 +1535,9 @@ class Agent3DElement extends HTMLElement {
? a
: null;
})();
+ // Now that the manifest resolved the real agent id, the wallet affordance
+ // (if opted in via the `wallet` attribute) can hydrate against it.
+ this._mountWalletAffordance();
if (_backendId) {
try {
const _policyBase = _scriptOrigin || window.location.origin;
diff --git a/src/galaxy.js b/src/galaxy.js
index 94aeecd05..93e9f1235 100644
--- a/src/galaxy.js
+++ b/src/galaxy.js
@@ -31,6 +31,11 @@ function cacheEls() {
'gxCardDesc', 'gxCardMeta', 'gxCardView', 'gxCardChat',
'gxResults', 'gxResultsList', 'gxResultsClose', 'gxResultsLabel',
'gxLoading', 'gxEmpty', 'gxEmptySub', 'gxError', 'gxErrorSub', 'gxRetry', 'gxHint',
+ // Money-Cam
+ 'gxMoneyToggle', 'gxMoneyCam', 'gxMcLiveDot', 'gxMcClose',
+ 'gxMcModeLive', 'gxMcModeReplay', 'gxMcStats', 'gxMcReplay', 'gxMcPlay',
+ 'gxMcScrub', 'gxMcSpeed', 'gxMcTime', 'gxMcFilters', 'gxMcTicker', 'gxMcNote',
+ 'gxFlow', 'gxFlowClose', 'gxFlowBody',
]) {
els[id] = $(id);
}
@@ -57,6 +62,41 @@ let rafPending = false;
// Camera fly-to tween
const fly = { active: false, t: 0, dur: 0.9, fromPos: new THREE.Vector3(), toPos: new THREE.Vector3(), fromTgt: new THREE.Vector3(), toTgt: new THREE.Vector3() };
+// ── Money-Cam ────────────────────────────────────────────────────────────────
+// The galaxy as the platform's live economy: every real, on-chain transfer that
+// touches a star is rendered as light moving between them. Data is /api/galaxy/flows
+// (agent↔agent edges + one-sided flares), all real — when it's quiet, it's calm.
+let flowLayer = null;
+let pollTimer = null;
+const FLOW_COLORS = {
+ tip: '#4ade80', // inbound value — success green
+ trade: '#4589ff', // a trade — brand blue
+ snipe: '#fbbf24', // a snipe — warn amber
+ payment: '#c4b5fd', // agent→agent payment — wallet violet
+ launch: '#ffd27a', // a coin launch — gold
+};
+const LIVE_POLL_MS = 6000; // cheap delta poll cadence while live + visible
+const REPLAY_DURATION_S = 30; // wall-clock to replay the whole loaded window at 1×
+const money = {
+ active: false,
+ mode: 'live', // 'live' | 'replay'
+ type: 'all', // all | tips | trades | payments | launches
+ history: [], // loaded flows, ascending by ts (the honest data window)
+ seen: new Set(), // flow ids already enqueued/animated (dedupe across polls)
+ queue: [], // flows waiting to animate (paced, never a frame-dropping burst)
+ releaseAcc: 0,
+ headCursor: null, // newest cursor — handed back as ?since= to poll the delta
+ loading: false,
+ pollFails: 0,
+ lastServerTime: null,
+ // replay
+ replayT: 1, // 0..1 playhead across the window
+ replaySpeed: 1,
+ replayPlaying: false,
+ replayPtr: 0, // index in history spawned up to
+ nodeVec: new Map(), // agentId → THREE.Vector3 (cached node world position)
+};
+
// Public debug/verification surface.
const dbg = (window.__galaxy = {
ready: false,
@@ -200,6 +240,16 @@ function renderGalaxy(data) {
// Frame the whole cloud.
flyTo(new THREE.Vector3(0, 36, 322), new THREE.Vector3(0, 0, 0), 0.001);
+
+ // Money-Cam: node positions changed with this snapshot — drop the cache and
+ // (re)enable the entry. If the cam is already open, re-seed against the new map.
+ money.nodeVec = new Map();
+ if (els.gxMoneyToggle) els.gxMoneyToggle.disabled = false;
+ if (money.active) {
+ flowLayer?.reset();
+ money.queue = [];
+ loadWindow();
+ }
}
// ── Net-worth glow (real wallet value lights the stars) ──────────────────────
@@ -473,6 +523,18 @@ function selectAgent(index, fly = false) {
// is a public read-only map, so the viewer is always a non-owner here.
const walletChip = walletChipHTML(a, { isOwner: false, showPending: false, link: true, tip: true });
if (walletChip) chips.push(walletChip);
+ // Money-Cam cross-link: how many real flows in the current window touch this
+ // agent — turns the inspect card into a jump-off into the live economy.
+ if (money.active && money.history.length) {
+ const involved = money.history.filter(
+ (f) => f.actor?.id === a.id || f.from?.id === a.id || f.to?.id === a.id,
+ ).length;
+ if (involved) {
+ chips.push(
+ `<span class="gx-chip gx-chip-flow" title="Public flows touching this agent in the current Money-Cam window">◉ ${involved} flow${involved > 1 ? 's' : ''} in view</span>`,
+ );
+ }
+ }
els.gxCardMeta.innerHTML = chips.join('');
wireWalletChips(els.gxCardMeta);
@@ -517,6 +579,7 @@ function setupThree() {
controls.addEventListener('end', scheduleIdle);
addBackgroundStars();
+ flowLayer = createFlowLayer(scene);
raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 4.2;
@@ -599,6 +662,11 @@ function tick() {
controls.update();
updateClusterLabels();
+ if (flowLayer) flowLayer.update(dt);
+ if (money.active) {
+ paceQueue(dt);
+ if (money.mode === 'replay') replayTick(dt);
+ }
renderer.render(scene, camera);
}
@@ -674,10 +742,19 @@ function onPointerDown(e) {
renderer.domElement.removeEventListener('pointerup', onUp);
if (!downAt) return;
const moved = Math.hypot(ev.clientX - downAt.x, ev.clientY - downAt.y);
- // A click (not a drag) on a star selects it; on empty space, deselect.
+ // A click (not a drag) on a star selects it; on empty space, deselect — but
+ // in Money-Cam a click near a flowing edge opens that real transfer instead.
if (moved < 5) {
if (downAt.idx >= 0) selectAgent(downAt.idx, true);
- else deselect();
+ else {
+ let picked = null;
+ if (money.active && flowLayer) {
+ raycaster.setFromCamera(pointer, camera);
+ picked = flowLayer.pick(raycaster);
+ }
+ if (picked) openFlow(picked, false);
+ else deselect();
+ }
}
downAt = null;
};
@@ -705,9 +782,62 @@ function bindUI() {
els.gxLegendToggle.setAttribute('aria-expanded', String(!collapsed));
els.gxLegendToggle.textContent = collapsed ? '+' : '−';
});
+ // ── Money-Cam controls ──────────────────────────────────────────────────
+ els.gxMoneyToggle.addEventListener('click', toggleMoneyCam);
+ els.gxMcClose.addEventListener('click', closeMoneyCam);
+ els.gxMcModeLive.addEventListener('click', () => setMcMode('live'));
+ els.gxMcModeReplay.addEventListener('click', () => setMcMode('replay'));
+ els.gxMcFilters.addEventListener('click', (e) => {
+ const b = e.target.closest('.gx-mc-filter');
+ if (b) setMcType(b.dataset.type);
+ });
+ els.gxMcTicker.addEventListener('click', (e) => {
+ const row = e.target.closest('.gx-mc-row');
+ if (!row) return;
+ const f = flowById(row.dataset.flow);
+ if (f) openFlow(f, true);
+ });
+ els.gxMcPlay.addEventListener('click', () => {
+ if (money.replayT >= 1) enterReplayWindow();
+ money.replayPlaying = !money.replayPlaying;
+ syncPlayBtn();
+ });
+ els.gxMcScrub.addEventListener('input', () => {
+ money.replayPlaying = false;
+ syncPlayBtn();
+ money.replayT = Number(els.gxMcScrub.value) / 1000;
+ // Move the playhead without retro-animating: advance the spawn pointer to
+ // the first flow past the new position.
+ const [t0, t1] = windowSpan();
+ const span = Math.max(1, t1 - t0);
+ const ptr = money.history.findIndex((f) => (new Date(f.ts).getTime() - t0) / span > money.replayT);
+ money.replayPtr = ptr < 0 ? money.history.length : ptr;
+ updateReplayTime();
+ });
+ els.gxMcSpeed.addEventListener('click', () => {
+ const order = [1, 2, 4];
+ money.replaySpeed = order[(order.indexOf(money.replaySpeed) + 1) % order.length];
+ els.gxMcSpeed.textContent = `${money.replaySpeed}×`;
+ });
+ els.gxFlowClose.addEventListener('click', closeFlow);
+ document.addEventListener('visibilitychange', () => {
+ if (!money.active) return;
+ if (document.hidden) stopPolling();
+ else if (money.mode === 'live') { startPolling(); pollDelta(); }
+ updateLiveDot();
+ });
+
window.addEventListener('keydown', (e) => {
+ const t = e.target;
+ const typing = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);
+ if (!typing && (e.key === 'm' || e.key === 'M')) {
+ toggleMoneyCam();
+ return;
+ }
if (e.key === 'Escape') {
- if (!els.gxCard.hidden) deselect();
+ if (!els.gxFlow.hidden) closeFlow();
+ else if (money.active) closeMoneyCam();
+ else if (!els.gxCard.hidden) deselect();
else if (state.focusMode) clearSearch();
}
});
@@ -745,7 +875,10 @@ function disposePoints() {
}
function dispose() {
try {
+ stopPolling();
renderer?.setAnimationLoop(null);
+ flowLayer?.dispose();
+ flowLayer = null;
disposePoints();
renderer?.dispose();
} catch {
@@ -780,6 +913,710 @@ function easeInOut(t) {
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
+// ══════════════════════════════════════════════════════════════════════════════
+// Money-Cam — the live economy layer
+// ══════════════════════════════════════════════════════════════════════════════
+
+// GPU-friendly flow renderer: pooled arcs + a single Points cloud of travelling
+// "photons" + a single Points cloud of impact/flare "rings". Everything is fixed
+// capacity, so a burst of flows can never grow unbounded or drop frames — excess
+// flows queue and animate as slots free. Every photon traces a real transfer.
+function createFlowLayer(scene) {
+ const PR = Math.min(devicePixelRatio || 1, 2);
+ const ARC_MAX = 56;
+ const ARC_SEG = 22;
+ const PHOTON_MAX = ARC_MAX;
+ const RING_MAX = 96;
+ const ARC_BASE = 0.34;
+
+ // Arc pool — faint bezier trails the photon rides along.
+ const arcPool = [];
+ for (let i = 0; i < ARC_MAX; i++) {
+ const geom = new THREE.BufferGeometry();
+ geom.setAttribute('position', new THREE.BufferAttribute(new Float32Array(ARC_SEG * 3), 3));
+ const mat = new THREE.LineBasicMaterial({
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+ const line = new THREE.Line(geom, mat);
+ line.frustumCulled = false;
+ line.visible = false;
+ line.renderOrder = 2;
+ scene.add(line);
+ arcPool.push({ line, geom, mat, free: true });
+ }
+ const acquireArc = () => {
+ for (const a of arcPool) if (a.free) { a.free = false; return a; }
+ return null;
+ };
+
+ // Photons — one travelling point per active edge.
+ const photonPos = new Float32Array(PHOTON_MAX * 3);
+ const photonCol = new Float32Array(PHOTON_MAX * 3);
+ const photonSize = new Float32Array(PHOTON_MAX);
+ const photonAlpha = new Float32Array(PHOTON_MAX);
+ const photonGeom = new THREE.BufferGeometry();
+ photonGeom.setAttribute('position', new THREE.BufferAttribute(photonPos, 3));
+ photonGeom.setAttribute('aColor', new THREE.BufferAttribute(photonCol, 3));
+ photonGeom.setAttribute('aSize', new THREE.BufferAttribute(photonSize, 1));
+ photonGeom.setAttribute('aAlpha', new THREE.BufferAttribute(photonAlpha, 1));
+ const photonMat = new THREE.ShaderMaterial({
+ uniforms: { uPixelRatio: { value: PR } },
+ vertexShader: FLOW_PHOTON_VERT,
+ fragmentShader: FLOW_PHOTON_FRAG,
+ transparent: true,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+ const photons = new THREE.Points(photonGeom, photonMat);
+ photons.frustumCulled = false;
+ photons.renderOrder = 3;
+ scene.add(photons);
+ const photonFree = [];
+ for (let i = PHOTON_MAX - 1; i >= 0; i--) photonFree.push(i);
+
+ // Rings — expanding halos for an edge's arrival and for one-sided flares.
+ const ringPos = new Float32Array(RING_MAX * 3);
+ const ringCol = new Float32Array(RING_MAX * 3);
+ const ringT = new Float32Array(RING_MAX).fill(1);
+ const ringSize = new Float32Array(RING_MAX);
+ const ringAge = new Float32Array(RING_MAX);
+ const ringDur = new Float32Array(RING_MAX).fill(1);
+ const ringActive = new Uint8Array(RING_MAX);
+ const ringGeom = new THREE.BufferGeometry();
+ ringGeom.setAttribute('position', new THREE.BufferAttribute(ringPos, 3));
+ ringGeom.setAttribute('aColor', new THREE.BufferAttribute(ringCol, 3));
+ ringGeom.setAttribute('aT', new THREE.BufferAttribute(ringT, 1));
+ ringGeom.setAttribute('aSize', new THREE.BufferAttribute(ringSize, 1));
+ const ringMat = new THREE.ShaderMaterial({
+ uniforms: { uPixelRatio: { value: PR }, uGrow: { value: REDUCED_MOTION ? 0.6 : 3.0 } },
+ vertexShader: FLOW_RING_VERT,
+ fragmentShader: FLOW_RING_FRAG,
+ transparent: true,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+ const rings = new THREE.Points(ringGeom, ringMat);
+ rings.frustumCulled = false;
+ rings.renderOrder = 3;
+ scene.add(rings);
+ let ringCursor = 0;
+
+ // Invisible pick points at active-edge midpoints → click an edge to inspect it.
+ const pickPos = new Float32Array(ARC_MAX * 3).fill(1e7);
+ const pickGeom = new THREE.BufferGeometry();
+ pickGeom.setAttribute('position', new THREE.BufferAttribute(pickPos, 3));
+ const pickPoints = new THREE.Points(
+ pickGeom,
+ new THREE.PointsMaterial({ size: 0.01, transparent: true, opacity: 0, depthWrite: false }),
+ );
+ pickPoints.frustumCulled = false;
+ pickPoints.renderOrder = 4;
+ scene.add(pickPoints);
+
+ const edges = [];
+ const tmpV = new THREE.Vector3();
+ const tmpMid = new THREE.Vector3();
+ const tmpPerp = new THREE.Vector3();
+ const UP = new THREE.Vector3(0, 1, 0);
+ const colorCache = new Map();
+ const col = (hex) => {
+ let c = colorCache.get(hex);
+ if (!c) { c = new THREE.Color(hex); colorCache.set(hex, c); }
+ return c;
+ };
+ const usdSize = (usd, base) =>
+ base + (22 - base) * Math.min(1, Math.log1p(Number(usd) || 0) / Math.log1p(5000));
+ const usdDur = (usd) => 1.5 + 1.0 * Math.min(1, Math.log1p(Number(usd) || 0) / Math.log1p(2000));
+ const ringSizeFor = (flow) => (flow.kind === 'launch' ? 16 : usdSize(flow.usd, 9));
+
+ function spawnRing(pos, color, size, kind) {
+ const s = ringCursor;
+ ringCursor = (ringCursor + 1) % RING_MAX;
+ ringPos[s * 3] = pos.x; ringPos[s * 3 + 1] = pos.y; ringPos[s * 3 + 2] = pos.z;
+ ringCol[s * 3] = color.r; ringCol[s * 3 + 1] = color.g; ringCol[s * 3 + 2] = color.b;
+ ringSize[s] = size;
+ ringAge[s] = 0;
+ ringDur[s] = kind === 'launch' ? 1.7 : 1.15;
+ ringActive[s] = 1;
+ ringT[s] = 0;
+ ringGeom.getAttribute('position').needsUpdate = true;
+ ringGeom.getAttribute('aColor').needsUpdate = true;
+ ringGeom.getAttribute('aSize').needsUpdate = true;
+ }
+
+ function freeEdge(e, i) {
+ if (e.slot >= 0) { photonAlpha[e.slot] = 0; photonSize[e.slot] = 0; photonFree.push(e.slot); e.slot = -1; }
+ e.arc.free = true;
+ e.arc.line.visible = false;
+ e.arc.mat.opacity = 0;
+ edges.splice(i, 1);
+ }
+
+ function spawnEdge(flow, a, b) {
+ const slot = photonFree.pop();
+ if (slot == null) return false;
+ const arc = acquireArc();
+ if (!arc) { photonFree.push(slot); return false; }
+
+ const dist = a.distanceTo(b);
+ tmpMid.copy(a).add(b).multiplyScalar(0.5);
+ tmpPerp.subVectors(b, a).normalize().cross(UP);
+ if (tmpPerp.lengthSq() < 1e-4) tmpPerp.set(1, 0, 0);
+ tmpPerp.normalize().multiplyScalar(dist * 0.18);
+ tmpMid.add(tmpPerp).addScaledVector(UP, dist * 0.1);
+ const curve = new THREE.QuadraticBezierCurve3(a.clone(), tmpMid.clone(), b.clone());
+
+ const pos = arc.geom.getAttribute('position');
+ for (let i = 0; i < ARC_SEG; i++) {
+ curve.getPoint(i / (ARC_SEG - 1), tmpV);
+ pos.setXYZ(i, tmpV.x, tmpV.y, tmpV.z);
+ }
+ pos.needsUpdate = true;
+
+ const cc = col(FLOW_COLORS[flow.kind] || '#9fb4d6');
+ arc.mat.color.copy(cc);
+ arc.mat.opacity = REDUCED_MOTION ? ARC_BASE * 1.4 : 0;
+ arc.line.visible = true;
+
+ photonCol[slot * 3] = cc.r; photonCol[slot * 3 + 1] = cc.g; photonCol[slot * 3 + 2] = cc.b;
+ photonSize[slot] = REDUCED_MOTION ? 0 : usdSize(flow.usd, 7);
+ photonAlpha[slot] = 0;
+ photonGeom.getAttribute('aColor').needsUpdate = true;
+
+ edges.push({ flow, curve, arc, slot, age: 0, dur: usdDur(flow.usd), phase: 'travel', fadeAge: 0, b: b.clone(), color: cc });
+ return true;
+ }
+
+ function spawnFlare(flow, pos) {
+ spawnRing(pos, col(FLOW_COLORS[flow.kind] || '#9fb4d6'), ringSizeFor(flow), flow.kind);
+ return true;
+ }
+
+ function update(dt) {
+ // Edges.
+ for (let i = edges.length - 1; i >= 0; i--) {
+ const e = edges[i];
+ e.age += dt;
+ if (REDUCED_MOTION) {
+ const k = Math.min(1, e.age / e.dur);
+ e.arc.mat.opacity = ARC_BASE * 1.4 * (1 - k);
+ if (k >= 1) { spawnRing(e.b, e.color, ringSizeFor(e.flow), e.flow.kind); freeEdge(e, i); }
+ continue;
+ }
+ if (e.phase === 'travel') {
+ const p = Math.min(1, e.age / e.dur);
+ e.curve.getPoint(p, tmpV);
+ photonPos[e.slot * 3] = tmpV.x; photonPos[e.slot * 3 + 1] = tmpV.y; photonPos[e.slot * 3 + 2] = tmpV.z;
+ let alpha = Math.min(1, p / 0.12);
+ if (p > 0.85) alpha *= Math.max(0, (1 - p) / 0.15);
+ photonAlpha[e.slot] = alpha;
+ e.arc.mat.opacity = ARC_BASE * Math.min(1, e.age / 0.22);
+ if (p >= 1) {
+ photonAlpha[e.slot] = 0; photonSize[e.slot] = 0; photonFree.push(e.slot); e.slot = -1;
+ e.phase = 'fade';
+ spawnRing(e.b, e.color, ringSizeFor(e.flow), e.flow.kind);
+ }
+ } else {
+ e.fadeAge += dt;
+ e.arc.mat.opacity = ARC_BASE * Math.max(0, 1 - e.fadeAge / 0.45);
+ if (e.fadeAge >= 0.45) freeEdge(e, i);
+ }
+ }
+ if (!REDUCED_MOTION && edges.length) {
+ photonGeom.getAttribute('position').needsUpdate = true;
+ photonGeom.getAttribute('aSize').needsUpdate = true;
+ photonGeom.getAttribute('aAlpha').needsUpdate = true;
+ }
+
+ // Rings.
+ let ringDirty = false;
+ for (let s = 0; s < RING_MAX; s++) {
+ if (!ringActive[s]) continue;
+ ringAge[s] += dt;
+ const t = ringAge[s] / ringDur[s];
+ if (t >= 1) { ringActive[s] = 0; ringT[s] = 1; } else ringT[s] = t;
+ ringDirty = true;
+ }
+ if (ringDirty) ringGeom.getAttribute('aT').needsUpdate = true;
+
+ // Pick midpoints (only the active prefix is real; the rest sit far away).
+ for (let i = 0; i < ARC_MAX; i++) {
+ if (i < edges.length) {
+ edges[i].curve.getPoint(0.5, tmpV);
+ pickPos[i * 3] = tmpV.x; pickPos[i * 3 + 1] = tmpV.y; pickPos[i * 3 + 2] = tmpV.z;
+ } else if (pickPos[i * 3] !== 1e7) {
+ pickPos[i * 3] = 1e7; pickPos[i * 3 + 1] = 1e7; pickPos[i * 3 + 2] = 1e7;
+ }
+ }
+ pickGeom.getAttribute('position').needsUpdate = true;
+ }
+
+ function pick(rc) {
+ if (!edges.length) return null;
+ const hits = rc.intersectObject(pickPoints, false);
+ if (!hits.length) return null;
+ const idx = hits[0].index;
+ return idx != null && idx < edges.length ? edges[idx].flow : null;
+ }
+
+ function reset() {
+ for (let i = edges.length - 1; i >= 0; i--) freeEdge(edges[i], i);
+ for (let s = 0; s < RING_MAX; s++) { ringActive[s] = 0; ringT[s] = 1; }
+ ringGeom.getAttribute('aT').needsUpdate = true;
+ }
+
+ function dispose() {
+ reset();
+ for (const a of arcPool) { scene.remove(a.line); a.geom.dispose(); a.mat.dispose(); }
+ scene.remove(photons); photonGeom.dispose(); photonMat.dispose();
+ scene.remove(rings); ringGeom.dispose(); ringMat.dispose();
+ scene.remove(pickPoints); pickGeom.dispose(); pickPoints.material.dispose();
+ }
+
+ return { spawnEdge, spawnFlare, update, pick, reset, dispose, get activeEdges() { return edges.length; } };
+}
+
+// ── Money-Cam controller ─────────────────────────────────────────────────────
+function nodeVec(agentId) {
+ if (!agentId) return null;
+ if (money.nodeVec.has(agentId)) return money.nodeVec.get(agentId);
+ const idx = state.idToIndex.get(agentId);
+ if (idx == null) return null;
+ const a = state.data?.agents[idx];
+ if (!a) return null;
+ const v = new THREE.Vector3(...a.coords);
+ money.nodeVec.set(agentId, v);
+ return v;
+}
+
+// Animate one real flow: an agent↔agent transfer becomes a travelling edge; a
+// one-sided flow (counterparty isn't a star we have) flares the single node. A
+// flow whose agent isn't in the current snapshot is honestly skipped — we never
+// invent a star to anchor it.
+function animateFlow(flow) {
+ if (!flowLayer) return false;
+ const fromV = flow.from?.id ? nodeVec(flow.from.id) : null;
+ const toV = flow.to?.id ? nodeVec(flow.to.id) : null;
+ if (fromV && toV && flow.from.id !== flow.to.id) return flowLayer.spawnEdge(flow, fromV, toV);
+ const v = (flow.actor?.id ? nodeVec(flow.actor.id) : null) || fromV || toV;
+ if (v) return flowLayer.spawnFlare(flow, v);
+ return false;
+}
+
+function isEdgeFlow(flow) {
+ return Boolean(flow.from?.id && flow.to?.id && flow.from.id !== flow.to.id);
+}
+
+async function fetchFlows({ since } = {}) {
+ const params = new URLSearchParams({ network: 'mainnet', type: money.type, limit: '140' });
+ if (since) params.set('since', since);
+ const res = await fetch(`/api/galaxy/flows?${params.toString()}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error(`flows ${res.status}`);
+ const body = await res.json().catch(() => ({}));
+ return body?.data || null;
+}
+
+function ingest(flowsNewestFirst) {
+ // Store ascending by ts; dedupe by id across overlapping polls.
+ const fresh = [];
+ for (const f of flowsNewestFirst) {
+ if (money.seen.has(f.id)) continue;
+ money.seen.add(f.id);
+ fresh.push(f);
+ }
+ if (!fresh.length) return [];
+ fresh.reverse(); // → ascending
+ money.history.push(...fresh);
+ money.history.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.id < b.id ? -1 : 1));
+ if (money.history.length > 500) {
+ money.history.splice(0, money.history.length - 500);
+ money.seen = new Set(money.history.map((f) => f.id));
+ }
+ return fresh;
+}
+
+async function loadWindow() {
+ money.loading = true;
+ setMcNote('');
+ try {
+ const data = await fetchFlows();
+ if (!data) throw new Error('no data');
+ money.history = [];
+ money.seen = new Set();
+ money.queue = [];
+ ingest(data.flows || []);
+ money.headCursor = data.head_cursor || null;
+ money.lastServerTime = data.server_time || null;
+ money.pollFails = 0;
+ renderStats();
+ renderTicker();
+ if (!money.history.length) {
+ setMcNote('Quiet right now — no public flows in the last 24h. The galaxy is calm.');
+ } else if (money.mode === 'live') {
+ // A gentle welcoming ripple of the most recent real flows (not all at once).
+ const seed = money.history.slice(-12);
+ money.queue.push(...seed);
+ }
+ if (money.mode === 'replay') enterReplayWindow();
+ } catch {
+ setMcNote('Money-Cam feed isn’t reachable right now — retrying. No flows are invented to fill the gap.');
+ money.pollFails++;
+ } finally {
+ money.loading = false;
+ updateLiveDot();
+ }
+}
+
+async function pollDelta() {
+ if (!money.active || money.mode !== 'live' || document.hidden) return;
+ if (!money.headCursor) { await loadWindow(); return; }
+ try {
+ const data = await fetchFlows({ since: money.headCursor });
+ if (!data) throw new Error('no data');
+ money.lastServerTime = data.server_time || money.lastServerTime;
+ const fresh = ingest(data.flows || []);
+ if (data.head_cursor) money.headCursor = data.head_cursor;
+ money.pollFails = 0;
+ setMcNote('');
+ if (fresh.length) {
+ money.queue.push(...fresh); // fresh is ascending → oldest animates first
+ renderStats();
+ renderTicker();
+ }
+ } catch {
+ money.pollFails++;
+ if (money.pollFails >= 2) setMcNote('Reconnecting to the live economy…');
+ }
+ updateLiveDot();
+}
+
+// Release queued flows at a steady cadence so a burst ripples rather than dropping
+// frames. The fixed-capacity flow layer naturally back-pressures; anything that
+// can't get a slot waits its turn.
+function paceQueue(dt) {
+ if (money.mode !== 'live' || !money.queue.length) return;
+ money.releaseAcc += dt;
+ const interval = 0.1;
+ let guard = 8;
+ while (money.queue.length && money.releaseAcc >= interval && guard-- > 0) {
+ money.releaseAcc -= interval;
+ animateFlow(money.queue.shift());
+ }
+ if (money.queue.length > 240) money.queue.splice(0, money.queue.length - 240);
+}
+
+// ── Replay ───────────────────────────────────────────────────────────────────
+function windowSpan() {
+ const h = money.history;
+ if (!h.length) return [0, 0];
+ return [new Date(h[0].ts).getTime(), new Date(h[h.length - 1].ts).getTime()];
+}
+function enterReplayWindow() {
+ money.replayPtr = 0;
+ money.replayT = 0;
+ money.replayPlaying = false;
+ if (els.gxMcScrub) els.gxMcScrub.value = '0';
+ updateReplayTime();
+}
+function replayTick(dt) {
+ if (money.mode !== 'replay' || !money.replayPlaying) return;
+ const [t0, t1] = windowSpan();
+ if (t1 <= t0) { money.replayPlaying = false; syncPlayBtn(); return; }
+ const prev = money.replayT;
+ money.replayT = Math.min(1, prev + (dt / REPLAY_DURATION_S) * money.replaySpeed);
+ spawnReplayBetween(prev, money.replayT, t0, t1);
+ if (els.gxMcScrub) els.gxMcScrub.value = String(Math.round(money.replayT * 1000));
+ updateReplayTime();
+ if (money.replayT >= 1) { money.replayPlaying = false; syncPlayBtn(); }
+}
+function spawnReplayBetween(fromT, toT, t0, t1) {
+ const span = Math.max(1, t1 - t0);
+ let guard = 60;
+ while (money.replayPtr < money.history.length && guard-- > 0) {
+ const f = money.history[money.replayPtr];
+ const norm = (new Date(f.ts).getTime() - t0) / span;
+ if (norm > toT) break;
+ if (norm > fromT - 1e-6) animateFlow(f);
+ money.replayPtr++;
+ }
+}
+function updateReplayTime() {
+ if (!els.gxMcTime) return;
+ const [t0, t1] = windowSpan();
+ if (t1 <= t0) { els.gxMcTime.textContent = money.history.length ? '1 flow' : ''; return; }
+ const at = t0 + (t1 - t0) * money.replayT;
+ els.gxMcTime.textContent = `${new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })} · ${money.history.length} real flows`;
+}
+function syncPlayBtn() {
+ if (els.gxMcPlay) els.gxMcPlay.textContent = money.replayPlaying ? '❙❙' : '▶';
+}
+
+// ── Panel rendering ──────────────────────────────────────────────────────────
+function computeWindow() {
+ let usd = 0, edges = 0;
+ for (const f of money.history) {
+ if (f.usd) usd += f.usd;
+ if (isEdgeFlow(f)) edges++;
+ }
+ return { count: money.history.length, usd, edges };
+}
+function renderStats() {
+ if (!els.gxMcStats) return;
+ const w = computeWindow();
+ const [t0, t1] = windowSpan();
+ const spanMin = t1 > t0 ? Math.max(1, Math.round((t1 - t0) / 60000)) : 0;
+ els.gxMcStats.innerHTML =
+ `<span class="gx-mc-stat"><strong>${w.count.toLocaleString()}</strong> flows</span>` +
+ `<span class="gx-mc-stat"><strong>${gxFmtUsd(w.usd)}</strong> moved</span>` +
+ `<span class="gx-mc-stat"><strong>${w.edges.toLocaleString()}</strong> agent↔agent</span>` +
+ (spanMin ? `<span class="gx-mc-stat gx-mc-span">last ${spanMin >= 60 ? `${Math.round(spanMin / 60)}h` : `${spanMin}m`}</span>` : '');
+}
+function renderTicker() {
+ if (!els.gxMcTicker) return;
+ const recent = money.history.slice(-7).reverse();
+ if (!recent.length) {
+ els.gxMcTicker.innerHTML = '<div class="gx-mc-empty">No flows in view yet.</div>';
+ return;
+ }
+ els.gxMcTicker.innerHTML = recent
+ .map((f) => {
+ const c = FLOW_COLORS[f.kind] || '#9fb4d6';
+ const amount = f.usd ? gxFmtUsd(f.usd) : f.kind === 'launch' ? `$${escapeHtml(f.symbol || 'coin')}` : f.sol != null ? `${(+f.sol).toFixed(3)} SOL` : '';
+ return (
+ `<button class="gx-mc-row" type="button" data-flow="${escapeHtml(f.id)}">` +
+ `<span class="gx-mc-row-dot" style="background:${c};box-shadow:0 0 8px ${c}"></span>` +
+ `<span class="gx-mc-row-main">${flowHeadline(f)}</span>` +
+ `<span class="gx-mc-row-amt">${escapeHtml(amount)}</span>` +
+ `<span class="gx-mc-row-ago">${relTime(f.ts)}</span>` +
+ `</button>`
+ );
+ })
+ .join('');
+}
+function flowHeadline(f) {
+ const a = escapeHtml(f.actor?.name || 'Agent');
+ if (f.kind === 'launch') return `${a} launched $${escapeHtml(f.symbol || 'a coin')}`;
+ if (f.kind === 'tip') return `${escapeHtml(f.from?.name || shortAddr(f.from?.wallet) || 'someone')} → ${a}`;
+ const to = f.to?.name ? escapeHtml(f.to.name) : shortAddr(f.to?.wallet) || 'market';
+ const verb = f.kind === 'payment' ? 'paid' : f.kind === 'snipe' ? 'sniped' : 'traded →';
+ return f.kind === 'payment' ? `${a} ${verb} ${to}` : `${a} ${verb} ${to}`;
+}
+
+// ── Flow inspector ───────────────────────────────────────────────────────────
+function partyHtml(p, fallback) {
+ if (!p) return `<span class="gx-flow-party">${escapeHtml(fallback || '—')}</span>`;
+ if (p.id) return `<a class="gx-flow-party gx-flow-link" href="/agents/${escapeHtml(p.id)}">${escapeHtml(p.name || 'Agent')}</a>`;
+ return `<span class="gx-flow-party"><code>${escapeHtml(shortAddr(p.wallet) || '—')}</code></span>`;
+}
+function openFlow(flow, fly = true) {
+ const c = FLOW_COLORS[flow.kind] || '#9fb4d6';
+ const label = { tip: 'Tip', trade: 'Trade', snipe: 'Snipe', payment: 'Payment', launch: 'Launch' }[flow.kind] || 'Flow';
+ const amount = flow.usd ? gxFmtUsd(flow.usd) : null;
+ const sub = flow.kind === 'launch'
+ ? `$${escapeHtml(flow.symbol || flow.coin_name || 'coin')}`
+ : flow.sol != null
+ ? `${(+flow.sol).toFixed(4)} SOL`
+ : flow.asset
+ ? `${flow.amount_raw ? '' : ''}${escapeHtml(flow.asset === 'SOL' ? 'SOL' : shortAddr(flow.asset) || flow.asset)}`
+ : '';
+ const explorerLink = flow.kind === 'launch' ? flow.mint_explorer : flow.explorer;
+ const explorerLabel = flow.kind === 'launch' ? 'View mint on Solscan' : 'View signature on Solscan';
+ const route = flow.kind === 'launch'
+ ? partyHtml(flow.actor)
+ : `${partyHtml(flow.from, 'market')} <span class="gx-flow-arrow" aria-hidden="true">→</span> ${partyHtml(flow.to, 'market')}`;
+
+ els.gxFlowBody.innerHTML =
+ `<div class="gx-flow-head"><span class="gx-flow-dot" style="background:${c};box-shadow:0 0 12px ${c}"></span>` +
+ `<span class="gx-flow-kind">${label}</span>` +
+ `<span class="gx-flow-time">${escapeHtml(absTime(flow.ts))}</span></div>` +
+ `<div class="gx-flow-amount">${amount ? `<strong>${escapeHtml(amount)}</strong>` : ''}${sub ? `<span>${escapeHtml(sub)}</span>` : ''}</div>` +
+ `<div class="gx-flow-route">${route}</div>` +
+ (explorerLink
+ ? `<a class="gx-flow-explorer" href="${escapeHtml(explorerLink)}" target="_blank" rel="noopener">${explorerLabel} ↗</a>`
+ : '<div class="gx-flow-explorer gx-flow-pending">Confirming on-chain…</div>');
+ els.gxFlow.hidden = false;
+
+ if (fly) {
+ const fv = flow.from?.id ? nodeVec(flow.from.id) : null;
+ const tv = flow.to?.id ? nodeVec(flow.to.id) : null;
+ const av = flow.actor?.id ? nodeVec(flow.actor.id) : null;
+ let target = null;
+ if (fv && tv) target = new THREE.Vector3().addVectors(fv, tv).multiplyScalar(0.5);
+ else target = av || fv || tv;
+ if (target) flyToTarget(target.clone(), 150);
+ }
+}
+function closeFlow() {
+ if (els.gxFlow) els.gxFlow.hidden = true;
+}
+
+// ── Mode + lifecycle ─────────────────────────────────────────────────────────
+function setMcNote(msg) {
+ if (!els.gxMcNote) return;
+ els.gxMcNote.textContent = msg || '';
+ els.gxMcNote.hidden = !msg;
+}
+function updateLiveDot() {
+ if (!els.gxMcLiveDot) return;
+ const live = money.active && money.mode === 'live' && !document.hidden;
+ els.gxMcLiveDot.classList.toggle('gx-mc-on', live && money.pollFails === 0);
+ els.gxMcLiveDot.classList.toggle('gx-mc-stale', money.pollFails > 0);
+}
+function startPolling() {
+ stopPolling();
+ pollTimer = setInterval(pollDelta, LIVE_POLL_MS);
+}
+function stopPolling() {
+ if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
+}
+function setMcMode(mode) {
+ money.mode = mode;
+ const live = mode === 'live';
+ els.gxMcModeLive.classList.toggle('gx-active', live);
+ els.gxMcModeReplay.classList.toggle('gx-active', !live);
+ els.gxMcModeLive.setAttribute('aria-selected', String(live));
+ els.gxMcModeReplay.setAttribute('aria-selected', String(!live));
+ els.gxMcReplay.hidden = live;
+ if (live) {
+ money.replayPlaying = false;
+ startPolling();
+ pollDelta();
+ } else {
+ stopPolling();
+ flowLayer?.reset();
+ enterReplayWindow();
+ }
+ updateLiveDot();
+}
+function setMcType(type) {
+ if (money.type === type) return;
+ money.type = type;
+ for (const b of els.gxMcFilters.querySelectorAll('.gx-mc-filter')) {
+ b.classList.toggle('gx-active', b.dataset.type === type);
+ }
+ flowLayer?.reset();
+ loadWindow().then(() => { if (money.mode === 'live') pollDelta(); });
+}
+function openMoneyCam() {
+ if (money.active) return;
+ if (!state.data || !flowLayer) return;
+ money.active = true;
+ els.gxMoneyCam.hidden = false;
+ els.gxMoneyToggle.setAttribute('aria-pressed', 'true');
+ els.gxMoneyToggle.classList.add('gx-active');
+ clearSearch();
+ if (!els.gxResults.hidden) els.gxResults.hidden = true;
+ controls.autoRotate = false;
+ track(ANALYTICS_EVENTS.SURFACE_OPENED, { surface: 'visualizer:money-cam' });
+ loadWindow();
+ startPolling();
+}
+function closeMoneyCam() {
+ if (!money.active) return;
+ money.active = false;
+ stopPolling();
+ flowLayer?.reset();
+ money.queue = [];
+ els.gxMoneyCam.hidden = true;
+ closeFlow();
+ els.gxMoneyToggle.setAttribute('aria-pressed', 'false');
+ els.gxMoneyToggle.classList.remove('gx-active');
+ if (!REDUCED_MOTION) scheduleIdle();
+}
+function toggleMoneyCam() {
+ if (money.active) closeMoneyCam();
+ else openMoneyCam();
+}
+
+// ── Money-Cam helpers ────────────────────────────────────────────────────────
+function shortAddr(w) {
+ if (!w || typeof w !== 'string') return '';
+ return w.length > 10 ? `${w.slice(0, 4)}…${w.slice(-4)}` : w;
+}
+function relTime(iso) {
+ const ms = Date.now() - new Date(iso).getTime();
+ if (!Number.isFinite(ms)) return '';
+ const s = Math.max(0, Math.round(ms / 1000));
+ if (s < 60) return `${s}s`;
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m`;
+ const h = Math.round(m / 60);
+ if (h < 24) return `${h}h`;
+ return `${Math.round(h / 24)}d`;
+}
+function absTime(iso) {
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? '' : d.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
+}
+function flowById(id) {
+ return money.history.find((f) => f.id === id) || null;
+}
+
+// ── Money-Cam flow shaders ───────────────────────────────────────────────────
+const FLOW_PHOTON_VERT = /* glsl */ `
+ attribute vec3 aColor;
+ attribute float aSize;
+ attribute float aAlpha;
+ uniform float uPixelRatio;
+ varying vec3 vColor;
+ varying float vAlpha;
+ void main() {
+ vColor = aColor;
+ vAlpha = aAlpha;
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
+ float dist = max(-mv.z, 1.0);
+ gl_PointSize = clamp(aSize * (300.0 / dist), 1.0, 64.0) * uPixelRatio;
+ gl_Position = projectionMatrix * mv;
+ }
+`;
+const FLOW_PHOTON_FRAG = /* glsl */ `
+ precision mediump float;
+ varying vec3 vColor;
+ varying float vAlpha;
+ void main() {
+ float d = length(gl_PointCoord - 0.5);
+ if (d > 0.5) discard;
+ float core = smoothstep(0.5, 0.0, d);
+ gl_FragColor = vec4(vColor * (0.6 + 0.9 * core), core * core * vAlpha);
+ }
+`;
+const FLOW_RING_VERT = /* glsl */ `
+ attribute vec3 aColor;
+ attribute float aT;
+ attribute float aSize;
+ uniform float uPixelRatio;
+ uniform float uGrow;
+ varying vec3 vColor;
+ varying float vT;
+ void main() {
+ vColor = aColor;
+ vT = aT;
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
+ float dist = max(-mv.z, 1.0);
+ float grow = aSize * (1.0 + aT * uGrow);
+ gl_PointSize = clamp(grow * (300.0 / dist), 2.0, 96.0) * uPixelRatio;
+ gl_Position = projectionMatrix * mv;
+ }
+`;
+const FLOW_RING_FRAG = /* glsl */ `
+ precision mediump float;
+ varying vec3 vColor;
+ varying float vT;
+ void main() {
+ float d = length(gl_PointCoord - 0.5) * 2.0;
+ if (d > 1.0) discard;
+ // Annulus near the outer edge; fades as the ring expands.
+ float ring = smoothstep(0.62, 0.9, d) * smoothstep(1.0, 0.9, d);
+ float alpha = ring * (1.0 - vT) * 0.9;
+ gl_FragColor = vec4(vColor, alpha);
+ }
+`;
+
// ── Shaders ──────────────────────────────────────────────────────────────────
const POINT_VERT = /* glsl */ `
attribute vec3 aColor;
diff --git a/src/guardian.js b/src/guardian.js
new file mode 100644
index 000000000..26b172404
--- /dev/null
+++ b/src/guardian.js
@@ -0,0 +1,284 @@
+/**
+ * Guardian console — page entry (/guardian).
+ *
+ * The cross-agent surface for someone trusted as a guardian or named as a
+ * beneficiary. They are NOT the owner, so they never see the owner-only Recovery
+ * tab in an agent's wallet hub — this is where they act: approve a recovery,
+ * decline it, confirm an inheritance, or push a ready process over the line. Being
+ * a guardian is a real, visible role in the graph; this page surfaces it with the
+ * weight it deserves.
+ *
+ * 100% real: every list item and every action hits the owner/guardian-gated API
+ * (CSRF-protected). No key is ever exposed — completing a process only changes who
+ * owns the agent.
+ */
+
+import { consumeCsrfToken } from './api.js';
+
+const root = document.getElementById('guardian-root');
+
+const STYLE = `
+.gd { display:flex; flex-direction:column; gap:16px; padding-top:14px; }
+.gd-hero { display:flex; gap:14px; align-items:flex-start; }
+.gd-hero-ic { width:42px; height:42px; border-radius:12px; display:grid; place-items:center; flex:none; font-size:20px; background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 16%,transparent); border:1px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 36%,transparent); color:var(--wallet-accent-ink,#c4b5fd); }
+.gd-hero h1 { margin:0 0 4px; font-family:var(--font-display,system-ui); font-size:var(--text-2xl,1.8rem); color:var(--ink-bright,#fff); }
+.gd-hero p { margin:0; color:var(--ink-dim,#888); font-size:var(--text-sm,.85rem); line-height:1.55; max-width:60ch; }
+.gd-badge { display:inline-flex; align-items:center; gap:6px; font-size:var(--text-2xs,.6875rem); font-weight:600; padding:3px 10px; border-radius:999px; margin-top:8px; color:var(--wallet-accent-ink,#c4b5fd); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 14%,transparent); border:1px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 32%,transparent); }
+.gd-card { border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:14px; background:var(--surface-1,rgba(255,255,255,.03)); padding:16px 18px; }
+.gd-card.act { border-color:color-mix(in srgb,var(--warn,#fbbf24) 45%,transparent); background:color-mix(in srgb,var(--warn,#fbbf24) 7%,transparent); }
+.gd-row { display:flex; gap:12px; align-items:center; }
+.gd-ava { width:40px; height:40px; border-radius:10px; object-fit:cover; flex:none; background:var(--surface-3,rgba(255,255,255,.08)); display:grid; place-items:center; color:var(--ink-dim,#888); font-size:15px; }
+.gd-id { flex:1; min-width:0; }
+.gd-name { font-size:var(--text-md,.95rem); color:var(--ink-bright,#fff); font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+.gd-name a { color:inherit; text-decoration:none; }
+.gd-name a:hover { text-decoration:underline; }
+.gd-meta { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:2px; }
+.gd-roles { display:flex; gap:6px; flex-wrap:wrap; }
+.gd-pill { font-size:var(--text-2xs,.6875rem); font-weight:600; padding:2px 8px; border-radius:999px; border:1px solid transparent; }
+.gd-pill.guardian { color:var(--wallet-accent-ink,#c4b5fd); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 14%,transparent); border-color:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 32%,transparent); }
+.gd-pill.beneficiary { color:var(--success,#4ade80); background:color-mix(in srgb,var(--success,#4ade80) 12%,transparent); border-color:color-mix(in srgb,var(--success,#4ade80) 30%,transparent); }
+.gd-proc { margin-top:12px; padding-top:12px; border-top:1px solid var(--stroke,rgba(255,255,255,.08)); }
+.gd-proc-h { font-size:var(--text-sm,.85rem); color:var(--ink-bright,#fff); display:flex; align-items:center; gap:8px; }
+.gd-narrate { font-style:italic; color:var(--ink,#c8c8c8); font-size:var(--text-sm,.8rem); line-height:1.5; padding:10px 12px; margin-top:8px; border-left:2px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 50%,transparent); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 7%,transparent); border-radius:0 10px 10px 0; }
+.gd-count { font-family:var(--font-mono,monospace); font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:6px; }
+.gd-tl { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:4px; }
+.gd-actions { display:flex; gap:8px; margin-top:12px; flex-wrap:wrap; }
+.gd-btn { appearance:none; font:inherit; font-size:var(--text-sm,.8rem); color:var(--ink,#e8e8e8); background:var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:10px; padding:8px 14px; cursor:pointer; transition:background .14s,border-color .14s,transform .08s; }
+.gd-btn:hover:not(:disabled){ background:var(--surface-3,rgba(255,255,255,.08)); border-color:var(--stroke-strong,rgba(255,255,255,.14)); }
+.gd-btn:active:not(:disabled){ transform:translateY(1px); }
+.gd-btn:disabled{ opacity:.4; cursor:not-allowed; }
+.gd-btn:focus-visible{ outline:2px solid var(--focus-ring-color,#fff); outline-offset:2px; }
+.gd-btn--approve{ background:color-mix(in srgb,var(--success,#4ade80) 16%,transparent); color:var(--success,#4ade80); border-color:color-mix(in srgb,var(--success,#4ade80) 40%,transparent); font-weight:600; }
+.gd-btn--danger{ background:color-mix(in srgb,var(--danger,#f87171) 14%,transparent); color:var(--danger,#f87171); border-color:color-mix(in srgb,var(--danger,#f87171) 40%,transparent); font-weight:600; }
+.gd-btn--primary{ background:var(--accent,#fff); color:#0a0a0a; border-color:var(--accent,#fff); font-weight:600; }
+.gd-empty{ text-align:center; padding:36px 16px; color:var(--ink-dim,#888); }
+.gd-empty .ill{ font-size:34px; opacity:.5; display:block; margin-bottom:10px; }
+.gd-skel{ height:84px; border-radius:14px; background:linear-gradient(90deg,var(--surface-1,rgba(255,255,255,.03)) 25%,var(--surface-2,rgba(255,255,255,.05)) 37%,var(--surface-1,rgba(255,255,255,.03)) 63%); background-size:400% 100%; animation:gd-sh 1.4s ease infinite; }
+.gd-toast{ position:fixed; left:50%; bottom:24px; transform:translateX(-50%) translateY(8px); background:var(--bg-1,#1a1a1a); color:var(--ink-bright,#fff); border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); border-radius:10px; padding:10px 16px; font-size:.85rem; box-shadow:0 8px 32px rgba(0,0,0,.5); opacity:0; pointer-events:none; transition:opacity .2s,transform .2s; z-index:9999; }
+.gd-toast[data-show="true"]{ opacity:1; transform:translateX(-50%) translateY(0); }
+@keyframes gd-sh{ 0%{background-position:100% 0} 100%{background-position:-100% 0} }
+@media (prefers-reduced-motion: reduce){ .gd-skel{animation:none} }
+`;
+
+function injectStyle() {
+ if (document.getElementById('gd-style')) return;
+ const t = document.createElement('style');
+ t.id = 'gd-style';
+ t.textContent = STYLE;
+ document.head.appendChild(t);
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
+
+let toastTimer = null;
+function toast(msg, ms = 2400) {
+ let el = document.querySelector('.gd-toast');
+ if (!el) { el = document.createElement('div'); el.className = 'gd-toast'; el.setAttribute('role', 'status'); el.setAttribute('aria-live', 'polite'); document.body.appendChild(el); }
+ el.textContent = msg;
+ el.dataset.show = 'true';
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => { el.dataset.show = 'false'; }, ms);
+}
+
+function fmtDuration(ms) {
+ if (ms == null) return '';
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
+ if (d > 0) return `${d}d ${h}h`;
+ if (h > 0) return `${h}h ${m}m`;
+ if (m > 0) return `${m}m`;
+ return `${s}s`;
+}
+
+async function call(url, { method = 'GET', body = null } = {}) {
+ try {
+ const opts = { method, credentials: 'include', headers: {} };
+ if (body != null) { opts.headers['content-type'] = 'application/json'; opts.body = JSON.stringify(body); }
+ if (method !== 'GET') { const tok = await consumeCsrfToken(); if (tok) opts.headers['x-csrf-token'] = tok; }
+ const r = await fetch(url, opts);
+ let j = null; try { j = await r.json(); } catch { /* empty */ }
+ if (!r.ok) return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, detail: j?.detail || null };
+ return { ok: true, status: r.status, data: j?.data ?? j };
+ } catch (err) {
+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ }
+}
+
+let busy = false;
+
+function avatarHTML(item) {
+ if (item.avatar_url) return `<img class="gd-ava" src="${esc(item.avatar_url)}" alt="" loading="lazy" onerror="this.outerHTML='<span class=\\'gd-ava\\'>${esc((item.agent_name || '?').slice(0, 1).toUpperCase())}</span>'" />`;
+ return `<span class="gd-ava" aria-hidden="true">${esc((item.agent_name || '?').slice(0, 1).toUpperCase())}</span>`;
+}
+
+function processHTML(item) {
+ const p = item.active_request;
+ if (!p) {
+ if (item.dead_man_enabled && item.roles.includes('beneficiary')) {
+ return `<div class="gd-proc"><p class="gd-tl">No active process. If the owner has gone silent past their threshold, you can arm inheritance.</p>
+ <div class="gd-actions"><button class="gd-btn" type="button" data-act="arm" data-agent="${esc(item.agent_id)}">Try to arm inheritance</button></div></div>`;
+ }
+ return `<div class="gd-proc"><p class="gd-tl">No active recovery or inheritance. You’ll be notified if you’re ever needed.</p></div>`;
+ }
+ const isInh = p.kind === 'inheritance';
+ const narrate = isInh
+ ? '“My owner has gone quiet. You’re my beneficiary or guardian — confirm only if you truly believe they’re gone. They can still stop this by showing up.”'
+ : '“I’m being recovered. If you trust this person is really my owner, approve. If anything feels off, decline.”';
+ const approvalsLine = p.approvals_required > 0
+ ? `Approvals: ${p.approvals}/${p.approvals_required}${p.declines ? ` · ${p.declines} declined` : ''}`
+ : (p.needs_beneficiary_confirmation ? 'Awaiting beneficiary confirmation' : 'Beneficiary confirmed');
+ const lockLine = p.ms_until_unlock > 0
+ ? `Safety window: ${fmtDuration(p.ms_until_unlock)} remaining`
+ : (p.status === 'ready' ? 'Safety window elapsed — ready to complete' : 'Safety window starts after approvals');
+ const youVoted = (p.votes || []).find((v) => v.user_id === item._viewerId);
+
+ const actions = [];
+ if (item.needs_action && !youVoted) {
+ if (isInh) {
+ actions.push(`<button class="gd-btn gd-btn--approve" type="button" data-act="confirm" data-agent="${esc(item.agent_id)}" data-rid="${esc(p.id)}">Confirm inheritance</button>`);
+ if (item.roles.includes('guardian')) actions.push(`<button class="gd-btn gd-btn--danger" type="button" data-act="decline" data-agent="${esc(item.agent_id)}" data-rid="${esc(p.id)}">Decline</button>`);
+ } else {
+ actions.push(`<button class="gd-btn gd-btn--approve" type="button" data-act="approve" data-agent="${esc(item.agent_id)}" data-rid="${esc(p.id)}">Approve recovery</button>`);
+ actions.push(`<button class="gd-btn gd-btn--danger" type="button" data-act="decline" data-agent="${esc(item.agent_id)}" data-rid="${esc(p.id)}">Decline</button>`);
+ }
+ } else if (youVoted) {
+ actions.push(`<span class="gd-pill ${youVoted.decision === 'approve' ? 'beneficiary' : 'guardian'}">You ${youVoted.decision === 'approve' ? 'approved' : 'declined'}</span>`);
+ }
+ if (p.status === 'ready') {
+ actions.push(`<button class="gd-btn gd-btn--primary" type="button" data-act="complete" data-agent="${esc(item.agent_id)}" data-rid="${esc(p.id)}">Complete transfer</button>`);
+ }
+
+ return `
+ <div class="gd-proc">
+ <div class="gd-proc-h">${isInh ? '🕊' : '🔓'} ${isInh ? 'Inheritance' : 'Recovery'} in progress <span class="gd-pill ${isInh ? 'beneficiary' : 'guardian'}">${esc(p.status)}</span></div>
+ <div class="gd-narrate">${esc(narrate)}</div>
+ <div class="gd-count">${esc(approvalsLine)}</div>
+ <div class="gd-tl">${esc(lockLine)} · opened ${new Date(p.created_at).toLocaleString()}</div>
+ ${actions.length ? `<div class="gd-actions">${actions.join('')}</div>` : ''}
+ </div>`;
+}
+
+function itemHTML(item) {
+ const roles = (item.roles || []).map((r) => `<span class="gd-pill ${r}">${r}</span>`).join('');
+ return `
+ <div class="gd-card ${item.needs_action ? 'act' : ''}">
+ <div class="gd-row">
+ ${avatarHTML(item)}
+ <div class="gd-id">
+ <div class="gd-name"><a href="/agent/${esc(item.agent_id)}">${esc(item.agent_name || 'Agent')}</a></div>
+ <div class="gd-meta">Owned by ${esc(item.owner?.label || 'someone')} · trusted since ${item.since ? new Date(item.since).toLocaleDateString() : '—'}</div>
+ </div>
+ <div class="gd-roles">${roles}</div>
+ </div>
+ ${processHTML(item)}
+ </div>`;
+}
+
+function renderLoading() {
+ injectStyle();
+ root.innerHTML = `<div class="gd"><div class="gd-skel"></div><div class="gd-skel"></div></div>`;
+}
+
+function renderSignedOut() {
+ root.innerHTML = `
+ <div class="gd">
+ <div class="gd-empty">
+ <span class="ill" aria-hidden="true">🛡</span>
+ <h2 style="margin:0 0 6px;color:var(--ink-bright,#fff);">Sign in to your guardian console</h2>
+ <p>This is where you help the people who trust you back into their agents. Sign in to see who’s named you.</p>
+ <div class="gd-actions" style="justify-content:center;margin-top:14px;"><a class="gd-btn gd-btn--primary" href="/account">Sign in</a></div>
+ </div>
+ </div>`;
+}
+
+function renderError(msg) {
+ root.innerHTML = `<div class="gd"><div class="gd-empty"><span class="ill">⚠️</span><p>${esc(msg || 'Something went wrong')}</p><div class="gd-actions" style="justify-content:center;"><button class="gd-btn" type="button" id="gd-retry">Try again</button></div></div></div>`;
+ document.getElementById('gd-retry')?.addEventListener('click', load);
+}
+
+function render(data, viewerId) {
+ injectStyle();
+ const items = data.items || [];
+ if (!items.length) {
+ root.innerHTML = `
+ <div class="gd">
+ <div class="gd-hero">
+ <span class="gd-hero-ic" aria-hidden="true">🛡</span>
+ <div><h1>Guardian console</h1><p>When someone names you a guardian or beneficiary of their agent, it shows up here. You’ll be able to help them recover access — or, if they’re truly gone, pass their agent to its heir.</p></div>
+ </div>
+ <div class="gd-empty"><span class="ill" aria-hidden="true">🫂</span><h2 style="margin:0 0 6px;color:var(--ink-bright,#fff);">No one’s named you yet</h2><p>Ask a friend who runs a funded agent to add you as a guardian — being someone’s safety net is a real bond on three.ws.</p></div>
+ </div>`;
+ return;
+ }
+ items.forEach((it) => { it._viewerId = viewerId; });
+ root.innerHTML = `
+ <div class="gd">
+ <div class="gd-hero">
+ <span class="gd-hero-ic" aria-hidden="true">🛡</span>
+ <div>
+ <h1>Guardian console</h1>
+ <p>The agents you’re trusted to protect. You never see anyone’s funds or keys — only the power to help them back in.</p>
+ ${data.actionable ? `<span class="gd-badge">● ${data.actionable} ${data.actionable === 1 ? 'agent needs' : 'agents need'} your action</span>` : ''}
+ </div>
+ </div>
+ ${items.map(itemHTML).join('')}
+ </div>`;
+ wire();
+}
+
+function wire() {
+ root.querySelectorAll('[data-act]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ if (busy) return;
+ const act = btn.dataset.act;
+ const agent = btn.dataset.agent;
+ const rid = btn.dataset.rid;
+ let confirmMsg = null;
+ if (act === 'approve') confirmMsg = 'Approve this recovery? Only do this if you trust the person is the rightful owner.';
+ if (act === 'confirm') confirmMsg = 'Confirm this inheritance? Only do this if you truly believe the owner is gone.';
+ if (act === 'decline') confirmMsg = 'Decline this request?';
+ if (act === 'complete') confirmMsg = 'Complete the transfer now? Control of the agent and its wallet passes to the new owner.';
+ if (confirmMsg && !confirm(confirmMsg)) return;
+
+ busy = true;
+ btn.disabled = true;
+ let url, res;
+ if (act === 'arm') {
+ res = await call(`/api/agents/${encodeURIComponent(agent)}/recovery/inheritance/arm`, { method: 'POST', body: {} });
+ } else {
+ url = `/api/agents/${encodeURIComponent(agent)}/recovery/requests/${encodeURIComponent(rid)}/${act}`;
+ res = await call(url, { method: 'POST', body: {} });
+ }
+ busy = false;
+ if (!res.ok) { toast(res.message || 'Action failed'); btn.disabled = false; return; }
+ const msg = {
+ approve: 'Approved — thank you for vouching',
+ confirm: 'Confirmed',
+ decline: 'Declined',
+ complete: 'Transfer complete — control has passed',
+ arm: 'Inheritance armed — the grace window has begun',
+ }[act] || 'Done';
+ toast(msg);
+ await load();
+ });
+ });
+}
+
+async function load() {
+ renderLoading();
+ const res = await call('/api/agents/recovery-inbox');
+ if (res.status === 401) { renderSignedOut(); return; }
+ if (!res.ok) { renderError(res.message); return; }
+ // Resolve the viewer id from the inbox payload (active_request votes reference
+ // user_ids); fall back to a /api/me lookup only if needed.
+ let viewerId = null;
+ try {
+ const me = await call('/api/me');
+ viewerId = me.ok ? (me.data?.id || me.data?.user?.id || null) : null;
+ } catch { /* non-fatal */ }
+ render(res.data, viewerId);
+}
+
+if (root) load();
diff --git a/src/irl.js b/src/irl.js
index 6da122c85..31698d6ca 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -82,6 +82,8 @@ import { openGlassesConnect } from './irl/glasses/connect-ui.js';
import { loadLeaflet } from './shared/leaflet-loader.js';
import { initDiscovery } from './irl/discovery.js';
import { walletChipEl, hasWallet } from './shared/agent-wallet-chip.js';
+import { buildSolanaPayUri } from './shared/solana-pay.js';
+import { renderQRToSVG } from './erc8004/qr.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -4881,6 +4883,54 @@ function _cardSkeletonHTML() {
return `${skeletonHTML(1, 'text')}${skeletonHTML(3, 'row')}`;
}
+const _TAPTIP_B58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// Build the IRL "tap to tip" block: a Solana Pay QR + a one-tap deep link to the
+// agent's real public address. This is the moment that only exists when you meet
+// an autonomous agent in physical space — scan the QR with a phone wallet, or tap
+// "Open in wallet" to launch Phantom/Solflare pre-filled. Public data only (the
+// agent's solana_address); no secret is ever involved. Returns null when the
+// agent has no valid address so the card simply omits the block.
+function _buildTapToTip(agent) {
+ const address = agent?.solana_address;
+ if (!address || !_TAPTIP_B58.test(String(address))) return null;
+ const label = (agent.name || 'three.ws agent').slice(0, 32);
+ const uri = buildSolanaPayUri(address, { label });
+ if (!uri) return null;
+
+ const wrap = document.createElement('div');
+ wrap.className = 'irl-taptip';
+ wrap.innerHTML =
+ `<button type="button" class="irl-taptip-toggle" aria-expanded="false">` +
+ `<span>◎ Tap to tip in person</span><span class="irl-taptip-caret">▾</span></button>` +
+ `<div class="irl-taptip-panel" hidden>` +
+ `<div class="irl-taptip-qr" aria-hidden="true"></div>` +
+ `<div class="irl-taptip-meta">` +
+ `<div class="irl-taptip-cap">Scan with Phantom · Solflare · Backpack</div>` +
+ `<a class="irl-taptip-open" href="${uri}">Open in wallet ↗</a>` +
+ `</div></div>`;
+
+ const toggle = wrap.querySelector('.irl-taptip-toggle');
+ const panel = wrap.querySelector('.irl-taptip-panel');
+ const qrSlot = wrap.querySelector('.irl-taptip-qr');
+ toggle.addEventListener('click', () => {
+ const open = panel.hidden;
+ panel.hidden = !open;
+ toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
+ if (open && !qrSlot.dataset.done) {
+ try {
+ qrSlot.innerHTML = renderQRToSVG(uri, { scale: 4, margin: 1 });
+ qrSlot.dataset.done = '1';
+ } catch {
+ // QR generation can overflow on a very long label — fall back to the
+ // deep link alone, never a broken slot.
+ qrSlot.remove();
+ }
+ }
+ });
+ return wrap;
+}
+
// Render the resolved card into the open sheet.
function _applyCard(card, pin) {
const agent = card.agent || {};
@@ -4925,6 +4975,14 @@ function _applyCard(card, pin) {
chip.style.marginTop = '10px';
body.appendChild(chip);
}
+ // Tap-to-tip in the real world — the moment unique to IRL/AR. You meet
+ // the agent in physical space and pay it on the spot: scan the Solana
+ // Pay QR with a phone wallet, or tap "Open in wallet" on this device to
+ // launch Phantom/Solflare pre-filled with the agent's real address. The
+ // chip above already covers the connected-browser-wallet tip; this is
+ // the in-person, no-extension path.
+ const tap = _buildTapToTip(agent);
+ if (tap) body.appendChild(tap);
}
}
diff --git a/src/mirror.js b/src/mirror.js
new file mode 100644
index 000000000..55dfe508a
--- /dev/null
+++ b/src/mirror.js
@@ -0,0 +1,154 @@
+// /mirror — Copy Trading discovery + management.
+//
+// Two real surfaces:
+// • Discover leaders — performance-weighted ranking of followable agents from
+// /api/mirror/leaderboard (real on-chain stats). "Mirror" picks one of your
+// agents and opens the leash setup modal.
+// • Your copy-trading — the owner mirror panel for each of your wallet-bearing
+// agents (kill switch, follows, "mirrored from @leader" feed), reusing the
+// exact shared component the agent detail page mounts.
+
+import { apiFetch } from './api.js';
+import { mountMirrorPanel, openFollowModal } from './shared/agent-mirror-panel.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const short = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');
+const fmtSol = (n) => (n == null || !Number.isFinite(Number(n)) ? '—' : Number(n).toFixed(Math.abs(n) < 1 ? 3 : 2).replace(/\.?0+$/, ''));
+
+const board = document.getElementById('mp-board');
+const sortSeg = document.getElementById('mp-sort');
+let sort = new URL(location.href).searchParams.get('sort') || 'score';
+let myAgents = [];
+
+function leaderRow(l) {
+ const roi = l.roi_pct != null ? `<span class="${l.roi_pct >= 0 ? 'pos' : 'neg'}">${l.roi_pct >= 0 ? '+' : ''}${l.roi_pct}% ROI</span>` : '';
+ const pnl = l.pnl_sol != null && l.pnl_sol !== 0 ? `<span class="${l.pnl_sol >= 0 ? 'pos' : 'neg'}">${l.pnl_sol >= 0 ? '+' : ''}◎${fmtSol(l.pnl_sol)}</span>` : '';
+ const win = l.win_rate != null ? `<span>${l.win_rate}% win</span>` : '';
+ const vol = l.volume_sol ? `<span>◎${fmtSol(l.volume_sol)} vol</span>` : '';
+ const fol = `<span>${l.followers} ${l.followers === 1 ? 'follower' : 'followers'}</span>`;
+ const stats = [roi, pnl, win, vol, fol].filter(Boolean).join('') || '<span>No settled trades yet</span>';
+ return `<div class="mp-lrow">
+ <div class="mp-rank ${l.rank <= 3 ? 'top' : ''}">#${l.rank}</div>
+ ${l.avatar ? `<img class="mp-av" src="${esc(l.avatar)}" alt="" loading="lazy">` : '<div class="mp-av"></div>'}
+ <div class="mp-lbody">
+ <div class="mp-lname"><a href="/agent/${esc(l.agent_id)}">${esc(l.name || short(l.agent_id))}</a></div>
+ <div class="mp-lstats">${stats}</div>
+ </div>
+ <button class="mp-mirror-btn" data-id="${esc(l.agent_id)}" data-name="${esc(l.name || '')}">⚡ Mirror</button>
+ </div>`;
+}
+
+async function loadBoard() {
+ board.innerHTML = '<div class="mp-sk"></div><div class="mp-sk"></div><div class="mp-sk"></div>';
+ try {
+ const res = await apiFetch(`/api/mirror/leaderboard?sort=${encodeURIComponent(sort)}&limit=30`, { allowAnonymous: true });
+ if (!res.ok) throw new Error('load failed');
+ const leaders = (await res.json()).data?.leaders || [];
+ if (!leaders.length) {
+ board.innerHTML = `<div class="mp-empty"><strong>No leaders yet</strong>Once agents start trading, the best ones rank here by their real track record. <a href="/create-agent" style="color:var(--wallet-accent,#c4b5fd)">Launch a trader →</a></div>`;
+ return;
+ }
+ board.innerHTML = leaders.map(leaderRow).join('');
+ board.querySelectorAll('.mp-mirror-btn').forEach((b) => {
+ b.addEventListener('click', () => mirrorLeader(b.dataset.id, b.dataset.name));
+ });
+ } catch {
+ board.innerHTML = `<div class="mp-empty"><strong>Couldn't load leaders</strong><button class="mp-mirror-btn" id="mp-retry">Retry</button></div>`;
+ document.getElementById('mp-retry')?.addEventListener('click', loadBoard);
+ }
+}
+
+// "Mirror" a leader → pick which of my agents follows it, then open the leash modal.
+async function mirrorLeader(leaderId, leaderName) {
+ if (!myAgents.length) {
+ // Re-check in case auth resolved after first paint.
+ await loadMine();
+ }
+ const candidates = myAgents.filter((a) => a.id !== leaderId);
+ if (!candidates.length) {
+ alert('You need your own agent first. Create or fork one, then mirror a leader.');
+ location.href = '/create-agent';
+ return;
+ }
+ const leader = { agent_id: leaderId, name: leaderName };
+ if (candidates.length === 1) {
+ const saved = await openFollowModal({ followerId: candidates[0].id, followerName: candidates[0].name, leader });
+ if (saved) loadMine();
+ return;
+ }
+ // Multi-agent picker.
+ const back = document.createElement('div');
+ back.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.66);backdrop-filter:blur(4px);z-index:9998;display:flex;align-items:center;justify-content:center;padding:16px';
+ back.innerHTML = `<div style="width:min(420px,96vw);background:var(--bg-1,#141414);border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));border-radius:14px;padding:22px">
+ <h3 style="margin:0 0 4px;font-family:var(--font-display,inherit);color:var(--ink-bright,#fff)">Which agent should mirror?</h3>
+ <p style="font-size:.72rem;color:var(--ink-dim,#9a9a9a);margin:0 0 14px">Pick the agent whose wallet copies ${esc(leaderName || 'this leader')}.</p>
+ <div style="display:flex;flex-direction:column;gap:6px">${candidates.map((a) => `<button type="button" data-id="${esc(a.id)}" data-name="${esc(a.name || '')}" style="display:flex;align-items:center;gap:10px;text-align:left;padding:10px;border-radius:10px;border:1px solid var(--stroke,rgba(255,255,255,.08));background:var(--surface-1,rgba(255,255,255,.03));color:var(--ink,#ddd);cursor:pointer">${a.avatar_url || a.profile_image_url ? `<img src="${esc(a.avatar_url || a.profile_image_url)}" style="width:32px;height:32px;border-radius:50%;object-fit:cover">` : '<span style="width:32px;height:32px;border-radius:50%;background:var(--surface-2,rgba(255,255,255,.05));display:inline-block"></span>'}<span style="font-weight:600;color:var(--ink-bright,#fff)">${esc(a.name || short(a.id))}</span></button>`).join('')}</div>
+ <div style="text-align:right;margin-top:14px"><button id="mp-pf-cancel" style="font:inherit;font-size:.8rem;padding:8px 16px;border-radius:8px;border:1px solid var(--stroke-strong,rgba(255,255,255,.14));background:transparent;color:var(--ink,#ddd);cursor:pointer">Cancel</button></div>
+ </div>`;
+ const close = () => back.remove();
+ back.addEventListener('click', (e) => { if (e.target === back) close(); });
+ back.querySelector('#mp-pf-cancel').addEventListener('click', close);
+ back.querySelectorAll('[data-id]').forEach((b) => b.addEventListener('click', async () => {
+ close();
+ const saved = await openFollowModal({ followerId: b.dataset.id, followerName: b.dataset.name, leader });
+ if (saved) loadMine();
+ }));
+ document.body.appendChild(back);
+}
+
+const mineSection = document.getElementById('mp-mine-section');
+const mineEl = document.getElementById('mp-mine');
+let _panelHandles = [];
+
+async function loadMine() {
+ _panelHandles.forEach((h) => { try { h.destroy(); } catch { /* idempotent */ } });
+ _panelHandles = [];
+ try {
+ const res = await apiFetch('/api/agents', { allowAnonymous: true });
+ if (!res.ok) { mineSection.hidden = true; return; }
+ const j = await res.json();
+ myAgents = (j.agents || j.data?.agents || j.data || []).filter((a) => a && a.id);
+ } catch { myAgents = []; }
+
+ const withWallets = myAgents.filter((a) => a.meta?.solana_address || a.solana_address || a.agent_solana_address);
+ if (!myAgents.length) {
+ // Logged out or no agents — keep the section hidden; the board CTA covers it.
+ mineSection.hidden = true;
+ return;
+ }
+ mineSection.hidden = false;
+ if (!withWallets.length) {
+ mineEl.innerHTML = `<div class="mp-empty"><strong>Your agents are getting their wallets ready</strong>Once an agent has a wallet, you can have it mirror a leader.</div>`;
+ return;
+ }
+ mineEl.innerHTML = '';
+ for (const a of withWallets) {
+ const card = document.createElement('div');
+ card.className = 'mp-agent-card';
+ const head = document.createElement('div');
+ head.className = 'mp-agent-head';
+ head.innerHTML = `${a.avatar_url || a.profile_image_url ? `<img class="mp-av" src="${esc(a.avatar_url || a.profile_image_url)}" alt="">` : '<div class="mp-av"></div>'}<div class="mp-lname"><a href="/agent/${esc(a.id)}">${esc(a.name || short(a.id))}</a></div>`;
+ const panelMount = document.createElement('div');
+ card.appendChild(head);
+ card.appendChild(panelMount);
+ mineEl.appendChild(card);
+ // The owner panel reveals its own content; on this page the card is always shown.
+ const agentRec = { id: a.id, name: a.name, isOwner: true, rawMetadata: { meta: a.meta || { solana_address: a.solana_address || a.agent_solana_address } } };
+ const handle = mountMirrorPanel({ mount: panelMount, agent: agentRec, isOwner: true });
+ _panelHandles.push(handle);
+ }
+}
+
+sortSeg.addEventListener('click', (e) => {
+ const b = e.target.closest('button[data-sort]');
+ if (!b) return;
+ sort = b.dataset.sort;
+ sortSeg.querySelectorAll('button').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
+ const u = new URL(location.href); u.searchParams.set('sort', sort); history.replaceState(null, '', u);
+ loadBoard();
+});
+sortSeg.querySelectorAll('button').forEach((x) => x.setAttribute('aria-pressed', String(x.dataset.sort === sort)));
+
+loadBoard();
+loadMine();
+window.addEventListener('auth:resolved', loadMine, { once: true });
diff --git a/src/shared/agent-mirror-panel.js b/src/shared/agent-mirror-panel.js
new file mode 100644
index 000000000..4be3ecd26
--- /dev/null
+++ b/src/shared/agent-mirror-panel.js
@@ -0,0 +1,587 @@
+// Shared Copy-Trading (mirror) panel — the avatar↔wallet↔identity weld made into
+// a leashed, autonomous fund manager. Mounted on the agent detail page; renders
+// the right view for the viewer's role:
+//
+// • Owner of the viewed agent → manage who THIS agent mirrors: the prominent
+// leash (kill switch + per-follow caps), the live "mirrored from @leader"
+// fill feed, enable/pause/unfollow, and "Sync now".
+// • Visitor (the viewed agent is a potential LEADER) → its honest, on-chain
+// track record + "Mirror this agent" with one of your own agents.
+// • Logged-out → track record + sign-in prompt.
+//
+// 100% real: every number is from /api/agents/:id/mirror* (real fills, real
+// signatures, real spend-policy caps). No mock leaders, no fake fills.
+
+import { apiFetch } from '../api.js';
+
+const VIOLET = 'var(--wallet-accent, #c4b5fd)';
+
+// ── tiny shared toast (no global toast in src/shared) ─────────────────────────
+let _toastEl = null;
+let _toastTimer = null;
+function toast(msg, ms = 2600) {
+ if (typeof document === 'undefined') return;
+ if (!_toastEl) {
+ _toastEl = document.createElement('div');
+ _toastEl.className = 'mir-toast';
+ _toastEl.setAttribute('role', 'status');
+ _toastEl.setAttribute('aria-live', 'polite');
+ document.body.appendChild(_toastEl);
+ }
+ _toastEl.textContent = msg;
+ _toastEl.dataset.show = 'true';
+ clearTimeout(_toastTimer);
+ _toastTimer = setTimeout(() => { if (_toastEl) _toastEl.dataset.show = 'false'; }, ms);
+}
+
+// ── helpers ───────────────────────────────────────────────────────────────────
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const shortAddr = (a, h = 4, t = 4) => (a && a.length > h + t + 1 ? `${a.slice(0, h)}…${a.slice(-t)}` : a || '');
+function fmtSol(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ if (v === 0) return '0';
+ if (Math.abs(v) < 0.001) return v.toExponential(1);
+ return `${v.toFixed(v < 1 ? 4 : 2).replace(/\.?0+$/, '')}`;
+}
+function fmtUsd(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '';
+ const v = Number(n);
+ if (v >= 1e6) return `$${(v / 1e6).toFixed(1)}M`;
+ if (v >= 1e3) return `$${(v / 1e3).toFixed(1)}K`;
+ return `$${v.toFixed(2)}`;
+}
+function timeAgo(t) {
+ if (!t) return '';
+ const d = (Date.now() - new Date(t).getTime()) / 1000;
+ if (d < 60) return 'just now';
+ if (d < 3600) return `${Math.floor(d / 60)}m ago`;
+ if (d < 86400) return `${Math.floor(d / 3600)}h ago`;
+ return `${Math.floor(d / 86400)}d ago`;
+}
+function sizingSummary(f) {
+ if (f.sizing_mode === 'fixed') return `${fmtSol(f.fixed_sol)} SOL per trade`;
+ if (f.sizing_mode === 'pct_balance') return `${f.pct_balance}% of balance`;
+ return `${f.proportion_pct}% of leader's size`;
+}
+function leashSummary(f) {
+ const parts = [];
+ if (f.max_per_trade_sol != null) parts.push(`max ◎${fmtSol(f.max_per_trade_sol)}/trade`);
+ if (f.daily_budget_sol != null) parts.push(`◎${fmtSol(f.daily_budget_sol)}/day`);
+ if (!f.copy_sells) parts.push('buys only');
+ return parts.join(' · ');
+}
+
+// ── styles ────────────────────────────────────────────────────────────────────
+const STYLE_ID = 'mir-panel-styles';
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const s = document.createElement('style');
+ s.id = STYLE_ID;
+ s.textContent = `
+.mir { font-family: var(--font-body, system-ui); color: var(--ink, #e8e8e8); display: flex; flex-direction: column; gap: var(--space-sm, 10px); }
+.mir-sk { height: 56px; border-radius: var(--radius-md, 10px); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.03)) 25%, var(--surface-2, rgba(255,255,255,.05)) 50%, var(--surface-1, rgba(255,255,255,.03)) 75%); background-size: 200% 100%; animation: mir-sh 1.3s infinite; }
+@keyframes mir-sh { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+.mir-empty { text-align: center; padding: var(--space-lg, 22px) var(--space-md, 16px); color: var(--ink-dim, #9a9a9a); font-size: var(--text-sm, .8rem); line-height: 1.5; }
+.mir-empty strong { color: var(--ink-bright, #fff); display: block; margin-bottom: 4px; font-family: var(--font-display, inherit); }
+.mir-err { color: var(--danger, #f87171); font-size: var(--text-sm, .8rem); padding: var(--space-sm, 10px); }
+
+.mir-leash { display: flex; align-items: center; gap: var(--space-sm, 10px); padding: var(--space-sm, 10px) var(--space-md, 14px);
+ border: 1px solid var(--wallet-stroke, rgba(139,92,246,.3)); border-radius: var(--radius-md, 10px);
+ background: var(--wallet-accent-soft, rgba(139,92,246,.08)); }
+.mir-leash-ico { width: 26px; height: 26px; flex: 0 0 auto; color: ${VIOLET}; }
+.mir-leash-txt { flex: 1 1 auto; font-size: var(--text-xs, .72rem); color: var(--ink-dim, #b8b8b8); line-height: 1.4; }
+.mir-leash-txt b { color: ${VIOLET}; font-family: var(--font-mono, monospace); }
+.mir-kill { flex: 0 0 auto; }
+
+.mir-toggle { display: inline-flex; align-items: center; gap: 7px; cursor: pointer; user-select: none; font-size: var(--text-xs, .72rem); color: var(--ink-dim, #b8b8b8); }
+.mir-switch { width: 38px; height: 22px; border-radius: 999px; background: var(--surface-3, rgba(255,255,255,.1)); position: relative; transition: background var(--duration-fast, .18s) var(--ease-standard, ease); flex: 0 0 auto; }
+.mir-switch::after { content: ''; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; transition: transform var(--duration-fast, .18s) var(--ease-standard, ease); }
+.mir-switch[data-on="true"] { background: var(--danger, #f87171); }
+.mir-switch[data-on="true"]::after { transform: translateX(16px); }
+.mir-switch.mir-switch-go[data-on="true"] { background: var(--success, #4ade80); }
+
+.mir-follow { display: flex; align-items: center; gap: var(--space-sm, 10px); padding: var(--space-sm, 10px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); transition: border-color var(--duration-fast, .18s); }
+.mir-follow:hover { border-color: var(--wallet-stroke, rgba(139,92,246,.3)); }
+.mir-follow[data-paused="true"] { opacity: .58; }
+.mir-av { width: 34px; height: 34px; border-radius: 50%; object-fit: cover; background: var(--surface-2, rgba(255,255,255,.05)); flex: 0 0 auto; }
+.mir-fl-body { flex: 1 1 auto; min-width: 0; }
+.mir-fl-name { font-size: var(--text-sm, .82rem); font-weight: 600; color: var(--ink-bright, #fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.mir-fl-sub { font-size: var(--text-2xs, .66rem); color: var(--ink-dim, #9a9a9a); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.mir-fl-actions { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }
+
+.mir-btn { font: inherit; font-size: var(--text-2xs, .68rem); padding: 5px 10px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-2, rgba(255,255,255,.05)); color: var(--ink, #e8e8e8); cursor: pointer; transition: all var(--duration-fast, .18s); white-space: nowrap; }
+.mir-btn:hover { border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); color: #fff; }
+.mir-btn:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+.mir-btn-primary { background: ${VIOLET}; color: #1a1340; border-color: transparent; font-weight: 700; }
+.mir-btn-primary:hover { background: var(--wallet-accent-strong, #a78bfa); color: #1a1340; }
+.mir-btn-danger { color: var(--danger, #f87171); border-color: var(--danger, #f87171); background: transparent; }
+.mir-btn-ico { padding: 5px 8px; line-height: 1; }
+
+.mir-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(80px, 1fr)); gap: var(--space-xs, 8px); }
+.mir-stat { padding: var(--space-sm, 10px); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.06)); text-align: center; }
+.mir-stat-v { font-family: var(--font-mono, monospace); font-size: var(--text-md, .9rem); font-weight: 700; color: var(--ink-bright, #fff); }
+.mir-stat-v.pos { color: var(--success, #4ade80); }
+.mir-stat-v.neg { color: var(--danger, #f87171); }
+.mir-stat-l { font-size: var(--text-2xs, .62rem); color: var(--ink-dim, #9a9a9a); text-transform: uppercase; letter-spacing: .04em; margin-top: 3px; }
+
+.mir-feed { display: flex; flex-direction: column; gap: 6px; }
+.mir-fill { display: flex; align-items: center; gap: 8px; font-size: var(--text-xs, .72rem); padding: 7px 9px; border-radius: var(--radius-sm, 6px); background: var(--surface-1, rgba(255,255,255,.025)); }
+.mir-dot { width: 7px; height: 7px; border-radius: 50%; flex: 0 0 auto; background: var(--ink-dim, #888); }
+.mir-dot.ok { background: var(--success, #4ade80); }
+.mir-dot.skip { background: var(--warn, #fbbf24); }
+.mir-dot.fail { background: var(--danger, #f87171); }
+.mir-fill-main { flex: 1 1 auto; min-width: 0; color: var(--ink, #ddd); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.mir-fill-main b { color: ${VIOLET}; }
+.mir-fill-side { font-family: var(--font-mono, monospace); text-transform: uppercase; font-size: var(--text-2xs, .62rem); letter-spacing: .05em; }
+.mir-fill-side.buy { color: var(--success, #4ade80); }
+.mir-fill-side.sell { color: var(--danger, #f87171); }
+.mir-fill-time { flex: 0 0 auto; color: var(--ink-faint, #777); font-size: var(--text-2xs, .62rem); }
+.mir-fill a { color: ${VIOLET}; text-decoration: none; }
+.mir-fill a:hover { text-decoration: underline; }
+
+.mir-row { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm, 10px); }
+.mir-h { font-size: var(--text-2xs, .64rem); text-transform: uppercase; letter-spacing: .07em; color: var(--ink-dim, #9a9a9a); margin: var(--space-xs, 8px) 0 2px; }
+
+.mir-modal-back { position: fixed; inset: 0; background: rgba(0,0,0,.66); backdrop-filter: blur(var(--blur-sm, 4px)); z-index: 9998; display: flex; align-items: center; justify-content: center; padding: 16px; }
+.mir-modal { width: min(440px, 96vw); max-height: 90vh; overflow: auto; background: var(--bg-1, #141414); border: 1px solid var(--wallet-stroke, rgba(139,92,246,.3)); border-radius: var(--radius-lg, 14px); padding: var(--space-lg, 22px); box-shadow: var(--shadow-3, 0 24px 64px rgba(0,0,0,.6)); }
+.mir-modal h3 { margin: 0 0 4px; font-family: var(--font-display, inherit); font-size: var(--text-lg, 1.05rem); color: var(--ink-bright, #fff); }
+.mir-modal .mir-sub { font-size: var(--text-xs, .72rem); color: var(--ink-dim, #9a9a9a); margin: 0 0 var(--space-md, 16px); line-height: 1.5; }
+.mir-field { margin-bottom: var(--space-sm, 12px); }
+.mir-field label { display: block; font-size: var(--text-2xs, .66rem); text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim, #9a9a9a); margin-bottom: 5px; }
+.mir-field input, .mir-field select { width: 100%; box-sizing: border-box; font: inherit; font-size: var(--text-sm, .82rem); padding: 8px 10px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-1, rgba(255,255,255,.03)); color: var(--ink-bright, #fff); }
+.mir-field input:focus, .mir-field select:focus { outline: none; border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); }
+.mir-seg { display: flex; gap: 6px; }
+.mir-seg button { flex: 1; font: inherit; font-size: var(--text-2xs, .68rem); padding: 7px 4px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke, rgba(255,255,255,.1)); background: var(--surface-1, rgba(255,255,255,.03)); color: var(--ink-dim, #b8b8b8); cursor: pointer; }
+.mir-seg button[aria-pressed="true"] { border-color: ${VIOLET}; color: ${VIOLET}; background: var(--wallet-accent-soft, rgba(139,92,246,.1)); }
+.mir-leash-preview { font-size: var(--text-xs, .72rem); color: var(--ink-dim, #b8b8b8); line-height: 1.6; padding: var(--space-sm, 10px); border-radius: var(--radius-md, 10px); background: var(--wallet-accent-soft, rgba(139,92,246,.08)); border: 1px solid var(--wallet-stroke, rgba(139,92,246,.25)); margin: var(--space-sm, 10px) 0; }
+.mir-leash-preview b { color: ${VIOLET}; font-family: var(--font-mono, monospace); }
+.mir-modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: var(--space-md, 16px); }
+.mir-modal-actions .mir-btn { padding: 8px 16px; font-size: var(--text-sm, .8rem); }
+.mir-checkrow { display: flex; align-items: center; gap: 8px; font-size: var(--text-sm, .8rem); color: var(--ink, #ddd); cursor: pointer; }
+
+.mir-toast { position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%) translateY(10px); background: var(--bg-1, #1a1a1a); color: var(--ink-bright, #fff); border: 1px solid var(--wallet-stroke-strong, rgba(139,92,246,.5)); border-radius: var(--radius-md, 10px); padding: 11px 18px; font-size: var(--text-sm, .82rem); opacity: 0; pointer-events: none; transition: opacity .22s, transform .22s; z-index: 10000; max-width: 90vw; box-shadow: var(--shadow-2, 0 12px 32px rgba(0,0,0,.5)); }
+.mir-toast[data-show="true"] { opacity: 1; transform: translateX(-50%) translateY(0); }
+`;
+ document.head.appendChild(s);
+}
+
+const LEASH_SVG = '<svg class="mir-leash-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg>';
+
+// ── follow setup modal ────────────────────────────────────────────────────────
+// followerId mirrors leader. Returns a promise resolving true if a follow was saved.
+function openFollowModal({ followerId, followerName, leader, existing = null }) {
+ ensureStyles();
+ return new Promise((resolve) => {
+ const back = document.createElement('div');
+ back.className = 'mir-modal-back';
+ const state = {
+ sizing_mode: existing?.sizing_mode || 'proportional',
+ proportion_pct: existing?.proportion_pct ?? 100,
+ fixed_sol: existing?.fixed_sol ?? 0.1,
+ pct_balance: existing?.pct_balance ?? 10,
+ max_per_trade_sol: existing?.max_per_trade_sol ?? 0.5,
+ daily_budget_sol: existing?.daily_budget_sol ?? 2,
+ copy_sells: existing ? existing.copy_sells : true,
+ network: existing?.network || 'mainnet',
+ };
+
+ function sizingField() {
+ if (state.sizing_mode === 'fixed') return `<div class="mir-field"><label>Fixed SOL per trade</label><input type="number" step="0.01" min="0" id="mir-fixed" value="${state.fixed_sol}"></div>`;
+ if (state.sizing_mode === 'pct_balance') return `<div class="mir-field"><label>% of your wallet balance</label><input type="number" step="1" min="1" max="100" id="mir-pct" value="${state.pct_balance}"></div>`;
+ return `<div class="mir-field"><label>% of leader's trade size</label><input type="number" step="5" min="1" id="mir-prop" value="${state.proportion_pct}"></div>`;
+ }
+ function previewText() {
+ let line;
+ if (state.sizing_mode === 'fixed') line = `buy <b>◎${fmtSol(state.fixed_sol)}</b> on every leader buy`;
+ else if (state.sizing_mode === 'pct_balance') line = `spend <b>${state.pct_balance}%</b> of your balance per leader buy`;
+ else line = `match <b>${state.proportion_pct}%</b> of the leader's size`;
+ return `<strong>${esc(followerName || 'Your agent')}</strong> will ${line}, capped at <b>◎${fmtSol(state.max_per_trade_sol)}</b>/trade and <b>◎${fmtSol(state.daily_budget_sol)}</b>/day. ${state.copy_sells ? 'It exits when the leader exits.' : 'Buys only.'} You can pause or stop anytime.`;
+ }
+ function render() {
+ back.innerHTML = `<div class="mir-modal" role="dialog" aria-modal="true" aria-label="Set up mirroring">
+ <h3>${existing ? 'Edit' : 'Mirror'} ${esc(leader.name || 'agent')}</h3>
+ <p class="mir-sub">Your agent <b style="color:var(--ink-bright,#fff)">${esc(followerName || followerId.slice(0, 8))}</b> will auto-copy <b style="color:var(--ink-bright,#fff)">${esc(leader.name || shortAddr(leader.agent_id))}</b>'s real trades — within your spend policy, fully on-chain.</p>
+ <div class="mir-field"><label>Sizing</label>
+ <div class="mir-seg" id="mir-seg">
+ <button type="button" data-m="proportional" aria-pressed="${state.sizing_mode === 'proportional'}">Proportional</button>
+ <button type="button" data-m="fixed" aria-pressed="${state.sizing_mode === 'fixed'}">Fixed</button>
+ <button type="button" data-m="pct_balance" aria-pressed="${state.sizing_mode === 'pct_balance'}">% balance</button>
+ </div>
+ </div>
+ ${sizingField()}
+ <div class="mir-row" style="gap:10px">
+ <div class="mir-field" style="flex:1"><label>Max ◎ / trade</label><input type="number" step="0.05" min="0" id="mir-cap" value="${state.max_per_trade_sol}"></div>
+ <div class="mir-field" style="flex:1"><label>Max ◎ / day</label><input type="number" step="0.1" min="0" id="mir-daily" value="${state.daily_budget_sol}"></div>
+ </div>
+ <div class="mir-field"><label>Network</label>
+ <select id="mir-net"><option value="mainnet" ${state.network === 'mainnet' ? 'selected' : ''}>Mainnet</option><option value="devnet" ${state.network === 'devnet' ? 'selected' : ''}>Devnet</option></select>
+ </div>
+ <label class="mir-checkrow"><input type="checkbox" id="mir-sells" ${state.copy_sells ? 'checked' : ''}> Mirror exits (sell when the leader sells)</label>
+ <div class="mir-leash-preview">${LEASH_SVG.replace('mir-leash-ico', 'mir-leash-ico" style="width:16px;height:16px;vertical-align:-3px')} ${previewText()}</div>
+ <div class="mir-modal-actions">
+ <button type="button" class="mir-btn" id="mir-cancel">Cancel</button>
+ <button type="button" class="mir-btn mir-btn-primary" id="mir-save">${existing ? 'Save' : 'Start mirroring'}</button>
+ </div>
+ </div>`;
+ wire();
+ }
+ function readInputs() {
+ const q = (id) => back.querySelector(id);
+ if (state.sizing_mode === 'fixed') state.fixed_sol = Number(q('#mir-fixed')?.value) || 0;
+ else if (state.sizing_mode === 'pct_balance') state.pct_balance = Number(q('#mir-pct')?.value) || 0;
+ else state.proportion_pct = Number(q('#mir-prop')?.value) || 0;
+ state.max_per_trade_sol = Number(q('#mir-cap')?.value) || 0;
+ state.daily_budget_sol = Number(q('#mir-daily')?.value) || 0;
+ state.network = q('#mir-net')?.value || 'mainnet';
+ state.copy_sells = !!q('#mir-sells')?.checked;
+ }
+ function wire() {
+ back.querySelectorAll('#mir-seg button').forEach((b) => {
+ b.addEventListener('click', () => { readInputs(); state.sizing_mode = b.dataset.m; render(); });
+ });
+ ['#mir-fixed', '#mir-pct', '#mir-prop', '#mir-cap', '#mir-daily', '#mir-sells'].forEach((sel) => {
+ back.querySelector(sel)?.addEventListener('input', () => { readInputs(); const p = back.querySelector('.mir-leash-preview'); if (p) p.innerHTML = `${LEASH_SVG.replace('mir-leash-ico', 'mir-leash-ico" style="width:16px;height:16px;vertical-align:-3px')} ${previewText()}`; });
+ });
+ back.querySelector('#mir-cancel').addEventListener('click', close);
+ back.querySelector('#mir-save').addEventListener('click', save);
+ }
+ async function save() {
+ readInputs();
+ const btn = back.querySelector('#mir-save');
+ btn.disabled = true; btn.textContent = 'Saving…';
+ try {
+ const res = await apiFetch(`/api/agents/${followerId}/mirror`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ leader_agent_id: leader.agent_id,
+ network: state.network,
+ sizing_mode: state.sizing_mode,
+ fixed_sol: state.fixed_sol,
+ proportion_pct: state.proportion_pct,
+ pct_balance: state.pct_balance,
+ max_per_trade_sol: state.max_per_trade_sol,
+ daily_budget_sol: state.daily_budget_sol,
+ copy_sells: state.copy_sells,
+ enabled: true,
+ }),
+ });
+ if (!res.ok) {
+ const j = await res.json().catch(() => ({}));
+ throw new Error(j?.error?.message || j?.message || 'Could not save');
+ }
+ toast(`Mirroring ${leader.name || 'agent'} — within your limits`);
+ close(true);
+ } catch (e) {
+ if (e?.redirected) return;
+ btn.disabled = false; btn.textContent = existing ? 'Save' : 'Start mirroring';
+ toast(e.message || 'Could not save mirroring');
+ }
+ }
+ function close(saved) {
+ document.removeEventListener('keydown', onKey);
+ back.remove();
+ resolve(!!saved);
+ }
+ function onKey(e) { if (e.key === 'Escape') close(false); }
+ back.addEventListener('click', (e) => { if (e.target === back) close(false); });
+ document.addEventListener('keydown', onKey);
+ render();
+ document.body.appendChild(back);
+ back.querySelector('#mir-save')?.focus();
+ });
+}
+
+export { openFollowModal };
+
+// ── the panel ─────────────────────────────────────────────────────────────────
+export function mountMirrorPanel({ mount, agent, isOwner = false }) {
+ if (!mount) return { destroy() {} };
+ ensureStyles();
+ const card = mount.closest('#ad-mirror-card') || mount.parentElement;
+ const agentId = agent.id;
+ let alive = true;
+ // The page resolves login async via /api/auth/me → window.__authed (undefined
+ // while pending). Optimistic until the probe says guest, then we re-render.
+ const isLoggedIn = () => window.__authed !== false;
+ const root = document.createElement('div');
+ root.className = 'mir';
+ mount.replaceChildren(root);
+ root.innerHTML = '<div class="mir-sk"></div><div class="mir-sk"></div>';
+
+ const show = () => { if (card) card.hidden = false; };
+ const hide = () => { if (card) card.hidden = true; };
+
+ function statEl(v, label, cls = '') {
+ return `<div class="mir-stat"><div class="mir-stat-v ${cls}">${v}</div><div class="mir-stat-l">${label}</div></div>`;
+ }
+
+ // Render the owner management view from /mirror.
+ function renderOwner(d) {
+ const followsHtml = d.following.length
+ ? d.following.map((f) => `
+ <div class="mir-follow" data-paused="${!f.enabled}" data-leader="${esc(f.leader_agent_id)}">
+ ${f.leader_avatar ? `<img class="mir-av" src="${esc(f.leader_avatar)}" alt="">` : '<div class="mir-av"></div>'}
+ <div class="mir-fl-body">
+ <div class="mir-fl-name"><a href="/agent/${esc(f.leader_agent_id)}" style="color:inherit;text-decoration:none">${esc(f.leader_name || shortAddr(f.leader_agent_id))}</a></div>
+ <div class="mir-fl-sub">${esc(sizingSummary(f))}${leashSummary(f) ? ' · ' + esc(leashSummary(f)) : ''}</div>
+ </div>
+ <div class="mir-fl-actions">
+ <label class="mir-toggle" title="${f.enabled ? 'Pause' : 'Resume'} this follow"><span class="mir-switch mir-switch-go" data-on="${f.enabled}" data-act="toggle"></span></label>
+ <button class="mir-btn mir-btn-ico" data-act="edit" title="Edit leash">✎</button>
+ <button class="mir-btn mir-btn-ico mir-btn-danger" data-act="unfollow" title="Stop following">✕</button>
+ </div>
+ </div>`).join('')
+ : `<div class="mir-empty"><strong>Not mirroring anyone yet</strong>Follow a high-performing agent and this wallet copies its real trades — within your spend policy. <br><a href="/mirror" style="color:${VIOLET}">Discover leaders →</a></div>`;
+
+ const recentHtml = d.recent.length
+ ? `<div class="mir-h">Recent mirror activity</div><div class="mir-feed">${d.recent.map(fillRow).join('')}</div>`
+ : '';
+
+ root.innerHTML = `
+ <div class="mir-leash">
+ ${LEASH_SVG}
+ <div class="mir-leash-txt">${d.killed
+ ? 'Mirroring is <b>halted</b> by the kill switch. No trades will copy until you turn it back on.'
+ : `Leashed autonomy: this wallet mirrors <b>${d.following_count}</b> ${d.following_count === 1 ? 'leader' : 'leaders'}, strictly inside your spend policy. Stop anytime.`}</div>
+ <label class="mir-toggle mir-kill" title="${d.killed ? 'Resume all mirroring' : 'Halt ALL mirroring instantly'}">${d.killed ? 'Killed' : 'Kill'} <span class="mir-switch" data-on="${d.killed}" data-act="kill"></span></label>
+ </div>
+ <div class="mir-row">
+ <div style="font-size:var(--text-2xs,.64rem);color:var(--ink-dim,#9a9a9a)">${d.followers_count ? `${d.followers_count} ${d.followers_count === 1 ? 'agent mirrors' : 'agents mirror'} you · ` : ''}following ${d.following_count}</div>
+ <button class="mir-btn" data-act="sync" ${d.killed ? 'disabled' : ''} title="Check leaders for new trades now">↻ Sync now</button>
+ </div>
+ <div id="mir-follows">${followsHtml}</div>
+ <div style="text-align:center"><button class="mir-btn mir-btn-primary" data-act="add" style="margin-top:4px">+ Mirror an agent</button></div>
+ ${recentHtml}`;
+ wireOwner(d);
+ }
+
+ function fillRow(f) {
+ const dot = f.status === 'executed' ? 'ok' : f.status === 'skipped' ? 'skip' : f.status === 'unconfirmed' ? 'skip' : 'fail';
+ const sideCls = f.side === 'sell' ? 'sell' : 'buy';
+ let detail;
+ if (f.status === 'executed') detail = `${f.side === 'buy' ? 'bought' : 'sold'} ${f.planned_sol != null ? `◎${fmtSol(f.planned_sol)} of ` : ''}${shortAddr(f.mint)}${f.usd != null ? ` (${fmtUsd(f.usd)})` : ''}`;
+ else if (f.status === 'unconfirmed') detail = `submitted ${shortAddr(f.mint)} — confirming`;
+ else if (f.status === 'skipped') detail = `skipped ${shortAddr(f.mint)} — ${esc(f.skip_label || f.skip_reason || 'no reason')}`;
+ else detail = `failed ${shortAddr(f.mint)}${f.skip_label ? ` — ${esc(f.skip_label)}` : ''}`;
+ const sig = f.signature ? ` <a href="https://solscan.io/tx/${esc(f.signature)}" target="_blank" rel="noopener" title="View on Solscan">↗</a>` : '';
+ return `<div class="mir-fill"><span class="mir-dot ${dot}"></span><span class="mir-fill-side ${sideCls}">${f.side}</span><span class="mir-fill-main">mirrored from <b>${esc(f.leader_name || shortAddr(f.leader_agent_id))}</b> · ${detail}${sig}</span><span class="mir-fill-time">${timeAgo(f.at)}</span></div>`;
+ }
+
+ function wireOwner(d) {
+ root.querySelector('[data-act="kill"]')?.parentElement?.addEventListener('click', async (e) => {
+ e.preventDefault();
+ const next = !d.killed;
+ await postAction('kill', { killed: next }, next ? 'All mirroring halted' : 'Mirroring resumed');
+ load();
+ });
+ root.querySelector('[data-act="sync"]')?.addEventListener('click', async (e) => {
+ const btn = e.currentTarget; btn.disabled = true; btn.textContent = 'Syncing…';
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/mirror/sync`, { method: 'POST' });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(j?.error?.message || 'Sync failed');
+ const all = (j.data?.synced || []).flatMap((s) => s.results || []);
+ const exec = all.filter((r) => r.status === 'executed').length;
+ const skip = all.filter((r) => r.status === 'skipped').length;
+ toast(all.length ? `Mirror sync: ${exec} executed, ${skip} skipped` : 'No new leader trades to mirror');
+ } catch (err) { if (!err?.redirected) toast(err.message || 'Sync failed'); }
+ load();
+ });
+ root.querySelector('[data-act="add"]')?.addEventListener('click', () => openLeaderPicker());
+ root.querySelectorAll('.mir-follow').forEach((row) => {
+ const leaderId = row.dataset.leader;
+ const f = d.following.find((x) => x.leader_agent_id === leaderId);
+ row.querySelector('[data-act="toggle"]')?.parentElement?.addEventListener('click', async (e) => {
+ e.preventDefault();
+ await saveFollowPatch(f, { enabled: !f.enabled });
+ load();
+ });
+ row.querySelector('[data-act="edit"]')?.addEventListener('click', async () => {
+ const saved = await openFollowModal({ followerId: agentId, followerName: agent.name, leader: { agent_id: leaderId, name: f.leader_name }, existing: f });
+ if (saved) load();
+ });
+ row.querySelector('[data-act="unfollow"]')?.addEventListener('click', async () => {
+ if (!confirm(`Stop mirroring ${f.leader_name || 'this agent'}? In-flight trades complete; no new ones start.`)) return;
+ await postAction('unfollow', { leader_agent_id: leaderId }, 'Stopped mirroring');
+ load();
+ });
+ });
+ }
+
+ async function saveFollowPatch(f, patch) {
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/mirror`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ leader_agent_id: f.leader_agent_id, network: f.network,
+ sizing_mode: f.sizing_mode, fixed_sol: f.fixed_sol, proportion_pct: f.proportion_pct,
+ pct_balance: f.pct_balance, max_per_trade_sol: f.max_per_trade_sol,
+ daily_budget_sol: f.daily_budget_sol, min_leader_sol: f.min_leader_sol,
+ copy_sells: f.copy_sells, ...patch,
+ }),
+ });
+ if (!res.ok) throw new Error('Could not update');
+ toast(patch.enabled === false ? 'Follow paused' : 'Follow resumed');
+ } catch (e) { if (!e?.redirected) toast(e.message || 'Update failed'); }
+ }
+
+ async function postAction(action, body, okMsg) {
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/mirror/${action}`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body || {}),
+ });
+ if (!res.ok) { const j = await res.json().catch(() => ({})); throw new Error(j?.error?.message || 'Action failed'); }
+ if (okMsg) toast(okMsg);
+ } catch (e) { if (!e?.redirected) toast(e.message || 'Action failed'); }
+ }
+
+ // Pick a leader to mirror (from the discovery leaderboard or a pasted id).
+ async function openLeaderPicker() {
+ let leaders = [];
+ try {
+ const res = await apiFetch('/api/mirror/leaderboard?sort=score&limit=12', { allowAnonymous: true });
+ if (res.ok) leaders = (await res.json()).data?.leaders || [];
+ } catch { /* fall back to manual entry */ }
+ leaders = leaders.filter((l) => l.agent_id !== agentId);
+ const back = document.createElement('div');
+ back.className = 'mir-modal-back';
+ back.innerHTML = `<div class="mir-modal" role="dialog" aria-modal="true" aria-label="Pick a leader">
+ <h3>Mirror a leader</h3>
+ <p class="mir-sub">Pick an agent to copy by its real track record, or paste an agent ID. Your agent executes its trades within your limits.</p>
+ <div class="mir-field"><label>Agent ID</label><input id="mir-leader-id" placeholder="uuid of the agent to mirror"></div>
+ ${leaders.length ? '<div class="mir-h">Top performers</div><div class="mir-feed" id="mir-leaders">' + leaders.map((l) => `<button type="button" class="mir-follow" data-id="${esc(l.agent_id)}" data-name="${esc(l.name || '')}" style="width:100%;text-align:left;cursor:pointer;border:1px solid var(--stroke,rgba(255,255,255,.08))">${l.avatar ? `<img class="mir-av" src="${esc(l.avatar)}" alt="">` : '<div class="mir-av"></div>'}<div class="mir-fl-body"><div class="mir-fl-name">#${l.rank} ${esc(l.name || shortAddr(l.agent_id))}</div><div class="mir-fl-sub">${l.roi_pct != null ? `${l.roi_pct > 0 ? '+' : ''}${l.roi_pct}% ROI · ` : ''}${l.win_rate != null ? `${l.win_rate}% win · ` : ''}${l.followers} followers</div></div></button>`).join('') + '</div>' : ''}
+ <div class="mir-modal-actions"><button type="button" class="mir-btn" id="mir-pick-cancel">Cancel</button></div>
+ </div>`;
+ const close = () => { back.remove(); document.removeEventListener('keydown', onKey); };
+ const onKey = (e) => { if (e.key === 'Escape') close(); };
+ back.addEventListener('click', (e) => { if (e.target === back) close(); });
+ document.addEventListener('keydown', onKey);
+ back.querySelector('#mir-pick-cancel').addEventListener('click', close);
+ const choose = async (leaderId, name) => {
+ leaderId = (leaderId || '').trim();
+ if (!/^[0-9a-f-]{36}$/i.test(leaderId)) { toast('Enter a valid agent ID'); return; }
+ if (leaderId === agentId) { toast('An agent cannot mirror itself'); return; }
+ close();
+ const saved = await openFollowModal({ followerId: agentId, followerName: agent.name, leader: { agent_id: leaderId, name } });
+ if (saved) load();
+ };
+ back.querySelectorAll('#mir-leaders [data-id]').forEach((b) => b.addEventListener('click', () => choose(b.dataset.id, b.dataset.name)));
+ back.querySelector('#mir-leader-id').addEventListener('keydown', (e) => { if (e.key === 'Enter') choose(e.target.value); });
+ document.body.appendChild(back);
+ back.querySelector('#mir-leader-id').focus();
+ }
+
+ // Render the visitor / logged-out view: this agent is a potential LEADER.
+ function renderLeader(record, agentMeta) {
+ const r = record.record;
+ const hasHistory = r.total > 0;
+ const pnlCls = r.realized.pnl_sol > 0 ? 'pos' : r.realized.pnl_sol < 0 ? 'neg' : '';
+ const statsHtml = hasHistory ? `
+ <div class="mir-stats">
+ ${statEl(`${r.realized.pnl_sol > 0 ? '+' : ''}${fmtSol(r.realized.pnl_sol)}`, 'P&L ◎', pnlCls)}
+ ${statEl(r.realized.win_rate != null ? `${r.realized.win_rate}%` : '—', 'Win rate')}
+ ${statEl(r.realized.roi_pct != null ? `${r.realized.roi_pct}%` : '—', 'ROI', r.realized.roi_pct > 0 ? 'pos' : r.realized.roi_pct < 0 ? 'neg' : '')}
+ ${statEl(`◎${fmtSol(r.realized.max_drawdown_sol)}`, 'Max DD')}
+ ${statEl(r.total, 'Trades')}
+ ${statEl(r.followers.total, 'Followers')}
+ </div>
+ <div style="font-size:var(--text-2xs,.62rem);color:var(--ink-faint,#777);text-align:center">Real on-chain track record · ${r.realized.settled} settled (${r.realized.wins}W / ${r.realized.losses}L)${r.last_trade_at ? ' · last trade ' + timeAgo(r.last_trade_at) : ''}</div>
+ ` : `<div class="mir-empty"><strong>No track record yet</strong>This agent hasn't made any trades. Its stats appear here the moment it does — every number on-chain-verified.</div>`;
+
+ const cta = isLoggedIn()
+ ? `<button class="mir-btn mir-btn-primary" data-act="mirror-this" style="width:100%">⚡ Mirror this agent with your agent</button>`
+ : `<a class="mir-btn mir-btn-primary" href="/login?next=${encodeURIComponent(location.pathname)}" style="width:100%;display:block;text-align:center;text-decoration:none">Sign in to mirror this agent</a>`;
+
+ root.innerHTML = `${statsHtml}<div style="margin-top:var(--space-sm,10px)">${cta}</div>
+ <div style="font-size:var(--text-2xs,.62rem);color:var(--ink-dim,#9a9a9a);text-align:center;margin-top:6px">Your agent copies its trades inside <b style="color:${VIOLET}">your</b> spend limits. Stop anytime.</div>`;
+
+ root.querySelector('[data-act="mirror-this"]')?.addEventListener('click', () => pickFollowerForLeader(agentMeta));
+ }
+
+ // Visitor flow: choose which of MY agents should mirror the viewed leader.
+ async function pickFollowerForLeader(leaderAgent) {
+ let mine = [];
+ try {
+ const res = await apiFetch('/api/agents', { allowAnonymous: true });
+ if (res.ok) {
+ const j = await res.json();
+ mine = (j.agents || j.data?.agents || j.data || []).filter((a) => a && a.id && a.id !== agentId);
+ }
+ } catch { /* handled below */ }
+ if (!mine.length) { toast('You need your own agent first — create or fork one'); return; }
+
+ const leader = { agent_id: agentId, name: leaderAgent.name };
+ if (mine.length === 1) {
+ const saved = await openFollowModal({ followerId: mine[0].id, followerName: mine[0].name, leader });
+ if (saved) load();
+ return;
+ }
+ const back = document.createElement('div');
+ back.className = 'mir-modal-back';
+ back.innerHTML = `<div class="mir-modal" role="dialog" aria-modal="true" aria-label="Pick your agent">
+ <h3>Which agent should mirror?</h3>
+ <p class="mir-sub">Pick the agent whose wallet will copy ${esc(leaderAgent.name || 'this leader')}'s trades.</p>
+ <div class="mir-feed">${mine.map((a) => `<button type="button" class="mir-follow" data-id="${esc(a.id)}" data-name="${esc(a.name || '')}" style="width:100%;text-align:left;cursor:pointer">${a.avatar_url || a.profile_image_url ? `<img class="mir-av" src="${esc(a.avatar_url || a.profile_image_url)}" alt="">` : '<div class="mir-av"></div>'}<div class="mir-fl-body"><div class="mir-fl-name">${esc(a.name || shortAddr(a.id))}</div></div></button>`).join('')}</div>
+ <div class="mir-modal-actions"><button type="button" class="mir-btn" id="mir-fp-cancel">Cancel</button></div>
+ </div>`;
+ const close = () => { back.remove(); document.removeEventListener('keydown', onKey); };
+ const onKey = (e) => { if (e.key === 'Escape') close(); };
+ back.addEventListener('click', (e) => { if (e.target === back) close(); });
+ document.addEventListener('keydown', onKey);
+ back.querySelector('#mir-fp-cancel').addEventListener('click', close);
+ back.querySelectorAll('[data-id]').forEach((b) => b.addEventListener('click', async () => {
+ close();
+ const saved = await openFollowModal({ followerId: b.dataset.id, followerName: b.dataset.name, leader });
+ if (saved) load();
+ }));
+ document.body.appendChild(back);
+ }
+
+ async function load() {
+ if (!alive) return;
+ try {
+ if (isOwner) {
+ const res = await apiFetch(`/api/agents/${agentId}/mirror`, { allowAnonymous: true });
+ if (res.status === 403 || res.status === 401) { renderLeaderFallback(); return; }
+ if (!res.ok) throw new Error('load failed');
+ const d = (await res.json()).data;
+ show();
+ renderOwner(d);
+ } else {
+ renderLeaderFallback();
+ }
+ } catch (e) {
+ if (e?.redirected) return;
+ root.innerHTML = `<div class="mir-err">Couldn't load copy-trading. <button class="mir-btn" id="mir-retry">Retry</button></div>`;
+ root.querySelector('#mir-retry')?.addEventListener('click', load);
+ show();
+ }
+ }
+
+ let _authListener = null;
+ async function renderLeaderFallback() {
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/mirror/track-record`, { allowAnonymous: true });
+ if (!res.ok) { hide(); return; }
+ const d = (await res.json()).data;
+ show();
+ renderLeader(d, { name: agent.name });
+ // Re-render the CTA once the auth probe resolves (guest ↔ member).
+ if (!_authListener) {
+ _authListener = () => { if (alive) renderLeader(d, { name: agent.name }); };
+ window.addEventListener('auth:resolved', _authListener, { once: true });
+ }
+ } catch { hide(); }
+ }
+
+ load();
+ return {
+ destroy() {
+ alive = false;
+ if (_authListener) window.removeEventListener('auth:resolved', _authListener);
+ mount.replaceChildren();
+ },
+ };
+}
diff --git a/src/shared/agent-reputation.js b/src/shared/agent-reputation.js
new file mode 100644
index 000000000..ccd319c9c
--- /dev/null
+++ b/src/shared/agent-reputation.js
@@ -0,0 +1,486 @@
+// Shared wallet-reputation UI — the single source of truth for the trust badge
+// and the breakdown view, used everywhere an agent appears.
+//
+// In a world of infinite forkable avatars, trust is the scarce asset. This module
+// renders an agent's REAL, server-computed credibility score (see
+// api/_lib/trust/wallet-reputation.js) as:
+// • a compact badge that hangs off the wallet identity on every surface, and
+// • a full breakdown panel (HUD tab) that explains exactly why the score is
+// what it is, with links to the real evidence.
+//
+// All numbers come from GET /api/agents/:id/reputation (single) and
+// /api/agents/reputation-batch (lists). Nothing is computed or faked client-side;
+// a brand-new agent honestly renders as "New", never a fabricated number.
+
+import { apiFetch } from '../api.js';
+
+// ── tiny utils ──────────────────────────────────────────────────────────────
+const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+const SHIELD_SVG =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>';
+
+// ── data layer (real APIs, in-memory coalescing) ─────────────────────────────
+
+const _cache = new Map(); // agentId -> compact rep (lite)
+const _full = new Map(); // agentId -> full rep promise
+
+/**
+ * Full reputation for a single agent (score, pillars, evidence, guidance).
+ * Cached per page load; pass force to bypass.
+ */
+export async function fetchReputation(agentId, { force = false } = {}) {
+ if (!agentId) return null;
+ if (!force && _full.has(agentId)) return _full.get(agentId);
+ const p = (async () => {
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/reputation`, { allowAnonymous: true });
+ if (!res.ok) throw new Error(`reputation ${res.status}`);
+ return res.json();
+ })();
+ _full.set(agentId, p);
+ p.catch(() => _full.delete(agentId)); // don't cache failures
+ return p;
+}
+
+/**
+ * Compact reputation for many agents in one round-trip. Returns a map
+ * { agentId: { score, tier, tierLabel, accent, isNew, totals } }.
+ */
+export async function fetchReputationBatch(ids) {
+ const want = [...new Set((ids || []).filter((id) => id && UUID_RE.test(String(id))))].filter((id) => !_cache.has(id));
+ if (want.length) {
+ try {
+ const res = await apiFetch('/api/agents/reputation-batch', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ids: want }),
+ allowAnonymous: true,
+ });
+ if (res.ok) {
+ const { data } = await res.json();
+ for (const id of want) if (data?.[id]) _cache.set(id, data[id]);
+ }
+ } catch {
+ /* leave uncached; badges stay in their resting (unloaded) state */
+ }
+ }
+ const out = {};
+ for (const id of ids || []) if (_cache.get(id)) out[id] = _cache.get(id);
+ return out;
+}
+
+// ── badge rendering ──────────────────────────────────────────────────────────
+
+/**
+ * Inner markup for a hydrated badge given compact rep data. A brand-new agent
+ * renders an honest neutral "New" chip; everyone else gets a tier + score pill
+ * tinted by the server-provided tier accent.
+ */
+function badgeInner(rep) {
+ if (!rep) return '';
+ if (rep.isNew) {
+ return `<span class="rep-badge rep-badge--new" title="New agent — no track record yet">✦ New</span>`;
+ }
+ const score = Math.round(rep.score);
+ const tip = `Wallet trust ${score}/100 · ${rep.tierLabel}. Click for the breakdown.`;
+ return (
+ `<span class="rep-badge" style="--rep-accent:${esc(rep.accent || '#c4b5fd')}" title="${esc(tip)}">` +
+ SHIELD_SVG +
+ `<span class="rep-badge-tier">${esc(rep.tierLabel)}</span>` +
+ `<span class="rep-badge-score">${score}</span>` +
+ `</span>`
+ );
+}
+
+/**
+ * A placeholder badge that hydrates itself from the batch endpoint when it
+ * scrolls into view. `agentId` must be a real agent UUID. Returns an HTML string;
+ * call hydrateReputationBadges(root) after injecting, or use reputationBadgeEl()
+ * for a ready-wired node.
+ */
+export function reputationBadgeHTML(agentId, opts = {}) {
+ if (!agentId || !UUID_RE.test(String(agentId))) return '';
+ const embedded = opts.embedded ? ' data-rep-embedded="1"' : '';
+ return `<span class="rep-badge-slot" data-rep-aid="${esc(agentId)}"${embedded} aria-label="Wallet trust score loading"></span>`;
+}
+
+export function reputationBadgeEl(agentId, opts = {}) {
+ if (!isBrowser()) return null;
+ const html = reputationBadgeHTML(agentId, opts);
+ if (!html) return null;
+ const tpl = document.createElement('template');
+ tpl.innerHTML = html.trim();
+ const node = tpl.content.firstElementChild;
+ if (node) observeReputationBadge(node);
+ return node;
+}
+
+// shared observer + batch queue for placeholder badges
+let _io = null;
+const _queued = new Set(); // aids waiting to fetch
+let _flushT = null;
+
+function ensureIO() {
+ if (_io || !isBrowser() || typeof IntersectionObserver === 'undefined') return _io;
+ _io = new IntersectionObserver(
+ (entries) => {
+ let changed = false;
+ for (const e of entries) {
+ if (!e.isIntersecting) continue;
+ const aid = e.target.getAttribute('data-rep-aid');
+ if (aid && !_cache.has(aid)) {
+ _queued.add(aid);
+ changed = true;
+ } else if (aid && _cache.has(aid)) {
+ fillBadge(e.target, _cache.get(aid));
+ }
+ _io.unobserve(e.target);
+ }
+ if (changed) scheduleFlush();
+ },
+ { rootMargin: '150px' },
+ );
+ return _io;
+}
+
+function scheduleFlush() {
+ if (_flushT) return;
+ _flushT = setTimeout(async () => {
+ _flushT = null;
+ const ids = [..._queued];
+ _queued.clear();
+ if (!ids.length) return;
+ await fetchReputationBatch(ids);
+ // Fill every connected placeholder whose data just arrived.
+ if (!isBrowser()) return;
+ for (const el of document.querySelectorAll('.rep-badge-slot[data-rep-aid]')) {
+ const aid = el.getAttribute('data-rep-aid');
+ if (_cache.has(aid) && !el.__repFilled) fillBadge(el, _cache.get(aid));
+ }
+ }, 80);
+}
+
+function fillBadge(el, rep) {
+ if (!el || el.__repFilled) return;
+ el.__repFilled = true;
+ const inner = badgeInner(rep);
+ if (!inner) {
+ el.remove();
+ return;
+ }
+ el.innerHTML = inner;
+ el.removeAttribute('aria-label');
+ const aid = el.getAttribute('data-rep-aid');
+ const badge = el.firstElementChild;
+ if (badge && aid) {
+ badge.setAttribute('role', 'button');
+ badge.setAttribute('tabindex', '0');
+ const go = (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ openReputation(aid);
+ };
+ badge.addEventListener('click', go);
+ badge.addEventListener('keydown', (ev) => {
+ if (ev.key === 'Enter' || ev.key === ' ') go(ev);
+ });
+ }
+ ensureStyles();
+}
+
+/** Register a single placeholder element for lazy hydration. */
+export function observeReputationBadge(el) {
+ if (!el || !isBrowser()) return;
+ ensureStyles();
+ const aid = el.getAttribute?.('data-rep-aid');
+ if (!aid) return;
+ if (_cache.has(aid)) {
+ fillBadge(el, _cache.get(aid));
+ return;
+ }
+ const io = ensureIO();
+ if (io) io.observe(el);
+ else {
+ _queued.add(aid);
+ scheduleFlush();
+ }
+}
+
+/** Scan a container and lazily hydrate every reputation badge placeholder in it. */
+export function hydrateReputationBadges(root) {
+ if (!root || typeof root.querySelectorAll !== 'function') return;
+ for (const el of root.querySelectorAll('.rep-badge-slot[data-rep-aid]')) {
+ if (!el.__repObserved) {
+ el.__repObserved = true;
+ observeReputationBadge(el);
+ }
+ }
+}
+
+/** Navigate to the agent's wallet hub, reputation tab. */
+export function openReputation(agentId) {
+ if (!agentId || !isBrowser()) return;
+ window.location.assign(`/agent/${encodeURIComponent(agentId)}/wallet#reputation`);
+}
+
+// ── full breakdown panel (HUD tab) ───────────────────────────────────────────
+
+const FALLBACK_PILLAR_MAX = 25;
+
+function scoreRing(rep) {
+ const pct = Math.max(0, Math.min(100, rep.score));
+ const accent = rep.isNew ? 'var(--ink-faint,#6b7280)' : rep.accent || 'var(--wallet-accent,#c4b5fd)';
+ return (
+ `<div class="rep-ring" style="--rep-accent:${esc(accent)};--rep-pct:${pct}">` +
+ `<div class="rep-ring-num">${rep.isNew ? '—' : Math.round(rep.score)}</div>` +
+ `<div class="rep-ring-of">${rep.isNew ? 'new' : `/ ${rep.max}`}</div>` +
+ `</div>`
+ );
+}
+
+function pillarRow(p) {
+ const pct = Math.max(0, Math.min(100, (p.points / (p.max || FALLBACK_PILLAR_MAX)) * 100));
+ return (
+ `<li class="rep-pillar">` +
+ `<div class="rep-pillar-head"><span class="rep-pillar-label">${esc(p.label)}</span>` +
+ `<span class="rep-pillar-pts">${p.points}<span class="rep-pillar-max">/${p.max}</span></span></div>` +
+ `<div class="rep-pillar-bar"><div class="rep-pillar-fill" style="width:${pct}%"></div></div>` +
+ (p.detail ? `<div class="rep-pillar-detail">${esc(p.detail)}</div>` : '') +
+ `</li>`
+ );
+}
+
+function evidenceRow(evidence) {
+ const entries = Object.values(evidence || {}).filter((e) => e && e.href && e.label);
+ if (!entries.length) return '';
+ return (
+ `<div class="rep-evidence"><div class="rep-section-label">Verifiable evidence</div><div class="rep-evidence-links">` +
+ entries
+ .map(
+ (e) =>
+ `<a class="rep-evi-link" href="${esc(e.href)}"${
+ /^https?:/.test(e.href) ? ' target="_blank" rel="noopener noreferrer"' : ''
+ }>${esc(e.label)} ↗</a>`,
+ )
+ .join('') +
+ `</div></div>`
+ );
+}
+
+function discountedRow(discounted) {
+ if (!discounted?.length) return '';
+ return (
+ `<div class="rep-discounted"><div class="rep-section-label">What doesn't count</div><ul class="rep-discount-list">` +
+ discounted
+ .map((d) => `<li><strong>${esc(d.label)}</strong><span>${esc(d.detail)}</span></li>`)
+ .join('') +
+ `</ul></div>`
+ );
+}
+
+function guidanceRow(guidance) {
+ if (!guidance?.length) return '';
+ return (
+ `<div class="rep-guidance"><div class="rep-section-label">Raise your trust</div><ul class="rep-guide-list">` +
+ guidance
+ .map(
+ (g) =>
+ `<li><a href="${esc(g.href)}"><strong>${esc(g.label)}</strong><span>${esc(g.detail)}</span></a></li>`,
+ )
+ .join('') +
+ `</ul></div>`
+ );
+}
+
+function panelInner(rep) {
+ const tierClass = rep.isNew ? 'rep-head--new' : '';
+ const head =
+ `<div class="rep-head ${tierClass}">` +
+ scoreRing(rep) +
+ `<div class="rep-head-meta">` +
+ `<div class="rep-head-tier" style="--rep-accent:${esc(rep.isNew ? '#9ca3af' : rep.accent || '#c4b5fd')}">${SHIELD_SVG}${esc(rep.tierLabel)}</div>` +
+ `<div class="rep-head-sub">${
+ rep.isNew
+ ? 'No track record yet — trust is earned through real activity over time.'
+ : 'A real, auditable trust score backed by money and time.'
+ }</div>` +
+ (rep.totals
+ ? `<div class="rep-head-stats">` +
+ statChip('$' + fmtUsd(rep.totals.settled_usd), 'volume') +
+ statChip(rep.totals.distinct_tippers, 'tippers') +
+ statChip(rep.totals.confirmed_payments, 'payments') +
+ statChip(rep.totals.fork_count, 'forks') +
+ (rep.totals.verified ? '<span class="rep-stat rep-stat--ok">✓ verified</span>' : '') +
+ `</div>`
+ : '') +
+ `</div></div>`;
+
+ const partial = rep.partial
+ ? `<div class="rep-partial" role="status">Some signals were momentarily unavailable — this score may be incomplete and will refresh.</div>`
+ : '';
+
+ const pillars = `<ul class="rep-pillars">${(rep.pillars || []).map(pillarRow).join('')}</ul>`;
+
+ return (
+ head +
+ partial +
+ pillars +
+ discountedRow(rep.discounted) +
+ evidenceRow(rep.evidence) +
+ (rep.is_owner ? guidanceRow(rep.guidance) : '') +
+ `<div class="rep-foot">Score v${rep.version} · updated ${esc(fmtTime(rep.computed_at))}. Every input is a real, settled on-chain or ledger fact.</div>`
+ );
+}
+
+function statChip(value, label) {
+ return `<span class="rep-stat"><b>${esc(value)}</b> ${esc(label)}</span>`;
+}
+
+/**
+ * Build the full reputation breakdown as a DOM node that loads its own data.
+ * Designed for the wallet HUD reputation tab. Renders loading → populated, with
+ * a real, actionable error state and a retry.
+ *
+ * @param {string} agentId
+ * @param {object} [opts]
+ * @returns {HTMLElement}
+ */
+export function reputationPanelEl(agentId, opts = {}) {
+ ensureStyles();
+ const root = document.createElement('div');
+ root.className = 'rep-panel';
+ root.innerHTML = skeletonHTML();
+
+ const load = async () => {
+ root.innerHTML = skeletonHTML();
+ try {
+ const rep = await fetchReputation(agentId, { force: opts.force });
+ if (!rep) throw new Error('no data');
+ root.innerHTML = panelInner(rep);
+ // Wire guidance/evidence stop-propagation if embedded.
+ root.querySelectorAll('a[href^="/"]').forEach((a) => a.addEventListener('click', (e) => e.stopPropagation()));
+ } catch {
+ root.innerHTML =
+ `<div class="rep-error" role="alert"><div class="rep-error-title">Trust score unavailable</div>` +
+ `<p>We couldn't compute this agent's reputation just now. Its real on-chain history is unchanged.</p>` +
+ `<button type="button" class="rep-retry">Try again</button></div>`;
+ root.querySelector('.rep-retry')?.addEventListener('click', load);
+ }
+ };
+ load();
+ return root;
+}
+
+function skeletonHTML() {
+ return (
+ `<div class="rep-head"><div class="rep-ring rep-sk"></div>` +
+ `<div class="rep-head-meta"><div class="rep-sk rep-sk-line" style="width:120px"></div>` +
+ `<div class="rep-sk rep-sk-line" style="width:200px;margin-top:8px"></div></div></div>` +
+ `<ul class="rep-pillars">${Array.from({ length: 4 })
+ .map(() => `<li class="rep-pillar"><div class="rep-sk rep-sk-line" style="width:100%;height:34px"></div></li>`)
+ .join('')}</ul>`
+ );
+}
+
+// ── format helpers ────────────────────────────────────────────────────────────
+function fmtUsd(n) {
+ n = Number(n) || 0;
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
+ return n.toFixed(n < 10 ? 2 : 0);
+}
+function fmtTime(iso) {
+ if (!iso) return 'just now';
+ try {
+ const d = new Date(iso);
+ const diff = (Date.now() - d.getTime()) / 1000;
+ if (diff < 90) return 'just now';
+ if (diff < 3600) return `${Math.round(diff / 60)}m ago`;
+ if (diff < 86400) return `${Math.round(diff / 3600)}h ago`;
+ return d.toLocaleDateString();
+ } catch {
+ return 'recently';
+ }
+}
+
+// ── styles (injected once, token-driven) ─────────────────────────────────────
+let _stylesInjected = false;
+export function ensureReputationStyles() {
+ ensureStyles();
+}
+function ensureStyles() {
+ if (_stylesInjected || !isBrowser()) return;
+ _stylesInjected = true;
+ const css = `
+.rep-badge-slot{display:inline-flex;vertical-align:middle}
+.rep-badge{display:inline-flex;align-items:center;gap:4px;font-family:var(--font-mono,ui-monospace,monospace);
+ font-size:var(--text-2xs,11px);font-weight:600;line-height:1;padding:3px 7px 3px 6px;border-radius:var(--radius-pill,999px);
+ color:var(--rep-accent,#c4b5fd);background:color-mix(in srgb,var(--rep-accent,#c4b5fd) 12%,transparent);
+ border:1px solid color-mix(in srgb,var(--rep-accent,#c4b5fd) 34%,transparent);cursor:pointer;
+ transition:transform var(--duration-fast,120ms) var(--ease-standard,ease),box-shadow var(--duration-fast,120ms) ease,background var(--duration-fast,120ms) ease;white-space:nowrap}
+.rep-badge svg{width:11px;height:11px;opacity:.9}
+.rep-badge-tier{letter-spacing:.02em}
+.rep-badge-score{padding-left:5px;margin-left:1px;border-left:1px solid color-mix(in srgb,var(--rep-accent,#c4b5fd) 34%,transparent);color:var(--ink-bright,#fff)}
+.rep-badge:hover{background:color-mix(in srgb,var(--rep-accent,#c4b5fd) 20%,transparent);transform:translateY(-1px)}
+.rep-badge:focus-visible{outline:none;box-shadow:0 0 0 2px color-mix(in srgb,var(--rep-accent,#c4b5fd) 55%,transparent)}
+.rep-badge--new{color:var(--ink-dim,#9ca3af);background:var(--surface-2,rgba(255,255,255,.05));border:1px solid var(--stroke,rgba(255,255,255,.1));cursor:default}
+.rep-badge--new:hover{transform:none}
+
+.rep-panel{font-family:var(--font-body,Inter,system-ui,sans-serif);color:var(--ink,#e5e7eb);display:flex;flex-direction:column;gap:var(--space-md,16px)}
+.rep-head{display:flex;gap:var(--space-md,16px);align-items:center}
+.rep-ring{--rep-pct:0;position:relative;width:84px;height:84px;flex:0 0 auto;border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;
+ background:radial-gradient(closest-side,var(--bg-0,#0a0a0a) 78%,transparent 79% 100%),conic-gradient(var(--rep-accent,#c4b5fd) calc(var(--rep-pct)*1%),var(--surface-2,rgba(255,255,255,.06)) 0)}
+.rep-ring-num{font-family:var(--font-display,Space Grotesk,sans-serif);font-size:var(--text-2xl,28px);font-weight:700;color:var(--ink-bright,#fff);line-height:1}
+.rep-ring-of{font-size:var(--text-2xs,11px);color:var(--ink-dim,#9ca3af);margin-top:2px}
+.rep-head-meta{min-width:0;flex:1}
+.rep-head-tier{display:inline-flex;align-items:center;gap:6px;font-family:var(--font-display,sans-serif);font-weight:700;font-size:var(--text-lg,18px);color:var(--rep-accent,#c4b5fd)}
+.rep-head-tier svg{width:16px;height:16px}
+.rep-head-sub{font-size:var(--text-sm,13px);color:var(--ink-dim,#9ca3af);margin-top:4px;line-height:1.4}
+.rep-head-stats{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}
+.rep-stat{font-size:var(--text-2xs,11px);color:var(--ink-dim,#9ca3af);background:var(--surface-1,rgba(255,255,255,.03));border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:var(--radius-sm,6px);padding:3px 7px;white-space:nowrap}
+.rep-stat b{color:var(--ink-bright,#fff);font-weight:700}
+.rep-stat--ok{color:var(--success,#4ade80);border-color:color-mix(in srgb,var(--success,#4ade80) 30%,transparent)}
+.rep-partial{font-size:var(--text-xs,12px);color:var(--warn,#fbbf24);background:color-mix(in srgb,var(--warn,#fbbf24) 10%,transparent);border:1px solid color-mix(in srgb,var(--warn,#fbbf24) 28%,transparent);border-radius:var(--radius-sm,6px);padding:8px 10px}
+.rep-pillars{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:var(--space-sm,10px)}
+.rep-pillar{background:var(--surface-1,rgba(255,255,255,.03));border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:var(--radius-md,10px);padding:10px 12px}
+.rep-pillar-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px}
+.rep-pillar-label{font-size:var(--text-sm,13px);font-weight:600;color:var(--ink-bright,#fff)}
+.rep-pillar-pts{font-family:var(--font-mono,monospace);font-size:var(--text-sm,13px);font-weight:700;color:var(--wallet-accent,#c4b5fd)}
+.rep-pillar-max{color:var(--ink-faint,#6b7280);font-weight:400}
+.rep-pillar-bar{height:4px;border-radius:2px;background:var(--surface-3,rgba(255,255,255,.08));margin:7px 0 6px;overflow:hidden}
+.rep-pillar-fill{height:100%;border-radius:2px;background:linear-gradient(90deg,var(--wallet-accent,#c4b5fd),var(--wallet-accent-strong,#a78bfa));transition:width var(--duration-base,300ms) var(--ease-standard,ease)}
+.rep-pillar-detail{font-size:var(--text-xs,12px);color:var(--ink-dim,#9ca3af);line-height:1.4}
+.rep-section-label{font-size:var(--text-2xs,11px);text-transform:uppercase;letter-spacing:.06em;color:var(--ink-faint,#6b7280);font-weight:600;margin-bottom:8px}
+.rep-discounted,.rep-evidence,.rep-guidance{padding-top:var(--space-sm,10px);border-top:1px solid var(--stroke,rgba(255,255,255,.08))}
+.rep-discount-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}
+.rep-discount-list li{display:flex;flex-direction:column;gap:2px;font-size:var(--text-xs,12px)}
+.rep-discount-list strong{color:var(--ink,#e5e7eb)}.rep-discount-list span{color:var(--ink-dim,#9ca3af);line-height:1.4}
+.rep-evidence-links{display:flex;flex-wrap:wrap;gap:8px}
+.rep-evi-link{font-size:var(--text-xs,12px);color:var(--wallet-accent,#c4b5fd);text-decoration:none;background:var(--wallet-accent-soft,rgba(139,92,246,.1));border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));border-radius:var(--radius-pill,999px);padding:4px 10px;transition:background var(--duration-fast,120ms) ease}
+.rep-evi-link:hover{background:var(--wallet-accent-fill,rgba(139,92,246,.15))}
+.rep-guide-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}
+.rep-guide-list a{display:flex;flex-direction:column;gap:2px;text-decoration:none;padding:9px 11px;border-radius:var(--radius-md,10px);background:var(--wallet-accent-soft,rgba(139,92,246,.08));border:1px solid var(--wallet-stroke,rgba(139,92,246,.25));transition:background var(--duration-fast,120ms) ease,transform var(--duration-fast,120ms) ease}
+.rep-guide-list a:hover{background:var(--wallet-accent-fill,rgba(139,92,246,.15));transform:translateX(2px)}
+.rep-guide-list strong{font-size:var(--text-sm,13px);color:var(--ink-bright,#fff)}
+.rep-guide-list span{font-size:var(--text-xs,12px);color:var(--ink-dim,#9ca3af);line-height:1.4}
+.rep-foot{font-size:var(--text-2xs,11px);color:var(--ink-faint,#6b7280);line-height:1.4;padding-top:var(--space-xs,6px)}
+.rep-error{text-align:center;padding:var(--space-lg,24px) var(--space-md,16px)}
+.rep-error-title{font-weight:700;color:var(--ink-bright,#fff);margin-bottom:6px}
+.rep-error p{font-size:var(--text-sm,13px);color:var(--ink-dim,#9ca3af);margin:0 0 14px}
+.rep-retry{font:inherit;font-size:var(--text-sm,13px);font-weight:600;color:var(--ink-bright,#fff);background:var(--wallet-accent-fill,rgba(139,92,246,.15));border:1px solid var(--wallet-stroke-strong,rgba(139,92,246,.5));border-radius:var(--radius-md,10px);padding:8px 18px;cursor:pointer;transition:background var(--duration-fast,120ms) ease}
+.rep-retry:hover{background:var(--wallet-accent-soft,rgba(139,92,246,.25))}
+.rep-sk{background:linear-gradient(90deg,var(--surface-1,rgba(255,255,255,.03)) 25%,var(--surface-2,rgba(255,255,255,.06)) 37%,var(--surface-1,rgba(255,255,255,.03)) 63%);background-size:400% 100%;animation:rep-shimmer 1.4s ease infinite;border-radius:var(--radius-sm,6px)}
+.rep-sk.rep-ring{border-radius:50%}
+.rep-sk-line{height:12px}
+@keyframes rep-shimmer{0%{background-position:100% 50%}100%{background-position:0 50%}}
+@media (prefers-reduced-motion:reduce){.rep-badge,.rep-pillar-fill,.rep-guide-list a,.rep-sk{transition:none;animation:none}}
+@media (max-width:480px){.rep-head{flex-direction:column;align-items:flex-start;text-align:left}}
+`;
+ const style = document.createElement('style');
+ style.id = 'rep-styles';
+ style.textContent = css;
+ document.head.appendChild(style);
+}
diff --git a/src/shared/agent-wallet-chip.js b/src/shared/agent-wallet-chip.js
index 009c99530..8e3e5769b 100644
--- a/src/shared/agent-wallet-chip.js
+++ b/src/shared/agent-wallet-chip.js
@@ -372,7 +372,7 @@ export function walletChipHTML(agent, opts = {}) {
ensureWalletChipStyles();
const {
isOwner = false, showPending = true, link = true, tip = true,
- balance = true, popover = true, network = 'mainnet',
+ balance = true, popover = true, network = 'mainnet', reputation = true,
} = opts;
const status = getWalletStatus(agent);
@@ -407,6 +407,14 @@ export function walletChipHTML(agent, opts = {}) {
// lives in the popover to keep dense list rows tidy.
const ownerBadge = isOwner ? '<span class="twc-own" title="You own this wallet">Yours</span>' : '';
+ // Wallet-trust badge — the wallet as a credibility signal. A self-hydrating
+ // placeholder that fills (or honestly removes itself for a brand-new agent)
+ // from the real reputation score. Only meaningful for a real agent row.
+ const repSlot =
+ reputation && isRealAgent
+ ? `<span class="rep-badge-slot" data-rep-aid="${esc(status.agentId)}"${link ? '' : ' data-rep-embedded="1"'} data-twc-rep aria-label="Wallet trust score loading"></span>`
+ : '';
+
// Live balance slot — renders a skeleton, then hydrates to "$1.2K +2.3%" on
// viewport-enter via POST /api/agents/balances. Read-only display, safe inside
// card anchors (it's a <span>, no nested <a>).
@@ -463,6 +471,7 @@ export function walletChipHTML(agent, opts = {}) {
WALLET_SVG +
addressLabelHTML(status) +
ownerBadge +
+ repSlot +
vanityTag +
balanceSlot +
copyBtn +
@@ -497,7 +506,7 @@ export function walletChipEl(agent, opts = {}) {
export function wireWalletChips(root) {
if (!root || typeof root.querySelectorAll !== 'function') return;
const chips = new Set();
- for (const el of root.querySelectorAll('.twc[data-twc-aid],.twc[data-twc-trigger],[data-twc-copy],[data-twc-stop],[data-twc-tip]')) {
+ for (const el of root.querySelectorAll('.twc[data-twc-aid],.twc[data-twc-trigger],[data-twc-rep],[data-twc-copy],[data-twc-stop],[data-twc-tip]')) {
chips.add(el.classList?.contains('twc') ? el : el.closest('.twc'));
}
for (const chip of chips) if (chip) wireWalletChip(chip);
@@ -536,6 +545,14 @@ function wireWalletChip(node) {
if (node.hasAttribute?.('data-twc-aid')) registerForHydration(node);
// Rich preview popover.
if (node.hasAttribute?.('data-twc-trigger')) wirePopoverTrigger(node);
+ // Wallet-trust badge: lazily hydrate the placeholder from the real score.
+ const repSlot = node.querySelector?.('[data-twc-rep]');
+ if (repSlot && !repSlot.__repObserved) {
+ repSlot.__repObserved = true;
+ import('./agent-reputation.js')
+ .then((m) => m.observeReputationBadge(repSlot))
+ .catch(() => {});
+ }
}
async function copyToClipboard(addr, btn) {
diff --git a/src/shared/portable-wallet.js b/src/shared/portable-wallet.js
new file mode 100644
index 000000000..8ac43edce
--- /dev/null
+++ b/src/shared/portable-wallet.js
@@ -0,0 +1,592 @@
+/**
+ * Portable wallet — the agent's wallet, self-contained enough to live ANYWHERE
+ * its avatar shows up off the main app shell: the `<agent-3d wallet>` web
+ * component on a stranger's blog (shadow DOM), the avatar SDK viewer, an IRL/AR
+ * card, the walk world, the chat app. One module, mounted into any root.
+ *
+ * Why this exists separately from `agent-wallet-chip.js`: the in-app chip injects
+ * its stylesheet into `document.head`, reads from a record the page already
+ * holds, and links to in-app routes — none of which survive a closed shadow root
+ * on a third-party origin. This module is the portable cousin:
+ *
+ * • Renders entirely inside a caller-supplied root (Element OR ShadowRoot) and
+ * ships its own scoped `<style>` so it needs no `tokens.css` and leaks no CSS.
+ * • Reads real, public-only data from the CORS:* embed endpoint
+ * (GET /api/agents/wallet-embed) — address, live USD value, $THREE/USDC,
+ * lifetime tips. No secrets, no owner fields, no app globals.
+ * • Is the VISITOR view by construction: Tip + "open on three.ws". It never
+ * renders or reaches an owner control; an embedding host cannot assert that
+ * the viewer owns the wallet (that is decided only by a real session on
+ * three.ws itself).
+ * • Tips for real three ways, in order of what the visitor actually has:
+ * 1. a connected browser Solana wallet → an inline, real, viewer-signed
+ * transfer (lazy-loads agent-tip.js so web3 never bloats first paint),
+ * 2. a phone → a Solana Pay QR they scan to pay from Phantom/Solflare,
+ * 3. neither → a deep link that opens the tip flow on three.ws.
+ *
+ * Degrades, never breaks: if the embed endpoint is unreachable (offline, CORS),
+ * it falls back to a clean static identity (seed name/avatar) + "open on
+ * three.ws" rather than a broken widget.
+ */
+
+import { buildSolanaPayUri } from './solana-pay.js';
+import { renderQRToSVG } from '../erc8004/qr.js';
+
+const ORIGIN_DEFAULT = 'https://three.ws';
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const STYLE_FLAG = '__pwStyled';
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]),
+ );
+}
+
+/** Compact USD: $0, <$0.01, $9.40, $950, $1.2K, $3.4M. */
+function fmtUsd(n) {
+ if (n == null || !Number.isFinite(n)) return null;
+ if (n <= 0) return '$0';
+ if (n < 0.01) return '<$0.01';
+ if (n < 10) return `$${n.toFixed(2)}`;
+ if (n < 1000) return `$${Math.round(n)}`;
+ if (n < 1e6) return `$${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}K`;
+ if (n < 1e9) return `$${(n / 1e6).toFixed(1)}M`;
+ return `$${(n / 1e9).toFixed(1)}B`;
+}
+
+/** Vanity-aware short address: keep a real matched prefix/suffix, else 4+4. */
+function shortAddr(address, vanity) {
+ const a = String(address || '');
+ if (!a) return '';
+ const pre = vanity?.prefix && a.startsWith(vanity.prefix) ? vanity.prefix : a.slice(0, 4);
+ const suf = vanity?.suffix && a.endsWith(vanity.suffix) ? vanity.suffix : a.slice(-4);
+ const preHi = !!(vanity?.prefix && a.startsWith(vanity.prefix));
+ const sufHi = !!(vanity?.suffix && a.endsWith(vanity.suffix));
+ return (
+ `<span class="${preHi ? 'pw-hi' : ''}">${esc(pre)}</span>` +
+ `<span class="pw-dots">…</span>` +
+ `<span class="${sufHi ? 'pw-hi' : ''}">${esc(suf)}</span>`
+ );
+}
+
+const WALLET_SVG =
+ '<svg class="pw-ico" viewBox="0 0 24 24" 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>';
+const COPY_SVG =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
+
+const STYLE = `
+.pw-root{--pw-accent:#c4b5fd;--pw-accent-strong:#a78bfa;--pw-soft:rgba(139,92,246,.12);--pw-fill:rgba(139,92,246,.2);
+ --pw-stroke:rgba(139,92,246,.32);--pw-stroke-2:rgba(139,92,246,.55);--pw-glow:rgba(139,92,246,.45);
+ --pw-bg:rgba(16,16,20,.96);--pw-ink:#e8e8ea;--pw-ink-dim:#9a9aa2;--pw-ink-bright:#fff;--pw-ok:#4ade80;--pw-danger:#f87171;
+ font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--pw-ink);box-sizing:border-box;}
+.pw-root *,.pw-root *::before,.pw-root *::after{box-sizing:border-box;}
+.pw-chip{display:inline-flex;align-items:center;gap:6px;max-width:100%;padding:4px 9px;border-radius:999px;cursor:pointer;
+ font:600 11px/1 inherit;color:var(--pw-accent);background:var(--pw-soft);border:1px solid var(--pw-stroke);
+ white-space:nowrap;transition:border-color .18s,background .18s,box-shadow .25s;appearance:none;}
+.pw-chip:hover,.pw-chip:focus-visible{border-color:var(--pw-stroke-2);background:var(--pw-fill);outline:none;}
+.pw-chip:focus-visible{box-shadow:0 0 0 2px var(--pw-glow);}
+.pw-chip[data-vanity="1"]{color:var(--pw-accent-strong);border-color:var(--pw-stroke-2);}
+.pw-ico{width:12px;height:12px;flex:none;opacity:.85;}
+.pw-addr{font-family:ui-monospace,"JetBrains Mono",SFMono-Regular,Menlo,monospace;letter-spacing:.01em;display:inline-flex;gap:1px;}
+.pw-hi{color:var(--pw-ink-bright);font-weight:700;}
+.pw-dots{opacity:.5;}
+.pw-val{font-family:ui-monospace,Menlo,monospace;font-weight:700;font-size:11px;color:var(--pw-ink-bright);
+ border-left:1px solid var(--pw-stroke);padding-left:6px;}
+.pw-sk{display:inline-block;width:30px;height:9px;border-radius:3px;
+ background:linear-gradient(90deg,rgba(255,255,255,.06),rgba(255,255,255,.18),rgba(255,255,255,.06));
+ background-size:200% 100%;animation:pw-sk 1.1s ease-in-out infinite;}
+@keyframes pw-sk{0%{background-position:200% 0}100%{background-position:-200% 0}}
+.pw-pop{margin-top:7px;width:264px;max-width:100%;background:var(--pw-bg);border:1px solid var(--pw-stroke-2);
+ border-radius:14px;padding:13px;box-shadow:0 20px 50px rgba(0,0,0,.55);backdrop-filter:blur(12px);
+ font-size:12px;line-height:1.45;}
+.pw-pop[hidden]{display:none;}
+.pw-pop-head{display:flex;align-items:center;gap:9px;margin-bottom:11px;}
+.pw-av{width:30px;height:30px;border-radius:8px;object-fit:cover;background:rgba(255,255,255,.08);flex:none;}
+.pw-id{min-width:0;flex:1;}
+.pw-name{font-weight:700;color:var(--pw-ink-bright);font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
+.pw-sub{font-size:10px;color:var(--pw-ink-dim);margin-top:1px;}
+.pw-total{display:flex;align-items:flex-end;justify-content:space-between;gap:8px;margin-bottom:10px;}
+.pw-usd{font:800 22px/1 "Space Grotesk",ui-sans-serif,system-ui;color:var(--pw-ink-bright);font-feature-settings:"tnum";}
+.pw-usd-lbl{font-size:9px;color:var(--pw-ink-dim);text-transform:uppercase;letter-spacing:.05em;margin-bottom:3px;}
+.pw-tips{text-align:right;font-size:10px;color:var(--pw-ink-dim);}
+.pw-tips b{display:block;color:var(--pw-accent);font:700 13px/1 ui-monospace,Menlo,monospace;}
+.pw-addrline{display:flex;align-items:center;gap:6px;font-family:ui-monospace,Menlo,monospace;font-size:10.5px;
+ background:rgba(255,255,255,.04);border-radius:8px;padding:6px 8px;margin-bottom:10px;}
+.pw-addrline .pw-mono{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--pw-ink-dim);}
+.pw-icobtn{appearance:none;background:none;border:none;padding:2px;margin:0;cursor:pointer;color:var(--pw-accent);
+ opacity:.7;display:inline-flex;transition:opacity .15s,transform .12s;}
+.pw-icobtn:hover{opacity:1;}
+.pw-icobtn:active{transform:scale(.88);}
+.pw-icobtn svg{width:13px;height:13px;}
+.pw-icobtn.pw-copied{color:var(--pw-ok);opacity:1;}
+.pw-acts{display:flex;flex-wrap:wrap;gap:6px;}
+.pw-btn{appearance:none;cursor:pointer;font:700 11px/1 inherit;border-radius:999px;padding:8px 12px;flex:1 1 auto;
+ border:1px solid var(--pw-stroke-2);background:var(--pw-soft);color:var(--pw-accent);
+ display:inline-flex;align-items:center;justify-content:center;gap:5px;text-decoration:none;
+ transition:background .15s,transform .12s,color .15s;white-space:nowrap;}
+.pw-btn:hover{background:var(--pw-fill);color:var(--pw-ink-bright);}
+.pw-btn:active{transform:scale(.97);}
+.pw-btn:focus-visible{outline:2px solid var(--pw-glow);outline-offset:2px;}
+.pw-btn-primary{background:linear-gradient(135deg,var(--pw-accent),var(--pw-accent-strong));color:#0a0a0a;border-color:transparent;}
+.pw-btn-primary:hover{filter:brightness(1.07);color:#0a0a0a;}
+.pw-tip{margin-top:10px;}
+.pw-tip[hidden]{display:none;}
+.pw-seg{display:flex;gap:5px;margin-bottom:8px;}
+.pw-presets{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:8px;}
+.pw-pre{appearance:none;cursor:pointer;font:600 11px/1 ui-monospace,Menlo,monospace;border-radius:8px;padding:7px 9px;flex:1 1 auto;
+ border:1px solid var(--pw-stroke);background:rgba(255,255,255,.03);color:var(--pw-ink);transition:border-color .15s,background .15s;}
+.pw-pre:hover{border-color:var(--pw-stroke-2);}
+.pw-pre[data-on="1"]{background:var(--pw-fill);border-color:var(--pw-stroke-2);color:var(--pw-ink-bright);}
+.pw-qr{display:flex;flex-direction:column;align-items:center;gap:7px;margin-top:10px;}
+.pw-qr[hidden]{display:none;}
+.pw-qr-frame{background:#fff;border-radius:10px;padding:8px;line-height:0;}
+.pw-qr-frame svg{display:block;width:140px;height:140px;}
+.pw-qr-cap{font-size:10px;color:var(--pw-ink-dim);text-align:center;}
+.pw-status{font-size:10.5px;margin-top:8px;min-height:13px;color:var(--pw-ink-dim);}
+.pw-status[data-kind="ok"]{color:var(--pw-ok);}
+.pw-status[data-kind="err"]{color:var(--pw-danger);}
+.pw-status a{color:inherit;text-decoration:underline;}
+.pw-pending{display:inline-flex;align-items:center;gap:6px;padding:4px 9px;border-radius:999px;font:600 11px/1 inherit;
+ color:var(--pw-ink-dim);background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.1);}
+.pw-link{font-size:10px;color:var(--pw-ink-dim);text-decoration:none;display:inline-block;margin-top:9px;transition:color .15s;}
+.pw-link:hover{color:var(--pw-accent);}
+@media (prefers-reduced-motion: reduce){.pw-sk{animation:none;}.pw-chip,.pw-btn,.pw-icobtn{transition:none;}}
+`;
+
+function ensureStyles(host) {
+ // `host` is the ShadowRoot or Element we render into. Inject the scoped <style>
+ // as a direct child of THAT node (once) so the styles reach our markup whether
+ // it lives in a shadow tree or a light-DOM container.
+ if (host[STYLE_FLAG]) return;
+ host[STYLE_FLAG] = true;
+ const style = document.createElement('style');
+ style.setAttribute('data-pw', '');
+ style.textContent = STYLE;
+ host.appendChild(style);
+}
+
+async function copyText(text) {
+ try {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(text);
+ return true;
+ }
+ } catch {
+ /* fall through */
+ }
+ try {
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ const ok = document.execCommand('copy');
+ ta.remove();
+ return ok;
+ } catch {
+ return false;
+ }
+}
+
+function detectSolana() {
+ if (typeof window === 'undefined') return null;
+ return window.phantom?.solana || window.solana || window.backpack?.solana || window.solflare || null;
+}
+
+const TIP_PRESETS = {
+ SOL: [0.05, 0.1, 0.25, 1],
+ USDC: [1, 5, 10, 25],
+};
+
+/**
+ * Mount a portable wallet into `host` (Element or ShadowRoot).
+ *
+ * @param {Element|ShadowRoot} host
+ * @param {object} opts
+ * @param {string} opts.agentId Agent UUID (required for live data).
+ * @param {string} [opts.origin='https://three.ws'] three.ws origin to read/deep-link.
+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']
+ * @param {'chip'|'card'} [opts.variant='chip'] Chip toggles a popover; card is always open.
+ * @param {boolean} [opts.tip=true] Show the inline tip flow.
+ * @param {boolean} [opts.qr=true] Offer a Solana Pay QR.
+ * @param {string} [opts.name] Seed name (used while loading / on offline fallback).
+ * @param {string} [opts.avatar] Seed avatar URL.
+ * @param {object} [opts.seedCard] A pre-fetched embed card (skip the network call).
+ * @returns {{ el: HTMLElement, refresh: () => void, destroy: () => void }}
+ */
+export function mountPortableWallet(host, opts = {}) {
+ const {
+ agentId,
+ origin = ORIGIN_DEFAULT,
+ network = 'mainnet',
+ variant = 'chip',
+ tip = true,
+ qr = true,
+ share = true,
+ name: seedName = null,
+ avatar: seedAvatar = null,
+ seedCard = null,
+ } = opts;
+
+ ensureStyles(host);
+ const root = document.createElement('div');
+ root.className = 'pw-root';
+ host.appendChild(root);
+
+ let card = seedCard || null;
+ let destroyed = false;
+ let outsideBound = false;
+
+ const state = {
+ open: variant === 'card',
+ tipOpen: false,
+ qrOpen: false,
+ tipToken: 'SOL',
+ tipAmount: TIP_PRESETS.SOL[1],
+ busy: false,
+ };
+
+ function setStatus(el, text, kind) {
+ if (!el) return;
+ el.textContent = text || '';
+ if (kind) el.dataset.kind = kind;
+ else el.removeAttribute('data-kind');
+ }
+
+ function render() {
+ if (destroyed) return;
+ // ── No agent id, or a wallet-less / unreachable agent → static identity ──
+ if (!card) {
+ root.innerHTML = renderLoadingOrSeed();
+ return;
+ }
+ if (!card.address || !BASE58_RE.test(String(card.address))) {
+ root.innerHTML =
+ `<span class="pw-pending" title="Wallet provisioning">${WALLET_SVG}<span>Wallet pending</span></span>` +
+ `<a class="pw-link" href="${esc(card.openUrl || origin)}" target="_blank" rel="noopener">Open on three.ws ↗</a>`;
+ return;
+ }
+
+ const vanity = card.vanity || null;
+ const usd = fmtUsd(card.balanceUsd);
+ const chip =
+ `<button type="button" class="pw-chip" data-vanity="${vanity ? '1' : '0'}" aria-haspopup="dialog" aria-expanded="${state.open ? 'true' : 'false'}" data-pw-toggle>` +
+ WALLET_SVG +
+ `<span class="pw-addr">${shortAddr(card.address, vanity)}</span>` +
+ (usd != null ? `<span class="pw-val">${esc(usd)}</span>` : '') +
+ `</button>`;
+
+ root.innerHTML = variant === 'chip' ? chip + popoverHTML() : popoverHTML(true);
+ wire();
+ }
+
+ function renderLoadingOrSeed() {
+ // Pre-data chip: show seed name + a skeleton value, never a void.
+ const label = seedName ? esc(seedName) : 'Wallet';
+ return (
+ `<button type="button" class="pw-chip" data-pw-toggle disabled>` +
+ WALLET_SVG +
+ `<span class="pw-addr">${label}</span>` +
+ `<span class="pw-val"><span class="pw-sk"></span></span>` +
+ `</button>`
+ );
+ }
+
+ function popoverHTML(forceOpen) {
+ const open = forceOpen || state.open;
+ const vanity = card.vanity || null;
+ const usd = fmtUsd(card.balanceUsd);
+ const av = card.avatar || seedAvatar;
+ const tipsCount = card.tips?.count || 0;
+ const tipsUsd = fmtUsd(card.tips?.usd);
+ const headline =
+ tipsCount > 0
+ ? `<div class="pw-tips"><b>${tipsCount}</b>tip${tipsCount === 1 ? '' : 's'}${tipsUsd ? ` · ${esc(tipsUsd)}` : ''}</div>`
+ : '';
+
+ const presets = TIP_PRESETS[state.tipToken] || TIP_PRESETS.SOL;
+ const tipPanel = tip
+ ? `<div class="pw-tip" ${state.tipOpen ? '' : 'hidden'} data-pw-tip>
+ <div class="pw-seg">
+ <button type="button" class="pw-pre" data-pw-token="SOL" data-on="${state.tipToken === 'SOL' ? '1' : '0'}">SOL</button>
+ <button type="button" class="pw-pre" data-pw-token="USDC" data-on="${state.tipToken === 'USDC' ? '1' : '0'}">USDC</button>
+ </div>
+ <div class="pw-presets">${presets
+ .map(
+ (p) =>
+ `<button type="button" class="pw-pre" data-pw-amt="${p}" data-on="${p === state.tipAmount ? '1' : '0'}">${p}</button>`,
+ )
+ .join('')}</div>
+ <button type="button" class="pw-btn pw-btn-primary" data-pw-send style="flex:1 1 100%">Send tip</button>
+ <div class="pw-status" data-pw-status aria-live="polite"></div>
+ </div>`
+ : '';
+
+ const qrPanel = qr
+ ? `<div class="pw-qr" ${state.qrOpen ? '' : 'hidden'} data-pw-qr>
+ <div class="pw-qr-frame" data-pw-qr-svg></div>
+ <div class="pw-qr-cap">Scan with Phantom / Solflare to tip</div>
+ </div>`
+ : '';
+
+ return (
+ `<div class="pw-pop" role="dialog" aria-label="${esc(card.name || 'Agent')} wallet" data-pw-pop ${open ? '' : 'hidden'}>` +
+ `<div class="pw-pop-head">` +
+ (av ? `<img class="pw-av" src="${esc(av)}" alt="" loading="lazy">` : `<span class="pw-av"></span>`) +
+ `<div class="pw-id"><div class="pw-name">${esc(card.name || 'Agent')}</div><div class="pw-sub">Agent wallet · Solana</div></div>` +
+ `</div>` +
+ `<div class="pw-total"><div><div class="pw-usd-lbl">Wallet value</div><div class="pw-usd">${esc(usd || '$0')}</div></div>${headline}</div>` +
+ `<div class="pw-addrline"><span class="pw-mono">${esc(card.address)}</span>` +
+ `<button type="button" class="pw-icobtn" data-pw-copy title="Copy address" aria-label="Copy wallet address">${COPY_SVG}</button></div>` +
+ `<div class="pw-acts">` +
+ (tip ? `<button type="button" class="pw-btn pw-btn-primary" data-pw-tipbtn>◎ Tip</button>` : '') +
+ (qr ? `<button type="button" class="pw-btn" data-pw-qrbtn>QR</button>` : '') +
+ (share ? `<button type="button" class="pw-btn" data-pw-share title="Share this wallet">Share</button>` : '') +
+ `<a class="pw-btn" href="${esc(card.openUrl)}" target="_blank" rel="noopener">Open ↗</a>` +
+ `</div>` +
+ tipPanel +
+ qrPanel +
+ `</div>`
+ );
+ }
+
+ function wire() {
+ const toggle = root.querySelector('[data-pw-toggle]');
+ const pop = root.querySelector('[data-pw-pop]');
+ if (toggle && variant === 'chip') {
+ toggle.addEventListener('click', () => {
+ state.open = !state.open;
+ toggle.setAttribute('aria-expanded', state.open ? 'true' : 'false');
+ if (pop) pop.hidden = !state.open;
+ if (state.open) bindOutside();
+ else unbindOutside();
+ });
+ }
+ if (!pop) return;
+
+ const copyBtn = pop.querySelector('[data-pw-copy]');
+ copyBtn?.addEventListener('click', async () => {
+ const ok = await copyText(card.address);
+ if (ok) {
+ copyBtn.classList.add('pw-copied');
+ setTimeout(() => copyBtn.classList.remove('pw-copied'), 1200);
+ }
+ });
+
+ const status = pop.querySelector('[data-pw-status]');
+
+ pop.querySelector('[data-pw-tipbtn]')?.addEventListener('click', () => {
+ state.tipOpen = !state.tipOpen;
+ if (state.tipOpen) state.qrOpen = false;
+ render();
+ });
+
+ pop.querySelector('[data-pw-qrbtn]')?.addEventListener('click', () => {
+ state.qrOpen = !state.qrOpen;
+ if (state.qrOpen) state.tipOpen = false;
+ render();
+ });
+
+ for (const b of pop.querySelectorAll('[data-pw-token]')) {
+ b.addEventListener('click', () => {
+ state.tipToken = b.dataset.pwToken;
+ state.tipAmount = (TIP_PRESETS[state.tipToken] || TIP_PRESETS.SOL)[1];
+ state.tipOpen = true;
+ render();
+ });
+ }
+ for (const b of pop.querySelectorAll('[data-pw-amt]')) {
+ b.addEventListener('click', () => {
+ state.tipAmount = Number(b.dataset.pwAmt);
+ for (const o of pop.querySelectorAll('[data-pw-amt]')) o.dataset.on = o === b ? '1' : '0';
+ });
+ }
+
+ pop.querySelector('[data-pw-send]')?.addEventListener('click', () => sendTip(status));
+
+ pop.querySelector('[data-pw-share]')?.addEventListener('click', async (e) => {
+ // The growth loop: a wallet worth screenshotting that links back to tip
+ // or fork. The /share?wallet=1 link previews with the vanity address +
+ // lifetime tips OG card.
+ const shareUrl = `${origin}/agent/${encodeURIComponent(agentId)}/share?wallet=1`;
+ const btn = e.currentTarget;
+ try {
+ if (navigator.share) {
+ await navigator.share({ title: `${card.name || 'Agent'} wallet`, url: shareUrl });
+ return;
+ }
+ } catch {
+ /* user dismissed the native sheet — fall through to copy */
+ }
+ const ok = await copyText(shareUrl);
+ if (ok && btn) {
+ const prev = btn.textContent;
+ btn.textContent = 'Copied!';
+ setTimeout(() => { btn.textContent = prev; }, 1300);
+ }
+ });
+
+ // A freshly-opened QR panel needs its SVG painted (render() leaves it empty).
+ if (state.qrOpen) {
+ const qrPanel = pop.querySelector('[data-pw-qr]');
+ if (qrPanel) renderQr(qrPanel);
+ }
+ }
+
+ function renderQr(qrPanel) {
+ const slot = qrPanel.querySelector('[data-pw-qr-svg]');
+ if (!slot || slot.dataset.done === '1') return;
+ const uri = buildSolanaPayUri(card.address, {
+ amount: state.tipAmount,
+ label: card.name || 'three.ws agent',
+ });
+ try {
+ slot.innerHTML = renderQRToSVG(uri, { scale: 4, margin: 1 });
+ slot.dataset.done = '1';
+ } catch {
+ slot.innerHTML = '';
+ const a = document.createElement('a');
+ a.className = 'pw-link';
+ a.href = card.tipUrl || card.openUrl;
+ a.target = '_blank';
+ a.rel = 'noopener';
+ a.textContent = 'Open tip on three.ws ↗';
+ slot.appendChild(a);
+ }
+ }
+
+ async function sendTip(status) {
+ if (state.busy) return;
+ const provider = detectSolana();
+ if (!provider) {
+ // No connected wallet — surface the QR (the fastest real path on a phone)
+ // and a three.ws deep link. render() rebuilds the panel, so write the
+ // status into the freshly-rendered element afterwards.
+ state.qrOpen = true;
+ state.tipOpen = true;
+ render();
+ const newStatus = root.querySelector('[data-pw-status]');
+ setStatus(newStatus, 'No Solana wallet here — scan the QR, or ');
+ if (newStatus) {
+ const a = document.createElement('a');
+ a.href = card.tipUrl || card.openUrl;
+ a.target = '_blank';
+ a.rel = 'noopener';
+ a.textContent = 'tip on three.ws ↗';
+ newStatus.appendChild(a);
+ }
+ return;
+ }
+ state.busy = true;
+ setStatus(status, 'Connecting…');
+ try {
+ const { tipAgent } = await import('./agent-tip.js');
+ const { signature, explorerUrl } = await tipAgent({
+ toAddress: card.address,
+ token: state.tipToken,
+ amount: state.tipAmount,
+ network,
+ onStage: (s) => setStatus(status, `${s[0].toUpperCase()}${s.slice(1)}…`),
+ });
+ setStatus(status, `Tipped ${state.tipAmount} ${state.tipToken} · `, 'ok');
+ const a = document.createElement('a');
+ a.href = explorerUrl;
+ a.target = '_blank';
+ a.rel = 'noopener';
+ a.textContent = `${signature.slice(0, 8)}…`;
+ status.appendChild(a);
+ softRefresh(); // pull the new balance/tip count without nuking this receipt
+ } catch (e) {
+ setStatus(status, e?.message || 'Tip failed — try again.', 'err');
+ } finally {
+ state.busy = false;
+ }
+ }
+
+ // Patch the live numbers in place (chip value, popover USD, tips) after a tip,
+ // so the on-screen receipt + explorer link survive the balance update.
+ async function softRefresh() {
+ const next = await fetchCard();
+ if (destroyed || !next) return;
+ card = { ...card, ...next };
+ const usd = fmtUsd(card.balanceUsd) || '$0';
+ const valEl = root.querySelector('.pw-chip .pw-val');
+ if (valEl) valEl.textContent = usd;
+ const usdEl = root.querySelector('.pw-usd');
+ if (usdEl) usdEl.textContent = usd;
+ const tipsEl = root.querySelector('.pw-tips b');
+ if (tipsEl && card.tips) tipsEl.textContent = String(card.tips.count || 0);
+ }
+
+ // composedPath-aware so a click inside our (possibly shadow-DOM) markup never
+ // counts as "outside" — only a genuine outside click collapses the popover.
+ function onDocClick(e) {
+ const path = e.composedPath ? e.composedPath() : [];
+ if (path.includes(root)) return;
+ const pop = root.querySelector('[data-pw-pop]');
+ const toggle = root.querySelector('[data-pw-toggle]');
+ if (pop) pop.hidden = true;
+ state.open = false;
+ toggle?.setAttribute('aria-expanded', 'false');
+ unbindOutside();
+ }
+ function bindOutside() {
+ if (outsideBound) return;
+ outsideBound = true;
+ document.addEventListener('click', onDocClick, true);
+ }
+ function unbindOutside() {
+ outsideBound = false;
+ document.removeEventListener('click', onDocClick, true);
+ }
+
+ async function fetchCard() {
+ if (!agentId) return null;
+ try {
+ const res = await fetch(
+ `${origin}/api/agents/wallet-embed?id=${encodeURIComponent(agentId)}&network=${encodeURIComponent(network)}`,
+ { headers: { accept: 'application/json' } },
+ );
+ if (!res.ok) return null;
+ const { data } = await res.json();
+ return data || null;
+ } catch {
+ return null;
+ }
+ }
+
+ async function refresh() {
+ const next = await fetchCard();
+ if (destroyed) return;
+ if (next) {
+ card = next;
+ } else if (!card) {
+ // Offline / CORS-blocked and nothing pre-seeded — a clean static identity.
+ card = {
+ agentId,
+ name: seedName,
+ avatar: seedAvatar,
+ address: null,
+ openUrl: `${origin}/agent/${agentId || ''}`,
+ };
+ }
+ render();
+ }
+
+ // First paint immediately (skeleton/seed), then hydrate from the real endpoint.
+ render();
+ if (!seedCard) refresh();
+ else render();
+
+ return {
+ el: root,
+ refresh,
+ destroy() {
+ destroyed = true;
+ unbindOutside();
+ root.remove();
+ },
+ };
+}
diff --git a/src/voice/talk-mode.js b/src/voice/talk-mode.js
index 07076655c..73cbeda8e 100644
--- a/src/voice/talk-mode.js
+++ b/src/voice/talk-mode.js
@@ -137,7 +137,10 @@ export function openTalkMode({ avatar, systemPromptFn }) {
speak: (text) => controller.speakText(text),
appendTranscript: (role, content) => appendTranscript(transcriptEl, { role, content }),
onFlourish: () => {
- scene.getEmoteController?.()?.play('celebrate').catch(() => {});
+ // Real confirmed tx only — fire the avatar's celebrate flourish (task 07).
+ try {
+ Promise.resolve(scene.getEmoteController?.()?.play('celebrate')).catch(() => {});
+ } catch {}
// Funds just moved — re-read the balance so the next command is grounded.
refreshWalletBalance(avatar.agent_id, network).then((b) => { walletBalance = b; });
},
@@ -149,7 +152,8 @@ export function openTalkMode({ avatar, systemPromptFn }) {
// Discoverable affordance: a one-tap example that drops a starter command into
// the text box so owners learn the capability exists.
if (walletHintBtn) {
- walletHintBtn.textContent = '💸 Try: “sell half my $THREE” · “tip 0.1 SOL to …”';
+ walletHintBtn.innerHTML =
+ '<span aria-hidden="true">◎</span> Try: “sell half my $THREE” · “tip 0.1 SOL to …”';
walletHintBtn.hidden = false;
walletHintBtn.addEventListener('click', () => {
textInput.value = 'tip 0.05 SOL to ';
diff --git a/src/voice/wallet-intent.js b/src/voice/wallet-intent.js
index de44eda69..e0894beae 100644
--- a/src/voice/wallet-intent.js
+++ b/src/voice/wallet-intent.js
@@ -309,7 +309,7 @@ export class WalletIntentController {
const verb = intent.action === 'tip' ? 'Tip' : 'Withdraw';
const destShown = intent.destination_label ? `${intent.destination_label} (${shortMint(dest)})` : shortMint(dest);
const rows = [
- ['Send', `${isSol ? '◎' : ''}${fmt(human, isSol ? 4 : 4)} ${symbol}`],
+ ['Send', `${isSol ? '◎' : ''}${fmt(human, 4)} ${symbol}`],
['To', destShown],
];
if (sim.usd != null) rows.push(['Value', `≈ $${fmt(sim.usd, 2)}`]);
@@ -409,7 +409,11 @@ export class WalletIntentController {
this.onFlourish();
} catch (err) {
this._clearCard();
- const extra = err.explorer ? ` You can check it here: ${err.explorer}` : '';
+ // A submitted-but-unconfirmed trade/withdraw still carries a signature the
+ // owner can verify — surface its explorer link rather than implying nothing
+ // happened. Trade errors stash it under `detail`; withdraw on the error.
+ const explorer = err.explorer || err.detail?.explorer || null;
+ const extra = explorer ? ` You can check it here: ${explorer}` : '';
await this._fail(`${err.message}${extra}`);
}
}
diff --git a/tests/agent-recovery.test.js b/tests/agent-recovery.test.js
new file mode 100644
index 000000000..ba7a846c1
--- /dev/null
+++ b/tests/agent-recovery.test.js
@@ -0,0 +1,141 @@
+// Unit tests for api/_lib/agent-recovery.js — the pure decision logic behind
+// social recovery & inheritance: config normalization, the approval/time-lock
+// state machine, the effective threshold, and the dead-man inactivity math.
+//
+// The DB + audit + notify + custody deps are mocked so these stay deterministic
+// and fast; we only exercise the pure exports here (the DB-touching flows are
+// integration-tested against a live DB elsewhere).
+
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/notify.js', () => ({ insertNotification: vi.fn() }));
+vi.mock('../api/_lib/agent-trade-guards.js', () => ({ recordCustodyEvent: vi.fn(async () => 1) }));
+
+const rec = await import('../api/_lib/agent-recovery.js');
+const {
+ getRecoveryConfig, effectiveThreshold, computeRequestPhase, deadManStatus,
+ RECOVERY_TIMELOCK_MS, RECOVERY_REQUEST_TTL_MS, isUuid,
+} = rec;
+
+const DAY = 24 * 60 * 60 * 1000;
+
+describe('getRecoveryConfig', () => {
+ it('returns safe defaults for empty meta', () => {
+ const c = getRecoveryConfig(null);
+ expect(c.threshold).toBe(null);
+ expect(c.dead_man.enabled).toBe(false);
+ expect(c.dead_man.inactivity_days).toBe(90);
+ expect(c.dead_man.grace_days).toBe(14);
+ });
+
+ it('clamps out-of-range inactivity/grace to bounds', () => {
+ const c = getRecoveryConfig({ recovery: { dead_man: { enabled: true, inactivity_days: 9999, grace_days: 0 } } });
+ expect(c.dead_man.inactivity_days).toBe(365); // max
+ expect(c.dead_man.grace_days).toBe(1); // min
+ expect(c.dead_man.enabled).toBe(true);
+ });
+
+ it('only treats enabled === true as on', () => {
+ expect(getRecoveryConfig({ recovery: { dead_man: { enabled: 'yes' } } }).dead_man.enabled).toBe(false);
+ });
+});
+
+describe('effectiveThreshold', () => {
+ it('is 0 with no guardians', () => {
+ expect(effectiveThreshold({ threshold: null }, 0)).toBe(0);
+ });
+ it('defaults to 2-of-N once 2+ guardians exist', () => {
+ expect(effectiveThreshold({ threshold: null }, 3)).toBe(2);
+ expect(effectiveThreshold({ threshold: null }, 1)).toBe(1);
+ });
+ it('honors an explicit threshold but clamps to guardian count', () => {
+ expect(effectiveThreshold({ threshold: 3 }, 5)).toBe(3);
+ expect(effectiveThreshold({ threshold: 9 }, 4)).toBe(4);
+ expect(effectiveThreshold({ threshold: 0 }, 4)).toBe(1);
+ });
+});
+
+describe('computeRequestPhase', () => {
+ const now = 1_700_000_000_000;
+ const createdAt = new Date(now - DAY).toISOString();
+
+ it('stays pending while approvals are below threshold', () => {
+ const p = computeRequestPhase({ status: 'pending_approvals', approvalsRequired: 2, approvalsCount: 1, timelockUntil: null, createdAt, now });
+ expect(p.phase).toBe('pending_approvals');
+ expect(p.approved).toBe(false);
+ });
+
+ it('expires a never-approved request past its TTL', () => {
+ const oldCreated = new Date(now - RECOVERY_REQUEST_TTL_MS - DAY).toISOString();
+ const p = computeRequestPhase({ status: 'pending_approvals', approvalsRequired: 2, approvalsCount: 0, timelockUntil: null, createdAt: oldCreated, now });
+ expect(p.phase).toBe('expired');
+ });
+
+ it('is time_locked once approved but the window has not elapsed', () => {
+ const until = new Date(now + RECOVERY_TIMELOCK_MS / 2).toISOString();
+ const p = computeRequestPhase({ status: 'time_locked', approvalsRequired: 2, approvalsCount: 2, timelockUntil: until, createdAt, now });
+ expect(p.phase).toBe('time_locked');
+ expect(p.msUntilUnlock).toBeGreaterThan(0);
+ });
+
+ it('becomes ready once approved and the time-lock has elapsed', () => {
+ const until = new Date(now - 1000).toISOString();
+ const p = computeRequestPhase({ status: 'time_locked', approvalsRequired: 2, approvalsCount: 2, timelockUntil: until, createdAt, now });
+ expect(p.phase).toBe('ready');
+ expect(p.msUntilUnlock).toBe(0);
+ });
+
+ it('drops back below readiness if approvals fall under threshold (guardian removed)', () => {
+ const until = new Date(now - 1000).toISOString();
+ const p = computeRequestPhase({ status: 'time_locked', approvalsRequired: 2, approvalsCount: 1, timelockUntil: until, createdAt, now });
+ expect(p.phase).toBe('pending_approvals');
+ expect(p.approved).toBe(false);
+ });
+
+ it('keeps terminal states terminal', () => {
+ for (const s of ['completed', 'cancelled', 'rejected', 'expired']) {
+ expect(computeRequestPhase({ status: s, approvalsRequired: 2, approvalsCount: 2, timelockUntil: null, createdAt, now }).phase).toBe(s);
+ }
+ });
+});
+
+describe('deadManStatus', () => {
+ const now = 1_700_000_000_000;
+ const cfg = { dead_man: { enabled: true, inactivity_days: 90, grace_days: 14 } };
+
+ it('is not eligible while the owner is recently active', () => {
+ const lastActive = new Date(now - 10 * DAY);
+ const dm = deadManStatus(cfg, lastActive, now);
+ expect(dm.eligible_to_arm).toBe(false);
+ expect(dm.inactive_days).toBe(10);
+ expect(dm.ms_until_arm).toBeGreaterThan(0);
+ });
+
+ it('becomes eligible once inactivity crosses the threshold', () => {
+ const lastActive = new Date(now - 100 * DAY);
+ const dm = deadManStatus(cfg, lastActive, now);
+ expect(dm.eligible_to_arm).toBe(true);
+ expect(dm.ms_until_arm).toBeLessThanOrEqual(0);
+ });
+
+ it('never eligible when disabled', () => {
+ const dm = deadManStatus({ dead_man: { enabled: false, inactivity_days: 90, grace_days: 14 } }, new Date(now - 200 * DAY), now);
+ expect(dm.eligible_to_arm).toBe(false);
+ });
+});
+
+describe('isUuid', () => {
+ it('accepts a v4 uuid and rejects junk', () => {
+ expect(isUuid('11111111-1111-4111-8111-111111111111')).toBe(true);
+ expect(isUuid('not-a-uuid')).toBe(false);
+ expect(isUuid(null)).toBe(false);
+ });
+});
+
+describe('time-lock constant', () => {
+ it('is 48h', () => {
+ expect(RECOVERY_TIMELOCK_MS).toBe(48 * 60 * 60 * 1000);
+ });
+});
diff --git a/tests/agent-reputation-ui.test.js b/tests/agent-reputation-ui.test.js
new file mode 100644
index 000000000..d6c5c6664
--- /dev/null
+++ b/tests/agent-reputation-ui.test.js
@@ -0,0 +1,137 @@
+// @vitest-environment jsdom
+//
+// DOM tests for the shared wallet-reputation UI. The pure scoring engine is
+// covered in wallet-reputation.test.js; here we pin that the badge + breakdown
+// render the real, server-shaped result correctly and that every state — new,
+// populated, and error — is honestly designed.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { computeReputation } from '../api/_lib/trust/wallet-reputation.js';
+
+// Mock the shared fetch layer so the UI module never hits the network.
+const apiFetch = vi.fn();
+vi.mock('../src/api.js', () => ({ apiFetch: (...a) => apiFetch(...a) }));
+
+const { reputationBadgeHTML, reputationPanelEl } = await import('../src/shared/agent-reputation.js');
+
+const AID = '11111111-2222-4333-8444-555555555555';
+const AID2 = '22222222-2222-4333-8444-555555555555';
+const AID3 = '33333333-2222-4333-8444-555555555555';
+const AID4 = '44444444-2222-4333-8444-555555555555';
+const AID5 = '55555555-2222-4333-8444-555555555555';
+
+function endpointShape(inputs, extra = {}) {
+ const r = computeReputation(inputs);
+ return {
+ agent_id: extra.agent_id || AID,
+ name: 'Test Agent',
+ ...r,
+ evidence: { wallet: { label: 'Wallet activity', href: 'https://solscan.io/account/x' } },
+ guidance: [],
+ is_owner: false,
+ computed_at: new Date().toISOString(),
+ ...extra,
+ };
+}
+
+function jsonResponse(body, ok = true) {
+ return { ok, status: ok ? 200 : 500, json: async () => body };
+}
+
+beforeEach(() => {
+ apiFetch.mockReset();
+});
+
+describe('reputationBadgeHTML', () => {
+ it('renders a self-hydrating placeholder for a real agent id', () => {
+ const html = reputationBadgeHTML(AID);
+ expect(html).toContain('rep-badge-slot');
+ expect(html).toContain(`data-rep-aid="${AID}"`);
+ });
+
+ it('returns empty string for a non-UUID id (no badge on non-agent rows)', () => {
+ expect(reputationBadgeHTML('not-a-uuid')).toBe('');
+ expect(reputationBadgeHTML('')).toBe('');
+ });
+});
+
+describe('reputationPanelEl', () => {
+ it('renders the score, tier, pillar bars and evidence for an established agent', async () => {
+ apiFetch.mockResolvedValueOnce(
+ jsonResponse(
+ endpointShape({
+ ageDays: 220,
+ activeDays90: 40,
+ externalTipUsd: 1200,
+ settledUsd: 3500,
+ tipCount: 18,
+ distinctTippers: 9,
+ confirmedPayments: 24,
+ failedPayments: 1,
+ forkCount: 5,
+ hasOnchainIdentity: true,
+ registryAverage: 4.6,
+ registryCount: 7,
+ validationCount: 2,
+ feedbackCount: 5,
+ }),
+ ),
+ );
+ const el = reputationPanelEl(AID2);
+ await new Promise((r) => setTimeout(r, 0));
+ const text = el.textContent;
+ expect(text).toMatch(/Tenure & consistency/);
+ expect(text).toMatch(/Earnings & volume/);
+ expect(el.querySelectorAll('.rep-pillar').length).toBe(6);
+ expect(el.querySelector('.rep-ring-num')).toBeTruthy();
+ // Evidence link present and points at real chain explorer.
+ expect(el.querySelector('.rep-evi-link')?.getAttribute('href')).toContain('solscan.io');
+ });
+
+ it('honestly shows a brand-new agent as "new" with no fabricated number', async () => {
+ apiFetch.mockResolvedValueOnce(
+ jsonResponse(
+ endpointShape({
+ ageDays: 0,
+ activeDays90: 0,
+ tipCount: 0,
+ distinctTippers: 0,
+ confirmedPayments: 0,
+ forkCount: 0,
+ hasOnchainIdentity: false,
+ }),
+ ),
+ );
+ const el = reputationPanelEl(AID3);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(el.querySelector('.rep-ring-num')?.textContent).toBe('—');
+ expect(el.textContent).toMatch(/No track record yet/i);
+ });
+
+ it('surfaces self-tips and concentration as "what doesn\'t count"', async () => {
+ apiFetch.mockResolvedValueOnce(
+ jsonResponse(
+ endpointShape({
+ ageDays: 100,
+ tipCount: 40,
+ distinctTippers: 1,
+ selfTipCount: 12,
+ externalTipUsd: 5000,
+ settledUsd: 5000,
+ }),
+ ),
+ );
+ const el = reputationPanelEl(AID4);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(el.textContent).toMatch(/doesn.t count/i);
+ expect(el.textContent).toMatch(/self-tip/i);
+ });
+
+ it('renders an actionable error state with retry when the API fails', async () => {
+ apiFetch.mockResolvedValueOnce(jsonResponse({}, false));
+ const el = reputationPanelEl(AID5);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(el.querySelector('.rep-retry')).toBeTruthy();
+ expect(el.textContent).toMatch(/unavailable/i);
+ });
+});
diff --git a/tests/api/fork-ownership-invariant.test.js b/tests/api/fork-ownership-invariant.test.js
new file mode 100644
index 000000000..57f2c16ef
--- /dev/null
+++ b/tests/api/fork-ownership-invariant.test.js
@@ -0,0 +1,124 @@
+// The ownership invariant — the user's central promise.
+//
+// Forking someone else's avatar must mint a BRAND-NEW custodial wallet for the
+// forker and leave the source untouched. This test proves it two ways:
+//
+// 1. Cryptographic distinctness (real keygen): provisioning two agents (the
+// source and its fork) yields a DISTINCT Solana address, a DISTINCT EVM
+// address, and DISTINCT encrypted secrets. No key material is shared.
+//
+// 2. Source-level non-copy guarantee: the fork handler (api/avatars/fork.js)
+// never reads an encrypted secret off the source, provisions wallets for the
+// NEWLY inserted agent id, and assigns ownership to the caller — so a secret
+// cannot leak from source to fork by construction.
+//
+// Real key generation + real AES-GCM encryption run; only the DB and audit sink
+// are mocked (mirrors tests/api/ensure-agent-wallet.test.js).
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+import { vi } from 'vitest';
+
+const sqlState = { queue: [], calls: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ const query = typeof strings === 'string' ? strings : strings.join('?');
+ sqlState.calls.push({ query, values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+}));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { JWT_SECRET: 'test-secret-please-do-not-use-in-production-ever' },
+}));
+
+const { provisionAgentWallets } = await import('../../api/_lib/agent-wallet.js');
+
+// Queue the four DB responses one provisionAgentWallets() call makes:
+// EVM SELECT, EVM UPDATE, Solana SELECT, Solana UPDATE.
+function queueProvision(agentId) {
+ sqlState.queue.push([{ id: agentId, wallet_address: null, meta: {} }]); // EVM select
+ sqlState.queue.push([]); // EVM update
+ sqlState.queue.push([{ id: agentId, meta: {} }]); // Solana select
+ sqlState.queue.push([]); // Solana update
+}
+
+// Pull the persisted address + encrypted secret back out of the UPDATE writes.
+function persistedFor(agentId) {
+ const updates = sqlState.calls.filter(
+ (c) => /update agent_identities/i.test(c.query) && c.values.includes(agentId),
+ );
+ const evm = updates.find((c) => /wallet_address\s*=/i.test(c.query));
+ const sol = updates.find((c) => !/wallet_address\s*=/i.test(c.query));
+ const evmMeta = JSON.parse(evm.values.find((v) => typeof v === 'string' && v.includes('encrypted_wallet_key')));
+ const solMeta = JSON.parse(sol.values.find((v) => typeof v === 'string' && v.includes('encrypted_solana_secret')));
+ return {
+ evmAddress: evm.values[0],
+ evmSecret: evmMeta.encrypted_wallet_key,
+ solAddress: solMeta.solana_address,
+ solSecret: solMeta.encrypted_solana_secret,
+ };
+}
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+describe('ownership invariant · fork mints a fresh, isolated wallet', () => {
+ it('source and fork get distinct addresses AND distinct encrypted secrets', async () => {
+ queueProvision('source-agent');
+ const sourceWallets = await provisionAgentWallets('source-agent');
+
+ queueProvision('fork-agent');
+ const forkWallets = await provisionAgentWallets('fork-agent');
+
+ // Live addresses returned to the caller are distinct on both chains.
+ expect(forkWallets.solana).not.toBe(sourceWallets.solana);
+ expect(forkWallets.evm).not.toBe(sourceWallets.evm);
+ expect(forkWallets.solana).toBeTruthy();
+ expect(forkWallets.evm).toMatch(/^0x[0-9a-fA-F]{40}$/);
+
+ // The persisted secrets are independently generated — no shared key bytes.
+ const src = persistedFor('source-agent');
+ const fork = persistedFor('fork-agent');
+ expect(fork.solSecret).not.toBe(src.solSecret);
+ expect(fork.evmSecret).not.toBe(src.evmSecret);
+ expect(fork.solAddress).toBe(forkWallets.solana);
+ expect(fork.evmAddress).toBe(forkWallets.evm);
+
+ // The fork's write path never references the source agent id — bytes
+ // untouched on the source side.
+ const forkUpdates = sqlState.calls.filter(
+ (c) => /update agent_identities/i.test(c.query) && c.values.includes('fork-agent'),
+ );
+ for (const u of forkUpdates) {
+ expect(u.values).not.toContain('source-agent');
+ expect(JSON.stringify(u.values)).not.toContain(src.solSecret);
+ expect(JSON.stringify(u.values)).not.toContain(src.evmSecret);
+ }
+ });
+});
+
+describe('ownership invariant · the fork handler cannot leak a secret', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const forkSrc = readFileSync(resolve(here, '../../api/avatars/fork.js'), 'utf8');
+
+ it('never selects or copies an encrypted secret from the source', () => {
+ // The source SELECT pulls only public columns; secrets are never read.
+ expect(forkSrc).not.toMatch(/encrypted_solana_secret/);
+ expect(forkSrc).not.toMatch(/encrypted_wallet_key/);
+ });
+
+ it('provisions fresh wallets for the newly inserted agent, owned by the caller', () => {
+ // A new agent_identities row is inserted with the caller as user_id…
+ expect(forkSrc).toMatch(/insert into agent_identities[\s\S]*?user_id/i);
+ expect(forkSrc).toMatch(/values\s*\(\s*\$\{auth\.userId\}/);
+ // …and wallets are provisioned for THAT new agent, not reused from source.
+ expect(forkSrc).toMatch(/provisionAgentWallets\(agent\.id\)/);
+ // Lineage is recorded (attribution), not key material.
+ expect(forkSrc).toMatch(/forked_from/);
+ });
+});
diff --git a/tests/galaxy-flows.test.js b/tests/galaxy-flows.test.js
new file mode 100644
index 000000000..5cb1ba50a
--- /dev/null
+++ b/tests/galaxy-flows.test.js
@@ -0,0 +1,143 @@
+import { describe, it, expect } from 'vitest';
+import {
+ encodeCursor,
+ decodeCursor,
+ shapeFlow,
+ isAgentEdge,
+ txExplorerUrl,
+ accountExplorerUrl,
+ TYPE_KINDS,
+ PUBLIC_SPEND_CATEGORIES,
+} from '../api/_lib/galaxy-flows.js';
+
+describe('galaxy-flows cursor', () => {
+ it('round-trips a (ts, rowId) cursor', () => {
+ const ts = '2026-06-23T12:34:56.000Z';
+ const c = encodeCursor(ts, 'c123');
+ const decoded = decodeCursor(c);
+ expect(decoded).toEqual({ ts, rowId: 'c123' });
+ });
+
+ it('rejects malformed cursors', () => {
+ expect(decodeCursor(null)).toBeNull();
+ expect(decodeCursor('')).toBeNull();
+ expect(decodeCursor('not-base64-!!!')).toBeNull();
+ // base64 of "abc|" → missing rowId
+ expect(decodeCursor(Buffer.from('abc|', 'utf8').toString('base64url'))).toBeNull();
+ });
+});
+
+describe('explorer urls', () => {
+ it('builds mainnet + devnet tx urls and null-safes', () => {
+ expect(txExplorerUrl('SIG', 'mainnet')).toBe('https://solscan.io/tx/SIG');
+ expect(txExplorerUrl('SIG', 'devnet')).toBe('https://solscan.io/tx/SIG?cluster=devnet');
+ expect(txExplorerUrl(null, 'mainnet')).toBeNull();
+ expect(accountExplorerUrl('ADDR', 'mainnet')).toBe('https://solscan.io/account/ADDR');
+ expect(accountExplorerUrl(null, 'mainnet')).toBeNull();
+ });
+});
+
+describe('type filter map', () => {
+ it('keeps trades + payments + launches separable, never leaks private categories', () => {
+ expect(TYPE_KINDS.tips).toEqual(['tip']);
+ expect(TYPE_KINDS.trades).toEqual(['trade', 'snipe']);
+ expect(TYPE_KINDS.all).toContain('launch');
+ expect(PUBLIC_SPEND_CATEGORIES).not.toContain('withdraw');
+ expect(PUBLIC_SPEND_CATEGORIES).not.toContain('vanity_swap');
+ });
+});
+
+const TIP_ROW = {
+ ts: new Date('2026-06-23T12:00:00Z'),
+ kind: 'tip',
+ direction: 'in',
+ row_id: 'c1',
+ network: 'mainnet',
+ actor_id: 'agent-A',
+ actor_name: 'Nova',
+ actor_addr: 'NOVAwallet',
+ actor_vp: 'NOVA',
+ actor_vs: null,
+ asset: 'SOL',
+ amount_lamports: '500000000',
+ amount_raw: null,
+ usd: 12.5,
+ signature: 'SIGTIP',
+ counterparty_addr: 'SENDERwallet',
+ counterparty_id: 'agent-B',
+ counterparty_name: 'Atlas',
+ mint: null,
+ symbol: null,
+ coin_name: null,
+};
+
+describe('shapeFlow — tip (inbound, agent↔agent)', () => {
+ const f = shapeFlow(TIP_ROW);
+ it('points the edge sender → receiver', () => {
+ expect(f.direction).toBe('in');
+ expect(f.from.id).toBe('agent-B'); // counterparty sent
+ expect(f.to.id).toBe('agent-A'); // actor received
+ });
+ it('derives sol + explorer + iso ts', () => {
+ expect(f.sol).toBe(0.5);
+ expect(f.usd).toBe(12.5);
+ expect(f.explorer).toBe('https://solscan.io/tx/SIGTIP');
+ expect(f.ts).toBe('2026-06-23T12:00:00.000Z');
+ });
+ it('is a real agent edge', () => {
+ expect(isAgentEdge(f)).toBe(true);
+ });
+});
+
+describe('shapeFlow — spend (outbound, one-sided flare)', () => {
+ const f = shapeFlow({
+ ...TIP_ROW,
+ kind: 'trade',
+ direction: 'out',
+ row_id: 'c2',
+ signature: 'SIGTRADE',
+ counterparty_addr: 'DEXpool', // not a platform agent
+ counterparty_id: null,
+ counterparty_name: null,
+ });
+ it('flows out from the actor to a bare wallet', () => {
+ expect(f.from.id).toBe('agent-A');
+ expect(f.to.wallet).toBe('DEXpool');
+ expect(f.to.id).toBeNull();
+ });
+ it('is NOT an agent edge (no second star) → renders as a flare', () => {
+ expect(isAgentEdge(f)).toBe(false);
+ });
+});
+
+describe('shapeFlow — launch (self event)', () => {
+ const f = shapeFlow({
+ ...TIP_ROW,
+ kind: 'launch',
+ direction: 'launch',
+ row_id: 'l1',
+ signature: null,
+ asset: null,
+ amount_lamports: null,
+ usd: null,
+ counterparty_addr: null,
+ counterparty_id: null,
+ counterparty_name: null,
+ mint: 'MINT123',
+ symbol: 'THREE',
+ coin_name: 'Three',
+ });
+ it('has the actor as source and no destination, with a mint explorer link', () => {
+ expect(f.from.id).toBe('agent-A');
+ expect(f.to).toBeNull();
+ expect(f.mint_explorer).toBe('https://solscan.io/account/MINT123');
+ expect(isAgentEdge(f)).toBe(false);
+ });
+});
+
+describe('isAgentEdge — self-transfer is never an edge', () => {
+ it('rejects counterparty === actor', () => {
+ const f = shapeFlow({ ...TIP_ROW, counterparty_id: 'agent-A' });
+ expect(isAgentEdge(f)).toBe(false);
+ });
+});
diff --git a/tests/wallet-format.test.js b/tests/wallet-format.test.js
new file mode 100644
index 000000000..4e4b3361c
--- /dev/null
+++ b/tests/wallet-format.test.js
@@ -0,0 +1,61 @@
+// The wallet program's single money + address formatter (src/shared/wallet-format.js).
+// One helper per concern: the chip re-exports formatWalletUsd, and the net-worth
+// presence layer's fmtUsd delegates to it, so the SAME value reads identically
+// across the chip and the inline net-worth figure.
+
+import { describe, it, expect } from 'vitest';
+import { formatWalletUsd, formatWalletUsdSafe, shortAddress } from '../src/shared/wallet-format.js';
+import { formatWalletUsd as chipUsd } from '../src/shared/agent-wallet-chip.js';
+import { fmtUsd } from '../src/shared/agent-networth.js';
+
+describe('formatWalletUsd · compact USD tiers', () => {
+ it('renders each magnitude band', () => {
+ expect(formatWalletUsd(0)).toBe('$0');
+ expect(formatWalletUsd(0.004)).toBe('<$0.01');
+ expect(formatWalletUsd(9.4)).toBe('$9.40');
+ expect(formatWalletUsd(950)).toBe('$950');
+ expect(formatWalletUsd(1200)).toBe('$1.2K');
+ expect(formatWalletUsd(34_000)).toBe('$34K');
+ expect(formatWalletUsd(3_400_000)).toBe('$3.4M');
+ expect(formatWalletUsd(1_100_000_000)).toBe('$1.1B');
+ });
+
+ it('returns null for non-finite so callers can omit the figure', () => {
+ expect(formatWalletUsd(null)).toBeNull();
+ expect(formatWalletUsd(undefined)).toBeNull();
+ expect(formatWalletUsd(NaN)).toBeNull();
+ });
+
+ it('formatWalletUsdSafe coerces missing values to $0', () => {
+ expect(formatWalletUsdSafe(null)).toBe('$0');
+ expect(formatWalletUsdSafe(NaN)).toBe('$0');
+ expect(formatWalletUsdSafe(1200)).toBe('$1.2K');
+ });
+});
+
+describe('one formatter, every surface', () => {
+ it('the chip re-export is the same function', () => {
+ expect(chipUsd).toBe(formatWalletUsd);
+ });
+
+ it('net-worth fmtUsd agrees with the chip on compact output', () => {
+ for (const v of [0, 9.4, 950, 1200, 34_000, 3_400_000]) {
+ expect(fmtUsd(v)).toBe(formatWalletUsdSafe(v));
+ }
+ // The casing drift is gone: compact thousands read "$1.2K", never "$1k".
+ expect(fmtUsd(1200)).toBe('$1.2K');
+ });
+});
+
+describe('shortAddress · address shortening', () => {
+ it('shortens long addresses head…tail', () => {
+ expect(shortAddress('0x1234567890abcdef1234567890abcdef12345678', 6, 4)).toBe('0x1234…5678');
+ expect(shortAddress('So11111111111111111111111111111111111111112')).toBe('So11…1112');
+ });
+
+ it('leaves already-short values intact', () => {
+ expect(shortAddress('abc')).toBe('abc');
+ expect(shortAddress('')).toBe('');
+ expect(shortAddress(null)).toBe('');
+ });
+});
diff --git a/vercel.json b/vercel.json
index c7ed2bca5..004430c7c 100644
--- a/vercel.json
+++ b/vercel.json
@@ -9,6 +9,9 @@
"api/cron/copy-fanout.js": {
"maxDuration": 120
},
+ "api/cron/mirror-fanout.js": {
+ "maxDuration": 120
+ },
"api/agents/[id].js": {
"maxDuration": 45
},
@@ -733,6 +736,10 @@
"src": "/activity/?",
"dest": "/activity.html"
},
+ {
+ "src": "/guardian/?",
+ "dest": "/guardian.html"
+ },
{
"src": "/trader/([^/]+)/share/?",
"dest": "/api/trader-share?agent_id=$1"
@@ -1779,6 +1786,22 @@
"src": "/api/agents/([^/]+)/solana/([^/]+)",
"dest": "/api/agents/[id]"
},
+ {
+ "src": "/api/agents/([^/]+)/recovery/requests/([^/]+)/([^/]+)",
+ "dest": "/api/agents/[id]"
+ },
+ {
+ "src": "/api/agents/([^/]+)/recovery/([^/]+)/([^/]+)",
+ "dest": "/api/agents/[id]"
+ },
+ {
+ "src": "/api/agents/([^/]+)/recovery/([^/]+)",
+ "dest": "/api/agents/[id]"
+ },
+ {
+ "src": "/api/agents/([^/]+)/recovery",
+ "dest": "/api/agents/[id]"
+ },
{
"src": "/api/agents/([^/]+)/pumpfun/([^/]+)",
"dest": "/api/agents/pumpfun/[action]?id=$1&action=$2"
@@ -1854,6 +1877,10 @@
"src": "/api/agents/reputation-batch",
"dest": "/api/agents/reputation-batch"
},
+ {
+ "src": "/api/reputation/leaderboard",
+ "dest": "/api/reputation/leaderboard"
+ },
{
"src": "/api/agents/([^/]+)/reputation",
"dest": "/api/agents/[id]"
@@ -3892,6 +3919,10 @@
"path": "/api/cron/flush-usage-events",
"schedule": "* * * * *"
},
+ {
+ "path": "/api/cron/dead-man-switch",
+ "schedule": "0 5 * * *"
+ },
{
"path": "/api/cron/auto-rig-sweep",
"schedule": "*/5 * * * *"
@@ -3968,6 +3999,10 @@
"path": "/api/cron/cleanup-csrf-tokens",
"schedule": "17 * * * *"
},
+ {
+ "path": "/api/cron/treasury-autopilot",
+ "schedule": "23 * * * *"
+ },
{
"path": "/api/cron/process-withdrawals",
"schedule": "0 * * * *"
@@ -3988,6 +4023,10 @@
"path": "/api/cron/copy-fanout",
"schedule": "*/2 * * * *"
},
+ {
+ "path": "/api/cron/mirror-fanout",
+ "schedule": "*/2 * * * *"
+ },
{
"path": "/api/cron/index-delegations",
"schedule": "*/5 * * * *"
diff --git a/vite.config.js b/vite.config.js
index c309e0c1b..022b7a25d 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -336,11 +336,13 @@ const appConfig = {
'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),
'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),
'agent-wallet': resolve(__dirname, 'pages/agent-wallet.html'),
+ guardian: resolve(__dirname, 'pages/guardian.html'),
launches: resolve(__dirname, 'pages/launches.html'),
pulse: resolve(__dirname, 'pages/pulse.html'),
'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),
watchlist: resolve(__dirname, 'pages/watchlist.html'),
leaderboard: resolve(__dirname, 'pages/leaderboard.html'),
+ mirror: resolve(__dirname, 'pages/mirror.html'),
trader: resolve(__dirname, 'pages/trader.html'),
trades: resolve(__dirname, 'pages/trades.html'),
'claim-wallet': resolve(__dirname, 'pages/claim-wallet.html'),
@@ -769,6 +771,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/watchlist/': resolve(root, 'pages/watchlist.html'),
'/leaderboard': resolve(root, 'pages/leaderboard.html'),
'/leaderboard/': resolve(root, 'pages/leaderboard.html'),
+ '/mirror': resolve(root, 'pages/mirror.html'),
+ '/mirror/': resolve(root, 'pages/mirror.html'),
'/trader': resolve(root, 'pages/trader.html'),
'/trader/': resolve(root, 'pages/trader.html'),
'/trades': resolve(root, 'pages/trades.html'),
@@ -823,6 +827,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/play/arena/': resolve(root, 'pages/play/arena.html'),
'/smart-money': resolve(root, 'pages/smart-money.html'),
'/smart-money/': resolve(root, 'pages/smart-money.html'),
+ '/guardian': resolve(root, 'pages/guardian.html'),
+ '/guardian/': resolve(root, 'pages/guardian.html'),
'/walk-embed': resolve(root, 'pages/walk-embed.html'),
'/walk-embed/': resolve(root, 'pages/walk-embed.html'),
'/walk': resolve(root, 'pages/walk-landing.html'),