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
Add capabilities/unlocks endpoints, integrity page, and policy/guard tests
nirholas5e2c810fdc7d
diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 029c8c7b5..747af852c 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -67,6 +67,11 @@ export default wrap(async function handler(req, res) {return mod.default(req, res, id, action, parts);}+ if (sub === 'capabilities') {+ const mod = await import('./capabilities.js');+ return mod.default(req, res, id, action, parts);+ }+if (sub === 'trade') {const mod = await import('./agent-trade.js');return mod.default(req, res, id, action);diff --git a/api/agents/_id/unlocks.js b/api/agents/_id/unlocks.jsnew file mode 100644index 000000000..fda8f519f--- /dev/null+++ b/api/agents/_id/unlocks.js@@ -0,0 +1,81 @@+// /api/agents/:id/unlocks+//+// GET → the agent's reputation-derived unlock state: which world areas and+// cosmetics its real, server-computed reputation has earned, how close it+// is to the rest, and which cosmetics it has already claimed. Public — an+// agent's tier and unlocks are a trust signal others rely on (mirrors the+// public /reputation read). `is_owner` is echoed so the client can show+// owner-only "claim" affordances.+// POST /claim { key } → owner-only: persist an unlocked cosmetic onto the agent+// record. Re-authorizes ownership AND the unlock requirement server-side+// (api/_lib/trust/access.js) and is CSRF-protected — a client can never+// fake a tier to grant itself a cosmetic.+//+// Real capability gates (e.g. the arena elite floor) call requireUnlock() from the+// protected route itself; this endpoint is the read + the cosmetic-claim surface.++import { cors, json, error, method, wrap, rateLimited, readJson } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { getSessionUser } from '../../_lib/auth.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { sql } from '../../_lib/db.js';+import { getAgentUnlocks, claimUnlock, resolveUserId, AccessError } from '../../_lib/trust/access.js';++export const handleUnlocks = wrap(async (req, res, agentId, action) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ if (req.method === 'GET') {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let payload;+ try {+ payload = await getAgentUnlocks(agentId);+ } catch (err) {+ if (err.status === 404) return error(res, 404, 'not_found', 'agent not found');+ throw err;+ }++ // Echo ownership so the client can reveal owner-only claim controls.+ const userId = await resolveUserId(req);+ let isOwner = false;+ if (userId) {+ const [own] = await sql`+ select 1 from agent_identities where id = ${agentId} and user_id = ${userId} and deleted_at is null limit 1+ `.catch(() => []);+ isOwner = Boolean(own);+ }++ return json(+ res,+ 200,+ { ...payload, is_owner: isOwner },+ { 'cache-control': 'public, max-age=30, stale-while-revalidate=180' },+ );+ }++ if (req.method === 'POST') {+ if (action !== 'claim') return error(res, 404, 'not_found', 'unknown action');++ const session = await getSessionUser(req).catch(() => null);+ if (!session) return error(res, 401, 'unauthenticated', 'sign in to claim unlocks');+ if (!(await requireCsrf(req, res, session.id))) return;++ const rl = await limits.user(session.id);+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req).catch(() => ({}));+ const key = typeof body?.key === 'string' ? body.key : null;+ if (!key) return error(res, 400, 'bad_request', 'missing unlock key');++ try {+ const result = await claimUnlock(req, { agentId, key });+ return json(res, 200, { ok: true, ...result });+ } catch (err) {+ if (err instanceof AccessError) return error(res, err.status, err.code, err.message);+ throw err;+ }+ }++ return method(req, res, ['GET', 'POST']);+});diff --git a/api/agents/capabilities.js b/api/agents/capabilities.jsnew file mode 100644index 000000000..62dce762a--- /dev/null+++ b/api/agents/capabilities.js@@ -0,0 +1,205 @@+// /api/agents/:id/capabilities — scoped session keys (least-privilege capabilities)+// for a custodial agent wallet. Dispatched from api/agents/[id].js with the+// remaining path segments. Owner-authenticated; every mutation is CSRF-gated.+//+// Routes:+// GET /capabilities list live + historical grants, settings, auto-suggestions+// POST /capabilities mint a scoped capability+// PUT /capabilities/settings toggle require_capabilities (least-privilege mode)+// POST /capabilities/:cid/revoke revoke one capability (immediate)+// POST /capabilities/revoke-all revoke every live capability ("kill all")+//+// Capabilities strictly SUBTRACT authority and are enforced server-side on every+// autonomous spend by api/_lib/wallet-capabilities.js (composed into the shared+// guards). This endpoint is the issuance + lifecycle + owner-visibility surface.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { requireCsrf } from '../_lib/csrf.js';+import { solUsdPrice } from '../_lib/avatar-wallet.js';+import { getSpendLimits, setSpendLimits, SpendLimitError } from '../_lib/agent-trade-guards.js';+import {+ mintCapability, listCapabilities, revokeCapability, revokeAllCapabilities,+ getCapability, CAPABILITY_ACTIONS,+} from '../_lib/wallet-capabilities.js';++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++// Owner gate: authenticated AND owns the agent. Returns { auth, agent } or null+// (response already sent on failure). Capabilities are an owner-only surface — a+// read-only visitor never sees another wallet's leashes.+async function loadOwner(req, res, id) {+ const auth = await resolveAuth(req);+ if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return null; }+ const [agent] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ if (!agent) { error(res, 404, 'not_found', 'agent not found'); return null; }+ if (agent.user_id !== auth.userId) { error(res, 403, 'forbidden', 'not your agent'); return null; }+ return { auth, agent };+}++function sendErr(res, e) {+ if (e instanceof SpendLimitError) {+ return error(res, e.status || 400, e.code || 'invalid', e.message, e.detail ? { detail: e.detail } : undefined);+ }+ if (e && e.status) return error(res, e.status, e.code || 'error', e.message);+ console.error('[capabilities] unexpected error', e?.message, e?.stack);+ return error(res, 500, 'server_error', 'something went wrong');+}++// ── GET: list + settings + auto-suggested least-privilege defaults ──────────────+async function handleList(req, res, id) {+ const caps = await listCapabilities(id, { includeRevoked: true });+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ const lim = getSpendLimits(row?.meta);+ const suggestions = await buildSuggestions(id, caps);+ return json(res, 200, {+ capabilities: caps,+ settings: { require_capabilities: lim.require_capabilities },+ actions: CAPABILITY_ACTIONS,+ suggestions,+ });+}++// Auto-suggest tight default capabilities so least-privilege is the default, not a+// chore. For every armed sniper strategy that has no live capability scoped to it,+// propose a snipe grant budgeted to (a touch above) the strategy's own daily SOL+// budget. The owner accepts it in one tap — the leash matches what the strategy+// can already spend, just made explicit + independently revocable.+async function buildSuggestions(agentId, caps) {+ const out = [];+ try {+ const strategies = await sql`+ SELECT id, network, enabled, daily_budget_lamports, per_trade_lamports+ FROM agent_sniper_strategies+ WHERE agent_id = ${agentId} AND enabled = true AND daily_budget_lamports > 0+ `;+ if (strategies.length === 0) return out;+ const liveByHolder = new Set(+ caps.filter((c) => c.status === 'active' && c.holder_ref).map((c) => c.holder_ref),+ );+ let solUsd = null;+ try { solUsd = await solUsdPrice(); } catch { solUsd = null; }+ for (const s of strategies) {+ if (liveByHolder.has(String(s.id))) continue; // already leashed+ const dailySol = Number(s.daily_budget_lamports) / 1e9;+ const perTradeSol = Number(s.per_trade_lamports) / 1e9;+ const aggregateUsd = solUsd ? Math.max(1, Math.ceil(dailySol * solUsd)) : null;+ const perUseUsd = solUsd && perTradeSol > 0 ? Math.max(1, Math.ceil(perTradeSol * solUsd * 1.05)) : null;+ out.push({+ kind: 'strategy',+ holder_ref: String(s.id),+ label: 'Sniper strategy',+ reason: `This strategy can spend up to ◎${dailySol.toFixed(3)}/day. A scoped key makes that explicit and revocable on its own.`,+ draft: {+ label: 'Sniper strategy',+ holder_kind: 'strategy',+ holder_ref: String(s.id),+ actions: ['snipe'],+ per_use_usd: perUseUsd,+ aggregate_usd: aggregateUsd,+ target_kind: 'any',+ targets: [],+ ttl_seconds: 24 * 60 * 60,+ },+ });+ }+ } catch (e) {+ console.warn('[capabilities] suggestions failed', e?.message);+ }+ return out;+}++// ── POST: mint ──────────────────────────────────────────────────────────────────+async function handleMint(req, res, id, userId) {+ let body;+ try { body = await readJson(req, 20_000); } catch { return error(res, 400, 'bad_request', 'invalid JSON body'); }+ const cap = await mintCapability({+ agentId: id,+ userId,+ label: body.label,+ holderKind: body.holder_kind,+ holderRef: body.holder_ref,+ actions: body.actions,+ perUseUsd: body.per_use_usd,+ aggregateUsd: body.aggregate_usd,+ targetKind: body.target_kind,+ targets: body.targets,+ expiresAt: body.expires_at,+ ttlSeconds: body.ttl_seconds,+ meta: body.meta && typeof body.meta === 'object' ? body.meta : {},+ });+ // Re-read through the list shaper so the response carries the same decorated+ // shape (status, spent_usd) the GET feed uses — one consistent capability object.+ const [shaped] = await listCapabilities(id, { includeRevoked: true }).then((rows) => rows.filter((r) => r.id === cap.id));+ return json(res, 201, { capability: shaped || cap });+}++// ── PUT settings: least-privilege mode toggle ───────────────────────────────────+async function handleSettings(req, res, id, userId) {+ let body;+ try { body = await readJson(req, 4_000); } catch { return error(res, 400, 'bad_request', 'invalid JSON body'); }+ if (typeof body.require_capabilities !== 'boolean') {+ return error(res, 400, 'validation_error', 'require_capabilities must be a boolean');+ }+ const next = await setSpendLimits(id, userId, { require_capabilities: body.require_capabilities }, { req });+ return json(res, 200, { settings: { require_capabilities: next.require_capabilities } });+}++// ── POST revoke / revoke-all ────────────────────────────────────────────────────+async function handleRevoke(req, res, id, userId, cid) {+ const existing = await getCapability(cid);+ if (!existing || String(existing.agent_id) !== String(id)) {+ return error(res, 404, 'not_found', 'capability not found');+ }+ const row = await revokeCapability(cid, { agentId: id, userId, reason: 'owner_revoked' });+ // Idempotent: revoking an already-revoked grant is success (it's already dead).+ return json(res, 200, { revoked: true, id: cid, already: !row });+}++async function handleRevokeAll(req, res, id, userId) {+ const count = await revokeAllCapabilities(id, userId, 'owner_revoked_all');+ return json(res, 200, { revoked: true, count });+}++export default async function handler(req, res, id, action, parts = []) {+ if (cors(req, res, { methods: 'GET,POST,PUT,OPTIONS', credentials: true })) return;++ // Rate-limit reads + writes per IP (shared bucket with other agent endpoints).+ const ip = clientIp(req);+ const rl = await limits.api(ip);+ if (!rl.success) return rateLimited(res, rl);++ // GET list — owner-gated, no CSRF.+ if (req.method === 'GET' && !action) {+ const owned = await loadOwner(req, res, id);+ if (!owned) return;+ try { return await handleList(req, res, id); } catch (e) { return sendErr(res, e); }+ }++ // All mutations: owner-gated + CSRF.+ if (req.method === 'POST' || req.method === 'PUT') {+ const owned = await loadOwner(req, res, id);+ if (!owned) return;+ if (!(await requireCsrf(req, res, owned.auth.userId))) return;+ const userId = owned.auth.userId;+ try {+ if (req.method === 'POST' && !action) return await handleMint(req, res, id, userId);+ if (req.method === 'PUT' && action === 'settings') return await handleSettings(req, res, id, userId);+ if (req.method === 'POST' && action === 'revoke-all') return await handleRevokeAll(req, res, id, userId);+ // /capabilities/:cid/revoke — action = capability id, parts[5] = 'revoke'+ if (req.method === 'POST' && action && parts[5] === 'revoke') {+ return await handleRevoke(req, res, id, userId, action);+ }+ } catch (e) { return sendErr(res, e); }+ }++ return error(res, 405, 'method_not_allowed', 'unsupported method or route');+}diff --git a/pages/integrity.html b/pages/integrity.htmlnew file mode 100644index 000000000..928ee382d--- /dev/null+++ b/pages/integrity.html@@ -0,0 +1,100 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Custody Integrity · three.ws</title>+ <meta name="description" content="three.ws custodial agent wallets are provably honest. Every few hours the platform commits a Merkle root over every wallet's on-chain state to Solana. Verify the latest root on-chain yourself — no account, no trust required." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/integrity" />+ <meta property="og:title" content="Custody Integrity · three.ws" />+ <meta property="og:description" content="Provable, on-chain-anchored custody for every agent wallet. Verify the latest root yourself — no trust required." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Custody+Integrity&d=Provable%2C+on-chain-anchored+custody+for+every+agent+wallet.+Don%27t+trust%2C+verify.&p=%2Fintegrity" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Custody Integrity · three.ws" />+ <meta name="twitter:description" content="Provable, on-chain-anchored custody for every agent wallet. Verify it yourself." />+ <meta name="theme-color" content="#0a0a0a" />+ <meta name="robots" content="index, follow, max-image-preview:large" />+ <link rel="canonical" href="https://three.ws/integrity" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <style>+ .intg-shell { max-width: 880px; margin: 0 auto; padding: clamp(20px, 5vw, 44px) 18px 80px; }+ .intg-hero { margin-bottom: 26px; }+ .intg-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: .72rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 10px; }+ .intg-kicker::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--success, #4ade80); box-shadow: 0 0 8px color-mix(in srgb, var(--success,#4ade80) 60%, transparent); }+ .intg-title { font-family: var(--font-display, system-ui); font-size: clamp(1.8rem, 5vw, 2.6rem); font-weight: 700; color: var(--ink-bright, #fff); margin: 0 0 10px; line-height: 1.08; }+ .intg-sub { color: var(--ink-dim, #888); font-size: 1rem; line-height: 1.6; margin: 0; max-width: 64ch; }+ .intg-sub a { color: var(--ink, #e8e8e8); }+ .intg-card { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,.03)); padding: clamp(16px, 3vw, 24px); margin-bottom: 18px; }+ .intg-status { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }+ .intg-seal { width: 52px; height: 52px; border-radius: 50%; flex: none; display: grid; place-items: center; font-size: 24px; background: var(--surface-3, rgba(255,255,255,.08)); }+ .intg-status.is-verified { }+ .intg-status.is-verified .intg-seal { background: color-mix(in srgb, var(--success,#4ade80) 18%, transparent); color: var(--success, #4ade80); }+ .intg-status.is-failed .intg-seal { background: color-mix(in srgb, var(--danger,#f87171) 18%, transparent); color: var(--danger, #f87171); }+ .intg-status.is-pending .intg-seal { background: color-mix(in srgb, var(--warn,#fbbf24) 18%, transparent); color: var(--warn, #fbbf24); }+ .intg-status-main { min-width: 0; flex: 1; }+ .intg-status-title { font-size: 1.2rem; font-weight: 700; color: var(--ink-bright, #fff); font-family: var(--font-display, system-ui); line-height: 1.15; }+ .intg-status-sub { font-size: .85rem; color: var(--ink-dim, #888); margin-top: 4px; line-height: 1.5; }+ .intg-status-sub a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }+ .intg-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-top: 18px; }+ .intg-stat { background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); padding: 12px 14px; }+ .intg-stat-k { font-size: .68rem; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim, #888); }+ .intg-stat-v { font-family: var(--font-mono, ui-monospace, monospace); font-size: 1.05rem; color: var(--ink-bright, #fff); margin-top: 5px; word-break: break-all; }+ .intg-stat-v a { color: inherit; }+ .intg-spin { width: 20px; height: 20px; border-radius: 50%; border: 2px solid color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); border-top-color: var(--warn,#fbbf24); animation: intg-spin 0.7s linear infinite; }+ @keyframes intg-spin { to { transform: rotate(360deg); } }+ @media (prefers-reduced-motion: reduce) { .intg-spin { animation: none; } }+ .intg-h2 { font-family: var(--font-display, system-ui); font-size: 1.1rem; font-weight: 600; color: var(--ink-bright, #fff); margin: 0 0 4px; }+ .intg-p { color: var(--ink-dim, #888); font-size: .9rem; line-height: 1.55; margin: 0 0 14px; max-width: 64ch; }+ .intg-table { width: 100%; border-collapse: collapse; font-size: .82rem; }+ .intg-table th { text-align: right; font-weight: 500; color: var(--ink-dim, #888); font-size: .68rem; text-transform: uppercase; letter-spacing: .04em; padding: 0 0 9px; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.08)); }+ .intg-table th:first-child { text-align: left; }+ .intg-table td { text-align: right; padding: 10px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); font-family: var(--font-mono, ui-monospace, monospace); color: var(--ink, #e8e8e8); }+ .intg-table td:first-child { text-align: left; }+ .intg-table tr:last-child td { border-bottom: none; }+ .intg-table a { color: var(--ink, #c8c8c8); }+ .intg-pill { display: inline-block; font-size: .66rem; font-weight: 600; padding: 2px 8px; border-radius: 999px; }+ .intg-pill.anchored { color: var(--success, #4ade80); background: color-mix(in srgb, var(--success,#4ade80) 12%, transparent); }+ .intg-pill.pending { color: var(--warn, #fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 12%, transparent); }+ .intg-pill.failed { color: var(--danger, #f87171); background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); }+ .intg-btn { appearance: none; font: inherit; font-size: .85rem; font-weight: 600; cursor: pointer; color: var(--ink, #e8e8e8); background: transparent; border: 1px solid var(--stroke, rgba(255,255,255,.14)); border-radius: var(--radius-md, 10px); padding: 9px 16px; text-decoration: none; display: inline-flex; align-items: center; gap: 7px; transition: background var(--duration-fast,140ms); }+ .intg-btn:hover { background: var(--surface-2, rgba(255,255,255,.05)); }+ .intg-btn:focus-visible { outline: 2px solid var(--focus-ring-color, #fff); outline-offset: 2px; }+ .intg-skel span { display: block; background: var(--surface-2, rgba(255,255,255,.05)); border-radius: var(--radius-md, 10px); animation: intg-skel 1.4s ease-in-out infinite; margin-bottom: 14px; }+ @keyframes intg-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }+ @media (prefers-reduced-motion: reduce) { .intg-skel span { animation: none; } }+ .intg-explain { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin-top: 6px; }+ .intg-step { padding: 14px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); }+ .intg-step-n { font-family: var(--font-mono, ui-monospace, monospace); font-size: .7rem; color: var(--success, #4ade80); }+ .intg-step-t { color: var(--ink-bright, #fff); font-weight: 600; font-size: .9rem; margin: 4px 0; }+ .intg-step-d { color: var(--ink-dim, #888); font-size: .82rem; line-height: 1.5; }+ </style>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Custody Integrity","description":"Provable, on-chain-anchored custody for every three.ws agent wallet.","url":"https://three.ws/integrity"}</script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="intg-shell">+ <section class="intg-hero">+ <p class="intg-kicker">Provable custody · live on-chain</p>+ <h1 class="intg-title">Custody you can verify</h1>+ <p class="intg-sub">Agent wallets on three.ws are custodial — we hold the keys and sign on your behalf. So we make custody <strong>provable</strong>, not promised. Every few hours we snapshot every wallet's on-chain state, build a Merkle tree, and commit the root to Solana. Below is the latest root and its anchoring transaction — verify it on-chain yourself. Own a wallet? <a href="/proof">Verify your own inclusion proof →</a></p>+ </section>+ <div id="intg-root" aria-live="polite"></div>+ </main>++ <script type="module" src="/src/integrity.js"></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/src/element.js b/src/element.jsindex 7a9533763..245af9c40 100644--- a/src/element.js+++ b/src/element.js@@ -1765,6 +1765,14 @@ class Agent3DElement extends HTMLElement {this._avatar = new AgentAvatar(this._viewer, protocol, _identity);this._avatar.attach();+ // Apply any mood set before the empathy layer existed so the avatar+ // boots straight into its current resting expression.+ if (this._pendingMood) {+ this._avatar.setMood(this._pendingMood.valence, this._pendingMood.arousal, {+ reducedMotion: this._pendingMood.reducedMotion,+ });+ }+if (this._runtime.tts) {const tts = this._runtime.tts;const avatar = this._avatar;@@ -3190,6 +3198,20 @@ class Agent3DElement extends HTMLElement {return true;}+ /**+ * Set the avatar's sustained mood (Living Agents · Task 07). Drives the+ * resting facial expression + posture continuously through the empathy layer.+ * Stored so it still lands if the empathy layer attaches after this call.+ * @param {number} valence -1..1+ * @param {number} arousal 0..1+ * @param {{reducedMotion?: boolean}} [opts]+ */+ setMood(valence, arousal, opts = {}) {+ this._pendingMood = { valence, arousal, reducedMotion: Boolean(opts.reducedMotion) };+ this._avatar?.setMood(valence, arousal, { reducedMotion: this._pendingMood.reducedMotion });+ return true;+ }+_waitForReady() {if (this._mounted) return Promise.resolve();return new Promise((resolve) => {diff --git a/tests/spend-policy-rules.test.js b/tests/spend-policy-rules.test.jsnew file mode 100644index 000000000..a8e12a705--- /dev/null+++ b/tests/spend-policy-rules.test.js@@ -0,0 +1,225 @@+/**+ * Natural-language spend policies — the deterministic core, pinned.+ *+ * This is money governance: the LLM only authors these rules, but THIS evaluator+ * enforces them on every spend. So the invariants that keep it trustworthy are+ * tested here, with no model and no DB (everything is pure):+ * - normalization is TOTAL — malformed/hostile input never throws, it drops away,+ * - the evaluator is first-match and fails closed on unobservable signals (a+ * token-age rule is inert on an x402 payment, never a false block),+ * - the plain-English readback is generated from the DSL (golden-pinned) so it can+ * never drift from what code enforces,+ * - the backtest math (rolling daily window, allowed/blocked tallies) is faithful,+ * - a policy diff flags any loosening so protection is never weakened silently.+ */++import { describe, it, expect } from 'vitest';+import {+ normalizePolicyRules, evaluatePolicy, isDenied, describeRule, describePolicyRules,+ diffPolicies, backtestPolicy, syntheticProbes, referencedFields,+ MAX_RULES, MAX_CLAUSES_PER_RULE,+} from '../api/_lib/spend-policy-rules.js';++const block = (when) => ({ action: 'block', when });+const evalDoc = (rules, ctx) => evaluatePolicy(normalizePolicyRules({ rules }), ctx);++describe('normalizePolicyRules — totality', () => {+ it('never throws on hostile / malformed input', () => {+ for (const bad of [null, undefined, 42, 'x', [], {}, { rules: 'no' }, { rules: [null, 1, {}] }, { rules: [{ action: 'nuke', when: [] }] }]) {+ expect(() => normalizePolicyRules(bad)).not.toThrow();+ expect(normalizePolicyRules(bad).rules).toBeInstanceOf(Array);+ }+ });++ it('drops rules whose every clause is invalid (no silent block-all)', () => {+ const doc = normalizePolicyRules({ rules: [{ action: 'block', when: [{ field: 'nonsense', op: 'gt', value: 1 }] }] });+ expect(doc.rules).toHaveLength(0);+ });++ it('drops empty-when rules — a catch-all belongs to the freeze switch', () => {+ expect(normalizePolicyRules({ rules: [{ action: 'block', when: [] }] }).rules).toHaveLength(0);+ });++ it('rejects an illegal operator for a field type', () => {+ // 'in' is a string op; illegal on a numeric field → clause dropped → rule dropped.+ expect(normalizePolicyRules({ rules: [block([{ field: 'amount_usd', op: 'in', value: [1, 2] }])] }).rules).toHaveLength(0);+ // boolean field only accepts 'is'+ expect(normalizePolicyRules({ rules: [block([{ field: 'destination_allowlisted', op: 'gt', value: 1 }])] }).rules).toHaveLength(0);+ });++ it('caps rule count and clause count', () => {+ const many = Array.from({ length: MAX_RULES + 20 }, () => block([{ field: 'amount_usd', op: 'gt', value: 1 }]));+ expect(normalizePolicyRules({ rules: many }).rules.length).toBeLessThanOrEqual(MAX_RULES);++ const manyClauses = Array.from({ length: MAX_CLAUSES_PER_RULE + 5 }, (_, i) => ({ field: 'amount_usd', op: 'gt', value: i }));+ const doc = normalizePolicyRules({ rules: [block(manyClauses)] });+ expect(doc.rules[0].when.length).toBeLessThanOrEqual(MAX_CLAUSES_PER_RULE);+ });++ it('assigns unique ids', () => {+ const doc = normalizePolicyRules({ rules: [+ { id: 'r', action: 'block', when: [{ field: 'amount_usd', op: 'gt', value: 1 }] },+ { id: 'r', action: 'block', when: [{ field: 'amount_usd', op: 'gt', value: 2 }] },+ ] });+ expect(new Set(doc.rules.map((r) => r.id)).size).toBe(doc.rules.length);+ });++ it('coerces numeric/boolean string values', () => {+ const doc = normalizePolicyRules({ rules: [+ block([{ field: 'amount_usd', op: 'gt', value: '50' }]),+ block([{ field: 'counterparty_seen_before', op: 'is', value: 'false' }]),+ ] });+ expect(doc.rules[0].when[0].value).toBe(50);+ expect(doc.rules[1].when[0].value).toBe(false);+ });+});++describe('evaluatePolicy — decisions', () => {+ it('blocks an over-limit amount, allows under', () => {+ const rules = [block([{ field: 'amount_usd', op: 'gt', value: 50 }])];+ expect(evalDoc(rules, { amount_usd: 60 }).decision).toBe('block');+ expect(evalDoc(rules, { amount_usd: 40 }).decision).toBe('allow');+ });++ it('defaults to allow when nothing matches', () => {+ expect(evalDoc([block([{ field: 'amount_usd', op: 'gt', value: 50 }])], { amount_usd: 1 }).matched).toBeNull();+ });++ it('an unobservable signal never matches (token-age rule inert on x402)', () => {+ const rules = [block([{ field: 'category', op: 'eq', value: 'trade' }, { field: 'token_age_hours', op: 'lt', value: 24 }])];+ // x402 payment: no token_age in context → rule cannot fire.+ expect(evalDoc(rules, { category: 'x402', amount_usd: 5 }).decision).toBe('allow');+ // young-token trade → blocked.+ expect(evalDoc(rules, { category: 'trade', token_age_hours: 2 }).decision).toBe('block');+ // old-token trade → allowed.+ expect(evalDoc(rules, { category: 'trade', token_age_hours: 100 }).decision).toBe('allow');+ });++ it('first match wins — an allow carve-out short-circuits a later block', () => {+ const rules = [+ { action: 'allow', when: [{ field: 'counterparty', op: 'eq', value: 'TRUSTED' }] },+ block([{ field: 'amount_usd', op: 'gt', value: 10 }]),+ ];+ expect(evalDoc(rules, { counterparty: 'TRUSTED', amount_usd: 999 }).decision).toBe('allow');+ expect(evalDoc(rules, { counterparty: 'OTHER', amount_usd: 999 }).decision).toBe('block');+ });++ it('freeze and require_step_up are denials', () => {+ expect(isDenied(evalDoc([{ action: 'freeze', when: [{ field: 'trade_pnl_pct', op: 'lt', value: -30 }] }], { trade_pnl_pct: -50 }).decision)).toBe(true);+ expect(evalDoc([{ action: 'require_step_up', when: [{ field: 'amount_usd', op: 'gt', value: 100 }] }], { amount_usd: 200 }).decision).toBe('step_up');+ });++ it('sol_reserve_after floor blocks draining the last SOL', () => {+ const rules = [block([{ field: 'sol_reserve_after', op: 'lt', value: 1 }])];+ expect(evalDoc(rules, { sol_reserve_after: 0.4 }).decision).toBe('block');+ expect(evalDoc(rules, { sol_reserve_after: 5 }).decision).toBe('allow');+ });++ it('counterparty_seen_before=false blocks first-time payees', () => {+ const rules = [block([{ field: 'category', op: 'eq', value: 'x402' }, { field: 'counterparty_seen_before', op: 'is', value: false }])];+ expect(evalDoc(rules, { category: 'x402', counterparty_seen_before: false }).decision).toBe('block');+ expect(evalDoc(rules, { category: 'x402', counterparty_seen_before: true }).decision).toBe('allow');+ });++ it('is total — a corrupt rule object never throws', () => {+ const doc = { rules: [{ action: 'block', when: [{ field: 'amount_usd', op: 'gt', value: 'NaN-ish' }] }, null, { when: null }] };+ expect(() => evaluatePolicy(doc, { amount_usd: 5 })).not.toThrow();+ });+});++describe('describeRule / readback — golden (must match enforcement)', () => {+ it('renders the README worked example, rule by rule', () => {+ expect(describeRule(block([{ field: 'amount_usd', op: 'gt', value: 50 }])))+ .toBe('Block the spend when the amount is over $50.');+ expect(describeRule(block([{ field: 'sol_reserve_after', op: 'lt', value: 1 }])))+ .toBe('Block the spend when it would leave less than 1 SOL in the wallet.');+ expect(describeRule({ action: 'freeze', when: [{ field: 'trade_pnl_pct', op: 'lt', value: -30 }] }))+ .toBe('Freeze the wallet and block all spending when the trade is down more than 30%.');+ expect(describeRule(block([{ field: 'category', op: 'eq', value: 'x402' }, { field: 'counterparty_seen_before', op: 'is', value: false }])))+ .toBe('Block the spend when it is an x402 payment and you have never paid this recipient before.');+ expect(describeRule(block([{ field: 'category', op: 'eq', value: 'trade' }, { field: 'token_age_hours', op: 'lt', value: 24 }])))+ .toBe('Block the spend when it is a trade and the token is younger than 1 day.');+ });++ it('numbers the policy readback', () => {+ const rb = describePolicyRules(normalizePolicyRules({ rules: [+ block([{ field: 'amount_usd', op: 'gt', value: 50 }]),+ block([{ field: 'sol_reserve_after', op: 'lt', value: 1 }]),+ ] }));+ expect(rb.map((r) => r.n)).toEqual([1, 2]);+ expect(rb[0].text).toContain('over $50');+ });+});++describe('diffPolicies — loosening detection', () => {+ const a = normalizePolicyRules({ rules: [block([{ field: 'amount_usd', op: 'gt', value: 50 }])] });+ const tighter = normalizePolicyRules({ rules: [+ block([{ field: 'amount_usd', op: 'gt', value: 50 }]),+ block([{ field: 'sol_reserve_after', op: 'lt', value: 1 }]),+ ] });+ const empty = normalizePolicyRules({ rules: [] });++ it('flags removing a protective rule as loosening', () => {+ expect(diffPolicies(a, empty).loosened).toBe(true);+ expect(diffPolicies(a, empty).loosening_notes.length).toBeGreaterThan(0);+ });+ it('adding a rule is not loosening', () => {+ const d = diffPolicies(a, tighter);+ expect(d.loosened).toBe(false);+ expect(d.added).toHaveLength(1);+ });+ it('an identical policy has no diff', () => {+ const d = diffPolicies(a, a);+ expect(d.added).toHaveLength(0);+ expect(d.removed).toHaveLength(0);+ expect(d.loosened).toBe(false);+ });+});++describe('backtestPolicy — faithful replay', () => {+ const day = (n) => new Date(Date.UTC(2026, 0, n, 12, 0, 0)).toISOString();+ const spend = (id, usd, extra = {}) => ({ id, event_type: 'spend', category: 'x402', asset: 'USDC', usd, created_at: day(id), ...extra });++ it('counts allowed vs blocked by the same evaluator', () => {+ const doc = normalizePolicyRules({ rules: [block([{ field: 'amount_usd', op: 'gt', value: 50 }])] });+ const events = [spend(1, 10), spend(2, 80), spend(3, 200), spend(4, 5)];+ const bt = backtestPolicy(doc, events);+ expect(bt.total).toBe(4);+ expect(bt.blocked).toBe(2);+ expect(bt.allowed).toBe(2);+ expect(bt.blocked_usd).toBe(280);+ expect(bt.by_rule[0].count).toBe(2);+ });++ it('rolling daily total only counts ALLOWED spends', () => {+ // "block when today's total would exceed $100". Replayed same-day.+ const doc = normalizePolicyRules({ rules: [block([{ field: 'daily_total_usd', op: 'gt', value: 100 }])] });+ const sameDay = (i, usd) => ({ id: i, event_type: 'spend', category: 'x402', asset: 'USDC', usd, created_at: new Date(Date.UTC(2026, 0, 1, 10 + i, 0, 0)).toISOString() });+ // 60 (ok, total 60) → 60 (blocked, would be 120) → 30 (ok, total 90; the blocked+ // one never counted) → 30 (blocked, would be 120).+ const bt = backtestPolicy(doc, [sameDay(1, 60), sameDay(2, 60), sameDay(3, 30), sameDay(4, 30)]);+ expect(bt.allowed).toBe(2);+ expect(bt.blocked).toBe(2);+ });++ it('ignores non-spend rows and is total on junk', () => {+ expect(() => backtestPolicy(normalizePolicyRules({ rules: [] }), null)).not.toThrow();+ const bt = backtestPolicy(normalizePolicyRules({ rules: [block([{ field: 'amount_usd', op: 'gt', value: 1 }])] }),+ [{ event_type: 'limit_change' }, { event_type: 'spend', usd: 5, created_at: day(1) }]);+ expect(bt.total).toBe(1);+ });+});++describe('syntheticProbes + referencedFields', () => {+ it('returns probes exercised by the same evaluator', () => {+ const doc = normalizePolicyRules({ rules: [block([{ field: 'amount_usd', op: 'gt', value: 50 }])] });+ const probes = syntheticProbes(doc);+ expect(probes.length).toBeGreaterThan(0);+ // A $250 payment must be flagged blocked.+ expect(probes.some((p) => p.denied)).toBe(true);+ });+ it('referencedFields reports the fields a policy reads', () => {+ const doc = normalizePolicyRules({ rules: [block([{ field: 'daily_total_usd', op: 'gt', value: 50 }])] });+ expect([...referencedFields(doc)]).toContain('daily_total_usd');+ });+});diff --git a/tests/wallet-anomaly-guard.test.js b/tests/wallet-anomaly-guard.test.jsnew file mode 100644index 000000000..17f1ca8f6--- /dev/null+++ b/tests/wallet-anomaly-guard.test.js@@ -0,0 +1,128 @@+// Integration-ish tests for api/_lib/anomaly-events.js guardOutboundAnomaly() —+// the live wiring that scores an outbound action, freezes the wallet, records the+// timeline row, and notifies the owner. The DB (sql) and notifier are mocked with+// a content-routed fake so we can assert the real control flow without a database.+//+// Headline: the simulated drain attack — many small payments to a never-seen+// address, staying under the daily USD cap — must FREEZE + RECORD + NOTIFY.++import { describe, it, expect, beforeEach, vi } from 'vitest';++// Content-routed sql mock: returns a shape based on what the query is doing, and+// records every call so tests can assert which side effects fired.+const calls = [];+let velocity = { c1: 1, c10: 1 };+let historyRows = [];++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings) => {+ const q = strings.join(' ');+ calls.push(q.replace(/\s+/g, ' ').trim());+ if (q.includes('SELECT user_id, meta FROM agent_identities')) return [{ user_id: 'owner-1', meta: METphase() }];+ if (q.includes("FILTER (WHERE created_at > now() - interval '1 minute'")) return [{ c1: velocity.c1, c10: velocity.c10 }];+ if (q.includes('SELECT usd, destination, asset, category, created_at')) return historyRows;+ if (q.includes('anomaly_baseline')) return []; // cache write+ if (q.includes("jsonb_build_object") && q.includes('frozen')) return [{ id: 'agent-1' }]; // freeze flipped+ if (q.includes('INSERT INTO agent_custody_events')) return [];+ if (q.includes('INSERT INTO agent_anomaly_events')) return [{ id: '99' }];+ return [];+ }),+}));++const notifySpy = vi.fn(() => ({ id: 'n1' }));+vi.mock('../api/_lib/notify.js', () => ({ insertNotification: (...a) => notifySpy(...a) }));++const { guardOutboundAnomaly } = await import('../api/_lib/anomaly-events.js');++// meta carrying an anomaly config; baseline is recomputed from historyRows.+let _meta = { anomaly: { sensitivity: 'balanced', enabled: true } };+function METphase() { return _meta; }++const KNOWN = 'KNOWNaddr1111111111111111111111111111111';+const NEW = 'NEWaddrZZZZ2222222222222222222222222222222';++function steadyHistory(n) {+ const out = [];+ for (let i = 0; i < n; i++) {+ out.push({ usd: 5, destination: KNOWN, asset: 'USDC', category: 'x402', created_at: `2026-05-${String((i % 27) + 1).padStart(2, '0')}T12:00:00Z` });+ }+ return out;+}++beforeEach(() => {+ calls.length = 0;+ notifySpy.mockClear();+ velocity = { c1: 1, c10: 1 };+ historyRows = steadyHistory(12);+ _meta = { anomaly: { sensitivity: 'balanced', enabled: true } };+});++describe('guardOutboundAnomaly — drain-within-the-cap attack', () => {+ it('freezes, records a flag, and notifies on a velocity-spike drain to a new address', async () => {+ velocity = { c1: 10, c10: 12 }; // burst — leaked-session signature+ const res = await guardOutboundAnomaly({+ agentId: 'agent-1', meta: _meta, category: 'x402', usdValue: 2, destination: NEW,+ asset: 'USDC', network: 'mainnet', selfCounted: true,+ });+ expect(res.decision).toBe('freeze');+ expect(res.message).toMatch(/frozen/i);+ // The wallet freeze flag was flipped …+ expect(calls.some((c) => c.includes('jsonb_build_object') && c.includes('frozen'))).toBe(true);+ // … a timeline flag row was inserted …+ expect(calls.some((c) => c.includes('INSERT INTO agent_anomaly_events'))).toBe(true);+ // … and the owner was notified.+ expect(notifySpy).toHaveBeenCalledTimes(1);+ expect(notifySpy.mock.calls[0][1]).toBe('wallet_anomaly_frozen');+ });+});++describe('guardOutboundAnomaly — normal activity', () => {+ it('allows a normal spend to a known address and does NOT freeze or notify', async () => {+ const res = await guardOutboundAnomaly({+ agentId: 'agent-1', meta: _meta, category: 'x402', usdValue: 5, destination: KNOWN,+ asset: 'USDC', network: 'mainnet', selfCounted: true,+ });+ expect(res.decision).toBe('allow');+ expect(calls.some((c) => c.includes('jsonb_build_object') && c.includes('frozen'))).toBe(false);+ expect(notifySpy).not.toHaveBeenCalled();+ });++ it('is a no-op when the owner disabled the guard', async () => {+ _meta = { anomaly: { enabled: false } };+ velocity = { c1: 30, c10: 50 };+ const res = await guardOutboundAnomaly({ agentId: 'agent-1', meta: _meta, category: 'x402', usdValue: 999, destination: NEW });+ expect(res.decision).toBe('allow');+ expect(notifySpy).not.toHaveBeenCalled();+ });+});++describe('guardOutboundAnomaly — withdraw is never blocked', () => {+ it('scores + records a critical withdraw but returns allow (owner escape hatch)', async () => {+ const res = await guardOutboundAnomaly({+ agentId: 'agent-1', meta: _meta, category: 'withdraw', usdValue: 5000, destination: NEW, asset: 'SOL',+ });+ expect(res.decision).toBe('allow'); // withdraw never frozen+ expect(calls.some((c) => c.includes('jsonb_build_object') && c.includes('frozen'))).toBe(false);+ });+});++describe('guardOutboundAnomaly — fail-safe on internal error', () => {+ it('strict sensitivity freezes when scoring cannot complete (never fails open)', async () => {+ _meta = { anomaly: { sensitivity: 'strict', enabled: true } };+ historyRows = null; // force the baseline recompute path to throw downstream+ // Make the velocity query throw to simulate an IO failure inside the try.+ const dbmod = await import('../api/_lib/db.js');+ dbmod.sql.mockImplementationOnce(async () => { throw new Error('db down'); });+ const res = await guardOutboundAnomaly({ agentId: 'agent-1', userId: 'owner-1', meta: _meta, category: 'x402', usdValue: 10, destination: NEW });+ expect(res.decision).toBe('freeze');+ expect(res.detail?.reason).toBe('scoring_error');+ });++ it('balanced sensitivity allows (records nothing fatal) when scoring errors', async () => {+ _meta = { anomaly: { sensitivity: 'balanced', enabled: true } };+ const dbmod = await import('../api/_lib/db.js');+ dbmod.sql.mockImplementationOnce(async () => { throw new Error('db down'); });+ const res = await guardOutboundAnomaly({ agentId: 'agent-1', userId: 'owner-1', meta: _meta, category: 'x402', usdValue: 10, destination: NEW });+ expect(res.decision).toBe('allow');+ });+});