Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Agent custodial trade endpoint + guardrails, AR placement capability, IRL page, changelog
nirholas5306ec8a43d8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb7d81ac6..165b0e9c8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -45,6 +45,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **You can move the moment a Coin Communities world loads** — On phones, the first-time welcome card in /play covered the whole screen — including the movement joystick — so new players tapped the stick and nothing happened until they dismissed the intro. The welcome card is now a non-blocking overlay: the joystick (and look-drag) stay live behind it and sit crisp on top, so you can start walking the instant the world appears, whether you read the intro first or not. (`/play`) `[fix]`- **Your $THREE holder tier now shows across the site** — Holding $THREE is now visible everywhere you are. A holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) on every page and links to the full tier breakdown. On Forge, choosing the High quality tier now shows a clear, designed panel instead of a silent block: holders see an "Unlocked" badge and generate straight away, while everyone else gets a "Get $THREE" path, the exact reason (sign in, link a wallet, or hold more), and a one-tap switch back to free Draft or Standard — no dead ends and no raw errors. (`/forge`) `[feature, improvement]`- **Your agent and its answer now sit together in chat** — When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel. (`/chat`) `[improvement]`+- **Your AR agent now hides behind real-world objects** — Place an agent in your room with the AR button and it now lives in the space instead of floating on top of the camera feed. Walk a chair, a doorway, or your own hand between your phone and the agent and the agent is correctly hidden behind it — the single biggest "is this really in my room?" upgrade. It uses your phone's depth sensor on devices that have one (recent Android Chrome); on every other device AR works exactly as before, with no change and nothing to turn on. (`/features/ar`) `[feature]`## 2026-06-17diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.jsindex e5e88a9fc..9b79af6b2 100644--- a/api/_lib/agent-trade-guards.js+++ b/api/_lib/agent-trade-guards.js@@ -34,12 +34,41 @@ const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const MAX_ALLOWLIST = 50;+// Fee + rent headroom kept above a buy so it never fails for lack of lamports to+// pay the network fee / open the token ATA. The single source of truth for the+// SOL-headroom floor — both the sniper executor and the discretionary+// agent-wallet trade endpoint import this rather than redefining it.+export const SOL_FEE_HEADROOM_LAMPORTS = 3_000_000n; // ~0.003 SOL+export const SPEND_LIMIT_DEFAULTS = Object.freeze({daily_usd: null,per_tx_usd: null,withdraw_allowlist: [],});+// Per-agent discretionary-trade policy (lamports-denominated), stored at+// agent_identities.meta.trade_limits. Distinct from meta.spend_limits (the+// cross-path USD ceiling): these are the SOL-budget + circuit-breaker knobs that+// govern the agent's own buys, mirroring the sniper's per-strategy caps so the+// discretionary path is held to the same standard. All opt-in — a null cap means+// "no lamports ceiling" and the trade is still governed by the USD spend policy+// and the wallet balance.+//+// per_trade_sol max SOL spent on any single buy (null = uncapped)+// daily_budget_sol rolling-24h SOL buy budget across trade + snipe (null = uncapped)+// max_price_impact_pct circuit breaker — reject a buy/sell over this impact+// max_slippage_bps ceiling on the client-supplied slippage+// max_concurrent max open discretionary positions (null = unlimited)+// kill_switch when true, every discretionary trade is rejected+export const TRADE_LIMIT_DEFAULTS = Object.freeze({+ per_trade_sol: null,+ daily_budget_sol: null,+ max_price_impact_pct: 15,+ max_slippage_bps: 1000,+ max_concurrent: null,+ kill_switch: false,+});+/*** A spend-policy breach. Always a structured 4xx (never a 500) so the boundary* can surface the reason to the user verbatim. `.code` is machine-readable;@@ -162,6 +191,217 @@ export async function lamportsToUsd(lamports) {return (Number(lamports) / 1e9) * price;}+// ── discretionary trade limits ────────────────────────────────────────────────++function clampNum(v, def, { min = 0, max = Infinity, round = false } = {}) {+ const n = Number(v);+ if (!Number.isFinite(n) || n < min) return def;+ const c = Math.min(max, n);+ return round ? Math.round(c) : c;+}++/** Coerce arbitrary input into a clean, bounded trade-limit object. */+export function normalizeTradeLimits(raw) {+ const r = raw && typeof raw === 'object' ? raw : {};+ return {+ per_trade_sol: numOrNull(r.per_trade_sol),+ daily_budget_sol: numOrNull(r.daily_budget_sol),+ max_price_impact_pct: clampNum(r.max_price_impact_pct, TRADE_LIMIT_DEFAULTS.max_price_impact_pct, { max: 100 }),+ max_slippage_bps: clampNum(r.max_slippage_bps, TRADE_LIMIT_DEFAULTS.max_slippage_bps, { max: 10000, round: true }),+ max_concurrent: r.max_concurrent == null ? null : clampNum(r.max_concurrent, null, { min: 1, max: 10000, round: true }),+ kill_switch: r.kill_switch === true,+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,+ };+}++/** Read the effective discretionary trade limits off an agent's meta blob. */+export function getTradeLimits(meta) {+ return normalizeTradeLimits(meta?.trade_limits);+}++/**+ * Persist a trade-limit patch onto the agent (owner-only). Only the keys present+ * in `patch` change; the rest are preserved. Writes a custody audit event and a+ * platform audit-log row. Returns the new normalized limits.+ */+export async function setTradeLimits(agentId, userId, patch, { req = null } = {}) {+ const [row] = await sql`+ SELECT id, user_id, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!row) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });+ if (row.user_id !== userId) throw Object.assign(new Error('not your agent'), { status: 403, code: 'forbidden' });++ const prev = getTradeLimits(row.meta);+ const p = patch && typeof patch === 'object' ? patch : {};+ const next = normalizeTradeLimits({+ per_trade_sol: 'per_trade_sol' in p ? p.per_trade_sol : prev.per_trade_sol,+ daily_budget_sol: 'daily_budget_sol' in p ? p.daily_budget_sol : prev.daily_budget_sol,+ max_price_impact_pct: 'max_price_impact_pct' in p ? p.max_price_impact_pct : prev.max_price_impact_pct,+ max_slippage_bps: 'max_slippage_bps' in p ? p.max_slippage_bps : prev.max_slippage_bps,+ max_concurrent: 'max_concurrent' in p ? p.max_concurrent : prev.max_concurrent,+ kill_switch: 'kill_switch' in p ? p.kill_switch : prev.kill_switch,+ });+ next.updated_at = new Date().toISOString();++ const meta = { ...(row.meta || {}), trade_limits: next };+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agentId}`;++ await recordCustodyEvent({+ agentId,+ userId,+ eventType: 'limit_change',+ reason: 'trade_limits_updated',+ meta: { prev, next },+ }).catch((e) => console.warn('[custody] trade limit_change record failed', e?.message));+ logAudit({ userId, action: 'custody.trade_limit_change', resourceId: agentId, meta: { prev, next }, req });++ return next;+}++// ── trade guard predicates ────────────────────────────────────────────────────+// Each returns null when the trade is allowed, or a structured+// { reason, detail } when blocked. These are the single source of truth for the+// "is this trade allowed" comparisons — the sniper executor and the discretionary+// agent-wallet trade endpoint both call them instead of inlining the math, so a+// cap or breaker can never drift between the two paths. Pure + synchronous: the+// caller fetches the live numbers (open count, daily spend, wallet balance,+// quote) and hands them in.++/** Discretionary trading paused for this agent. */+export function checkKillSwitch(killed) {+ return killed ? { reason: 'kill_switch', detail: {} } : null;+}++/** Open-position concurrency ceiling. Blocked when openCount >= maxConcurrent. */+export function checkConcurrency(openCount, maxConcurrent) {+ if (maxConcurrent == null) return null;+ if (Number(openCount) >= Number(maxConcurrent)) {+ return { reason: 'max_positions', detail: { open: Number(openCount), max: Number(maxConcurrent) } };+ }+ return null;+}++/** Per-trade spend cap (lamports). Blocked when amount > cap. */+export function checkPerTradeCap(amountLamports, capLamports) {+ if (capLamports == null) return null;+ const amt = BigInt(amountLamports);+ const cap = BigInt(capLamports);+ if (amt > cap) {+ return { reason: 'per_trade_cap', detail: { amount_lamports: amt.toString(), cap_lamports: cap.toString() } };+ }+ return null;+}++/** Rolling daily budget (lamports). Blocked when spent + amount > budget. */+export function checkDailyBudgetLamports(spentLamports, amountLamports, budgetLamports) {+ if (budgetLamports == null) return null;+ const spent = BigInt(spentLamports);+ const amt = BigInt(amountLamports);+ const budget = BigInt(budgetLamports);+ if (spent + amt > budget) {+ return {+ reason: 'daily_budget',+ detail: { spent_lamports: spent.toString(), amount_lamports: amt.toString(), budget_lamports: budget.toString() },+ };+ }+ return null;+}++/** Wallet must cover the spend plus a fee/rent headroom. Blocked when short. */+export function checkSolHeadroom(walletLamports, spendLamports, headroomLamports = SOL_FEE_HEADROOM_LAMPORTS) {+ const wallet = BigInt(walletLamports);+ const spend = BigInt(spendLamports);+ const head = BigInt(headroomLamports);+ if (wallet < spend + head) {+ return {+ reason: 'insufficient_sol',+ detail: { wallet_lamports: wallet.toString(), required_lamports: (spend + head).toString() },+ };+ }+ return null;+}++/** Price-impact circuit breaker. Blocked when impact > max. */+export function checkPriceImpact(priceImpactPct, maxPct) {+ if (maxPct == null) return null;+ if (Number(priceImpactPct) > Number(maxPct)) {+ return { reason: 'price_impact', detail: { impact_pct: Number(priceImpactPct), max_pct: Number(maxPct) } };+ }+ return null;+}++/** Lamports spent (buys) by an agent over the trailing window — the trade ++ * snipe SOL outflow that backs the discretionary daily budget. One wallet, one+ * budget: a buy from the sniper and a buy from the trade endpoint both count. */+export async function getDailySpendLamports(agentId, network = 'mainnet', windowHours = 24) {+ const [row] = await sql`+ SELECT COALESCE(SUM(amount_lamports), 0)::text AS lamports+ FROM agent_custody_events+ WHERE agent_id = ${agentId}+ AND network = ${network}+ AND event_type = 'spend'+ AND status IN ('ok', 'pending', 'confirmed')+ AND amount_lamports IS NOT NULL+ AND created_at > now() - (${windowHours} || ' hours')::interval+ `;+ return BigInt(row?.lamports ?? '0');+}++const LAMPORTS_PER_SOL = 1_000_000_000n;++function lamportsToSolStr(lamports, dp = 4) {+ const n = Number(BigInt(lamports)) / 1e9;+ return n.toFixed(dp).replace(/\.?0+$/, '') || '0';+}++// Map a guard-predicate reason → an HTTP status + a plain-language, actionable+// message for the boundary. A guard rejection is always a 4xx with the reason and+// the numbers behind it — never a 500, never an exception that escapes.+const GUARD_RESPONSE = {+ kill_switch: {+ status: 403,+ message: () => 'Trading is paused for this agent. Re-enable discretionary trading under Limits & Safety to continue.',+ },+ per_trade_cap: {+ status: 422,+ message: (d) => `This trade of ${lamportsToSolStr(d.amount_lamports)} SOL is over the per-trade cap of ${lamportsToSolStr(d.cap_lamports)} SOL. Lower the amount or raise the cap under Limits & Safety.`,+ },+ daily_budget: {+ status: 422,+ message: (d) => `This trade would bring today's spend to ${lamportsToSolStr(BigInt(d.spent_lamports) + BigInt(d.amount_lamports))} SOL, over the daily budget of ${lamportsToSolStr(d.budget_lamports)} SOL. Wait for the window to roll over or raise the budget.`,+ },+ max_positions: {+ status: 409,+ message: (d) => `This agent already holds ${d.open} open ${d.open === 1 ? 'trade' : 'trades'} (max ${d.max}). Close one before opening another.`,+ },+ insufficient_sol: {+ status: 400,+ message: (d) => `The agent wallet needs about ${lamportsToSolStr(d.required_lamports)} SOL (including network fees) but holds ${lamportsToSolStr(d.wallet_lamports)}. Fund the wallet and retry.`,+ },+ price_impact: {+ status: 422,+ message: (d) => `Price impact is ${Number(d.impact_pct).toFixed(2)}% — above the ${Number(d.max_pct).toFixed(2)}% safety breaker. Lower the trade size or raise the impact limit under Limits & Safety.`,+ },+};++/**+ * Turn a guard-predicate result into a boundary-ready 4xx response shape.+ * @param {{ reason: string, detail?: object }} blocked+ * @returns {{ status: number, code: string, message: string, detail: object }}+ */+export function tradeGuardResponse(blocked) {+ const entry = GUARD_RESPONSE[blocked.reason] || { status: 422, message: () => `Trade rejected: ${blocked.reason}` };+ return {+ status: entry.status,+ code: blocked.reason,+ message: entry.message(blocked.detail || {}),+ detail: blocked.detail || {},+ };+}++export { LAMPORTS_PER_SOL };+/*** Sum the USD-equivalent of an agent's outbound spends over the trailing window.* Only priced rows (usd not null) count — see module header on unpriced SPL.diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 9e20db538..b000f54ee 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -524,6 +524,14 @@ export const limits = {// custodial withdrawals.withdrawalPerUser: (userId) =>getLimiter('withdrawal:user', { limit: 5, window: '1 d', critical: true }).limit(userId),+ // Discretionary agent-wallet trades: server-signed buys/sells from the agent's+ // custodial wallet (POST /api/agents/:id/trade). Each one moves real funds and+ // decrypts a custodial key, so it gets its own per-user write budget separate+ // from the strict per-IP `authIp` ceiling — 30/min lets an owner actively trade+ // while still capping a runaway client or a hijacked session. Critical so a+ // Redis outage fails closed rather than uncapping custodial spends.+ tradePerUser: (userId) =>+ getLimiter('agent-trade:user', { limit: 30, window: '1 m', critical: true }).limit(userId),// Per-user audit-log reads — the page polls on mount + "load older". 120/min// per user is generous for browse but discourages scraping the full year.// local: per-user browse/poll of one's own audit log — no side effects, nodiff --git a/api/agents/[id].js b/api/agents/[id].jsindex e8da56b1d..11e3bcfa3 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -4,6 +4,9 @@* /api/agents/:id/solana — agent's Solana wallet (address + balance, provision)* /api/agents/:id/solana/activity — recent on-chain signatures for the wallet* /api/agents/:id/solana/airdrop — devnet airdrop (1 SOL)+ * /api/agents/:id/trade — owner-only: buy/sell a pump.fun token from the agent's custodial wallet+ * /api/agents/:id/trade/quote — owner-only: preview expected out, price impact, fees, guard verdict+ * /api/agents/:id/trade/limits — owner-only: read/update the per-agent discretionary trade limits* /api/agents/:id/sns — list owned .sol domains and attach one as the agent's SNS id* /api/agents/:id/actions — paginated signed action log* /api/agents/:id/animations — owner-only: replace meta.animations@@ -60,6 +63,11 @@ export default wrap(async function handler(req, res) {return mod.default(req, res, id, action);}+ if (sub === 'trade') {+ const mod = await import('./agent-trade.js');+ return mod.default(req, res, id, action);+ }+if (sub === 'eth-vanity') {const mod = await import('./eth-vanity.js');return mod.default(req, res, id, action);diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.jsnew file mode 100644index 000000000..42984279c--- /dev/null+++ b/api/agents/agent-trade.js@@ -0,0 +1,695 @@+// POST /api/agents/:id/trade — discretionary, owner-authenticated pump.fun trade+// from the agent's OWN custodial wallet (server-signed).+//+// This is the discretionary sibling of the sniper: same instruction builders+// (PumpTradeClient buy/sell, AMM sell on graduation), same custodial key path+// (recoverSolanaAgentKeypair, audit-logged), and — critically — the SAME shared+// guardrail module (api/_lib/agent-trade-guards.js). The owner funds the agent+// wallet, then drives buys/sells through this endpoint; every trade is capped,+// budgeted, price-impact-broken, idempotent, and recorded into the custody+// ledger that backs the spend ceilings and the owner-facing audit feed.+//+// Routes (dispatched from api/agents/[id].js, sub === 'trade'):+// POST /api/agents/:id/trade execute a buy/sell+// POST /api/agents/:id/trade/quote preview: expected out, impact, fees, guards+// GET /api/agents/:id/trade/quote same preview via query params+// GET /api/agents/:id/trade/limits read the per-agent trade limits+// PUT /api/agents/:id/trade/limits update the per-agent trade limits (owner)+//+// SNIPER_MODE=simulate or { simulate: true } runs the full real-quote path but+// skips the broadcast (paper mode) — an ops/test toggle, never the default.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { ensureAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';+import { getConnection, getPumpTradeClient } from '../_lib/pump.js';+import { buildAmmSellInstructions, quoteAmmSell } from '../../workers/agent-sniper/amm-exit.js';+import { logAudit } from '../_lib/audit.js';+import { explorerTxUrl } from '../_lib/avatar-wallet.js';+import { PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, getMint,+ TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';+import { randomUUID } from 'node:crypto';+import {+ validateSolanaAddress, enforceSpendLimit, SpendLimitError, lamportsToUsd,+ getSpendLimits, getTradeLimits, setTradeLimits, getDailySpendLamports,+ recordCustodyEvent, updateCustodyEvent,+ checkKillSwitch, checkConcurrency, checkPerTradeCap, checkDailyBudgetLamports,+ checkSolHeadroom, checkPriceImpact, tradeGuardResponse,+ SOL_FEE_HEADROOM_LAMPORTS, LAMPORTS_PER_SOL, TRADE_LIMIT_DEFAULTS,+} from '../_lib/agent-trade-guards.js';++const WSOL_MINT = 'So11111111111111111111111111111111111111112';+const CONFIRM_TIMEOUT_MS = 45_000;++function normNetwork(n) {+ return n === 'devnet' ? 'devnet' : 'mainnet';+}++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++// Owner gate shared by every route here. On any failure it writes the response+// and returns { error: true }; on success returns the owner + agent row + meta.+async function loadOwnedAgent(req, res, id) {+ const auth = await resolveAuth(req);+ if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return { error: true }; }++ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return { error: true }; }+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'not your agent'); return { error: true }; }++ return { auth, row, meta: { ...(row.meta || {}) } };+}++// Whole-token → base units, and SOL → lamports, without float drift on the+// integer part. amount is already validated finite + positive.+function toBaseUnits(amount, decimals) {+ const [whole, frac = ''] = String(amount).split('.');+ const fracPadded = (frac + '0'.repeat(decimals)).slice(0, decimals);+ return BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt(fracPadded || '0');+}++function solToLamports(sol) {+ return toBaseUnits(sol, 9);+}++function lamportsToSol(l) {+ return Number(BigInt(l)) / 1e9;+}++// Resolve the agent's SPL holding for a mint: token program, decimals, ATA, and+// current base-unit balance. Throws a structured boundary error on any miss.+async function resolveHolding(conn, mintPk, ownerPk) {+ let mintAcc;+ try {+ mintAcc = await conn.getAccountInfo(mintPk);+ } catch {+ mintAcc = null;+ }+ if (!mintAcc) throw boundary(400, 'invalid_mint', 'token mint not found on this network');+ const tokenProgramId = mintAcc.owner.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;++ let decimals;+ try {+ decimals = (await getMint(conn, mintPk, 'confirmed', tokenProgramId)).decimals;+ } catch {+ throw boundary(400, 'invalid_mint', 'could not read the token mint');+ }++ const ata = getAssociatedTokenAddressSync(mintPk, ownerPk, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);+ let balanceRaw = 0n;+ try {+ balanceRaw = BigInt((await conn.getTokenAccountBalance(ata)).value.amount);+ } catch {+ balanceRaw = 0n; // no ATA → holds none+ }+ return { tokenProgramId, decimals, ata, balanceRaw };+}++function boundary(status, code, message, detail = {}) {+ return Object.assign(new Error(message), { status, code, detail, isBoundary: true });+}++function isGraduatedErr(err) {+ return err?.name === 'CoinGraduatedError' || err?.code === 'CoinGraduated';+}++// Price a buy or sell against live state. Returns everything the guards and the+// builder need. Throws boundary() errors for bad input / unpriceable / RPC.+async function quoteTrade({ ctx, side, mintPk, amount, isMax, slippagePct, network, ownerPk }) {+ const slippageBps = Math.round(slippagePct * 100);++ if (side === 'buy') {+ const lamports = solToLamports(amount);+ if (lamports <= 0n) throw boundary(400, 'invalid_amount', 'amount rounds to zero lamports');+ let q;+ try {+ q = await ctx.client.quoteForBuy({ mint: mintPk, quoteAmount: new ctx.BN(lamports.toString()), slippagePct });+ } catch (err) {+ if (isGraduatedErr(err)) {+ throw boundary(409, 'graduated', 'This coin has graduated off the bonding curve. Buying it from the agent wallet via the AMM isn’t supported on this path yet.');+ }+ throw boundary(502, 'quote_failed', `could not price the buy: ${err?.message || 'unknown error'}`);+ }+ requireSolQuote(ctx, q.quoteMint);+ const expectedBase = BigInt(q.expectedBaseTokens.toString());+ if (expectedBase <= 0n) throw boundary(422, 'zero_out', 'this amount buys zero tokens — raise it');+ const minOut = (expectedBase * BigInt(10000 - slippageBps)) / 10000n;+ return {+ venue: 'bonding_curve',+ lamports, baseAmount: null, decimals: null,+ expectedOutRaw: expectedBase, minOutRaw: minOut,+ priceImpactPct: Number(q.priceImpactPct ?? 0),+ usdValue: null, slippageBps,+ };+ }++ // sell+ const conn = ctx.connection;+ const { decimals, balanceRaw } = await resolveHolding(conn, mintPk, ownerPk);+ if (balanceRaw <= 0n) throw boundary(400, 'insufficient_token_balance', 'the agent holds none of this token');+ const baseAmount = isMax ? balanceRaw : toBaseUnits(amount, decimals);+ if (baseAmount <= 0n) throw boundary(400, 'invalid_amount', 'amount rounds to zero token units');+ if (baseAmount > balanceRaw) {+ throw boundary(400, 'insufficient_token_balance', 'amount exceeds the agent token balance', {+ balance_raw: balanceRaw.toString(), decimals,+ });+ }++ const baseBn = new ctx.BN(baseAmount.toString());+ let expectedSolOut;+ let priceImpactPct;+ let venue = 'bonding_curve';+ try {+ const q = await ctx.client.quoteForSell({ mint: mintPk, baseAmount: baseBn, slippagePct });+ requireSolQuote(ctx, q.quoteMint);+ expectedSolOut = BigInt(q.expectedQuoteOut.toString());+ priceImpactPct = Number(q.priceImpactPct ?? 0);+ } catch (err) {+ if (!isGraduatedErr(err)) {+ if (err?.isBoundary) throw err;+ throw boundary(502, 'quote_failed', `could not price the sell: ${err?.message || 'unknown error'}`);+ }+ // Graduated: route the quote through the canonical AMM pool.+ const a = await quoteAmmSell({ network, mint: mintPk.toBase58(), baseAmount: baseBn, slippagePct });+ expectedSolOut = a.expectedQuoteOut;+ priceImpactPct = Number(a.priceImpactPct ?? 0);+ venue = 'amm';+ }+ const minOut = (expectedSolOut * BigInt(10000 - slippageBps)) / 10000n;+ return {+ venue,+ lamports: null, baseAmount, decimals,+ expectedOutRaw: expectedSolOut, minOutRaw: minOut,+ priceImpactPct, usdValue: null, slippageBps,+ };+}++function requireSolQuote(ctx, quoteMint) {+ if (!quoteMint) return;+ const isDefault = quoteMint.equals?.(ctx.web3.PublicKey.default);+ const b58 = quoteMint.toBase58?.();+ if (isDefault || b58 === WSOL_MINT) return;+ throw boundary(422, 'quote_not_sol', 'this coin is not SOL-quoted — the agent wallet trades in SOL on this path');+}++// Build the on-chain instructions for a prepared trade.+async function buildTradeInstructions({ ctx, side, venue, mintPk, ownerPk, lamports, baseAmount, slippagePct, network }) {+ if (side === 'buy') {+ const built = await ctx.client.buildBuyInstructions({+ mint: mintPk, user: ownerPk, quoteAmount: new ctx.BN(lamports.toString()), slippagePct,+ });+ return { instructions: built.instructions, expectedOutRaw: BigInt(built.expectedBaseTokens.toString()) };+ }+ const baseBn = new ctx.BN(baseAmount.toString());+ if (venue === 'amm') {+ const built = await buildAmmSellInstructions({ network, mint: mintPk.toBase58(), user: ownerPk, baseAmount: baseBn, slippagePct });+ return { instructions: built.instructions, expectedOutRaw: built.expectedQuoteOut };+ }+ const built = await ctx.client.buildSellInstructions({ mint: mintPk, user: ownerPk, baseAmount: baseBn, slippagePct });+ return { instructions: built.instructions, expectedOutRaw: BigInt(built.expectedQuoteOut.toString()) };+}++// Run every guard for a prepared trade. Returns null if clear, or a 4xx response+// shape. Buys are gated on the lamport caps + USD ceiling + balance; sells only+// move SOL inward, so they skip the spend caps but still honor the kill switch,+// the price-impact breaker, and a fee-headroom floor.+async function runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta }) {+ const killed = checkKillSwitch(tradeLimits.kill_switch);+ if (killed) return tradeGuardResponse(killed);++ const impact = checkPriceImpact(prep.priceImpactPct, tradeLimits.max_price_impact_pct);+ if (impact) return tradeGuardResponse(impact);++ if (side === 'buy') {+ const lamports = prep.lamports;+ const capLamports = tradeLimits.per_trade_sol == null ? null : solToLamports(tradeLimits.per_trade_sol);+ const cap = checkPerTradeCap(lamports, capLamports);+ if (cap) return tradeGuardResponse(cap);++ if (tradeLimits.max_concurrent != null) {+ const open = await countOpenTrades(id, network);+ const conc = checkConcurrency(open, tradeLimits.max_concurrent);+ if (conc) return tradeGuardResponse(conc);+ }++ const budgetLamports = tradeLimits.daily_budget_sol == null ? null : solToLamports(tradeLimits.daily_budget_sol);+ if (budgetLamports != null) {+ const spent = await getDailySpendLamports(id, network);+ const budget = checkDailyBudgetLamports(spent, lamports, budgetLamports);+ if (budget) return tradeGuardResponse(budget);+ }++ // Cross-path USD ceiling (shared with withdraw / x402 / snipe).+ try {+ await enforceSpendLimit({ agentId: id, meta, category: 'trade', usdValue: prep.usdValue, network });+ } catch (e) {+ if (e instanceof SpendLimitError) return { status: e.status, code: e.code, message: e.message, detail: e.detail };+ throw e;+ }++ const headroom = checkSolHeadroom(walletLamports, lamports, SOL_FEE_HEADROOM_LAMPORTS);+ if (headroom) return tradeGuardResponse(headroom);+ } else {+ // Sell: only needs enough SOL on hand to pay the network fee (and maybe+ // open a wSOL/quote ATA). Reuse the same headroom floor with zero spend.+ const headroom = checkSolHeadroom(walletLamports, 0n, SOL_FEE_HEADROOM_LAMPORTS);+ if (headroom) {+ return tradeGuardResponse({+ reason: 'insufficient_sol',+ detail: { wallet_lamports: BigInt(walletLamports).toString(), required_lamports: SOL_FEE_HEADROOM_LAMPORTS.toString() },+ });+ }+ }+ return null;+}++// Count the agent's open discretionary trades in the trailing window — buys that+// haven't been closed by a matching sell. A lightweight concurrency signal drawn+// from the unified custody ledger (only enforced when max_concurrent is set).+async function countOpenTrades(agentId, network) {+ const [r] = await sql`+ SELECT count(*)::int AS n FROM agent_custody_events+ WHERE agent_id = ${agentId} AND network = ${network}+ AND event_type = 'spend' AND category = 'trade'+ AND status IN ('pending', 'confirmed', 'ok')+ AND (meta->>'side') = 'buy'+ AND created_at > now() - interval '24 hours'+ `;+ return r?.n ?? 0;+}++// Parse + validate the trade request body into a normalized shape, or throw a+// boundary() error. Shared by execute + preview.+function parseTradeInput(body, tradeLimits) {+ const side = body.side === 'sell' ? 'sell' : body.side === 'buy' ? 'buy' : null;+ if (!side) throw boundary(400, 'invalid_side', 'side must be "buy" or "sell"');++ const mintCheck = validateSolanaAddress(body.mint);+ if (!mintCheck.valid) throw boundary(400, 'invalid_mint', `mint is not a valid Solana address (${mintCheck.reason})`);++ const denom = side === 'buy' ? 'sol' : 'token';+ const isMax = side === 'sell' && (body.amount === 'max' || body.amount === 'MAX' || body.amount === 'all');+ let amount = null;+ if (!isMax) {+ amount = Number(body.amount);+ if (!Number.isFinite(amount) || amount <= 0) {+ throw boundary(400, 'invalid_amount', side === 'buy' ? 'amount (SOL to spend) must be a positive number' : 'amount (tokens to sell) must be a positive number or "max"');+ }+ }++ const requestedBps = Number.isFinite(Number(body.slippageBps)) ? Math.round(Number(body.slippageBps)) : tradeLimits.max_slippage_bps;+ const slippageBps = Math.max(0, Math.min(tradeLimits.max_slippage_bps, requestedBps));++ return {+ side, denom, isMax, amount,+ mintPk: mintCheck.pubkey,+ mint: mintCheck.base58,+ slippageBps,+ slippagePct: slippageBps / 100,+ network: normNetwork(body.network),+ simulate: body.simulate === true || process.env.SNIPER_MODE === 'simulate',+ idempotencyKey: typeof body.idempotency_key === 'string' && body.idempotency_key.trim()+ ? body.idempotency_key.trim().slice(0, 128)+ : null,+ };+}++// ── execute ─────────────────────────────────────────────────────────────────++async function handleExecute(req, res, id) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const owned = await loadOwnedAgent(req, res, id);+ if (owned.error) return;+ const { auth, meta } = owned;++ const rlUser = await limits.tradePerUser(auth.userId);+ if (!rlUser.success) return rateLimited(res, rlUser);+ const rlIp = await limits.authIp(clientIp(req));+ if (!rlIp.success) return rateLimited(res, rlIp);++ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');+ }++ const tradeLimits = getTradeLimits(meta);+ let input;+ try {+ input = parseTradeInput(body, tradeLimits);+ } catch (e) {+ return boundaryError(res, e);+ }+ const { side, network, simulate, slippagePct } = input;+ const idempotencyKey = input.idempotencyKey || randomUUID();++ // Guarantee the wallet exists (lazy provision) so a funded-but-unprovisioned+ // agent can trade. ensureAgentWallet audits the provision and never returns+ // the secret.+ let address;+ try {+ address = (await ensureAgentWallet(id, auth.userId, { reason: 'trade' })).address;+ } catch (e) {+ return error(res, 500, 'wallet_unavailable', 'could not prepare the agent wallet — try again');+ }+ const ownerPk = new PublicKey(address);++ // Fast-path idempotency: a retry of a finished/in-flight trade with the same key.+ {+ const [existing] = await sql`+ SELECT id, status, signature, meta FROM agent_custody_events+ WHERE agent_id = ${id} AND idempotency_key = ${idempotencyKey}+ `;+ if (existing) {+ if (existing.status === 'confirmed') {+ return json(res, 200, { data: { replayed: true, signature: existing.signature, explorer: explorerTxUrl(existing.signature, network), network, ...(existing.meta || {}) } });+ }+ if (existing.status === 'pending') {+ return error(res, 409, 'trade_in_progress', 'a trade with this id is already in flight — check the audit log before retrying', { signature: existing.signature || null });+ }+ return error(res, 409, 'trade_failed', 'this trade id already failed — retry with a fresh idempotency key', { signature: existing.signature || null });+ }+ }++ let ctx;+ try {+ ctx = await getPumpTradeClient({ network });+ } catch (e) {+ return error(res, 502, 'rpc_error', 'could not connect to the trade RPC — try again');+ }+ const conn = ctx.connection;++ let walletLamports;+ try {+ walletLamports = BigInt(await conn.getBalance(ownerPk, 'confirmed'));+ } catch {+ return error(res, 502, 'rpc_error', 'could not read the wallet balance — try again');+ }++ // Price the trade.+ let prep;+ try {+ prep = await quoteTrade({ ctx, side, mintPk: input.mintPk, amount: input.amount, isMax: input.isMax, slippagePct, network, ownerPk });+ } catch (e) {+ return boundaryError(res, e);+ }+ if (side === 'buy' && prep.lamports != null) {+ try { prep.usdValue = await lamportsToUsd(prep.lamports); } catch { prep.usdValue = null; }+ }++ // Run the shared guardrails.+ let blocked;+ try {+ blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta });+ } catch (e) {+ return error(res, 502, 'guard_check_failed', 'could not verify the trade guardrails — try again');+ }+ if (blocked) return error(res, blocked.status, blocked.code, blocked.message, { detail: blocked.detail });++ // Build the on-chain instructions (also the real graduation check for buys).+ let built;+ try {+ built = await buildTradeInstructions({ ctx, side, venue: prep.venue, mintPk: input.mintPk, ownerPk, lamports: prep.lamports, baseAmount: prep.baseAmount, slippagePct, network });+ } catch (e) {+ if (isGraduatedErr(e)) {+ return error(res, 409, 'graduated', 'This coin graduated mid-trade — refresh the quote and retry.');+ }+ return error(res, 502, 'build_failed', `could not build the trade: ${e?.message || 'unknown error'}`);+ }++ const ledgerMeta = {+ side, mint: input.mint, venue: prep.venue, slippage_bps: input.slippageBps,+ price_impact_pct: prep.priceImpactPct,+ expected_out: prep.expectedOutRaw.toString(),+ min_out: prep.minOutRaw.toString(),+ ...(side === 'sell' ? { base_amount: prep.baseAmount.toString(), token_decimals: prep.decimals } : {}),+ };++ // Paper mode: simulate the real instructions, never sign, never record.+ if (simulate) {+ const message = new TransactionMessage({ payerKey: ownerPk, recentBlockhash: (await safeBlockhash(conn))?.blockhash || '11111111111111111111111111111111', instructions: built.instructions }).compileToV0Message();+ const vtx = new VersionedTransaction(message);+ let sim = null;+ try {+ sim = await conn.simulateTransaction(vtx, { sigVerify: false, replaceRecentBlockhash: true });+ } catch (e) {+ return error(res, 502, 'simulation_failed', e?.message || 'simulation failed');+ }+ return json(res, 200, {+ data: {+ simulated: true, side, mint: input.mint, network, venue: prep.venue,+ expected_out: prep.expectedOutRaw.toString(),+ min_out: prep.minOutRaw.toString(),+ price_impact_pct: prep.priceImpactPct,+ err: sim.value?.err ?? null,+ units_consumed: sim.value?.unitsConsumed ?? null,+ },+ });+ }++ // Claim the idempotency slot — this row is also the ledger/audit entry. Buys+ // count toward the SOL + USD budgets (amount_lamports + usd set); sells move+ // SOL inward, so they record for audit with null amounts (don't consume budget).+ const claim = await sql`+ INSERT INTO agent_custody_events+ (agent_id, user_id, event_type, category, network, asset,+ amount_lamports, amount_raw, usd, status, idempotency_key, reason, meta)+ VALUES (+ ${id}, ${auth.userId}, 'spend', 'trade', ${network},+ ${side === 'buy' ? 'SOL' : input.mint},+ ${side === 'buy' ? String(prep.lamports) : null},+ ${side === 'sell' ? String(prep.baseAmount) : null},+ ${side === 'buy' ? (prep.usdValue ?? null) : null},+ 'pending', ${idempotencyKey}, ${`trade_${side}`},+ ${JSON.stringify(ledgerMeta)}::jsonb+ )+ ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING+ RETURNING id+ `;+ if (!claim.length) {+ return error(res, 409, 'trade_in_progress', 'a trade with this id is already in flight — check the audit log before retrying');+ }+ const claimId = claim[0].id;++ // Recover the custodial key (audit-logged) and sign.+ let keypair;+ try {+ keypair = await recoverSolanaAgentKeypair(meta.encrypted_solana_secret, {+ agentId: id, userId: auth.userId, reason: `trade_${side}`,+ meta: { mint: input.mint, network, venue: prep.venue, custody_event_id: claimId },+ });+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});+ return error(res, 500, 'key_recover_failed', 'could not access the agent wallet key — no funds were moved');+ }++ // Submit + confirm, re-checking the chain on an ambiguous timeout.+ let result;+ try {+ result = await signSendConfirm(conn, keypair, built.instructions);+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: e?.code || 'send_failed', message: e?.message?.slice(0, 200) } }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.trade_failed', resourceId: id, meta: { side, mint: input.mint, reason: e?.code || 'send_failed', network }, req });+ return error(res, 502, 'send_failed', 'the trade could not be submitted and no funds were moved — try again');+ }++ if (!result.confirmed) {+ await updateCustodyEvent(claimId, { signature: result.signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.trade_unconfirmed', resourceId: id, meta: { side, mint: input.mint, signature: result.signature, network }, req });+ return error(res, 202, 'trade_unconfirmed', 'the trade was submitted but not yet confirmed — check the explorer link before retrying', { signature: result.signature, explorer: explorerTxUrl(result.signature, network) });+ }++ await updateCustodyEvent(claimId, { status: 'confirmed', signature: result.signature }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.trade', resourceId: id, meta: { side, mint: input.mint, venue: prep.venue, network, signature: result.signature, usd: prep.usdValue }, req });++ // Re-read the SOL balance for the response.+ let newSol = null;+ try { newSol = (await conn.getBalance(ownerPk, 'confirmed')) / 1e9; } catch { /* best-effort */ }++ return json(res, 200, {+ data: {+ replayed: false,+ signature: result.signature,+ explorer: explorerTxUrl(result.signature, network),+ side, mint: input.mint, network, venue: prep.venue,+ slippage_bps: input.slippageBps,+ price_impact_pct: prep.priceImpactPct,+ ...(side === 'buy'+ ? { sol_spent: lamportsToSol(prep.lamports), tokens_received: prep.expectedOutRaw.toString() }+ : { tokens_sold: prep.baseAmount.toString(), sol_received: lamportsToSol(prep.expectedOutRaw) }),+ min_out: prep.minOutRaw.toString(),+ new_balance_sol: newSol,+ },+ });+}++async function safeBlockhash(conn) {+ try { return await conn.getLatestBlockhash('confirmed'); } catch { return null; }+}++// Assemble a v0 tx, sign with the agent key, broadcast, and confirm — with a+// status re-check on an ambiguous confirm so a landed tx is never marked failed.+// Mirrors the proven flow in solana-wallet.js handleWithdraw.+async function signSendConfirm(conn, payer, instructions) {+ const bh = await conn.getLatestBlockhash('confirmed');+ const message = new TransactionMessage({+ payerKey: payer.publicKey,+ recentBlockhash: bh.blockhash,+ instructions,+ }).compileToV0Message();+ const vtx = new VersionedTransaction(message);+ vtx.sign([payer]);++ let signature;+ try {+ signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 3 });+ } catch (e) {+ throw Object.assign(new Error(e?.message || 'send failed'), { code: 'send_failed' });+ }++ let confirmed = true;+ try {+ const r = await conn.confirmTransaction({ signature, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight }, 'confirmed');+ if (r?.value?.err) confirmed = false;+ } catch {+ try {+ const st = await conn.getSignatureStatus(signature, { searchTransactionHistory: true });+ const s = st?.value?.confirmationStatus;+ confirmed = !st?.value?.err && (s === 'confirmed' || s === 'finalized');+ } catch {+ confirmed = false;+ }+ }+ return { signature, confirmed };+}++// ── preview / quote ───────────────────────────────────────────────────────────++async function handleQuote(req, res, id) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const owned = await loadOwnedAgent(req, res, id);+ if (owned.error) return;+ const { auth, meta } = owned;++ const rl = await limits.walletRead(auth.userId);+ if (!rl.success) return rateLimited(res, rl);++ let body = {};+ if (req.method === 'POST') {+ try { body = await readJson(req); } catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid request body'); }+ } else {+ const url = new URL(req.url, 'http://x');+ body = {+ side: url.searchParams.get('side'),+ mint: url.searchParams.get('mint'),+ amount: url.searchParams.get('amount'),+ slippageBps: url.searchParams.get('slippageBps'),+ network: url.searchParams.get('network'),+ };+ }++ const tradeLimits = getTradeLimits(meta);+ let input;+ try {+ input = parseTradeInput(body, tradeLimits);+ } catch (e) {+ return boundaryError(res, e);+ }+ const { side, network, slippagePct } = input;++ const address = meta.solana_address || null;+ if (!address) return error(res, 404, 'no_wallet', 'agent has no solana wallet yet — fund it to start trading');+ const ownerPk = new PublicKey(address);++ let ctx;+ try { ctx = await getPumpTradeClient({ network }); } catch { return error(res, 502, 'rpc_error', 'could not connect to the trade RPC — try again'); }+ const conn = ctx.connection;++ let walletLamports = 0n;+ try { walletLamports = BigInt(await conn.getBalance(ownerPk, 'confirmed')); } catch { /* preview tolerates */ }++ let prep;+ try {+ prep = await quoteTrade({ ctx, side, mintPk: input.mintPk, amount: input.amount, isMax: input.isMax, slippagePct, network, ownerPk });+ } catch (e) {+ return boundaryError(res, e);+ }+ if (side === 'buy' && prep.lamports != null) {+ try { prep.usdValue = await lamportsToUsd(prep.lamports); } catch { prep.usdValue = null; }+ }++ let blocked = null;+ try { blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta }); } catch { blocked = null; }++ return json(res, 200, {+ data: {+ side, mint: input.mint, network, venue: prep.venue,+ slippage_bps: input.slippageBps,+ price_impact_pct: prep.priceImpactPct,+ ...(side === 'buy'+ ? { sol_in: lamportsToSol(prep.lamports), expected_tokens_out: prep.expectedOutRaw.toString() }+ : { tokens_in: prep.baseAmount.toString(), token_decimals: prep.decimals, expected_sol_out: lamportsToSol(prep.expectedOutRaw) }),+ min_out: prep.minOutRaw.toString(),+ wallet_balance_sol: Number(walletLamports) / 1e9,+ allowed: !blocked,+ blocked_reason: blocked ? { code: blocked.code, message: blocked.message, detail: blocked.detail } : null,+ },+ });+}++// ── limits (read / update) ──────────────────────────────────────────────────++async function handleLimits(req, res, id) {+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT'])) return;++ const owned = await loadOwnedAgent(req, res, id);+ if (owned.error) return;+ const { auth, meta } = owned;++ if (req.method === 'GET') {+ return json(res, 200, { data: { limits: getTradeLimits(meta), defaults: TRADE_LIMIT_DEFAULTS } });+ }++ const rl = await limits.tradePerUser(auth.userId);+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try { body = await readJson(req); } catch (e) { return error(res, 400, 'bad_request', e?.message || 'invalid request body'); }++ try {+ const next = await setTradeLimits(id, auth.userId, body, { req });+ return json(res, 200, { data: { limits: next } });+ } catch (e) {+ if (e?.status) return error(res, e.status, e.code || 'error', e.message);+ return error(res, 500, 'limit_update_failed', 'could not update the trade limits — try again');+ }+}++function boundaryError(res, e) {+ if (e?.isBoundary) return error(res, e.status, e.code, e.message, e.detail && Object.keys(e.detail).length ? { detail: e.detail } : {});+ return error(res, 500, 'internal_error', 'unexpected error preparing the trade');+}++export default async function handler(req, res, id, action) {+ if (action === 'limits') return handleLimits(req, res, id);+ if (action === 'quote') return handleQuote(req, res, id);+ if (action) return error(res, 404, 'not_found', 'unknown trade sub-resource');+ return handleExecute(req, res, id);+}diff --git a/data/changelog.json b/data/changelog.jsonindex ebdf3ea43..d2853097c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws \u2014 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-18",+ "title": "Your AR agent now hides behind real-world objects",+ "summary": "Place an agent in your room with the AR button and it now lives in the space instead of floating on top of the camera feed. Walk a chair, a doorway, or your own hand between your phone and the agent and the agent is correctly hidden behind it — the single biggest \"is this really in my room?\" upgrade. It uses your phone's depth sensor on devices that have one (recent Android Chrome); on every other device AR works exactly as before, with no change and nothing to turn on.",+ "tags": [+ "feature"+ ],+ "link": "/features/ar"+ },{"date": "2026-06-18","title": "Skill prices fade in smoothly on agent pages",diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.htmlindex 7e1f85470..cc06ee614 100644--- a/pages/ibm/x402-demo.html+++ b/pages/ibm/x402-demo.html@@ -5,9 +5,9 @@<meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>x402 live demo — three.ws × IBM</title>-<meta name="description" content="A live, self-contained x402 demo: pay $0.001 in USDC from your own wallet to call a real three.ws data API. Settled on-chain on Solana. No backend, no account.">+<meta name="description" content="A live, self-contained x402 demo: pay $0.001 in USDC from your own wallet to call a real three.ws data API. Settled on-chain on Base or Solana. No backend, no account."><meta property="og:title" content="x402 live demo — three.ws × IBM">-<meta property="og:description" content="Pay $0.001 in USDC from your own wallet to call a real three.ws API. See HTTP 402 micropayments settle on-chain in about a second.">+<meta property="og:description" content="Pay $0.001 in USDC from your own wallet to call a real three.ws API. See HTTP 402 micropayments settle on-chain — on Base or Solana — in seconds."><meta property="og:type" content="website"><style>/* ─── Self-hosted IBM Plex (latin subset) — no third-party font CDN, so a@@ -113,7 +113,7 @@ a:focus-visible{outline-offset:3px}/* ── Hero ── */.hero{padding:56px 0 36px}.partner-label{display:inline-flex;align-items:center;gap:12px;border:1px solid var(--ibm-border);padding:6px 14px;font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--ibm-muted);margin-bottom:28px}-.ibm-mark{font-family:var(--font-sans);font-weight:600;font-size:13px;letter-spacing:.02em;color:#fff;background:#0530ad;padding:3px 8px;line-height:1}+.ibm-mark{font-family:var(--font-sans);font-weight:700;font-size:15px;letter-spacing:-.01em;color:var(--ibm-blue);line-height:1}.hero h1{font-size:clamp(30px,5vw,46px);font-weight:300;line-height:1.1;margin-bottom:18px;max-width:680px}.hero h1 strong{font-weight:600}.hero-sub{font-size:18px;color:var(--ibm-muted);max-width:620px;font-weight:300;line-height:1.6}@@ -389,9 +389,9 @@ agent-3d:defined ~ .agent-skel{display:none}<meta property="og:image:height" content="630"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="x402 Live Demo (IBM × three.ws) · three.ws">- <meta name="twitter:description" content="A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.">+ <meta name="twitter:description" content="A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership."><meta name="twitter:image" content="https://three.ws/og-image.png">- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"x402 Live Demo (IBM × three.ws)","description":"A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.","url":"https://three.ws/ibm/x402-demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"x402 Live Demo (IBM × three.ws)","description":"A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.","url":"https://three.ws/ibm/x402-demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script><!-- model-viewer renders the GLB returned by the paid Forge demo (Demo 01).Self-hosted (travels with this file under ./vendor/) so the page needs nothird-party script CDN — a strict `script-src 'self'` host won't block it.@@ -412,16 +412,18 @@ agent-3d:defined ~ .agent-skel{display:none}<header class="hero"><div class="inner"><div class="partner-label">- <!-- IBM brand: neutral wordmark lockup. Confirm exact mark + "Business Partner"- usage rights with IBM before public launch (see task 08 / HOSTING.md). -->+ <!-- IBM brand: neutral typographic wordmark (IBM Plex, Carbon blue) — a defensible+ placeholder, NOT the registered 8-bar logo. Confirm the exact mark and the+ "IBM Business Partner" lockup + wording with IBM brand before public launch+ (see HOSTING.md, "Note on branding"). --><span class="ibm-mark">IBM</span><span>Business Partner</span><span style="color:var(--ibm-border)" aria-hidden="true">|</span><span class="mono">three.ws</span></div><h1>A live showcase of agentic commerce, built with <strong>IBM</strong></h1>- <p class="hero-sub">IBM has shaped computing for over a century — and it stays at the frontier by backing what comes next. three.ws is one of those bets: a platform for on-chain micropayments and embodied AI agents. As an IBM Business Partner, we built this page to demonstrate that partnership in the open — every demo below runs against real, production three.ws systems. Nothing is mocked, nothing is a slide.</p>- <p class="hero-sub" style="margin-top:14px">Five things we want to show you: pay a few cents to turn text into a 3D model, pay-per-call micropayments over <span class="mono">x402</span>, an autonomous 3D agent that buys its own data, a shared 3D world, and an agent placed in augmented reality. Try each one yourself — both demos settle real USDC from your own wallet.</p>+ <p class="hero-sub">IBM has shaped computing for over a century — and it stays at the frontier by backing what comes next. three.ws is one of those bets: a platform for on-chain micropayments and 3D AI agents. As an IBM Business Partner, we built this page to demonstrate that partnership in the open — every demo below runs against real, production three.ws systems. Nothing is mocked, nothing is a slide.</p>+ <p class="hero-sub" style="margin-top:14px">Five things we want to show you: pay a few cents to turn text into a 3D model, pay-per-call micropayments over <span class="mono">x402</span>, an autonomous 3D agent that buys its own data, a shared 3D world, and an agent placed in augmented reality. Try each one yourself — the two paid demos (Forge and the x402 call) settle real USDC from your own wallet.</p><nav class="demo-nav" aria-label="The demos on this page"><a href="#forge"><span class="n">01</span>Forge</a><a href="#demo"><span class="n">02</span>x402 payments</a>@@ -504,7 +506,7 @@ agent-3d:defined ~ .agent-skel{display:none}<!-- requirements --><div class="note"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>- <p>You'll need a browser wallet — <b>MetaMask</b> or <b>Phantom</b> (for Solana) — holding the model's price in <b>USDC</b> on mainnet. Payment is a gasless signature; the network fee is sponsored by the facilitator. Generation runs after the payment verifies and takes roughly a minute. No wallet? Use the <a href="https://three.ws/forge" target="_blank" rel="noopener">free Forge tool</a> instead.</p>+ <p>You'll need a browser wallet — <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) — holding the model's price in <b>USDC</b> on mainnet. This spends <b>real USDC</b> — the price shown above — from your own wallet. The payment itself is a gasless signature: the network fee is sponsored by the x402 facilitator, so it isn't added to your cost. Generation runs once the payment verifies and takes roughly a minute. No wallet? Use the <a href="https://three.ws/forge" target="_blank" rel="noopener">free Forge tool</a> instead.</p></div></div></div>@@ -531,7 +533,7 @@ agent-3d:defined ~ .agent-skel{display:none}<li class="step"><div class="step-n">03 · PAY & RETRY</div><h3>Wallet signs, call settles</h3>- <p>You sign a gasless USDC authorization, resend with an <code>X-PAYMENT</code> header, and get your data.</p>+ <p>You sign a gasless USDC authorization, resend with an <code>X-PAYMENT</code> header, and the call settles on-chain — your data comes back.</p></li></ol></div>@@ -542,7 +544,7 @@ agent-3d:defined ~ .agent-skel{display:none}<div class="inner"><div class="section-tag">Demo 02 · Payments</div><h2 id="demo-h">Buy a <strong>data call</strong> for $0.001</h2>- <p class="section-lead">This calls a real three.ws API — a token-symbol availability check — for one tenth of a cent in USDC, settled on Solana mainnet. The price below is read live from the server's own 402 response.</p>+ <p class="section-lead">This calls a real three.ws API — a ticker-symbol availability check — for one tenth of a cent in USDC, settled on-chain. The price below is read live from the server's own 402 response.</p><div class="demo"><div class="demo-head">@@ -590,7 +592,7 @@ agent-3d:defined ~ .agent-skel{display:none}<!-- requirements --><div class="note"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>- <p>You'll need a browser wallet — <b>MetaMask</b> or <b>Phantom</b> (for Solana) — holding at least <b>$0.001 USDC</b> on mainnet. This spends real funds, but only a tenth of a cent. The payment is a gasless signature; the network fee is sponsored by the facilitator. No wallet? You can still watch the 402 challenge above and read the <a href="https://three.ws/docs/x402" target="_blank" rel="noopener">protocol docs</a>.</p>+ <p>You'll need a browser wallet — <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) — holding at least <b>$0.001 USDC</b> on mainnet. This spends <b>real USDC</b> — one tenth of a cent — from your own wallet. The payment itself is a gasless signature: the network fee is sponsored by the x402 facilitator, so it isn't added to your cost (it isn't zero, just not yours to pay). No wallet? You can still watch the live 402 challenge above and read the <a href="https://three.ws/docs/x402" target="_blank" rel="noopener">protocol docs</a>.</p></div></div></div>@@ -699,7 +701,7 @@ agent-3d:defined ~ .agent-skel{display:none}<nav class="footer-nav" aria-label="Footer"><a href="https://three.ws" target="_blank" rel="noopener">Platform</a><a href="https://three.ws/docs/x402" target="_blank" rel="noopener">x402 Protocol</a>- <a href="https://three.ws/docs/ibm-x402" target="_blank" rel="noopener">IBM × x402 Docs</a>+ <a href="https://three.ws/docs/ibm" target="_blank" rel="noopener">IBM × three.ws</a><a href="https://three.ws/bazaar" target="_blank" rel="noopener">Endpoint Bazaar</a><a href="https://three.ws/forge" target="_blank" rel="noopener">Forge</a><a href="https://three.ws/play" target="_blank" rel="noopener">Play</a>@@ -707,7 +709,7 @@ agent-3d:defined ~ .agent-skel{display:none}<a href="https://three.ws/changelog" target="_blank" rel="noopener">Changelog</a></nav><div class="footer-legal">- Live x402 demo · three.ws, an IBM Business Partner. Payments settle in USDC on Solana mainnet via the x402 protocol. The only coin this platform issues is $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump).+ Live x402 demo · three.ws, an IBM Business Partner. Payments settle in USDC on Base or Solana mainnet via the x402 protocol. The only coin this platform issues is $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump).</div></div></footer>diff --git a/pages/irl.html b/pages/irl.htmlindex d5c262cb6..2a1407e16 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -492,6 +492,44 @@line-height: 1.35;color: #e8e8ef;letter-spacing: -0.01em;+ /* Readable over a live camera feed on both bright and dark floors: the+ dark pill already scrims the text; this shadow keeps thin strokes legible+ if the translucent pill happens to sit over a white surface. */+ text-shadow: 0 1px 2px rgba(0,0,0,0.55);+ }+ /* ✓ confirm affordance — revealed on .irl-xr-bar.is-anchored the instant the+ anchor takes (paired with the in-scene pulse + haptic). Collapsed to zero+ width while idle so it never reserves space in the pill. */+ .irl-xr-check {+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 0;+ height: 22px;+ border-radius: 999px;+ background: rgba(52,211,153,0.18);+ color: #6ee7b7;+ overflow: hidden;+ opacity: 0;+ transform: scale(0.6);+ transition: opacity 0.18s ease, transform 0.18s cubic-bezier(0.2,1.4,0.4,1);+ }+ .irl-xr-bar.is-anchored .irl-xr-check {+ width: 22px;+ margin-right: 2px;+ opacity: 1;+ transform: scale(1);+ animation: irl-xr-check-pop 0.42s cubic-bezier(0.2,1.4,0.4,1);+ }+ @keyframes irl-xr-check-pop {+ 0% { transform: scale(0.4); }+ 60% { transform: scale(1.18); }+ 100% { transform: scale(1); }+ }+ @media (prefers-reduced-motion: reduce) {+ .irl-xr-check { transition: opacity 0.12s linear; transform: none; }+ .irl-xr-bar.is-anchored .irl-xr-check { transform: none; animation: none; }}.irl-xr-exit {flex-shrink: 0;@@ -1844,8 +1882,9 @@the immersive-ar dom-overlay root so the in-session hint + exit are visibleover the AR view. Also the mount for the designed start-failure error card. --><div id="irl-xr-overlay" hidden>- <div class="irl-xr-bar">- <p id="irl-xr-hint" class="irl-xr-hint" aria-live="polite">Point at the floor and move your phone slowly</p>+ <div class="irl-xr-bar" id="irl-xr-bar">+ <span id="irl-xr-check" class="irl-xr-check" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>+ <p id="irl-xr-hint" class="irl-xr-hint" aria-live="polite">Sweep your phone slowly to find the floor</p><button id="irl-xr-exit" type="button" class="irl-xr-exit" aria-label="Exit floor anchoring"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>Exitdiff --git a/public/changelog.json b/public/changelog.jsonindex 618a51bea..af01f8bd4 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T09:08:58.430Z",+ "generated_at": "2026-06-18T09:14:06.495Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -409,6 +409,16 @@"improvement"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Your AR agent now hides behind real-world objects",+ "summary": "Place an agent in your room with the AR button and it now lives in the space instead of floating on top of the camera feed. Walk a chair, a doorway, or your own hand between your phone and the agent and the agent is correctly hidden behind it — the single biggest \"is this really in my room?\" upgrade. It uses your phone's depth sensor on devices that have one (recent Android Chrome); on every other device AR works exactly as before, with no change and nothing to turn on.",+ "link": "/features/ar",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-17","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 56d61ca09..1c889dc86 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -318,6 +318,14 @@<category>improvement</category><description>When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel.</description></item>+ <item>+ <title>Your AR agent now hides behind real-world objects</title>+ <link>https://three.ws/features/ar</link>+ <guid isPermaLink="false">2026-06-18:Your AR agent now hides behind real-world objects</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Place an agent in your room with the AR button and it now lives in the space instead of floating on top of the camera feed. Walk a chair, a doorway, or your own hand between your phone and the agent and the agent is correctly hidden behind it — the single biggest "is this really in my room?" upgrade. It uses your phone's depth sensor on devices that have one (recent Android Chrome); on every other device AR works exactly as before, with no change and nothing to turn on.</description>+ </item><item><title>Animation Gallery</title><link>https://three.ws/animations</link>diff --git a/public/features.json b/public/features.jsonindex 173107598..a599b7aa3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T09:08:58.356Z",+ "generated_at": "2026-06-18T09:14:06.306Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/ar/placement-capability.js b/src/ar/placement-capability.jsnew file mode 100644index 000000000..e3409d597--- /dev/null+++ b/src/ar/placement-capability.js@@ -0,0 +1,49 @@+// Floor-placement capability resolver for /irl.+//+// Replaces the binary "WebXR or nothing" gate with a small resolver that picks+// the richest floor-placement path a device can actually deliver, so iOS Safari+// stops falling all the way back to compass+GPS when it can do real ARKit+// placement:+//+// 'webxr' — immersive-ar with live hit-test + XRAnchor (Android Chrome and+// some desktop XR). In-canvas placement → real anchored pose →+// shareable GPS pin. The full-parity path (src/ar/webxr.js).+// 'quicklook' — iOS Safari / iPadOS. ARKit AR Quick Look opens the agent in the+// system AR viewer and places it on a detected plane. It is a+// SEPARATE viewer: it places-and-views in the user's room but+// cannot feed a pose back to our canvas, so the durable, shareable+// pin still comes from the gyro+GPS Pin path. The /irl copy says so.+// 'pin' — no device AR surface (older Android, desktop, locked-down WebView)+// → compass + GPS "Pin here" is the placement, exactly as before.+//+// Extension point — a commercial in-canvas WebAR SLAM backend (e.g. 8th Wall)+// would slot in ABOVE 'webxr' as a 'webar' capability: true iOS in-canvas surface+// placement with pose callbacks that feed the SAME onFloorAnchored persistence in+// src/irl.js, achieving full parity (live placement → shareable pin) on iOS. It is+// intentionally NOT wired here because it requires a paid SDK + license key, and a+// key-less stub would be dead UI. When the credential exists, add the provider+// check as the first branch below and a matching backend in the /irl entry+// handler; nothing else changes, because persistence and UX are already shared.++import { WebXRSession } from './webxr.js';+import { canUseQuickLook } from './quick-look.js';++/** @typedef {'webxr'|'quicklook'|'pin'} PlacementCapability */++/**+ * Resolve the richest floor-placement path this device supports. Async because+ * the WebXR probe (`navigator.xr.isSessionSupported`) is async; never throws —+ * any failure resolves to the always-available 'pin' path.+ *+ * @returns {Promise<PlacementCapability>}+ */+export async function resolvePlacementCapability() {+ try {+ if (await WebXRSession.isSupported()) return 'webxr';+ } catch {+ // A thrown support probe (no navigator.xr, blocked API) is just "not webxr".+ }+ // iOS/iPadOS has no immersive-ar but does have ARKit Quick Look.+ if (canUseQuickLook()) return 'quicklook';+ return 'pin';+}diff --git a/src/ar/webxr.js b/src/ar/webxr.jsindex 20a578ab2..6dafaba6c 100644--- a/src/ar/webxr.js+++ b/src/ar/webxr.js@@ -360,27 +360,174 @@ export class WebXRSession {this._onAnchored?.(anchorPose, { degraded: this._anchor === null });}- // Build the floor reticle: a flat ring whose geometry is pre-rotated into the- // XZ plane so the hit pose (Y = surface normal) lays it on the surface.+ // Build the floor reticle: a flat ring + an inner dot, both pre-rotated into the+ // XZ plane so the hit pose (Y = surface normal) lays them on the surface. The+ // group is oriented to the hit each frame; _updateReticleVisual animates the+ // searching↔locked look (dim/breathing → bright/filled) off the eased lock+ // amount, so this only establishes geometry — no per-frame branching here._buildReticle() {- const geo = new RingGeometry(0.08, 0.11, 36).rotateX(-Math.PI / 2);+ const group = new Group();+ group.renderOrder = 999; // draw over the passthrough + agent+ group.visible = false;++ const ringGeo = new RingGeometry(0.08, 0.11, 40).rotateX(-Math.PI / 2);+ const ringMat = new MeshBasicMaterial({+ color: this._dimColor.clone(), transparent: true, opacity: 0.6, depthTest: false,+ });+ const ring = new Mesh(ringGeo, ringMat);+ ring.renderOrder = 999;++ // Inner dot: invisible while searching, fades in as the surface locks so+ // "ready to place" reads at a glance. Lifted a hair so it never z-fights the+ // ring on the exact same plane.+ const dotGeo = new CircleGeometry(0.032, 32).rotateX(-Math.PI / 2).translate(0, 0.001, 0);+ const dotMat = new MeshBasicMaterial({+ color: this._lockColor.clone(), transparent: true, opacity: 0, depthTest: false,+ });+ const dot = new Mesh(dotGeo, dotMat);+ dot.renderOrder = 1000;++ group.add(ring, dot);+ this._reticle = group;+ this._reticleRing = ring;+ this._reticleDot = dot;+ this._viewer.scene.add(group);+ }++ // Soft contact shadow — a single transparent plane with a radial-gradient map+ // (no real shadow map). Grounds the avatar so it sits *on* the floor instead of+ // floating; follows the reticle pre-tap and the anchor after. Lifted a few mm+ // along the surface normal so it never z-fights the real floor that the depth+ // occluder stamps — which also makes it correctly hidden by closer real geometry.+ _buildShadow() {+ const size = 128;+ let tex = null;+ try {+ const cnv = document.createElement('canvas');+ cnv.width = cnv.height = size;+ const ctx = cnv.getContext('2d');+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);+ g.addColorStop(0, 'rgba(0,0,0,0.42)');+ g.addColorStop(0.55, 'rgba(0,0,0,0.20)');+ g.addColorStop(1, 'rgba(0,0,0,0)');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, size, size);+ tex = new CanvasTexture(cnv);+ } catch {+ tex = null; // no DOM canvas (shouldn't happen in-session) → tinted disc fallback+ }+ const geo = new PlaneGeometry(0.6, 0.6).rotateX(-Math.PI / 2).translate(0, 0.004, 0);+ const mat = new MeshBasicMaterial({+ map: tex, color: tex ? 0xffffff : 0x000000, transparent: true,+ opacity: 0.9, depthWrite: false,+ });+ const mesh = new Mesh(geo, mat);+ mesh.renderOrder = 1; // beneath the reticle, above the passthrough+ mesh.visible = false;+ this._shadow = mesh;+ this._shadowTex = tex;+ this._viewer.scene.add(mesh);+ }++ // One-shot "pulse-out" ring fired on a successful anchor (the visible half of+ // the confirm beat). Separate from the reticle so it can keep animating after+ // the reticle retires. Hidden until _fireConfirmPulse arms it.+ _buildPulseRing() {+ const geo = new RingGeometry(0.10, 0.13, 40).rotateX(-Math.PI / 2);const mat = new MeshBasicMaterial({- color: 0x9b8cff, transparent: true, opacity: 0.9, depthTest: false,+ color: this._lockColor.clone(), transparent: true, opacity: 0, depthTest: false,});const ring = new Mesh(geo, mat);- ring.renderOrder = 999; // draw over the passthrough + agent- ring.matrixAutoUpdate = true;+ ring.renderOrder = 1001; // above the reticlering.visible = false;- this._reticle = ring;+ this._pulseRing = ring;this._viewer.scene.add(ring);}+ // Lay the contact shadow flat on a hit (or anchor) pose and reveal it.+ _placeShadow(matrix) {+ if (!this._shadow) return;+ this._shadow.position.setFromMatrixPosition(matrix);+ this._shadow.quaternion.setFromRotationMatrix(matrix);+ this._shadow.visible = true;+ }++ // Arm the confirm pulse at the tap point. Reduced motion skips the visual beat+ // (the haptic + ✓ copy still confirm); otherwise the ring expands and fades via+ // _updatePulse. No allocation — the pulse state object is reused.+ _fireConfirmPulse() {+ if (this._reducedMotion || !this._pulseRing) return;+ this._pulseRing.position.setFromMatrixPosition(this._latestHitMatrix);+ this._pulseRing.quaternion.setFromRotationMatrix(this._latestHitMatrix);+ this._pulse.t = 0;+ this._pulse.active = true;+ this._pulseRing.visible = true;+ }++ // Per-frame reticle look. Eases the lock amount toward the live hit state and+ // maps it (+ a slow breathing phase) to scale/opacity/dot/colour via the pure,+ // unit-tested reticleVisual(). Writes straight onto materials with a reused+ // buffer and in-place colour lerp — zero per-frame allocation.+ _updateReticleVisual(time, dt) {+ const group = this._reticle;+ if (!group || !group.visible) return;+ const target = this._hasHit ? 1 : 0;+ // Snap toward lock a touch faster than it relaxes toward searching, so the+ // "locked" beat feels crisp while losing the surface feels gentle.+ const rate = Math.min(1, dt * (target > this._hitAmount ? 16 : 9));+ this._hitAmount += (target - this._hitAmount) * rate;+ const breathe = this._reducedMotion ? 0 : Math.sin(time * 0.0019) * 0.5 + 0.5;+ reticleVisual(this._rv, this._hitAmount, breathe, this._reducedMotion);+ group.scale.setScalar(this._rv.scale);+ const ringMat = this._reticleRing.material;+ ringMat.opacity = this._rv.opacity;+ ringMat.color.lerpColors(this._dimColor, this._lockColor, this._rv.colorMix);+ this._reticleDot.material.opacity = this._rv.dot * 0.95;+ }++ // Advance the one-shot confirm pulse, if armed. Expands + fades the ring via the+ // pure advancePulse(), then retires it. No-op (and no allocation) once done.+ _updatePulse(dt) {+ if (!this._pulse.active || !this._pulseRing) return;+ advancePulse(this._pulse, dt);+ this._pulseRing.scale.setScalar(this._pulse.scale);+ this._pulseRing.material.opacity = this._pulse.opacity;+ if (this._pulse.done) {+ this._pulse.active = false;+ this._pulseRing.visible = false;+ }+ }+_disposeReticle() {if (!this._reticle) return;this._viewer.scene.remove(this._reticle);- this._reticle.geometry?.dispose();- this._reticle.material?.dispose();+ for (const child of [this._reticleRing, this._reticleDot]) {+ child?.geometry?.dispose();+ child?.material?.dispose();+ }this._reticle = null;+ this._reticleRing = null;+ this._reticleDot = null;+ }++ _disposeShadow() {+ if (this._shadow) {+ this._viewer.scene.remove(this._shadow);+ this._shadow.geometry?.dispose();+ this._shadow.material?.dispose();+ this._shadow = null;+ }+ this._shadowTex?.dispose();+ this._shadowTex = null;+ }++ _disposePulseRing() {+ if (!this._pulseRing) return;+ this._viewer.scene.remove(this._pulseRing);+ this._pulseRing.geometry?.dispose();+ this._pulseRing.material?.dispose();+ this._pulseRing = null;+ this._pulse.active = false;}// Notify the host only on transitions (searching ↔ surface found), not per frame.@@ -390,10 +537,14 @@ export class WebXRSession {this._onHit?.(has);}- // Tracking lost/recovered. On loss, hide the reticle so the user never taps a- // stale one; the host surfaces a recoverable "move to a brighter spot" hint.+ // Tracking lost/recovered. On loss, hide the reticle (and its contact shadow)+ // so the user never taps a stale one; the host surfaces a recoverable "move to a+ // brighter spot" hint. A returning surface re-shows both on the next hit frame._setTracking(ok) {- if (!ok && this._reticle) this._reticle.visible = false;+ if (!ok) {+ if (this._reticle) this._reticle.visible = false;+ if (!this._anchored && this._shadow) this._shadow.visible = false;+ }this._onTracking?.(ok);}@@ -403,7 +554,10 @@ export class WebXRSession {_handleVisibilityChange() {const visible = isXrVisible(this._session?.visibilityState);this._paused = !visible;- if (!visible && this._reticle) this._reticle.visible = false;+ if (!visible) {+ if (this._reticle) this._reticle.visible = false;+ if (!this._anchored && this._shadow) this._shadow.visible = false;+ }this._onVisibility?.(visible);}@@ -454,6 +608,8 @@ export class WebXRSession {this._hitTestSource = null;}this._disposeReticle();+ this._disposeShadow();+ this._disposePulseRing();// Detach + free the depth occluder (no-op when it was never attached).this._depthOcclusion?.dispose();this._depthOcclusion = null;@@ -462,6 +618,8 @@ export class WebXRSession {this._anchor = null;this._latestHit = null;this._hasHit = false;+ this._hadHit = false;+ this._hitAmount = 0;this._paused = false;this._trackingState = { misses: 0, lost: false };diff --git a/src/irl.js b/src/irl.jsindex 4388ffb67..839aa72a5 100644--- a/src/irl.js+++ b/src/irl.js@@ -43,6 +43,8 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';import { WebXRSession } from './ar/webxr.js';+import { resolvePlacementCapability } from './ar/placement-capability.js';+import { openQuickLook } from './ar/quick-look.js';import { createPersistGate, placementHint } from './ar/anchor-lifecycle.js';import { IrlNet } from './irl-net.js';import { wireShareButton } from './irl/share-frame.js';@@ -146,6 +148,7 @@ const avatarBtn = $('irl-avatar-btn');const lockBtn = $('irl-lock-btn');const anchorBtn = $('irl-anchor-btn'); // WebXR "Place on floor" — revealed only when supportedconst xrOverlay = $('irl-xr-overlay'); // WebXR dom-overlay root (in-session hint + exit + error)+const xrBarEl = $('irl-xr-bar'); // hint+exit pill; .is-anchored reveals the ✓ confirmconst xrHintEl = $('irl-xr-hint');const xrExitBtn = $('irl-xr-exit');@@ -735,6 +738,15 @@ const animMgr = new AnimationManager();let avatar = null, avatarYaw = 0, avatarLean = 0, currentMotion = 'idle';let _currentAvatarId = null;let _currentAgentId = null;+// iOS AR Quick Look (capability 'quicklook'): the GLB actually loaded for the+// current avatar, the server-hosted USDZ companion (if the record carries one),+// and a lazily generated USDZ blob URL when it doesn't. The generated URL is+// cached by source GLB and revoked whenever the avatar changes so we never leak+// object URLs or hand Quick Look a stale model.+let _currentGlbUrl = null;+let _currentUsdzUrl = null;+let _usdzObjectUrl = null;+let _usdzObjectUrlFor = null;function _clearAvatar() {if (avatar) {@@ -752,6 +764,12 @@ async function loadAvatar(idOrUrl, nameOverride) {let avatarName = nameOverride || 'Your Avatar';let glbUrl = resolveAvatarUrl(typeof idOrUrl === 'string' && /^https?:\/\/|^\//.test(idOrUrl) ? idOrUrl : id);+ // New avatar invalidates any USDZ we prepared for the previous one: forget the+ // server companion and revoke a generated blob URL so iOS Quick Look never+ // opens the wrong agent and we don't leak object URLs across avatar switches.+ _currentUsdzUrl = null;+ if (_usdzObjectUrl) { URL.revokeObjectURL(_usdzObjectUrl); _usdzObjectUrl = null; _usdzObjectUrlFor = null; }+// Fetch metadata only when id is a DB UUID (not already a URL)_currentAgentId = null;if (id && !/^https?:\/\//.test(id) && !id.startsWith('/')) {@@ -762,9 +780,15 @@ async function loadAvatar(idOrUrl, nameOverride) {if (meta?.name && !nameOverride) avatarName = meta.name;if (meta?.url) glbUrl = meta.url;if (meta?.agent_id) _currentAgentId = meta.agent_id;+ // Server-hosted USDZ companion (presign-usdz pipeline) → iOS Quick Look+ // opens it directly, no client-side conversion needed.+ if (meta?.usdz_url) _currentUsdzUrl = meta.usdz_url;}} catch {}}+ // Remember the GLB we're actually loading so the iOS path can convert it to a+ // USDZ on demand when the record has no hosted companion.+ _currentGlbUrl = glbUrl;nameEl.textContent = avatarName;document.title = `${avatarName} IRL · three.ws`;@@ -1779,38 +1803,56 @@ const floorPersist = createPersistGate((payload) => persistFloorAnchor(payload.p// Coordinated XR hint priority so transient lifecycle states (backgrounding,// tracking loss) never clobber — or get clobbered by — the placement copy.-// Highest active state wins: paused > tracking-lost > the latest resting message-// (searching → tap-to-place → anchored/saved). Every callback funnels through-// here instead of calling setXrHint directly, so the displayed line is always the-// single most important thing the user needs to know right now.-const SEARCHING_HINT = 'Point at the floor and move your phone slowly';+// Highest active state wins: paused > tracking-lost > the latest resting message,+// which walks the placement arc searching → aiming → placed → saved. Every callback+// funnels through here instead of calling setXrHint directly, so the displayed line+// is always the single most important thing the user needs to know right now.+const SEARCHING_HINT = 'Sweep your phone slowly to find the floor';const xrHintState = { paused: false, trackingLost: false, resting: SEARCHING_HINT };function renderXrHint() {if (xrHintState.paused) setXrHint('Paused — bring the app forward to keep placing');- else if (xrHintState.trackingLost) setXrHint('Tracking lost — move to a brighter, more textured spot');+ else if (xrHintState.trackingLost) setXrHint('Lost the room — move to a brighter, more textured spot');else setXrHint(xrHintState.resting);}// Update the resting (placement-progress) line and re-render under current priority.function setXrResting(text) { xrHintState.resting = text; renderXrHint(); }-// Reset the priority machine for a fresh session entry.+// Reveal/clear the ✓ confirm affordance on the hint pill (paired with the in-scene+// pulse + haptic from WebXRSession). Idempotent; safe when the bar is absent.+function setXrConfirmed(on) { if (xrBarEl) xrBarEl.classList.toggle('is-anchored', !!on); }++// Reset the priority machine (and the confirm ✓) for a fresh session entry.function resetXrHint() {xrHintState.paused = false;xrHintState.trackingLost = false;xrHintState.resting = SEARCHING_HINT;+ setXrConfirmed(false);renderXrHint();}+// The placement path this device can deliver, resolved once on load. Drives both+// the button's visibility/label and which entry handler its click runs.+let _placementCapability = 'pin';+async function detectFloorAnchorSupport() {try {- if (!(await WebXRSession.isSupported())) return; // iOS Safari / desktop → Pin path only- if (anchorBtn) anchorBtn.hidden = false;+ _placementCapability = await resolvePlacementCapability();} catch {- // No navigator.xr or a thrown support check → leave the entry hidden; the- // Pin button (A4 gyro+GPS) remains the anchor path. No console noise.+ _placementCapability = 'pin';}+ if (!anchorBtn) return;+ // No AR surface (older Android, desktop, locked-down WebView) → keep the button+ // hidden; the Pin button (A4 gyro+GPS) remains the placement, exactly as before.+ if (_placementCapability === 'pin') return;+ // 'Place on floor' is the same label everywhere (one mental model); only the+ // accessible description differs, since iOS opens the system AR viewer (Quick+ // Look) rather than placing inside our canvas.+ anchorBtn.setAttribute('aria-label', _placementCapability === 'quicklook'+ ? 'View your agent on the floor in AR (iOS Quick Look)'+ : 'Place agent on the floor with AR');+ anchorBtn.hidden = false;}function setXrHint(text) {@@ -1865,7 +1907,7 @@ async function enterFloorAnchor() {try {xrSession = new WebXRSession(xrViewer, {domOverlayRoot: xrOverlay,- onHit: (has) => setXrResting(has ? 'Tap to place your agent on the floor' : SEARCHING_HINT),+ onHit: (has) => setXrResting(has ? 'Looks good — tap to place your agent' : SEARCHING_HINT),// Tracking loss / recovery is a transient, higher-priority overlay on the// resting hint — recoverable, self-clearing, never a dead reticle.onTracking: (ok) => { xrHintState.trackingLost = !ok; renderXrHint(); },@@ -1891,7 +1933,7 @@ async function enterFloorAnchor() {},});await xrSession.start();- setStatus('Floor anchoring on — point at the floor, then tap to place');+ setStatus('Floor anchoring on — find the floor, then tap to place your agent');} catch (err) {log.error('[irl] WebXR start failed:', err);xrSession = null;@@ -1909,6 +1951,10 @@ async function enterFloorAnchor() {// carries the degraded flag (no real XRAnchor) so we tell the user the truth.function onFloorAnchored(pose, meta = {}) {const degraded = meta.degraded === true;+ // The DOM half of the confirm beat: light the ✓ on the hint pill the instant the+ // tap takes (the in-scene pulse + haptic fire from WebXRSession). It rides every+ // downstream copy change until the session resets.+ setXrConfirmed(true);// The gate decides: with a live fix it persists now; during GPS warm-up it// holds the pose (degraded flag rides along) and onGPSPosition drains it once.const outcome = floorPersist.place({ pose, degraded }, gpsState.ready);@@ -1917,7 +1963,7 @@ function onFloorAnchored(pose, meta = {}) {// GPS pin yet. A quick tap during GPS warm-up should still persist, not vanish.setXrResting(degraded? 'Placed — saving this spot once your location locks in (may drift on this device)'- : 'Anchored here — saving this spot once your location locks in');+ : 'Placed — saving this spot the moment your location locks in');}// outcome === 'persisted' → persistFloorAnchor set the resting hint already.}@@ -1955,16 +2001,64 @@ function persistFloorAnchor(pose, degraded = false) {gpsPin.id = result.id;revealMyPinsBtn();setXrResting(result.permanent- ? 'Anchored & saved — permanently visible to nearby users'- : 'Anchored & saved — nearby users can see you for 7 days');+ ? 'Saved — your agent is here for everyone nearby'+ : 'Saved — people nearby can see your agent for 7 days');} else {// Surface the moderation/cap/rate reason; the in-session anchor still holds.- setXrResting(result?.message || 'Anchored here — couldn’t save the pin, retry on exit');+ setXrResting(result?.message || 'Placed — couldn’t save the pin yet, retry on exit');}});}-if (anchorBtn) anchorBtn.addEventListener('click', enterFloorAnchor);+// ── iOS AR Quick Look (capability 'quicklook') ─────────────────────────────+//+// ARKit Quick Look needs a USDZ. Prefer the server-hosted companion the avatar+// record carries (presign-usdz pipeline); otherwise convert the GLB we already+// loaded for this avatar to USDZ in-browser (src/usdz-pipeline.js → three's+// USDZExporter), cache the blob URL by source GLB, and reuse it for the session.+// The same client-side export model-viewer ships, so a blob: URL drives Quick+// Look on modern Safari. Real conversion, real model — never a hidden button.+async function resolveQuickLookUrl() {+ if (_currentUsdzUrl) return _currentUsdzUrl;+ const glbUrl = _currentGlbUrl || resolveAvatarUrl(_currentAvatarId);+ if (_usdzObjectUrl && _usdzObjectUrlFor === glbUrl) return _usdzObjectUrl;+ const res = await fetch(glbUrl);+ if (!res.ok) throw new Error(`GLB fetch failed: ${res.status}`);+ const { glbBlobToUsdzBlob } = await import('./usdz-pipeline.js');+ const usdzBlob = await glbBlobToUsdzBlob(await res.blob());+ if (_usdzObjectUrl) URL.revokeObjectURL(_usdzObjectUrl);+ _usdzObjectUrl = URL.createObjectURL(usdzBlob);+ _usdzObjectUrlFor = glbUrl;+ return _usdzObjectUrl;+}++async function enterQuickLookPlacement() {+ if (anchorBtn) { anchorBtn.classList.add('is-active'); anchorBtn.disabled = true; }+ setStatus('Preparing your agent for AR…', { loading: true, sticky: true });+ try {+ const usdzUrl = await resolveQuickLookUrl();+ openQuickLook(usdzUrl);+ // Quick Look is a separate system viewer — it places-and-views the agent on+ // your real floor but can't hand a pose back to our canvas, so the durable,+ // shareable pin still comes from the Pin path. State that, no silent gap.+ setStatus('Opening AR — point at your floor to place your agent. To leave a shareable pin nearby people can find, tap Pin here.', { sticky: true });+ } catch (err) {+ log.error('[irl] Quick Look prep failed:', err);+ setStatus('Couldn’t prepare AR for this agent — use Pin here for compass + GPS placement instead.', { error: true, sticky: true });+ } finally {+ if (anchorBtn) { anchorBtn.classList.remove('is-active'); anchorBtn.disabled = false; }+ }+}++// One button, capability-routed: iOS opens AR Quick Look; WebXR devices enter the+// in-canvas hit-test session. ('pin' devices never reach here — the button stays+// hidden and the Pin path is the placement.)+function enterFloorPlacement() {+ if (_placementCapability === 'quicklook') return enterQuickLookPlacement();+ return enterFloorAnchor();+}++if (anchorBtn) anchorBtn.addEventListener('click', enterFloorPlacement);if (xrExitBtn) xrExitBtn.addEventListener('click', () => { xrSession?.end(); });// Taps on the overlay chrome (hint, exit, error actions) must not also fire the// XR 'select' that places an anchor.diff --git a/tests/ar-anchor-lifecycle.test.js b/tests/ar-anchor-lifecycle.test.jsindex e93809b52..f82c21fbc 100644--- a/tests/ar-anchor-lifecycle.test.js+++ b/tests/ar-anchor-lifecycle.test.js@@ -21,6 +21,9 @@ import {isXrVisible,placementHint,createPersistGate,+ reticleVisual,+ advancePulse,+ RETICLE_PULSE_SECONDS,} from '../src/ar/anchor-lifecycle.js';describe('nextTrackingState — transition-only tracking loss', () => {@@ -205,3 +208,96 @@ describe('createPersistGate — the durable pin saves EXACTLY once', () => {expect(persist.mock.calls[0][0].degraded).toBe(true);});});++describe('reticleVisual — searching ↔ locked look', () => {+ const buf = () => ({ scale: 0, opacity: 0, dot: 0, colorMix: 0 });++ it('locked (hit = 1) is full size, bright, dot filled, fully colour-shifted', () => {+ const v = reticleVisual(buf(), 1, 0, false);+ expect(v.scale).toBeCloseTo(1, 5);+ expect(v.opacity).toBeCloseTo(0.96, 5);+ expect(v.dot).toBe(1);+ expect(v.colorMix).toBe(1);+ });++ it('searching (hit = 0) is smaller, dimmer, dotless, un-shifted', () => {+ const v = reticleVisual(buf(), 0, 0, false);+ expect(v.scale).toBeLessThan(0.9);+ expect(v.opacity).toBeLessThan(0.5);+ expect(v.dot).toBe(0);+ expect(v.colorMix).toBe(0);+ });++ it('the breathing phase only modulates the searching look, never overshoots lock', () => {+ const calm = reticleVisual(buf(), 0, 0, false);+ const peak = reticleVisual(buf(), 0, 1, false);+ expect(peak.scale).toBeGreaterThan(calm.scale);+ expect(peak.opacity).toBeGreaterThan(calm.opacity);+ // Even at the top of the breath, searching stays below the locked values.+ expect(peak.scale).toBeLessThanOrEqual(1);+ expect(peak.opacity).toBeLessThan(0.96);+ });++ it('reduced motion flattens the breath to one calm static value', () => {+ const a = reticleVisual(buf(), 0, 0, true);+ const b = reticleVisual(buf(), 0, 1, true); // breathe ignored when reduced+ expect(a).toEqual(b);+ expect(a.scale).toBeCloseTo(0.94, 5);+ expect(a.opacity).toBeCloseTo(0.5, 5);+ });++ it('clamps out-of-range hit and breathe instead of extrapolating', () => {+ const over = reticleVisual(buf(), 5, 9, false);+ expect(over.scale).toBeCloseTo(1, 5);+ expect(over.dot).toBe(1);+ const under = reticleVisual(buf(), -3, -2, false);+ expect(under.dot).toBe(0);+ expect(under.colorMix).toBe(0);+ });++ it('writes into the caller-owned buffer and returns it (no per-frame allocation)', () => {+ const out = buf();+ const ret = reticleVisual(out, 0.5, 0.5, false);+ expect(ret).toBe(out);+ });+});++describe('advancePulse — one-shot confirm ring', () => {+ const buf = () => ({ t: 0, scale: 1, opacity: 0, done: false });++ it('starts expanding and fading from the tap point', () => {+ const p = advancePulse(buf(), 0.1);+ expect(p.t).toBeCloseTo(0.1, 5);+ expect(p.scale).toBeGreaterThan(1);+ expect(p.opacity).toBeLessThan(0.85);+ expect(p.opacity).toBeGreaterThan(0);+ expect(p.done).toBe(false);+ });++ it('completes at the full duration: max scale, zero opacity, done', () => {+ const p = advancePulse(buf(), RETICLE_PULSE_SECONDS);+ expect(p.scale).toBeCloseTo(3, 5);+ expect(p.opacity).toBeCloseTo(0, 5);+ expect(p.done).toBe(true);+ });++ it('expands monotonically and fades monotonically across the run', () => {+ const p = buf();+ let prevScale = 0;+ let prevOpacity = 1;+ for (let i = 0; i < 6; i++) {+ advancePulse(p, RETICLE_PULSE_SECONDS / 6);+ expect(p.scale).toBeGreaterThanOrEqual(prevScale);+ expect(p.opacity).toBeLessThanOrEqual(prevOpacity);+ prevScale = p.scale;+ prevOpacity = p.opacity;+ }+ expect(p.done).toBe(true);+ });++ it('mutates the caller-owned state and returns it (reused buffer, no allocation)', () => {+ const out = buf();+ const ret = advancePulse(out, 0.05);+ expect(ret).toBe(out);+ });+});diff --git a/tests/ar-placement-capability.test.js b/tests/ar-placement-capability.test.jsnew file mode 100644index 000000000..8719cda8f--- /dev/null+++ b/tests/ar-placement-capability.test.js@@ -0,0 +1,73 @@+// Placement-capability resolver (src/ar/placement-capability.js): the small+// device-classification that replaced /irl's binary WebXR gate. It must pick the+// RICHEST path a device can deliver — webxr where immersive-ar exists, ARKit+// Quick Look on iOS, and the always-available compass+GPS Pin path otherwise —+// and never throw (a broken probe degrades to 'pin', not an exception).++import { afterEach, describe, expect, it, vi } from 'vitest';++import { resolvePlacementCapability } from '../src/ar/placement-capability.js';++const ORIG_NAV = globalThis.navigator;++// Install a synthetic navigator: `xr` controls the immersive-ar probe, the rest+// drives the iOS sniff in canUseQuickLook().+function setNavigator({ xrSupported = null, ua = '', platform = 'Linux x86_64', maxTouchPoints = 0 } = {}) {+ const xr = xrSupported === null ? undefined : {+ isSessionSupported: vi.fn(async (mode) => mode === 'immersive-ar' && xrSupported === true),+ };+ if (xrSupported === 'throw') {+ xr.isSessionSupported = vi.fn(async () => { throw new Error('probe blew up'); });+ }+ Object.defineProperty(globalThis, 'navigator', {+ value: { xr, userAgent: ua, platform, maxTouchPoints },+ configurable: true,+ writable: true,+ });+}++afterEach(() => {+ Object.defineProperty(globalThis, 'navigator', { value: ORIG_NAV, configurable: true, writable: true });+ vi.restoreAllMocks();+});++describe('resolvePlacementCapability()', () => {+ it('returns "webxr" when immersive-ar is supported (Android Chrome)', async () => {+ setNavigator({ xrSupported: true, ua: 'Mozilla/5.0 (Linux; Android 14) Chrome/120' });+ expect(await resolvePlacementCapability()).toBe('webxr');+ });++ it('prefers webxr over quicklook when a device somehow offers both', async () => {+ setNavigator({ xrSupported: true, ua: 'iPhone', platform: 'iPhone', maxTouchPoints: 5 });+ expect(await resolvePlacementCapability()).toBe('webxr');+ });++ it('returns "quicklook" on iOS Safari (no immersive-ar)', async () => {+ setNavigator({ xrSupported: false, ua: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Safari', platform: 'iPhone' });+ expect(await resolvePlacementCapability()).toBe('quicklook');+ });++ it('returns "quicklook" on iPadOS (MacIntel + touch points masquerade)', async () => {+ setNavigator({ xrSupported: false, ua: 'Mozilla/5.0 (Macintosh; Intel Mac OS X) Safari', platform: 'MacIntel', maxTouchPoints: 5 });+ expect(await resolvePlacementCapability()).toBe('quicklook');+ });++ it('returns "pin" on a device with neither AR surface (desktop, old Android)', async () => {+ setNavigator({ xrSupported: false, ua: 'Mozilla/5.0 (Windows NT 10.0) Chrome/120', platform: 'Win32' });+ expect(await resolvePlacementCapability()).toBe('pin');+ });++ it('returns "pin" when navigator.xr is absent entirely', async () => {+ setNavigator({ xrSupported: null, ua: 'Mozilla/5.0 (X11; Linux) Firefox', platform: 'Linux x86_64' });+ expect(await resolvePlacementCapability()).toBe('pin');+ });++ it('never throws — a blown-up XR probe degrades to the next path, not an exception', async () => {+ // Probe throws AND it's an iPhone → falls through to quicklook, not a crash.+ setNavigator({ xrSupported: 'throw', ua: 'iPhone', platform: 'iPhone', maxTouchPoints: 5 });+ expect(await resolvePlacementCapability()).toBe('quicklook');+ // Probe throws on a non-iOS device → the always-available Pin path.+ setNavigator({ xrSupported: 'throw', ua: 'Android', platform: 'Linux armv8l' });+ expect(await resolvePlacementCapability()).toBe('pin');+ });+});diff --git a/tests/ar-webxr-session.test.js b/tests/ar-webxr-session.test.jsindex 6894bbcaf..c053bda6f 100644--- a/tests/ar-webxr-session.test.js+++ b/tests/ar-webxr-session.test.js@@ -89,13 +89,13 @@ describe('hit → tap → anchored (the happy path)', () => {it('moves the reticle and content onto the hit, then anchors on tap', async () => {const onAnchored = vi.fn();- const { renderer, viewer, xrSession } = await mount({ onAnchored });+ const { renderer, viewer, session, xrSession } = await mount({ onAnchored });const matrix = hitMatrix({ x: 1, y: -1.5, z: -2, yawDeg: 30 });renderer.tick(16, hitFrame(matrix));- // Reticle and content track the hit pose before the tap.- const reticle = viewer.scene.children.find((c) => c.type === 'Mesh');+ // Reticle (a ring+dot Group) and content track the hit pose before the tap.+ const reticle = session._reticle;expect(reticle.visible).toBe(true);expect(reticle.position.toArray()).toEqual([1, -1.5, -2]);expect(viewer.content.position.toArray()).toEqual([1, -1.5, -2]);@@ -173,10 +173,12 @@ describe('end() / OS-initiated end — restoration is idempotent', () => {it('restores the viewer and tears down exactly once, however the session ends', async () => {const onEnd = vi.fn();// Give content a non-trivial pre-AR transform, THEN start so it's captured.- const { renderer, viewer, session, xrSession } = await mount({ onEnd }, { start: false });+ const rig = await mount({ onEnd }, { start: false });+ const { renderer, viewer, session } = rig;viewer.content.position.set(5, 6, 7);viewer.content.rotation.set(0, 0.5, 0);await session.start();+ const xrSession = rig.xrSession; // the device handed one out only after start()// A hit moves content during the session…renderer.tick(16, hitFrame(hitMatrix({ x: 9, z: -9 })));@@ -193,8 +195,10 @@ describe('end() / OS-initiated end — restoration is idempotent', () => {// Content restored to the pre-AR transform captured at start.expect(viewer.content.position.toArray()).toEqual([5, 6, 7]);expect(viewer.content.rotation.y).toBeCloseTo(0.5, 6);- // The reticle Mesh was disposed and removed from the scene.- expect(viewer.scene.children.some((c) => c.type === 'Mesh')).toBe(false);+ // Reticle, contact shadow and pulse ring were all disposed and removed —+ // only the host's own content group is left in the scene.+ expect(session._reticle).toBeNull();+ expect(viewer.scene.children).toEqual([viewer.content]);// The visibilitychange listener was removed before teardown.expect(xrSession.listenerCount('visibilitychange')).toBe(0);@@ -236,9 +240,9 @@ describe('tracking loss — fires once, on the transition only', () => {});it('hides the reticle on tracking loss so the user never taps a stale one', async () => {- const { renderer, viewer } = await mount({});+ const { renderer, session } = await mount({});renderer.tick(0, hitFrame(hitMatrix({ z: -1 })));- const reticle = viewer.scene.children.find((c) => c.type === 'Mesh');+ const reticle = session._reticle;expect(reticle.visible).toBe(true);for (let i = 1; i <= TRACKING_LOSS_FRAMES; i++) renderer.tick(i, lostFrame());expect(reticle.visible).toBe(false);diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex 7ac80a4fd..6a49ba1a8 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -13,13 +13,11 @@ import { countOpenPositions, getDailySpend } from './strategy-store.js';import { notifyBuy, notifySell } from '../../api/_lib/sniper/notify.js';import {getSpendLimits, enforceSpendLimit, SpendLimitError, recordSpend, lamportsToUsd,+ checkConcurrency, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,+ SOL_FEE_HEADROOM_LAMPORTS,} 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.-const SOL_HEADROOM_LAMPORTS = 3_000_000n; // ~0.003 SOL-// ── per-agent serialization ────────────────────────────────────────────────// Single-worker assumption: a per-agent in-process lock makes the budget +// concurrency checks race-free without a DB reservation. (Scaling to N workers@@ -101,11 +99,13 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {// 2. concurrency capconst open = await countOpenPositions(strat.agent_id, cfg.network);- if (open >= strat.max_concurrent_positions) return skip(tag, 'max_positions');+ const concurrency = checkConcurrency(open, strat.max_concurrent_positions);+ if (concurrency) return skip(tag, concurrency.reason);// 3. daily budget capconst spent = await getDailySpend(strat.agent_id, cfg.network);- if (spent + perTrade > BigInt(strat.daily_budget_lamports)) return skip(tag, 'daily_budget');+ const budget = checkDailyBudgetLamports(spent, perTrade, BigInt(strat.daily_budget_lamports));+ if (budget) return skip(tag, budget.reason);// 3b. shared per-agent spend policy (the same ceiling that governs// withdraw / x402 / trade). Opt-in: only priced + enforced when the owner@@ -138,9 +138,8 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {const ctx = await getTradeCtx(cfg.network);const lamports = BigInt(await ctx.connection.getBalance(keypair.publicKey, 'confirmed'));- if (lamports < perTrade + SOL_HEADROOM_LAMPORTS) {- return await fail(posId, tag, 'insufficient_sol');- }+ const headroom = checkSolHeadroom(lamports, perTrade, SOL_FEE_HEADROOM_LAMPORTS);+ if (headroom) return await fail(posId, tag, headroom.reason);const mintPk = new ctx.web3.PublicKey(mint.mint);const slippagePct = strat.slippage_bps / 100;@@ -150,9 +149,8 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {if (strat.require_sol_quote && !quote.quoteMint.equals(ctx.web3.PublicKey.default) && quote.quoteMint.toBase58() !== 'So11111111111111111111111111111111111111112') {return await fail(posId, tag, 'quote_not_sol');}- if (Number(quote.priceImpactPct) > Number(strat.max_price_impact_pct)) {- return await fail(posId, tag, 'price_impact');- }+ const impact = checkPriceImpact(Number(quote.priceImpactPct), Number(strat.max_price_impact_pct));+ if (impact) return await fail(posId, tag, impact.reason);// 7. build + (live) broadcastconst built = await ctx.client.buildBuyInstructions({