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.

Strategy objects, in-world & chat wallets, server voice capture

nirholasaa897bbe34e0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04bead04c..aa1c5a752 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
+- **Copy-trading page now shows each of your agents' wallet identity** — On the Copy Trading page, every one of your agents listed under "your copy-trading" now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears. (`/mirror`) `[improvement]`
- **Embedded widgets never hang on a blank frame** — When an embedded avatar widget couldn't fetch its model — an expired draft link, a flaky network, a Safari load failure — it used to leave a blank box with no explanation. Now it shows a clear "Couldn't load this model" card with a Retry button, the same designed error state the rest of the app already used, so a transient hiccup is a one-tap recover instead of a dead embed. `[fix]`
- **Every agent now carries a real, auditable trust score — and there's a leaderboard of the most trusted** — In a world of infinite forkable avatars, trust is the scarce asset, so every agent's wallet now shows an honest 0–100 trust score wherever the agent appears — on its profile, its cards, the marketplace, and the galaxy. Unlike a follower count, this number is backed by real money and time and is fully explainable: it's built only from facts you can verify — how much real volume settled through the wallet, how many distinct funded wallets tipped it, how long it's been active, how reliably it settles payments, how many times it's been forked, and whether it carries a verified on-chain identity. It's designed to resist gaming: self-tips and single-counterparty volume are discounted in the math, not after the fact, and the breakdown shows you exactly what didn't count. Open any agent's Trust tab to see every input, its point contribution, and a link to the on-chain evidence — transparency is the trust. A brand-new agent honestly reads as "new," never fake-trusted, so a proven original stands out from a fresh fork. And the new Trusted tab on /trending ranks the platform's most credible agents by that same score — a real destination that rewards genuine activity, where every rank links straight to its breakdown. (`/trending`) `[feature]`
- **Feature: Agent Studio is complete — Body, Money, and Skills tabs are now live** — Agent Studio used to mount a real Brain and Memory editor but left Body, Money, and Skills as 'mounts here' placeholders. All three are now fully built and wired beside the live 3D stage. Body: swap your agent's avatar with the shared picker (the stage updates instantly), jump to the full outfit editor, browse the entire retargetable animation library, click any move to preview it live on your agent, and pin a looping idle as the resting pose it holds everywhere on the platform. Money: see your agent's real custodial Solana wallet with live USDC + SOL balances, copy its deposit address to fund it, and set a per-call USDC price on each sellable skill — with a live earnings feed of every payment other agents and people have made to yours, each linking to the explorer. Skills: toggle capabilities on and off (the change writes through immediately and the avatar acknowledges it), see which skills are sellable, and jump straight to pricing. Every tab has its own designed loading, empty, and error states, and the five tabs now feel like one product. (`/agent-studio`) `[feature]`
@@ -24,6 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab** — Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions. (`/pose`) `[improvement, feature]`
- **Improvement: Base USDC payments confirm even when an RPC provider is flaky** — When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient. `[improvement, infra]`
- **Improvement: every server error now hands you a support reference code** — When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose. `[improvement, infra]`
+- **IRL: pinned agents now hold their exact spot indoors instead of drifting** — When you pin your agent to a real-world spot in IRL — on a table, a desk, a shelf — it now stays put as you pan and move your phone, instead of sliding away. Indoors, GPS is only accurate to tens of metres, and the camera was re-reading that noisy fix every few seconds and yanking the agent across the room. Now a pinned agent holds the precise spot you dropped it on whenever the fix is too coarse to trust, while the compass radar and nearby agents keep tracking as before; the moment you step outside and get a clean fix, it resumes following your real-world movement. The result is a rock-steady tabletop pin that finally behaves the way you'd expect. (`/irl`) `[fix]`
- **Mirror a proven agent and yours trades alongside it — Copy Trading, fully custodial** — Follow a high-performing agent and your own agent now mirrors its real on-chain trades automatically — proportionally, and strictly inside the spend policy you already set. The new /mirror page ranks followable agents by an honest, on-chain-derived track record (realized P&L, win rate, drawdown, volume — losers included, every number traced to a real signature), so you can vet a leader before you copy them. Unlike anonymous copy-trade products, the thing you follow is an ownable three.ws agent with a face, a voice, and its own real funds at stake. Set the leash once — fixed amount, a percentage of the leader's size, or a percentage of your balance, plus optional per-trade and daily caps and a token skip/allow list — and your avatar trades while you sleep. Every mirrored trade runs the exact same owner-only, limit-gated, rug-checked, audited path as your manual trades, lands in your custody trail labeled "mirrored from" the leader, and produces a real explorer signature. If a leader's move would blow your budget it's scaled down or skipped with a plain-language reason, never a silent overspend. Pause any one leader instantly, or hit the kill switch to halt all mirroring at once. Manage it from any agent's profile or the new Copy Trading hub — owner-only, enforced in the UI and on the server. (`/mirror`) `[feature]`
- **More uploaded avatars animate out of the box — no more accidental T-poses** — Avatars exported from Reallusion Character Creator 3/4 and 3ds Max (Biped) used to import frozen in a stiff T-pose because the platform didn't recognize their skeleton naming. Both are now mapped to the universal rig, so a CC or Biped avatar walks, idles, and emotes like any other — legs included — the moment you bring it in. A batch of generic side-labelled rigs from auto-riggers now animate too. No setup, no allowlist; it just moves. `[fix, improvement]`
- **New: a server error now lands you on a real page — with your support code ready to copy** — On the rare occasion something breaks on our side, you used to get the host's blank error screen — a dead end. Now you land on a proper three.ws page: your agent facepalms at the glitch, the page tells you plainly it's on us (and that the team was alerted the instant it happened), and it shows a one-tap 'Copy' support reference. 'Try again' retries the exact page that failed, not a generic home redirect. Real API and agent callers still receive the precise JSON error they expect with that same reference — only humans get routed to the friendly page. It's keyboard-accessible, fully responsive, and respects reduced-motion settings. `[feature, improvement]`
@@ -46,6 +48,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
+- **Your agent's wallet now follows it everywhere — the chat, the 3D world, and any site** — An agent's wallet is its identity, so it now shows up wherever its avatar does, not just inside the app. In the chat, the agent you're talking to carries a wallet chip — open it to see its live value and lifetime tips, copy its address, or tip it for a good answer. In the walk-around 3D world, stroll up to another player who's piloting an agent and its wallet rises beside their nameplate: vanity address, real balance, and a one-tap tip, right there in the scene. And the lightweight avatar viewer in our SDK can now opt into the same wallet card, so an agent embedded on any third-party site keeps its real, tippable identity. Every number is real and read from the same public wallet data as the rest of the platform, so values never disagree across surfaces; it's always the visitor view, so owner-only controls never leak into an embed. It's deliberately frugal in the live 3D world — only the nearest agent's wallet loads, and only once — so nothing stutters. `[feature]`
- **Your avatar has a job — the Earn home in every agent wallet** — Every agent wallet now has an Earn tab that turns it from a vault into a working participant in the agent economy. It opens with the number that matters: what your avatar has actually earned — today, this week, and all time — every dollar traced to a real settlement (skill sales and tips), never an estimate. Come back after time away and it tells you what it made while you were gone. Below that is the earning engine: price your agent's skills in USDC right where the money lands, so the moment someone buys, real funds move into this wallet. Then the part that makes letting an agent spend on its own feel safe — your agent can pay other agents and services over real x402 rails, but only inside the daily cap, per-payment limit, and allowlist you set, with a prominent kill switch that freezes all autonomous spending instantly (your own withdrawals always stay open). Finally, a clean receipts statement of every payment in and out — counterparty, amount, time, and on-chain signature — plus a path to the live services directory where agents discover and hire each other. Owner-only, enforced in the UI and on the server. (`/economy`) `[feature]`
## 2026-06-22
diff --git a/api/_lib/agent-strategy-runtime.js b/api/_lib/agent-strategy-runtime.js
new file mode 100644
index 000000000..b04f07048
--- /dev/null
+++ b/api/_lib/agent-strategy-runtime.js
@@ -0,0 +1,563 @@
+// Strategy Object runtime — turns an equipped, rule-based Strategy into the
+// agent's REAL, server-signed, fully-leashed trading.
+//
+// Safe by construction: every strategy-initiated trade runs through the SAME
+// shared spend guardrails (api/_lib/agent-trade-guards.js) the discretionary
+// trade endpoint, the sniper, and the mirror executor use; the SAME pump quote +
+// instruction builders (api/agents/solana-trade.js); the SAME MEV-aware execution
+// engine; and lands in the SAME custody ledger (agent_custody_events, category
+// 'trade', reason 'strategy:<slug>', meta.strategy = { strategy_id, equip_id… }).
+// A strategy can NEVER bypass a limit:
+// • the per-owner global kill switch (strategy_kill_switch) and the per-equip
+// `active` flag both halt it before any tx;
+// • the agent's per-trade cap, rolling daily budget, USD ceiling, price-impact
+// breaker, rug/honeypot firewall, and SOL headroom all gate every buy;
+// • the strategy's OWN caps (per-trade size, slippage, max concurrent, cooldown)
+// are ADDITIONAL constraints layered on top — never a way around the leash;
+// • a retried (equip, mint) never double-spends — the custody idempotency key and
+// the agent_strategy_positions unique (agent,mint,network) index both dedupe it.
+//
+// Trigger source: REAL pump.fun launches (api/_lib/pump-launch-feed.js) for entries;
+// REAL on-chain re-quotes (quoteTrade sell) for exits. No synthetic launches, no
+// simulated fills, no fabricated prices — entries are best-effort, exits are real.
+
+import { PublicKey } from '@solana/web3.js';
+import { sql } from './db.js';
+import { quoteTrade, buildTradeInstructions } from '../agents/solana-trade.js';
+import { recoverSolanaAgentKeypair } from './agent-wallet.js';
+import { solanaConnection } from './agent-pumpfun.js';
+import { submitProtected } from './execution-engine.js';
+import { assessTradeSafety, recordFirewallDecision } from './trade-firewall.js';
+import { logAudit } from './audit.js';
+import { cacheSet } from './cache.js';
+import { WSOL_MINT } from './pump-trade-args.js';
+import {
+ getSpendLimits, getTradeLimits, enforceSpendLimit, SpendLimitError, lamportsToUsd,
+ getDailySpendLamports, updateCustodyEvent,
+ checkPerTradeCap, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,
+ SOL_FEE_HEADROOM_LAMPORTS,
+} from './agent-trade-guards.js';
+import { normalizeStrategyConfig, matchesEntry, shouldExit } from './strategy-schema.js';
+import { recentPumpLaunches, enrichCreatorStats } from './pump-launch-feed.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const lamToSol = (l) => Number(BigInt(l)) / LAMPORTS_PER_SOL;
+const netOf = (v) => (v === 'devnet' ? 'devnet' : 'mainnet');
+
+// Human-readable labels for the skip/exit codes the runtime emits, surfaced in the
+// owner's activity feed so a "skipped" line always explains itself.
+export const STRATEGY_SKIP_LABELS = Object.freeze({
+ kill_switch: 'agent trade kill switch is on',
+ owner_kill: 'your strategy kill switch is engaged',
+ per_trade_cap: 'over the agent’s per-trade SOL cap',
+ daily_budget: 'agent’s daily SOL budget reached',
+ daily_cap: 'agent’s daily USD ceiling reached',
+ per_tx_cap: 'over the agent’s per-trade USD cap',
+ frozen: 'agent wallet is frozen',
+ price_impact: 'price impact above the limit',
+ firewall_blocked: 'blocked by the rug/honeypot firewall',
+ insufficient_sol: 'not enough SOL for size + fees',
+ no_market: 'no tradeable market for this mint',
+ wsol: 'wrapped SOL is not a tradeable target',
+ max_concurrent: 'at the strategy’s max concurrent positions',
+ cooldown: 'within the strategy’s cooldown window',
+ already_held: 'agent already holds a position in this mint',
+ wallet_preparing: 'agent wallet still provisioning',
+ no_holding: 'no token balance to exit',
+});
+
+// ── agent loader ──────────────────────────────────────────────────────────────
+async function loadAgent(agentId) {
+ const [row] = await sql`
+ SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row) return null;
+ const meta = { ...(row.meta || {}) };
+ return {
+ id: row.id,
+ ownerId: row.user_id,
+ name: row.name,
+ meta,
+ address: meta.solana_address || null,
+ encryptedSecret: meta.encrypted_solana_secret || null,
+ };
+}
+
+// The agent's full token balance for a mint (raw base units) — used to value an
+// open position (re-quote a sell of the real holding) and to size the real exit.
+async function readTokenBalance(conn, ownerPk, mintPk) {
+ try {
+ const res = await conn.getParsedTokenAccountsByOwner(ownerPk, { mint: mintPk });
+ let raw = 0n;
+ let decimals = 6;
+ for (const acc of res?.value || []) {
+ const info = acc.account?.data?.parsed?.info?.tokenAmount;
+ if (info?.amount) raw += BigInt(info.amount);
+ if (Number.isInteger(info?.decimals)) decimals = info.decimals;
+ }
+ return { raw, decimals };
+ } catch {
+ return { raw: 0n, decimals: 6 };
+ }
+}
+
+// ── the guarded strategy trade ────────────────────────────────────────────────
+// The SAME guard sequence as handleTrade (api/agents/solana-trade.js) and the
+// mirror executor, composed for a server-initiated strategy action. Returns a
+// structured result — never throws past the boundary. Labels the custody trail
+// with reason 'strategy:<slug>' so every fill is attributable to the strategy.
+export async function runStrategyTrade({
+ agent, side, mint, network, solAmount, tokenAmountRaw, slippageBps, idempotencyKey, strategyRef,
+}) {
+ const { id, ownerId, meta, address, encryptedSecret } = agent;
+ if (!address || !encryptedSecret) return { status: 'failed', code: 'wallet_preparing' };
+
+ let mintPk; let ownerPk;
+ try { mintPk = new PublicKey(mint); ownerPk = new PublicKey(address); }
+ catch { return { status: 'failed', code: 'bad_address' }; }
+ if (mint === WSOL_MINT) return { status: 'skipped', code: 'wsol' };
+
+ const conn = solanaConnection(network);
+
+ // 1. Quote — real pump curve / AMM pricing.
+ let quote;
+ try {
+ quote = await quoteTrade({ conn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps });
+ } catch (e) {
+ if (e?.code === 'pool_not_found') return { status: 'skipped', code: 'no_market' };
+ return { status: 'failed', code: e?.code || 'quote_failed', message: (e?.message || '').slice(0, 200) };
+ }
+
+ 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 discretionary path.
+ if (tradeLimits.kill_switch) return { status: 'skipped', code: 'kill_switch' };
+
+ 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));
+ if (checkPerTradeCap(lamportsIn, capLamports)) return { status: 'skipped', code: 'per_trade_cap' };
+
+ if (tradeLimits.daily_budget_sol != null) {
+ const budgetLamports = BigInt(Math.floor(tradeLimits.daily_budget_sol * LAMPORTS_PER_SOL));
+ const spent = await getDailySpendLamports(id, network);
+ if (checkDailyBudgetLamports(spent, lamportsIn, budgetLamports)) return { status: 'skipped', code: 'daily_budget' };
+ }
+ try {
+ await enforceSpendLimit({ agentId: id, limits: limitsCfg, category: 'trade', usdValue, network });
+ } catch (e) {
+ if (e instanceof SpendLimitError) return { status: 'skipped', code: e.code };
+ throw e;
+ }
+ }
+
+ if (checkPriceImpact(quote.priceImpactPct, tradeLimits.max_price_impact_pct)) {
+ return { status: 'skipped', code: 'price_impact' };
+ }
+
+ // 3. Rug/honeypot firewall — buys only, the unsafe direction. A 'block' verdict
+ // refuses the entry (degrades to allow when a source is down, never stalls).
+ 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: 'strategy', agentId: id, userId: ownerId,
+ quoteLamports: BigInt(quote.inAtomics), enforced: assessment.verdict === 'block',
+ }).catch(() => {});
+ if (assessment.verdict === 'block') return { status: 'skipped', code: 'firewall_blocked' };
+ }
+ }
+
+ // 4. SOL fee/headroom against the real on-chain balance.
+ let walletLamports = null;
+ try { walletLamports = BigInt(await conn.getBalance(ownerPk, 'confirmed')); }
+ catch { walletLamports = null; }
+ if (walletLamports != null) {
+ const spendLamports = side === 'buy' ? BigInt(quote.inAtomics) : 0n;
+ if (checkSolHeadroom(walletLamports, spendLamports, SOL_FEE_HEADROOM_LAMPORTS)) {
+ return { status: 'skipped', code: 'insufficient_sol' };
+ }
+ }
+
+ // 5. Idempotency claim in the custody ledger (also the spend row). A retry with
+ // the same key replays instead of double-spending.
+ const [prior] = await sql`
+ SELECT status, signature, id FROM agent_custody_events
+ WHERE agent_id = ${id} AND idempotency_key = ${idempotencyKey} LIMIT 1
+ `;
+ if (prior) {
+ if (prior.status === 'confirmed' && prior.signature) {
+ return { status: 'executed', signature: prior.signature, custodyEventId: Number(prior.id), usd: usdValue, priceImpact: quote.priceImpactPct, quote, replayed: true };
+ }
+ if (prior.status === 'pending') return { status: 'failed', code: 'in_flight' };
+ return { status: 'failed', code: 'prior_failed' };
+ }
+
+ const reason = `strategy:${strategyRef?.slug || 'strategy'}`.slice(0, 64);
+ const eventMeta = {
+ side, mint, venue: quote.venue, reason,
+ expected_out_atomics: quote.outAtomics, min_out_atomics: quote.minOutAtomics,
+ slippage_bps: slippageBps, price_impact_pct: quote.priceImpactPct,
+ strategy: strategyRef,
+ };
+ const claim = await sql`
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset,
+ amount_lamports, amount_raw, usd, status, reason, idempotency_key, meta)
+ VALUES (
+ ${id}, ${ownerId}, 'spend', 'trade', ${network},
+ ${side === 'buy' ? 'SOL' : mint},
+ ${side === 'buy' ? quote.inAtomics : null},
+ ${side === 'sell' ? quote.inAtomics : null},
+ ${side === 'buy' ? usdValue ?? null : null},
+ 'pending', ${reason}, ${idempotencyKey},
+ ${JSON.stringify(eventMeta)}::jsonb
+ )
+ ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
+ RETURNING id
+ `;
+ if (!claim.length) return { status: 'failed', code: 'in_flight' };
+ const claimId = Number(claim[0].id);
+
+ // 6. Recover the key (audit-logged), build, broadcast, confirm.
+ let keypair;
+ try {
+ keypair = await recoverSolanaAgentKeypair(encryptedSecret, {
+ agentId: id, userId: ownerId, reason: `strategy_${side}`,
+ meta: { mint, network, custody_event_id: claimId, strategy_id: strategyRef?.strategy_id || null },
+ });
+ } catch {
+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});
+ return { status: 'failed', code: 'key_recover_failed' };
+ }
+
+ let instructions;
+ try {
+ instructions = await buildTradeInstructions({ side, conn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });
+ } catch (e) {
+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'build_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});
+ return { status: 'failed', code: 'build_failed' };
+ }
+
+ let signature;
+ let confirmed = true;
+ let execTelemetry = null;
+ try {
+ const result = await submitProtected({
+ network, connection: solanaConnection(network), 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: ownerId, action: 'custody.trade_failed', resourceId: id, meta: { side, mint, reason, strategy: strategyRef } });
+ return { status: 'failed', code: 'send_failed' };
+ }
+ }
+
+ if (!confirmed) {
+ await updateCustodyEvent(claimId, { signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});
+ logAudit({ userId: ownerId, action: 'custody.trade_unconfirmed', resourceId: id, meta: { side, mint, signature, reason, strategy: strategyRef } });
+ return { status: 'unconfirmed', signature, custodyEventId: claimId, usd: usdValue, priceImpact: quote.priceImpactPct, quote };
+ }
+
+ await updateCustodyEvent(claimId, { status: 'confirmed', signature, usd: side === 'buy' ? usdValue ?? null : null, meta: execTelemetry ? { exec: execTelemetry } : undefined }).catch(() => {});
+ logAudit({ userId: ownerId, action: 'custody.trade', resourceId: id, meta: { side, mint, venue: quote.venue, usd: usdValue, signature, network, reason, strategy: strategyRef, exec_route: execTelemetry?.route } });
+ await cacheSet(`sol:bal:${address}:${network}`, null, 1).catch(() => {});
+
+ return { status: 'executed', signature, custodyEventId: claimId, usd: usdValue, priceImpact: quote.priceImpactPct, quote };
+}
+
+// ── entries: evaluate real launches against one equipped strategy ─────────────
+// Best-effort. Opens at most `maxEntries` real positions this sweep. Records an
+// open position row per confirmed buy; the unique (agent,mint,network) index and
+// the custody idempotency key both prevent a double entry.
+async function evaluateEntries({ equip, agent, launches, nowMs, maxEntries = 3 }) {
+ const config = normalizeStrategyConfig(equip.config_snapshot);
+ const network = netOf(equip.network);
+ const results = [];
+
+ // pump.fun's public launch feed is mainnet-only — devnet has no entries (open
+ // positions there still exit via real on-chain re-quotes).
+ if (network !== 'mainnet' || !launches.length) return results;
+
+ // Cooldown — honor the strategy's minimum gap between entries.
+ if (config.risk.cooldown_minutes > 0 && equip.last_fired_at) {
+ const sinceMin = (nowMs - new Date(equip.last_fired_at).getTime()) / 60000;
+ if (sinceMin < config.risk.cooldown_minutes) return results;
+ }
+
+ // Concurrency — never exceed the strategy's max concurrent open positions.
+ const [openCnt] = await sql`
+ SELECT count(*)::int AS n FROM agent_strategy_positions
+ WHERE equip_id = ${equip.id} AND status IN ('open','closing')
+ `;
+ let room = Math.max(0, (config.risk.max_concurrent_positions || 0) - Number(openCnt?.n || 0));
+ if (room <= 0) return results;
+
+ const slippageBps = config.sizing.max_slippage_bps;
+ let opened = 0;
+ for (const launchRaw of launches) {
+ if (opened >= maxEntries || room <= 0) break;
+ const launch = { ...launchRaw };
+
+ // Enrich creator history only when the strategy actually gates on it (one
+ // upstream fetch per candidate, cached) — keeps the sweep cheap.
+ if ((config.entry.max_creator_launches != null || config.entry.min_creator_graduated != null) && launch.creator_launches == null) {
+ await enrichCreatorStats(launch).catch(() => {});
+ }
+
+ const verdict = matchesEntry(config, launch, nowMs);
+ if (!verdict.pass) continue;
+
+ // Already holding this mint for this equip? Don't stack.
+ const [held] = await sql`
+ SELECT 1 FROM agent_strategy_positions
+ WHERE equip_id = ${equip.id} AND mint = ${launch.mint} AND network = ${network}
+ AND status IN ('open','closing') LIMIT 1
+ `;
+ if (held) continue;
+
+ const idem = `strategy:${equip.id}:entry:${launch.mint}`;
+ const strategyRef = {
+ strategy_id: equip.strategy_id, equip_id: equip.id, slug: equip.slug,
+ strategy_name: equip.strategy_name, action: 'entry',
+ };
+ let result;
+ try {
+ result = await runStrategyTrade({
+ agent, side: 'buy', mint: launch.mint, network,
+ solAmount: config.sizing.amount_sol, tokenAmountRaw: null,
+ slippageBps, idempotencyKey: idem, strategyRef,
+ });
+ } catch (e) {
+ result = { status: 'failed', code: (e?.message || 'error').slice(0, 120) };
+ }
+
+ results.push({ mint: launch.mint, action: 'entry', ...result, reasons: verdict.reasons });
+
+ if (result.status === 'executed' || result.status === 'unconfirmed') {
+ const entryLamports = result.quote ? result.quote.inAtomics : null;
+ const baseAmount = result.quote ? result.quote.outAtomics : null;
+ await sql`
+ INSERT INTO agent_strategy_positions
+ (equip_id, strategy_id, agent_id, owner_id, network, mint, symbol, name, status,
+ entry_sig, entry_lamports, base_amount, entry_price_impact_pct,
+ peak_value_lamports, last_value_lamports, last_quoted_at)
+ VALUES (
+ ${equip.id}, ${equip.strategy_id}, ${agent.id}, ${equip.owner_id}, ${network},
+ ${launch.mint}, ${launch.symbol || null}, ${launch.name || null}, 'open',
+ ${result.signature || null}, ${entryLamports}, ${baseAmount}, ${result.priceImpact ?? null},
+ ${entryLamports}, ${entryLamports}, now()
+ )
+ ON CONFLICT (agent_id, mint, network) DO NOTHING
+ `.catch(() => {});
+ await sql`
+ UPDATE agent_strategy_equips
+ SET last_fired_at = now(), fires_count = fires_count + 1, last_eval_at = now(), updated_at = now()
+ WHERE id = ${equip.id}
+ `.catch(() => {});
+ opened += 1;
+ room -= 1;
+ }
+ }
+ return results;
+}
+
+// ── exits: re-quote every open position, close on TP/SL/trailing/timeout ───────
+// 100% real: the live value is a real quoteTrade(sell) of the agent's REAL on-chain
+// token balance; the exit is a real sell of that balance through the guarded path.
+async function evaluateExits({ equip, agent, nowMs, killed }) {
+ const network = netOf(equip.network);
+ const config = normalizeStrategyConfig(equip.config_snapshot);
+ const results = [];
+
+ const positions = await sql`
+ SELECT * FROM agent_strategy_positions
+ WHERE equip_id = ${equip.id} AND status IN ('open','closing') AND network = ${network}
+ ORDER BY opened_at ASC
+ `;
+ if (!positions.length) return results;
+
+ const conn = solanaConnection(network);
+ let ownerPk = null;
+ try { ownerPk = new PublicKey(agent.address); } catch { return results; }
+
+ for (const pos of positions) {
+ const mintPk = new PublicKey(pos.mint);
+ const { raw } = await readTokenBalance(conn, ownerPk, mintPk);
+
+ // The agent no longer holds the token (sold elsewhere / dust) — reconcile the
+ // row closed against real chain state rather than leaving a ghost position.
+ if (raw <= 0n) {
+ await sql`
+ UPDATE agent_strategy_positions
+ SET status = 'closed', exit_reason = 'manual', closed_at = now()
+ WHERE id = ${pos.id} AND status IN ('open','closing')
+ `.catch(() => {});
+ results.push({ mint: pos.mint, action: 'reconcile', status: 'closed', reason: 'no_holding' });
+ continue;
+ }
+
+ // Live value = a real re-quote of selling the whole holding.
+ let curValue = null;
+ try {
+ const q = await quoteTrade({ conn, side: 'sell', mintPk, mintStr: pos.mint, network, solAmount: null, tokenAmountRaw: raw.toString(), slippageBps: config.sizing.max_slippage_bps });
+ curValue = Number(q.outAtomics);
+ } catch { curValue = pos.last_value_lamports != null ? Number(pos.last_value_lamports) : null; }
+
+ if (curValue != null) {
+ const peak = Math.max(Number(pos.peak_value_lamports || 0), curValue);
+ await sql`
+ UPDATE agent_strategy_positions
+ SET last_value_lamports = ${curValue}, peak_value_lamports = ${peak}, last_quoted_at = now()
+ WHERE id = ${pos.id}
+ `.catch(() => {});
+ pos.peak_value_lamports = peak;
+ }
+
+ // While the kill switch is engaged, keep marking-to-market (so the owner sees
+ // live value) but never initiate an exit trade — the leash halts ALL strategy
+ // trading. The owner retains manual control via the discretionary endpoint.
+ if (killed) { results.push({ mint: pos.mint, action: 'hold', status: 'killed' }); continue; }
+
+ const decision = shouldExit(config, {
+ entry_lamports: pos.entry_lamports, peak_value_lamports: pos.peak_value_lamports, opened_at: new Date(pos.opened_at).getTime(),
+ }, curValue, nowMs);
+ if (!decision.exit) continue;
+
+ const idem = `strategy:${equip.id}:exit:${pos.mint}:${pos.id}`;
+ const strategyRef = {
+ strategy_id: equip.strategy_id, equip_id: equip.id, slug: equip.slug,
+ strategy_name: equip.strategy_name, action: 'exit', exit_reason: decision.reason,
+ };
+ await sql`UPDATE agent_strategy_positions SET status = 'closing' WHERE id = ${pos.id} AND status = 'open'`.catch(() => {});
+
+ let result;
+ try {
+ result = await runStrategyTrade({
+ agent, side: 'sell', mint: pos.mint, network,
+ solAmount: null, tokenAmountRaw: raw.toString(),
+ slippageBps: config.sizing.max_slippage_bps, idempotencyKey: idem, strategyRef,
+ });
+ } catch (e) {
+ result = { status: 'failed', code: (e?.message || 'error').slice(0, 120) };
+ }
+
+ results.push({ mint: pos.mint, action: 'exit', reason: decision.reason, ...result });
+
+ if (result.status === 'executed' || result.status === 'unconfirmed') {
+ const exitLamports = result.quote ? Number(result.quote.outAtomics) : null;
+ const entryLamports = pos.entry_lamports != null ? Number(pos.entry_lamports) : null;
+ const pnl = exitLamports != null && entryLamports != null ? exitLamports - entryLamports : null;
+ const pnlPct = pnl != null && entryLamports > 0 ? (pnl / entryLamports) * 100 : null;
+ await sql`
+ UPDATE agent_strategy_positions
+ SET status = 'closed', exit_reason = ${decision.reason}, exit_sig = ${result.signature || null},
+ exit_lamports = ${exitLamports}, realized_pnl_lamports = ${pnl}, realized_pnl_pct = ${pnlPct},
+ closed_at = now()
+ WHERE id = ${pos.id}
+ `.catch(() => {});
+ } else {
+ // Exit failed to land — drop back to 'open' so the next sweep retries.
+ await sql`UPDATE agent_strategy_positions SET status = 'open', error = ${result.code || 'exit_failed'} WHERE id = ${pos.id} AND status = 'closing'`.catch(() => {});
+ }
+ }
+ return results;
+}
+
+// ── public: evaluate one equip (exits first, then entries) ────────────────────
+export async function evaluateEquip(equip, { launches = null, nowMs = null, killed = false, maxEntries = 3 } = {}) {
+ const now = nowMs ?? Date.now();
+ const agent = await loadAgent(equip.agent_id);
+ if (!agent) return { equip_id: equip.id, error: 'agent_missing', results: [] };
+ if (!agent.address || !agent.encryptedSecret) {
+ await sql`UPDATE agent_strategy_equips SET last_eval_at = now() WHERE id = ${equip.id}`.catch(() => {});
+ return { equip_id: equip.id, error: 'wallet_preparing', results: [] };
+ }
+
+ const out = [];
+ // Exits ALWAYS run (mark-to-market + close) so positions are managed even on a
+ // sweep with no fresh launches.
+ const exits = await evaluateExits({ equip, agent, nowMs: now, killed });
+ out.push(...exits);
+
+ // Entries only when not killed and the equip is active.
+ if (!killed && equip.active) {
+ const feed = launches ?? await recentPumpLaunches({ network: netOf(equip.network), limit: 50 }).catch(() => []);
+ const entries = await evaluateEntries({ equip, agent, launches: feed, nowMs: now, maxEntries });
+ out.push(...entries);
+ }
+
+ await sql`UPDATE agent_strategy_equips SET last_eval_at = now() WHERE id = ${equip.id}`.catch(() => {});
+ return { equip_id: equip.id, results: out };
+}
+
+// ── public: a never-throwing launch-feed read (devnet → [], outage → []) ──────
+export async function recentPumpLaunchesSafe(network = 'mainnet') {
+ if (netOf(network) !== 'mainnet') return [];
+ return recentPumpLaunches({ network: 'mainnet', limit: 50 }).catch(() => []);
+}
+
+// ── public: the per-owner global kill set ─────────────────────────────────────
+export async function engagedKillOwners() {
+ const rows = await sql`SELECT owner_id FROM strategy_kill_switch WHERE engaged = true`.catch(() => []);
+ return new Set(rows.map((r) => r.owner_id));
+}
+
+// ── public: sweep every active equip on a network (cron + owner "Run now") ─────
+// Pulls the real launch feed ONCE and shares it across every equip on the network,
+// so a fanout of N equips makes one upstream feed call, not N. Bounded so a short
+// cron can never run away.
+export async function sweepStrategies({ network = 'mainnet', maxEquips = 200, maxEntriesPerEquip = 3 } = {}) {
+ const net = netOf(network);
+ const nowMs = Date.now();
+
+ const equips = await sql`
+ SELECT e.id, e.strategy_id, e.agent_id, e.owner_id, e.config_snapshot, e.strategy_version,
+ e.network, e.active, e.last_fired_at, e.last_eval_at,
+ s.slug, s.name AS strategy_name
+ FROM agent_strategy_equips e
+ JOIN agent_strategies s ON s.id = e.strategy_id AND s.deleted_at IS NULL
+ JOIN agent_identities a ON a.id = e.agent_id AND a.deleted_at IS NULL
+ WHERE e.active = true AND e.network = ${net}
+ ORDER BY e.last_eval_at ASC NULLS FIRST
+ LIMIT ${maxEquips}
+ `;
+ if (!equips.length) return { network: net, equips: 0, results: [] };
+
+ const killed = await engagedKillOwners();
+ const launches = net === 'mainnet' ? await recentPumpLaunches({ network: net, limit: 50 }).catch(() => []) : [];
+
+ const stats = { executed: 0, skipped: 0, failed: 0, unconfirmed: 0, closed: 0 };
+ let evaluated = 0;
+ for (const equip of equips) {
+ try {
+ const r = await evaluateEquip(equip, { launches, nowMs, killed: killed.has(equip.owner_id), maxEntries: maxEntriesPerEquip });
+ evaluated += 1;
+ for (const res of r.results) {
+ if (res.status && stats[res.status] != null) stats[res.status] += 1;
+ if (res.action === 'reconcile' && res.status === 'closed') stats.closed += 1;
+ }
+ } catch (e) {
+ stats.failed += 1;
+ stats.last_error = (e?.message || 'error').slice(0, 160);
+ }
+ }
+ return { network: net, equips: evaluated, ...stats };
+}
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 7bb2deba1..fe5fe4fde 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -82,6 +82,11 @@ export default wrap(async function handler(req, res) {
return mod.default(req, res, id, action);
}
+ if (sub === 'strategies') {
+ const mod = await import('./agent-strategy-objects.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/agent-strategy-objects.js b/api/agents/agent-strategy-objects.js
new file mode 100644
index 000000000..9c4370f20
--- /dev/null
+++ b/api/agents/agent-strategy-objects.js
@@ -0,0 +1,270 @@
+// /api/agents/:id/strategies — equip / unequip Strategy Objects on an agent and
+// drive the leashed runtime. Owner-only to configure; every strategy-initiated
+// trade executes through the task-05 engine inside the agent's spend policy
+// (api/_lib/agent-strategy-runtime.js) — this surface manages the equip bindings
+// and the per-owner kill switch; it never bypasses a guard.
+//
+// GET /api/agents/:id/strategies equipped strategies + live positions + kill state (owner)
+// POST /api/agents/:id/strategies equip a strategy { strategy_id, network } (owner)
+// POST /api/agents/:id/strategies/unequip unequip { equip_id | strategy_id } (owner)
+// POST /api/agents/:id/strategies/toggle pause/resume one equip { equip_id, active } (owner)
+// POST /api/agents/:id/strategies/kill toggle the per-owner global kill switch (owner)
+// POST /api/agents/:id/strategies/sweep evaluate this agent's equips now (owner "Run now")
+
+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 { normalizeStrategyConfig } from '../_lib/strategy-schema.js';
+import { evaluateEquip, recentPumpLaunchesSafe } from '../_lib/agent-strategy-runtime.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;
+}
+
+async function loadOwned(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in to manage strategies'); 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 equip strategies on this agent'); return null; }
+ return { auth, row };
+}
+
+async function killEngaged(ownerId) {
+ const [r] = await sql`SELECT engaged FROM strategy_kill_switch WHERE owner_id = ${ownerId}`.catch(() => [null]);
+ return !!r?.engaged;
+}
+
+function equipView(e, perf) {
+ return {
+ equip_id: e.id,
+ strategy_id: e.strategy_id,
+ strategy_name: e.strategy_name,
+ slug: e.slug,
+ owner_id: e.owner_id,
+ author_id: e.author_id,
+ network: e.network,
+ active: e.active,
+ strategy_version: e.strategy_version,
+ config: e.config_snapshot,
+ last_eval_at: e.last_eval_at || null,
+ last_fired_at: e.last_fired_at || null,
+ fires_count: Number(e.fires_count || 0),
+ performance: perf || { proven: false, trades: 0, open: 0 },
+ };
+}
+
+// GET — equipped strategies, their live positions, and the global kill state.
+async function handleGet(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const equips = await sql`
+ SELECT e.*, s.name AS strategy_name, s.slug, s.owner_id AS author_id
+ FROM agent_strategy_equips e
+ JOIN agent_strategies s ON s.id = e.strategy_id AND s.deleted_at IS NULL
+ WHERE e.agent_id = ${id}
+ ORDER BY e.created_at DESC
+ `;
+ const equipIds = equips.map((e) => e.id);
+
+ // Live performance per equip from real closed positions, plus the open positions.
+ let perfMap = new Map();
+ let positions = [];
+ if (equipIds.length) {
+ const perfRows = await sql`
+ SELECT equip_id,
+ count(*) FILTER (WHERE status = 'closed')::int AS closed,
+ count(*) FILTER (WHERE status IN ('open','closing'))::int AS open,
+ count(*) FILTER (WHERE status = 'closed' AND realized_pnl_lamports > 0)::int AS wins,
+ COALESCE(SUM(realized_pnl_lamports) FILTER (WHERE status = 'closed'), 0)::text AS pnl_lamports,
+ COALESCE(SUM(entry_lamports) FILTER (WHERE status = 'closed'), 0)::text AS entry_lamports
+ FROM agent_strategy_positions WHERE equip_id = ANY(${equipIds}) GROUP BY equip_id
+ `.catch(() => []);
+ for (const r of perfRows) {
+ const closed = Number(r.closed || 0);
+ const pnl = Number(r.pnl_lamports || 0) / 1e9;
+ const entry = Number(r.entry_lamports || 0) / 1e9;
+ perfMap.set(r.equip_id, {
+ proven: closed > 0, trades: closed, open: Number(r.open || 0),
+ pnl_sol: Number(pnl.toFixed(4)),
+ roi_pct: entry > 0 ? Number(((pnl / entry) * 100).toFixed(1)) : null,
+ win_rate: closed > 0 ? Number(((Number(r.wins || 0) / closed) * 100).toFixed(0)) : null,
+ });
+ }
+ positions = await sql`
+ SELECT id, equip_id, strategy_id, mint, symbol, name, status, exit_reason,
+ entry_sig, entry_lamports, exit_sig, exit_lamports, realized_pnl_lamports, realized_pnl_pct,
+ last_value_lamports, peak_value_lamports, opened_at, closed_at
+ FROM agent_strategy_positions
+ WHERE equip_id = ANY(${equipIds})
+ ORDER BY (status IN ('open','closing')) DESC, opened_at DESC
+ LIMIT 60
+ `.catch(() => []);
+ }
+
+ return json(res, 200, {
+ data: {
+ killed: await killEngaged(owned.auth.userId),
+ equips: equips.map((e) => equipView(e, perfMap.get(e.id))),
+ positions: positions.map((p) => ({
+ id: p.id, equip_id: p.equip_id, strategy_id: p.strategy_id,
+ mint: p.mint, symbol: p.symbol, name: p.name, status: p.status, exit_reason: p.exit_reason,
+ entry_sig: p.entry_sig, exit_sig: p.exit_sig,
+ entry_sol: p.entry_lamports != null ? Number(p.entry_lamports) / 1e9 : null,
+ exit_sol: p.exit_lamports != null ? Number(p.exit_lamports) / 1e9 : null,
+ value_sol: p.last_value_lamports != null ? Number(p.last_value_lamports) / 1e9 : null,
+ pnl_sol: p.realized_pnl_lamports != null ? Number(p.realized_pnl_lamports) / 1e9 : null,
+ pnl_pct: p.realized_pnl_pct != null ? Number(p.realized_pnl_pct) : null,
+ opened_at: p.opened_at, closed_at: p.closed_at,
+ })),
+ },
+ });
+}
+
+// POST — equip a strategy on this agent.
+async function handleEquip(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ if (!owned.row.meta?.solana_address) return error(res, 409, 'wallet_preparing', 'this agent’s wallet is still provisioning');
+
+ const body = await readJson(req).catch(() => null);
+ const strategyId = body?.strategy_id;
+ if (!isUuid(strategyId)) return error(res, 400, 'validation_error', 'a valid strategy_id is required');
+ const network = netOf(body?.network);
+
+ // The strategy must be the caller's own OR a published one (forking is the path to
+ // owning the rules; equipping a published strategy runs it under YOUR spend policy).
+ const [strat] = await sql`SELECT id, owner_id, name, config, version, published FROM agent_strategies WHERE id = ${strategyId} AND deleted_at IS NULL`;
+ if (!strat) return error(res, 404, 'not_found', 'strategy not found');
+ if (strat.owner_id !== owned.auth.userId && !strat.published) return error(res, 403, 'forbidden', 'this strategy is not published');
+
+ const snapshot = normalizeStrategyConfig(strat.config);
+ const [equip] = await sql`
+ INSERT INTO agent_strategy_equips (strategy_id, agent_id, owner_id, config_snapshot, strategy_version, network, active)
+ VALUES (${strategyId}, ${id}, ${owned.auth.userId}, ${JSON.stringify(snapshot)}::jsonb, ${strat.version}, ${network}, true)
+ ON CONFLICT (agent_id, strategy_id) DO UPDATE SET
+ active = true, network = ${network},
+ config_snapshot = ${JSON.stringify(snapshot)}::jsonb, strategy_version = ${strat.version},
+ updated_at = now()
+ RETURNING *
+ `;
+ await sql`UPDATE agent_strategies SET equips_count = (SELECT count(*) FROM agent_strategy_equips WHERE strategy_id = ${strategyId} AND active = true) WHERE id = ${strategyId}`.catch(() => {});
+ logAudit({ userId: owned.auth.userId, action: 'strategy.equip', resourceId: id, meta: { strategy_id: strategyId, network } });
+ return json(res, 200, { data: { equip: equipView({ ...equip, strategy_name: strat.name, slug: null, author_id: strat.owner_id }, { proven: false, trades: 0, open: 0 }) } });
+}
+
+async function handleUnequip(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const body = await readJson(req).catch(() => ({}));
+ const where = isUuid(body?.equip_id)
+ ? sql`id = ${body.equip_id} AND agent_id = ${id}`
+ : isUuid(body?.strategy_id)
+ ? sql`strategy_id = ${body.strategy_id} AND agent_id = ${id}`
+ : null;
+ if (!where) return error(res, 400, 'validation_error', 'equip_id or strategy_id required');
+ const [removed] = await sql`UPDATE agent_strategy_equips SET active = false, updated_at = now() WHERE ${where} RETURNING strategy_id`;
+ if (removed) {
+ await sql`UPDATE agent_strategies SET equips_count = (SELECT count(*) FROM agent_strategy_equips WHERE strategy_id = ${removed.strategy_id} AND active = true) WHERE id = ${removed.strategy_id}`.catch(() => {});
+ }
+ logAudit({ userId: owned.auth.userId, action: 'strategy.unequip', resourceId: id, meta: { strategy_id: removed?.strategy_id } });
+ return json(res, 200, { data: { unequipped: !!removed } });
+}
+
+async function handleToggle(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const body = await readJson(req).catch(() => ({}));
+ if (!isUuid(body?.equip_id)) return error(res, 400, 'validation_error', 'equip_id required');
+ const active = body.active !== false;
+ const [row] = await sql`UPDATE agent_strategy_equips SET active = ${active}, updated_at = now() WHERE id = ${body.equip_id} AND agent_id = ${id} RETURNING strategy_id`;
+ if (!row) return error(res, 404, 'not_found', 'equip not found');
+ await sql`UPDATE agent_strategies SET equips_count = (SELECT count(*) FROM agent_strategy_equips WHERE strategy_id = ${row.strategy_id} AND active = true) WHERE id = ${row.strategy_id}`.catch(() => {});
+ return json(res, 200, { data: { active } });
+}
+
+// POST kill — toggle the per-owner GLOBAL kill switch (halts ALL the owner's strategies).
+async function handleKill(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+ const body = await readJson(req).catch(() => ({}));
+ const current = await killEngaged(owned.auth.userId);
+ const next = body?.killed === undefined ? !current : !!body.killed;
+ await sql`
+ INSERT INTO strategy_kill_switch (owner_id, engaged, engaged_at, updated_at)
+ VALUES (${owned.auth.userId}, ${next}, ${next ? sql`now()` : null}, now())
+ ON CONFLICT (owner_id) DO UPDATE SET engaged = ${next}, engaged_at = ${next ? sql`now()` : null}, updated_at = now()
+ `;
+ logAudit({ userId: owned.auth.userId, action: 'strategy.kill', resourceId: id, meta: { engaged: next } });
+ return json(res, 200, { data: { killed: next } });
+}
+
+// POST sweep — evaluate THIS agent's active equips now (owner "Run now"). Exits run
+// even when killed (mark-to-market); entries only when not killed.
+async function handleSweep(req, res, id) {
+ const owned = await loadOwned(req, res, id);
+ if (!owned) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;
+
+ const killed = await killEngaged(owned.auth.userId);
+ const equips = await sql`
+ SELECT e.*, s.name AS strategy_name, s.slug
+ FROM agent_strategy_equips e
+ JOIN agent_strategies s ON s.id = e.strategy_id AND s.deleted_at IS NULL
+ WHERE e.agent_id = ${id} AND e.active = true
+ ORDER BY e.last_eval_at ASC NULLS FIRST
+ `;
+ if (!equips.length) return json(res, 200, { data: { evaluated: 0, results: [] } });
+
+ const byNet = new Set(equips.map((e) => netOf(e.network)));
+ const launchesByNet = {};
+ for (const net of byNet) launchesByNet[net] = await recentPumpLaunchesSafe(net);
+
+ const nowMs = Date.now();
+ const out = [];
+ for (const e of equips) {
+ try {
+ const r = await evaluateEquip(e, { launches: launchesByNet[netOf(e.network)], nowMs, killed, maxEntries: 3 });
+ out.push({ equip_id: e.id, strategy_name: e.strategy_name, results: r.results });
+ } catch (err) {
+ out.push({ equip_id: e.id, strategy_name: e.strategy_name, error: (err?.message || 'error').slice(0, 140) });
+ }
+ }
+ return json(res, 200, { data: { evaluated: equips.length, killed, results: out } });
+}
+
+export default async function handler(req, res, id, action) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!isUuid(id)) return error(res, 404, 'not_found', 'agent not found');
+
+ if (req.method === 'GET' && !action) return handleGet(req, res, id);
+ if (req.method === 'POST' && !action) return handleEquip(req, res, id);
+ if (req.method === 'POST' && action === 'unequip') return handleUnequip(req, res, id);
+ if (req.method === 'POST' && action === 'toggle') return handleToggle(req, res, id);
+ if (req.method === 'POST' && action === 'kill') return handleKill(req, res, id);
+ if (req.method === 'POST' && action === 'sweep') return handleSweep(req, res, id);
+ return error(res, 404, 'not_found', `unknown strategies route: ${action || req.method}`);
+}
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index dd478c833..9672e9af1 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -1394,6 +1394,77 @@ async function realizedPnlFor(id) {
}
}
+// Embodied-finance "flow" signals — the live DYNAMICS that ride on top of the
+// static net-worth tier so an agent that is *currently* earning reads warmer and a
+// bleeding one reads cooler, honestly. Every value traces to a real custody row:
+//
+// - momentum_usd_24h : realized net flow over the trailing 24h. Inflows are
+// confirmed tips (and, once Money Streams lands, stream credits); outflows are
+// spends (trades/snipes/x402/withdraw) and owner withdraws. A positive number
+// means the wallet took in more than it paid out today.
+// - streaming_now : count of OPEN, still-running money streams crediting this
+// agent right now. There is no stream event type until task 01 ships, so this
+// query is written generically (category/event_type='stream', meta.end_at in
+// the future) and returns 0 today — never a fabricated "earning" glow.
+// - last_tip_at : ISO time of the most recent confirmed tip, for the
+// recency pulse. null when never tipped.
+//
+// All windowed by `created_at`; defensive so a missing column/table degrades to a
+// neutral (flat) signal rather than throwing.
+async function flowSignalsFor(id) {
+ const flat = { momentumUsd24h: 0, inflowUsd24h: 0, outflowUsd24h: 0, streamingNow: 0, lastTipAt: null };
+ try {
+ const [flow] = await sql`
+ SELECT
+ COALESCE(sum(usd) FILTER (
+ WHERE event_type = 'tip' AND created_at > now() - interval '24 hours'
+ ), 0)::float8 AS inflow,
+ COALESCE(sum(usd) FILTER (
+ WHERE event_type IN ('spend', 'withdraw') AND created_at > now() - interval '24 hours'
+ ), 0)::float8 AS outflow,
+ max(created_at) FILTER (WHERE event_type = 'tip') AS last_tip_at
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND status IN ('ok', 'confirmed', 'pending')
+ `;
+ const inflow = Number(flow?.inflow) || 0;
+ const outflow = Number(flow?.outflow) || 0;
+ let streamingNow = 0;
+ try {
+ // Open streams crediting this agent right now. Generic by design so it
+ // lights up automatically when Money Streams (task 01) records its events,
+ // and stays 0 — never faked — until then.
+ const [s] = await sql`
+ SELECT count(*)::int AS n FROM agent_custody_events
+ WHERE agent_id = ${id}
+ AND (category = 'stream' OR event_type = 'stream')
+ AND status IN ('ok', 'pending')
+ AND COALESCE((meta->>'end_at')::timestamptz, now() + interval '1 second') > now()
+ `;
+ streamingNow = s?.n || 0;
+ } catch { streamingNow = 0; }
+ return {
+ momentumUsd24h: inflow - outflow,
+ inflowUsd24h: inflow,
+ outflowUsd24h: outflow,
+ streamingNow,
+ lastTipAt: flow?.last_tip_at ? new Date(flow.last_tip_at).toISOString() : null,
+ };
+ } catch {
+ return flat;
+ }
+}
+
+// Map a real signed 24h net flow (USD) onto a bounded momentum scalar in [-1, 1]
+// for the embodiment. Log-scaled so a $5 day and a $5,000 day both read as
+// "earning" without the larger one eye-searing — symmetric for inflow/outflow.
+// 0 → 0, ±$10 → ±0.5, ±$1,000 → ±1.0. Pure + documented; never random.
+function momentumScalar(usd) {
+ const v = Number(usd) || 0;
+ if (v === 0) return 0;
+ const mag = Math.min(1, Math.log10(1 + Math.abs(v)) / 3);
+ return v > 0 ? mag : -mag;
+}
+
// One real read of every reputation signal the look + regalia use.
async function reputationFor(id) {
const [forkCount, tips, pnl] = await Promise.all([
@@ -1448,7 +1519,7 @@ async function handleNetWorth(req, res, id) {
if (!rl.success) return rateLimited(res, rl);
const prefs = normalizePrefs(row.meta?.networth_look);
- const { forkCount, tips, pnl } = await reputationFor(id);
+ const [{ forkCount, tips, pnl }, flowRaw] = await Promise.all([reputationFor(id), flowSignalsFor(id)]);
const repState = {
forkCount,
tipCount: tips.count, tipUsd: tips.usd,
@@ -1470,6 +1541,7 @@ async function handleNetWorth(req, res, id) {
agent_id: id, address: null, network: 'mainnet', provisioning: true,
portfolio: { usd: 0, sol: 0, three: null, usdc: 0, token_count: 0, top: [] },
reputation,
+ flow: buildFlowPayload({ balanceSol: 0, balanceUsd: 0, tier: look.tier.key, flowRaw }),
tier: look.tier, look, marks: computeMarks({ usd: 0, ...repState }, { hubUrl }),
prefs, is_owner: isOwner, hub_url: hubUrl,
},
@@ -1518,6 +1590,7 @@ async function handleNetWorth(req, res, id) {
top,
},
reputation,
+ flow: buildFlowPayload({ balanceSol: sol, balanceUsd: usd, tier: look.tier.key, flowRaw }),
tier: look.tier,
look,
marks,
@@ -1529,6 +1602,24 @@ async function handleNetWorth(req, res, id) {
});
}
+// Shape the embodiment flow block the same way in every branch: the static
+// balance/tier the aura already uses, plus the live momentum/streaming/recency
+// dynamics. `momentum` is the bounded scalar the client maps to a warm/cool
+// shift; the raw USD figures are kept for the owner's "why" breakdown.
+function buildFlowPayload({ balanceSol, balanceUsd, tier, flowRaw }) {
+ return {
+ balance_sol: Number(balanceSol) || 0,
+ balance_usd: Number(balanceUsd) || 0,
+ tier,
+ momentum: momentumScalar(flowRaw.momentumUsd24h),
+ momentum_usd_24h: flowRaw.momentumUsd24h,
+ inflow_usd_24h: flowRaw.inflowUsd24h,
+ outflow_usd_24h: flowRaw.outflowUsd24h,
+ streaming_now: flowRaw.streamingNow,
+ last_tip_at: flowRaw.lastTipAt,
+ };
+}
+
// ── tip recording (on-chain verified) ──────────────────────────────────────────
// POST /api/agents/:id/solana/tip — record a P2P tip that a visitor already sent
// on-chain from their OWN wallet (api/../src/shared/agent-tip.js builds + signs it
@@ -1730,6 +1821,338 @@ async function handlePulseVisibility(req, res, id) {
return json(res, 200, { data: { opt_out: optOut, is_public: isPublic, in_public_pulse: isPublic && !optOut } });
}
+// ── money streams ───────────────────────────────────────────────────────────────
+// A Money Stream is pay-per-second income: a visitor authorizes a rate + a signed
+// max-total ceiling, then their browser micro-settles the accrued amount on a fixed
+// cadence with a REAL on-chain transfer from their own wallet to the agent's public
+// wallet (src/shared/agent-money-stream.js). Each settlement is one already-final
+// transfer — three.ws never custodies the funds. The client hands us the confirmed
+// signature; we INDEPENDENTLY verify on-chain that it credited the agent before
+// recording it, and we refuse any settlement that would push a stream session over
+// the ceiling it was opened with. Settlements are PUBLIC custody events
+// (event_type='stream', category='stream') grouped by a client stream_id, so they
+// power the agent's earnings view and the Money Pulse the same way tips do.
+//
+// POST /api/agents/:id/solana/stream — record + verify one settlement.
+// GET /api/agents/:id/solana/stream — earnings (lifetime + earning-now + daily).
+
+const STREAM_ID_RE = /^[0-9a-fA-F-]{8,64}$/;
+// A stream is "earning now" while its last settlement is fresher than the longest
+// settle cadence (60s) plus a grace window — anything older is a finished session.
+const STREAM_LIVE_WINDOW_S = 150;
+// Cumulative settlements may overshoot the signed ceiling only by floating-point
+// dust; anything beyond this is a real over-ceiling attempt and is rejected.
+const STREAM_CEILING_EPSILON = 1e-9;
+
+// Human (whole-asset) amount a stream row settled, from its stored raw fields.
+function _streamRowHuman(row, usdcMint) {
+ if (row.amount_lamports != null) return Number(row.amount_lamports) / 1e9;
+ if (row.amount_raw != null) return Number(row.amount_raw) / (row.asset === usdcMint ? 1e6 : 1e9);
+ return 0;
+}
+
+async function handleStreamRecord(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true, origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ // Streaming is open to anyone with a wallet (signed-in or not); throttle per-IP
+ // so the on-chain verification can't be abused. A settle fires every ~45–60s per
+ // active stream, well under this budget.
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const [row] = await sql`SELECT id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ const address = row.meta?.solana_address || null;
+ if (!address) return error(res, 404, 'not_found', 'agent has no solana wallet');
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+
+ const signature = typeof body.signature === 'string' ? body.signature.trim() : '';
+ if (!signature || signature.length < 32 || signature.length > 128 || !BASE58_RE.test(signature)) {
+ return error(res, 400, 'validation_error', 'a valid base58 tx signature is required');
+ }
+ const streamId = typeof body.stream_id === 'string' ? body.stream_id.trim() : '';
+ if (!streamId || !STREAM_ID_RE.test(streamId)) {
+ return error(res, 400, 'validation_error', 'a valid stream_id (uuid) is required');
+ }
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+ const assetRaw = typeof body.asset === 'string' && body.asset.trim() ? body.asset.trim().toUpperCase() : 'SOL';
+ const ratePerMinute = Number(body.rate_per_minute);
+ if (!Number.isFinite(ratePerMinute) || ratePerMinute <= 0) {
+ return error(res, 400, 'validation_error', 'rate_per_minute must be a positive number');
+ }
+ const maxTotal = Number(body.max_total);
+ if (!Number.isFinite(maxTotal) || maxTotal <= 0) {
+ return error(res, 400, 'validation_error', 'max_total must be a positive number');
+ }
+
+ const usdcMint = USDC_MINT_BY_CLUSTER[network];
+
+ // Idempotency: one row per settlement signature per agent.
+ const idempotencyKey = `stream:${signature}`;
+ {
+ const [existing] = await sql`
+ SELECT id FROM agent_custody_events
+ WHERE agent_id = ${id} AND idempotency_key = ${idempotencyKey}
+ `;
+ if (existing) {
+ return json(res, 200, { data: { recorded: false, replayed: true, signature, explorer: explorerTxUrl(signature, network), network } });
+ }
+ }
+
+ // Ceiling enforcement — the streamer signed a max_total when they opened this
+ // session; the sum of all confirmed settlements for the stream_id (plus this one)
+ // can never exceed it. We use the ceiling from the FIRST recorded settlement of
+ // the session as authoritative so a later request can't silently raise its own cap.
+ const priorRows = await sql`
+ SELECT amount_lamports, amount_raw, asset, meta
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND category = 'stream' AND meta->>'stream_id' = ${streamId}
+ `;
+ let priorSum = 0;
+ let sessionCeiling = maxTotal;
+ let sessionAsset = null;
+ for (const r of priorRows) {
+ priorSum += _streamRowHuman(r, usdcMint);
+ const c = Number(r.meta?.max_total);
+ if (Number.isFinite(c) && c > 0) sessionCeiling = c; // first/any prior ceiling wins
+ if (sessionAsset == null && r.asset) sessionAsset = r.asset;
+ }
+
+ // Verify on-chain before trusting the client's claimed amount.
+ const conn = solanaConnection(network);
+ let tx;
+ try {
+ tx = await conn.getParsedTransaction(signature, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' });
+ } catch {
+ tx = null;
+ }
+ if (!tx) return error(res, 202, 'tx_pending', 'transaction not visible yet — it may still be confirming, retry shortly');
+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'that settlement failed on-chain — nothing was streamed');
+
+ // Resolve the credited amount + asset straight from the chain.
+ let amountLamports = null, amountRaw = null, usd = null, assetOut = 'SOL', decimals = 9;
+ if (assetRaw === 'SOL') {
+ const lamports = _lamportsCreditedTo(tx, address);
+ if (lamports <= 0n) return error(res, 422, 'no_funds_received', 'no SOL was received at this agent wallet in that settlement');
+ amountLamports = lamports;
+ assetOut = 'SOL';
+ try { usd = await lamportsToUsd(lamports); } catch { usd = null; }
+ } else {
+ const mint = assetRaw === 'USDC' ? usdcMint : (validateSolanaAddress(body.asset).valid ? validateSolanaAddress(body.asset).base58 : null);
+ if (!mint) return error(res, 400, 'invalid_asset', 'asset must be "SOL", "USDC", or a valid SPL mint');
+ const atomics = _tokenCreditedTo(tx, mint, address);
+ if (atomics <= 0n) return error(res, 422, 'no_funds_received', 'none of that token was received at this agent wallet in that settlement');
+ amountRaw = atomics;
+ assetOut = mint;
+ if (mint === usdcMint) { decimals = 6; usd = Number(atomics) / 1e6; }
+ }
+
+ // A stream session is single-asset. Reject a settlement that switches asset
+ // mid-stream — it would corrupt the ceiling accounting.
+ if (sessionAsset && sessionAsset !== assetOut) {
+ return error(res, 409, 'asset_mismatch', 'this settlement uses a different asset than the rest of the stream session');
+ }
+
+ const thisHuman = amountLamports != null ? Number(amountLamports) / 1e9 : Number(amountRaw) / 10 ** decimals;
+ if (priorSum + thisHuman > sessionCeiling + STREAM_CEILING_EPSILON) {
+ return error(res, 409, 'ceiling_exceeded', 'this settlement would exceed the stream ceiling you authorized — it was not recorded', {
+ ceiling: sessionCeiling, settled_so_far: priorSum, attempted: thisHuman,
+ });
+ }
+
+ const from = _firstSigner(tx, address);
+ const blockTime = tx.blockTime ? new Date(tx.blockTime * 1000).toISOString() : null;
+
+ const inserted = await sql`
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset,
+ amount_lamports, amount_raw, usd, destination, signature, status, idempotency_key, meta)
+ VALUES (
+ ${id}, NULL, 'stream', 'stream', ${network}, ${assetOut},
+ ${amountLamports != null ? String(amountLamports) : null},
+ ${amountRaw != null ? String(amountRaw) : null},
+ ${usd ?? null}, ${address}, ${signature}, 'confirmed', ${idempotencyKey},
+ ${JSON.stringify({
+ source: 'money_stream', stream_id: streamId, rate_per_minute: ratePerMinute,
+ max_total: sessionCeiling, asset: assetOut, from: from || null,
+ block_time: blockTime, decimals,
+ })}::jsonb
+ )
+ ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
+ RETURNING id
+ `;
+ if (!inserted.length) {
+ return json(res, 200, { data: { recorded: false, replayed: true, signature, explorer: explorerTxUrl(signature, network), network } });
+ }
+
+ // Reflect the inbound funds in the cached balance immediately.
+ await cacheSet(`sol:bal:${address}:${network}`, null, 1).catch(() => {});
+
+ return json(res, 201, {
+ data: {
+ recorded: true, replayed: false, id: String(inserted[0].id),
+ signature, explorer: explorerTxUrl(signature, network), network,
+ asset: assetOut, amount: thisHuman, usd: usd ?? null, from: from || null,
+ stream_id: streamId, settled_so_far: priorSum + thisHuman, ceiling: sessionCeiling,
+ },
+ });
+}
+
+async function handleStreamEarnings(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true, origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const [row] = await sql`SELECT id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ const address = row.meta?.solana_address || null;
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const fromRaw = url.searchParams.get('from');
+ const from = fromRaw && BASE58_RE.test(fromRaw) && fromRaw.length >= 32 && fromRaw.length <= 44 ? fromRaw : null;
+ const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') || '20', 10) || 20));
+ const beforeRaw = url.searchParams.get('before');
+ const beforeId = beforeRaw && /^\d+$/.test(beforeRaw) ? beforeRaw : null;
+
+ const usdcMint = USDC_MINT_BY_CLUSTER[network];
+
+ if (!address) {
+ return json(res, 200, {
+ data: {
+ agentId: id, network, has_wallet: false,
+ lifetime: { settlements: 0, sessions: 0, streamers: 0, sol: 0, usdc: 0, usd: 0 },
+ earning_now: { active_streams: 0, last_settle_at: null, usd_per_min: 0 },
+ daily: [], recent: [], next_cursor: null,
+ },
+ });
+ }
+
+ // Lifetime aggregates over every confirmed stream settlement.
+ const [life] = await sql`
+ SELECT
+ count(*)::int AS settlements,
+ count(DISTINCT meta->>'stream_id')::int AS sessions,
+ count(DISTINCT meta->>'from')::int AS streamers,
+ COALESCE(sum(amount_lamports), 0)::float8 AS lamports,
+ COALESCE(sum(amount_raw) FILTER (WHERE asset = ${usdcMint}), 0)::float8 AS usdc_raw,
+ COALESCE(sum(usd), 0)::float8 AS usd
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND category = 'stream' AND network = ${network}
+ `;
+
+ // Earning-now: stream sessions whose last settlement is still inside the live
+ // window. Their summed rate is the agent's current per-minute income.
+ const [live] = await sql`
+ SELECT
+ count(*)::int AS active_streams,
+ COALESCE(sum(rate), 0)::float8 AS usd_per_min,
+ max(last_at) AS last_settle_at
+ FROM (
+ SELECT meta->>'stream_id' AS sid,
+ max(created_at) AS last_at,
+ (array_agg((meta->>'rate_per_minute')::float8 ORDER BY created_at DESC))[1] AS rate
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND category = 'stream' AND network = ${network}
+ GROUP BY meta->>'stream_id'
+ HAVING max(created_at) > now() - (interval '1 second' * ${STREAM_LIVE_WINDOW_S})
+ ) live_sessions
+ `;
+
+ // Daily USD + SOL income for the last 30 days (the owner earnings chart).
+ const daily = await sql`
+ SELECT to_char(date_trunc('day', created_at), 'YYYY-MM-DD') AS day,
+ COALESCE(sum(usd), 0)::float8 AS usd,
+ COALESCE(sum(amount_lamports), 0)::float8 / 1e9 AS sol
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND category = 'stream' AND network = ${network}
+ AND created_at > now() - interval '30 days'
+ GROUP BY 1 ORDER BY 1 ASC
+ `;
+
+ // Recent settlements (optionally scoped to one streamer's view).
+ const recentRows = await sql`
+ SELECT id, asset, amount_lamports, amount_raw, usd, signature, network, created_at, meta
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND category = 'stream' AND network = ${network}
+ AND (${from}::text IS NULL OR meta->>'from' = ${from})
+ AND (${beforeId}::bigint IS NULL OR id < ${beforeId})
+ ORDER BY id DESC
+ LIMIT ${limit}
+ `;
+ const recent = recentRows.map((e) => ({
+ id: String(e.id),
+ asset: e.asset === usdcMint ? 'USDC' : e.asset,
+ amount: _streamRowHuman(e, usdcMint),
+ usd: e.usd != null ? Number(e.usd) : null,
+ from: e.meta?.from || null,
+ stream_id: e.meta?.stream_id || null,
+ rate_per_minute: e.meta?.rate_per_minute != null ? Number(e.meta.rate_per_minute) : null,
+ signature: e.signature,
+ explorer: e.signature ? explorerTxUrl(e.signature, e.network) : null,
+ created_at: e.created_at,
+ }));
+ const nextCursor = recent.length === limit ? recent[recent.length - 1].id : null;
+
+ // A single streamer's own history with this agent (their "you've streamed" line).
+ let you = null;
+ if (from) {
+ const [y] = await sql`
+ SELECT count(*)::int AS settlements,
+ count(DISTINCT meta->>'stream_id')::int AS sessions,
+ COALESCE(sum(amount_lamports), 0)::float8 AS lamports,
+ COALESCE(sum(amount_raw) FILTER (WHERE asset = ${usdcMint}), 0)::float8 AS usdc_raw,
+ COALESCE(sum(usd), 0)::float8 AS usd
+ FROM agent_custody_events
+ WHERE agent_id = ${id} AND category = 'stream' AND network = ${network} AND meta->>'from' = ${from}
+ `;
+ you = {
+ settlements: y?.settlements || 0,
+ sessions: y?.sessions || 0,
+ sol: (Number(y?.lamports) || 0) / 1e9,
+ usdc: (Number(y?.usdc_raw) || 0) / 1e6,
+ usd: Number(y?.usd) || 0,
+ };
+ }
+
+ return json(res, 200, {
+ data: {
+ agentId: id, network, has_wallet: true, address,
+ lifetime: {
+ settlements: life?.settlements || 0,
+ sessions: life?.sessions || 0,
+ streamers: life?.streamers || 0,
+ sol: (Number(life?.lamports) || 0) / 1e9,
+ usdc: (Number(life?.usdc_raw) || 0) / 1e6,
+ usd: Number(life?.usd) || 0,
+ },
+ earning_now: {
+ active_streams: live?.active_streams || 0,
+ usd_per_min: Number(live?.usd_per_min) || 0,
+ last_settle_at: live?.last_settle_at || null,
+ },
+ daily: daily.map((d) => ({ day: d.day, usd: Number(d.usd) || 0, sol: Number(d.sol) || 0 })),
+ recent,
+ next_cursor: nextCursor,
+ ...(you ? { you } : {}),
+ },
+ });
+}
+
+async function handleStream(req, res, id) {
+ if (req.method === 'GET') return handleStreamEarnings(req, res, id);
+ return handleStreamRecord(req, res, id);
+}
+
// ── dispatcher ────────────────────────────────────────────────────────────────
export default async function handler(req, res, id, action) {
@@ -1742,6 +2165,7 @@ export default async function handler(req, res, id, action) {
if (action === 'custody') return handleCustody(req, res, id);
if (action === 'limits') return handleLimits(req, res, id);
if (action === 'tip') return handleTip(req, res, id);
+ if (action === 'stream') return handleStream(req, res, id);
if (action === 'pulse-visibility') return handlePulseVisibility(req, res, id);
if (action === 'intent') {
const mod = await import('./solana-intent.js');
diff --git a/api/asr.js b/api/asr.js
index f5f419a74..1f71738bb 100644
--- a/api/asr.js
+++ b/api/asr.js
@@ -65,9 +65,31 @@ function encodingFromContentType(ct) {
}
}
+// Encodings the lane accepts, advertised on the capability probe so the client
+// knows what it may upload without hard-coding the list twice.
+const ACCEPTED_ENCODINGS = ['wav', 'pcm', 'flac', 'ogg'];
+
export default wrap(async function handler(req, res) {
- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
- if (!method(req, res, ['POST'])) return;
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ // Capability probe — lets the avatar talk UI decide, without browser-sniffing,
+ // whether to capture audio for server-side Riva recognition or fall back to the
+ // browser's own SpeechRecognition. Cheap, unauthenticated, briefly cacheable.
+ if (req.method === 'GET' || req.method === 'HEAD') {
+ return json(
+ res,
+ 200,
+ {
+ configured: nvidiaAsrConfigured(),
+ encodings: ACCEPTED_ENCODINGS,
+ // 16 kHz mono is the Riva acoustic-model rate and the rate the client
+ // downsamples its capture to — surface it so the two never drift.
+ sampleRate: 16000,
+ },
+ { 'cache-control': 'public, max-age=60' },
+ );
+ }
if (!nvidiaAsrConfigured()) {
return error(
diff --git a/api/cron/strategy-fanout.js b/api/cron/strategy-fanout.js
new file mode 100644
index 000000000..e60a8d8a5
--- /dev/null
+++ b/api/cron/strategy-fanout.js
@@ -0,0 +1,43 @@
+// GET /api/cron/strategy-fanout — drive the Strategy Object runtime.
+//
+// For every active equip (a strategy bound to an agent), evaluate REAL pump.fun
+// launches against the entry rules and manage open positions (re-quote, take-profit
+// / stop-loss / trailing / timeout), executing every action through the task-05
+// engine inside the agent's spend policy (api/_lib/agent-strategy-runtime.js).
+//
+// Idempotent end to end: the agent_strategy_positions unique (agent,mint,network)
+// index and the custody idempotency key both prevent double-entry / double-spend,
+// so re-running this cron (or overlapping with an owner "Run now") is always safe.
+// The per-owner global kill switch halts all of an owner's strategies at once;
+// exits still mark-to-market while killed but never initiate a trade.
+
+import { error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sweepStrategies } from '../_lib/agent-strategy-runtime.js';
+
+const NETWORKS = ['mainnet', 'devnet'];
+
+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 out = {};
+ for (const network of NETWORKS) {
+ try {
+ out[network] = await sweepStrategies({ network, maxEquips: 200, maxEntriesPerEquip: 3 });
+ } catch (err) {
+ out[network] = { error: (err?.message || 'error').slice(0, 160) };
+ }
+ }
+ return json(res, 200, { ok: true, ...out });
+});
diff --git a/api/strategies.js b/api/strategies.js
new file mode 100644
index 000000000..8d3accc4b
--- /dev/null
+++ b/api/strategies.js
@@ -0,0 +1,372 @@
+// /api/strategies — the Strategy Object library: an ownable, publishable,
+// forkable, leaderboard-ranked trade strategy as a first-class object.
+//
+// GET /api/strategies list (scope=mine|published, sort, q)
+// POST /api/strategies create a strategy (owner-authored)
+// GET /api/strategies/leaderboard published strategies ranked by REAL live perf
+// GET /api/strategies/:id fetch one (public if published; owner otherwise)
+// PATCH /api/strategies/:id edit config/name/description (owner, bumps version)
+// DELETE /api/strategies/:id soft-delete (owner)
+// POST /api/strategies/:id/fork fork into the caller's library (lineage, no wallet access)
+// POST /api/strategies/:id/publish toggle published (owner)
+//
+// Strategies are NOT free text — every config passes validateStrategyConfig before
+// it persists. Performance shown is REAL live performance aggregated from real
+// on-chain fills (agent_strategy_positions); a strategy with no closed positions is
+// honestly "unproven" — never a fabricated backtest curve. Forking copies the RULES
+// only: fresh ownership, lineage credited to the author, and the forker runs them
+// under THEIR OWN spend policy — no wallet access is ever transferred.
+
+import { sql } from './_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
+import { requireCsrf } from './_lib/csrf.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { isUuid } from './_lib/validate.js';
+import { logAudit } from './_lib/audit.js';
+import { validateStrategyConfig, slugifyStrategy } from './_lib/strategy-schema.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;
+}
+
+const LIST_SORTS = new Set(['recent', 'forks', 'equips', 'performance']);
+
+// Real live performance for a set of strategies, aggregated from real closed
+// on-chain positions across every equip of each strategy. Returns a map id→stats.
+// A strategy with 0 closed positions is "unproven" (proven:false) — never faked.
+async function performanceByStrategy(ids) {
+ if (!ids.length) return new Map();
+ const rows = await sql`
+ SELECT strategy_id,
+ count(*) FILTER (WHERE status = 'closed')::int AS closed,
+ count(*) FILTER (WHERE status IN ('open','closing'))::int AS open,
+ count(*) FILTER (WHERE status = 'closed' AND realized_pnl_lamports > 0)::int AS wins,
+ count(*) FILTER (WHERE status = 'closed' AND realized_pnl_lamports <= 0)::int AS losses,
+ COALESCE(SUM(realized_pnl_lamports) FILTER (WHERE status = 'closed'), 0)::text AS pnl_lamports,
+ COALESCE(SUM(entry_lamports) FILTER (WHERE status = 'closed'), 0)::text AS entry_lamports,
+ COALESCE(MIN(realized_pnl_lamports) FILTER (WHERE status = 'closed'), 0)::text AS worst_lamports,
+ MAX(closed_at) AS last_closed_at
+ FROM agent_strategy_positions
+ WHERE strategy_id = ANY(${ids})
+ GROUP BY strategy_id
+ `.catch(() => []);
+ const map = new Map();
+ for (const r of rows) {
+ const closed = Number(r.closed || 0);
+ const pnl = Number(r.pnl_lamports || 0) / 1e9;
+ const entry = Number(r.entry_lamports || 0) / 1e9;
+ map.set(r.strategy_id, {
+ proven: closed > 0,
+ trades: closed,
+ open: Number(r.open || 0),
+ wins: Number(r.wins || 0),
+ losses: Number(r.losses || 0),
+ pnl_sol: Number(pnl.toFixed(4)),
+ roi_pct: entry > 0 ? Number(((pnl / entry) * 100).toFixed(1)) : null,
+ win_rate: closed > 0 ? Number(((Number(r.wins || 0) / closed) * 100).toFixed(0)) : null,
+ worst_sol: Number((Number(r.worst_lamports || 0) / 1e9).toFixed(4)),
+ last_closed_at: r.last_closed_at || null,
+ });
+ }
+ return map;
+}
+
+function publicStrategy(row, perf, ownerName) {
+ return {
+ id: row.id,
+ name: row.name,
+ slug: row.slug,
+ description: row.description || null,
+ config: row.config,
+ version: row.version,
+ published: row.published,
+ published_at: row.published_at || null,
+ owner_id: row.owner_id,
+ owner_name: ownerName || null,
+ fork_of: row.fork_of || null,
+ forked_from: row.forked_from || null,
+ forks_count: Number(row.forks_count || 0),
+ equips_count: Number(row.equips_count || 0),
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ performance: perf || { proven: false, trades: 0, open: 0 },
+ };
+}
+
+async function ownerNames(ids) {
+ if (!ids.length) return new Map();
+ const rows = await sql`SELECT id, COALESCE(display_name, username) AS name FROM users WHERE id = ANY(${ids})`.catch(() => []);
+ return new Map(rows.map((u) => [u.id, u.name]));
+}
+
+// GET /api/strategies?scope=mine|published&sort=&q=&limit=
+async function handleList(req, res, auth) {
+ const p = new URL(req.url, 'http://x').searchParams;
+ const scope = p.get('scope') === 'mine' ? 'mine' : 'published';
+ const sort = LIST_SORTS.has(p.get('sort')) ? p.get('sort') : (scope === 'published' ? 'performance' : 'recent');
+ const q = (p.get('q') || '').trim().slice(0, 80);
+ const limit = Math.min(60, Math.max(1, parseInt(p.get('limit') || '30', 10) || 30));
+
+ if (scope === 'mine') {
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to view your strategies');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const rows = await sql`
+ SELECT * FROM agent_strategies
+ WHERE owner_id = ${auth.userId} AND deleted_at IS NULL
+ ${q ? sql`AND name ILIKE ${'%' + q + '%'}` : sql``}
+ ORDER BY updated_at DESC
+ LIMIT ${limit}
+ `;
+ const perf = await performanceByStrategy(rows.map((r) => r.id));
+ const names = await ownerNames([auth.userId]);
+ return json(res, 200, { data: { scope, strategies: rows.map((r) => publicStrategy(r, perf.get(r.id), names.get(r.owner_id))) } });
+ }
+
+ // Published marketplace (public). An optional `author` filters to one creator's
+ // published strategies — the agent-profile "strategies this creator publishes".
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const author = p.get('author');
+ const rows = await sql`
+ SELECT * FROM agent_strategies
+ WHERE published = true AND deleted_at IS NULL
+ ${isUuid(author) ? sql`AND owner_id = ${author}` : sql``}
+ ${q ? sql`AND (name ILIKE ${'%' + q + '%'} OR description ILIKE ${'%' + q + '%'})` : sql``}
+ ORDER BY ${sort === 'forks' ? sql`forks_count DESC` : sort === 'equips' ? sql`equips_count DESC` : sql`published_at DESC`}
+ LIMIT ${limit}
+ `;
+ const perf = await performanceByStrategy(rows.map((r) => r.id));
+ const names = await ownerNames([...new Set(rows.map((r) => r.owner_id))]);
+ let strategies = rows.map((r) => publicStrategy(r, perf.get(r.id), names.get(r.owner_id)));
+ // "performance" sort ranks proven strategies by ROI, then unproven by recency —
+ // a real, honest order (no synthetic curve can climb it).
+ if (sort === 'performance') {
+ strategies = strategies.sort((a, b) => {
+ const ap = a.performance.proven ? 1 : 0, bp = b.performance.proven ? 1 : 0;
+ if (ap !== bp) return bp - ap;
+ if (ap && bp) return (b.performance.roi_pct ?? -1e9) - (a.performance.roi_pct ?? -1e9);
+ return new Date(b.published_at || 0) - new Date(a.published_at || 0);
+ });
+ }
+ return json(res, 200, { data: { scope, sort, strategies } });
+}
+
+// GET /api/strategies/leaderboard — proven published strategies, ranked by real ROI.
+async function handleLeaderboard(req, res) {
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const limit = Math.min(50, Math.max(1, parseInt(new URL(req.url, 'http://x').searchParams.get('limit') || '20', 10) || 20));
+ const rows = await sql`SELECT * FROM agent_strategies WHERE published = true AND deleted_at IS NULL LIMIT 200`;
+ const perf = await performanceByStrategy(rows.map((r) => r.id));
+ const names = await ownerNames([...new Set(rows.map((r) => r.owner_id))]);
+ const ranked = rows
+ .map((r) => publicStrategy(r, perf.get(r.id), names.get(r.owner_id)))
+ .filter((s) => s.performance.proven)
+ .sort((a, b) => (b.performance.roi_pct ?? -1e9) - (a.performance.roi_pct ?? -1e9))
+ .slice(0, limit)
+ .map((s, i) => ({ ...s, rank: i + 1 }));
+ return json(res, 200, { data: { leaders: ranked, count: ranked.length } });
+}
+
+// POST /api/strategies — create.
+async function handleCreate(req, res, auth) {
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ const body = await readJson(req).catch(() => null);
+ if (!body) return error(res, 400, 'validation_error', 'invalid JSON body');
+
+ const name = String(body.name || '').trim().slice(0, 80);
+ if (!name) return error(res, 400, 'validation_error', 'a strategy needs a name');
+ const description = body.description == null ? null : String(body.description).slice(0, 2000);
+
+ const { valid, errors, config } = validateStrategyConfig(body.config);
+ if (!valid) return error(res, 400, 'validation_error', 'strategy rules are invalid', { errors });
+
+ const slug = await uniqueSlug(auth.userId, name);
+ const [row] = await sql`
+ INSERT INTO agent_strategies (owner_id, name, slug, description, config, version)
+ VALUES (${auth.userId}, ${name}, ${slug}, ${description}, ${JSON.stringify(config)}::jsonb, 1)
+ RETURNING *
+ `;
+ logAudit({ userId: auth.userId, action: 'strategy.create', resourceId: row.id, meta: { name } });
+ const names = await ownerNames([auth.userId]);
+ return json(res, 201, { data: publicStrategy(row, { proven: false, trades: 0, open: 0 }, names.get(auth.userId)) });
+}
+
+// A per-owner unique slug — append -2, -3… on collision (matches the partial unique index).
+async function uniqueSlug(ownerId, name) {
+ const base = slugifyStrategy(name);
+ const taken = await sql`SELECT slug FROM agent_strategies WHERE owner_id = ${ownerId} AND deleted_at IS NULL AND (slug = ${base} OR slug LIKE ${base + '-%'})`.catch(() => []);
+ const set = new Set(taken.map((r) => r.slug));
+ if (!set.has(base)) return base;
+ for (let i = 2; i < 1000; i++) { const c = `${base}-${i}`; if (!set.has(c)) return c; }
+ return `${base}-${Date.now()}`;
+}
+
+async function loadStrategy(id) {
+ const [row] = await sql`SELECT * FROM agent_strategies WHERE id = ${id} AND deleted_at IS NULL`;
+ return row || null;
+}
+
+// GET /api/strategies/:id
+async function handleGetOne(req, res, auth, id) {
+ const row = await loadStrategy(id);
+ if (!row) return error(res, 404, 'not_found', 'strategy not found');
+ const isOwner = auth && row.owner_id === auth.userId;
+ if (!row.published && !isOwner) return error(res, 404, 'not_found', 'strategy not found');
+ const perf = await performanceByStrategy([id]);
+ const names = await ownerNames([row.owner_id]);
+ // Where it's equipped — owner sees the live equip surface; everyone sees the count.
+ const [eq] = await sql`SELECT count(*)::int AS n, count(*) FILTER (WHERE active) AS active FROM agent_strategy_equips WHERE strategy_id = ${id}`.catch(() => [{ n: 0, active: 0 }]);
+ return json(res, 200, {
+ data: {
+ ...publicStrategy(row, perf.get(id), names.get(row.owner_id)),
+ is_owner: !!isOwner,
+ equipped: { total: Number(eq?.n || 0), active: Number(eq?.active || 0) },
+ },
+ });
+}
+
+// PATCH /api/strategies/:id — edit (owner). Bumps version; re-snapshots into no equip
+// (existing equips keep their pinned config_snapshot until re-equipped).
+async function handleUpdate(req, res, auth, id) {
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const row = await loadStrategy(id);
+ if (!row) return error(res, 404, 'not_found', 'strategy not found');
+ if (row.owner_id !== auth.userId) return error(res, 403, 'forbidden', 'not your strategy');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ const body = await readJson(req).catch(() => null);
+ if (!body) return error(res, 400, 'validation_error', 'invalid JSON body');
+
+ let { name, slug, description, config, version } = row;
+ let bump = false;
+ if (typeof body.name === 'string' && body.name.trim()) {
+ const next = body.name.trim().slice(0, 80);
+ if (next !== name) { name = next; slug = await uniqueSlug(auth.userId, next); }
+ }
+ if (body.description !== undefined) description = body.description == null ? null : String(body.description).slice(0, 2000);
+ if (body.config !== undefined) {
+ const r = validateStrategyConfig(body.config);
+ if (!r.valid) return error(res, 400, 'validation_error', 'strategy rules are invalid', { errors: r.errors });
+ if (JSON.stringify(r.config) !== JSON.stringify(row.config)) { config = r.config; bump = true; }
+ }
+ const nextVersion = bump ? version + 1 : version;
+ const [updated] = await sql`
+ UPDATE agent_strategies
+ SET name = ${name}, slug = ${slug}, description = ${description},
+ config = ${JSON.stringify(config)}::jsonb, version = ${nextVersion}, updated_at = now()
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ logAudit({ userId: auth.userId, action: 'strategy.update', resourceId: id, meta: { version: nextVersion } });
+ const perf = await performanceByStrategy([id]);
+ const names = await ownerNames([auth.userId]);
+ return json(res, 200, { data: publicStrategy(updated, perf.get(id), names.get(auth.userId)) });
+}
+
+// DELETE /api/strategies/:id — soft-delete (owner). Deactivates equips so the
+// runtime stops evaluating it; open positions remain owner-managed.
+async function handleDelete(req, res, auth, id) {
+ const row = await loadStrategy(id);
+ if (!row) return error(res, 404, 'not_found', 'strategy not found');
+ if (row.owner_id !== auth.userId) return error(res, 403, 'forbidden', 'not your strategy');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ await sql`UPDATE agent_strategies SET deleted_at = now(), published = false WHERE id = ${id}`;
+ await sql`UPDATE agent_strategy_equips SET active = false, updated_at = now() WHERE strategy_id = ${id}`.catch(() => {});
+ logAudit({ userId: auth.userId, action: 'strategy.delete', resourceId: id });
+ return json(res, 200, { data: { deleted: true } });
+}
+
+// POST /api/strategies/:id/fork — clone the RULES into the caller's library.
+// Fresh ownership, lineage credited to the author. No wallet access transferred:
+// the forker runs the rules under THEIR OWN spend policy. Mirrors api/agents/fork.js.
+async function handleFork(req, res, auth, id) {
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ const src = await loadStrategy(id);
+ if (!src) return error(res, 404, 'not_found', 'strategy not found');
+ if (!src.published && src.owner_id !== auth.userId) return error(res, 403, 'forbidden', 'this strategy is not published');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
+ const [srcOwner] = await sql`SELECT COALESCE(display_name, username) AS name FROM users WHERE id = ${src.owner_id}`.catch(() => [{}]);
+ const forked_from = {
+ strategy_id: src.id,
+ owner_id: src.owner_id,
+ owner_name: srcOwner?.name || null,
+ name: src.name,
+ version: src.version,
+ forked_at: new Date().toISOString(),
+ };
+ const slug = await uniqueSlug(auth.userId, src.name);
+ const [row] = await sql`
+ INSERT INTO agent_strategies (owner_id, name, slug, description, config, version, fork_of, forked_from)
+ VALUES (${auth.userId}, ${src.name}, ${slug}, ${src.description}, ${JSON.stringify(src.config)}::jsonb, 1, ${src.id}, ${JSON.stringify(forked_from)}::jsonb)
+ RETURNING *
+ `;
+ await sql`UPDATE agent_strategies SET forks_count = forks_count + 1 WHERE id = ${src.id}`.catch(() => {});
+ logAudit({ userId: auth.userId, action: 'strategy.fork', resourceId: row.id, meta: { fork_of: src.id, author: src.owner_id } });
+ const names = await ownerNames([auth.userId]);
+ return json(res, 201, { data: publicStrategy(row, { proven: false, trades: 0, open: 0 }, names.get(auth.userId)) });
+}
+
+// POST /api/strategies/:id/publish — toggle published (owner).
+async function handlePublish(req, res, auth, id) {
+ const row = await loadStrategy(id);
+ if (!row) return error(res, 404, 'not_found', 'strategy not found');
+ if (row.owner_id !== auth.userId) return error(res, 403, 'forbidden', 'not your strategy');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ const body = await readJson(req).catch(() => ({}));
+ const next = body?.published === undefined ? !row.published : !!body.published;
+ const [updated] = await sql`
+ UPDATE agent_strategies
+ SET published = ${next}, published_at = ${next ? sql`COALESCE(published_at, now())` : sql`published_at`}, updated_at = now()
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ logAudit({ userId: auth.userId, action: 'strategy.publish', resourceId: id, meta: { published: next } });
+ const perf = await performanceByStrategy([id]);
+ const names = await ownerNames([auth.userId]);
+ return json(res, 200, { data: publicStrategy(updated, perf.get(id), names.get(auth.userId)) });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;
+
+ const parts = new URL(req.url, 'http://x').pathname.split('/').filter(Boolean); // ['api','strategies', maybe id, maybe action]
+ const seg = parts[2] || null;
+ const action = parts[3] || null;
+ const auth = await resolveAuth(req);
+
+ // Collection + special collection routes.
+ if (!seg) {
+ if (req.method === 'GET') return handleList(req, res, auth);
+ if (req.method === 'POST') {
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to create a strategy');
+ return handleCreate(req, res, auth);
+ }
+ return error(res, 405, 'method_not_allowed', 'unsupported method');
+ }
+ if (seg === 'leaderboard') return handleLeaderboard(req, res);
+
+ if (!isUuid(seg)) return error(res, 404, 'not_found', 'strategy not found');
+ const id = seg;
+
+ if (req.method === 'GET' && !action) return handleGetOne(req, res, auth, id);
+
+ // Everything below mutates → requires auth.
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (req.method === 'POST' && action === 'fork') return handleFork(req, res, auth, id);
+ if (req.method === 'POST' && action === 'publish') return handlePublish(req, res, auth, id);
+ if (req.method === 'PATCH' && !action) return handleUpdate(req, res, auth, id);
+ if (req.method === 'DELETE' && !action) return handleDelete(req, res, auth, id);
+ return error(res, 404, 'not_found', `unknown strategy route: ${action || req.method}`);
+});
diff --git a/avatar-sdk/src/viewer.js b/avatar-sdk/src/viewer.js
index aaa2ed9ba..97949a35f 100644
--- a/avatar-sdk/src/viewer.js
+++ b/avatar-sdk/src/viewer.js
@@ -30,7 +30,7 @@ const TAG = 'three-ws-viewer';
class ThreeWsViewerElement extends HTMLElement {
static get observedAttributes() {
- return ['src', 'alt', 'background'];
+ return ['src', 'alt', 'background', 'wallet', 'agent-id', 'api-base'];
}
constructor() {
@@ -53,6 +53,7 @@ class ThreeWsViewerElement extends HTMLElement {
this._raf = 0;
this._resizeObs = null;
this._loadToken = 0;
+ this._wallet = null; // mounted wallet affordance, when opted in
}
connectedCallback() {
@@ -62,6 +63,7 @@ class ThreeWsViewerElement extends HTMLElement {
const src = this.getAttribute('src');
if (src) this._loadModel(src);
this._applyAlt(this.getAttribute('alt'));
+ this._applyWallet();
}
disconnectedCallback() {
@@ -82,6 +84,7 @@ class ThreeWsViewerElement extends HTMLElement {
}
this._envTex?.dispose();
this._envTex = null;
+ if (this._wallet) { try { this._wallet.destroy(); } catch { /* gone */ } this._wallet = null; }
if (this._model) { this._disposeModel(this._model); this._model = null; }
this._scene = null;
this._camera = null;
@@ -92,6 +95,7 @@ class ThreeWsViewerElement extends HTMLElement {
if (name === 'src') this._loadModel(value);
else if (name === 'alt') this._applyAlt(value);
else if (name === 'background') this._applyBackground(value);
+ else if (name === 'wallet' || name === 'agent-id' || name === 'api-base') this._applyWallet();
}
_init() {
@@ -214,6 +218,27 @@ class ThreeWsViewerElement extends HTMLElement {
this._label.textContent = text;
}
+ // Opt-in wallet identity: with `wallet agent-id="<uuid>"` the viewer shows the
+ // agent's public wallet (address, value, tips, one-tap tip) without pulling the
+ // heavy <agent-3d> runtime or any dependency. Lazy-loaded so a wallet-less embed
+ // pays zero cost. Visitor view only — never an owner control.
+ async _applyWallet() {
+ const wants = this.hasAttribute('wallet');
+ const agentId = (this.getAttribute('agent-id') || '').trim();
+ const apiBase = (this.getAttribute('api-base') || '').trim() || undefined;
+ // Tear down on a change so we never stack two cards or keep a stale agent.
+ if (this._wallet) { try { this._wallet.destroy(); } catch { /* gone */ } this._wallet = null; }
+ if (!wants || !agentId) return;
+ const network = (this.getAttribute('wallet') || '').toLowerCase() === 'devnet' ? 'devnet' : 'mainnet';
+ try {
+ const { mountSdkWallet } = await import('./wallet-affordance.js');
+ if (!this.isConnected || (this.getAttribute('agent-id') || '').trim() !== agentId) return;
+ this._wallet = mountSdkWallet(this._shadow, { agentId, apiBase, network });
+ } catch {
+ /* wallet module unavailable — the viewer still renders the avatar cleanly */
+ }
+ }
+
_disposeModel(obj) {
obj?.traverse?.((n) => {
n.geometry?.dispose?.();
diff --git a/avatar-sdk/src/wallet-affordance.js b/avatar-sdk/src/wallet-affordance.js
new file mode 100644
index 000000000..a4a506a33
--- /dev/null
+++ b/avatar-sdk/src/wallet-affordance.js
@@ -0,0 +1,209 @@
+// Self-contained wallet affordance for <three-ws-viewer>.
+//
+// The minimal mesh viewer has no agent runtime, so when an embedder opts in with
+// `wallet agent-id="<uuid>"` we render the agent's wallet identity here without
+// pulling the heavy <agent-3d> runtime, a wallet SDK, or any dependency. It reads
+// ONLY public data from three.ws's CORS:* embed endpoint
+// (GET /api/agents/wallet-embed) — address, live USD value, lifetime tips — and
+// is the visitor view by construction: copy the address, tip from a phone wallet
+// via a Solana Pay deep link, or open the full wallet on three.ws. It never
+// exposes a secret or an owner control; ownership is decided only by a real
+// three.ws session, never asserted by the embedding host.
+//
+// Kept dependency-free on purpose: the published @three-ws/avatar package must
+// not depend on the main app's internal modules. The richer in-app/off-site
+// wallet (connected-wallet signing, QR) lives on <agent-3d wallet>.
+
+const ORIGIN_DEFAULT = 'https://three.ws';
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]),
+ );
+}
+
+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`;
+}
+
+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);
+ return `${esc(pre)}…${esc(suf)}`;
+}
+
+// Solana Pay URI — opens Phantom/Solflare on a phone for a real, one-tap tip.
+function solanaPayUri(address, { label } = {}) {
+ const params = new URLSearchParams();
+ if (label) params.set('label', label);
+ const q = params.toString();
+ return `solana:${address}${q ? `?${q}` : ''}`;
+}
+
+const STYLE = `
+.tws-w{position:absolute;left:10px;bottom:10px;z-index:6;font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;}
+.tws-w *{box-sizing:border-box;}
+.tws-w-chip{display:inline-flex;align-items:center;gap:6px;padding:4px 9px;border-radius:999px;cursor:pointer;appearance:none;
+ font:600 11px/1 inherit;color:#c4b5fd;background:rgba(139,92,246,.14);border:1px solid rgba(139,92,246,.34);
+ white-space:nowrap;transition:background .18s,border-color .18s;backdrop-filter:blur(8px);}
+.tws-w-chip:hover{background:rgba(139,92,246,.22);border-color:rgba(139,92,246,.55);}
+.tws-w-ico{width:12px;height:12px;flex:none;opacity:.85;}
+.tws-w-addr{font-family:ui-monospace,"JetBrains Mono",Menlo,monospace;letter-spacing:.01em;}
+.tws-w-val{font-family:ui-monospace,Menlo,monospace;font-weight:700;color:#fff;border-left:1px solid rgba(139,92,246,.34);padding-left:6px;}
+.tws-w-pop{margin-bottom:7px;width:248px;max-width:60vw;background:rgba(16,16,20,.97);border:1px solid rgba(139,92,246,.5);
+ border-radius:13px;padding:12px;box-shadow:0 18px 46px rgba(0,0,0,.55);backdrop-filter:blur(12px);color:#e8e8ea;
+ font-size:12px;line-height:1.45;}
+.tws-w-pop[hidden]{display:none;}
+.tws-w-head{display:flex;align-items:center;gap:8px;margin-bottom:10px;}
+.tws-w-av{width:28px;height:28px;border-radius:7px;object-fit:cover;background:rgba(255,255,255,.08);flex:none;}
+.tws-w-name{font-weight:700;color:#fff;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
+.tws-w-sub{font-size:10px;color:#9a9aa2;}
+.tws-w-total{display:flex;align-items:flex-end;justify-content:space-between;gap:8px;margin-bottom:9px;}
+.tws-w-usd{font:800 21px/1 "Space Grotesk",ui-sans-serif,system-ui;color:#fff;}
+.tws-w-usdl{font-size:9px;color:#9a9aa2;text-transform:uppercase;letter-spacing:.05em;margin-bottom:3px;}
+.tws-w-tips{text-align:right;font-size:10px;color:#9a9aa2;}
+.tws-w-tips b{display:block;color:#c4b5fd;font:700 13px/1 ui-monospace,Menlo,monospace;}
+.tws-w-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:9px;}
+.tws-w-mono{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#9a9aa2;}
+.tws-w-cp{appearance:none;background:none;border:none;padding:2px;cursor:pointer;color:#c4b5fd;opacity:.75;display:inline-flex;}
+.tws-w-cp:hover{opacity:1;}
+.tws-w-cp svg{width:13px;height:13px;}
+.tws-w-acts{display:flex;gap:6px;}
+.tws-w-btn{flex:1 1 auto;appearance:none;cursor:pointer;text-decoration:none;text-align:center;font:700 11px/1 inherit;
+ border-radius:999px;padding:8px 10px;border:1px solid rgba(139,92,246,.5);background:rgba(139,92,246,.12);color:#c4b5fd;
+ display:inline-flex;align-items:center;justify-content:center;gap:5px;transition:background .15s,color .15s;}
+.tws-w-btn:hover{background:rgba(139,92,246,.22);color:#fff;}
+.tws-w-btn-primary{background:linear-gradient(135deg,#c4b5fd,#a78bfa);color:#0a0a0a;border-color:transparent;}
+.tws-w-pending{display:inline-flex;align-items:center;gap:6px;padding:4px 9px;border-radius:999px;font:600 11px/1 inherit;
+ color:#9a9aa2;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);backdrop-filter:blur(8px);}
+@media (prefers-reduced-motion: reduce){.tws-w-chip,.tws-w-btn{transition:none;}}
+`;
+
+const WALLET_SVG =
+ '<svg class="tws-w-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>';
+
+/**
+ * Mount a self-contained wallet affordance into a host (Element or ShadowRoot).
+ *
+ * @param {Element|ShadowRoot} host
+ * @param {object} opts
+ * @param {string} opts.agentId Agent UUID.
+ * @param {string} [opts.apiBase] three.ws origin (default https://three.ws).
+ * @param {'mainnet'|'devnet'} [opts.network]
+ * @returns {{ destroy: () => void }}
+ */
+export function mountSdkWallet(host, opts = {}) {
+ const { agentId, apiBase = ORIGIN_DEFAULT, network = 'mainnet' } = opts;
+ const origin = String(apiBase || ORIGIN_DEFAULT).replace(/\/$/, '');
+
+ const style = document.createElement('style');
+ style.textContent = STYLE;
+ const root = document.createElement('div');
+ root.className = 'tws-w';
+ host.appendChild(style);
+ host.appendChild(root);
+
+ let card = null;
+ let open = false;
+ let destroyed = false;
+
+ if (!agentId || !UUID_RE.test(String(agentId))) {
+ root.remove();
+ style.remove();
+ return { destroy() {} };
+ }
+
+ function render() {
+ if (destroyed) return;
+ if (!card) {
+ root.innerHTML = `<span class="tws-w-pending">${WALLET_SVG}<span>Wallet…</span></span>`;
+ return;
+ }
+ if (!card.address || !BASE58_RE.test(String(card.address))) {
+ root.innerHTML =
+ `<a class="tws-w-pending" href="${esc(card.openUrl || origin)}" target="_blank" rel="noopener" style="text-decoration:none">${WALLET_SVG}<span>Wallet pending</span></a>`;
+ return;
+ }
+ const usd = fmtUsd(card.balanceUsd);
+ const tips = card.tips?.count || 0;
+ const tipsUsd = fmtUsd(card.tips?.usd);
+ const pay = solanaPayUri(card.address, { label: card.name || 'three.ws agent' });
+ root.innerHTML =
+ `<div class="tws-w-pop" role="dialog" aria-label="${esc(card.name || 'Agent')} wallet" ${open ? '' : 'hidden'}>` +
+ `<div class="tws-w-head">` +
+ (card.avatar ? `<img class="tws-w-av" src="${esc(card.avatar)}" alt="" loading="lazy">` : `<span class="tws-w-av"></span>`) +
+ `<div style="min-width:0"><div class="tws-w-name">${esc(card.name || 'Agent')}</div><div class="tws-w-sub">Agent wallet · Solana</div></div></div>` +
+ `<div class="tws-w-total"><div><div class="tws-w-usdl">Wallet value</div><div class="tws-w-usd">${esc(usd || '$0')}</div></div>` +
+ (tips > 0 ? `<div class="tws-w-tips"><b>${tips}</b>tip${tips === 1 ? '' : 's'}${tipsUsd ? ` · ${esc(tipsUsd)}` : ''}</div>` : '') +
+ `</div>` +
+ `<div class="tws-w-addrline"><span class="tws-w-mono">${esc(card.address)}</span>` +
+ `<button type="button" class="tws-w-cp" data-copy title="Copy address" aria-label="Copy wallet address">${COPY_SVG}</button></div>` +
+ `<div class="tws-w-acts">` +
+ `<a class="tws-w-btn tws-w-btn-primary" href="${esc(pay)}">◎ Tip</a>` +
+ `<a class="tws-w-btn" href="${esc(card.walletUrl || card.openUrl)}" target="_blank" rel="noopener">Open ↗</a>` +
+ `</div></div>` +
+ `<button type="button" class="tws-w-chip" data-toggle aria-haspopup="dialog" aria-expanded="${open ? 'true' : 'false'}">` +
+ WALLET_SVG +
+ `<span class="tws-w-addr">${shortAddr(card.address, card.vanity)}</span>` +
+ (usd != null ? `<span class="tws-w-val">${esc(usd)}</span>` : '') +
+ `</button>`;
+ wire();
+ }
+
+ function wire() {
+ const toggle = root.querySelector('[data-toggle]');
+ const pop = root.querySelector('.tws-w-pop');
+ toggle?.addEventListener('click', () => {
+ open = !open;
+ toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
+ if (pop) pop.hidden = !open;
+ });
+ root.querySelector('[data-copy]')?.addEventListener('click', async (e) => {
+ const btn = e.currentTarget;
+ try {
+ await navigator.clipboard.writeText(card.address);
+ btn.style.color = '#4ade80';
+ setTimeout(() => { btn.style.color = ''; }, 1200);
+ } catch { /* clipboard denied — address is still visible */ }
+ });
+ }
+
+ render();
+ fetch(`${origin}/api/agents/wallet-embed?id=${encodeURIComponent(agentId)}&network=${encodeURIComponent(network)}`, {
+ headers: { accept: 'application/json' },
+ })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => {
+ if (destroyed) return;
+ card = j?.data || { agentId, address: null, openUrl: `${origin}/agent/${agentId}` };
+ render();
+ })
+ .catch(() => {
+ if (destroyed) return;
+ card = { agentId, address: null, openUrl: `${origin}/agent/${agentId}` };
+ render();
+ });
+
+ return {
+ destroy() {
+ destroyed = true;
+ root.remove();
+ style.remove();
+ },
+ };
+}
diff --git a/chat/src/AgentWallet.svelte b/chat/src/AgentWallet.svelte
new file mode 100644
index 000000000..f2fd61d20
--- /dev/null
+++ b/chat/src/AgentWallet.svelte
@@ -0,0 +1,52 @@
+<script>
+ // The wallet identity of the agent you're chatting with — tip it for a good
+ // answer, copy its address, or open its full wallet on three.ws. Thin Svelte
+ // wrapper over the shared portable wallet (one module, mounted everywhere the
+ // avatar appears) so the chat never forks the wallet logic. Reads only public
+ // data from the CORS:* wallet-embed endpoint; it is the visitor view by
+ // construction (no owner controls in chat).
+ import { onMount, onDestroy } from 'svelte';
+ import { mountPortableWallet } from '$shared/portable-wallet.js';
+
+ export let agentId = '';
+ /** 'chip' toggles a popover; 'card' renders the wallet open inline. */
+ export let variant = 'chip';
+
+ let host;
+ let mount = null;
+ let mountedId = null;
+
+ function remount(id) {
+ if (mount) {
+ try { mount.destroy(); } catch { /* already gone */ }
+ mount = null;
+ }
+ mountedId = null;
+ if (!host || !id) return;
+ mount = mountPortableWallet(host, {
+ agentId: id,
+ variant,
+ tip: true,
+ qr: true,
+ share: true,
+ theme: 'light',
+ });
+ mountedId = id;
+ }
+
+ onMount(() => remount(agentId));
+ onDestroy(() => { try { mount?.destroy(); } catch { /* gone */ } });
+
+ // Re-mount when the active agent changes.
+ $: if (host && agentId !== mountedId) remount(agentId);
+</script>
+
+<span class="agent-wallet" bind:this={host}></span>
+
+<style>
+ .agent-wallet {
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ }
+</style>
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index c40659f48..25f29846d 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -38,6 +38,7 @@
import Toolcall from './Toolcall.svelte';
import Modal from './Modal.svelte';
import Composer from './three-ui/Composer.svelte';
+ import AgentWallet from './AgentWallet.svelte';
import Icon from './Icon.svelte';
import {
feArrowUp,
@@ -2739,6 +2740,10 @@
{agentVisible ? 'Hide avatar' : 'Show avatar'}
</button>
{/if}
+ {#if effectiveAgentId}
+ <!-- The agent's wallet identity — tip it for a good answer. -->
+ <AgentWallet agentId={effectiveAgentId} />
+ {/if}
</div>
{/if}
<Composer
diff --git a/chat/vite.config.js b/chat/vite.config.js
index 5eb0652a4..f9c07ad7a 100644
--- a/chat/vite.config.js
+++ b/chat/vite.config.js
@@ -55,6 +55,11 @@ export default defineConfig(function () {
emptyOutDir: true,
},
server: {
+ fs: {
+ // The chat app reuses shared wallet modules that live in the main
+ // repo's src/ (one repo, one wallet truth) — allow Vite to serve them.
+ allow: [path.resolve(__dirname, '..')],
+ },
proxy: {
// Vercel serverless functions live under /api/* in production but
// Vite's dev server doesn't run them. Forward /api/* to a real
@@ -76,6 +81,9 @@ export default defineConfig(function () {
dedupe: ['three'],
alias: {
'$src': path.resolve(__dirname, './src'),
+ // Shared wallet layer lives in the main app's src/shared (single source
+ // of truth for the agent wallet everywhere its avatar appears).
+ '$shared': path.resolve(__dirname, '../src/shared'),
}
},
define: {
diff --git a/data/changelog.json b/data/changelog.json
index 2a88c3540..936f39eeb 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,32 @@
{
"$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": "IRL: pinned agents now hold their exact spot indoors instead of drifting",
+ "summary": "When you pin your agent to a real-world spot in IRL — on a table, a desk, a shelf — it now stays put as you pan and move your phone, instead of sliding away. Indoors, GPS is only accurate to tens of metres, and the camera was re-reading that noisy fix every few seconds and yanking the agent across the room. Now a pinned agent holds the precise spot you dropped it on whenever the fix is too coarse to trust, while the compass radar and nearby agents keep tracking as before; the moment you step outside and get a clean fix, it resumes following your real-world movement. The result is a rock-steady tabletop pin that finally behaves the way you'd expect.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/irl"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Copy-trading page now shows each of your agents' wallet identity",
+ "summary": "On the Copy Trading page, every one of your agents listed under \"your copy-trading\" now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/mirror"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Your agent's wallet now follows it everywhere — the chat, the 3D world, and any site",
+ "summary": "An agent's wallet is its identity, so it now shows up wherever its avatar does, not just inside the app. In the chat, the agent you're talking to carries a wallet chip — open it to see its live value and lifetime tips, copy its address, or tip it for a good answer. In the walk-around 3D world, stroll up to another player who's piloting an agent and its wallet rises beside their nameplate: vanity address, real balance, and a one-tap tip, right there in the scene. And the lightweight avatar viewer in our SDK can now opt into the same wallet card, so an agent embedded on any third-party site keeps its real, tippable identity. Every number is real and read from the same public wallet data as the rest of the platform, so values never disagree across surfaces; it's always the visitor view, so owner-only controls never leak into an embed. It's deliberately frugal in the live 3D world — only the nearest agent's wallet loads, and only once — so nothing stutters.",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"title": "Talk to your avatar — a new free speech-to-text lane closes the voice loop",
diff --git a/pages/mirror.html b/pages/mirror.html
index 36ad0e0d3..b1a820b71 100644
--- a/pages/mirror.html
+++ b/pages/mirror.html
@@ -67,7 +67,9 @@
.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 { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.mp-agent-head .mp-lname a { font-size: var(--text-md, .95rem); }
+ .mp-agent-chip { display: flex; }
.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); }
diff --git a/public/changelog.json b/public/changelog.json
index 38664e099..0e3813d3c 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T05:06:30.997Z",
+ "generated_at": "2026-06-23T05:17:28.201Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -37,6 +37,16 @@
"security"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Copy-trading page now shows each of your agents' wallet identity",
+ "summary": "On the Copy Trading page, every one of your agents listed under \"your copy-trading\" now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears.",
+ "link": "/mirror",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -190,6 +200,16 @@
"infra"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "IRL: pinned agents now hold their exact spot indoors instead of drifting",
+ "summary": "When you pin your agent to a real-world spot in IRL — on a table, a desk, a shelf — it now stays put as you pan and move your phone, instead of sliding away. Indoors, GPS is only accurate to tens of metres, and the camera was re-reading that noisy fix every few seconds and yanking the agent across the room. Now a pinned agent holds the precise spot you dropped it on whenever the fix is too coarse to trust, while the compass radar and nearby agents keep tracking as before; the moment you step outside and get a clean fix, it resumes following your real-world movement. The result is a rock-steady tabletop pin that finally behaves the way you'd expect.",
+ "link": "/irl",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -421,6 +441,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Your agent's wallet now follows it everywhere — the chat, the 3D world, and any site",
+ "summary": "An agent's wallet is its identity, so it now shows up wherever its avatar does, not just inside the app. In the chat, the agent you're talking to carries a wallet chip — open it to see its live value and lifetime tips, copy its address, or tip it for a good answer. In the walk-around 3D world, stroll up to another player who's piloting an agent and its wallet rises beside their nameplate: vanity address, real balance, and a one-tap tip, right there in the scene. And the lightweight avatar viewer in our SDK can now opt into the same wallet card, so an agent embedded on any third-party site keeps its real, tippable identity. Every number is real and read from the same public wallet data as the rest of the platform, so values never disagree across surfaces; it's always the visitor view, so owner-only controls never leak into an embed. It's deliberately frugal in the live 3D world — only the nearest agent's wallet loads, and only once — so nothing stutters.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index fe5b75e5e..4ea8d5020 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -30,6 +30,14 @@
<category>fix</category>
<description>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.</description>
</item>
+ <item>
+ <title>Copy-trading page now shows each of your agents' wallet identity</title>
+ <link>https://three.ws/mirror</link>
+ <guid isPermaLink="false">2026-06-23:Copy-trading page now shows each of your agents' wallet identity</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>On the Copy Trading page, every one of your agents listed under &quot;your copy-trading&quot; now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears.</description>
+ </item>
<item>
<title>Embedded widgets never hang on a blank frame</title>
<link>https://three.ws/changelog</link>
@@ -150,6 +158,14 @@
<category>improvement</category>
<description>When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose.</description>
</item>
+ <item>
+ <title>IRL: pinned agents now hold their exact spot indoors instead of drifting</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-23:IRL: pinned agents now hold their exact spot indoors instead of drifting</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>When you pin your agent to a real-world spot in IRL — on a table, a desk, a shelf — it now stays put as you pan and move your phone, instead of sliding away. Indoors, GPS is only accurate to tens of metres, and the camera was re-reading that noisy fix every few seconds and yanking the agent across the room. Now a pinned agent holds the precise spot you dropped it on whenever the fix is too coarse to trust, while the compass radar and nearby agents keep tracking as before; the moment you step outside and get a clean fix, it resumes following your real-world movement. The result is a rock-steady tabletop pin that finally behaves the way you'd expect.</description>
+ </item>
<item>
<title>Mirror a proven agent and yours trades alongside it — Copy Trading, fully custodial</title>
<link>https://three.ws/mirror</link>
@@ -326,6 +342,14 @@
<category>feature</category>
<description>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.</description>
</item>
+ <item>
+ <title>Your agent's wallet now follows it everywhere — the chat, the 3D world, and any site</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Your agent's wallet now follows it everywhere — the chat, the 3D world, and any site</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>An agent's wallet is its identity, so it now shows up wherever its avatar does, not just inside the app. In the chat, the agent you're talking to carries a wallet chip — open it to see its live value and lifetime tips, copy its address, or tip it for a good answer. In the walk-around 3D world, stroll up to another player who's piloting an agent and its wallet rises beside their nameplate: vanity address, real balance, and a one-tap tip, right there in the scene. And the lightweight avatar viewer in our SDK can now opt into the same wallet card, so an agent embedded on any third-party site keeps its real, tippable identity. Every number is real and read from the same public wallet data as the rest of the platform, so values never disagree across surfaces; it's always the visitor view, so owner-only controls never leak into an embed. It's deliberately frugal in the live 3D world — only the nearest agent's wallet loads, and only once — so nothing stutters.</description>
+ </item>
<item>
<title>Your avatar has a job — the Earn home in every agent wallet</title>
<link>https://three.ws/economy</link>
diff --git a/public/features.json b/public/features.json
index 225f1343b..9f7dbf6cd 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T05:06:30.818Z",
+ "generated_at": "2026-06-23T05:17:27.947Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-wallet-hub/tabs/trade.js b/src/agent-wallet-hub/tabs/trade.js
index bba7a806f..b8f04d56e 100644
--- a/src/agent-wallet-hub/tabs/trade.js
+++ b/src/agent-wallet-hub/tabs/trade.js
@@ -454,7 +454,7 @@ registerWalletTab({
return `<div class="awh-card">
<div class="awh-tr-banner awh-tr-banner--info" role="note">
<span aria-hidden="true">👁️</span>
- <span>You’re viewing <strong>${esc(ctx.agent.name || 'this agent')}</strong>’s wallet. Holdings and trade history are public; only the owner can trade from it.</span>
+ <span>You’re viewing <strong>${esc(ctx.agent.name || 'this agent')}</strong>’s wallet. Its holdings are public; only the owner can trade from it or see its trade history.</span>
</div>
</div>`;
}
diff --git a/src/irl.js b/src/irl.js
index 31698d6ca..5c73ef1dc 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -1475,6 +1475,17 @@ let _gpsCamTransition = null;
// schedules this backoff re-arm, letting an idle session self-heal without a reload.
let _gpsRetryTimer = null;
const GPS_RETRY_MS = 4000;
+// Below this horizontal accuracy a GPS fix is trusted to *move* the own pinned
+// avatar — reprojecting it from its coordinates so walking translates the world.
+// Above it the fix is too coarse for close-range placement: an indoor fix (typically
+// 20–60 m) would swim the avatar metres off the spot it was dropped on every ~10 s
+// poll. A coarse fix leaves the avatar planted (its placed position is already the
+// pin's round-trip, so it's correct in the viewer frame) while the camera, radar, and
+// nearby agents keep tracking; a later sub-bar fix resumes moving the own avatar.
+// 10 m: indoor fixes report 15–60 m (often optimistically low), so they stay planted;
+// a clear-sky outdoor fix (3–10 m) is trusted to track. ORIGIN_REJECT_M (35) already
+// drops the very worst fixes from the origin blend; this is the tighter own-avatar bar.
+const GPS_RENDER_MAX_ACC_M = 10;
function gpsToWorld(agentLat, agentLng) {
if (!gpsState.ready) return new Vector3(0, 0, 0);
@@ -1900,10 +1911,16 @@ function onGPSPosition(pos) {
// by here, so the gate drains its held pose exactly once (a no-op otherwise).
floorPersist.onFix(gpsState.ready);
- // Move pinned avatar to its GPS-anchored world position. anchor_height_m (A2)
- // keeps the feet on the ground plane on slopes / indoors — 0 today, but read
- // it back so future floor-corrected placements render at the right height.
- if (gpsPin) {
+ // Move the pinned avatar to its GPS-anchored world position — but ONLY when the fix
+ // is accurate enough to be an improvement. Reprojecting the own avatar from a noisy
+ // fix is exactly what swims it off the spot it was dropped: indoors the accuracy is
+ // tens of metres, so each ~10 s fix would yank it across the room. A coarse fix
+ // leaves the avatar planted at its placed position (which is the pin's round-trip,
+ // so it's already correct in the viewer frame); a fix that lands under the accuracy
+ // bar — typically once the user steps outside — resumes tracking and snaps it to its
+ // true world spot. anchor_height_m (A2) keeps the feet on the ground plane — 0 today,
+ // but read it back so future floor-corrected placements render at the right height.
+ if (gpsPin && gpsFixRendersOwnAvatar()) {
const wp = gpsToWorld(gpsPin.lat, gpsPin.lng);
avatarRig.position.set(wp.x, gpsPin.heightM ?? 0, wp.z);
}
@@ -1943,6 +1960,26 @@ function onGPSPosition(pos) {
irlNet?.moveTo(gpsState.lat, gpsState.lng);
}
+// True when the live fix is accurate enough to move the own avatar to its GPS spot.
+// A coarse (indoor) fix leaves the avatar planted where it was dropped instead of
+// swimming it across the room with GPS noise. See GPS_RENDER_MAX_ACC_M.
+function gpsFixRendersOwnAvatar() {
+ return Number.isFinite(gpsState.accuracy) && gpsState.accuracy <= GPS_RENDER_MAX_ACC_M;
+}
+
+// Hand the own pinned avatar from the local gyro lock to the viewer-centric GPS
+// frame: camera at the origin, avatar reprojected from its coordinates each fix.
+// Eases the camera from the gyro pivot to the origin (the avatar holds its world
+// spot) so the upgrade reads as a glide, not a teleport. Idempotent.
+function enterGpsRenderMode() {
+ if (gpsModeActive) return;
+ if (gyroLockCamPos && !prefersReducedMotion()) {
+ _gpsCamTransition = { from: gyroLockCamPos.clone(), elapsed: 0 };
+ }
+ gpsModeActive = true;
+ document.body.classList.add('gps-mode');
+}
+
// Build the GPS world-anchor for the freshly locked own avatar and open the
// caption panel to persist its A2 pose. Requires a live GPS fix — setLocked()
// calls this directly when one is ready, or defers it here via _pendingGpsLock
@@ -1961,16 +1998,21 @@ function anchorGpsPin() {
const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));
const pinLat = gpsState.lat + (-avatarRig.position.z / mLat);
const pinLng = gpsState.lng + ( avatarRig.position.x / mLng);
+ // Close-range placement (a spot on a table, a chair) needs sub-metre anchoring,
+ // which GPS never delivers. Only hand rendering to the viewer-centric GPS frame
+ // when the fix is accurate enough not to make things worse — outdoors with a
+ // clear sky. Indoors the fix is far too coarse (tens of metres), so keep the
+ // rock-solid local gyro lock that holds the avatar exactly where it was dropped;
+ // the pin still persists below for nearby discovery, and onGPSPosition() upgrades
+ // to the GPS frame the moment a fix lands under GPS_RENDER_MAX_ACC_M.
// Local→GPS upgrade: glide the camera from the gyro pivot to the viewer origin
- // instead of snapping. The avatar holds its world spot (the pin is derived so
- // gpsToWorld() returns its current position), so easing the only thing that
- // moves — the camera — keeps the avatar from visibly teleporting in the room.
- // Reduced-motion jumps straight to the anchored frame.
- if (!gpsModeActive && gyroLockCamPos && !prefersReducedMotion()) {
- _gpsCamTransition = { from: gyroLockCamPos.clone(), elapsed: 0 };
- }
- gpsModeActive = true;
- document.body.classList.add('gps-mode');
+ // instead of snapping. The avatar holds its world spot (its placed position is the
+ // pin's round-trip), so easing the only thing that moves — the camera — keeps it
+ // from visibly teleporting in the room. This always enters the GPS frame so the
+ // radar and nearby agents stay live; whether each later fix is allowed to *move*
+ // the own avatar is gated separately on accuracy (onGPSPosition) so a coarse indoor
+ // fix can't swim it off the spot it was dropped.
+ enterGpsRenderMode();
// On iOS the live compass is the authoritative bearing — re-derive cameraYaw from
// the freshest reading so the stored heading is north-anchored even when this runs
// between orientation events (notably the deferred first-GPS-fix path).
diff --git a/src/mirror.js b/src/mirror.js
index 55dfe508a..f70ed97af 100644
--- a/src/mirror.js
+++ b/src/mirror.js
@@ -10,6 +10,7 @@
import { apiFetch } from './api.js';
import { mountMirrorPanel, openFollowModal } from './shared/agent-mirror-panel.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.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 || '');
@@ -127,11 +128,16 @@ async function loadMine() {
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>`;
+ // Owner's own wallet-bearing agent → its identity chip (same shared component
+ // every other surface uses) so the wallet reads identically here and links to
+ // the HUD; these cards are already filtered to agents that have a wallet.
+ const chip = walletChipHTML(a, { isOwner: true, showPending: false, link: true, tip: false });
+ 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>${chip ? `<div class="mp-agent-chip">${chip}</div>` : ''}</div>`;
const panelMount = document.createElement('div');
card.appendChild(head);
card.appendChild(panelMount);
mineEl.appendChild(card);
+ if (chip) wireWalletChips(head);
// 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 });
diff --git a/src/shared/portable-wallet.js b/src/shared/portable-wallet.js
index 8ac43edce..fb023ee56 100644
--- a/src/shared/portable-wallet.js
+++ b/src/shared/portable-wallet.js
@@ -81,6 +81,15 @@ const STYLE = `
--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;}
+/* Light surfaces (e.g. the chat app) — darken the chip ink for contrast while the
+ floating popover stays a dark glass card (its vars are re-set below). */
+.pw-root[data-theme="light"]{--pw-accent:#7c3aed;--pw-accent-strong:#6d28d9;--pw-soft:rgba(124,58,237,.08);
+ --pw-fill:rgba(124,58,237,.14);--pw-stroke:rgba(124,58,237,.28);--pw-stroke-2:rgba(124,58,237,.5);
+ --pw-glow:rgba(124,58,237,.4);--pw-ink:#1e1b2e;--pw-ink-dim:#6b6780;--pw-ink-bright:#0a0a0a;}
+.pw-root[data-theme="light"] .pw-pop{--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-ink:#e8e8ea;--pw-ink-dim:#9a9aa2;--pw-ink-bright:#fff;}
.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;}
@@ -214,6 +223,7 @@ const TIP_PRESETS = {
* @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).
+ * @param {'dark'|'light'} [opts.theme='dark'] 'light' darkens the chip ink for light surfaces.
* @returns {{ el: HTMLElement, refresh: () => void, destroy: () => void }}
*/
export function mountPortableWallet(host, opts = {}) {
@@ -228,11 +238,13 @@ export function mountPortableWallet(host, opts = {}) {
name: seedName = null,
avatar: seedAvatar = null,
seedCard = null,
+ theme = 'dark',
} = opts;
ensureStyles(host);
const root = document.createElement('div');
root.className = 'pw-root';
+ if (theme === 'light') root.setAttribute('data-theme', 'light');
host.appendChild(root);
let card = seedCard || null;
diff --git a/src/shared/strategy-forms.js b/src/shared/strategy-forms.js
new file mode 100644
index 000000000..8b8830224
--- /dev/null
+++ b/src/shared/strategy-forms.js
@@ -0,0 +1,351 @@
+// Shared Strategy Object UI primitives — the config editor, the equip picker, the
+// human-readable rule summary, plus the styles every strategy surface uses. Reused
+// by the /strategies library page and the agent-detail equip panel so the editor
+// and the design stay in one place.
+//
+// 100% real: the editor POSTs/PATCHes to /api/strategies (server-validated against
+// the same schema the runtime uses); the equip picker POSTs to
+// /api/agents/:id/strategies. No mock state, no fake preview numbers.
+
+import { apiFetch } from '../api.js';
+
+export const VIOLET = 'var(--wallet-accent, #c4b5fd)';
+
+export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+export const shortAddr = (a, h = 4, t = 4) => (a && a.length > h + t + 1 ? `${a.slice(0, h)}…${a.slice(-t)}` : a || '');
+export 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+$/, '')}`;
+}
+export function timeAgo(t) {
+ if (!t) return '';
+ const d = (Date.now() - new Date(t).getTime()) / 1000;
+ if (d < 0) return 'just now';
+ 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`;
+}
+
+// ── toast ──────────────────────────────────────────────────────────────────────
+let _toastEl = null;
+let _toastTimer = null;
+export function toast(msg, ms = 2800) {
+ if (typeof document === 'undefined') return;
+ if (!_toastEl) {
+ _toastEl = document.createElement('div');
+ _toastEl.className = 'so-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);
+}
+
+// ── rule summary — a one-line, honest plain-language read of a config ──────────
+export function configSummary(config) {
+ const c = config || {};
+ const e = c.entry || {}, s = c.sizing || {}, x = c.exits || {}, k = c.risk || {};
+ const parts = [];
+ if (e.max_age_minutes != null) parts.push(`launches &lt;${e.max_age_minutes}m old`);
+ if (e.min_liquidity_sol != null) parts.push(`liq ≥◎${fmtSol(e.min_liquidity_sol)}`);
+ if (e.min_market_cap_usd != null || e.max_market_cap_usd != null) {
+ const lo = e.min_market_cap_usd != null ? `$${fmtUsdShort(e.min_market_cap_usd)}` : '';
+ const hi = e.max_market_cap_usd != null ? `$${fmtUsdShort(e.max_market_cap_usd)}` : '';
+ parts.push(`MC ${lo}${lo && hi ? '–' : ''}${hi}`);
+ }
+ if (e.require_socials) parts.push('has socials');
+ parts.push(`size ◎${fmtSol(s.amount_sol)}`);
+ if (x.take_profit_pct != null) parts.push(`TP +${x.take_profit_pct}%`);
+ if (x.stop_loss_pct != null) parts.push(`SL −${x.stop_loss_pct}%`);
+ if (x.trailing_stop_pct != null) parts.push(`trail ${x.trailing_stop_pct}%`);
+ if (x.max_hold_minutes != null) parts.push(`≤${formatMinutes(x.max_hold_minutes)}`);
+ if (k.max_concurrent_positions != null) parts.push(`max ${k.max_concurrent_positions} open`);
+ return parts.join(' · ');
+}
+function fmtUsdShort(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return '—';
+ if (n >= 1e9) return `${(n / 1e9).toFixed(1)}B`;
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
+ if (n >= 1e3) return `${(n / 1e3).toFixed(0)}K`;
+ return `${n}`;
+}
+function formatMinutes(m) {
+ const n = Number(m);
+ if (!Number.isFinite(n)) return '—';
+ if (n >= 1440) return `${Math.round(n / 1440)}d`;
+ if (n >= 60) return `${Math.round(n / 60)}h`;
+ return `${n}m`;
+}
+
+// ── styles (injected once) ─────────────────────────────────────────────────────
+const STYLE_ID = 'so-shared-styles';
+export function ensureStrategyStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const s = document.createElement('style');
+ s.id = STYLE_ID;
+ s.textContent = `
+.so-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)); }
+.so-toast[data-show="true"] { opacity: 1; transform: translateX(-50%) translateY(0); }
+.so-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; }
+.so-modal { width: min(540px, 96vw); max-height: 92vh; 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)); }
+.so-modal h3 { margin: 0 0 4px; font-family: var(--font-display, inherit); font-size: var(--text-lg, 1.1rem); color: var(--ink-bright, #fff); }
+.so-modal .so-sub { font-size: var(--text-xs, .72rem); color: var(--ink-dim, #9a9a9a); margin: 0 0 var(--space-md, 16px); line-height: 1.5; }
+.so-group { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: var(--space-sm, 12px); margin-bottom: var(--space-sm, 12px); }
+.so-group > legend, .so-glabel { font-size: var(--text-2xs, .64rem); text-transform: uppercase; letter-spacing: .07em; color: ${VIOLET}; font-weight: 700; padding: 0 4px; margin-bottom: 8px; display: block; }
+.so-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+@media (max-width: 460px) { .so-grid { grid-template-columns: 1fr; } }
+.so-field { margin-bottom: 2px; }
+.so-field label { display: block; font-size: var(--text-2xs, .66rem); color: var(--ink-dim, #9a9a9a); margin-bottom: 5px; }
+.so-field input, .so-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); }
+.so-field input:focus, .so-field select:focus { outline: none; border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); }
+.so-field .so-hint { font-size: var(--text-2xs, .6rem); color: var(--ink-faint, #777); margin-top: 3px; }
+.so-checkrow { display: flex; align-items: center; gap: 8px; font-size: var(--text-sm, .8rem); color: var(--ink, #ddd); cursor: pointer; margin-top: 4px; }
+.so-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; }
+.so-preview b { color: ${VIOLET}; font-family: var(--font-mono, monospace); }
+.so-err { color: var(--danger, #f87171); font-size: var(--text-xs, .72rem); margin: 6px 0; }
+.so-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: var(--space-md, 16px); }
+.so-btn { font: inherit; font-size: var(--text-sm, .8rem); padding: 9px 16px; 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, .16s); white-space: nowrap; }
+.so-btn:hover { border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); color: #fff; }
+.so-btn:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+.so-btn-primary { background: ${VIOLET}; color: #1a1340; border-color: transparent; font-weight: 700; }
+.so-btn-primary:hover { background: var(--wallet-accent-strong, #a78bfa); color: #1a1340; }
+.so-btn-primary:disabled { opacity: .6; cursor: progress; }
+.so-pick { display: flex; align-items: center; gap: 10px; width: 100%; text-align: left; padding: 9px; 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)); color: var(--ink, #e8e8e8); cursor: pointer; margin-bottom: 6px; transition: border-color .16s; }
+.so-pick:hover { border-color: var(--wallet-stroke, rgba(139,92,246,.35)); }
+.so-pick img, .so-pick .so-av { width: 32px; height: 32px; border-radius: 50%; object-fit: cover; background: var(--surface-2, rgba(255,255,255,.06)); flex: 0 0 auto; }
+.so-pick .so-pname { font-size: var(--text-sm, .82rem); font-weight: 600; color: var(--ink-bright, #fff); }
+`;
+ document.head.appendChild(s);
+}
+
+const DEFAULTS = {
+ 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, stop_loss_pct: 40, trailing_stop_pct: null, max_hold_minutes: null },
+ risk: { max_concurrent_positions: 3, cooldown_minutes: 0 },
+};
+
+const numOrNull = (v) => { const s = String(v ?? '').trim(); if (s === '') return null; const n = Number(s); return Number.isFinite(n) ? n : null; };
+
+// ── the strategy editor ────────────────────────────────────────────────────────
+// existing: a strategy object to edit (PATCH); null → create (POST). Resolves the
+// saved strategy object, or null if cancelled.
+export function openStrategyEditor({ existing = null } = {}) {
+ ensureStrategyStyles();
+ const cfg = existing?.config ? structuredCloneSafe(existing.config) : structuredCloneSafe(DEFAULTS);
+ return new Promise((resolve) => {
+ const back = document.createElement('div');
+ back.className = 'so-modal-back';
+ const state = {
+ name: existing?.name || '',
+ description: existing?.description || '',
+ network: cfg.network || 'mainnet',
+ entry: { ...DEFAULTS.entry, ...(cfg.entry || {}) },
+ sizing: { ...DEFAULTS.sizing, ...(cfg.sizing || {}) },
+ exits: { ...DEFAULTS.exits, ...(cfg.exits || {}) },
+ risk: { ...DEFAULTS.risk, ...(cfg.risk || {}) },
+ };
+
+ function num(v) { return v == null ? '' : v; }
+ function previewText() {
+ const c = { entry: state.entry, sizing: state.sizing, exits: state.exits, risk: state.risk };
+ return configSummary(c) || 'Define your rules above.';
+ }
+ function render() {
+ back.innerHTML = `<div class="so-modal" role="dialog" aria-modal="true" aria-label="${existing ? 'Edit' : 'New'} strategy">
+ <h3>${existing ? 'Edit strategy' : 'New strategy'}</h3>
+ <p class="so-sub">A strategy is a real, rule-based plan. When equipped, your agent evaluates real launches and executes on-chain — always inside your spend policy.</p>
+
+ <div class="so-field"><label>Name</label><input id="so-name" maxlength="80" placeholder="e.g. Fresh-launch sniper" value="${esc(state.name)}"></div>
+ <div class="so-field"><label>Description <span style="color:var(--ink-faint,#777)">(optional)</span></label><input id="so-desc" maxlength="2000" placeholder="What edge does this capture?" value="${esc(state.description)}"></div>
+
+ <fieldset class="so-group"><legend>Entry — when to buy</legend>
+ <div class="so-grid">
+ <div class="so-field"><label>Max launch age (min)</label><input type="number" min="1" max="10080" id="so-age" value="${num(state.entry.max_age_minutes)}"><div class="so-hint">only act on launches newer than this</div></div>
+ <div class="so-field"><label>Min liquidity (◎ SOL)</label><input type="number" min="0" step="0.1" id="so-liq" value="${num(state.entry.min_liquidity_sol)}"></div>
+ <div class="so-field"><label>Min market cap (USD)</label><input type="number" min="0" id="so-mcmin" value="${num(state.entry.min_market_cap_usd)}"></div>
+ <div class="so-field"><label>Max market cap (USD)</label><input type="number" min="0" id="so-mcmax" value="${num(state.entry.max_market_cap_usd)}"></div>
+ <div class="so-field"><label>Max creator launches</label><input type="number" min="0" id="so-claunch" value="${num(state.entry.max_creator_launches)}"><div class="so-hint">skip serial deployers</div></div>
+ <div class="so-field"><label>Min creator graduations</label><input type="number" min="0" id="so-cgrad" value="${num(state.entry.min_creator_graduated)}"></div>
+ </div>
+ <label class="so-checkrow"><input type="checkbox" id="so-socials" ${state.entry.require_socials ? 'checked' : ''}> Require socials (X / Telegram / site)</label>
+ </fieldset>
+
+ <fieldset class="so-group"><legend>Sizing</legend>
+ <div class="so-grid">
+ <div class="so-field"><label>Per-trade size (◎ SOL)</label><input type="number" min="0.0001" step="0.01" id="so-size" value="${num(state.sizing.amount_sol)}"><div class="so-hint">still capped by your agent's spend policy</div></div>
+ <div class="so-field"><label>Max slippage (bps)</label><input type="number" min="0" max="10000" id="so-slip" value="${num(state.sizing.max_slippage_bps)}"><div class="so-hint">500 = 5%</div></div>
+ </div>
+ </fieldset>
+
+ <fieldset class="so-group"><legend>Exits — at least one upside exit + a stop-loss</legend>
+ <div class="so-grid">
+ <div class="so-field"><label>Take-profit (%)</label><input type="number" min="1" id="so-tp" value="${num(state.exits.take_profit_pct)}"><div class="so-hint">100 = sell at 2×</div></div>
+ <div class="so-field"><label>Stop-loss (%) — required</label><input type="number" min="1" max="99" id="so-sl" value="${num(state.exits.stop_loss_pct)}"></div>
+ <div class="so-field"><label>Trailing stop (%)</label><input type="number" min="1" max="99" id="so-trail" value="${num(state.exits.trailing_stop_pct)}"><div class="so-hint">% drop from peak</div></div>
+ <div class="so-field"><label>Max hold (min)</label><input type="number" min="1" id="so-hold" value="${num(state.exits.max_hold_minutes)}"></div>
+ </div>
+ </fieldset>
+
+ <fieldset class="so-group"><legend>Risk</legend>
+ <div class="so-grid">
+ <div class="so-field"><label>Max concurrent positions</label><input type="number" min="1" max="50" id="so-conc" value="${num(state.risk.max_concurrent_positions)}"></div>
+ <div class="so-field"><label>Cooldown between entries (min)</label><input type="number" min="0" id="so-cool" value="${num(state.risk.cooldown_minutes)}"></div>
+ <div class="so-field"><label>Network</label><select id="so-net"><option value="mainnet" ${state.network === 'mainnet' ? 'selected' : ''}>Mainnet</option><option value="devnet" ${state.network === 'devnet' ? 'selected' : ''}>Devnet</option></select></div>
+ </div>
+ </fieldset>
+
+ <div class="so-preview" id="so-preview">${previewText()}</div>
+ <div class="so-err" id="so-err" hidden></div>
+ <div class="so-actions">
+ <button type="button" class="so-btn" id="so-cancel">Cancel</button>
+ <button type="button" class="so-btn so-btn-primary" id="so-save">${existing ? 'Save changes' : 'Create strategy'}</button>
+ </div>
+ </div>`;
+ wire();
+ }
+ function readInputs() {
+ const q = (id) => back.querySelector(id);
+ state.name = q('#so-name')?.value || '';
+ state.description = q('#so-desc')?.value || '';
+ state.network = q('#so-net')?.value || 'mainnet';
+ state.entry.max_age_minutes = numOrNull(q('#so-age')?.value);
+ state.entry.min_liquidity_sol = numOrNull(q('#so-liq')?.value);
+ state.entry.min_market_cap_usd = numOrNull(q('#so-mcmin')?.value);
+ state.entry.max_market_cap_usd = numOrNull(q('#so-mcmax')?.value);
+ state.entry.max_creator_launches = numOrNull(q('#so-claunch')?.value);
+ state.entry.min_creator_graduated = numOrNull(q('#so-cgrad')?.value);
+ state.entry.require_socials = !!q('#so-socials')?.checked;
+ state.sizing.amount_sol = numOrNull(q('#so-size')?.value);
+ state.sizing.max_slippage_bps = numOrNull(q('#so-slip')?.value);
+ state.exits.take_profit_pct = numOrNull(q('#so-tp')?.value);
+ state.exits.stop_loss_pct = numOrNull(q('#so-sl')?.value);
+ state.exits.trailing_stop_pct = numOrNull(q('#so-trail')?.value);
+ state.exits.max_hold_minutes = numOrNull(q('#so-hold')?.value);
+ state.risk.max_concurrent_positions = numOrNull(q('#so-conc')?.value);
+ state.risk.cooldown_minutes = numOrNull(q('#so-cool')?.value);
+ }
+ function wire() {
+ back.querySelectorAll('input,select').forEach((el) => el.addEventListener('input', () => {
+ readInputs();
+ const p = back.querySelector('#so-preview'); if (p) p.innerHTML = previewText();
+ }));
+ back.querySelector('#so-cancel').addEventListener('click', () => close(null));
+ back.querySelector('#so-save').addEventListener('click', save);
+ }
+ function buildConfig() {
+ return {
+ network: state.network,
+ entry: { trigger: 'new_launch', ...state.entry },
+ sizing: state.sizing,
+ exits: state.exits,
+ risk: state.risk,
+ };
+ }
+ async function save() {
+ readInputs();
+ const errEl = back.querySelector('#so-err');
+ const btn = back.querySelector('#so-save');
+ if (!state.name.trim()) { showErr('Give your strategy a name.'); return; }
+ btn.disabled = true; btn.textContent = 'Saving…';
+ try {
+ const payload = { name: state.name.trim(), description: state.description.trim() || null, config: buildConfig() };
+ const res = await apiFetch(existing ? `/api/strategies/${existing.id}` : '/api/strategies', {
+ method: existing ? 'PATCH' : 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const fieldErrs = j?.error?.errors || j?.errors;
+ if (Array.isArray(fieldErrs) && fieldErrs.length) throw new Error(fieldErrs.map((e) => e.message).join(' '));
+ throw new Error(j?.error?.message || j?.message || 'Could not save');
+ }
+ toast(existing ? 'Strategy updated' : 'Strategy created');
+ close(j.data);
+ } catch (e) {
+ if (e?.redirected) return;
+ btn.disabled = false; btn.textContent = existing ? 'Save changes' : 'Create strategy';
+ showErr(e.message || 'Could not save');
+ }
+ function showErr(m) { if (errEl) { errEl.textContent = m; errEl.hidden = false; } }
+ }
+ function showErr(m) { const e = back.querySelector('#so-err'); if (e) { e.textContent = m; e.hidden = false; } }
+ function close(result) { document.removeEventListener('keydown', onKey); back.remove(); resolve(result); }
+ function onKey(e) { if (e.key === 'Escape') close(null); }
+ back.addEventListener('click', (e) => { if (e.target === back) close(null); });
+ document.addEventListener('keydown', onKey);
+ render();
+ document.body.appendChild(back);
+ back.querySelector('#so-name')?.focus();
+ });
+}
+
+function structuredCloneSafe(o) {
+ try { return structuredClone(o); } catch { return JSON.parse(JSON.stringify(o)); }
+}
+
+// ── equip picker — choose which of MY agents equips this strategy ──────────────
+// Resolves true if an equip was created.
+export async function openEquipPicker({ strategy }) {
+ ensureStrategyStyles();
+ 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);
+ }
+ } catch { /* handled below */ }
+ if (!mine.length) { toast('You need your own agent first — create or fork one'); return false; }
+
+ if (mine.length === 1) return equipOn(mine[0], strategy);
+
+ return new Promise((resolve) => {
+ const back = document.createElement('div');
+ back.className = 'so-modal-back';
+ back.innerHTML = `<div class="so-modal" role="dialog" aria-modal="true" aria-label="Pick an agent to equip">
+ <h3>Equip “${esc(strategy.name)}”</h3>
+ <p class="so-sub">Pick the agent that will run these rules. It trades on-chain within <b style="color:var(--ink-bright,#fff)">its own</b> spend policy — no wallet access is shared.</p>
+ <div>${mine.map((a) => `<button type="button" class="so-pick" data-id="${esc(a.id)}">${a.avatar_url || a.profile_image_url ? `<img src="${esc(a.avatar_url || a.profile_image_url)}" alt="">` : '<div class="so-av"></div>'}<span class="so-pname">${esc(a.name || shortAddr(a.id))}</span></button>`).join('')}</div>
+ <div class="so-actions"><button type="button" class="so-btn" id="so-pick-cancel">Cancel</button></div>
+ </div>`;
+ const close = (v) => { back.remove(); document.removeEventListener('keydown', onKey); resolve(v); };
+ const onKey = (e) => { if (e.key === 'Escape') close(false); };
+ back.addEventListener('click', (e) => { if (e.target === back) close(false); });
+ document.addEventListener('keydown', onKey);
+ back.querySelector('#so-pick-cancel').addEventListener('click', () => close(false));
+ back.querySelectorAll('[data-id]').forEach((b) => b.addEventListener('click', async () => {
+ const agent = mine.find((a) => a.id === b.dataset.id);
+ close(await equipOn(agent, strategy));
+ }));
+ document.body.appendChild(back);
+ });
+}
+
+async function equipOn(agent, strategy) {
+ try {
+ const res = await apiFetch(`/api/agents/${agent.id}/strategies`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy_id: strategy.id, network: strategy.config?.network || 'mainnet' }),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(j?.error?.message || 'Could not equip');
+ toast(`Equipped on ${agent.name || 'your agent'} — running within its limits`);
+ return true;
+ } catch (e) {
+ if (e?.redirected) return false;
+ toast(e.message || 'Could not equip');
+ return false;
+ }
+}
diff --git a/src/voice/mic-capture.js b/src/voice/mic-capture.js
new file mode 100644
index 000000000..379ba9cfd
--- /dev/null
+++ b/src/voice/mic-capture.js
@@ -0,0 +1,306 @@
+/**
+ * MicCapture — cross-browser microphone capture for the NVIDIA Riva ASR lane.
+ *
+ * The browser's MediaRecorder produces WebM/Opus, which Riva ASR rejects, so we
+ * capture raw PCM via the Web Audio graph instead and resample it to the 16 kHz
+ * mono LINEAR_PCM that /api/asr expects. This works in every browser — including
+ * Firefox, where window.SpeechRecognition does not exist — which is the whole
+ * reason the Riva lane exists.
+ *
+ * Capture path:
+ * getUserMedia ─▶ MediaStreamSource ─▶ AudioWorklet (or ScriptProcessor) ─▶ Float32 chunks
+ * └─▶ AnalyserNode (live RMS for the UI mic meter)
+ *
+ * The AudioContext runs at the device's native rate; we accumulate Float32
+ * samples and downsample to 16 kHz only when a WAV is built (final on release,
+ * or an interim snapshot mid-hold), so no per-sample resampling runs on the
+ * audio thread. AudioWorklet is preferred; ScriptProcessorNode is the fallback
+ * for Safari/older browsers where addModule isn't available.
+ *
+ * Usage:
+ * const mic = new MicCapture();
+ * await mic.start(); // throws 'permission-denied' | 'no-mic' | 'unsupported'
+ * mic.getLevel(); // 0..1 RMS, drive a live indicator
+ * const interim = mic.snapshotWav(); // Blob | null — audio so far, for a partial pass
+ * const final = await mic.stop(); // Blob | null — the full utterance as a 16 kHz WAV
+ * mic.dispose(); // idempotent teardown
+ */
+
+const TARGET_RATE = 16000;
+
+// Posts mono Float32 frames from the audio thread to the main thread. Kept tiny
+// and dependency-free so it survives being inlined as a Blob module URL.
+const WORKLET_SRC = /* js */ `
+class MicCaptureProcessor extends AudioWorkletProcessor {
+ process(inputs) {
+ const ch = inputs[0] && inputs[0][0];
+ if (ch && ch.length) this.port.postMessage(ch.slice(0));
+ return true;
+ }
+}
+registerProcessor('mic-capture', MicCaptureProcessor);
+`;
+
+export class MicCapture {
+ constructor() {
+ this._stream = null;
+ this._ctx = null;
+ this._source = null;
+ this._node = null; // AudioWorkletNode | ScriptProcessorNode
+ this._analyser = null;
+ this._chunks = [];
+ this._length = 0;
+ this._sourceRate = TARGET_RATE;
+ this._levelBuf = null;
+ this._started = false;
+ this._disposed = false;
+ }
+
+ get capturing() {
+ return this._started;
+ }
+
+ /** Whether the environment can capture at all (no mic UI on insecure origins). */
+ static isSupported() {
+ return (
+ typeof navigator !== 'undefined' &&
+ !!navigator.mediaDevices?.getUserMedia &&
+ !!(window.AudioContext || window.webkitAudioContext)
+ );
+ }
+
+ /**
+ * Acquire the mic and begin buffering. Rejects with an Error whose `.code` is
+ * one of: 'unsupported' | 'permission-denied' | 'no-mic' | 'capture-failed'
+ * so the caller can message each case precisely.
+ */
+ async start() {
+ if (this._started) return;
+ if (!MicCapture.isSupported()) throw codedError('Microphone capture is not supported in this browser.', 'unsupported');
+
+ let stream;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },
+ });
+ } catch (err) {
+ const name = err?.name || '';
+ if (name === 'NotAllowedError' || name === 'SecurityError') {
+ throw codedError('Microphone access was blocked. Allow the mic, or type your message instead.', 'permission-denied');
+ }
+ if (name === 'NotFoundError' || name === 'OverconstrainedError') {
+ throw codedError('No microphone was found. Plug one in, or type your message instead.', 'no-mic');
+ }
+ throw codedError(`Could not start the microphone: ${err?.message || name || 'unknown error'}`, 'capture-failed');
+ }
+ this._stream = stream;
+
+ const AC = window.AudioContext || window.webkitAudioContext;
+ const ctx = new AC();
+ this._ctx = ctx;
+ this._sourceRate = ctx.sampleRate || TARGET_RATE;
+ if (ctx.state === 'suspended') await ctx.resume().catch(() => {});
+
+ this._source = ctx.createMediaStreamSource(stream);
+
+ this._analyser = ctx.createAnalyser();
+ this._analyser.fftSize = 512;
+ this._levelBuf = new Uint8Array(this._analyser.fftSize);
+ this._source.connect(this._analyser);
+
+ const onFrame = (frame) => {
+ if (!this._started) return;
+ // Copy — the worklet transfers a view backed by a reused buffer.
+ const copy = frame instanceof Float32Array ? frame : new Float32Array(frame);
+ this._chunks.push(copy.slice ? copy.slice(0) : new Float32Array(copy));
+ this._length += copy.length;
+ };
+
+ let usedWorklet = false;
+ if (ctx.audioWorklet?.addModule) {
+ try {
+ const url = URL.createObjectURL(new Blob([WORKLET_SRC], { type: 'application/javascript' }));
+ await ctx.audioWorklet.addModule(url);
+ URL.revokeObjectURL(url);
+ const node = new AudioWorkletNode(ctx, 'mic-capture');
+ node.port.onmessage = (e) => onFrame(e.data);
+ this._source.connect(node);
+ // A muted sink keeps the worklet pulling frames without echoing the mic.
+ const sink = ctx.createGain();
+ sink.gain.value = 0;
+ node.connect(sink).connect(ctx.destination);
+ this._node = node;
+ usedWorklet = true;
+ } catch {
+ usedWorklet = false; // fall through to ScriptProcessor
+ }
+ }
+
+ if (!usedWorklet) {
+ const node = ctx.createScriptProcessor(4096, 1, 1);
+ node.onaudioprocess = (e) => onFrame(e.inputBuffer.getChannelData(0));
+ this._source.connect(node);
+ node.connect(ctx.destination); // ScriptProcessor needs a destination to fire
+ this._node = node;
+ }
+
+ this._started = true;
+ }
+
+ /** Live capture level, 0..1 RMS. Returns 0 before start / after stop. */
+ getLevel() {
+ if (!this._analyser || !this._levelBuf) return 0;
+ this._analyser.getByteTimeDomainData(this._levelBuf);
+ let sum = 0;
+ for (let i = 0; i < this._levelBuf.length; i++) {
+ const v = (this._levelBuf[i] - 128) / 128;
+ sum += v * v;
+ }
+ return Math.min(1, Math.sqrt(sum / this._levelBuf.length) * 1.8);
+ }
+
+ /** Seconds of audio buffered so far. */
+ get durationSec() {
+ return this._length / this._sourceRate;
+ }
+
+ /**
+ * A WAV of everything captured so far WITHOUT stopping — used to fire an
+ * interim recognition pass mid-hold so partial words can surface. Returns null
+ * until there is enough audio (≈0.4 s) to be worth a round-trip.
+ */
+ snapshotWav() {
+ if (this._length < this._sourceRate * 0.4) return null;
+ return this._buildWav();
+ }
+
+ /**
+ * Stop capture and return the full utterance as a 16 kHz mono WAV Blob, or
+ * null if nothing audible was captured. Releases the mic immediately; call
+ * dispose() to also close the audio context.
+ */
+ async stop() {
+ if (!this._started) return null;
+ this._started = false;
+ // Drop the live mic; the buffered samples are already ours.
+ for (const track of this._stream?.getTracks() || []) {
+ try {
+ track.stop();
+ } catch {}
+ }
+ const wav = this._length > 0 ? this._buildWav() : null;
+ return wav;
+ }
+
+ /** Idempotent teardown of every audio resource. */
+ dispose() {
+ if (this._disposed) return;
+ this._disposed = true;
+ this._started = false;
+ try {
+ if (this._node) {
+ this._node.onaudioprocess = null;
+ if (this._node.port) this._node.port.onmessage = null;
+ this._node.disconnect();
+ }
+ } catch {}
+ try {
+ this._source?.disconnect();
+ } catch {}
+ try {
+ this._analyser?.disconnect();
+ } catch {}
+ for (const track of this._stream?.getTracks() || []) {
+ try {
+ track.stop();
+ } catch {}
+ }
+ if (this._ctx && this._ctx.state !== 'closed') {
+ this._ctx.close().catch(() => {});
+ }
+ this._chunks = [];
+ this._length = 0;
+ this._node = null;
+ this._source = null;
+ this._analyser = null;
+ this._stream = null;
+ this._ctx = null;
+ }
+
+ // ── internal ──────────────────────────────────────────────────────────
+
+ _flatten() {
+ const out = new Float32Array(this._length);
+ let offset = 0;
+ for (const chunk of this._chunks) {
+ out.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return out;
+ }
+
+ // Native-rate Float32 → 16 kHz mono → little-endian s16 → RIFF/WAVE Blob.
+ _buildWav() {
+ const native = this._flatten();
+ const pcm16 = floatTo16kPcm(native, this._sourceRate);
+ return new Blob([pcm16Wav(pcm16, TARGET_RATE)], { type: 'audio/wav' });
+ }
+}
+
+function codedError(message, code) {
+ const err = new Error(message);
+ err.code = code;
+ return err;
+}
+
+// Linear-interpolating resample of mono Float32 from `inRate` to 16 kHz, then
+// quantize to little-endian s16. Linear interpolation is more than adequate for
+// speech recognition and avoids pulling in a filter library.
+function floatTo16kPcm(samples, inRate) {
+ if (!samples.length) return new Int16Array(0);
+ const ratio = inRate / TARGET_RATE;
+ const outLen = ratio <= 1 ? samples.length : Math.floor(samples.length / ratio);
+ const out = new Int16Array(outLen);
+ for (let i = 0; i < outLen; i++) {
+ const pos = i * ratio;
+ const idx = Math.floor(pos);
+ const frac = pos - idx;
+ const a = samples[idx] || 0;
+ const b = samples[idx + 1] !== undefined ? samples[idx + 1] : a;
+ const s = a + (b - a) * frac;
+ out[i] = Math.max(-32768, Math.min(32767, Math.round(s * 32767)));
+ }
+ return out;
+}
+
+// Wrap s16 PCM in a 44-byte RIFF/WAVE header. /api/asr strips this header back to
+// raw LINEAR_PCM server-side (api/_lib/asr-nvidia.js parseWav).
+function pcm16Wav(pcm16, sampleRate) {
+ const channels = 1;
+ const bytesPerSample = 2;
+ const blockAlign = channels * bytesPerSample;
+ const byteRate = sampleRate * blockAlign;
+ const dataBytes = pcm16.length * bytesPerSample;
+ const buffer = new ArrayBuffer(44 + dataBytes);
+ const view = new DataView(buffer);
+ writeAscii(view, 0, 'RIFF');
+ view.setUint32(4, 36 + dataBytes, true);
+ writeAscii(view, 8, 'WAVE');
+ writeAscii(view, 12, 'fmt ');
+ view.setUint32(16, 16, true); // PCM fmt chunk size
+ view.setUint16(20, 1, true); // audio format: PCM
+ view.setUint16(22, channels, true);
+ view.setUint32(24, sampleRate, true);
+ view.setUint32(28, byteRate, true);
+ view.setUint16(32, blockAlign, true);
+ view.setUint16(34, bytesPerSample * 8, true);
+ writeAscii(view, 36, 'data');
+ view.setUint32(40, dataBytes, true);
+ let offset = 44;
+ for (let i = 0; i < pcm16.length; i++, offset += 2) view.setInt16(offset, pcm16[i], true);
+ return buffer;
+}
+
+function writeAscii(view, offset, str) {
+ for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i));
+}
diff --git a/src/voice/talk-controller.js b/src/voice/talk-controller.js
index 8686ae9b0..293bc240d 100644
--- a/src/voice/talk-controller.js
+++ b/src/voice/talk-controller.js
@@ -26,8 +26,16 @@
*/
import { LipsyncDriver, tapAudioElement } from './lipsync-driver.js';
+import { MicCapture } from './mic-capture.js';
import { log } from '../shared/log.js';
+// Riva interim recognition cadence. While holding to talk we fire a recognition
+// pass over the audio-so-far on this interval so partial words surface live;
+// MAX_INTERIMS caps the round-trips per utterance so a long hold can't drain the
+// metered ASR budget. The release always runs one authoritative final pass.
+const INTERIM_INTERVAL_MS = 1400;
+const MAX_INTERIMS = 4;
+
const EDGE_VOICES_BY_GENDER = {
female: 'en-US-AriaNeural',
male: 'en-US-GuyNeural',
@@ -43,17 +51,19 @@ export class TalkController {
* @param {() => string} [opts.systemPromptFn] Optional system prompt builder
* @param {(msg: { role: 'user'|'assistant', content: string }) => void} [opts.onMessage]
* Hook so the host UI can append a transcript line.
- * @param {(state: 'idle'|'listening'|'thinking'|'speaking') => void} [opts.onStateChange]
+ * @param {(state: 'idle'|'listening'|'transcribing'|'thinking'|'speaking') => void} [opts.onStateChange]
+ * @param {(partial: string) => void} [opts.onInterim] Live (non-final) transcript while listening.
* @param {(err: Error) => void} [opts.onError]
* @param {{ attach: Function, setMouthShape: Function }} opts.mouthTarget
*/
- constructor({ avatar, systemPromptFn, onMessage, onStateChange, onError, mouthTarget, commandInterceptor }) {
+ constructor({ avatar, systemPromptFn, onMessage, onStateChange, onInterim, onError, mouthTarget, commandInterceptor }) {
if (!avatar?.id) throw new Error('TalkController: avatar.id required');
if (!mouthTarget) throw new Error('TalkController: mouthTarget required');
this.avatar = avatar;
this.systemPromptFn = systemPromptFn || (() => '');
this.onMessage = onMessage || (() => {});
this.onStateChange = onStateChange || (() => {});
+ this.onInterim = onInterim || (() => {});
this.onError = onError || ((e) => log.warn('[talk]', e?.message));
this.mouthTarget = mouthTarget;
// Optional async hook: gets first crack at a final transcript. If it returns
@@ -69,45 +79,146 @@ export class TalkController {
this._currentTap = null;
this._driver = null;
this._voicePromise = null; // resolves to { provider, voiceId } | null
+
+ // Speech-to-text routing. 'riva' = server-side NVIDIA Riva (cross-browser),
+ // 'browser' = window.SpeechRecognition (Chrome/Edge/Safari), 'none' = text
+ // only. Resolved once by prepare(); language tracks the avatar's locale.
+ this._sttMode = null;
+ this._sttModePromise = null;
+ this._listenMode = null; // mode of the in-flight turn
+ this._mic = null;
+ this._interimTimer = null;
+ this._interimBusy = false;
+ this._interimCount = 0;
+ this.language = 'en-US';
}
get state() {
return this._state;
}
+ /** Resolved STT path: 'riva' | 'browser' | 'none' (null until prepare()). */
+ get sttMode() {
+ return this._sttMode;
+ }
+
+ /** Live mic level (0..1) while the Riva lane is capturing; 0 otherwise. */
+ get micLevel() {
+ return this._mic ? this._mic.getLevel() : 0;
+ }
+
+ /**
+ * Decide the STT path once, before the first turn. Probes /api/asr for the
+ * free NVIDIA Riva lane (works in every browser, including Firefox); falls
+ * back to the browser's own SpeechRecognition, then to text-only. Safe to
+ * call repeatedly — the probe runs at most once. Returns the resolved mode.
+ */
+ async prepare() {
+ if (this._sttMode) return this._sttMode;
+ if (!this._sttModePromise) {
+ this._sttModePromise = (async () => {
+ const hasBrowserSR = !!(window.SpeechRecognition || window.webkitSpeechRecognition);
+ const canCapture = MicCapture.isSupported();
+ if (canCapture) {
+ try {
+ const r = await fetch('/api/asr', { headers: { accept: 'application/json' } });
+ if (r.ok) {
+ const j = await r.json();
+ if (j?.configured) return (this._sttMode = 'riva');
+ }
+ } catch {
+ // Probe failure is not fatal — fall back to whatever the browser offers.
+ }
+ }
+ return (this._sttMode = hasBrowserSR ? 'browser' : 'none');
+ })();
+ }
+ return this._sttModePromise;
+ }
+
/**
- * Begin a single push-to-talk turn. Returns immediately; the recognized
- * speech triggers the chat call on the recognizer's `end` event. Call
- * stopListening() to terminate before a final result lands.
+ * Begin a single push-to-talk turn. Returns immediately. The recognized speech
+ * triggers the chat call when stopListening() lands a final transcript (Riva)
+ * or on the recognizer's `end` event (browser). Routes by the mode resolved in
+ * prepare(), with a synchronous fallback if prepare() hasn't settled yet.
*/
startListening() {
if (this._state !== 'idle') return false;
+ const mode = this._sttMode || this._fallbackSttMode();
+ if (mode === 'riva') {
+ this._listenMode = 'riva';
+ this._startRivaListening();
+ return true;
+ }
+ if (mode === 'browser') {
+ this._listenMode = 'browser';
+ return this._startBrowserListening();
+ }
+ this._listenMode = null;
+ this.onError(coded('Voice input isn’t available here — type your message instead.', 'stt-unavailable'));
+ return false;
+ }
+
+ /** Stop an in-flight recognition. State transitions to idle (or transcribing). */
+ stopListening() {
+ if (this._listenMode === 'riva') {
+ this._stopRivaListening().catch((err) => {
+ this._setState('idle');
+ this.onError(err);
+ });
+ return;
+ }
+ if (this._recognizer) {
+ try {
+ this._recognizer.stop();
+ } catch {}
+ }
+ }
+
+ // Best mode to use before prepare() has resolved. Prefer the browser's own
+ // recognizer (zero setup, instant) when present; otherwise attempt Riva if the
+ // environment can capture audio at all.
+ _fallbackSttMode() {
+ if (window.SpeechRecognition || window.webkitSpeechRecognition) return 'browser';
+ return MicCapture.isSupported() ? 'riva' : 'none';
+ }
+
+ // ── Browser SpeechRecognition path (Chrome/Edge/Safari) ────────────────
+ _startBrowserListening() {
const RecCls = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!RecCls) {
- this.onError(
- new Error('Your browser does not support speech input. Try Chrome, Edge, or Safari.'),
- );
+ this.onError(coded('Your browser does not support speech input. Try Chrome, Edge, or Safari.', 'stt-unavailable'));
return false;
}
const rec = new RecCls();
- rec.lang = 'en-US';
+ rec.lang = this.language;
rec.continuous = false;
- rec.interimResults = false;
+ rec.interimResults = true;
rec.maxAlternatives = 1;
this._recognizer = rec;
let finalText = '';
rec.onresult = (e) => {
- const last = e.results[e.results.length - 1];
- if (last.isFinal) finalText = last[0].transcript;
+ let interim = '';
+ for (let i = e.resultIndex; i < e.results.length; i++) {
+ const res = e.results[i];
+ if (res.isFinal) finalText += res[0].transcript;
+ else interim += res[0].transcript;
+ }
+ if (interim) this.onInterim(interim);
};
rec.onerror = (e) => {
- this.onError(new Error(`Speech recognition error: ${e.error || 'unknown'}`));
+ const kind = e.error || 'unknown';
+ // 'no-speech'/'aborted' are benign end-of-hold outcomes, not failures.
+ if (kind !== 'no-speech' && kind !== 'aborted') {
+ this.onError(coded(`Speech recognition error: ${kind}`, kind === 'not-allowed' ? 'permission-denied' : 'stt-failed'));
+ }
};
rec.onend = () => {
this._recognizer = null;
+ this.onInterim('');
const transcript = finalText.trim();
if (!transcript) {
this._setState('idle');
@@ -121,21 +232,132 @@ export class TalkController {
this._setState('listening');
return true;
} catch (err) {
- this.onError(new Error(`Could not start mic: ${err.message}`));
+ this.onError(coded(`Could not start mic: ${err.message}`, 'capture-failed'));
this._setState('idle');
return false;
}
}
- /** Stop an in-flight recognition. The current state transitions to idle. */
- stopListening() {
- if (this._recognizer) {
- try {
- this._recognizer.stop();
- } catch {}
+ // ── NVIDIA Riva path (cross-browser, server-side) ──────────────────────
+ _startRivaListening() {
+ const mic = new MicCapture();
+ this._mic = mic;
+ this._setState('listening'); // optimistic — the getUserMedia prompt is showing
+ mic.start().then(
+ () => {
+ // stopListening() may have run during the permission prompt.
+ if (this._mic !== mic) {
+ mic.dispose();
+ return;
+ }
+ this._interimCount = 0;
+ this._interimBusy = false;
+ this._interimTimer = setInterval(() => this._fireInterim(), INTERIM_INTERVAL_MS);
+ },
+ (err) => {
+ if (this._mic === mic) this._mic = null;
+ mic.dispose();
+ this._setState('idle');
+ this.onError(err); // .code: permission-denied | no-mic | unsupported | capture-failed
+ },
+ );
+ }
+
+ async _stopRivaListening() {
+ this._clearInterim();
+ const mic = this._mic;
+ if (!mic) return;
+ this._mic = null;
+
+ // Nothing captured (released before the mic opened) — quietly reset.
+ if (!mic.capturing) {
+ mic.dispose();
+ this._setState('idle');
+ return;
+ }
+
+ this._setState('transcribing');
+ let wav = null;
+ try {
+ wav = await mic.stop();
+ } catch {
+ // fall through — treated as no audio below
+ } finally {
+ mic.dispose();
+ }
+ this.onInterim('');
+
+ if (!wav) {
+ this._setState('idle');
+ return;
+ }
+
+ let transcript = '';
+ try {
+ transcript = (await this._recognize(wav)).trim();
+ } catch (err) {
+ this._setState('idle');
+ this.onError(err);
+ return;
+ }
+
+ if (!transcript) {
+ this._setState('idle');
+ this.onError(coded('No speech detected — hold the button and speak, or type your message.', 'no-speech'));
+ return;
+ }
+
+ this._handleTranscript(transcript).catch((err) => this.onError(err));
+ }
+
+ // Fire one interim recognition over the audio captured so far so partial words
+ // surface live. Strictly best-effort: a failed or rate-limited interim is
+ // swallowed; the authoritative transcript comes from the final pass on release.
+ async _fireInterim() {
+ if (!this._mic || this._interimBusy || this._interimCount >= MAX_INTERIMS) return;
+ const snapshot = this._mic.snapshotWav();
+ if (!snapshot) return;
+ this._interimBusy = true;
+ this._interimCount += 1;
+ try {
+ const text = await this._recognize(snapshot);
+ if (this._mic && text) this.onInterim(text); // still listening
+ } catch {
+ // interim is optional — ignore
+ } finally {
+ this._interimBusy = false;
}
}
+ _clearInterim() {
+ if (this._interimTimer) {
+ clearInterval(this._interimTimer);
+ this._interimTimer = null;
+ }
+ this._interimBusy = false;
+ }
+
+ // POST a WAV clip to the free Riva ASR lane and return the transcript text.
+ async _recognize(wavBlob) {
+ const r = await fetch(`/api/asr?language=${encodeURIComponent(this.language)}`, {
+ method: 'POST',
+ headers: { 'content-type': 'audio/wav' },
+ credentials: 'include',
+ body: wavBlob,
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ const err = coded(
+ j.error_description || j.error || `Speech recognition failed (${r.status})`,
+ j.error || (r.status === 429 ? 'rate_limited' : 'asr_failed'),
+ );
+ err.status = r.status;
+ throw err;
+ }
+ const j = await r.json();
+ return j.text || '';
+ }
+
/**
* Force a turn from text (e.g. typed message). Same downstream path as
* speech input — chat → TTS → lipsync.
@@ -148,6 +370,11 @@ export class TalkController {
/** Stop everything immediately and detach. Idempotent. */
stop() {
+ this._clearInterim();
+ if (this._mic) {
+ this._mic.dispose();
+ this._mic = null;
+ }
this.stopListening();
this._stopPlayback();
this._driver?.dispose();
@@ -420,3 +647,11 @@ export class TalkController {
this.onStateChange(state);
}
}
+
+// Error carrying a machine-readable `.code` so the host UI can route each
+// failure precisely (mic denial → text input, rate limit → "try later", etc).
+function coded(message, code) {
+ const err = new Error(message);
+ err.code = code;
+ return err;
+}
diff --git a/src/walk-wallet.js b/src/walk-wallet.js
new file mode 100644
index 000000000..66abc4cb4
--- /dev/null
+++ b/src/walk-wallet.js
@@ -0,0 +1,231 @@
+/**
+ * In-world wallet reveal for the walk / play 3D world.
+ *
+ * The wallet is the agent's identity, so it must follow the agent's face even
+ * here, in a live multiplayer render loop. Walk up to another player who is
+ * piloting a real agent and that agent's wallet rises beside its nameplate — its
+ * vanity-aware address, live value, lifetime tips, and a one-tap Tip. Meeting an
+ * agent in the world and paying it on the spot is the moment; this is the part of
+ * the wallet layer that only three.ws can do, because only here is a funded,
+ * self-custodial wallet welded to a walking, ownable avatar.
+ *
+ * Performance is the whole game in a render loop, so this is deliberately frugal:
+ * • Only ONE wallet is ever revealed — the single nearest in-range agent — so
+ * a crowded plaza never triggers N balance reads.
+ * • Proximity is scanned on a throttle (not every frame); only the active
+ * card's screen anchor updates per frame, and that is a single read of the
+ * nameplate the renderer already positions.
+ * • Embed cards are fetched once per agent from the public CORS:* endpoint and
+ * cached, so re-approaching someone you already met costs nothing.
+ * • Hysteresis (reveal near, release a little farther) stops the card from
+ * flickering when you hover at the edge of range.
+ *
+ * Everything shown is real: the card is the same public wallet-embed the chip,
+ * the IRL card, and the off-site embed all read, so a number never disagrees
+ * across surfaces. It is the visitor view by construction (Tip + open on
+ * three.ws) — no owner control is reachable from another player's wallet.
+ */
+
+import { mountPortableWallet } from './shared/portable-wallet.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+// Metres in world space. Reveal when you get close; only release once you step
+// meaningfully away so the card is stable while you stand and read/tip.
+const REVEAL_RANGE = 5;
+const RELEASE_RANGE = 7.5;
+const SCAN_MS = 220; // proximity re-scan cadence (not per-frame)
+
+const STYLE_ID = 'walk-wallet-reveal-styles';
+
+function ensureStyles() {
+ if (document.getElementById(STYLE_ID)) return;
+ const s = document.createElement('style');
+ s.id = STYLE_ID;
+ s.textContent = `
+.walk-wallet-reveal{position:fixed;top:0;left:0;z-index:5;transform:translate(-50%,0);
+ pointer-events:auto;will-change:transform;filter:drop-shadow(0 10px 30px rgba(0,0,0,.5));
+ opacity:0;transition:opacity .18s ease;}
+.walk-wallet-reveal[data-show="1"]{opacity:1;}
+.walk-wallet-reveal[hidden]{display:none;}
+.walk-remote-label.is-wallet{border-color:var(--wallet-stroke-strong,rgba(139,92,246,.55));
+ box-shadow:0 0 0 1px rgba(139,92,246,.35),0 4px 18px rgba(139,92,246,.25);color:#fff;}
+body.is-zen .walk-wallet-reveal{display:none !important;}
+@media (prefers-reduced-motion: reduce){.walk-wallet-reveal{transition:none;}}
+`;
+ document.head.appendChild(s);
+}
+
+/** Horizontal (ground-plane) distance between two THREE vectors. */
+function groundDist(a, b) {
+ const dx = a.x - b.x;
+ const dz = a.z - b.z;
+ return Math.hypot(dx, dz);
+}
+
+/**
+ * @param {object} cfg
+ * @param {() => {x:number,y:number,z:number}} cfg.getLocalPosition Local avatar world position.
+ * @param {Map<string, any>} cfg.remotePlayers sessionId → RemotePlayer (has .rig, .agent, .label).
+ * @param {'mainnet'|'devnet'} [cfg.network]
+ * @returns {{ update: (nowMs:number) => void, destroy: () => void }}
+ */
+export function createWalkWalletProximity({ getLocalPosition, remotePlayers, network = 'mainnet' }) {
+ ensureStyles();
+
+ const overlay = document.createElement('div');
+ overlay.className = 'walk-wallet-reveal';
+ overlay.hidden = true;
+ document.body.appendChild(overlay);
+
+ const cardCache = new Map(); // agentId → Promise<card|null> (dedupes + caches reads)
+ let mount = null; // active mountPortableWallet handle
+ let activeAgentId = null;
+ let activePlayer = null; // RemotePlayer we are anchored to
+ let swapToken = 0;
+ let lastScan = 0;
+ let destroyed = false;
+
+ function fetchCard(agentId) {
+ if (cardCache.has(agentId)) return cardCache.get(agentId);
+ const p = fetch(`/api/agents/wallet-embed?id=${encodeURIComponent(agentId)}&network=${encodeURIComponent(network)}`, {
+ headers: { accept: 'application/json' },
+ })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => j?.data || null)
+ .catch(() => null);
+ cardCache.set(agentId, p);
+ return p;
+ }
+
+ function agentOf(player) {
+ const a = player?.agent;
+ return a && UUID_RE.test(String(a)) ? String(a) : null;
+ }
+
+ function teardown() {
+ if (mount) {
+ try { mount.destroy(); } catch { /* already gone */ }
+ mount = null;
+ }
+ if (activePlayer?.label) activePlayer.label.classList.remove('is-wallet');
+ activePlayer = null;
+ activeAgentId = null;
+ overlay.hidden = true;
+ overlay.removeAttribute('data-show');
+ overlay.innerHTML = '';
+ }
+
+ async function revealFor(player, agentId) {
+ const token = ++swapToken;
+ // Tear down the previous card immediately so two never overlap mid-swap.
+ if (mount) { try { mount.destroy(); } catch { /* gone */ } mount = null; }
+ if (activePlayer?.label) activePlayer.label.classList.remove('is-wallet');
+ overlay.innerHTML = '';
+ activePlayer = player;
+ activeAgentId = agentId;
+ player.label?.classList.add('is-wallet');
+ overlay.hidden = false;
+
+ const card = await fetchCard(agentId);
+ // Player may have moved out of range (or another won the slot) while the
+ // card loaded — honor the latest decision.
+ if (destroyed || token !== swapToken) return;
+ mount = mountPortableWallet(overlay, {
+ agentId,
+ network,
+ variant: 'card', // open by construction — an inviting in-world card
+ tip: true,
+ qr: true,
+ share: true,
+ seedCard: card || undefined,
+ name: card?.name || player.label?.textContent || undefined,
+ });
+ overlay.setAttribute('data-show', '1');
+ }
+
+ function pickNearest(local) {
+ let best = null;
+ let bestD = Infinity;
+ for (const p of remotePlayers.values()) {
+ if (!p?.rig) continue;
+ if (!agentOf(p)) continue;
+ const d = groundDist(local, p.rig.position);
+ if (d < bestD) { bestD = d; best = p; }
+ }
+ return { best, bestD };
+ }
+
+ function position() {
+ if (!activePlayer || overlay.hidden) return;
+ const label = activePlayer.label;
+ // Anchor under the nameplate the renderer already places. If the player is
+ // off-screen (label hidden) or hidden by zen mode, hide the card too.
+ if (!label || label.style.display === 'none') {
+ overlay.removeAttribute('data-show');
+ return;
+ }
+ const r = label.getBoundingClientRect();
+ if (r.width === 0 && r.height === 0) {
+ overlay.removeAttribute('data-show');
+ return;
+ }
+ let left = r.left + r.width / 2;
+ let top = r.bottom + 8;
+ const ow = overlay.offsetWidth || 264;
+ const oh = overlay.offsetHeight || 120;
+ // Keep the card on screen on small viewports / near edges.
+ const half = ow / 2;
+ if (left - half < 8) left = half + 8;
+ if (left + half > window.innerWidth - 8) left = window.innerWidth - half - 8;
+ if (top + oh > window.innerHeight - 8) top = Math.max(8, r.top - oh - 8);
+ overlay.style.transform = `translate(-50%,0) translate(${Math.round(left)}px,${Math.round(top)}px)`;
+ overlay.setAttribute('data-show', '1');
+ }
+
+ function update(now) {
+ if (destroyed) return;
+ const local = getLocalPosition?.();
+ if (!local) { if (activePlayer) teardown(); return; }
+
+ if (now - lastScan >= SCAN_MS) {
+ lastScan = now;
+
+ // The active player left the world or stopped piloting an agent.
+ if (activePlayer && (!remotePlayers.has(activePlayer.sessionId) || !agentOf(activePlayer) || !activePlayer.rig)) {
+ teardown();
+ }
+
+ const { best, bestD } = pickNearest(local);
+
+ if (activePlayer) {
+ // Keep the current card until the player steps past the release ring,
+ // unless they vanished above.
+ const stillActive = remotePlayers.has(activePlayer.sessionId) && activePlayer.rig;
+ const d = stillActive ? groundDist(local, activePlayer.rig.position) : Infinity;
+ if (d > RELEASE_RANGE) {
+ teardown();
+ if (best && bestD <= REVEAL_RANGE) revealFor(best, agentOf(best));
+ } else if (best && best !== activePlayer && bestD <= REVEAL_RANGE && bestD < d - 1.5) {
+ // A clearly-closer agent supersedes the current one (1.5m margin
+ // avoids thrashing between two near-equidistant players).
+ revealFor(best, agentOf(best));
+ }
+ } else if (best && bestD <= REVEAL_RANGE) {
+ revealFor(best, agentOf(best));
+ }
+ }
+
+ // Cheap per-frame anchor update for the one active card.
+ position();
+ }
+
+ return {
+ update,
+ destroy() {
+ destroyed = true;
+ teardown();
+ overlay.remove();
+ },
+ };
+}
diff --git a/src/walk.js b/src/walk.js
index a6c5434d0..3bd59dfd7 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -65,6 +65,7 @@ import { log } from './shared/log.js';
import { createWalkTrails3D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';
import { createWalkSession, showWelcomeBackToast } from './walk-session.js';
import { createWalkNpcs } from './walk-npcs.js';
+import { createWalkWalletProximity } from './walk-wallet.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
@@ -2318,6 +2319,9 @@ function tick() {
}
updateRemotePlayers(dt);
+ // 4·5 Reveal the wallet of the nearest agent you walk up to (one card, cheap).
+ walletProximity.update(performance.now());
+
// 4a. Advance the NPC companions' FSMs (greeter waves on approach, wanderer
// roams, guide leads toward a landmark) against the live player position.
if (walkNpcs && avatar) walkNpcs.update(dt, avatarRig.position);
@@ -2777,6 +2781,14 @@ const REMOTE_YAW_LERP = 0.18;
/** @type {Map<string, RemotePlayer>} */
const remotePlayers = new Map();
+// In-world wallet reveal: walk up to a player piloting an agent and its wallet
+// (vanity address, live value, tip) rises beside the nameplate. Frugal by design
+// — one card, throttled proximity scan, cached embed reads. See walk-wallet.js.
+const walletProximity = createWalkWalletProximity({
+ getLocalPosition: () => avatarRig.position,
+ remotePlayers,
+});
+
let net = null;
let netConnected = false;
let coinTotem = null; // CoinTotem instance when in a coin community world
@@ -2910,6 +2922,8 @@ class RemotePlayer {
this._lastEmoteTs = 0;
this._emoting = false;
this._avatarUrl = initial?.avatar || '';
+ // The agent this peer is piloting (UUID) — drives the in-world wallet reveal.
+ this.agent = initial?.agent || null;
this._avatarLoadToken = 0;
this._heldTemplateUrl = null; // remote-template URL this player currently clones
this._root = root;
@@ -2987,6 +3001,10 @@ class RemotePlayer {
if (player.cosmetics !== undefined && player.cosmetics !== this._cosWire) {
this._applyCosmetics(player.cosmetics);
}
+ // A player can swap which agent they pilot without rejoining.
+ if (player.agent !== undefined && player.agent !== this.agent) {
+ this.agent = player.agent || null;
+ }
}
// (Re)dress this peer in their equipped loadout. Idempotent — re-applies only
diff --git a/vercel.json b/vercel.json
index 1afd9f65f..f18299d75 100644
--- a/vercel.json
+++ b/vercel.json
@@ -6,11 +6,14 @@
"NODE_OPTIONS": "--no-deprecation"
},
"functions": {
- "api/cron/copy-fanout.js": {
+ "api/cron/{copy-fanout,mirror-fanout,three-holders-snapshot}.js": {
"maxDuration": 120
},
- "api/cron/mirror-fanout.js": {
- "maxDuration": 120
+ "api/cron/{strategy-fanout,gmgn-seed}.js": {
+ "maxDuration": 300
+ },
+ "api/strategies.js": {
+ "maxDuration": 30
},
"api/agents/[id].js": {
"maxDuration": 45
@@ -53,14 +56,7 @@
"includeFiles": "data/pages.json",
"maxDuration": 30
},
- "api/cron/three-holders-snapshot.js": {
- "maxDuration": 120
- },
- "api/cron/relayer-balance-check.js": {
- "includeFiles": "data/pages.json",
- "maxDuration": 60
- },
- "api/cron/flush-usage-events.js": {
+ "api/cron/{relayer-balance-check,flush-usage-events,oracle-digest}.js": {
"includeFiles": "data/pages.json",
"maxDuration": 60
},
@@ -79,13 +75,6 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 120
},
- "api/cron/oracle-digest.js": {
- "includeFiles": "data/pages.json",
- "maxDuration": 60
- },
- "api/cron/gmgn-seed.js": {
- "maxDuration": 300
- },
"api/cron/[name].js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
@@ -680,6 +669,14 @@
"src": "/mirror/?",
"dest": "/mirror.html"
},
+ {
+ "src": "/strategies/?",
+ "dest": "/strategies.html"
+ },
+ {
+ "src": "/api/strategies/(.*)",
+ "dest": "/api/strategies"
+ },
{
"src": "/mint-success/?",
"dest": "/mint-success.html"
@@ -4023,6 +4020,10 @@
"path": "/api/cron/mirror-fanout",
"schedule": "*/2 * * * *"
},
+ {
+ "path": "/api/cron/strategy-fanout",
+ "schedule": "*/2 * * * *"
+ },
{
"path": "/api/cron/index-delegations",
"schedule": "*/5 * * * *"