Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Ship agent wallet hub, IRL room mode, sniper deploy/AMM-exit
nirholasa6ea3ab2df43
diff --git a/api/irl/agent-card.js b/api/irl/agent-card.jsindex 3a4de8d59..0b45c1016 100644--- a/api/irl/agent-card.js+++ b/api/irl/agent-card.js@@ -79,8 +79,16 @@ export function deriveReputation({ fbTotal, scoreAvg, uniqueAttesters, valPassed/*** Fetch the on-chain reputation aggregates for an agent's Solana asset in a- * single round-trip. Returns null on any failure (missing tables, RPC, etc.) so- * the caller can degrade to { available:false } without failing the card.+ * single round-trip, then derive a tier/score.+ *+ * Failure contract (the card must never 500): a *query* failure — most commonly+ * a fresh / mid-migration DB where `solana_attestations` does not exist yet, but+ * also RPC/connection errors — REJECTS so the caller can mark the card+ * `{ available:false, degraded:true }` (we genuinely couldn't read reputation).+ * A *successful* read that yields no row (driver edge / partial result) is NOT a+ * failure: it means "no attestations", so we derive from zeros and the card+ * shows an available, freshly-scored agent rather than throwing on+ * `undefined.fb_total`.*/async function fetchReputation(asset, network) {const [row] = await sql`@@ -108,13 +116,19 @@ async function fetchReputation(asset, network) {FROM solana_attestationsWHERE agent_asset = ${asset} AND network = ${network}) AS tasks_accepted`;+ // The coalesce'd subselects guarantee exactly one row from real Postgres; an+ // undefined row only arises from a driver/partial edge. Treat it as "no+ // attestations" (zeros) so a successful-but-empty read never throws a+ // TypeError that the caller would mislabel as a degraded query failure.+ const r = row || {};+ const toInt = (v) => { const n = Number(v); return Number.isFinite(n) ? n : 0; };return deriveReputation({- fbTotal: row.fb_total,- scoreAvg: row.score_avg,- uniqueAttesters: row.unique_attesters,- valPassed: row.val_passed,- valFailed: row.val_failed,- tasksAccepted: row.tasks_accepted,+ fbTotal: toInt(r.fb_total),+ scoreAvg: toInt(r.score_avg),+ uniqueAttesters: toInt(r.unique_attesters),+ valPassed: toInt(r.val_passed),+ valFailed: toInt(r.val_failed),+ tasksAccepted: toInt(r.tasks_accepted),});}diff --git a/api/irl/pins.js b/api/irl/pins.jsindex fd8a5aff4..f96afaf8b 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -356,9 +356,16 @@ const REL_MAX_M = 500;// reaches the DB query or a log line. The SQL is already parameterized (this is// not the injection guard) — it's input hygiene + defense in depth, and it lets a// "not a pin id" request fail fast with a clear message instead of a confusing 404.-const PIN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+//+// A real id is a 36-char UUID; we accept that exactly, plus a conservative+// opaque-id fallback (1–64 chars, URL/path-safe alphabet only) so the guard is+// about REJECTING the dangerous shapes — control chars, whitespace, quotes,+// SQL-injection text, multi-KB blobs — rather than over-fitting to one format.+const PIN_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const PIN_ID_SAFE_RE = /^[A-Za-z0-9_-]{1,64}$/;export function isValidPinId(id) {- return typeof id === 'string' && PIN_ID_RE.test(id);+ if (typeof id !== 'string' || !id) return false;+ return PIN_UUID_RE.test(id) || PIN_ID_SAFE_RE.test(id);}// Smallest signed distance between two compass bearings, 0–180°.diff --git a/api/x402-pay.js b/api/x402-pay.jsindex 9f3be7c48..1ab2fe4b2 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -47,6 +47,7 @@ import { sql } from './_lib/db.js';import { logger } from './_lib/usage.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';+import { enforceSpendLimit, SpendLimitError, recordSpend } from './_lib/agent-trade-guards.js';const log = logger('x402-pay');@@ -184,11 +185,14 @@ async function loadAgentKeypairForUser(agentId, userId) {if (!row) return null;const enc = row.meta?.encrypted_solana_secret;if (!enc) return null;- return recoverSolanaAgentKeypair(enc, {+ const keypair = await recoverSolanaAgentKeypair(enc, {agentId,userId,reason: 'x402_pay_tool_call',});+ // Carry the agent meta so the caller can enforce + record against the shared+ // per-agent spend policy without a second DB round-trip.+ return { keypair, meta: row.meta || {} };}async function getAgentsForUser(userId) {@@ -409,7 +413,7 @@ function sseSend(res, event, data) {res.write(`data: ${JSON.stringify(data)}\n\n`);}-async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl }) {+async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl, spendGuard = null }) {const buyer = buyerOverride ?? loadAgentKeypair();const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });@@ -417,6 +421,28 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl })const accept = requirements.find((r) => r.network === NETWORK_SOLANA_MAINNET);if (!accept) throw Object.assign(new Error('no_solana_accept_configured'), { status: 500 });+ // Per-agent spend policy — enforced BEFORE any payment is built/signed so a+ // breach moves no funds. USDC is dollar-denominated (6 decimals), so the+ // payment amount converts straight to the USD ceiling unit.+ const spendUsd = Number(accept.amount) / 1e6;+ if (spendGuard) {+ try {+ await enforceSpendLimit({+ agentId: spendGuard.agentId,+ meta: spendGuard.meta,+ category: 'x402',+ usdValue: spendUsd,+ destination: accept.payTo,+ network: spendGuard.network || 'mainnet',+ });+ } catch (e) {+ if (e instanceof SpendLimitError) {+ throw Object.assign(new Error(e.message), { status: e.status, code: e.code, detail: e.detail });+ }+ throw e;+ }+ }+const t0 = Date.now();emit('challenge', { network: accept.network, amount: accept.amount, payTo: accept.payTo });@@ -471,6 +497,22 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl })void recordFeedEntry(feedEntry).catch((err) => {log.warn('feed_record_failed', { tx: settled.transaction, message: err?.message });});+ // Record the agent's x402 spend into the shared custody ledger so it counts+ // toward the per-agent daily ceiling and shows in the custody audit trail.+ if (spendGuard) {+ void recordSpend({+ agentId: spendGuard.agentId,+ userId: spendGuard.userId,+ category: 'x402',+ network: spendGuard.network || 'mainnet',+ asset: 'USDC',+ usd: spendUsd,+ destination: accept.payTo,+ signature: settled.transaction || null,+ status: settled.transaction ? 'confirmed' : 'ok',+ meta: { tool },+ }).catch((err) => log.warn('x402_spend_record_failed', { message: err?.message }));+ }if (settled.transaction) {void persistCall(settled.transaction, {...feedEntry,@@ -608,12 +650,15 @@ export default wrap(async (req, res) => {// Resolve payer: agent wallet (agentId + authed) or shared showcase wallet.let buyer;+ let spendGuard = null;if (input.agentId) {const auth = await requireAuth(req);if (!auth) return json(res, 401, { error: 'authentication_required' });- const kp = await loadAgentKeypairForUser(String(input.agentId), auth.userId);- if (!kp) return json(res, 403, { error: 'agent_not_found_or_no_solana_wallet' });- buyer = kp;+ const loaded = await loadAgentKeypairForUser(String(input.agentId), auth.userId);+ if (!loaded) return json(res, 403, { error: 'agent_not_found_or_no_solana_wallet' });+ buyer = loaded.keypair;+ // Per-agent spend policy applies to x402 just like trade/snipe/withdraw.+ spendGuard = { agentId: String(input.agentId), userId: auth.userId, meta: loaded.meta, network: 'mainnet' };} else {try {buyer = loadAgentKeypair();@@ -631,7 +676,7 @@ export default wrap(async (req, res) => {sseInit(res);const emit = (ev, data) => sseSend(res, ev, data);try {- await runFlow({ tool, args, emit, buyer, resourceUrl });+ await runFlow({ tool, args, emit, buyer, resourceUrl, spendGuard });} catch (err) {emit('error', payErrorEnvelope(err));} finally {@@ -647,7 +692,7 @@ export default wrap(async (req, res) => {if (ev === 'result') final = data;};try {- await runFlow({ tool, args, emit, buyer, resourceUrl });+ await runFlow({ tool, args, emit, buyer, resourceUrl, spendGuard });} catch (err) {return json(res, payErrorStatus(err), payErrorEnvelope(err));}diff --git a/data/changelog.json b/data/changelog.jsonindex 84592a2c5..3936b0de2 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,34 @@{"$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-17",+ "title": "IRL: place an agent at a spot you pick on a map — not your exact location",+ "summary": "You no longer have to stand somewhere to leave an agent there. Tap \"Place on map\" in IRL and choose any point — search a place by name or drag the pin — and your agent is placed exactly there. It's the privacy-friendly way to drop an agent at a café, a plaza, or an event without writing your real standing position into the public feed, and it works even before you grant location. The picker is a real map with search and a draggable marker, and every state — loading, no results, a map that won't load — is handled, so you always know where your agent will land before you confirm.",+ "tags": ["feature", "improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL: new Location & privacy controls — see what's shared, and dial it down",+ "summary": "IRL now has a Location & privacy panel, reachable from the top bar, that explains in plain language what a placed agent actually shares: it's visible only to someone physically within about 60 metres of it, never on a map or a browsable list, and never tied to your account — and pins you place without signing in disappear after 7 days. From the same panel you can switch discovery to Approximate, which rounds the position your phone sends while it looks for nearby agents so your exact spot never leaves the device; toggle whether you appear to others nearby; and jump straight to managing or removing the agents you've placed. The first time you grant location, a short one-time note walks you through the same facts.",+ "tags": ["feature", "improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL: see every agent you've placed on a map and wipe them all in one tap",+ "summary": "The 'My pins' panel in /irl is now a real management surface. A small map at the top plots every agent you've placed, so you can see at a glance where you dropped things — tap any marker and it jumps to that agent's row in the list. Each row now shows exactly when it disappears: a countdown like 'expires in 6d' for pins placed without an account (they self-delete after a week), or 'permanent' once you're signed in. And a single 'Remove all from this device' button — with a clear confirm step — wipes every agent you placed from this device in one go, so cleaning up after trying things out takes one tap instead of deleting them one by one. If the map can't load it quietly falls back to the list, which always works.",+ "tags": ["improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "Embedded avatars: polished loading, seamless looping, and smarter framing",+ "summary": "The live 3D avatars dotted around the site — the ones in the home-page feature cards and anywhere an <agent-3d> embed appears — now feel intentional from the first frame. Each one fades in behind a soft skeleton placeholder while its model streams, instead of popping in cold. Animations no longer hard-snap: a one-shot gesture like a wave plays once and settles smoothly back into an idle stance rather than jumping at the loop boundary. A new framing option crops the avatar to head-to-mid-thigh so it fills its card instead of standing tiny and low. If a body ever fails to load, you get a tasteful silhouette rather than a blank or broken box. Avatars pause themselves when scrolled off-screen to save battery, and anyone who's asked their device to reduce motion gets a calm, held pose instead of looping animation.",+ "tags": ["improvement"],+ "link": "/embed"+ },{"date": "2026-06-17","title": "Try x402 live — pay a tenth of a cent to call a real API from your own wallet",diff --git a/deploy/sniper/README.md b/deploy/sniper/README.mdnew file mode 100644index 000000000..2c9a96efe--- /dev/null+++ b/deploy/sniper/README.md@@ -0,0 +1,188 @@+# Deploy: agent-sniper worker → Cloud Run++The [`agent-sniper`](../../workers/agent-sniper) worker is a **long-lived+background process** that holds the live PumpPortal new-mint feed open, scores+launches against every armed agent strategy, and — in `live` mode — snipes from+each agent's **own** encrypted Solana wallet, then manages each position to its+exit. It holds a websocket open and runs timer loops with no inbound request to+"wake" it, so it **cannot run on Vercel** (an hourly cron can't snipe a launch)+and **must** run with always-on CPU and one always-warm instance.++This directory is the repeatable Cloud Run deploy, following the same house+pattern as [`deploy/world`](../world).++## TL;DR++```bash+# One-time: create the secrets (below), then:+node scripts/deploy-sniper.mjs # build → push → deploy in SIMULATE mode+curl -s https://three.ws/api/sniper/status # confirm it's live+```++`SNIPER_MODE` defaults to **`simulate`** — real on-chain quotes, **no broadcast,+zero spend**. Going `live` is a deliberate, separate cutover (see below); the+deploy script will never flip a service to live for you.++## Single instance is load-bearing++The worker's budget / concurrency guardrails are made race-free by an+**in-process per-agent lock** (`workers/agent-sniper/executor.js`). Two instances+would each independently pass the daily-budget check and **double-spend**.+`cloudrun.yaml` therefore pins `minScale = maxScale = 1`. This is a correctness+constraint, not a cost choice — do not scale it out without first replacing the+in-process lock with an atomic DB spend reservation.++## Required GCP setup (one time)++Project `aerial-vehicle-466722-p5`, region `us-central1` (override with+`GCP_PROJECT` / `GCP_REGION`). The deploy script enables the APIs, creates the+runtime service account `agent-sniper-sa@…`, and creates the `workers` Artifact+Registry repo if missing — all idempotent.++### Secrets — NEVER commit these; they live only in Secret Manager++| Secret | Required | Holds |+|--------|----------|-------|+| `sniper-database-url` | ✅ always | `DATABASE_URL` — Neon Postgres (strategies, position ledger, heartbeat). |+| `sniper-jwt-secret` | ✅ always | `JWT_SECRET` — decrypts each agent's Solana secret to sign. Loaded per-trade at runtime; **never baked into the image**. |+| `sniper-solana-rpc-url` | ✅ for **live** | `SOLANA_RPC_URL` — a real RPC (Helius/Triton). A public RPC 429s under the firehose; `loadConfig()` **refuses to start live without it**. |+| `telegram-bot-token` | optional | `TELEGRAM_BOT_TOKEN` — enables ops alerting. |+| `telegram-alerts-chat-id` | optional | `TELEGRAM_ALERTS_CHAT_ID` — the private ops channel (same one `api/_lib/alerts.js` uses). Absent → alerting is a silent no-op; the worker still runs. |++```bash+PROJECT=aerial-vehicle-466722-p5+SA=agent-sniper-sa@${PROJECT}.iam.gserviceaccount.com++printf '%s' "$DATABASE_URL" | gcloud secrets create sniper-database-url --data-file=- --project=$PROJECT+printf '%s' "$JWT_SECRET" | gcloud secrets create sniper-jwt-secret --data-file=- --project=$PROJECT+printf '%s' "$SOLANA_RPC_URL" | gcloud secrets create sniper-solana-rpc-url --data-file=- --project=$PROJECT+printf '%s' "$TELEGRAM_BOT_TOKEN" | gcloud secrets create telegram-bot-token --data-file=- --project=$PROJECT+printf '%s' "$TELEGRAM_ALERTS_CHAT_ID" | gcloud secrets create telegram-alerts-chat-id --data-file=- --project=$PROJECT++for s in sniper-database-url sniper-jwt-secret sniper-solana-rpc-url telegram-bot-token telegram-alerts-chat-id; do+ gcloud secrets add-iam-policy-binding "$s" --project=$PROJECT \+ --member=serviceAccount:$SA --role=roles/secretmanager.secretAccessor+done+```++(The `telegram-bot-token` / `telegram-alerts-chat-id` secrets are the platform's+shared ops-alert credentials and may already exist for other workers — reuse them.)++## Runtime config (set in `cloudrun.yaml`, not secrets)++| Var | Default | Meaning |+|-----|---------|---------|+| `SNIPER_MODE` | `simulate` | `simulate` = real quotes, no broadcast, no spend. `live` = real trades. |+| `SNIPER_NETWORK` | `mainnet` | `mainnet` \| `devnet`. |+| `SNIPER_GLOBAL_KILL` | `0` | `1` halts all **new** buys; open positions still manage/exit. |+| `SNIPER_HEARTBEAT_MS` | `30000` | Liveness heartbeat cadence → `bot_heartbeat` → `/api/sniper/status`. |+| `SNIPER_FEED_WATCHDOG_MS` | `180000` | Re-subscribe + alert if the feed is silent this long. |+| `SNIPER_ERROR_ALERT_THRESHOLD` / `_WINDOW_MS` | `5` / `600000` | Executor/RPC errors in the window that trip an ops alert. |+| `SNIPER_ANNOUNCE` | `1` | Announce boot/shutdown to the ops channel. |++Full per-trade knobs (budget caps, throttles, intel/first-claim) are documented+in [`workers/agent-sniper/README.md`](../../workers/agent-sniper/README.md). The+trade-shaping caps (`daily_budget_lamports`, `per_trade_lamports`,+`max_concurrent_positions`, `max_price_impact_pct`, `stop_loss_pct`) are+**per-strategy DB columns**, set by the owner when arming — not env.++## Fail-closed++`loadConfig()` throws (and the process exits non-zero, so Cloud Run shows a crash+loop instead of silently mis-trading) when:++- `DATABASE_URL` or `JWT_SECRET` is missing,+- `SNIPER_MODE` / `SNIPER_NETWORK` is not one of the allowed values,+- `SNIPER_MODE=live` with neither `SOLANA_RPC_URL` nor `HELIUS_API_KEY`.++This is unit-verified in `tests/agent-sniper-ops.test.mjs`.++## Deploy (simulate)++```bash+node scripts/deploy-sniper.mjs # build + push + deploy + verify heartbeat+node scripts/deploy-sniper.mjs --skip-build # redeploy the current image (config-only change)+node scripts/deploy-sniper.mjs --dry-run # print the gcloud commands, run nothing+```++Or by hand:++```bash+gcloud builds submit --config deploy/sniper/cloudbuild.yaml . # build from REPO ROOT+gcloud run services replace deploy/sniper/cloudrun.yaml --region=us-central1+```++The cloudbuild context is the **repo root** (not this dir) — the sniper image+copies `api/`, the `agent-payments-sdk/` workspace, and `workers/agent-sniper/`.++### Verify simulate works against the real feed++```bash+# Heartbeat / feed-live signal (public, machine-readable):+curl -s https://three.ws/api/sniper/status | jq+# → { "state": "live", "mode": "simulate", "feedLive": true, "strategies": N, ... }++# Logs: real new-mint scoring + simulated buys, zero broadcast (sig = "SIMULATED"):+gcloud run services logs read agent-sniper --region=us-central1 --project=aerial-vehicle-466722-p5+# look for: "feed connected", "candidate", and trade lines with mode=simulate / sig=SIMULATED+```++`state: "live"` here means the **worker** is live and its feed is connected (not+that it's trading with real money). In simulate it scores and records simulated+positions with `buy_sig='SIMULATED'` and never broadcasts.++## Cutover to live (gated, deliberate)++Live mode signs and broadcasts real transactions from agent wallets. Do **not**+flip it until all of the following are true:++1. `sniper-solana-rpc-url` secret is set to a real RPC (Helius/Triton). Live+ refuses a public RPC.+2. At least one agent has an **armed strategy with conservative caps** (small+ `daily_budget_lamports` + `per_trade_lamports`, a mandatory `stop_loss_pct`,+ `max_concurrent_positions: 1`) and a **funded** wallet. Arm via the+ owner-only `POST /api/sniper/strategy`.+3. You have watched `simulate` score + simulate-buy real launches for long enough+ to trust the scoring.++Then edit `cloudrun.yaml` (`SNIPER_MODE: live`) and redeploy:++```bash+# set SNIPER_MODE to "live" in deploy/sniper/cloudrun.yaml, then:+node scripts/deploy-sniper.mjs --skip-build+```++The deployed worker enforces the **same guardrails as code** — no env weakens+them: global + per-agent kill switch, daily budget cap, max concurrent+positions, mandatory stop-loss (DB `CHECK`), price-impact circuit breaker, and a+one-shot idempotency lock per (agent, mint). Confirm they're active by arming a+strategy that should be skipped (e.g. price-impact above its breaker) and seeing+the `skip`/`failed` reason in the logs.++### Emergency stop++```bash+# Halt all NEW buys immediately (open positions still manage/exit):+# set SNIPER_GLOBAL_KILL: "1" in cloudrun.yaml, then:+node scripts/deploy-sniper.mjs --skip-build+# Per-agent: set agent_sniper_strategies.kill_switch = true (any open position exits at market).+```++## Watchdog, alerting, and health++- **Feed watchdog + auto-reconnect.** The PumpPortal client reconnects with+ backoff internally; on top of that the worker watches for *silence* — if no+ event arrives within `SNIPER_FEED_WATCHDOG_MS` it tears down and re-subscribes,+ marks `feedConnected=false` in the heartbeat, and fires an ops alert. A silent+ dead feed is the worst failure mode, so it self-heals **and** pages.+- **Ops alerts** (Telegram, via `api/_lib/alerts.js`'s dedup/throttle) fire on:+ feed silence/re-subscribe, an executor/RPC error spike, and worker+ boot/shutdown. These go to the **ops** channel (`TELEGRAM_ALERTS_CHAT_ID`) and+ are distinct from the per-strategy trade notifications+ (`TELEGRAM_SNIPER_CHAT_ID`, `api/_lib/sniper/notify.js`).+- **Heartbeat → `/api/sniper/status`.** The worker upserts a `bot_heartbeat` row+ (`worker='agent-sniper'`) every `SNIPER_HEARTBEAT_MS` carrying mode, network,+ `feedConnected`, last-event age, active strategy count, reconnect/error+ counters, and uptime. `GET /api/sniper/status` reads it and reports+ `live` / `degraded` (alive but feed silent) / `down` / `unknown` — answerable+ without SSHing into the instance, and consumable by the platform status page.diff --git a/deploy/sniper/cloudbuild.yaml b/deploy/sniper/cloudbuild.yamlnew file mode 100644index 000000000..ffbe0612e--- /dev/null+++ b/deploy/sniper/cloudbuild.yaml@@ -0,0 +1,38 @@+# Cloud Build — builds and pushes the agent-sniper image to Artifact Registry.+#+# IMPORTANT: unlike the world image, this one builds from the REPO ROOT as+# context. The sniper Dockerfile (workers/agent-sniper/Dockerfile) copies+# `api/`, the `agent-payments-sdk/` workspace, and `workers/agent-sniper/` — it+# is not self-contained in its own directory.+#+# Run manually from the repo root:+# gcloud builds submit --config deploy/sniper/cloudbuild.yaml .+#+# Or end to end (build → push → deploy → verify):+# node scripts/deploy-sniper.mjs++substitutions:+ _REGION: us-central1+ _REPO: workers+ _IMAGE: agent-sniper++steps:+ - name: gcr.io/cloud-builders/docker+ args:+ - build+ - -t+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:$SHORT_SHA+ - -t+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:latest+ - -f+ - workers/agent-sniper/Dockerfile+ - .+ timeout: 1200s++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:latest++options:+ machineType: E2_HIGHCPU_8+ logging: CLOUD_LOGGING_ONLYdiff --git a/deploy/sniper/cloudrun.yaml b/deploy/sniper/cloudrun.yamlnew file mode 100644index 000000000..a2d16ef7e--- /dev/null+++ b/deploy/sniper/cloudrun.yaml@@ -0,0 +1,123 @@+# Cloud Run service — agent-sniper (autonomous pump.fun sniper worker).+#+# A long-lived background worker (NOT an HTTP server, NOT a Vercel cron). It+# holds the PumpPortal new-mint feed open, scores launches, and — in live mode —+# snipes from each agent's OWN encrypted Solana wallet. Because it holds a+# websocket open and must keep its CPU between requests, it runs with always-on+# CPU and exactly one always-warm instance.+#+# ── SINGLE INSTANCE IS LOAD-BEARING ──────────────────────────────────────────+# The worker's budget + concurrency guardrails are made race-free by an+# IN-PROCESS per-agent lock (workers/agent-sniper/executor.js, README "Guardrails").+# Running more than one instance would let two instances each pass the daily-budget+# check and double-spend. minScale == maxScale == 1 is therefore mandatory, not a+# cost choice. Scaling out would require an atomic DB spend reservation first.+#+# ── DEFAULT MODE IS SIMULATE ──────────────────────────────────────────────────+# SNIPER_MODE defaults to `simulate` (real on-chain quotes, NO broadcast, zero+# spend). Going live is a deliberate, documented cutover — see deploy/sniper/README.md.+# Live mode also REQUIRES a real RPC (loadConfig refuses to start live on a public+# RPC), supplied via the SOLANA_RPC_URL secret below.+#+# ── ONE-TIME SECRET SETUP (never commit these) ────────────────────────────────+# printf '%s' "$DATABASE_URL" | gcloud secrets create sniper-database-url --data-file=-+# printf '%s' "$JWT_SECRET" | gcloud secrets create sniper-jwt-secret --data-file=-+# printf '%s' "$SOLANA_RPC_URL" | gcloud secrets create sniper-solana-rpc-url --data-file=- # live only+# # optional ops alerting (reuses the platform's ops channel):+# printf '%s' "$TELEGRAM_BOT_TOKEN" | gcloud secrets create telegram-bot-token --data-file=-+# printf '%s' "$TELEGRAM_ALERTS_CHAT_ID" | gcloud secrets create telegram-alerts-chat-id --data-file=-+# # then grant the runtime SA read on each:+# for s in sniper-database-url sniper-jwt-secret sniper-solana-rpc-url telegram-bot-token telegram-alerts-chat-id; do \+# gcloud secrets add-iam-policy-binding "$s" \+# --member=serviceAccount:[email protected] \+# --role=roles/secretmanager.secretAccessor; done+#+# Apply with:+# gcloud run services replace deploy/sniper/cloudrun.yaml --region=us-central1+# (or, end to end: node scripts/deploy-sniper.mjs)++apiVersion: serving.knative.dev/v1+kind: Service+metadata:+ name: agent-sniper+ labels:+ cloud.googleapis.com/location: us-central1+ annotations:+ run.googleapis.com/launch-stage: BETA+ # Not a public website — the only "traffic" is the platform's own deploy.+ run.googleapis.com/ingress: internal+spec:+ template:+ metadata:+ annotations:+ # Exactly one always-warm instance. See the SINGLE INSTANCE note above —+ # this is required for guardrail correctness, not just to avoid cold starts.+ autoscaling.knative.dev/minScale: "1"+ autoscaling.knative.dev/maxScale: "1"+ # Always-on CPU: the worker scores feed events and sweeps positions on a+ # timer with no inbound request to "wake" it. Throttling CPU between+ # requests would freeze the feed loop and silently stop sniping.+ run.googleapis.com/cpu-throttling: "false"+ run.googleapis.com/execution-environment: gen2+ spec:+ serviceAccountName: [email protected]+ # No inbound HTTP; one worker process. Keep concurrency at 1.+ containerConcurrency: 1+ timeoutSeconds: 3600+ containers:+ - image: us-central1-docker.pkg.dev/aerial-vehicle-466722-p5/workers/agent-sniper:latest+ env:+ - name: NODE_ENV+ value: production+ # DEFAULT SIMULATE. Flip to "live" ONLY via the documented cutover+ # (deploy/sniper/README.md) once at least one agent wallet is funded.+ - name: SNIPER_MODE+ value: simulate+ - name: SNIPER_NETWORK+ value: mainnet+ # Emergency stop: set to "1" and redeploy to halt all new buys while+ # still letting open positions manage/exit.+ - name: SNIPER_GLOBAL_KILL+ value: "0"+ # Liveness heartbeat cadence (ms) → bot_heartbeat → /api/sniper/status.+ - name: SNIPER_HEARTBEAT_MS+ value: "30000"+ # Required: Neon Postgres (strategies + position ledger + heartbeat).+ - name: DATABASE_URL+ valueFrom:+ secretKeyRef:+ name: sniper-database-url+ key: latest+ # Required: decrypts each agent's encrypted Solana secret to sign.+ # Never baked into the image; loaded per-trade at runtime.+ - name: JWT_SECRET+ valueFrom:+ secretKeyRef:+ name: sniper-jwt-secret+ key: latest+ # Required for LIVE mode (a public RPC 429s under the firehose). Safe to+ # leave mounted in simulate too — it's only used when a trade broadcasts.+ - name: SOLANA_RPC_URL+ valueFrom:+ secretKeyRef:+ name: sniper-solana-rpc-url+ key: latest+ # Ops alerting (optional) — reuses the platform's shared ops channel.+ # Absent → sendOpsAlert is a no-op, the worker still runs.+ - name: TELEGRAM_BOT_TOKEN+ valueFrom:+ secretKeyRef:+ name: telegram-bot-token+ key: latest+ - name: TELEGRAM_ALERTS_CHAT_ID+ valueFrom:+ secretKeyRef:+ name: telegram-alerts-chat-id+ key: latest+ resources:+ limits:+ cpu: "1"+ memory: 1Gi+ traffic:+ - percent: 100+ latestRevision: truediff --git a/package.json b/package.jsonindex 8c3e207d9..2e23b8576 100644--- a/package.json+++ b/package.json@@ -137,6 +137,9 @@"db:migrate": "node scripts/apply-migrations.mjs --apply","db:status": "node scripts/apply-migrations.mjs","worker:oracle": "node workers/oracle/index.js",+ "worker:sniper": "node workers/agent-sniper/index.js",+ "worker:sniper:live": "SNIPER_MODE=live node workers/agent-sniper/index.js",+ "deploy:sniper": "node scripts/deploy-sniper.mjs","pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js","pump:refresh-idls": "node scripts/refresh-pump-idls.mjs","seed:skills": "node scripts/seed-skills.js",diff --git a/pages/agent-wallet.html b/pages/agent-wallet.htmlnew file mode 100644index 000000000..aadc9de98--- /dev/null+++ b/pages/agent-wallet.html@@ -0,0 +1,170 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <title>Agent wallet — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="theme-color" content="#000000" />+ <meta+ name="description"+ content="Manage a three.ws 3D AI agent's self-custodied Solana wallet — live balance, deposits, trading, sniping, x402 payments, and withdrawals, all in one place."+ />+ <meta name="robots" content="noindex" />++ <meta property="og:type" content="website" />+ <meta property="og:title" content="Agent wallet — three.ws" />+ <meta+ property="og:description"+ content="Your 3D AI agent's own Solana wallet: balance, deposit, trade, snipe, pay, and withdraw."+ />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <style>+ .awh-wrap {+ max-width: 820px;+ margin: 0 auto;+ padding: calc(var(--space-md) * 2) var(--space-md) calc(var(--space-md) * 4);+ }+ .awh-crumb {+ font: var(--text-sm) var(--font-body);+ color: var(--ink-dim);+ margin: 0 0 var(--space-lg);+ }+ .awh-crumb a {+ color: inherit;+ }+ .awh-crumb a:hover {+ color: var(--ink);+ }++ /* Page-level loading / message states (the hub itself styles its tabs). */+ .awh-page-skel {+ display: flex;+ flex-direction: column;+ gap: var(--space-4, 16px);+ max-width: 760px;+ margin: 0 auto;+ }+ .awh-page-skel-row,+ .awh-page-skel-tabs,+ .awh-page-skel-card {+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ border-radius: var(--radius-lg, 14px);+ animation: awh-page-pulse 1.4s ease-in-out infinite;+ }+ .awh-page-skel-row {+ height: 52px;+ width: 70%;+ }+ .awh-page-skel-tabs {+ height: 38px;+ width: 100%;+ border-radius: var(--radius-md, 10px);+ }+ .awh-page-skel-card {+ height: 200px;+ width: 100%;+ }+ @keyframes awh-page-pulse {+ 0%,+ 100% {+ opacity: 0.5;+ }+ 50% {+ opacity: 1;+ }+ }++ .awh-page-msg {+ max-width: 540px;+ margin: calc(var(--space-md) * 3) auto;+ text-align: center;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ padding: var(--space-xl) var(--space-lg);+ }+ .awh-page-msg h1 {+ font-family: var(--font-display);+ font-size: var(--text-lg);+ margin: 0 0 var(--space-sm);+ color: var(--ink-bright);+ }+ .awh-page-msg p {+ color: var(--ink-dim);+ font: var(--text-md) var(--font-body);+ line-height: var(--leading-normal);+ margin: 0 0 var(--space-lg);+ }+ .awh-page-msg-actions {+ display: flex;+ gap: var(--space-sm);+ justify-content: center;+ flex-wrap: wrap;+ }+ .awh-page-btn {+ appearance: none;+ font: var(--text-md) var(--font-body);+ color: var(--ink);+ background: var(--surface-2);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: 9px 16px;+ cursor: pointer;+ text-decoration: none;+ transition:+ background var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard);+ }+ .awh-page-btn:hover {+ background: var(--surface-3);+ border-color: var(--stroke-strong);+ }+ .awh-page-btn:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+ }+ .awh-page-btn--primary {+ background: var(--accent);+ color: #0a0a0a;+ border-color: var(--accent);+ font-weight: 600;+ }+ @media (prefers-reduced-motion: reduce) {+ .awh-page-skel-row,+ .awh-page-skel-tabs,+ .awh-page-skel-card {+ animation: none;+ }+ }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>++ <main class="awh-wrap">+ <p class="awh-crumb"><a href="/">Home</a> / <a href="/agents">Agents</a> / Wallet</p>+ <div id="awh-root"></div>+ </main>++ <script type="module" src="/src/agent-wallet.js"></script>+ <script src="/nav.js" defer></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/create-agent.html b/pages/create-agent.htmlindex 699f00d2c..566eaf79b 100644--- a/pages/create-agent.html+++ b/pages/create-agent.html@@ -1497,7 +1497,10 @@</p><div class="success-preview" id="success-preview" hidden></div><div class="success-actions">- <a class="btn btn--primary btn--lg" id="success-open" href="#"+ <a class="btn btn--primary btn--lg" id="success-fund" href="#"+ >Fund agent wallet</a+ >+ <a class="btn btn--secondary btn--lg" id="success-open" href="#">Open agent</a><a class="btn btn--secondary btn--lg" id="success-edit" href="#"diff --git a/pages/ibm/HOSTING.md b/pages/ibm/HOSTING.mdindex 946b86089..c9ad10d49 100644--- a/pages/ibm/HOSTING.md+++ b/pages/ibm/HOSTING.md@@ -5,6 +5,10 @@ protocol: a visitor pays **$0.001 USDC** from their own wallet to call a real thAPI, settled on-chain on Base or Solana. This guide is everything the IBM web team needs tohost it.+> **Reference deployment:** a byte-for-byte copy of this exact file runs at+> <https://three.ws/ibm/x402-demo>. Compare your hosted copy against it, or link to it+> directly if you'd rather not self-host.+## What it demonstrates (one paragraph)x402 reactivates the dormant HTTP `402 Payment Required` status as a payment rail. A normal@@ -101,6 +105,30 @@ three.ws serves the API and widget with `Access-Control-Allow-Origin: *` and exppayment headers, so calls from `live.ibm.com` work cross-origin with no extra configuration oneither side.+## Embed the pay button anywhere else++The whole flow is one drop-in script plus any element carrying a `data-x402-endpoint`. The+same eight lines that power the demo work standalone — drop them into a blog post, a docs+page, or a product page to add a working pay-per-call paywall with no framework, build step,+or SDK:++```html+<script type="module" src="https://three.ws/x402.js"></script>++<button+ data-x402-endpoint="https://three.ws/api/x402/symbol-availability?ticker=GRANITE"+ data-x402-merchant="three.ws"+ data-x402-action="Check symbol">+ Pay $0.001 & run+</button>+```++On click the script reads the endpoint's `402` challenge, opens the visitor's wallet for a+gasless USDC authorization, retries the call, and dispatches `x402:result` / `x402:error`+events with the response and on-chain receipt. Point `data-x402-endpoint` at any three.ws+x402 GET endpoint (browse them in the [Bazaar](https://three.ws/bazaar)) to charge for a+different call. The same Tier 1 / Tier 2 CSP guidance above applies to the host page.+## Note on brandingThe page uses a neutral "IBM · Business Partner" wordmark lockup. Confirm the exact mark anddiff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.htmlindex d1aea85e3..dac12aa92 100644--- a/pages/ibm/x402-demo.html+++ b/pages/ibm/x402-demo.html@@ -699,7 +699,7 @@ a:focus-visible{outline-offset:3px}var trigger = document.activeElement; // restore focus here when the modal closessetBusy(true);- setResultLoading('Opening wallet… approve the $0.001 USDC payment to continue.');+ setResultLoading('Waiting for your wallet… approve the $0.001 USDC payment to continue.');window.X402.pay({endpoint: ENDPOINT + '?ticker=' + encodeURIComponent(ticker),diff --git a/public/changelog.json b/public/changelog.jsonindex f2dd7996d..f87e916fc 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T12:17:39.896Z",+ "generated_at": "2026-06-17T12:30:50.548Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex 38a90b3bc..f101d97e3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T12:09:48.162Z",+ "generated_at": "2026-06-17T12:30:50.044Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/deploy-sniper.mjs b/scripts/deploy-sniper.mjsnew file mode 100644index 000000000..3a06149ce--- /dev/null+++ b/scripts/deploy-sniper.mjs@@ -0,0 +1,216 @@+#!/usr/bin/env node+/**+ * deploy-sniper.mjs — build, push, and deploy the agent-sniper worker to Cloud+ * Run, idempotently, following the house pattern (see deploy/world/*).+ *+ * The agent-sniper worker (workers/agent-sniper) is a long-lived background+ * process — it holds the PumpPortal feed open and snipes from agent wallets, so+ * it cannot run on Vercel. This script is the repeatable deploy:+ *+ * 1. verify gcloud is installed + authenticated+ * 2. enable the required GCP APIs (idempotent)+ * 3. ensure the runtime service account + the Artifact Registry repo exist+ * 4. preflight the secrets the service config mounts (warn if missing)+ * 5. build + push the image via Cloud Build (deploy/sniper/cloudbuild.yaml)+ * 6. deploy the service (deploy/sniper/cloudrun.yaml) — minScale=maxScale=1,+ * no CPU throttling, default SNIPER_MODE=simulate+ * 7. verify the worker reported a fresh heartbeat (proves it actually booted+ * and connected — not just that the revision rolled out)+ *+ * Usage:+ * node scripts/deploy-sniper.mjs # build + deploy (simulate)+ * node scripts/deploy-sniper.mjs --skip-build # redeploy current image only+ * node scripts/deploy-sniper.mjs --dry-run # print the gcloud commands, run nothing+ *+ * SIMULATE is the default and the only mode this script deploys. Going LIVE is a+ * deliberate, separate cutover — see deploy/sniper/README.md ("Cutover to live").+ * This script will NOT flip a service to live.+ *+ * Env (overridable):+ * GCP_PROJECT default aerial-vehicle-466722-p5 (the platform's Cloud Run project)+ * GCP_REGION default us-central1+ */++import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { existsSync } from 'node:fs';++const __dirname = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = resolve(__dirname, '..');++const PROJECT = process.env.GCP_PROJECT || 'aerial-vehicle-466722-p5';+const REGION = process.env.GCP_REGION || 'us-central1';+const REPO = 'workers'; // Artifact Registry repo (shared by the worker images)+const SERVICE = 'agent-sniper';+const RUNTIME_SA = `agent-sniper-sa@${PROJECT}.iam.gserviceaccount.com`;+const CLOUDBUILD = 'deploy/sniper/cloudbuild.yaml';+const CLOUDRUN = 'deploy/sniper/cloudrun.yaml';++// Secrets the cloudrun.yaml mounts. database-url + jwt-secret are mandatory;+// solana-rpc-url is required only for the live cutover; telegram-* enable ops+// alerting and are optional.+const REQUIRED_SECRETS = ['sniper-database-url', 'sniper-jwt-secret'];+const OPTIONAL_SECRETS = ['sniper-solana-rpc-url', 'telegram-bot-token', 'telegram-alerts-chat-id'];++const args = process.argv.slice(2);+const DRY_RUN = args.includes('--dry-run');+const SKIP_BUILD = args.includes('--skip-build');++const C = { cyan: '\x1b[1;36m', green: '\x1b[1;32m', yellow: '\x1b[1;33m', red: '\x1b[1;31m', reset: '\x1b[0m' };+const log = (m) => console.log(`${C.cyan}[deploy-sniper]${C.reset} ${m}`);+const ok = (m) => console.log(`${C.green}[deploy-sniper] ✓${C.reset} ${m}`);+const warn = (m) => console.warn(`${C.yellow}[deploy-sniper] !${C.reset} ${m}`);+const die = (m) => { console.error(`${C.red}[deploy-sniper] ERROR:${C.reset} ${m}`); process.exit(1); };++/** Run a command. Returns {status, stdout, stderr}. Honors --dry-run for mutating gcloud calls. */+function run(cmd, cmdArgs, { mutating = true, capture = false } = {}) {+ const pretty = `${cmd} ${cmdArgs.join(' ')}`;+ if (DRY_RUN && mutating) {+ console.log(`${C.yellow}[dry-run]${C.reset} ${pretty}`);+ return { status: 0, stdout: '', stderr: '' };+ }+ const res = spawnSync(cmd, cmdArgs, {+ cwd: REPO_ROOT,+ encoding: 'utf8',+ stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',+ });+ return { status: res.status ?? 1, stdout: res.stdout || '', stderr: res.stderr || '' };+}++function gcloud(cmdArgs, opts) {+ return run('gcloud', [...cmdArgs, `--project=${PROJECT}`], opts);+}++function preflight() {+ if (run('gcloud', ['version'], { mutating: false, capture: true }).status !== 0) {+ die('gcloud not found on PATH. Install the Cloud SDK: https://cloud.google.com/sdk/docs/install');+ }+ const token = run('gcloud', ['auth', 'print-access-token'], { mutating: false, capture: true });+ if (token.status !== 0) {+ die("gcloud is not authenticated — run 'gcloud auth login' (a deployer with Cloud Run + Cloud Build + Artifact Registry + Secret Manager access on " + PROJECT + ').');+ }+ for (const f of [CLOUDBUILD, CLOUDRUN, 'workers/agent-sniper/Dockerfile']) {+ if (!existsSync(resolve(REPO_ROOT, f))) die(`missing ${f} — run from the repo root`);+ }+ ok('gcloud authenticated; deploy artifacts present');+}++function enableApis() {+ log('enabling required APIs (idempotent)…');+ const r = gcloud(['services', 'enable',+ 'run.googleapis.com', 'cloudbuild.googleapis.com',+ 'artifactregistry.googleapis.com', 'secretmanager.googleapis.com',+ ]);+ if (r.status !== 0) die('failed to enable APIs (insufficient permission on ' + PROJECT + '?)');+ ok('APIs enabled');+}++function ensureServiceAccount() {+ const exists = gcloud(['iam', 'service-accounts', 'describe', RUNTIME_SA], { mutating: false, capture: true });+ if (exists.status === 0) { ok(`runtime SA exists: ${RUNTIME_SA}`); return; }+ log(`creating runtime SA ${RUNTIME_SA}…`);+ const r = gcloud(['iam', 'service-accounts', 'create', 'agent-sniper-sa',+ '--display-name=agent-sniper worker runtime']);+ if (r.status !== 0 && !DRY_RUN) warn('could not create the runtime SA (may already exist or lack permission) — verify it manually');+ else ok('runtime SA ready');+}++function ensureRepo() {+ const exists = gcloud(['artifacts', 'repositories', 'describe', REPO, `--location=${REGION}`],+ { mutating: false, capture: true });+ if (exists.status === 0) { ok(`Artifact Registry repo exists: ${REPO}`); return; }+ log(`creating Artifact Registry repo ${REPO} in ${REGION}…`);+ const r = gcloud(['artifacts', 'repositories', 'create', REPO,+ '--repository-format=docker', `--location=${REGION}`,+ '--description=three.ws long-lived worker images']);+ if (r.status !== 0 && !DRY_RUN) die('failed to create Artifact Registry repo');+ ok('Artifact Registry repo ready');+}++function checkSecrets() {+ log('checking mounted secrets…');+ for (const name of REQUIRED_SECRETS) {+ const r = gcloud(['secrets', 'describe', name], { mutating: false, capture: true });+ if (r.status !== 0) {+ die(`required secret "${name}" is missing. Create it (NEVER commit secrets):\n` ++ ` printf '%s' "$VALUE" | gcloud secrets create ${name} --data-file=- --project=${PROJECT}\n` ++ ` gcloud secrets add-iam-policy-binding ${name} --project=${PROJECT} \\\n` ++ ` --member=serviceAccount:${RUNTIME_SA} --role=roles/secretmanager.secretAccessor`);+ }+ ok(`secret present: ${name}`);+ }+ for (const name of OPTIONAL_SECRETS) {+ const r = gcloud(['secrets', 'describe', name], { mutating: false, capture: true });+ if (r.status !== 0) {+ warn(`optional secret "${name}" is missing — ${name === 'sniper-solana-rpc-url'+ ? 'REQUIRED before the live cutover (live mode refuses a public RPC)'+ : 'ops alerting via Telegram will be disabled'}.`);+ } else {+ ok(`secret present: ${name}`);+ }+ }+}++function build() {+ if (SKIP_BUILD) { warn('--skip-build: reusing the current :latest image'); return; }+ log('building + pushing image via Cloud Build (this can take several minutes)…');+ const r = gcloud(['builds', 'submit', `--config=${CLOUDBUILD}`, '.']);+ if (r.status !== 0) die('Cloud Build failed — see the build logs above');+ ok('image built + pushed');+}++function deploy() {+ log('deploying service (minScale=maxScale=1, no CPU throttling, mode=simulate)…');+ const r = gcloud(['run', 'services', 'replace', CLOUDRUN, `--region=${REGION}`]);+ if (r.status !== 0) die('gcloud run services replace failed');+ ok('service config applied');+}++async function verifyHeartbeat() {+ if (DRY_RUN) { warn('--dry-run: skipping heartbeat verification'); return; }+ if (!process.env.DATABASE_URL) {+ warn('DATABASE_URL not set locally — cannot verify the heartbeat from here.');+ warn(`Verify the worker is live with: curl -s https://three.ws/api/sniper/status`);+ warn('Or read the logs: gcloud run services logs read agent-sniper --region=' + REGION + ' --project=' + PROJECT);+ return;+ }+ log('waiting for the worker to report a fresh heartbeat…');+ const { sql } = await import('../api/_lib/db.js');+ const deadline = Date.now() + 90_000;+ while (Date.now() < deadline) {+ try {+ const [beat] = await sql`SELECT mode, last_beat_at, meta FROM bot_heartbeat WHERE worker = 'agent-sniper' LIMIT 1`;+ if (beat) {+ const ageMs = Date.now() - new Date(beat.last_beat_at).getTime();+ if (ageMs < 90_000) {+ const meta = beat.meta || {};+ ok(`heartbeat fresh (${Math.round(ageMs / 1000)}s) — mode=${beat.mode} feedConnected=${meta.feedConnected} strategies=${meta.strategies}`);+ return;+ }+ }+ } catch (e) {+ warn('heartbeat probe error (will retry): ' + (e?.message || e));+ }+ await new Promise((r) => setTimeout(r, 5_000));+ }+ warn('no fresh heartbeat within 90s. The revision rolled out but the worker may still be booting (image pull + SDK build) or wedged.');+ warn('Check logs: gcloud run services logs read agent-sniper --region=' + REGION + ' --project=' + PROJECT);+}++async function main() {+ log(`project=${PROJECT} region=${REGION} service=${SERVICE} mode=simulate${DRY_RUN ? ' [DRY-RUN]' : ''}`);+ preflight();+ enableApis();+ ensureServiceAccount();+ ensureRepo();+ checkSecrets();+ build();+ deploy();+ await verifyHeartbeat();+ ok('done. Worker deployed in SIMULATE mode (zero spend).');+ log('Live cutover (gated): see deploy/sniper/README.md → "Cutover to live".');+ log('Status surface: https://three.ws/api/sniper/status');+}++main().catch((e) => die(e?.stack || e?.message || String(e)));diff --git a/scripts/verify-embed-avatar-ux.mjs b/scripts/verify-embed-avatar-ux.mjsnew file mode 100644index 000000000..062cda15e--- /dev/null+++ b/scripts/verify-embed-avatar-ux.mjs@@ -0,0 +1,160 @@+// Verify the embedded-avatar UX (Task 5): loading skeleton, error fallback,+// reduced-motion static pose, loop-honoring playback, portrait/full framing,+// and offscreen render pause — all driven by the LOCAL <agent-3d> component+// (src/element.js), not the deployed CDN bundle.+//+// BASE_URL=http://localhost:5191 node scripts/verify-embed-avatar-ux.mjs+//+// Writes a throwaway page under public/, exercises it, and deletes it.+import { chromium } from 'playwright';+import { writeFileSync, rmSync, mkdirSync } from 'fs';++const BASE = process.env.BASE_URL || 'http://localhost:5191';+const TMP = 'public/_tmp-avatar-ux.html';+const CZ = '/avatars/cz.glb';+const MICHELLE = '/avatars/michelle.glb';+const BAD = '/avatars/__does_not_exist__.glb';++const PAGE = `<!doctype html><html><head><meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<style>+ body { margin:0; background:#0b0d10; font-family:system-ui; }+ .grid { display:grid; grid-template-columns:repeat(2,1fr); gap:16px; padding:16px; }+ .card { position:relative; aspect-ratio:16/9; border:1px solid #222; border-radius:8px; overflow:hidden; background:#111; }+ .card agent-3d { position:absolute; inset:0; width:100%; height:100%; }+ .spacer { height:3000px; }+ #offscreen { position:relative; height:240px; border:1px solid #222; margin:16px; }+ #offscreen agent-3d { position:absolute; inset:0; width:100%; height:100%; }+</style></head><body>+<div class="grid">+ <div class="card"><agent-3d id="loopAv" body="${CZ}" framing="portrait" clip="rumba" kiosk avatar-chat="off" background="transparent" eager></agent-3d></div>+ <div class="card"><agent-3d id="oneshotAv" body="${MICHELLE}" framing="portrait" clip="wave" kiosk avatar-chat="off" background="transparent" eager></agent-3d></div>+ <div class="card"><agent-3d id="fullAv" body="${CZ}" framing="full" clip="idle" kiosk avatar-chat="off" background="transparent" eager></agent-3d></div>+ <div class="card"><agent-3d id="badAv" body="${BAD}" framing="portrait" kiosk avatar-chat="off" background="transparent" eager></agent-3d></div>+</div>+<div class="spacer"></div>+<div id="offscreen"><agent-3d id="bottomAv" body="${CZ}" framing="portrait" clip="idle" kiosk avatar-chat="off" background="transparent" eager></agent-3d></div>+<script type="module">+ window.__ready = {};+ window.__error = {};+ import('/src/element.js').then(() => {+ for (const el of document.querySelectorAll('agent-3d')) {+ el.addEventListener('agent:ready', () => { window.__ready[el.id] = true; });+ el.addEventListener('agent:error', (e) => { window.__error[el.id] = (e.detail?.error?.message || String(e.detail?.error) || 'error'); });+ }+ });+</script>+</body></html>`;++mkdirSync('reports', { recursive: true });+writeFileSync(TMP, PAGE);++const out = [];+const log = (...a) => { out.push(a.join(' ')); console.log(...a); };+let failures = 0;+const assert = (cond, label, extra = '') => {+ log(`${cond ? 'PASS' : 'FAIL'} ${label}${extra ? ' — ' + extra : ''}`);+ if (!cond) failures++;+};++const browser = await chromium.launch();++async function inspect(page, id) {+ return page.evaluate((id) => {+ const el = document.getElementById(id);+ if (!el || !el.shadowRoot) return null;+ const sr = el.shadowRoot;+ const am = el._viewer?.animationManager;+ return {+ hasSkeleton: !!sr.querySelector('.skeleton'),+ loadingHidden: !!sr.querySelector('.loading')?.hidden,+ hasFallback: !!sr.querySelector('.fallback'),+ framing: el._viewer?.options?.framing ?? null,+ currentClip: am?.currentName ?? null,+ currentActionNull: am ? am.currentAction === null : null,+ visible: el._viewer?._visible ?? null,+ rafNull: el._viewer ? el._viewer._rafId === null : null,+ ready: !!window.__ready[id],+ error: window.__error[id] || null,+ };+ }, id);+}++// ── 1. Normal motion context: framing, loading, error, loop-honoring ──────────+{+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });+ const page = await ctx.newPage();+ const problems = [];+ page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') problems.push(`[${m.type()}] ${m.text()}`); });+ page.on('pageerror', (e) => problems.push(`[pageerror] ${e.message}`));++ await page.goto(`${BASE}/_tmp-avatar-ux.html`, { waitUntil: 'domcontentloaded', timeout: 60000 });+ // Skeleton should be visible immediately while the GLB streams.+ await page.waitForTimeout(150);+ const earlyLoop = await inspect(page, 'loopAv');+ assert(earlyLoop?.hasSkeleton, 'loading skeleton present in shadow DOM');++ // Wait for the good avatars to be ready and the bad one to error.+ await page.waitForFunction(() => window.__ready.loopAv && window.__ready.fullAv && (window.__error.badAv || window.__ready.badAv), null, { timeout: 30000 }).catch(() => {});+ await page.waitForTimeout(2500);++ const loop = await inspect(page, 'loopAv');+ const full = await inspect(page, 'fullAv');+ const bad = await inspect(page, 'badAv');+ const oneshot = await inspect(page, 'oneshotAv');++ assert(loop?.framing === 'portrait', 'portrait framing applied (loopAv)', `framing=${loop?.framing}`);+ assert(full?.framing === 'full', 'full framing applied (fullAv)', `framing=${full?.framing}`);+ assert(loop?.loadingHidden === true, 'skeleton hidden after ready (loopAv)');+ assert(loop?.currentClip === 'rumba', 'loop clip honored — rumba is current (loopAv)', `current=${loop?.currentClip}`);+ assert(full?.currentClip === 'idle', 'idle loop current (fullAv)', `current=${full?.currentClip}`);+ assert(!!bad?.hasFallback, 'error → decoration fallback silhouette shown (badAv)', `error=${bad?.error}`);+ assert(!!bad?.error, 'agent:error dispatched for bad GLB (badAv)');+ log(`info oneshot current clip after settle window: ${oneshot?.currentClip}`);++ // Responsive screenshots.+ for (const w of [320, 768, 1440]) {+ await page.setViewportSize({ width: w, height: Math.round(w * 1.4) });+ await page.waitForTimeout(700);+ await page.screenshot({ path: `reports/avatar-ux-${w}.png` });+ log(`screenshot → reports/avatar-ux-${w}.png (${w}px)`);+ }++ // Offscreen pause: bottomAv is far below the fold at the top scroll position.+ await page.setViewportSize({ width: 1440, height: 900 });+ await page.evaluate(() => window.scrollTo(0, 0));+ await page.waitForTimeout(900);+ const bottom = await inspect(page, 'bottomAv');+ assert(bottom?.visible === false, 'offscreen avatar marked not-visible (bottomAv)', `visible=${bottom?.visible}`);+ assert(bottom?.rafNull === true, 'offscreen avatar paused its render loop (rafId null)', `rafNull=${bottom?.rafNull}`);+ // Scroll it into view → resumes.+ await page.locator('#bottomAv').scrollIntoViewIfNeeded();+ await page.waitForTimeout(700);+ const bottomAfter = await inspect(page, 'bottomAv');+ assert(bottomAfter?.visible === true, 'avatar resumes rendering when scrolled back in (bottomAv)', `visible=${bottomAfter?.visible}`);++ const realProblems = problems.filter((p) => !/WebSocket|\[vite\]|favicon|404 \(Not Found\)|__does_not_exist__|ReadPixels|GL Driver|Failed to load resource/.test(p));+ log(`\nconsole errors/warnings (filtered): ${realProblems.length}`);+ realProblems.slice(0, 12).forEach((p) => log(' ' + p));+ await ctx.close();+}++// ── 2. Reduced-motion context: avatar holds a static pose, no looping ─────────+{+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' });+ const page = await ctx.newPage();+ await page.goto(`${BASE}/_tmp-avatar-ux.html`, { waitUntil: 'domcontentloaded', timeout: 60000 });+ await page.waitForFunction(() => window.__ready.loopAv, null, { timeout: 30000 }).catch(() => {});+ await page.waitForTimeout(2500);+ const loop = await inspect(page, 'loopAv');+ // Under reduced motion the decoration freezes: the active action is released+ // (currentAction === null) so the render loop can settle — no looping motion.+ assert(loop?.currentActionNull === true, 'reduced-motion: avatar holds a static pose (no active looping action)', `currentActionNull=${loop?.currentActionNull}`);+ await ctx.close();+}++await browser.close();+rmSync(TMP, { force: true });++log(`\n${failures === 0 ? '✅ ALL CHECKS PASSED' : `❌ ${failures} CHECK(S) FAILED`}`);+process.exit(failures === 0 ? 0 : 1);diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.jsnew file mode 100644index 000000000..e7d440633--- /dev/null+++ b/src/agent-wallet-hub/index.js@@ -0,0 +1,316 @@+/**+ * Agent Wallet hub — the single product home for an agent's self-custodied+ * Solana wallet. Tabbed: Balance · Deposit · Trade · Snipe · Pay · Withdraw.+ *+ * This file owns the shell: layout, the agent header (name + wallet-readiness),+ * the network selector, the accessible tab strip, and the shared context handed+ * to every tab. The tabs themselves live in ./tabs/*.js and self-register via+ * ./registry.js — adding a tab is a new file + one import below, never an edit+ * to a shared list.+ *+ * Balance is fully built (this task). Deposit/Trade/Snipe/Pay/Withdraw ship as+ * honest "coming online" placeholders that later tasks (02/04/06/08/09) replace+ * by overwriting their own tab file.+ *+ * Reachable from the agent profile and the create-agent success screen as+ * `/agent/:id/wallet` (or `?id=`). Owner sees management tabs; a visitor gets a+ * read-only view (Balance + Deposit only).+ */++import { getVisibleTabs } from './registry.js';++// Tab modules — importing each one runs its registerWalletTab() side effect.+// To add a tab later: drop a file in ./tabs/ and add one import line here.+import './tabs/balance.js';+import './tabs/deposit.js';+import './tabs/trade.js';+import './tabs/snipe.js';+import './tabs/pay.js';+import './tabs/withdraw.js';++import { escapeHtml, shortAddress, copyToClipboard, toast } from './util.js';++const STYLE_ID = 'agent-wallet-hub-style';+const STYLE = `+.awh { --awh-gap: var(--space-4, 16px); display: flex; flex-direction: column; gap: var(--awh-gap); max-width: 760px; margin: 0 auto; }+.awh-header { display: flex; align-items: center; gap: var(--space-3, 12px); flex-wrap: wrap; }+.awh-avatar { width: 44px; height: 44px; border-radius: var(--radius-md, 10px); object-fit: cover; background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); flex: none; }+.awh-id { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+.awh-name { font-family: var(--font-display, system-ui); font-size: var(--text-lg, 1.236rem); font-weight: 600; color: var(--ink-bright, #fff); margin: 0; line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 46vw; }+.awh-sub { font-size: var(--text-sm, .764rem); color: var(--ink-dim, #888); display: flex; align-items: center; gap: var(--space-2, 8px); flex-wrap: wrap; }+.awh-sub a { color: inherit; text-decoration: none; border-bottom: 1px dotted currentColor; }+.awh-sub a:hover { color: var(--ink, #e8e8e8); }+.awh-ready { display: inline-flex; align-items: center; gap: 5px; font-size: var(--text-2xs, .6875rem); font-weight: 600; padding: 2px 8px; border-radius: var(--radius-pill, 999px); border: 1px solid transparent; }+.awh-ready::before { content: ''; width: 7px; height: 7px; border-radius: 50%; flex: none; }+.awh-ready[data-state="ready"] { color: var(--success, #4ade80); background: color-mix(in srgb, var(--success, #4ade80) 14%, transparent); border-color: color-mix(in srgb, var(--success, #4ade80) 35%, transparent); }+.awh-ready[data-state="ready"]::before { background: var(--success, #4ade80); box-shadow: 0 0 6px color-mix(in srgb, var(--success,#4ade80) 60%, transparent); }+.awh-ready[data-state="preparing"] { color: var(--warn, #fbbf24); background: color-mix(in srgb, var(--warn, #fbbf24) 12%, transparent); border-color: color-mix(in srgb, var(--warn, #fbbf24) 32%, transparent); }+.awh-ready[data-state="preparing"]::before { background: var(--warn, #fbbf24); animation: awh-pulse 1.3s ease-in-out infinite; }+.awh-net { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-sm, .764rem); color: var(--ink-dim, #888); }+.awh-net select { font: inherit; color: var(--ink, #e8e8e8); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-sm, 6px); padding: 4px 8px; cursor: pointer; }+.awh-net select:focus-visible { outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, #fff); outline-offset: var(--focus-ring-offset, 2px); }++.awh-tabs { display: flex; gap: 2px; overflow-x: auto; scrollbar-width: thin; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.08)); padding-bottom: 0; -webkit-overflow-scrolling: touch; }+.awh-tab { appearance: none; font: inherit; font-size: var(--text-md, .8125rem); font-weight: 500; color: var(--ink-dim, #888); background: transparent; border: none; border-bottom: 2px solid transparent; padding: 10px 14px; cursor: pointer; white-space: nowrap; transition: color var(--duration-fast, 140ms) var(--ease-standard, ease), border-color var(--duration-fast, 140ms) var(--ease-standard, ease), background var(--duration-fast, 140ms) var(--ease-standard, ease); border-radius: var(--radius-sm, 6px) var(--radius-sm, 6px) 0 0; }+.awh-tab:hover { color: var(--ink, #e8e8e8); background: var(--surface-1, rgba(255,255,255,.03)); }+.awh-tab[aria-selected="true"] { color: var(--ink-bright, #fff); border-bottom-color: var(--accent, #fff); }+.awh-tab:focus-visible { outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, #fff); outline-offset: -2px; }++.awh-panel { animation: awh-fade var(--duration-base, 220ms) var(--ease-out, ease); }+.awh-panel[hidden] { display: none; }++/* Shared card + control vocabulary for tabs to reuse. */+.awh-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,.03)); padding: var(--space-4, 16px) var(--space-5, 20px); }+.awh-card + .awh-card { margin-top: var(--awh-gap); }+.awh-card-h { font-size: var(--text-2xs, .6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim, #888); margin: 0 0 var(--space-3, 12px); display: flex; align-items: center; gap: 8px; }+.awh-btn { appearance: none; font: inherit; font-size: var(--text-md, .8125rem); color: var(--ink, #e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: 8px 14px; cursor: pointer; transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms), transform var(--duration-instant,80ms); }+.awh-btn:hover:not(:disabled) { background: var(--surface-3, rgba(255,255,255,.08)); border-color: var(--stroke-strong, rgba(255,255,255,.14)); }+.awh-btn:active:not(:disabled) { transform: translateY(1px); }+.awh-btn:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: var(--focus-ring-offset,2px); }+.awh-btn:disabled { opacity: var(--disabled-opacity, .4); cursor: var(--disabled-cursor, not-allowed); }+.awh-btn--primary { background: var(--accent, #fff); color: #0a0a0a; border-color: var(--accent, #fff); font-weight: 600; }+.awh-btn--primary:hover:not(:disabled) { background: color-mix(in srgb, var(--accent,#fff) 88%, #000); }+.awh-mono { font-family: var(--font-mono, ui-monospace, monospace); }+.awh-empty { color: var(--ink-dim, #888); font-size: var(--text-sm, .764rem); padding: var(--space-3,12px) 0; }+.awh-placeholder { display: flex; flex-direction: column; align-items: flex-start; gap: var(--space-3,12px); }+.awh-placeholder-badge { font-size: var(--text-2xs,.6875rem); font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 12%, transparent); border: 1px solid color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); border-radius: var(--radius-pill,999px); padding: 3px 10px; }+.awh-placeholder p { margin: 0; color: var(--ink-dim,#888); font-size: var(--text-md,.8125rem); line-height: 1.5; }++.awh-toast { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%) translateY(8px); background: var(--bg-1, #1a1a1a); color: var(--ink-bright,#fff); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-md,10px); padding: 10px 16px; font-size: var(--text-md,.8125rem); box-shadow: var(--shadow-3, 0 8px 32px rgba(0,0,0,.5)); opacity: 0; pointer-events: none; transition: opacity var(--duration-base,220ms), transform var(--duration-base,220ms); z-index: 9999; }+.awh-toast[data-show="true"] { opacity: 1; transform: translateX(-50%) translateY(0); }++@keyframes awh-fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }+@keyframes awh-pulse { 0%,100% { opacity: 1; } 50% { opacity: .35; } }+@media (prefers-reduced-motion: reduce) { .awh-panel, .awh-ready[data-state="preparing"]::before, .awh-toast { animation: none; transition: none; } }++@media (max-width: 520px) {+ .awh-name { max-width: 60vw; }+ .awh-net { margin-left: 0; flex-basis: 100%; }+ .awh-tab { padding: 10px 11px; font-size: var(--text-sm,.764rem); }+}+`;++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = STYLE_ID;+ tag.textContent = STYLE;+ document.head.appendChild(tag);+}++/**+ * Mount the Agent Wallet hub into a container.+ *+ * @param {object} opts+ * @param {HTMLElement} opts.mount — container element+ * @param {object} opts.agent — agent record (id, name, avatar_*, walletReady, solana_address, is_owner)+ * @param {string} [opts.initialTab] — tab id to open first (defaults to URL hash or 'balance')+ * @param {(net: string) => void} [opts.onNetworkChange]+ * @returns {{ destroy: () => void, refresh: () => void, openTab: (id: string) => void }}+ */+export function mountAgentWalletHub({ mount, agent, initialTab, onNetworkChange } = {}) {+ if (!mount || !agent?.id) {+ throw new Error('mountAgentWalletHub requires { mount, agent.id }');+ }+ injectStyle();++ const isOwner = !!(agent.is_owner ?? agent.isOwner);+ let network = 'mainnet';+ const networkListeners = new Set();+ if (typeof onNetworkChange === 'function') networkListeners.add(onNetworkChange);++ // Shared context handed to every tab — the only surface tabs depend on.+ const ctx = {+ agentId: agent.id,+ agent,+ isOwner,+ get network() {+ return network;+ },+ getNetwork: () => network,+ onNetworkChange: (fn) => {+ if (typeof fn === 'function') networkListeners.add(fn);+ return () => networkListeners.delete(fn);+ },+ escapeHtml,+ shortAddress,+ copyToClipboard,+ toast,+ };++ const tabs = getVisibleTabs(isOwner);+ const validIds = new Set(tabs.map((t) => t.id));+ const hashTab = (location.hash || '').replace(/^#/, '');+ let activeId =+ (initialTab && validIds.has(initialTab) && initialTab) ||+ (validIds.has(hashTab) && hashTab) ||+ (tabs[0]?.id ?? null);++ const ready = !!(agent.walletReady ?? agent.wallet_ready);+ const profileUrl = agent.home_url || `/agent/${agent.id}`;++ mount.innerHTML = `+ <section class="awh" aria-label="Agent wallet">+ <header class="awh-header">+ ${+ agent.avatar_thumbnail_url || agent.avatar_model_url+ ? `<img class="awh-avatar" src="${escapeHtml(agent.avatar_thumbnail_url || '')}" alt="" loading="lazy" onerror="this.remove()" />`+ : '<div class="awh-avatar" aria-hidden="true"></div>'+ }+ <div class="awh-id">+ <h1 class="awh-name" title="${escapeHtml(agent.name || 'Agent')}">${escapeHtml(agent.name || 'Agent')} wallet</h1>+ <div class="awh-sub">+ <span class="awh-ready" data-state="${ready ? 'ready' : 'preparing'}" role="status">+ ${ready ? 'Wallet ready' : 'Preparing wallet…'}+ </span>+ <a href="${escapeHtml(profileUrl)}">View agent profile</a>+ </div>+ </div>+ <label class="awh-net">+ Network+ <select data-awh="network" aria-label="Solana network">+ <option value="mainnet">Mainnet</option>+ <option value="devnet">Devnet</option>+ </select>+ </label>+ </header>++ <div class="awh-tabs" role="tablist" aria-label="Wallet sections">+ ${tabs+ .map(+ (t, i) => `+ <button class="awh-tab" role="tab" type="button"+ id="awh-tab-${escapeHtml(t.id)}"+ data-awh-tab="${escapeHtml(t.id)}"+ aria-controls="awh-panel-${escapeHtml(t.id)}"+ aria-selected="${t.id === activeId ? 'true' : 'false'}"+ tabindex="${t.id === activeId ? '0' : '-1'}">${escapeHtml(t.label)}</button>`,+ )+ .join('')}+ </div>++ ${tabs+ .map(+ (t) => `+ <div class="awh-panel" role="tabpanel"+ id="awh-panel-${escapeHtml(t.id)}"+ aria-labelledby="awh-tab-${escapeHtml(t.id)}"+ data-awh-panel="${escapeHtml(t.id)}"+ ${t.id === activeId ? '' : 'hidden'}></div>`,+ )+ .join('')}+ </section>+ `;++ const netSelect = mount.querySelector('[data-awh="network"]');+ const tabButtons = [...mount.querySelectorAll('[data-awh-tab]')];+ const panelFor = (id) => mount.querySelector(`[data-awh-panel="${CSS.escape(id)}"]`);++ // Lazy-mount each tab on first activation; keep the instance so onShow/onHide+ // and destroy can fire. A tab mount that throws degrades to an inline error+ // rather than breaking the whole hub.+ const instances = new Map();+ function ensureMounted(id) {+ if (instances.has(id)) return instances.get(id);+ const panel = panelFor(id);+ const def = tabs.find((t) => t.id === id);+ if (!panel || !def) return null;+ let inst = null;+ try {+ inst = def.mount({ panel, ctx }) || {};+ } catch (err) {+ console.error(`[agent-wallet-hub] tab "${id}" failed to mount`, err);+ panel.innerHTML = `<div class="awh-card"><p class="awh-empty">This section could not load. <button class="awh-btn" type="button" data-awh-retry="${escapeHtml(id)}">Retry</button></p></div>`;+ panel.querySelector('[data-awh-retry]')?.addEventListener('click', () => {+ instances.delete(id);+ ensureMounted(id);+ panelFor(id)?.querySelector('[data-awh-tab]'); // no-op guard+ const fresh = instances.get(id);+ fresh?.onShow?.();+ });+ inst = {};+ }+ instances.set(id, inst);+ return inst;+ }++ function openTab(id) {+ if (!validIds.has(id) || id === activeId) {+ // still ensure the requested (or current) tab is mounted + shown+ if (validIds.has(id)) {+ ensureMounted(id)?.onShow?.();+ }+ return;+ }+ const prev = activeId;+ activeId = id;+ for (const btn of tabButtons) {+ const on = btn.dataset.awhTab === id;+ btn.setAttribute('aria-selected', on ? 'true' : 'false');+ btn.tabIndex = on ? 0 : -1;+ }+ for (const t of tabs) {+ const panel = panelFor(t.id);+ if (panel) panel.hidden = t.id !== id;+ }+ if (prev && instances.has(prev)) instances.get(prev)?.onHide?.();+ ensureMounted(id)?.onShow?.();+ try {+ history.replaceState(null, '', `#${id}`);+ } catch {+ /* hash update best-effort */+ }+ }++ // Tab strip interactions: click + full roving-tabindex keyboard nav.+ for (const btn of tabButtons) {+ btn.addEventListener('click', () => openTab(btn.dataset.awhTab));+ }+ mount.querySelector('.awh-tabs')?.addEventListener('keydown', (e) => {+ const idx = tabButtons.findIndex((b) => b.dataset.awhTab === activeId);+ if (idx < 0) return;+ let next = -1;+ if (e.key === 'ArrowRight') next = (idx + 1) % tabButtons.length;+ else if (e.key === 'ArrowLeft') next = (idx - 1 + tabButtons.length) % tabButtons.length;+ else if (e.key === 'Home') next = 0;+ else if (e.key === 'End') next = tabButtons.length - 1;+ if (next < 0) return;+ e.preventDefault();+ const btn = tabButtons[next];+ openTab(btn.dataset.awhTab);+ btn.focus();+ });++ netSelect?.addEventListener('change', () => {+ network = netSelect.value === 'devnet' ? 'devnet' : 'mainnet';+ for (const fn of networkListeners) {+ try {+ fn(network);+ } catch (err) {+ console.error('[agent-wallet-hub] network listener failed', err);+ }+ }+ });++ // Mount + show the initial tab.+ if (activeId) ensureMounted(activeId)?.onShow?.();++ function destroy() {+ for (const inst of instances.values()) {+ try {+ inst?.destroy?.();+ } catch {+ /* tab teardown best-effort */+ }+ }+ instances.clear();+ networkListeners.clear();+ mount.innerHTML = '';+ }++ return {+ destroy,+ openTab,+ refresh: () => instances.get(activeId)?.onShow?.(),+ };+}diff --git a/src/agent-wallet-hub/registry.js b/src/agent-wallet-hub/registry.jsnew file mode 100644index 000000000..12df9a05c--- /dev/null+++ b/src/agent-wallet-hub/registry.js@@ -0,0 +1,57 @@+/**+ * Agent Wallet hub — tab registry.+ *+ * The hub is built so each tab self-registers in ITS OWN file. A later task+ * (deposit/trade/snipe/pay/withdraw) ships its tab by:+ * 1. writing `src/agent-wallet-hub/tabs/<name>.js` that calls+ * `registerWalletTab({ ... })` at import time, and+ * 2. importing that file once from `src/agent-wallet-hub/index.js`.+ *+ * It never edits a shared array of tab definitions — registration is a side+ * effect of importing the tab module. `order` keeps the tab strip stable+ * regardless of import order.+ *+ * A tab definition:+ * {+ * id: 'balance', // unique, used in the URL hash + data attrs+ * label: 'Balance', // tab strip text+ * order: 10, // ascending sort key+ * ownerOnly: false, // hide from non-owner (read-only) viewers+ * mount({ panel, ctx }) { ... return { destroy?, onShow?, onHide? } }+ * }+ *+ * `ctx` (shared hub context) gives every tab the same primitives:+ * { agentId, isOwner, network, getNetwork, onNetworkChange, escapeHtml,+ * shortAddress, copyToClipboard, toast }+ */++const _tabs = new Map();++/**+ * Register a wallet hub tab. Idempotent per id (HMR / double-import safe): a+ * later registration with the same id replaces the earlier one.+ * @param {{ id: string, label: string, order?: number, ownerOnly?: boolean,+ * mount: (args: { panel: HTMLElement, ctx: object }) => (object|void) }} def+ */+export function registerWalletTab(def) {+ if (!def || !def.id || typeof def.mount !== 'function') {+ throw new Error('registerWalletTab requires { id, label, mount }');+ }+ _tabs.set(def.id, {+ id: def.id,+ label: def.label || def.id,+ order: Number.isFinite(def.order) ? def.order : 100,+ ownerOnly: !!def.ownerOnly,+ mount: def.mount,+ });+}++/** All registered tabs, sorted by `order` then label. */+export function getRegisteredTabs() {+ return [..._tabs.values()].sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));+}++/** The tabs a given viewer may see (owner-only tabs hidden from visitors). */+export function getVisibleTabs(isOwner) {+ return getRegisteredTabs().filter((t) => isOwner || !t.ownerOnly);+}diff --git a/src/agent-wallet-hub/tabs/_placeholder.js b/src/agent-wallet-hub/tabs/_placeholder.jsnew file mode 100644index 000000000..4569ff1e0--- /dev/null+++ b/src/agent-wallet-hub/tabs/_placeholder.js@@ -0,0 +1,54 @@+/**+ * Agent Wallet hub — placeholder tab factory.+ *+ * The Balance tab ships fully built in this task. Deposit, Trade, Snipe, Pay, and+ * Withdraw are honest "coming online" placeholders that the later epic tasks+ * (02/04/06/08/09) replace by overwriting their own tab file. Each placeholder is+ * a real, designed empty-state — it tells the user exactly what the section will+ * do and that it is arriving, never a blank void or a fake/disabled control.+ */++import { registerWalletTab } from '../registry.js';++const PH_STYLE_ID = 'awh-placeholder-style';+const PH_STYLE = `+.awh-ph { display: flex; flex-direction: column; align-items: flex-start; gap: var(--space-3,12px); }+.awh-ph-icon { width: 38px; height: 38px; border-radius: var(--radius-md,10px); display: grid; place-items: center; background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); font-size: 18px; }+.awh-ph h2 { margin: 0; font-size: var(--text-lg,1.236rem); color: var(--ink-bright,#fff); font-family: var(--font-display, system-ui); }+.awh-ph p { margin: 0; color: var(--ink-dim,#888); font-size: var(--text-md,.8125rem); line-height: var(--leading-normal,1.618); max-width: 52ch; }+`;+function injectPlaceholderStyle() {+ if (typeof document === 'undefined' || document.getElementById(PH_STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = PH_STYLE_ID;+ tag.textContent = PH_STYLE;+ document.head.appendChild(tag);+}++/**+ * Register a "coming online" placeholder tab.+ * @param {{ id, label, order, ownerOnly?, icon, title, body }} def+ */+export function registerPlaceholderTab(def) {+ registerWalletTab({+ id: def.id,+ label: def.label,+ order: def.order,+ ownerOnly: !!def.ownerOnly,+ mount({ panel, ctx }) {+ injectPlaceholderStyle();+ const { escapeHtml } = ctx;+ panel.innerHTML = `+ <div class="awh-card">+ <div class="awh-ph">+ <div class="awh-ph-icon" aria-hidden="true">${escapeHtml(def.icon || '◎')}</div>+ <span class="awh-placeholder-badge">Coming online</span>+ <h2>${escapeHtml(def.title)}</h2>+ <p>${escapeHtml(def.body)}</p>+ </div>+ </div>+ `;+ return {};+ },+ });+}diff --git a/src/agent-wallet-hub/tabs/balance.js b/src/agent-wallet-hub/tabs/balance.jsnew file mode 100644index 000000000..cd97a8aba--- /dev/null+++ b/src/agent-wallet-hub/tabs/balance.js@@ -0,0 +1,310 @@+/**+ * Agent Wallet hub — Balance tab (fully built).+ *+ * Live SOL balance + USD estimate, recent on-chain activity, manual refresh, and+ * a 30s poll while visible. Every state is designed: skeleton loading, populated,+ * empty (no balance / no activity), and a "balance unavailable" RPC-failure state+ * that retries rather than showing a misleading 0 or a thrown error.+ *+ * All balances are real, read from GET /api/agents/:id/solana (and …/activity) —+ * the same live-RPC path with failover + 60s server cache used elsewhere. No+ * hardcoded or sample balances.+ */++import { registerWalletTab } from '../registry.js';+import { fetchAgentSolanaWallet, fetchAgentSolanaActivity } from '../../agent-solana-wallet.js';+import { solToUsd } from '../../shared/usd-price.js';+import { formatSol, timeAgo, explorerAddressUrl, explorerTxUrl } from '../util.js';++const POLL_MS = 30_000;++const BAL_STYLE_ID = 'awh-balance-style';+const BAL_STYLE = `+.awh-bal-top { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-3,12px); }+.awh-bal-amount { font-family: var(--font-display, system-ui); font-size: var(--text-xl, 1.618rem); font-weight: 700; color: var(--ink-bright,#fff); line-height: 1.1; }+.awh-bal-amount.is-unavailable { font-size: var(--text-md,.8125rem); font-weight: 600; color: var(--warn,#fbbf24); cursor: help; }+.awh-bal-usd { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top: 4px; }+.awh-bal-refresh { flex: none; }+.awh-bal-addr { display: flex; align-items: center; gap: var(--space-2,8px); margin-top: var(--space-4,16px); flex-wrap: wrap; }+.awh-bal-addr .awh-mono { font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); padding: 6px 9px; border-radius: var(--radius-sm,6px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); }+.awh-bal-mini { padding: 6px 10px; font-size: var(--text-sm,.764rem); text-decoration: none; }+.awh-bal-note { margin-top: var(--space-3,12px); font-size: var(--text-sm,.764rem); color: var(--warn,#fbbf24); }++.awh-act-list { list-style: none; margin: 0; padding: 0; }+.awh-act-row { display: flex; align-items: center; gap: var(--space-3,12px); padding: 9px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); font-size: var(--text-sm,.764rem); }+.awh-act-row:last-child { border-bottom: none; }+.awh-act-sig { color: var(--ink,#e8e8e8); text-decoration: none; }+.awh-act-sig:hover { text-decoration: underline; }+.awh-act-meta { color: var(--ink-dim,#888); flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.awh-act-delta { font-family: var(--font-mono, ui-monospace, monospace); flex: none; }+.awh-act-delta.is-pos { color: var(--success,#4ade80); }+.awh-act-delta.is-neg { color: var(--danger,#f87171); }++.awh-bal-skelbar, .awh-act-skel span { background: var(--surface-2, rgba(255,255,255,.05)); border-radius: var(--radius-sm,6px); animation: awh-skel 1.4s ease-in-out infinite; }+.awh-bal-skelbar--lg { height: 28px; width: 42%; margin-bottom: 10px; }+.awh-bal-skelbar--sm { height: 14px; width: 26%; margin-bottom: 18px; }+.awh-bal-skelbar--row { height: 34px; width: 60%; }+.awh-act-skel { display: flex; flex-direction: column; gap: 10px; }+.awh-act-skel span { height: 16px; width: 100%; }+.awh-act-skel span:nth-child(2) { width: 80%; }+.awh-act-skel span:nth-child(3) { width: 88%; }+@keyframes awh-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }+@media (prefers-reduced-motion: reduce) { .awh-bal-skelbar, .awh-act-skel span { animation: none; } }+`;+function injectBalanceStyle() {+ if (typeof document === 'undefined' || document.getElementById(BAL_STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = BAL_STYLE_ID;+ tag.textContent = BAL_STYLE;+ document.head.appendChild(tag);+}++registerWalletTab({+ id: 'balance',+ label: 'Balance',+ order: 10,+ ownerOnly: false,+ mount({ panel, ctx }) {+ const { escapeHtml, shortAddress, copyToClipboard, toast } = ctx;+ let pollTimer = null;+ let detachNet = null;+ let visible = false;+ let destroyed = false;++ const state = {+ loaded: false,+ address: ctx.agent.solana_address || ctx.agent.meta?.solana_address || null,+ sol: null,+ usd: null,+ balanceError: null,+ activity: null,+ activityError: null,+ activityLoaded: false,+ refreshing: false,+ };++ function render() {+ if (destroyed) return;+ if (!state.loaded) {+ panel.innerHTML = `+ <div class="awh-card awh-bal-skel" aria-busy="true" aria-label="Loading balance">+ <div class="awh-bal-skelbar awh-bal-skelbar--lg"></div>+ <div class="awh-bal-skelbar awh-bal-skelbar--sm"></div>+ <div class="awh-bal-skelbar awh-bal-skelbar--row"></div>+ </div>`;+ return;+ }++ const net = ctx.getNetwork();+ const hasAddr = !!state.address;+ const balUnavailable = state.balanceError != null;+ const balText = balUnavailable+ ? 'Balance unavailable'+ : state.sol == null+ ? '—'+ : `${formatSol(state.sol)} SOL`;+ const usdText =+ !balUnavailable && state.usd != null+ ? `≈ $${state.usd.toLocaleString('en-US', { maximumFractionDigits: state.usd < 1 ? 4 : 2 })}`+ : '';++ panel.innerHTML = `+ <div class="awh-card">+ <div class="awh-bal-top">+ <div>+ <div class="awh-bal-amount ${balUnavailable ? 'is-unavailable' : ''}"+ ${balUnavailable ? 'title="The Solana RPC could not be reached — this retries automatically."' : ''}>+ ${escapeHtml(balText)}+ </div>+ ${usdText ? `<div class="awh-bal-usd">${escapeHtml(usdText)}</div>` : ''}+ </div>+ <button class="awh-btn awh-bal-refresh" type="button" data-act="refresh"+ ${state.refreshing ? 'disabled' : ''} aria-label="Refresh balance">+ ${state.refreshing ? 'Refreshing…' : '↻ Refresh'}+ </button>+ </div>+ ${+ hasAddr+ ? `<div class="awh-bal-addr">+ <span class="awh-mono" title="${escapeHtml(state.address)}">${escapeHtml(shortAddress(state.address, 6, 6))}</span>+ <button class="awh-btn awh-bal-mini" type="button" data-act="copy" aria-label="Copy wallet address">Copy</button>+ <a class="awh-btn awh-bal-mini" href="${escapeHtml(explorerAddressUrl(state.address, net))}" target="_blank" rel="noopener">Explorer ↗</a>+ </div>`+ : `<div class="awh-empty">This agent does not have a Solana wallet yet. It is being prepared automatically.</div>`+ }+ ${+ balUnavailable+ ? `<div class="awh-bal-note">The Solana network was unreachable. Retrying automatically — your funds are safe.</div>`+ : ''+ }+ </div>++ <div class="awh-card">+ <h2 class="awh-card-h">Recent activity</h2>+ <div data-host="activity">+ ${+ !state.activityLoaded+ ? `<div class="awh-act-skel"><span></span><span></span><span></span></div>`+ : renderActivity(net)+ }+ </div>+ </div>+ `;++ panel.querySelector('[data-act="refresh"]')?.addEventListener('click', () => {+ refreshAll(true);+ });+ panel.querySelector('[data-act="copy"]')?.addEventListener('click', async () => {+ const ok = await copyToClipboard(state.address);+ toast(ok ? 'Address copied' : 'Copy failed — select it manually');+ });+ }++ function renderActivity(net) {+ if (state.activityError) {+ return `<div class="awh-empty">Could not load activity. <button class="awh-btn awh-bal-mini" type="button" data-act="retry-activity">Retry</button></div>`;+ }+ const rows = state.activity || [];+ if (!rows.length) {+ return `<div class="awh-empty">No on-chain activity yet. Deposits and trades appear here.</div>`;+ }+ return `<ul class="awh-act-list">${rows+ .map((a) => {+ const delta = a.sol_delta;+ let cls = '';+ let txt = '—';+ if (typeof delta === 'number') {+ cls = delta > 0 ? 'is-pos' : delta < 0 ? 'is-neg' : '';+ txt = `${delta > 0 ? '+' : ''}${formatSol(delta)} SOL`;+ }+ const failed = a.success === false;+ return `<li class="awh-act-row">+ <a class="awh-mono awh-act-sig" href="${escapeHtml(explorerTxUrl(a.signature, net))}" target="_blank" rel="noopener">${escapeHtml(shortAddress(a.signature, 6, 4))}</a>+ <span class="awh-act-meta">${escapeHtml(a.summary ? a.summary : failed ? 'failed' : 'transfer')} · ${escapeHtml(timeAgo(a.block_time))}</span>+ <span class="awh-act-delta ${cls}">${escapeHtml(txt)}</span>+ </li>`;+ })+ .join('')}</ul>`;+ }++ async function loadBalance() {+ const net = ctx.getNetwork();+ let r;+ try {+ r = await fetchAgentSolanaWallet(ctx.agentId, net);+ } catch {+ // Transient client/network failure — surface as the designed+ // "unavailable" state rather than a thrown error.+ state.balanceError = 'rpc_error';+ return;+ }+ if (r.status === 'forbidden') {+ // Visitor on a non-owned wallet still reads the public balance via+ // the same endpoint; a 401/403 here means the wallet read is gated.+ // Fall back to whatever public address we already have.+ return;+ }+ if (r.status === 'none') {+ state.address = null;+ state.sol = null;+ state.balanceError = null;+ return;+ }+ if (r.status === 'error') {+ state.balanceError = 'rpc_error';+ return;+ }+ // ok+ state.address = r.data.address || state.address;+ state.sol = r.data.sol;+ state.balanceError = r.data.balance_error || null;+ if (!state.balanceError && state.sol != null) {+ state.usd = await solToUsd(state.sol);+ } else {+ state.usd = null;+ }+ }++ async function loadActivity() {+ const net = ctx.getNetwork();+ if (!state.address) {+ state.activity = [];+ state.activityLoaded = true;+ state.activityError = null;+ return;+ }+ try {+ const data = await fetchAgentSolanaActivity(ctx.agentId, net, 10);+ state.activity = data?.signatures || [];+ state.activityError = null;+ } catch (e) {+ state.activityError = e?.message || 'activity_error';+ } finally {+ state.activityLoaded = true;+ }+ }++ async function refreshAll(manual = false) {+ if (state.refreshing) return;+ state.refreshing = manual;+ if (manual) render();+ await Promise.all([loadBalance(), loadActivity()]);+ state.loaded = true;+ state.refreshing = false;+ render();+ }++ function startPoll() {+ stopPoll();+ pollTimer = setInterval(() => {+ if (!visible || destroyed) return;+ // Poll balance only (cheap); leave activity to manual refresh ++ // the next show to avoid hammering the parsed-tx RPC.+ loadBalance().then(() => render());+ }, POLL_MS);+ }+ function stopPoll() {+ if (pollTimer) clearInterval(pollTimer);+ pollTimer = null;+ }++ // React to network switches from the hub header.+ detachNet = ctx.onNetworkChange(() => {+ state.loaded = false;+ state.activityLoaded = false;+ state.activity = null;+ state.usd = null;+ render();+ refreshAll();+ });++ // Delegate the activity-retry button (it lives inside the activity host).+ panel.addEventListener('click', (e) => {+ if (e.target?.dataset?.act === 'retry-activity') {+ state.activityLoaded = false;+ render();+ loadActivity().then(() => render());+ }+ });++ render();++ return {+ onShow() {+ visible = true;+ if (!state.loaded) refreshAll();+ else render();+ startPoll();+ },+ onHide() {+ visible = false;+ stopPoll();+ },+ destroy() {+ destroyed = true;+ stopPoll();+ detachNet?.();+ },+ };+ },+});diff --git a/src/agent-wallet-hub/tabs/deposit.js b/src/agent-wallet-hub/tabs/deposit.jsnew file mode 100644index 000000000..cfe22a74a--- /dev/null+++ b/src/agent-wallet-hub/tabs/deposit.js@@ -0,0 +1,19 @@+/**+ * Agent Wallet hub — Deposit tab (placeholder; replaced by epic task 02).+ *+ * Visible to owner AND visitors: funding an agent is a public-safe action (you+ * can deposit to any agent's public address). Task 02 ships the QR + copy ++ * `solana:` deep-link + live "funds received" confirmation here.+ */++import { registerPlaceholderTab } from './_placeholder.js';++registerPlaceholderTab({+ id: 'deposit',+ label: 'Deposit',+ order: 20,+ ownerOnly: false,+ icon: '↓',+ title: 'Fund this wallet',+ body: 'Scan a QR with your phone, copy the address, or tap a one-tap Solana deposit link to send SOL to this agent — with a live confirmation the moment funds land. This panel is being wired up now.',+});diff --git a/src/agent-wallet-hub/tabs/pay.js b/src/agent-wallet-hub/tabs/pay.jsnew file mode 100644index 000000000..9ad780939--- /dev/null+++ b/src/agent-wallet-hub/tabs/pay.js@@ -0,0 +1,18 @@+/**+ * Agent Wallet hub — Pay tab (placeholder; replaced by epic task 08).+ *+ * Owner-only: paying for services spends the agent's own funds.+ * Task 08 ships in-product x402 pay from the per-agent wallet + payment activity.+ */++import { registerPlaceholderTab } from './_placeholder.js';++registerPlaceholderTab({+ id: 'pay',+ label: 'Pay',+ order: 50,+ ownerOnly: true,+ icon: '⌁',+ title: 'Pay for services',+ body: 'Pay x402 paid-API endpoints in USDC straight from the agent’s wallet — no shared platform wallet — with a running ledger of what the agent has paid for. This panel is being wired up now.',+});diff --git a/src/agent-wallet-hub/tabs/snipe.js b/src/agent-wallet-hub/tabs/snipe.jsnew file mode 100644index 000000000..b4da72828--- /dev/null+++ b/src/agent-wallet-hub/tabs/snipe.js@@ -0,0 +1,18 @@+/**+ * Agent Wallet hub — Snipe tab (placeholder; replaced by epic task 06).+ *+ * Owner-only: arming an autonomous strategy spends the agent's own funds.+ * Task 06 ships the sniper arming form + live positions/PnL dashboard.+ */++import { registerPlaceholderTab } from './_placeholder.js';++registerPlaceholderTab({+ id: 'snipe',+ label: 'Snipe',+ order: 40,+ ownerOnly: true,+ icon: '◎',+ title: 'Arm an autonomous strategy',+ body: 'Set a budget, entry filters, and exit rules, then let the agent snipe brand-new pump.fun launches on its own — with live positions and realized PnL tracked here. This panel is being wired up now.',+});diff --git a/src/agent-wallet-hub/tabs/trade.js b/src/agent-wallet-hub/tabs/trade.jsnew file mode 100644index 000000000..9fdf73662--- /dev/null+++ b/src/agent-wallet-hub/tabs/trade.js@@ -0,0 +1,18 @@+/**+ * Agent Wallet hub — Trade tab (placeholder; replaced by epic task 04).+ *+ * Owner-only: discretionary trading moves the agent's own custodial funds.+ * Task 04 ships the pump.fun buy/sell widget that signs from the agent wallet.+ */++import { registerPlaceholderTab } from './_placeholder.js';++registerPlaceholderTab({+ id: 'trade',+ label: 'Trade',+ order: 30,+ ownerOnly: true,+ icon: '⇄',+ title: 'Trade from this wallet',+ body: 'Buy and sell pump.fun tokens directly from the agent’s own funded wallet, with live quotes, slippage controls, and price-impact guardrails. This panel is being wired up now.',+});diff --git a/src/agent-wallet-hub/tabs/withdraw.js b/src/agent-wallet-hub/tabs/withdraw.jsnew file mode 100644index 000000000..2f51e62d6--- /dev/null+++ b/src/agent-wallet-hub/tabs/withdraw.js@@ -0,0 +1,19 @@+/**+ * Agent Wallet hub — Withdraw tab (placeholder; replaced by epic task 09).+ *+ * Owner-only: only the owner may move funds out of the custodial wallet.+ * Task 09 ships the withdraw/sweep path (SOL + SPL), spend limits, and the+ * custody audit trail.+ */++import { registerPlaceholderTab } from './_placeholder.js';++registerPlaceholderTab({+ id: 'withdraw',+ label: 'Withdraw',+ order: 60,+ ownerOnly: true,+ icon: '↑',+ title: 'Withdraw funds',+ body: 'Move all SOL and SPL tokens out of the agent wallet to any address or .sol name at any time — you always control the funds. Spend limits and a full custody audit trail live here too. This panel is being wired up now.',+});diff --git a/src/agent-wallet-hub/util.js b/src/agent-wallet-hub/util.jsnew file mode 100644index 000000000..3a02ca2e4--- /dev/null+++ b/src/agent-wallet-hub/util.js@@ -0,0 +1,111 @@+/**+ * Agent Wallet hub — shared, dependency-free UI utilities used by the shell and+ * every tab. No DOM framework, no third-party deps.+ */++/** Escape a string for safe interpolation into innerHTML. */+export function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/** Compact a base58 address: "AbCd…WxYz". */+export function shortAddress(addr, head = 4, tail = 4) {+ if (!addr || typeof addr !== 'string') return '';+ if (addr.length <= head + tail + 1) return addr;+ return `${addr.slice(0, head)}…${addr.slice(-tail)}`;+}++/**+ * Copy text to the clipboard. Uses the async Clipboard API with a synchronous+ * execCommand fallback for older / non-secure contexts. Resolves true on success.+ */+export async function copyToClipboard(text) {+ if (!text) return false;+ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(text);+ return true;+ }+ } catch {+ /* fall through to legacy path */+ }+ try {+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.setAttribute('readonly', '');+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ const ok = document.execCommand('copy');+ ta.remove();+ return ok;+ } catch {+ return false;+ }+}++let _toastEl = null;+let _toastTimer = null;+/** Show a transient toast message anchored to the bottom-center of the viewport. */+export function toast(message, ms = 2200) {+ if (typeof document === 'undefined') return;+ if (!_toastEl) {+ _toastEl = document.createElement('div');+ _toastEl.className = 'awh-toast';+ _toastEl.setAttribute('role', 'status');+ _toastEl.setAttribute('aria-live', 'polite');+ document.body.appendChild(_toastEl);+ }+ _toastEl.textContent = message;+ _toastEl.dataset.show = 'true';+ clearTimeout(_toastTimer);+ _toastTimer = setTimeout(() => {+ if (_toastEl) _toastEl.dataset.show = 'false';+ }, ms);+}++/** Format a SOL number for display. Returns "—" for nullish. */+export function formatSol(sol) {+ if (sol == null || Number.isNaN(sol)) return '—';+ // Trim to 4 dp but drop trailing zeros so "1.2000" reads "1.2".+ const fixed = Number(sol).toFixed(4);+ return fixed.replace(/\.?0+$/, '') || '0';+}++/** Format a USD estimate. Returns null when no price/balance is available. */+export function formatUsd(amount) {+ if (amount == null || Number.isNaN(amount)) return null;+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+ maximumFractionDigits: amount < 1 ? 4 : 2,+ }).format(amount);+}++/** Human "x ago" from a unix-seconds timestamp. */+export function timeAgo(unixSeconds) {+ if (!unixSeconds) return '';+ const sec = Math.max(0, Math.floor(Date.now() / 1000 - unixSeconds));+ if (sec < 60) return `${sec}s ago`;+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ return `${Math.floor(sec / 86400)}d ago`;+}++/** Explorer URL for a Solana address on the given network. */+export function explorerAddressUrl(address, network) {+ return network === 'devnet'+ ? `https://explorer.solana.com/address/${address}?cluster=devnet`+ : `https://solscan.io/account/${address}`;+}++/** Explorer URL for a Solana transaction signature on the given network. */+export function explorerTxUrl(sig, network) {+ return network === 'devnet'+ ? `https://explorer.solana.com/tx/${sig}?cluster=devnet`+ : `https://solscan.io/tx/${sig}`;+}diff --git a/src/agent-wallet.js b/src/agent-wallet.jsnew file mode 100644index 000000000..ca186a951--- /dev/null+++ b/src/agent-wallet.js@@ -0,0 +1,105 @@+/**+ * Agent Wallet hub — page entry.+ *+ * Route: /agent/:id/wallet (also accepts ?id=<uuid>). Resolves the agent, then+ * mounts the tabbed hub (Balance · Deposit · Trade · Snipe · Pay · Withdraw).+ *+ * Every page state is designed: loading skeleton, not-found, fetch error (with+ * retry), and the live hub. Owner vs visitor is decided server-side by the+ * agent record's `is_owner`.+ */++import { mountAgentWalletHub } from './agent-wallet-hub/index.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;++function resolveAgentId() {+ const fromQuery = new URLSearchParams(location.search).get('id');+ if (fromQuery) return fromQuery;+ // /agent/:id/wallet or /agents/:id/wallet+ const m = location.pathname.match(/\/agents?\/([^/]+)\/wallet/);+ return m ? decodeURIComponent(m[1]) : null;+}++const root = document.getElementById('awh-root');++function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function renderLoading() {+ root.innerHTML = `+ <div class="awh-page-skel" aria-busy="true" aria-label="Loading agent wallet">+ <div class="awh-page-skel-row"></div>+ <div class="awh-page-skel-tabs"></div>+ <div class="awh-page-skel-card"></div>+ </div>`;+}++function renderMessage({ title, body, actionHref, actionLabel, retry }) {+ root.innerHTML = `+ <div class="awh-page-msg" role="alert">+ <h1>${escapeHtml(title)}</h1>+ <p>${escapeHtml(body)}</p>+ <div class="awh-page-msg-actions">+ ${actionHref ? `<a class="awh-page-btn awh-page-btn--primary" href="${escapeHtml(actionHref)}">${escapeHtml(actionLabel || 'Continue')}</a>` : ''}+ ${retry ? `<button class="awh-page-btn" type="button" data-act="retry">Try again</button>` : ''}+ </div>+ </div>`;+ if (retry) root.querySelector('[data-act="retry"]')?.addEventListener('click', () => load());+}++async function load() {+ const agentId = resolveAgentId();+ if (!agentId || !UUID_RE.test(agentId)) {+ renderMessage({+ title: 'No agent selected',+ body: 'This page needs an agent. Open it from an agent profile, or create your first agent to get a self-custodied Solana wallet.',+ actionHref: '/create-agent',+ actionLabel: 'Create an agent',+ });+ document.title = 'Agent wallet — three.ws';+ return;+ }++ renderLoading();++ let agent;+ try {+ const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, {+ credentials: 'include',+ headers: { accept: 'application/json' },+ });+ if (res.status === 404) {+ renderMessage({+ title: 'Agent not found',+ body: 'This agent doesn’t exist or has been removed. It may have been deleted by its owner.',+ actionHref: '/agents',+ actionLabel: 'Browse agents',+ });+ document.title = 'Agent not found — three.ws';+ return;+ }+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ agent = data.agent;+ if (!agent) throw new Error('empty agent payload');+ } catch {+ renderMessage({+ title: 'Couldn’t load this wallet',+ body: 'We couldn’t reach the agent service. This is usually temporary — check your connection and try again.',+ retry: true,+ });+ document.title = 'Agent wallet — three.ws';+ return;+ }++ document.title = `${agent.name || 'Agent'} wallet — three.ws`;++ mountAgentWalletHub({ mount: root, agent });+}++load();diff --git a/src/create-agent.js b/src/create-agent.jsindex 1d60d7305..a553d5efd 100644--- a/src/create-agent.js+++ b/src/create-agent.js@@ -1088,6 +1088,11 @@ function succeed(agent) {const open = $('success-open');open.href = agent.home_url || `/agent/${agent.id}`;$('success-edit').href = `/agent/${agent.id}/edit`;+ // Lead the user straight into funding the agent's new self-custodied wallet —+ // the Deposit tab of the wallet hub (QR + copy + live confirmation lands here+ // via the epic's task 02).+ const fund = $('success-fund');+ if (fund) fund.href = `/agent/${agent.id}/wallet#deposit`;// Show the 3D body if it's publicly readable.const modelUrl = agent.avatar_model_url;diff --git a/src/irl.js b/src/irl.jsindex 79093361d..e5f74d3b7 100644--- a/src/irl.js+++ b/src/irl.js@@ -54,6 +54,8 @@ import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';import { detectTier, BUDGETS, TIER_ORDER, shiftTier } from './irl/perf-budget.js';import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';import { roomOriginWorld, agentWorldPosition } from './irl/room-anchor.js';+import { anchorPoseToPin } from './irl/floor-anchor.js';+import { initRoomMode } from './irl/room-mode.js';import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch } from './irl/sensor-fusion.js';import { pinBandAction } from './irl/proximity-band.js';import { loadInto } from './shared/async-state.js';@@ -1511,6 +1513,72 @@ async function savePin(lat, lng, heading = 0, caption = '', anchor = null) {}}+// Place an agent into a shared ROOM (Epic R / R1). The room-mode UI hands us a+// computed body { lat, lng, heading, room:{…}, absolute } from room-session.js;+// we attach the device's identity + avatar + A2 anchor pose, POST it (the room+// block rides through to api/irl/pins.js), and on success spawn it immediately so+// it renders world-locked at once via the room frame (pinWorldPos). Returns the+// same { ok, id, message } shape the UI surfaces.+async function placeRoomAgent(body) {+ try {+ const room = body?.room;+ if (!room || !room.id) return { ok: false, message: 'Could not anchor the room — try again.' };+ const heading = ((Math.round(body.heading) % 360) + 360) % 360;+ const source = body.absolute ? 'gyro-gps' : 'gyro-gps:rel';+ const r = await fetch('/api/irl/pins', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ lat: body.lat, lng: body.lng, heading,+ caption: null,+ avatarUrl: resolveAvatarUrl(_currentAvatarId),+ avatarName: nameEl.textContent,+ deviceToken: _deviceToken,+ agentId: _currentAgentId || null,+ anchor: { heightM: 0, yawDeg: heading, gpsAccuracyM: gpsState.accuracy, altitudeM: gpsState.altitude, source },+ room: {+ id: room.id,+ originLat: room.originLat, originLng: room.originLng,+ originYawDeg: room.originYawDeg || 0,+ relEast: room.relEast, relNorth: room.relNorth,+ },+ }),+ });+ if (!r.ok) {+ let payload = {};+ try { payload = await r.json(); } catch {}+ return { ok: false, status: r.status, error: payload.error || 'error', message: payload.message || saveErrorFallback(payload.error) };+ }+ const data = await r.json();+ if (!data.pin) return { ok: false, message: saveErrorFallback() };++ // Spawn locally so the just-placed agent is world-locked immediately, without+ // waiting for the next proximity poll. snake_case shape incl. the room frame,+ // matching the nearby projection so pinRoom()/pinWorldPos() render it correctly.+ const pin = {+ id: data.pin.id,+ lat: body.lat, lng: body.lng,+ heading, anchor_yaw_deg: heading, anchor_height_m: 0,+ room_id: room.id, rel_east_m: room.relEast, rel_north_m: room.relNorth,+ origin_lat: room.originLat, origin_lng: room.originLng, origin_yaw_deg: room.originYawDeg || 0,+ avatar_url: resolveAvatarUrl(_currentAvatarId), avatar_name: nameEl.textContent,+ caption: '', x402_endpoint: null, agent_id: _currentAgentId || null,+ distance_m: 0, group: null, labelEl: null, glbLoaded: false,+ };+ if (!nearbyPins.find(p => p.id === pin.id)) {+ _myPinIds.add(pin.id);+ nearbyPins.push(pin);+ spawnNearbyPin(pin);+ updateNearbyBadge();+ revealMyPinsBtn();+ }+ return { ok: true, id: pin.id };+ } catch {+ return { ok: false, error: 'network', message: saveErrorFallback('network') };+ }+}+// Human fallback for a placement rejection when the server didn't ship a message.// The API always sends one for D4 rejections; this covers network/parse gaps.function saveErrorFallback(code) {@@ -4999,6 +5067,35 @@ bootAvatar();// path; desktop Chrome reports false and adds no console noise.detectFloorAnchorSupport();+// ── Room authoring mode (Epic R / R1) — "place agents around me" ────────────+// Self-contained UI lives in src/irl/room-mode.js (its own DOM + styles); we+// supply the live pose, AR/permission readiness, and the placement (network ++// scene spawn) it calls back into. Rooms are delivered to other viewers by the+// REST proximity read — there is no realtime pin push to wire here.+initRoomMode({+ controlRow: document.querySelector('.irl-secondary-row'),+ getFix: () => ({ lat: gpsState.lat, lng: gpsState.lng, ready: gpsState.ready, accuracy: gpsState.accuracy }),+ getHeading: () => ({+ // Prefer the iOS true-compass bearing; otherwise derive from the camera yaw+ // (which onDeviceOrientation north-anchors when an absolute stream exists).+ deg: lastCompassHeading != null+ ? lastCompassHeading+ : ((-(cameraYaw * 180 / Math.PI)) % 360 + 360) % 360,+ absolute: !!prefersAbsOrientation,+ }),+ ensureReady: async () => {+ try {+ if (!arActive) await enableAR();+ initGPS();+ ensurePermission('motion').catch(() => {});+ ensurePermission('location').catch(() => {});+ } catch { /* honest disabled states in the HUD cover a denied permission */ }+ return arActive;+ },+ placeRoomAgent,+ status: (m, o) => setStatus(m, o),+});+// ── Dev-only perf harness (E2) ──────────────────────────────────────────────// Gated behind import.meta.env.DEV → tree-shaken out of production builds, so no// synthetic pins ever ship. Lets us verify the LOD/culling/queue budget under adiff --git a/src/irl/room-mode.js b/src/irl/room-mode.jsnew file mode 100644index 000000000..f00b94911--- /dev/null+++ b/src/irl/room-mode.js@@ -0,0 +1,321 @@+// "Place agents around me" — the /irl room authoring UI (Epic R / R1).+//+// Self-contained on purpose: it builds its OWN DOM (entry button, aim HUD, room+// badge) and injects its OWN styles, so it needs only a single additive hook in+// src/irl.js (initRoomMode) and never edits the shared markup. It rides the pure,+// unit-tested src/irl/room-session.js for all geometry/session logic and calls+// back into irl.js through injected deps for pose, permissions, and the actual+// placement (which owns the network + 3D scene).+//+// The interaction: enter the mode, physically aim the phone at a real spot, set a+// distance, tap Place — the agent drops at that compass bearing + distance,+// anchored into one shared room, and renders world-locked immediately (it stays+// put as you turn). Drop several around you; the left wall stays empty unless you+// aim there. Everything is delivered to other viewers by the existing REST+// proximity read (rooms do not ride realtime).++import {+ establishRoom,+ roomPlacement,+ clampDistance,+ serializeRoom,+ reviveRoom,+ DIST_DEFAULT_M,+} from './room-session.js';++const STORE_KEY = 'irl_room_v1';+const COMPASS_8 = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];+function compassLabel(deg) {+ return COMPASS_8[Math.round((((deg % 360) + 360) % 360) / 45) % 8];+}++// Coarse, stable place token for the room id (≈110 m grid) — keeps placements at+// one spot in one session sharing a room without pulling in a geohash dep.+function locationKey(lat, lng) {+ return `${Math.round(lat * 1000)}x${Math.round(lng * 1000)}`.replace('-', 'n');+}++let _stylesInjected = false;+function injectStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const css = `+.irl-room-fab.is-active{background:rgba(124,92,255,.22);border-color:rgba(124,92,255,.7);color:#fff}+#irl-aim-hud{position:fixed;inset:0;z-index:6;pointer-events:none;display:none;+ font:inherit;color:#fff}+#irl-aim-hud.is-open{display:block}+.irl-aim-reticle{position:absolute;top:46%;left:50%;width:74px;height:74px;+ margin:-37px 0 0 -37px;border-radius:50%;border:2px solid rgba(255,255,255,.9);+ box-shadow:0 0 0 2px rgba(0,0,0,.35),0 0 18px rgba(124,92,255,.55);+ animation:irlAimPulse 1.8s ease-in-out infinite}+.irl-aim-reticle::before,.irl-aim-reticle::after{content:'';position:absolute;+ background:rgba(255,255,255,.9);box-shadow:0 0 4px rgba(0,0,0,.5)}+.irl-aim-reticle::before{top:50%;left:18px;right:18px;height:2px;margin-top:-1px}+.irl-aim-reticle::after{left:50%;top:18px;bottom:18px;width:2px;margin-left:-1px}+@keyframes irlAimPulse{0%,100%{transform:scale(1);opacity:.85}50%{transform:scale(1.08);opacity:1}}+.irl-aim-readout{position:absolute;top:calc(46% + 50px);left:50%;transform:translateX(-50%);+ background:rgba(0,0,0,.55);border:1px solid rgba(255,255,255,.18);border-radius:999px;+ padding:5px 12px;font-size:13px;font-weight:600;letter-spacing:.2px;white-space:nowrap;+ backdrop-filter:blur(6px)}+.irl-aim-panel{position:absolute;left:0;right:0;bottom:0;pointer-events:auto;+ padding:14px 16px calc(16px + env(safe-area-inset-bottom));+ background:linear-gradient(to top,rgba(8,8,16,.92),rgba(8,8,16,.55) 70%,transparent);+ display:flex;flex-direction:column;gap:12px}+.irl-aim-coach{font-size:13px;line-height:1.4;color:rgba(255,255,255,.82);text-align:center;margin:0}+.irl-aim-coach[data-tone="warn"]{color:#fcd34d}+.irl-aim-dist{display:flex;align-items:center;gap:12px}+.irl-aim-dist label{font-size:12px;opacity:.7;min-width:58px}+.irl-aim-dist input[type=range]{flex:1;accent-color:#7c5cff;height:28px}+.irl-aim-dist output{min-width:54px;text-align:right;font-weight:700;font-variant-numeric:tabular-nums}+.irl-aim-actions{display:flex;gap:10px;align-items:stretch}+.irl-aim-place{flex:1;min-height:52px;border:none;border-radius:14px;font-size:16px;font-weight:700;+ color:#fff;background:linear-gradient(135deg,#7c5cff,#9d7bff);cursor:pointer;+ box-shadow:0 6px 20px rgba(124,92,255,.4);transition:transform .12s ease,filter .12s ease}+.irl-aim-place:hover{filter:brightness(1.08)}+.irl-aim-place:active{transform:scale(.97)}+.irl-aim-place:disabled{opacity:.5;cursor:not-allowed;box-shadow:none}+.irl-aim-place.is-flash{animation:irlPlaceFlash .4s ease}+@keyframes irlPlaceFlash{0%{transform:scale(1)}40%{transform:scale(.92)}100%{transform:scale(1)}}+.irl-aim-face,.irl-aim-done{min-height:52px;padding:0 14px;border-radius:14px;font-size:14px;font-weight:600;+ background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.2);color:#fff;cursor:pointer}+.irl-aim-face[aria-pressed="true"]{background:rgba(124,92,255,.28);border-color:rgba(124,92,255,.6)}+.irl-aim-face:focus-visible,.irl-aim-done:focus-visible,.irl-aim-place:focus-visible{+ outline:2px solid #9d7bff;outline-offset:2px}+.irl-room-badge{position:fixed;left:50%;top:72px;transform:translateX(-50%);z-index:7;+ display:none;align-items:center;gap:7px;pointer-events:auto;+ background:rgba(8,8,16,.7);border:1px solid rgba(124,92,255,.45);border-radius:999px;+ padding:6px 13px;font-size:13px;font-weight:600;backdrop-filter:blur(8px);color:#fff}+.irl-room-badge.is-shown{display:flex}+.irl-room-badge .dot{width:7px;height:7px;border-radius:50%;background:#7c5cff;box-shadow:0 0 7px #7c5cff}+@media (prefers-reduced-motion:reduce){+ .irl-aim-reticle{animation:none}.irl-aim-place.is-flash{animation:none}}+`;+ const style = document.createElement('style');+ style.setAttribute('data-irl-room-mode', '');+ style.textContent = css;+ document.head.appendChild(style);+}++/**+ * Wire the room authoring mode. All DOM is created here; irl.js supplies pose,+ * permission/AR readiness, and the placement (network + scene) via deps.+ *+ * @param {object} deps+ * @param {Element|null} deps.controlRow where to mount the entry button (falls back to body)+ * @param {() => {lat:number,lng:number,ready:boolean,accuracy:number}} deps.getFix+ * @param {() => {deg:number, absolute:boolean}} deps.getHeading live compass bearing+ * @param {() => Promise<boolean>} deps.ensureReady turn on camera AR + perms; resolve true when usable+ * @param {(body:object) => Promise<{ok:boolean,id?:string,message?:string}>} deps.placeRoomAgent+ * @param {(msg:string, opts?:object) => void} [deps.status]+ * @returns {{ isActive:()=>boolean, exit:()=>void }}+ */+export function initRoomMode(deps) {+ const { getFix, getHeading, ensureReady, placeRoomAgent } = deps;+ const status = deps.status || (() => {});+ if (typeof getFix !== 'function' || typeof placeRoomAgent !== 'function') {+ throw new Error('initRoomMode: getFix + placeRoomAgent are required');+ }+ injectStyles();++ let active = false;+ let distM = DIST_DEFAULT_M;+ let faceViewer = true;+ let activeRoom = reviveRoomFromStore();+ let tickTimer = null;+ let busy = false;++ // ── Entry button ─────────────────────────────────────────────────────────+ const fab = document.createElement('button');+ fab.type = 'button';+ fab.className = 'irl-pill-btn irl-room-fab';+ fab.setAttribute('aria-pressed', 'false');+ fab.setAttribute('aria-label', 'Place AI agents around your room');+ fab.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="2.4"/><path d="M12 3v3M12 18v3M3 12h3M18 12h3"/><circle cx="12" cy="12" r="8.5" opacity=".5"/></svg> Place agents`;+ (deps.controlRow || document.body).appendChild(fab);+ fab.addEventListener('click', () => (active ? exit() : enter()));++ // ── Room badge ───────────────────────────────────────────────────────────+ const badge = document.createElement('div');+ badge.className = 'irl-room-badge';+ badge.setAttribute('role', 'status');+ badge.setAttribute('aria-live', 'polite');+ document.body.appendChild(badge);++ // ── Aim HUD ──────────────────────────────────────────────────────────────+ const hud = document.createElement('div');+ hud.id = 'irl-aim-hud';+ hud.innerHTML = `+ <div class="irl-aim-reticle" aria-hidden="true"></div>+ <div class="irl-aim-readout" id="irl-aim-readout" aria-hidden="true">2.5 m</div>+ <div class="irl-aim-panel" role="group" aria-label="Place an agent">+ <p class="irl-aim-coach" id="irl-aim-coach">Aim at a spot and tap Place to drop your first agent.</p>+ <div class="irl-aim-dist">+ <label for="irl-aim-range">Distance</label>+ <input type="range" id="irl-aim-range" min="0.5" max="8" step="0.5" value="2.5"+ aria-label="Distance to place the agent, in metres">+ <output id="irl-aim-out" for="irl-aim-range">2.5 m</output>+ </div>+ <div class="irl-aim-actions">+ <button type="button" class="irl-aim-place" id="irl-aim-place">Place agent</button>+ <button type="button" class="irl-aim-face" id="irl-aim-face" aria-pressed="true"+ aria-label="Agent faces you">Faces you</button>+ <button type="button" class="irl-aim-done" id="irl-aim-done">Done</button>+ </div>+ </div>`;+ document.body.appendChild(hud);++ const reticleReadout = hud.querySelector('#irl-aim-readout');+ const coach = hud.querySelector('#irl-aim-coach');+ const range = hud.querySelector('#irl-aim-range');+ const out = hud.querySelector('#irl-aim-out');+ const placeBtn = hud.querySelector('#irl-aim-place');+ const faceBtn = hud.querySelector('#irl-aim-face');+ const doneBtn = hud.querySelector('#irl-aim-done');++ range.addEventListener('input', () => {+ distM = clampDistance(parseFloat(range.value));+ refreshReadouts();+ });+ faceBtn.addEventListener('click', () => {+ faceViewer = !faceViewer;+ faceBtn.setAttribute('aria-pressed', String(faceViewer));+ faceBtn.textContent = faceViewer ? 'Faces you' : 'Faces away';+ });+ doneBtn.addEventListener('click', exit);+ placeBtn.addEventListener('click', place);+ // Keyboard: Esc exits, Enter on the HUD places.+ hud.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') { e.preventDefault(); exit(); }+ });++ function reviveRoomFromStore() {+ try { return reviveRoom(localStorage.getItem(STORE_KEY) || ''); } catch { return null; }+ }+ function persistRoom() {+ try { localStorage.setItem(STORE_KEY, serializeRoom(activeRoom)); } catch {}+ }++ function refreshReadouts() {+ out.textContent = `${distM.toFixed(1)} m`;+ const fix = getFix();+ const ready = !!fix && fix.ready;+ const heading = getHeading ? getHeading() : { deg: 0, absolute: false };+ const dir = compassLabel(heading.deg);+ reticleReadout.textContent = ready ? `${distM.toFixed(1)} m · ${dir} ${Math.round(heading.deg)}°` : `${distM.toFixed(1)} m`;++ // Coach + Place enablement reflect the live state honestly.+ if (!ready) {+ setCoach(`Finding your spot…${fix && fix.accuracy ? ` (±${Math.round(fix.accuracy)} m)` : ''}`, 'warn');+ placeBtn.disabled = true;+ return;+ }+ placeBtn.disabled = busy;+ if (!heading.absolute) {+ setCoach('Compass not calibrated — others may see this room rotated. Placement still works.', 'warn');+ } else if (activeRoom && activeRoom.count > 0) {+ setCoach(`Aim and Place to add another. ${activeRoom.count} placed in this room.`);+ } else {+ setCoach('Aim at a spot and tap Place to drop your first agent.');+ }+ }+ function setCoach(text, tone) {+ coach.textContent = text;+ if (tone) coach.setAttribute('data-tone', tone); else coach.removeAttribute('data-tone');+ }++ function refreshBadge() {+ const n = activeRoom ? activeRoom.count : 0;+ if (active && n > 0) {+ badge.innerHTML = `<span class="dot"></span> ${n} agent${n === 1 ? '' : 's'} in this room`;+ badge.classList.add('is-shown');+ } else {+ badge.classList.remove('is-shown');+ }+ }++ async function enter() {+ if (active) return;+ let ok = false;+ try { ok = await ensureReady(); } catch { ok = false; }+ if (!ok) { status('Turn on the camera and allow motion + location to place agents.', { warn: true }); return; }+ active = true;+ busy = false;+ document.body.classList.add('irl-room-mode');+ fab.setAttribute('aria-pressed', 'true');+ fab.classList.add('is-active');+ hud.classList.add('is-open');+ range.value = String(distM);+ refreshReadouts();+ refreshBadge();+ placeBtn.focus();+ tickTimer = setInterval(refreshReadouts, 120); // live compass/fix readout, decoupled from the render loop+ }++ function exit() {+ if (!active) return;+ active = false;+ document.body.classList.remove('irl-room-mode');+ fab.setAttribute('aria-pressed', 'false');+ fab.classList.remove('is-active');+ hud.classList.remove('is-open');+ badge.classList.remove('is-shown');+ if (tickTimer) { clearInterval(tickTimer); tickTimer = null; }+ }++ async function place() {+ if (busy) return;+ const fix = getFix();+ if (!fix || !fix.ready) { setCoach('Waiting for a GPS fix before placing…', 'warn'); return; }+ const heading = getHeading ? getHeading() : { deg: 0, absolute: false };++ // Establish the room on the first placement of the session/spot.+ if (!activeRoom) {+ activeRoom = establishRoom({+ lat: fix.lat, lng: fix.lng,+ headingDeg: heading.deg, hasAbsoluteCompass: heading.absolute,+ locationKey: locationKey(fix.lat, fix.lng),+ rand: (Math.random().toString(36).slice(2, 8)),+ now: Date.now(),+ });+ }++ let body;+ try {+ body = roomPlacement({+ room: activeRoom,+ viewerLat: fix.lat, viewerLng: fix.lng,+ bearingDeg: heading.deg, distM, faceViewer,+ });+ } catch (err) {+ setCoach('Could not compute the placement — try again.', 'warn');+ return;+ }+ body.absolute = heading.absolute; // irl.js maps this to anchor_source++ busy = true;+ placeBtn.disabled = true;+ const prevLabel = placeBtn.textContent;+ placeBtn.textContent = 'Placing…';+ let result;+ try { result = await placeRoomAgent(body); } catch { result = { ok: false, message: 'Network error — try again.' }; }++ busy = false;+ placeBtn.textContent = prevLabel;+ if (result && result.ok) {+ activeRoom.count = (activeRoom.count || 0) + 1;+ persistRoom();+ placeBtn.classList.remove('is-flash'); void placeBtn.offsetWidth; placeBtn.classList.add('is-flash');+ try { navigator.vibrate && navigator.vibrate(10); } catch {}+ refreshBadge();+ refreshReadouts();+ } else {+ setCoach(result?.message || 'Could not place the agent — try again.', 'warn');+ }+ placeBtn.disabled = false;+ }++ return {+ isActive: () => active,+ exit,+ };+}diff --git a/tasks/irl-privacy/04-gps-edge-hysteresis.md b/tasks/irl-privacy/04-gps-edge-hysteresis.mddeleted file mode 100644index e0927bc83..000000000--- a/tasks/irl-privacy/04-gps-edge-hysteresis.md+++ /dev/null@@ -1,69 +0,0 @@-# 04 — GPS-edge hysteresis / anti-flicker--> Size **S–M** · `src/irl.js` (`loadNearbyPins`, `refreshKnownPin`, despawn path,-> `NEARBY_RADIUS`), small pure helper. A real correctness + zero-jank bug, not polish.--## Goal--Stop agents near the radius boundary from popping in and out as consumer GPS-jitters, and stop avatars from "swimming" frame-to-frame. Discovery must be rock-steady: once an agent appears, it stays put until you genuinely walk away.--## Why it matters--Consumer GPS is ~5–30 m noisy; our discovery gate is 40 m. An agent sitting at-~38–42 m will cross the threshold on *every* fix, so the server returns it, then-drops it, then returns it — the avatar spawns, disposes its GPU resources, and-respawns repeatedly. That's visible flicker, wasted GLB loads, and a janky,-unprofessional feel — exactly what "best UX" rules out. The origin low-pass-(`blendOrigin`) smooths the *viewer* origin but does nothing for *set membership*-churn at the edge.--## Current state (real lines)--- `api/irl/pins.js` nearby GET hard-caps the requested radius:- `Math.min(60, Math.max(10, parseFloat(req.query.radius ?? '40')))`. The client- requests `NEARBY_RADIUS = 40`.-- `src/irl.js` `loadNearbyPins()` rebuilds the set every 10 s: pins absent from the- response are removed via `disposePin(p)`; new ones are `spawnNearbyPin`-ed. There- is **no hysteresis** — membership is whatever the last poll returned.-- `pinWorldPos` already resolves room-anchored clusters exactly; standalone pins- use their own lat/lng, which is where edge jitter shows.--## What to build--1. **Asymmetric radius (hysteresis).** Discover at 40 m, but only *drop* a pin once- it's clearly gone — e.g. request a slightly wider read radius (client asks for- the cap, ~55–60 m) and apply the **enter** threshold (40 m) only to pins not- already rendered, while keeping an already-rendered pin until it exceeds an- **exit** threshold (e.g. 55 m). Compute distance client-side from `pinWorldPos`- (already done each GPS fix) so the band is enforced locally regardless of the- server's coarse set. Keep the server cap intact — never widen past 60 m.-2. **Despawn debounce.** A pin must be out-of-band for N consecutive polls (or T- seconds) before `disposePin` — so a single bad fix never evicts a stable agent.-3. **Spawn/despawn transitions.** Fade/scale in on spawn, fade out on despawn- (respect `prefers-reduced-motion`) so even a legitimate arrival/exit is smooth,- not a pop.-4. Keep the per-fix reposition (`pinWorldPos`) — that's correct; this task governs- *membership*, not position.--## Acceptance checklist--- [ ] A pin held at ~40 m with simulated ±10 m GPS noise stays rendered without a- single dispose/respawn cycle (assert in a unit test on the pure band helper).-- [ ] Exit requires sustained out-of-band (debounced), not one poll.-- [ ] Spawn/despawn are animated; `prefers-reduced-motion` falls back to instant.-- [ ] Server radius cap unchanged (still `Math.min(60, …)`); no roster widening.-- [ ] No extra GLB refetches on a stable pin (watch the Network tab); no console noise.-- [ ] Unit test for the hysteresis band (enter/exit/debounce) added to the suite.--## Out of scope--The arrival cue (task 03) consumes the *stable* arrival signal this produces — keep-the "newly stable in-band" event clean so 03 doesn't double-fire. No server change.--## Verify--`npm run dev` → /irl with `__irlSeedPins` + a scripted GPS wobble around a pin at-the boundary (dev harness per [memory: irl-perf-e2]); confirm the avatar holds-steady and `__irlPerf()` shows no churn in load/evict counts.diff --git a/tasks/irl-privacy/05-location-leak-audit.md b/tasks/irl-privacy/05-location-leak-audit.mddeleted file mode 100644index 30e183ab4..000000000--- a/tasks/irl-privacy/05-location-leak-audit.md+++ /dev/null@@ -1,78 +0,0 @@-# 05 — Location-leak audit across every sibling surface--> Size **M** · Read-heavy audit of `api/irl/*`, `src/irl.js` deep-links,-> `src/irl/share-frame.js`, `src/dashboard-next/pages/irl-*`, plus any agent-profile-> "View in IRL" link. Output: a written audit + fixes for anything that leaks.--## Goal--Close the *side doors*. The nearby read is locked down — but an agent's location-could still leak through a sibling endpoint, a deep-link, a share image, the-dashboard, or an error/log. Audit every surface that touches a pin and prove none-of them lets you resolve **another** user's agent → its location without physical-presence.--## Why it matters--A privacy guarantee is only as strong as its weakest endpoint. We have a family of-IRL endpoints added around the same time (`agent-card`, `agent-summary`,-`interactions`, `interactions-stream`, `report`) plus deep-links (`?agent=`,-`?highlight=`) and a share-frame generator. Any one of them returning a `lat`/`lng`,-an origin coordinate, or an agent→pin mapping that works from afar reopens exactly-the hole we just closed — quietly.--## Current state / where to look (real files)--- `api/irl/agent-card.js`, `api/irl/agent-summary.js` — do their responses include- `lat`/`lng`/`origin_*` for an agent the caller isn't near? They must not (an agent- *card* should describe the agent, not pinpoint it).-- `api/irl/interactions.js`, `api/irl/interactions-stream.js` — the owner SSE inbox.- Confirm the privacy filter (`publicRow`/`matches`, see [memory: irl-d3-interaction-broadcast])- never ships an actor's GPS, and that an interaction record doesn't carry pin coords- to anyone but the owner.-- `api/irl/pins.js` `?mine` / `/mine` feeds — return coordinates, which is correct- (they're the owner's own pins). Confirm they're strictly owner/device-scoped and- can't be coerced cross-user (e.g. a guessed `deviceToken`, a missing auth check).-- `src/irl.js` deep-links: `?agent=<id>` (`agentFocusId`) and `?highlight=<pinId>`- open/flash a pin **only after it loads via the proximity poll**. Confirm neither- fetches or reveals a location for an agent that isn't already in range — i.e. the- deep-link is a "focus it *if* you're near it," never a "take me to it."-- `src/irl/share-frame.js` — the share image/card must not embed lat/lng or a map.-- `src/dashboard-next/pages/irl-placements.js` (+ `irl-reputation`, `irl-outfit-editor`)- — these show the owner *their own* pins (fine); confirm they never fetch others'.-- Logs: grep for any `console.*` that prints pin `lat`/`lng` on a public path- (client-error reporter, server logs) per [memory: observability-stack].--## What to do--1. For each surface above, document **what it returns/exposes** and whether a- non-present, non-owner caller can learn a location. Put it in- `reports/irl-location-leak-audit.md` as a table: surface · exposes coords? ·- owner-scoped? · verdict.-2. Fix every leak found, smallest change that holds the invariant (e.g. drop- `lat`/`lng`/`origin_*` from an agent-card response; tighten an owner check). Add a- focused test for each fix.-3. Re-state the invariant in a one-line code comment at each fixed site so a future- edit doesn't silently re-add the field.--## Acceptance checklist--- [ ] `reports/irl-location-leak-audit.md` covers every `api/irl/*` endpoint, both- deep-links, the share frame, and the three dashboard pages, with a verdict each.-- [ ] No public/non-owner surface returns `lat`/`lng`/`origin_*` or an agent→location- mapping resolvable from afar.-- [ ] `?mine` / `/mine` proven strictly owner/device-scoped (test for the cross-user- attempt → no data).-- [ ] Deep-links (`?agent`, `?highlight`) only focus an already-in-range pin; verified.-- [ ] Each fix has a regression test; full suite green.--## Out of scope--The nearby feed itself (already locked + covered by `irl-pins-location-guards`).-CI wiring of new tests is fine here or rolled into task 07.--## Verify--For each "exposes coords? = no" verdict, run the actual request unauthenticated /-as a non-owner and confirm the response carries no location. Paste the responses-into the audit doc.diff --git a/tests/agent-sniper-ops.test.js b/tests/agent-sniper-ops.test.jsnew file mode 100644index 000000000..1494a1948--- /dev/null+++ b/tests/agent-sniper-ops.test.js@@ -0,0 +1,134 @@+// agent-sniper ops/deploy hardening — config fail-closed + error-spike tracker.+//+// These cover the deploy-safety guarantees the Cloud Run worker depends on:+// 1. loadConfig() refuses to start on missing/invalid env (fail closed), so a+// misconfigured revision crash-loops loudly instead of trading half-blind.+// 2. live mode refuses a missing RPC (a public RPC 429s under the firehose).+// 3. the error-spike tracker pages ONCE per run-up and re-arms only after the+// window drains — so a sustained RPC outage alerts once, not on every error.+//+// Pure logic only: no DB, no network, no pump SDK — fast and deterministic.++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { loadConfig } from '../workers/agent-sniper/config.js';+import { makeErrorTracker } from '../workers/agent-sniper/error-tracker.js';++const SNIPER_KEYS = Object.keys(process.env).filter((k) => k.startsWith('SNIPER_'));++describe('agent-sniper loadConfig — fail closed', () => {+ let saved;+ beforeEach(() => {+ saved = { ...process.env };+ // Start from a clean sniper env each test.+ for (const k of [...SNIPER_KEYS, 'DATABASE_URL', 'JWT_SECRET', 'SOLANA_RPC_URL', 'HELIUS_API_KEY']) {+ delete process.env[k];+ }+ });+ afterEach(() => {+ for (const k of Object.keys(process.env)) delete process.env[k];+ Object.assign(process.env, saved);+ });++ it('throws when DATABASE_URL is missing', () => {+ process.env.JWT_SECRET = 'x';+ expect(() => loadConfig()).toThrow(/DATABASE_URL/);+ });++ it('throws when JWT_SECRET is missing', () => {+ process.env.DATABASE_URL = 'postgres://x';+ expect(() => loadConfig()).toThrow(/JWT_SECRET/);+ });++ it('throws on an invalid SNIPER_MODE', () => {+ process.env.DATABASE_URL = 'postgres://x';+ process.env.JWT_SECRET = 'x';+ process.env.SNIPER_MODE = 'yolo';+ expect(() => loadConfig()).toThrow(/SNIPER_MODE/);+ });++ it('throws on an invalid SNIPER_NETWORK', () => {+ process.env.DATABASE_URL = 'postgres://x';+ process.env.JWT_SECRET = 'x';+ process.env.SNIPER_NETWORK = 'testnet';+ expect(() => loadConfig()).toThrow(/SNIPER_NETWORK/);+ });++ it('refuses live mode without a real RPC', () => {+ process.env.DATABASE_URL = 'postgres://x';+ process.env.JWT_SECRET = 'x';+ process.env.SNIPER_MODE = 'live';+ expect(() => loadConfig()).toThrow(/SOLANA_RPC_URL|HELIUS_API_KEY/);+ });++ it('allows live mode once an RPC is present', () => {+ process.env.DATABASE_URL = 'postgres://x';+ process.env.JWT_SECRET = 'x';+ process.env.SNIPER_MODE = 'live';+ process.env.SOLANA_RPC_URL = 'https://rpc.example';+ const cfg = loadConfig();+ expect(cfg.mode).toBe('live');+ });++ it('defaults to simulate with sane ops knobs', () => {+ process.env.DATABASE_URL = 'postgres://x';+ process.env.JWT_SECRET = 'x';+ const cfg = loadConfig();+ expect(cfg.mode).toBe('simulate');+ expect(cfg.network).toBe('mainnet');+ expect(cfg.heartbeatMs).toBeGreaterThanOrEqual(10_000);+ expect(cfg.errorAlertThreshold).toBeGreaterThanOrEqual(1);+ expect(cfg.errorAlertWindowMs).toBeGreaterThanOrEqual(60_000);+ expect(cfg.announceLifecycle).toBe(true);+ });++ it('clamps the heartbeat cadence to a 10s floor', () => {+ process.env.DATABASE_URL = 'postgres://x';+ process.env.JWT_SECRET = 'x';+ process.env.SNIPER_HEARTBEAT_MS = '1';+ expect(loadConfig().heartbeatMs).toBe(10_000);+ });+});++describe('agent-sniper error-spike tracker', () => {+ it('fires once exactly when the threshold is crossed, not before', () => {+ const t = makeErrorTracker({ threshold: 3, windowMs: 60_000 });+ expect(t.record('a')).toBeNull();+ expect(t.record('b')).toBeNull();+ const spike = t.record('c');+ expect(spike).toMatchObject({ count: 3, windowMs: 60_000, lastError: 'c' });+ });++ it('does not re-fire while still above threshold (armed=false)', () => {+ const t = makeErrorTracker({ threshold: 2, windowMs: 60_000 });+ t.record('a');+ expect(t.record('b')).toMatchObject({ count: 2 }); // trips+ expect(t.record('c')).toBeNull(); // still hot — no second page+ expect(t.record('d')).toBeNull();+ });++ it('re-arms after the window drains below threshold', () => {+ let now = 1_000_000;+ const realNow = Date.now;+ Date.now = () => now;+ try {+ const t = makeErrorTracker({ threshold: 2, windowMs: 10_000 });+ t.record('a');+ expect(t.record('b')).toMatchObject({ count: 2 }); // trips, armed=false+ now += 20_000; // window fully drains+ t.tick(); // prunes + re-arms+ expect(t.total).toBe(0);+ t.record('c');+ expect(t.record('d')).toMatchObject({ count: 2 }); // can trip again+ } finally {+ Date.now = realNow;+ }+ });++ it('tracks the most recent error message and rolling total', () => {+ const t = makeErrorTracker({ threshold: 100, windowMs: 60_000 });+ t.record('first');+ t.record('second');+ expect(t.lastError).toBe('second');+ expect(t.total).toBe(2);+ });+});diff --git a/tests/api/irl-agent-card.test.js b/tests/api/irl-agent-card.test.jsindex b2efd8ba3..890ff9e4f 100644--- a/tests/api/irl-agent-card.test.js+++ b/tests/api/irl-agent-card.test.js@@ -17,22 +17,32 @@ import { deriveReputation } from '../../api/irl/agent-card.js';// ── Mutable fixtures the sql router reads, reset per test ──────────────────────let agentRow = null; // agent_identities row (null → agent 404)+let agentThrows = false; // simulate a missing agent_identities table (query rejects)let repAgg = null; // reputation aggregate rowlet repThrows = false; // simulate a reputation-query failure (must degrade, not 500)+let repEmpty = false; // simulate a successful-but-rowless reputation read ([] result)let serviceRows = []; // agent_paid_services rows+let servicesThrow = false; // simulate a missing agent_paid_services table (query rejects)let pinRow = null; // irl_pins row when resolving by ?pin=// One tagged-template sql mock that routes by the query text, mirroring the real// fan-out in buildCard(): agent SELECT, reputation WITH fb/val, services SELECT.const sqlMock = vi.fn((strings) => {const q = Array.isArray(strings) ? strings.join(' ') : String(strings);- if (/FROM agent_identities/i.test(q)) return Promise.resolve(agentRow ? [agentRow] : []);+ if (/FROM agent_identities/i.test(q)) {+ if (agentThrows) return Promise.reject(new Error('relation "agent_identities" does not exist'));+ return Promise.resolve(agentRow ? [agentRow] : []);+ }if (/FROM irl_pins/i.test(q)) return Promise.resolve(pinRow ? [pinRow] : []);if (/solana_attestations[\s\S]*threews\.feedback/i.test(q)) {if (repThrows) return Promise.reject(new Error('rep table unavailable'));+ if (repEmpty) return Promise.resolve([]); // successful read, zero rowsreturn Promise.resolve([repAgg]);}- if (/FROM agent_paid_services/i.test(q)) return Promise.resolve(serviceRows);+ if (/FROM agent_paid_services/i.test(q)) {+ if (servicesThrow) return Promise.reject(new Error('relation "agent_paid_services" does not exist'));+ return Promise.resolve(serviceRows);+ }return Promise.resolve([]);});// The handler uses `.catch(() => [])` on the agent + services queries, so the mock@@ -78,7 +88,10 @@ beforeEach(() => {avatar_thumbnail_key: 'thumbs/atlas.png', avatar_visibility: 'public',};repAgg = { fb_total: 20, score_avg: 4.6, unique_attesters: 9, val_passed: 3, val_failed: 0, tasks_accepted: 14 };+ agentThrows = false;repThrows = false;+ repEmpty = false;+ servicesThrow = false;serviceRows = [{ slug: 'route-plan', name: 'Route planning', description: 'Plan a multi-stop trip', price_atomics: '50000', network: 'base' },{ slug: 'weather', name: 'Weather brief', description: null, price_atomics: '10000', network: 'base' },@@ -151,6 +164,64 @@ describe('GET /api/irl/agent-card — merged payload', () => {expect(body.card.services).toHaveLength(2); // the menu is unaffected});+ it('never 500s when the reputation table is missing on a fresh DB (degrades, no leak)', async () => {+ // A fresh / mid-migration DB rejects the solana_attestations read. The card+ // must come back 200 with reputation degraded — not a 500 / stack trace.+ repThrows = true;+ const { res, body } = await getCard('agent_id=agent-1');+ expect(res.statusCode).toBe(200);+ expect(body.error).toBeUndefined();+ expect(body.card.reputation).toMatchObject({ available: false, degraded: true });+ expect(body.card.reputation.asset).toBe('THREEsynthetic1111111111111111111111111111');+ });++ it('treats a successful-but-rowless reputation read as zero, not a 500 (undefined-row guard)', async () => {+ // The coalesce'd aggregate normally returns one row; a driver/partial edge+ // could yield []. buildCard must not throw on row.fb_total — it derives from+ // zeros and the card is available with a fresh score, never degraded/500.+ repEmpty = true;+ const { res, body } = await getCard('agent_id=agent-1');+ expect(res.statusCode).toBe(200);+ expect(body.error).toBeUndefined();+ expect(body.card.reputation.available).toBe(true);+ expect(body.card.reputation.degraded).toBeUndefined();+ expect(body.card.reputation.score).toBe(0);+ expect(body.card.reputation.tier).toBe('new');+ expect(body.card.reputation.attestation_count).toBe(0);+ expect(body.card.services).toHaveLength(2);+ });++ it('coerces null aggregate columns to zero rather than NaN/throwing', async () => {+ // score_avg etc. can come back null from coalesce-less driver paths; the+ // derivation must still produce a finite score, not NaN.+ repAgg = { fb_total: null, score_avg: null, unique_attesters: null, val_passed: null, val_failed: null, tasks_accepted: null };+ const { res, body } = await getCard('agent_id=agent-1');+ expect(res.statusCode).toBe(200);+ expect(body.card.reputation.available).toBe(true);+ expect(Number.isFinite(body.card.reputation.score)).toBe(true);+ expect(body.card.reputation.score).toBe(0);+ expect(body.card.reputation.unique_attesters).toBe(0);+ });++ it('survives a fresh DB where agent_identities itself is missing (no 500)', async () => {+ // The agent query .catch(() => []) → no agent → genuine 404 for an explicit+ // agent_id, never an uncaught 500 / stack trace.+ agentThrows = true;+ const { res, body } = await getCard('agent_id=agent-1');+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('survives a fresh DB where agent_paid_services is missing — empty menu, no 500', async () => {+ // The services query .catch(() => []) → empty menu; reputation + agent still render.+ servicesThrow = true;+ const { res, body } = await getCard('agent_id=agent-1');+ expect(res.statusCode).toBe(200);+ expect(body.error).toBeUndefined();+ expect(body.card.services).toEqual([]);+ expect(body.card.agent.name).toBe('Atlas');+ });+it('shows no-reputation (available:false) for an agent with no on-chain asset, never a number', async () => {agentRow.meta = {}; // no sol_mint_addressconst { res, body } = await getCard('agent_id=agent-1');diff --git a/tests/api/irl-pins-hardening.test.js b/tests/api/irl-pins-hardening.test.jsindex 2e08150fe..8b0f4881e 100644--- a/tests/api/irl-pins-hardening.test.js+++ b/tests/api/irl-pins-hardening.test.js@@ -141,15 +141,21 @@ beforeEach(() => {// ── Pure helpers ─────────────────────────────────────────────────────────────describe('isValidPinId', () => {- it('accepts a canonical UUID and rejects garbage / oversized ids', () => {+ it('accepts a canonical UUID + conservative opaque ids', () => {expect(isValidPinId(UUID)).toBe(true);- expect(isValidPinId('not-a-uuid')).toBe(false);+ expect(isValidPinId('pin-1')).toBe(true); // url/path-safe opaque id+ expect(isValidPinId('del_1')).toBe(true);+ });+ it('rejects empty / non-string / oversized / dangerous-shaped ids', () => {expect(isValidPinId('')).toBe(false);expect(isValidPinId(null)).toBe(false);expect(isValidPinId(123)).toBe(false);- expect(isValidPinId('x'.repeat(5000))).toBe(false);+ expect(isValidPinId('x'.repeat(5000))).toBe(false); // oversized+ expect(isValidPinId('has space')).toBe(false); // whitespace+ expect(isValidPinId('a/b')).toBe(false); // path separator// SQL-injection-shaped id is rejected at the boundary (defense in depth).expect(isValidPinId("1' OR '1'='1")).toBe(false);+ expect(isValidPinId('drop;--')).toBe(false);});});@@ -208,7 +214,7 @@ describe('GET /api/irl/pins — radius validation', () => {// ── Pin-id validation on mutations (task 13) ─────────────────────────────────describe('PATCH /api/irl/pins — pin-id validation', () => {it('400s a malformed id before any auth or DB work', async () => {- const { res, body } = await patch({ id: 'garbage', calibrate: { lat: 40.7128, lng: -74.006 } });+ const { res, body } = await patch({ id: "bad id'", calibrate: { lat: 40.7128, lng: -74.006 } });expect(res.statusCode).toBe(400);expect(body.error).toMatch(/invalid pin id/i);const ranSelect = sqlMock.mock.calls.some(([s]) =>@@ -219,7 +225,7 @@ describe('PATCH /api/irl/pins — pin-id validation', () => {describe('DELETE /api/irl/pins — pin-id validation', () => {it('400s a malformed id before the delete query', async () => {- const { res, body } = await del({ id: 'garbage', deviceToken: 'device-A' });+ const { res, body } = await del({ id: "bad id'", deviceToken: 'device-A' });expect(res.statusCode).toBe(400);expect(body.error).toMatch(/invalid pin id/i);const ranDelete = sqlMock.mock.calls.some(([s]) =>@@ -289,6 +295,46 @@ describe('delete — expiry-guarded WHERE', () => {});});+// ── Bulk purge (L5 — Remove all from this device) ────────────────────────────+describe('DELETE /api/irl/pins?all=1 — bulk device purge', () => {+ const deleteQueries = () => sqlMock.mock.calls+ .map(([s]) => (Array.isArray(s) ? s.join(' ') : String(s)))+ .filter((q) => /DELETE FROM irl_pins/i.test(q));++ it('purges every pin for the device token and returns the count', async () => {+ deleteResult = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];+ const { res, body } = await del({ all: '1', deviceToken: 'device-A' });+ expect(res.statusCode).toBe(200);+ expect(body).toEqual({ ok: true, deleted: 3 });+ });++ it('scopes the purge to the device token only — strict IS NOT NULL guard, never by id', async () => {+ await del({ all: '1', deviceToken: 'device-A' });+ const q = deleteQueries().pop();+ expect(q).toBeTruthy();+ expect(q).toMatch(/device_token IS NOT NULL/i);+ expect(q).not.toMatch(/WHERE id =/i);+ // the bound parameter is exactly the caller's device token (no NULL/empty match)+ const call = sqlMock.mock.calls.find(([s]) =>+ /DELETE FROM irl_pins/i.test(Array.isArray(s) ? s.join(' ') : String(s)));+ expect(call.slice(1)).toContain('device-A');+ });++ it('400s a bulk delete with no device token and never runs the delete', async () => {+ const { res, body } = await del({ all: '1' });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/device token/i);+ expect(deleteQueries()).toHaveLength(0);+ });++ it('leaves the single-id delete path unchanged (id-scoped WHERE)', async () => {+ const { res, body } = await del({ id: UUID, deviceToken: 'device-A' });+ expect(res.statusCode).toBe(200);+ expect(body.ok).toBe(true);+ expect(deleteQueries().pop()).toMatch(/WHERE id =/i);+ });+});+// ── Rate-limiter fail-open (task 12) ─────────────────────────────────────────describe('rate limiter fail-open', () => {it('a throwing limiter does not 500 a GET — the request is allowed', async () => {diff --git a/tests/irl-proximity-band.test.js b/tests/irl-proximity-band.test.jsindex 5ce9d1252..815f15956 100644--- a/tests/irl-proximity-band.test.js+++ b/tests/irl-proximity-band.test.js@@ -18,21 +18,26 @@ import {// Mirror of how loadNearbyPins() threads the per-pin debounce counter: feed a series// of (distance, listed) polls through the band and collect the actions, carrying the// rendered flag + oobPolls forward exactly as the real reconcile loop does. Returns-// the action sequence plus whether the pin was ever disposed.+// the action sequence, whether the pin was ever disposed, and how many "newly stable+// in-range" arrival signals fired — loadNearbyPins() calls emitPinStable(entry) on+// exactly the 'spawn' action, so arrivals === the count of 'spawn's. Task 03's+// proximity-arrival cue consumes that signal, so this count IS its no-double-fire+// guarantee under GPS-edge jitter.function runPolls(initialRendered, polls, opts) {let rendered = initialRendered;let oobPolls = 0;const actions = [];+ let arrivals = 0;for (const { distance, listed = true } of polls) {const action = pinBandAction({ distance, rendered, listed, oobPolls }, opts);actions.push(action);- if (action === 'spawn') { rendered = true; oobPolls = 0; }+ if (action === 'spawn') { rendered = true; oobPolls = 0; arrivals += 1; }else if (action === 'keep') { oobPolls = 0; }else if (action === 'wait') { oobPolls += 1; }else if (action === 'drop') { rendered = false; oobPolls = 0; }// 'ignore' leaves an unrendered pin unrendered}- return { actions, disposed: actions.includes('drop') };+ return { actions, disposed: actions.includes('drop'), arrivals };}describe('band constants', () => {@@ -146,3 +151,59 @@ describe('options override the band', () => {expect(actions).toEqual(['wait', 'wait', 'drop']);});});++// The "newly stable in-range" signal task 03 consumes. loadNearbyPins() fires+// emitPinStable(entry) on exactly the band's 'spawn' action — so arrival count ==+// 'spawn' count. These tests pin the contract the arrival cue depends on: one+// signal per genuine arrival, ZERO during edge jitter, and a fresh signal only+// after a genuine departure + return.+describe('newly-stable-in-range arrival signal (→ task 03)', () => {+ it('fires exactly once when a pin first crosses the enter gate', () => {+ // Approach from outside: ignored beyond enter, one arrival on the gate cross,+ // then steady keeps that must not re-fire.+ const { arrivals, actions } = runPolls(false, [+ { distance: 50 }, // ignore — outside enter, not discovered by drifting near+ { distance: 38 }, // spawn — crossed the 40 m gate → ONE arrival+ { distance: 36 }, // keep+ { distance: 41 }, // keep — inside exit (55), still rendered+ ]);+ expect(actions).toEqual(['ignore', 'spawn', 'keep', 'keep']);+ expect(arrivals).toBe(1);+ });++ it('does NOT fire while a steady pin jitters ±10 m at the 40 m edge', () => {+ // The headline bug, viewed from the cue's seat: a pin physically at 40 m with+ // noisy fixes is one arrival on first discovery and then pure keeps — the cue+ // must never re-buzz the user on every wobble.+ const first = runPolls(false, [{ distance: 39 }]); // discovered once+ expect(first.arrivals).toBe(1);+ const noisy = [40, 50, 31, 47, 38, 49, 30, 45, 42, 50, 33, 48]+ .map(distance => ({ distance, listed: true }));+ const after = runPolls(true, noisy); // already rendered → all keeps+ expect(after.arrivals).toBe(0);+ expect(after.actions.every(a => a === 'keep')).toBe(true);+ });++ it('re-fires only after a genuine departure and return', () => {+ // Walk in (arrival), walk away past exit until debounce drops it, then walk+ // back in — that second discovery is a real, separate arrival and SHOULD fire.+ const { arrivals, actions } = runPolls(false, [+ { distance: 35 }, // spawn → arrival 1+ { distance: 60 }, // wait+ { distance: 65 }, // drop (gone)+ { distance: 65, listed: false }, // ignore (not listed, not rendered)+ { distance: 30 }, // spawn → arrival 2 (genuine return)+ ]);+ expect(actions).toEqual(['spawn', 'wait', 'drop', 'ignore', 'spawn']);+ expect(arrivals).toBe(2);+ });++ it('does not fire for a pin that merely refreshed in place', () => {+ // A rendered pin getting fresh server rows every poll (rename/calibrate) stays+ // 'keep' — refreshKnownPin handles the data, the band emits nothing.+ const { arrivals } = runPolls(true, [+ { distance: 12 }, { distance: 13 }, { distance: 11 }, { distance: 14 },+ ]);+ expect(arrivals).toBe(0);+ });+});diff --git a/tests/src/animation-decoration-playback.test.js b/tests/src/animation-decoration-playback.test.jsnew file mode 100644index 000000000..e6e0584df--- /dev/null+++ b/tests/src/animation-decoration-playback.test.js@@ -0,0 +1,160 @@+import { describe, it, expect, vi } from 'vitest';+import { EventDispatcher } from 'three';+import { AnimationManager } from '../../src/animation-manager.js';++// These tests cover the "seamless looping" core of the embed/home avatar UX:+// a one-shot clip (manifest loop:false, e.g. celebrate/wave) must NOT clamp and+// freeze on its final frame — it plays once, then crossfades into the looping+// settle clip (idle), so a small silent thumbnail never hard-snaps at the loop+// boundary. `freeze()` backs the prefers-reduced-motion path: hold a clean pose+// and release the active action so the host render loop can idle.+//+// AnimationManager.playOnce()/crossfadeTo()/freeze() drive a real+// THREE.AnimationMixer + AnimationActions at runtime. Here we stand in+// lightweight doubles for those three primitives (the same approach the+// canonical-support test uses with a fake model) so the manager's own decision+// logic — not three's mixer internals — is what's under test. The mixer double+// is a real EventDispatcher so the `finished` event the settle relies on is the+// genuine three event channel.++function fakeAction(name) {+ return {+ name,+ enabled: true,+ paused: false,+ clampWhenFinished: false,+ _loop: null,+ _played: false,+ reset() {+ this._played = false;+ return this;+ },+ play() {+ this._played = true;+ return this;+ },+ stop() {+ this._played = false;+ return this;+ },+ fadeIn() {+ return this;+ },+ fadeOut() {+ return this;+ },+ setLoop(mode) {+ this._loop = mode;+ return this;+ },+ crossFadeTo() {+ return this;+ },+ getClip() {+ return { name, tracks: [] };+ },+ };+}++// Seed a manager with named actions/clips already "loaded", and a real+// EventDispatcher mixer. model + canonical map stay null so the fallen-pose+// guard (which needs a real rig to sample) is a no-op — every clip is "safe".+function seedManager(names) {+ const mgr = new AnimationManager();+ mgr.mixer = new EventDispatcher();+ mgr.model = null;+ mgr._canonicalToNode = null;+ mgr._animationDefs = names.map((name) => ({+ name,+ url: `/animations/clips/${name}.json`,+ loop: name === 'idle',+ }));+ for (const name of names) {+ const clip = { name, tracks: [] };+ mgr.clips.set(name, clip);+ mgr.actions.set(name, fakeAction(name));+ }+ return mgr;+}++describe('AnimationManager.playOnce (one-shot → settle, no hard snap)', () => {+ it('plays the one-shot as LoopOnce and clamps until the settle picks up', async () => {+ const mgr = seedManager(['celebrate', 'idle']);+ await mgr.playOnce('celebrate', { settleTo: 'idle', fade: 0.2 });++ const celebrate = mgr.actions.get('celebrate');+ expect(mgr.currentName).toBe('celebrate');+ // LoopOnce === 2200 in three; clampWhenFinished holds the final frame so+ // the settle crossfade has something to fade from instead of a frame-0 snap.+ expect(celebrate._loop).toBe(2200);+ expect(celebrate.clampWhenFinished).toBe(true);+ expect(celebrate._played).toBe(true);+ });++ it('crossfades into the settle clip when the one-shot finishes', async () => {+ const mgr = seedManager(['celebrate', 'idle']);+ const crossfadeSpy = vi.spyOn(mgr, 'crossfadeTo');+ await mgr.playOnce('celebrate', { settleTo: 'idle', fade: 0.3 });+ crossfadeSpy.mockClear(); // ignore any crossfade during the initial play++ const celebrate = mgr.actions.get('celebrate');+ // three fires `finished` with the originating action when a LoopOnce action+ // completes; the settle listener reacts only to its own action.+ mgr.mixer.dispatchEvent({ type: 'finished', action: celebrate });++ expect(crossfadeSpy).toHaveBeenCalledWith('idle', 0.3);+ });++ it('ignores a finished event for a different action', async () => {+ const mgr = seedManager(['celebrate', 'idle', 'wave']);+ await mgr.playOnce('celebrate', { settleTo: 'idle' });+ const crossfadeSpy = vi.spyOn(mgr, 'crossfadeTo');++ mgr.mixer.dispatchEvent({ type: 'finished', action: mgr.actions.get('wave') });+ expect(crossfadeSpy).not.toHaveBeenCalled();+ });++ it('does not settle if another clip took over before the one-shot finished', async () => {+ const mgr = seedManager(['celebrate', 'idle', 'dance']);+ await mgr.playOnce('celebrate', { settleTo: 'idle' });+ const celebrate = mgr.actions.get('celebrate');++ // Something else (e.g. a user pill click) grabbed the avatar mid-clip.+ mgr.currentAction = mgr.actions.get('dance');+ mgr.currentName = 'dance';+ const crossfadeSpy = vi.spyOn(mgr, 'crossfadeTo');++ mgr.mixer.dispatchEvent({ type: 'finished', action: celebrate });+ expect(crossfadeSpy).not.toHaveBeenCalled();+ });++ it('settles into the fallback clip when the one-shot is unavailable on the rig', async () => {+ const mgr = seedManager(['idle']); // celebrate not loaded / unsupported+ const crossfadeSpy = vi.spyOn(mgr, 'crossfadeTo');+ await mgr.playOnce('celebrate', { settleTo: 'idle', fade: 0.25 });+ // Never leave the avatar frozen in bind pose — fall straight to idle.+ expect(crossfadeSpy).toHaveBeenCalledWith('idle', 0.25);+ });+});++describe('AnimationManager.freeze (reduced-motion hold)', () => {+ it('pauses the active action and releases it so the render loop can idle', async () => {+ const mgr = seedManager(['idle']);+ await mgr.crossfadeTo('idle', 0);+ const idle = mgr.actions.get('idle');+ expect(mgr.currentAction).toBe(idle);++ mgr.freeze();+ // Held pose: the action stays paused (keeps applying its pose on any later+ // tick) but is no longer the "current" action, so nothing schedules frames.+ expect(idle.paused).toBe(true);+ expect(mgr.currentAction).toBeNull();+ expect(mgr.currentName).toBeNull();+ });++ it('is a no-op when nothing is playing', () => {+ const mgr = seedManager(['idle']);+ expect(() => mgr.freeze()).not.toThrow();+ expect(mgr.currentAction).toBeNull();+ });+});diff --git a/vercel.json b/vercel.jsonindex ae5df926d..216c55018 100644--- a/vercel.json+++ b/vercel.json@@ -2457,6 +2457,10 @@},"dest": "/agent-embed.html"},+ {+ "src": "/agent/([^/]+)/wallet/?",+ "dest": "/agent-wallet.html"+ },{"src": "/agent/index.html","dest": "/agent/index.html"@@ -2874,6 +2878,10 @@"src": "/agents/","dest": "/agents/index.html"},+ {+ "src": "/agents/[^/.]+/wallet/?",+ "dest": "/agent-wallet.html"+ },{"src": "/agents/([^/.]+)","has": [diff --git a/vite.config.js b/vite.config.jsindex 0d027e7ba..39e119065 100644--- a/vite.config.js+++ b/vite.config.js@@ -320,6 +320,7 @@ const appConfig = {'embed-walk': resolve(__dirname, 'pages/embed-walk.html'),'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),+ 'agent-wallet': resolve(__dirname, 'pages/agent-wallet.html'),launches: resolve(__dirname, 'pages/launches.html'),'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),watchlist: resolve(__dirname, 'pages/watchlist.html'),@@ -1017,6 +1018,10 @@ support: resolve(__dirname, 'pages/support.html'),// `[^/.]+` (no dot) mirrors vercel.json's `/agents/([^/.]+)` so// static assets like /agents/boot.js fall through to public/// instead of being served the agent-detail HTML shell.+ // /agent/:id/wallet and /agents/:id/wallet → Agent Wallet hub+ // (must precede the /agent/:id and /agents/:id catch-alls below).+ else if (!filePath && /^\/agents?\/[^/.]+\/wallet\/?$/.test(path))+ filePath = resolve(root, 'pages/agent-wallet.html');else if (!filePath && /^\/agents\/[^/.]+\/?$/.test(path))filePath = resolve(root, 'pages/agent-detail.html');else if (!filePath && /^\/agent\/[^/]+\/edit$/.test(path))diff --git a/workers/agent-sniper/amm-exit.js b/workers/agent-sniper/amm-exit.jsnew file mode 100644index 000000000..02764cb52--- /dev/null+++ b/workers/agent-sniper/amm-exit.js@@ -0,0 +1,146 @@+// agent-sniper — post-graduation AMM exit.+//+// When a position's coin graduates off the pump.fun bonding curve onto the+// canonical pump AMM pool, the bonding-curve sell path (PumpTradeClient+// quoteForSell / buildSellInstructions) can no longer price or close it. This+// module re-quotes and builds the sell against the AMM pool instead, so a+// graduated position still exits on stop-loss / trailing / take-profit /+// timeout with a real fill — never parked.+//+// It reuses the SAME pool resolution + SDK calls the user-driven sell path uses+// (api/pump/[action].js → getAmmPoolState + PumpAmmSdk.sellBaseInput), so there+// is one source of truth for AMM pricing across the platform. All amounts are+// quote atomics; the sniper trades SOL-quoted curves (require_sol_quote), so the+// quote currency on the resolved pool is wSOL and atomics are lamports.++import { getAmmPoolState, getConnection } from '../../api/_lib/pump.js';++const WSOL_MINT = 'So11111111111111111111111111111111111111112';++// Resolve the canonical AMM pool for a graduated mint and read everything the+// pricing + instruction builders need. Throws { code:'pool_not_found' } when the+// coin has NOT graduated (no pool yet) so callers can distinguish "still on the+// curve" from a transient RPC error.+async function resolvePool(network, mintStr) {+ const amm = await getAmmPoolState({ network, mint: mintStr });+ const sdk = await import('@pump-fun/pump-swap-sdk');+ return { amm, sdk };+}++/**+ * Has `mint` graduated to the AMM on `network`? Deterministic — a live canonical+ * pool means the coin is off the curve. Returns false for a missing pool (still+ * on the curve); rethrows transient RPC errors so callers don't treat an outage+ * as "not graduated".+ */+export async function isGraduated({ network, mint }) {+ try {+ await getAmmPoolState({ network, mint });+ return true;+ } catch (err) {+ if (err?.code === 'pool_not_found') return false;+ throw err;+ }+}++/**+ * Re-quote a graduated position's current SOL value off the AMM pool. Mirrors+ * the read-side quote in api/pump/[action].js (functional sellBaseInput against+ * live reserves). Returns lamports (atomics) the sale would net, plus the+ * min-out floor and a derived price-impact figure for the circuit breaker.+ *+ * @param {object} p+ * @param {'mainnet'|'devnet'} p.network+ * @param {string} p.mint+ * @param {import('bn.js')} p.baseAmount token base units held (BN)+ * @param {number} p.slippagePct+ * @returns {Promise<{ poolKey: string, expectedQuoteOut: bigint, minQuoteOut: bigint, priceImpactPct: number }>}+ * @throws {Error} { code: 'pool_not_found' } when the coin has not graduated.+ */+export async function quoteAmmSell({ network, mint, baseAmount, slippagePct }) {+ const { amm, sdk } = await resolvePool(network, mint);+ const priced = priceSellFromPool(amm, sdk, baseAmount, slippagePct);+ return { poolKey: amm.poolKey.toString(), ...priced };+}++// Price a base-token sell against a resolved AMM pool. Mirrors the read-side+// quote in api/pump/[action].js (functional sellBaseInput against live+// reserves). The sniper only opens SOL-quoted curves (require_sol_quote), so a+// pool that resolved to a non-SOL quote breaks the lamports-denominated PnL math+// — refuse rather than mis-price.+function priceSellFromPool(amm, sdk, baseAmount, slippagePct) {+ const { pool, baseReserve, quoteReserve, baseMintAccount, globalConfig, feeConfig } = amm;++ const resolvedQuoteMint = pool.quoteMint?.toString?.() ?? WSOL_MINT;+ if (resolvedQuoteMint !== WSOL_MINT) {+ const e = new Error(`amm pool quote is ${resolvedQuoteMint}, expected wSOL`);+ e.code = 'amm_quote_not_sol';+ throw e;+ }++ const r = sdk.sellBaseInput({+ base: baseAmount,+ slippage: slippagePct,+ baseReserve,+ quoteReserve,+ globalConfig,+ baseMintAccount,+ baseMint: pool.baseMint,+ coinCreator: pool.coinCreator,+ creator: pool.creator,+ feeConfig,+ });+ const expectedQuoteOut = BigInt((r.uiQuote ?? r.minQuote).toString());+ const minQuoteOut = BigInt((r.minQuote ?? r.uiQuote).toString());++ // Price impact: the spot value of the base at current reserves vs. what the+ // constant-product sale actually nets. quote/base spot * base = ideal; the+ // shortfall is impact. Guards a thin post-graduation pool the same way the+ // entry breaker guards a thin curve.+ const priceImpactPct = derivePriceImpact(baseReserve, quoteReserve, baseAmount, expectedQuoteOut);++ return { expectedQuoteOut, minQuoteOut, priceImpactPct };+}++/**+ * Build the AMM sell instructions for a graduated position. Mirrors the+ * user-driven sell builder (api/pump/[action].js): swapSolanaState for the+ * pool + the offline SDK's sellBaseInput, which embeds the slippage-derived+ * min-out floor on-chain. Returns the instructions plus the expected/min SOL out.+ *+ * @param {object} p+ * @param {'mainnet'|'devnet'} p.network+ * @param {string} p.mint+ * @param {import('@solana/web3.js').PublicKey} p.user+ * @param {import('bn.js')} p.baseAmount token base units held (BN)+ * @param {number} p.slippagePct+ * @returns {Promise<{ instructions: import('@solana/web3.js').TransactionInstruction[], poolKey: string, expectedQuoteOut: bigint, minQuoteOut: bigint, priceImpactPct: number }>}+ * @throws {Error} { code: 'pool_not_found' } when the coin has not graduated.+ */+export async function buildAmmSellInstructions({ network, mint, user, baseAmount, slippagePct }) {+ const { amm, sdk } = await resolvePool(network, mint);+ const priced = priceSellFromPool(amm, sdk, baseAmount, slippagePct);++ const offline = new sdk.PumpAmmSdk();+ const online = new sdk.OnlinePumpAmmSdk(getConnection({ network }));+ const swapState = await online.swapSolanaState(amm.poolKey, user);+ const instructions = await offline.sellBaseInput(swapState, baseAmount, slippagePct);++ return { instructions, poolKey: amm.poolKey.toString(), ...priced };+}++// Constant-product price impact for selling `baseIn` into a pool, as a percent+// of the no-impact (spot) value. Clamped to [0, 100]; returns 0 if reserves are+// missing so a quote can't be falsely rejected by the breaker.+function derivePriceImpact(baseReserve, quoteReserve, baseIn, quoteOut) {+ const b = Number(baseReserve?.toString?.() ?? baseReserve ?? 0);+ const q = Number(quoteReserve?.toString?.() ?? quoteReserve ?? 0);+ const inAmt = Number(baseIn?.toString?.() ?? baseIn ?? 0);+ const out = Number(quoteOut ?? 0);+ if (!(b > 0) || !(q > 0) || !(inAmt > 0)) return 0;+ const spotOut = (inAmt * q) / b; // quote per base at current spot * baseIn+ if (!(spotOut > 0)) return 0;+ const impact = ((spotOut - out) / spotOut) * 100;+ if (!Number.isFinite(impact)) return 0;+ return Math.max(0, Math.min(100, impact));+}diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex 8cd0b0c88..dba6cafa3 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -11,6 +11,10 @@ import { loadAgentKeypair } from './keys.js';import { getTradeCtx, signAndSend } from './trade-client.js';import { countOpenPositions, getDailySpend } from './strategy-store.js';import { notifyBuy, notifySell } from '../../api/_lib/sniper/notify.js';+import {+ getSpendLimits, enforceSpendLimit, SpendLimitError, recordSpend, lamportsToUsd,+} from '../../api/_lib/agent-trade-guards.js';+import { buildAmmSellInstructions } from './amm-exit.js';// Fee + rent headroom we keep above the trade size so a buy doesn't fail for// lack of lamports to pay fees / open the token ATA.@@ -39,6 +43,50 @@ function bn(ctx, v) {return new ctx.BN(BigInt(v).toString());}+// ── shared per-agent spend policy ────────────────────────────────────────────+// Bridges the sniper to the same ceiling that governs withdraw / x402 / trade+// (api/_lib/agent-trade-guards.js). Returns { blocked, reason }. Never throws:+// the sniper's own lamports caps stay the hard backstop, so a pricing or DB+// hiccup here degrades to "allow" rather than stalling the trader.+async function enforceSharedSpendPolicy(agentId, network, perTradeLamports) {+ try {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;+ const limits = getSpendLimits(row?.meta);+ // No USD ceiling set → nothing to price or enforce; skip the price call.+ if (limits.daily_usd == null && limits.per_tx_usd == null) return { blocked: false };+ let usdValue = null;+ try {+ usdValue = await lamportsToUsd(perTradeLamports);+ } catch {+ // Can't price the SOL spend right now — don't block (lamports caps hold).+ return { blocked: false };+ }+ await enforceSpendLimit({ agentId, limits, category: 'snipe', usdValue, network });+ return { blocked: false };+ } catch (err) {+ if (err instanceof SpendLimitError) return { blocked: true, reason: 'spend_limit' };+ log.warn?.('spend_policy_check_failed', { agent: agentId, message: err?.message });+ return { blocked: false };+ }+}++// Record a confirmed/simulated snipe buy into the shared custody ledger so it+// counts toward the per-agent daily ceiling and shows in the audit trail.+// Fire-and-forget — prices the SOL spend best-effort, never blocks the trade.+function recordSnipeSpend({ agentId, userId, network, lamports, signature, mode, mint }) {+ (async () => {+ let usd = null;+ try { usd = await lamportsToUsd(lamports); } catch { usd = null; }+ await recordSpend({+ agentId, userId, category: 'snipe', network, asset: 'SOL',+ amountLamports: lamports, usd,+ signature: signature && signature !== 'SIMULATED' ? signature : null,+ status: mode === 'live' ? 'confirmed' : 'ok',+ meta: { mint, mode },+ });+ })().catch((err) => log.warn?.('snipe_spend_record_failed', { agent: agentId, message: err?.message }));+}+/*** Attempt to snipe `mint` for `strat`. All checks short-circuit before any tx.* @returns {Promise<{ status: string, reason?: string, sig?: string }>}@@ -59,6 +107,14 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {const spent = await getDailySpend(strat.agent_id, cfg.network);if (spent + perTrade > BigInt(strat.daily_budget_lamports)) return skip(tag, 'daily_budget');+ // 3b. shared per-agent spend policy (the same ceiling that governs+ // withdraw / x402 / trade). Opt-in: only priced + enforced when the owner+ // has actually set a USD ceiling, so the hot snipe path stays price-call-+ // free otherwise. Pricing/DB hiccups never block — the lamports caps above+ // remain the hard backstop.+ const policy = await enforceSharedSpendPolicy(strat.agent_id, cfg.network, perTrade);+ if (policy.blocked) return skip(tag, policy.reason);+// 4. idempotency lock — claim the (agent,mint,network) slot BEFORE the tx.const claimed = await sql`INSERT INTO agent_sniper_positions@@ -125,6 +181,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {`;log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });+ recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint });return { status: 'open', sig };} catch (err) {return await fail(posId, tag, errCode(err), err);@@ -153,19 +210,35 @@ export async function executeSell({ cfg, position, reason }) {let expectedOut;let built;- try {- const quote = await ctx.client.quoteForSell({ mint: mintPk, baseAmount, slippagePct });- expectedOut = BigInt(quote.expectedQuoteOut.toString());- built = await ctx.client.buildSellInstructions({ mint: mintPk, user: keypair.publicKey, baseAmount, slippagePct });- } catch (err) {- if (err?.name === 'CoinGraduatedError') return await markGraduated(position.id, tag);- throw err;+ let venue = 'bonding_curve';++ // A position already flagged graduated skips the dead curve and goes+ // straight to the AMM — no point re-quoting a curve we know is complete.+ const preGraduated = typeof position.error === 'string' && position.error.startsWith('graduated');+ if (preGraduated) {+ built = await buildGraduatedSell({ cfg, position, keypair, baseAmount, slippagePct });+ expectedOut = built.expectedQuoteOut;+ venue = 'amm';+ } else {+ try {+ const quote = await ctx.client.quoteForSell({ mint: mintPk, baseAmount, slippagePct });+ expectedOut = BigInt(quote.expectedQuoteOut.toString());+ built = await ctx.client.buildSellInstructions({ mint: mintPk, user: keypair.publicKey, baseAmount, slippagePct });+ } catch (err) {+ // Graduation is the one "failure" that isn't one: the curve is+ // complete, so route the same exit through the AMM pool instead of+ // parking the bag. Any other error propagates to the retry handler.+ if (err?.name !== 'CoinGraduatedError') throw err;+ built = await buildGraduatedSell({ cfg, position, keypair, baseAmount, slippagePct });+ expectedOut = built.expectedQuoteOut;+ venue = 'amm';+ }}let sig = 'SIMULATED';if (cfg.mode === 'live') {sig = await signAndSend(ctx, keypair, built.instructions, cfg.confirmTimeoutMs);- } else {+ } else if (venue === 'bonding_curve') {expectedOut = BigInt(built.expectedQuoteOut.toString());}@@ -178,12 +251,13 @@ export async function executeSell({ cfg, position, reason }) {exit_quote_lamports = ${expectedOut.toString()},realized_pnl_lamports = ${pnl.toString()},realized_pnl_pct = ${pnlPct},+ error = ${null},closed_at = now()WHERE id = ${position.id}`;- log.trade('sell', { ...tag, mode: cfg.mode, sig, pnl_sol: lamportsToSol(pnl), pnl_pct: pnlPct.toFixed(1) });+ log.trade('sell', { ...tag, venue, mode: cfg.mode, sig, pnl_sol: lamportsToSol(pnl), pnl_pct: pnlPct.toFixed(1) });notifySell({ agentName: position.agent_name || position.agent_id, symbol: position.symbol, mint: position.mint, pnlSol: lamportsToSol(pnl), pnlPct, exitReason: reason, mode: cfg.mode, sig, chatId: position.telegram_chat_id || null });- return { status: 'closed', sig, pnl: pnl.toString() };+ return { status: 'closed', sig, pnl: pnl.toString(), venue };} catch (err) {// A failed sell must NOT terminate the position — leave it 'open' so the// next tick retries the exit rather than stranding the bag as 'failed'.@@ -194,16 +268,20 @@ export async function executeSell({ cfg, position, reason }) {});}-async function markGraduated(posId, tag) {- // Bonding-curve sell is impossible post-graduation. Flag for the AMM-exit- // fast-follow and stop re-quoting (getOpenPositions excludes 'graduated%').- await sql`- UPDATE agent_sniper_positions- SET error = 'graduated:awaiting_amm_exit', exit_reason = 'graduated', last_quoted_at = now()- WHERE id = ${posId}- `;- log.warn('position graduated — needs AMM exit', tag);- return { status: 'graduated' };+// Build the AMM sell for a graduated position. Reuses the platform's pool+// resolution + PumpAmmSdk (api/pump/[action].js parity) so the exit prices off+// the live pool, with the slippage-derived min-out floor embedded on-chain. In+// `simulate` mode the instructions are still built (proving the path works) but+// never broadcast — expectedQuoteOut becomes the paper fill.+async function buildGraduatedSell({ cfg, position, keypair, baseAmount, slippagePct }) {+ const { instructions, expectedQuoteOut } = await buildAmmSellInstructions({+ network: cfg.network,+ mint: position.mint,+ user: keypair.publicKey,+ baseAmount,+ slippagePct,+ });+ return { instructions, expectedQuoteOut };}function skip(tag, reason) {diff --git a/workers/agent-sniper/strategy-store.js b/workers/agent-sniper/strategy-store.jsindex bd7932e9a..d2c66abc5 100644--- a/workers/agent-sniper/strategy-store.js+++ b/workers/agent-sniper/strategy-store.js@@ -54,7 +54,13 @@ export async function getDailySpend(agentId, network) {return BigInt(r?.spent ?? '0');}-/** Open positions across all agents — the position-loop work set. */+/**+ * Open positions across all agents — the position-loop work set.+ *+ * Graduated positions (error LIKE 'graduated%') are INCLUDED: the sweep+ * re-quotes them off the AMM pool and exits them there, so they no longer park+ * indefinitely. The sweep reads `error` to pick the venue (AMM vs curve).+ */export async function getOpenPositions(network) {return sql`SELECT p.*, s.take_profit_pct, s.stop_loss_pct, s.trailing_stop_pct,@@ -64,7 +70,6 @@ export async function getOpenPositions(network) {JOIN agent_sniper_strategies s ON s.id = p.strategy_idWHERE p.network = ${network}AND p.status = 'open'- AND (p.error IS NULL OR p.error NOT LIKE 'graduated%')ORDER BY p.opened_at ASCLIMIT 200`;