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
feat(wallet): owner-signed, epoch-bounded spend delegation for agent wallets
nirholas92bb445c2ea7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a93012d8a..e77ec9c16 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **A new wallet linkage score flags a coin's creator buying their own launch**: GET /api/crypto/linkage cross-checks 2-10 Solana addresses for shared control: a 0-100 same-controller score per pair, combining six real on-chain signals by noisy-OR (shared fee payer, one address funding the other, both sharing a first funder, SPL token-account control, direct transfers, a shared funder sending similar amounts in a short window), every match backed by the signature or account that triggered it. It is keyless, free, and part of the public Crypto Data API, and now wired into two places that act on money: the Trade Safety Firewall warns when an early buyer scores as the same controller as a coin's creator (wash-trading dressed up as demand), and copy-trading refuses to size an order behind a leader whose own wallet links to the creator of the coin they are 'signaling', showing the follower exactly why. The same scorer ships as the wallet_linkage tool in the hosted intel MCP server for any AI agent to call directly. (`/crypto-api`) `[feature, security]`- **A read-only drift report for every standalone GitHub mirror**: npm run mirrors:drift compares each of the ~105 standalone mirrors in data/standalone-mirrors.json against its monorepo source at the last synced commit (GitHub API, with a README-timestamp fallback when rate-limited), flags any package whose GitHub copy has diverged, and writes the result to tasks/mirror-drift-<date>.json. It never pushes or mutates a mirror; it is the audit step that found the two fixes above. (`/docs/contributing`) `[infra, docs]`+- **Agents can now carry an owner-signed, offline-verifiable spend cap**: A new Delegation tab in the agent wallet hub lets an owner sign a portable spend delegation with their own linked Solana wallet (a message, never a transaction): 'this agent may move at most CAP lamports per EPOCH, until NOT_AFTER.' The signed envelope is plain text and the verification math is a zero-dependency function any outside counterparty can run themselves (packages/agent-guards, spec in its README) to confirm the authorization without trusting three.ws's say-so. three.ws enforces the same cap server-side on every call through POST /api/agent/guard, measured from the agent wallet's REALIZED spend in the custody ledger rather than the agent's own claim, so an exact-output trade that ends up costing more than advertised still can't slip past the ceiling. A replayed nonce, an expired delegation, or a signature from the wrong wallet is rejected with a specific reason. (`/docs/agent-wallet-api`) `[feature, security]`- **Atomic is now a six-tab Transaction V1 lab, not just an inspector**: /atomic grew five tabs beyond the Inspector, each reachable by click, arrow-key/Home/End tab navigation, or a deep link (?tab=mask, ?tab=sponsor, ?tab=planner, ?tab=diff, ?tab=wallet). The config mask decoder reads a V1 transaction's real TransactionConfigMask u32 and its fixed-width ConfigValues byte by byte, flagging a half-set priority-fee pair or a reserved bit SIMD-0385 has not assigned yet. The sponsor cap view shows a paymaster exactly what it is agreeing to pay, reading V1's inline config instead of a Compute Budget instruction scan that sees nothing on a V1 transaction. The size and budget planner compiles a pasted instruction set with @solana/kit to an exact byte count against legacy, V0, or V1's ceiling, including an exact lamport total for a chosen priority fee. The legacy/V0/V1 diff compiles the same instructions three ways and reports the real byte deltas, honestly, including the case where V1's inline config makes it larger than legacy. The wallet V1 capability check connects the browser's injected wallet and reports the same verdict the rest of three.ws would get from findV1WalletStandardSigner before ever requesting a real V1 signature. Nothing here is estimated: every number comes from compiling and decoding real transactions, and nothing is ever signed, simulated, or broadcast. (`/atomic`) `[feature]`- **Atomic now replays a pump.fun transaction step by step**: Atomic (/atomic) decodes every Pump, PumpSwap, and PumpFees event in a transaction's logs, oldest first, and renders it as a Replay panel: a bonding-curve-position bar, a human-readable description of each step (create, buy/sell, graduation, creator-fee collection and distribution, GitHub social-fee claims, and post-graduation PumpSwap swaps), and the SOL/token amounts that moved. An event the installed SDK does not recognize still renders, labeled unrecognized, instead of silently disappearing. For a create transaction, the panel also pages through the earliest trades on that mint since launch, walking Solana's signature history backward in bounded pages since RPC has no forward cursor. `[feature]`- **Creator earnings now cross-check two independent pump.fun sources**: A coin's earnings figure on /launches/<mint> and in the agent earnings card used to come from one source only: the creator wallet's lifetime fee index. It now also sums that specific coin's own pump.fun distribution timeline, the only feed that can say which coin actually paid a wallet, and shows both: 'this coin paid X SOL' next to the wallet-level figure, plus a plain sentence when the two sources disagree and by how much. Nothing is hidden when sources drift apart; the gap is the point. The snapshot pipeline that already indexed wallet-level fees now reconciles against the timeline for every coin on each refresh. (`/launches`) `[feature]`diff --git a/api/_lib/agent-spend-delegation.js b/api/_lib/agent-spend-delegation.jsnew file mode 100644index 000000000..9cb2fc5a2--- /dev/null+++ b/api/_lib/agent-spend-delegation.js@@ -0,0 +1,187 @@+// Owner-signed, epoch-bounded spend delegations: server-side store ++// enforcement. See packages/agent-guards/src/delegation.js for the canonical+// message format and the offline-verifiable signature spec; this module is+// the platform's own copy of that same arithmetic, run against the REAL+// realized-spend ledger (agent_custody_events) rather than a caller's claim.+//+// Lifecycle:+// 1. The owner signs { agent, owner, cap_lamports_per_epoch, epoch_seconds,+// not_after, nonce } with their linked Solana wallet (a message, never+// a transaction) and submits { delegation, signature }.+// 2. registerDelegation verifies the signature, verifies `owner` really is+// the agent's linked owner wallet, and stores it. A replayed nonce+// (same agent + nonce already on file, whatever its current status) is+// rejected: a captured signed envelope can never be resubmitted to+// reset the epoch counter or extend an authorization past what was+// actually signed.+// 3. checkDelegationSpend runs on every subsequent proposed spend for that+// agent: it sums REALIZED spend from agent_custody_events over the+// trailing `epoch_seconds` window (the same ledger `updateCustodyEvent`+// corrects to the post-settlement realized amount for exact-output+// trades) and rejects a debit that would push the rolling total past+// the signed cap.+//+// No delegation on file for an agent is not a block: the feature is+// owner-opt-in, exactly like every other cap in agent-trade-guards.js.++import { sql } from './db.js';+import { verifyDelegationSignature, checkDelegationCap } from '../../packages/agent-guards/src/delegation.js';+import { getDailySpendLamports } from './agent-trade-guards.js';+import { logAudit } from './audit.js';++const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++export class DelegationError extends Error {+ constructor(code, message, extra = {}) {+ super(message);+ this.code = code;+ this.extra = extra;+ }+}++/**+ * Look up the Solana wallet the agent's owner has linked to their account.+ * This is the ONLY address a delegation for this agent may claim as `owner`.+ * That is what makes the endpoint safe to expose without a session: forgery+ * is prevented by the Ed25519 signature check, not by auth on the request.+ */+async function ownerWalletFor(agentId) {+ const [agent] = await sql`+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return null;+ const [wallet] = await sql`+ SELECT address FROM user_wallets+ WHERE user_id = ${agent.user_id} AND chain_type = 'solana'+ ORDER BY is_primary DESC, created_at ASC+ LIMIT 1+ `;+ return wallet?.address ?? null;+}++/**+ * Verify + store a signed delegation envelope. Returns the stored row on+ * success; throws DelegationError with a specific `code` on every rejection+ * path (wrong signer, expired, replayed nonce, unknown agent).+ */+export async function registerDelegation({ agentId, delegation, signature }) {+ if (!delegation || typeof delegation !== 'object') {+ throw new DelegationError('invalid_delegation', 'delegation must be an object.');+ }+ const nonce = typeof delegation.nonce === 'string' ? delegation.nonce.trim().slice(0, 200) : '';+ if (!nonce) throw new DelegationError('invalid_delegation', 'delegation.nonce is required.');++ const owner = typeof delegation.owner === 'string' ? delegation.owner.trim() : '';+ if (!SOLANA_ADDRESS_RE.test(owner)) {+ throw new DelegationError('invalid_delegation', 'delegation.owner must be a base58 Solana address.');+ }++ const capLamports = BigInt(delegation.cap_lamports_per_epoch ?? 0);+ const epochSeconds = Number(delegation.epoch_seconds);+ const notAfterSec = Number(delegation.not_after);+ if (capLamports <= 0n) throw new DelegationError('invalid_delegation', 'cap_lamports_per_epoch must be positive.');+ if (!Number.isFinite(epochSeconds) || epochSeconds <= 0) {+ throw new DelegationError('invalid_delegation', 'epoch_seconds must be a positive number.');+ }+ if (!Number.isFinite(notAfterSec)) throw new DelegationError('invalid_delegation', 'not_after must be a unix timestamp (seconds).');+ if (notAfterSec <= Math.floor(Date.now() / 1000)) {+ throw new DelegationError('expired_delegation', 'This delegation is already expired (not_after is in the past).');+ }++ const ownerWallet = await ownerWalletFor(agentId);+ if (!ownerWallet) {+ throw new DelegationError('agent_not_found', 'That agent has no linked owner wallet to delegate from.');+ }+ if (ownerWallet !== owner) {+ throw new DelegationError('wrong_signer', "delegation.owner does not match this agent's linked owner wallet.");+ }++ let sigOk = false;+ try {+ sigOk = verifyDelegationSignature({ ...delegation, agent: agentId, owner, nonce }, signature);+ } catch {+ sigOk = false;+ }+ if (!sigOk) {+ throw new DelegationError('wrong_signer', 'Signature does not verify against the claimed owner wallet.');+ }++ let row;+ try {+ [row] = await sql`+ INSERT INTO agent_spend_delegations+ (agent_id, owner_wallet, cap_lamports_per_epoch, epoch_seconds, not_after, nonce, signature)+ VALUES (+ ${agentId}, ${owner}, ${capLamports.toString()}, ${Math.round(epochSeconds)},+ to_timestamp(${notAfterSec}), ${nonce}, ${signature}+ )+ RETURNING id, agent_id, owner_wallet, cap_lamports_per_epoch, epoch_seconds, not_after, nonce, status, created_at+ `;+ } catch (e) {+ if (String(e?.message || '').includes('agent_spend_delegations_nonce_unique')) {+ throw new DelegationError('replayed_nonce', 'This delegation nonce has already been used for this agent.');+ }+ throw e;+ }++ logAudit({+ userId: null,+ action: 'agent.spend_delegation.registered',+ resourceId: agentId,+ meta: { delegationId: row.id, capLamportsPerEpoch: capLamports.toString(), epochSeconds, notAfter: row.not_after },+ });++ return row;+}++/**+ * The current delegation on file for an agent (not revoked), or null. This+ * deliberately does NOT filter on `not_after > now()`: a time-expired+ * delegation must still be returned so checkDelegationSpend's cap check sees+ * it and rejects with DELEGATION_EXPIRED, rather than it silently looking+ * like "no delegation" once its clock runs out.+ */+export async function getActiveDelegation(agentId) {+ const [row] = await sql`+ SELECT id, agent_id, owner_wallet, cap_lamports_per_epoch, epoch_seconds, not_after, nonce, status, created_at+ FROM agent_spend_delegations+ WHERE agent_id = ${agentId} AND status = 'active'+ ORDER BY created_at DESC+ LIMIT 1+ `;+ return row || null;+}++/**+ * Check a proposed debit (lamports) against the agent's active delegation,+ * if any. Realized epoch spend is read straight from agent_custody_events,+ * the same ledger every custody path (trade/snipe/x402/withdraw) writes and+ * corrects to the post-settlement realized amount, never from the caller's+ * own claim about what the action will cost.+ *+ * Returns { gated: false } when no delegation is on file (opt-in cap, not a+ * default restriction). Returns { gated: true, allow, code, reason, detail }+ * when a delegation IS on file and was evaluated.+ */+export async function checkDelegationSpend({ agentId, debitLamports, network = 'mainnet' }) {+ const delegation = await getActiveDelegation(agentId);+ if (!delegation) return { gated: false };++ const epochHours = Number(delegation.epoch_seconds) / 3600;+ const epochSpentLamports = await getDailySpendLamports(agentId, network, epochHours);++ const result = checkDelegationCap({+ delegation: {+ agent: delegation.agent_id,+ owner: delegation.owner_wallet,+ cap_lamports_per_epoch: delegation.cap_lamports_per_epoch,+ epoch_seconds: delegation.epoch_seconds,+ not_after: Math.floor(new Date(delegation.not_after).getTime() / 1000),+ nonce: delegation.nonce,+ },+ epochSpentLamports,+ debitLamports: BigInt(debitLamports ?? 0),+ });++ return { gated: true, delegation, epochSpentLamports, ...result };+}diff --git a/api/_lib/migrations/20261014140000_agent_spend_delegations.sql b/api/_lib/migrations/20261014140000_agent_spend_delegations.sqlnew file mode 100644index 000000000..159eb6a4f--- /dev/null+++ b/api/_lib/migrations/20261014140000_agent_spend_delegations.sql@@ -0,0 +1,48 @@+-- Owner-signed, epoch-bounded spend delegations (work order 515-integrate-16).+-- A delegation is an Ed25519 signature, over a fixed-field plain-text message+-- (see packages/agent-guards/src/delegation.js), by the agent's OWNER wallet,+-- authorizing at most `cap_lamports_per_epoch` of realized spend per rolling+-- `epoch_seconds` window, until `not_after`. Anyone (not just three.ws) can+-- verify the signature offline; the platform additionally enforces the cap+-- server-side against the agent's real, realized spend ledger+-- (agent_custody_events), never the caller's self-reported notional.+--+-- `nonce` is unique per agent FOREVER (not just while "active"): once a+-- delegation has been registered, replaying the exact same signed envelope+-- (same nonce) is rejected, even after it expires or is superseded. That is+-- what stops a captured-off-the-wire delegation from being re-submitted to+-- reset bookkeeping or re-arm a lapsed authorization.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261014140000_agent_spend_delegations.sql+-- Idempotent.++begin;++create table if not exists agent_spend_delegations (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ owner_wallet text not null,+ cap_lamports_per_epoch bigint not null,+ epoch_seconds integer not null,+ not_after timestamptz not null,+ nonce text not null,+ signature text not null,+ status text not null default 'active',+ created_at timestamptz not null default now(),+ revoked_at timestamptz,++ constraint agent_spend_delegations_nonce_unique unique (agent_id, nonce),+ constraint agent_spend_delegations_cap_check check (cap_lamports_per_epoch > 0),+ constraint agent_spend_delegations_epoch_check check (epoch_seconds > 0),+ constraint agent_spend_delegations_owner_wallet_check check (char_length(owner_wallet) between 32 and 44),+ constraint agent_spend_delegations_status_check check (status in ('active', 'revoked', 'expired'))+);++-- The active delegation for an agent is "the most recent row with status =+-- 'active' and not_after in the future", read with ORDER BY created_at DESC+-- LIMIT 1. This partial index keeps that lookup cheap without needing a+-- separate "is_current" flag to keep in sync.+create index if not exists idx_spend_delegations_agent_active+ on agent_spend_delegations(agent_id, created_at desc)+ where status = 'active';++commit;diff --git a/api/agent/guard.js b/api/agent/guard.jsindex 91f56e627..8769994f0 100644--- a/api/agent/guard.js+++ b/api/agent/guard.js@@ -16,14 +16,28 @@// no secrets and no state, and its whole job is to be reachable from an// anonymous BYOK chat session. Rate-limited per IP like the other open// compute endpoints.+//+// On top of the seven layers sits an eighth, opt-in one: an owner-signed+// spend delegation (packages/agent-guards/src/delegation.js). This same+// endpoint accepts `{ agentId, delegation, delegationSignature }` to verify+// and store a newly signed delegation, and folds a cap check for the active+// delegation (if any) into every call's verdict, measured from the agent's+// REALIZED spend ledger, never the caller's claimed notional.import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { solUsdPrice } from '../_lib/avatar-wallet.js';import { GuardChain, SpendGuard, TradeGuard, createX402Hook } from '@three-ws/agent-runtime';+import { registerDelegation, checkDelegationSpend, DelegationError } from '../_lib/agent-spend-delegation.js';const MAX_CALLS = 20;const SOL_MINT = 'So11111111111111111111111111111111111111112';+const LAMPORTS_PER_SOL = 1_000_000_000n;+// agent_spend_delegations.agent_id is a uuid column; this anonymous endpoint+// takes agentId as free-form caller input, so a non-uuid value must be+// rejected before it ever reaches a query, not surfaced as a DB error.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const isUuid = (v) => typeof v === 'string' && UUID_RE.test(v);// Resolve the USD notional server-side where the call shape makes it// unambiguous (the GuardChain's own guidance: the guard never prices token@@ -49,6 +63,21 @@ function solAmountOf(call) {}}+// Lamports a call would actually debit from the agent's own wallet, for+// checking against a signed spend delegation. Prefers the SOL-denominated+// amount resolved above; falls back to converting a resolved USD notional at+// the same SOL/USD price already fetched for the batch. A call whose cost+// can't be resolved in lamports is not gated by delegation (nothing to+// measure against), same as any other unresolved-notional blind spot.+function debitLamportsOf(call, solUsd) {+ const sol = solAmountOf(call);+ if (Number.isFinite(sol) && sol > 0) return BigInt(Math.round(sol * Number(LAMPORTS_PER_SOL)));+ if (Number.isFinite(call.valueUsd) && call.valueUsd > 0 && solUsd) {+ return BigInt(Math.round((call.valueUsd / solUsd) * Number(LAMPORTS_PER_SOL)));+ }+ return undefined;+}+// One TradeGuard serves every request: it is stateless and its registries are// module-level. SpendGuard instances are per-request because the envelope// (caps, firewall) is caller-supplied.@@ -93,7 +122,43 @@ export default wrap(async function handler(req, res) {const rawCalls = Array.isArray(body?.calls) ? body.calls : body?.call ? [body.call] : [];const calls = rawCalls.map(sanitizeCall).filter(Boolean);++ // A request may register a new owner-signed delegation, preflight calls+ // against the agent's existing one, or both in the same round trip (sign,+ // then immediately check the next proposed call against the cap just set).+ let delegationRegistration;+ if (body.delegation && typeof body.delegation === 'object') {+ const agentIdForDelegation = typeof body.agentId === 'string' ? body.agentId.slice(0, 200) : '';+ const signature = typeof body.delegationSignature === 'string' ? body.delegationSignature : '';+ if (!agentIdForDelegation) {+ return error(res, 400, 'missing_agent_id', 'Registering a delegation requires `agentId`.');+ }+ if (!signature) {+ return error(res, 400, 'missing_signature', 'Registering a delegation requires `delegationSignature`.');+ }+ if (!isUuid(agentIdForDelegation)) {+ return error(res, 400, 'invalid_agent_id', 'agentId must be a uuid.');+ }+ try {+ const row = await registerDelegation({ agentId: agentIdForDelegation, delegation: body.delegation, signature });+ delegationRegistration = {+ ok: true,+ id: row.id,+ capLamportsPerEpoch: row.cap_lamports_per_epoch,+ epochSeconds: row.epoch_seconds,+ notAfter: row.not_after,+ };+ } catch (err) {+ if (err instanceof DelegationError) {+ delegationRegistration = { ok: false, code: err.code, message: err.message };+ } else {+ throw err;+ }+ }+ }+if (calls.length === 0) {+ if (delegationRegistration) return json(res, 200, { engine: '@three-ws/agent-runtime', verdicts: [], delegationRegistration });return error(res, 400, 'no_calls', 'Provide `calls: [{ identifier, apiName, arguments }]`.');}if (calls.length > MAX_CALLS) {@@ -180,8 +245,37 @@ export default wrap(async function handler(req, res) {valueUsd: call.valueUsd,x402: call.x402,});- verdicts.push({ apiName: call.apiName, identifier: call.identifier, verdict });++ // A signed spend delegation is an additional, owner-opted-in layer on+ // top of the seven in the chain: it can only tighten a verdict (turn an+ // allow into a block), never loosen one the chain already blocked. The+ // chain's own layers/blindSpots/warnings are left intact for diagnosis.+ let delegation;+ if (isUuid(agentId)) {+ const debitLamports = debitLamportsOf(call, solUsd);+ if (debitLamports !== undefined) {+ const result = await checkDelegationSpend({ agentId, debitLamports, network: body.network || 'mainnet' });+ if (result.gated) {+ delegation = {+ allow: result.allow,+ code: result.code,+ reason: result.reason,+ detail: result.detail,+ };+ if (!result.allow && verdict.decision !== 'block') {+ verdict.decision = 'block';+ verdict.blockedBy = 'spend_delegation';+ verdict.code = result.code;+ verdict.reason = result.reason;+ }+ }+ }+ }++ verdicts.push({ apiName: call.apiName, identifier: call.identifier, verdict, delegation });}- return json(res, 200, { engine: '@three-ws/agent-runtime', verdicts });+ const payload = { engine: '@three-ws/agent-runtime', verdicts };+ if (delegationRegistration) payload.delegationRegistration = delegationRegistration;+ return json(res, 200, payload);});diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex 03ef7db54..61825d631 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -42,6 +42,7 @@ import {describePolicyRules, backtestPolicy, syntheticProbes, normalizePolicyRules, MAX_RULES,} from '../_lib/spend-policy-rules.js';import { compilePolicyFromText } from '../_lib/spend-policy-compiler.js';+import { registerDelegation, getActiveDelegation, DelegationError } from '../_lib/agent-spend-delegation.js';// SOL-outflow spend policy enforced on agent-signed launches/buys/swaps. Exposed// read-only on the limits GET so the launch console can show the real ceiling.import { resolveSpendPolicy } from '../_lib/agent-spend-policy.js';@@ -1343,6 +1344,59 @@ async function handlePolicy(req, res, id) {return json(res, 200, { data: { policy: saved, readback: describePolicyRules(saved), backtest } });}+// ── signed spend delegation ────────────────────────────────────────────────────+// Owner-only. The owner's cap here is a SIGNATURE, not a session write: the+// browser prompts the owner's own wallet (Wallet Standard `solana:signMessage`,+// never a transaction) for the exact bytes `delegationMessage` builds, and this+// endpoint stores the result after re-verifying it (api/_lib/agent-spend-delegation.js).+// The owner session gate below is a convenience for this surface, not the real+// security boundary: that is the Ed25519 check, so the exact same delegation+// can also be registered through the anonymous POST /api/agent/guard.+//+// GET /delegation the active delegation on file (or null)+// POST /delegation { delegation, delegationSignature } verify + store a newly signed one+const DELEGATION_ERROR_STATUS = {+ invalid_delegation: 400,+ expired_delegation: 400,+ agent_not_found: 404,+ wrong_signer: 403,+ replayed_nonce: 409,+};+async function handleDelegation(req, res, id) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const owned = await loadOwnedWallet(req, res, id);+ if (owned.error) return;+ const { auth } = owned;++ const rl = await limits.walletRead(auth.userId);+ if (!rl.success) return rateLimited(res, rl);++ if (req.method === 'GET') {+ const active = await getActiveDelegation(id);+ return json(res, 200, { data: { delegation: active } });+ }++ // POST: the owner already signed in their wallet; this just verifies + stores.+ if (!(await requireCsrf(req, res, auth.userId))) return;+ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');+ }+ try {+ const row = await registerDelegation({ agentId: id, delegation: body?.delegation, signature: body?.delegationSignature });+ return json(res, 200, { data: { delegation: row } });+ } catch (e) {+ if (e instanceof DelegationError) {+ return error(res, DELEGATION_ERROR_STATUS[e.code] || 400, e.code, e.message);+ }+ throw e;+ }+}+// ── vanity grind + custodial swap ──────────────────────────────────────────────// GET /api/agents/:id/solana/vanity — owner-only current vanity status.// POST /api/agents/:id/solana/vanity — owner-only: grind a vanity keypair@@ -2681,6 +2735,7 @@ export default async function handler(req, res, id, action) {return mod.handleGuard(req, res, id);}if (action === 'policy') return handlePolicy(req, res, id);+ if (action === 'delegation') return handleDelegation(req, res, id);if (action === 'tip') return handleTip(req, res, id);if (action === 'royalty') return handleRoyalty(req, res, id);if (action === 'stream') return handleStream(req, res, id);diff --git a/data/changelog.json b/data/changelog.jsonindex 0b290390f..565ccb418 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-14",+ "title": "Agents can now carry an owner-signed, offline-verifiable spend cap",+ "summary": "A new Delegation tab in the agent wallet hub lets an owner sign a portable spend delegation with their own linked Solana wallet (a message, never a transaction): 'this agent may move at most CAP lamports per EPOCH, until NOT_AFTER.' The signed envelope is plain text and the verification math is a zero-dependency function any outside counterparty can run themselves (packages/agent-guards, spec in its README) to confirm the authorization without trusting three.ws's say-so. three.ws enforces the same cap server-side on every call through POST /api/agent/guard, measured from the agent wallet's REALIZED spend in the custody ledger rather than the agent's own claim, so an exact-output trade that ends up costing more than advertised still can't slip past the ceiling. A replayed nonce, an expired delegation, or a signature from the wrong wallet is rejected with a specific reason.",+ "tags": [+ "feature",+ "security"+ ],+ "link": "/docs/agent-wallet-api"+ },{"date": "2026-10-14","title": "The pre-push guard now catches a leaked Solana secret key, and withdrawals warn before a sweeper bot drains them",diff --git a/docs/agent-wallet-api.md b/docs/agent-wallet-api.mdindex 0e7f39f6a..5d17f1cb2 100644--- a/docs/agent-wallet-api.md+++ b/docs/agent-wallet-api.md@@ -1,6 +1,6 @@# Agent wallet control API-Every three.ws agent owns one custodial **Solana** wallet. Seven owner-only HTTP surfaces hang off it, and this is their developer reference: exact routes, exact request and response JSON, exact error codes, and a working curl call for each.+Every three.ws agent owns one custodial **Solana** wallet. Eight owner-only HTTP surfaces hang off it, and this is their developer reference: exact routes, exact request and response JSON, exact error codes, and a working curl call for each.This document is the API reference the surrounding docs deliberately leave out. Read those first for the "why":@@ -12,7 +12,7 @@ This document is the API reference the surrounding docs deliberately leave out.## Orientation-All seven surfaces address the same custodial Solana keypair, obey the same owner gate, and are clamped by the same spend policy. None of them can widen authority: each one either reads the wallet, or narrows and schedules what the wallet is already allowed to do.+All eight surfaces address the same custodial Solana keypair, obey the same owner gate, and are clamped by the same spend policy. None of them can widen authority: each one either reads the wallet, or narrows and schedules what the wallet is already allowed to do.| Surface | Route root | What it controls ||---|---|---|@@ -23,6 +23,7 @@ All seven surfaces address the same custodial Solana keypair, obey the same owne| Portfolio | `/api/agents/:id/portfolio` | FIFO cost basis, realized and unrealized P&L by source, live risk metrics || Recovery | `/api/agents/:id/recovery` | Guardians, approval threshold, dead-man check-in, inheritance || Solana guard | `/api/agents/:id/solana/guard` | The behavioral anomaly baseline, its sensitivity, and freeze adjudication |+| Spend delegation | `/api/agents/:id/solana/delegation` | The owner-signed, epoch-bounded spend cap verified against realized ledger spend |The shared model, in one paragraph. A caller is resolved to a user id from either a session cookie or a bearer token. That user must own the agent, or the surface refuses (recovery is the one exception: guardians and the beneficiary get a scoped view). Every mutation is CSRF-gated for cookie callers. Anything that can move funds runs through the shared spend guards in [`api/_lib/agent-trade-guards.js`](../api/_lib/agent-trade-guards.js), so the wallet-wide policy (`per_tx_usd`, `daily_usd`, `per_counterparty_daily_usd`, `withdraw_allowlist` (the [destination whitelist](./destination-whitelist.md), edited through `/api/wallet-whitelist`), `frozen`, `require_capabilities`) is enforced at the signing boundary, not per feature. A scheduled order, an armed intent, an autopilot rule, and an autonomous agent-to-agent payment are therefore all subject to the same ceilings and the same freeze as a manual trade. That enforcement fails closed on its inputs: a caller that hands the guard neither a pre-read policy nor the agent's meta gets the agent's real policy read from its row, and a spend for an agent that no longer exists is refused rather than defaulted to an unrestricted wallet. See [autonomous agent-to-agent payments](./a2a-payments.md) for the policy fields, the kill switch, and the receipts they leave behind.@@ -1207,6 +1208,49 @@ curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/solana/guard" \-d '{"action":"approve","event_id":"4417"}'```+## Signed spend delegation: a portable, offline-verifiable cap++Source: [`api/_lib/agent-spend-delegation.js`](../api/_lib/agent-spend-delegation.js), dispatched from [`api/agents/solana-wallet.js`](../api/agents/solana-wallet.js). Canonical format, message builder, and the zero-dependency verify/cap math: [`packages/agent-guards/src/delegation.js`](../packages/agent-guards/src/delegation.js) (full spec in that package's [README](../packages/agent-guards/README.md#spec-signed-spend-delegation)). Owner-facing UI: the Delegation tab in the agent wallet hub ([`src/agent-wallet-hub/tabs/delegation.js`](../src/agent-wallet-hub/tabs/delegation.js)).++A delegation is a statement the owner signs with their own linked Solana wallet, never a transaction: *"agent X may move at most CAP lamports per EPOCH_SECONDS, until NOT_AFTER."* Unlike every other control on this page, it is not three.ws-specific: the signed envelope is plain text, and `verifyDelegationSignature` is a ~100-line, dependency-free function any counterparty can run themselves to confirm the authorization without trusting three.ws's say-so. three.ws also enforces the same cap server-side, on every preflight through [`POST /api/agent/guard`](#preflight-guard-enforcement), measured from the agent wallet's REALIZED spend in `agent_custody_events` rather than the agent's own claim about what an action will cost, so an exact-output trade that ends up costing more than advertised still cannot slip past the ceiling.++| Method | Route | Purpose |+|---|---|---|+| `GET` | `/solana/delegation` | The current delegation on file (any status), or `null` |+| `POST` | `/solana/delegation` | Verify and store a delegation the owner already signed in their wallet |++Both are owner-gated and rate-limited; `POST` is CSRF-gated. This route is a convenience layer for the owner-facing UI, not the security boundary: the real authorization check is the Ed25519 signature, which is why the lower-level preflight endpoint below can accept the same envelope anonymously.++### GET /solana/delegation++```json+{ "data": { "delegation": {+ "id": "…", "agent_id": "…", "owner_wallet": "7Xy…",+ "cap_lamports_per_epoch": "500000000", "epoch_seconds": 86400,+ "not_after": "2026-11-13T00:00:00.000Z", "nonce": "a1b2c3…",+ "status": "active", "created_at": "2026-10-14T18:00:00.000Z"+} } }+```++`delegation` is `null` when none is on file. Note that a time-expired row is still returned (its `not_after` is simply in the past) rather than disappearing: a delegation that lapsed is a fact the owner should see, not silence.++### POST /solana/delegation++Body: `{ "delegation": { "agent", "owner", "cap_lamports_per_epoch", "epoch_seconds", "not_after", "nonce" }, "delegationSignature": "<base58 or base64>" }`. Every delegation field is carried as a decimal string; see the package README for the exact canonical message those six fields serialize to before signing.++```bash+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/solana/delegation" \+ -H "authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{"delegation":{"agent":"'"$AGENT_ID"'","owner":"7Xy…","cap_lamports_per_epoch":"500000000","epoch_seconds":"86400","not_after":"1794700800","nonce":"a1b2c3d4"},"delegationSignature":"base64sig…"}'+```++Rejections are specific, each a `DelegationError` code: `invalid_delegation` (malformed field), `expired_delegation` (`not_after` already in the past), `agent_not_found` (no owner wallet linked to this agent), `wrong_signer` (the signature does not verify against the agent's linked owner wallet), `replayed_nonce` (this exact `agent_id` + `nonce` pair was already registered, whatever its current status). A nonce is permanently retired on first use: a captured signed envelope can never be resubmitted to reset the epoch counter or re-extend an authorization past what was actually signed.++### Preflight guard enforcement++[`POST /api/agent/guard`](../api/agent/guard.js) is the one endpoint that actually enforces a delegation's cap. It accepts the same `{ delegation, delegationSignature }` pair inline (registering or re-registering before evaluating `calls`) and, for every proposed call, resolves the call's lamport cost and rejects with `blockedBy: "spend_delegation"` and `code: "DELEGATION_CAP_EXCEEDED"` or `"DELEGATION_EXPIRED"` when the active delegation would be breached. The delegation layer only ever *tightens* an `allow` into a `block`; if the guard's seven existing layers already blocked the call for another reason, the delegation check never runs or overrides it.+## Related- [Agent wallets](agent-wallets.md) for the wallet itself: creation, key custody, and the five spend paths.diff --git a/docs/agent-wallets.md b/docs/agent-wallets.mdindex a8e527851..667bcb5f9 100644--- a/docs/agent-wallets.md+++ b/docs/agent-wallets.md@@ -55,7 +55,7 @@ Two asymmetries are deliberate:Coin-launch and bonding-curve activity carries an additional SOL-denominated policy (`max_sol_per_tx`, `daily_sol_cap`, an optional `allowed_mints` allowlist). A freshly provisioned agent that has never been configured defaults to **1 SOL per transaction and 5 SOL per rolling day**, so a stolen session token cannot drain it.-On top of the numeric caps sit two additive layers, each of which can only ever *narrow* a spend, never widen it: [natural-language spend rules](financial-controls.md) that an LLM authors and deterministic code enforces, and a behavioral anomaly guard that freezes the wallet when a spend doesn't look like the agent's normal behavior.+On top of the numeric caps sit three additive layers, each of which can only ever *narrow* a spend, never widen it: [natural-language spend rules](financial-controls.md) that an LLM authors and deterministic code enforces, a behavioral anomaly guard that freezes the wallet when a spend doesn't look like the agent's normal behavior, and an owner-signed, epoch-bounded [spend delegation](agent-wallet-api.md#signed-spend-delegation-a-portable-offline-verifiable-cap) that any outside counterparty can verify offline, enforced against the wallet's realized ledger spend rather than a self-reported amount.### The audit trail@@ -63,7 +63,7 @@ Every spend writes a row to the custody event ledger — amount, USD value, dest## Where owners manage it-The **Agent Wallet Hub** lives at `/agent/:id/wallet`. Owners see all 23 sections; a visitor to a public agent page sees a read-only view: Balance, Deposit, Trust, Trade, and Pulse. Everything a visitor sees is public on-chain data, so the balance a visitor reads is the same live figure the owner reads. The transaction feed is the exception: it is owner-only server-side, so the visitor's Balance tab says so and links to the block explorer instead. A network selector switches every read and write between mainnet and devnet.+The **Agent Wallet Hub** lives at `/agent/:id/wallet`. Owners see all 26 sections; a visitor to a public agent page sees a read-only view: Balance, Deposit, Trust, Trade, and Pulse. Everything a visitor sees is public on-chain data, so the balance a visitor reads is the same live figure the owner reads. The transaction feed is the exception: it is owner-only server-side, so the visitor's Balance tab says so and links to the block explorer instead. A network selector switches every read and write between mainnet and devnet.`/agent-wallet` is the same hub reached without naming an agent. It resolves the signed-in owner's agents: one agent opens its hub directly, several render a picker, none offers a route to create the first one, and a signed-out visitor is asked to sign in.@@ -76,6 +76,7 @@ Key endpoints:- `GET`/`PUT /api/agents/:id/solana/limits`: read and set the spend policy- `POST /api/agents/:id/solana/withdraw`: sweep an asset out- `GET /api/agents/:id/solana/guard` — anomaly guard state and flagged activity+- `GET`/`POST /api/agents/:id/solana/delegation`: read, or verify-and-store, an owner-signed [spend delegation](agent-wallet-api.md#signed-spend-delegation-a-portable-offline-verifiable-cap)Full request/response shapes are in the [REST API reference](api-reference.md).diff --git a/packages/agent-guards/README.md b/packages/agent-guards/README.mdindex 3c7d33c6c..6b7a35804 100644--- a/packages/agent-guards/README.md+++ b/packages/agent-guards/README.md@@ -18,6 +18,7 @@<a href="#quick-start">Quick start</a> ·<a href="#api">API</a> ·<a href="#how-it-works">How it works</a> ·+ <a href="#spec-signed-spend-delegation">Signed spend delegation</a> ·<a href="https://three.ws">three.ws</a></p>@@ -285,6 +286,121 @@ message — never a thrown 500. `checkTrade` surfaces these on `decision.reason``{ spent_lamports, amount_lamports, budget_lamports }` — so a UI can render theexact overage without re-deriving it.+## Spec: signed spend delegation++Every cap above is **configuration**: the owner sets a number through the API,+and the platform trusts whoever is authenticated as that owner to have set it.+A signed spend delegation is the stronger, portable form of the same idea: the+owner signs a cap with their own wallet (a message, never a transaction), and+the signature itself is the authorization. Anyone, not just three.ws, can+verify it offline; the platform additionally enforces it against the agent's+*realized* spend, never a caller's claim.++### Format++```ts+interface SpendDelegation {+ agent: string; // the agent's id+ owner: string; // owner's base58 Solana address+ cap_lamports_per_epoch: string | number; // max realized spend per epoch+ epoch_seconds: string | number; // rolling window length+ not_after: string | number; // unix seconds; the delegation's hard expiry+ nonce: string; // unique per (agent, nonce) forever+}+```++### Canonical message++`delegationMessage(delegation)` serializes the six fields above, in this exact+order, one per line, under a fixed domain-separation header so a signature+can never be replayed against a different protocol that happens to share a+field name:++```+three.ws/agent-spend-delegation/v1+agent: <agent>+owner: <owner>+cap_lamports_per_epoch: <cap_lamports_per_epoch>+epoch_seconds: <epoch_seconds>+not_after: <not_after>+nonce: <nonce>+```++The owner signs exactly these bytes with their wallet's `signMessage` (the+Wallet Standard `solana:signMessage` feature, supported by every major+Solana wallet). The result is a base64 Ed25519 signature over the message.++### Verification++```js+import { delegationMessage, verifyDelegationSignature, checkDelegationCap } from '@three-ws/agent-guards';++const ok = verifyDelegationSignature(delegation, signatureBase64);+// true only if `signatureBase64` is a valid Ed25519 signature, by the+// keypair for `delegation.owner`, over delegationMessage(delegation).+```++`verifyDelegationSignature` has zero dependencies: it decodes the base58+owner address itself and verifies with Node's built-in `node:crypto`, so any+JS runtime can check a delegation offline without pulling in a Solana SDK.++### Cap check++```js+const result = checkDelegationCap({+ delegation,+ epochSpentLamports, // realized spend already incurred this epoch+ debitLamports, // the proposed action's cost+});+// { allow: false, code: 'DELEGATION_CAP_EXCEEDED', reason, detail } or+// { allow: false, code: 'DELEGATION_EXPIRED', reason } or+// { allow: true, code: 'OK', reason: null }+```++`epochSpentLamports` must come from the **realized** ledger (post-settlement+actuals), not the sum of what the agent *intended* to spend: an exact-output+trade that settles for more than quoted must still be caught. On the+platform, that ledger is `agent_custody_events`; `checkDelegationCap` itself+is venue-agnostic and takes the number as an argument.++### Enforcement on three.ws++`POST /api/agent/guard` both registers a delegation and enforces the active+one against every proposed call in the same request:++```js+// Register (the owner has just signed `delegation` in their wallet):+await fetch('https://three.ws/api/agent/guard', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId, delegation, delegationSignature }),+});+// → { delegationRegistration: { ok: true, id, capLamportsPerEpoch, epochSeconds, notAfter } }++// Preflight a call against it:+await fetch('https://three.ws/api/agent/guard', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId, calls: [{ identifier: 'solana_transfer', arguments: { token: 'SOL', amount: 0.3 } }] }),+});+// → { verdicts: [{ verdict, delegation: { allow, code, reason, detail } }] }+```++A nonce is unique per agent **forever** (a Postgres unique constraint, not a+time window): once registered, resubmitting the exact same signed envelope is+rejected as `replayed_nonce`, even long after it expires or is superseded.+Registration also verifies `delegation.owner` really is that agent's linked+owner wallet (not just any valid signature): a delegation can only ever be+signed by the account that actually owns the agent.++| Export | Purpose |+|---|---|+| `DELEGATION_DOMAIN` | The fixed first line of every delegation message (`three.ws/agent-spend-delegation/v1`). |+| `canonicalDelegationFields(delegation)` | Validate + stringify the six required fields. Throws `TypeError` if any is missing. |+| `delegationMessage(delegation)` | The exact UTF-8 bytes the owner signs. |+| `verifyDelegationSignature(delegation, signature)` | `true`/`false`. Zero dependencies. |+| `checkDelegationCap({ delegation, nowSec?, epochSpentLamports, debitLamports })` | The enforcement decision: `{ allow, code, reason, detail }`. |+## Examples**Provision a new agent with conservative rails** before handing it a key:diff --git a/packages/agent-guards/src/delegation.js b/packages/agent-guards/src/delegation.jsnew file mode 100644index 000000000..b25331e43--- /dev/null+++ b/packages/agent-guards/src/delegation.js@@ -0,0 +1,159 @@+// Signed, epoch-bounded spend delegation: a portable, auditable owner+// authorization: "agent X may move at most CAP lamports per EPOCH_SECONDS,+// until NOT_AFTER." The owner signs this statement with their own wallet+// (a Wallet Standard `solana:signMessage`, never a transaction), and ANY+// counterparty can verify the signature and the math themselves: no API+// call to three.ws required. The platform enforces the same cap server-side,+// measured from the agent wallet's REALIZED balance change (never the+// caller's self-reported notional), so an exact-output trade that quietly+// costs more than advertised still can't slip past the ceiling.+//+// Zero-dep by design (mirrors the rest of this package): the ed25519 verify+// below uses only Node's built-in `node:crypto` (Ed25519 support has shipped+// since Node 12 / OpenSSL 1.1.1) plus a ~20-line base58 decoder, so this+// module never pulls in bs58 or a curve library just to check a signature.++import { createPublicKey, verify as cryptoVerify } from 'node:crypto';++// Domain-separates this signature from any other message format a wallet+// might be asked to sign (SIWS, a different app's delegation, etc.), so a+// signature over a SIWS message can never be replayed here and vice versa.+export const DELEGATION_DOMAIN = 'three.ws/agent-spend-delegation/v1';++const FIELD_ORDER = ['agent', 'owner', 'cap_lamports_per_epoch', 'epoch_seconds', 'not_after', 'nonce'];++// ── base58 (Bitcoin/Solana alphabet): decode only, no external dep ────────++const B58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+const B58_MAP = (() => {+ const m = new Map();+ for (let i = 0; i < B58_ALPHABET.length; i++) m.set(B58_ALPHABET[i], i);+ return m;+})();++function base58Decode(str) {+ if (typeof str !== 'string' || str.length === 0) throw new Error('base58: empty input');+ let num = 0n;+ for (const ch of str) {+ const val = B58_MAP.get(ch);+ if (val === undefined) throw new Error(`base58: invalid character "${ch}"`);+ num = num * 58n + BigInt(val);+ }+ // Leading '1's encode leading zero bytes: count and restore them.+ let leadingZeros = 0;+ for (const ch of str) {+ if (ch === '1') leadingZeros++;+ else break;+ }+ let hex = num.toString(16);+ if (hex.length % 2) hex = `0${hex}`;+ const body = hex === '00' && num === 0n ? [] : Array.from(Buffer.from(hex, 'hex'));+ return new Uint8Array([...new Array(leadingZeros).fill(0), ...body]);+}++// ── canonical fields + signable message ─────────────────────────────────────++/**+ * Normalize + stringify every field in a fixed order. Every numeric field is+ * carried as a decimal string in the signed message (wallets render raw text;+ * a float would risk a cross-client rounding mismatch at the byte level that+ * breaks the signature even though the "value" looks identical).+ */+export function canonicalDelegationFields(d) {+ if (!d || typeof d !== 'object') throw new TypeError('delegation must be an object');+ const out = {};+ for (const key of FIELD_ORDER) {+ if (d[key] === undefined || d[key] === null || d[key] === '') {+ throw new TypeError(`delegation.${key} is required`);+ }+ out[key] = String(d[key]);+ }+ return out;+}++/**+ * The exact UTF-8 text the owner's wallet signs. One field per line, fixed+ * order, human-legible (a hardware wallet or Phantom's sign-message dialog+ * renders this verbatim), the same "plain statement, not opaque bytes"+ * property SIWS uses (see api/_lib/siws.js), so an owner can actually read+ * what they're authorizing before approving it.+ */+export function delegationMessage(d) {+ const f = canonicalDelegationFields(d);+ return [+ DELEGATION_DOMAIN,+ `agent: ${f.agent}`,+ `owner: ${f.owner}`,+ `cap_lamports_per_epoch: ${f.cap_lamports_per_epoch}`,+ `epoch_seconds: ${f.epoch_seconds}`,+ `not_after: ${f.not_after}`,+ `nonce: ${f.nonce}`,+ ].join('\n');+}++// Wrap a raw 32-byte Ed25519 public key in the fixed SPKI DER envelope Node's+// crypto module requires to build a verifiable KeyObject. The envelope bytes+// are constant for every Ed25519 key (OID 1.3.101.112); only the 32-byte+// payload varies.+const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');++function publicKeyObjectFromBase58(address) {+ const raw = base58Decode(address);+ if (raw.length !== 32) throw new Error(`invalid Solana address: expected 32 bytes, got ${raw.length}`);+ const der = Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(raw)]);+ return createPublicKey({ key: der, format: 'der', type: 'spki' });+}++function decodeSignature(signature) {+ // Wallets encode the 64-byte signature as base58 (Phantom) or base64.+ if (/^[1-9A-HJ-NP-Za-km-z]{87,88}$/.test(signature)) return Buffer.from(base58Decode(signature));+ return Buffer.from(signature, 'base64');+}++/**+ * Verify that `signature` over `delegationMessage(delegation)` was produced+ * by the Ed25519 key at `delegation.owner`. Pure and offline: any+ * counterparty (not just three.ws) can run this to confirm an agent's+ * portable spend authorization without trusting the platform's say-so.+ * Throws on a malformed delegation/signature shape; returns false (never+ * throws) for a well-formed but non-matching signature.+ */+export function verifyDelegationSignature(delegation, signature) {+ const message = delegationMessage(delegation);+ const msgBytes = Buffer.from(message, 'utf8');+ const sigBytes = decodeSignature(signature);+ if (sigBytes.length !== 64) return false;+ const pubKey = publicKeyObjectFromBase58(delegation.owner);+ return cryptoVerify(null, msgBytes, pubKey, sigBytes);+}++// ── pure cap check (no I/O: the server mirrors this over real ledger data) ─++/**+ * Pure epoch-cap arithmetic, identical to the check the server runs over the+ * real realized-spend ledger. `epochSpentLamports` is whatever the caller has+ * already measured as spent in the current rolling epoch window (server:+ * summed from realized `agent_custody_events`, never the agent's own claim).+ * `debitLamports` is the lamport cost of the proposed action. Three outcomes+ * besides "allow": the delegation has lapsed, the clock has run out, or this+ * debit would push the rolling total past the cap.+ */+export function checkDelegationCap({ delegation, nowSec, epochSpentLamports, debitLamports }) {+ const cap = BigInt(delegation.cap_lamports_per_epoch);+ const notAfter = Number(delegation.not_after);+ const now = Number.isFinite(Number(nowSec)) ? Number(nowSec) : Math.floor(Date.now() / 1000);+ if (!Number.isFinite(notAfter) || now > notAfter) {+ return { allow: false, code: 'DELEGATION_EXPIRED', reason: `This delegation expired at ${new Date(notAfter * 1000).toISOString()}.` };+ }+ const spent = BigInt(epochSpentLamports ?? 0);+ const debit = BigInt(debitLamports ?? 0);+ if (spent + debit > cap) {+ return {+ allow: false,+ code: 'DELEGATION_CAP_EXCEEDED',+ reason: `This action would bring the current epoch's realized spend to ${(spent + debit).toString()} lamports, over the delegated cap of ${cap.toString()}.`,+ detail: { spentLamports: spent.toString(), debitLamports: debit.toString(), capLamportsPerEpoch: cap.toString() },+ };+ }+ return { allow: true, code: 'OK', reason: null };+}diff --git a/packages/agent-guards/src/index.d.ts b/packages/agent-guards/src/index.d.tsindex 3887c4b5c..5b13cb619 100644--- a/packages/agent-guards/src/index.d.ts+++ b/packages/agent-guards/src/index.d.ts@@ -240,3 +240,39 @@ export interface GuardsClient {export declare function createGuards(options?: GuardsClientOptions): GuardsClient;export declare function guards(agentId: string, options?: AgentBindingOptions): AgentGuards;++// ── signed spend delegation ────────────────────────────────────────────────++export interface SpendDelegation {+ agent: string;+ owner: string;+ cap_lamports_per_epoch: string | number | bigint;+ epoch_seconds: string | number;+ not_after: string | number;+ nonce: string;+}++export type DelegationCanonicalFields = Record<+ 'agent' | 'owner' | 'cap_lamports_per_epoch' | 'epoch_seconds' | 'not_after' | 'nonce',+ string+>;++export type DelegationCheckCode = 'OK' | 'DELEGATION_EXPIRED' | 'DELEGATION_CAP_EXCEEDED';++export interface DelegationCheckResult {+ allow: boolean;+ code: DelegationCheckCode;+ reason: string | null;+ detail?: { spentLamports: string; debitLamports: string; capLamportsPerEpoch: string };+}++export declare const DELEGATION_DOMAIN: string;+export declare function canonicalDelegationFields(d: SpendDelegation): DelegationCanonicalFields;+export declare function delegationMessage(d: SpendDelegation): string;+export declare function verifyDelegationSignature(delegation: SpendDelegation, signature: string): boolean;+export declare function checkDelegationCap(args: {+ delegation: SpendDelegation;+ nowSec?: number;+ epochSpentLamports: bigint | number | string;+ debitLamports: bigint | number | string;+}): DelegationCheckResult;diff --git a/packages/agent-guards/src/index.js b/packages/agent-guards/src/index.jsindex c81964548..a76970d70 100644--- a/packages/agent-guards/src/index.js+++ b/packages/agent-guards/src/index.js@@ -16,6 +16,13 @@import { createHttp, ThreeWsError } from './http.js';export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';+export {+ DELEGATION_DOMAIN,+ canonicalDelegationFields,+ delegationMessage,+ verifyDelegationSignature,+ checkDelegationCap,+} from './delegation.js';// 1 SOL = 1e9 lamports — the on-chain unit the per-trade / daily-budget caps use.export const LAMPORTS_PER_SOL = 1_000_000_000n;diff --git a/packages/agent-guards/test/delegation.test.js b/packages/agent-guards/test/delegation.test.jsnew file mode 100644index 000000000..ed777199c--- /dev/null+++ b/packages/agent-guards/test/delegation.test.js@@ -0,0 +1,113 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { generateKeyPairSync, sign as cryptoSign } from 'node:crypto';+import {+ DELEGATION_DOMAIN,+ delegationMessage,+ verifyDelegationSignature,+ checkDelegationCap,+} from '../src/delegation.js';++// Real Ed25519 keypairs end to end, no stubs, no mocked crypto. Mirrors how+// an actual Solana wallet (Phantom, Backpack, a hardware signer) would sign+// the exact bytes `delegationMessage` produces.++const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+function b58encode(buf) {+ let num = 0n;+ for (const b of buf) num = num * 256n + BigInt(b);+ let out = '';+ while (num > 0n) {+ out = B58[Number(num % 58n)] + out;+ num /= 58n;+ }+ let leadingZeros = 0;+ for (const b of buf) {+ if (b === 0) leadingZeros++;+ else break;+ }+ return B58[0].repeat(leadingZeros) + (out || '');+}++function makeSigner() {+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');+ const raw = publicKey.export({ type: 'spki', format: 'der' }).subarray(-32);+ return { address: b58encode(raw), sign: (msg) => cryptoSign(null, Buffer.from(msg, 'utf8'), privateKey) };+}++function baseDelegation(owner, overrides = {}) {+ return {+ agent: 'THREEsynthetic1111111111111111111111111111',+ owner,+ cap_lamports_per_epoch: '1000000000', // 1 SOL per epoch+ epoch_seconds: '86400',+ not_after: String(Math.floor(Date.now() / 1000) + 3600),+ nonce: 'nonce-' + Math.random().toString(36).slice(2),+ ...overrides,+ };+}++test('delegationMessage is domain-separated and field-ordered', () => {+ const owner = makeSigner();+ const d = baseDelegation(owner.address, { nonce: 'fixed-nonce' });+ const msg = delegationMessage(d);+ assert.equal(msg.split('\n')[0], DELEGATION_DOMAIN);+ assert.deepEqual(msg.split('\n').slice(1), [+ `agent: ${d.agent}`,+ `owner: ${d.owner}`,+ `cap_lamports_per_epoch: ${d.cap_lamports_per_epoch}`,+ `epoch_seconds: ${d.epoch_seconds}`,+ `not_after: ${d.not_after}`,+ `nonce: fixed-nonce`,+ ]);+});++test('verifyDelegationSignature accepts a real signature from the claimed owner', () => {+ const owner = makeSigner();+ const d = baseDelegation(owner.address);+ const sig = owner.sign(delegationMessage(d)).toString('base64');+ assert.equal(verifyDelegationSignature(d, sig), true);+});++test('verifyDelegationSignature rejects a wrong signer (signature from a different key)', () => {+ const owner = makeSigner();+ const impostor = makeSigner();+ const d = baseDelegation(owner.address); // claims to be `owner`...+ const sig = impostor.sign(delegationMessage(d)).toString('base64'); // ...but signed by someone else+ assert.equal(verifyDelegationSignature(d, sig), false);+});++test('verifyDelegationSignature rejects a tampered field (signature no longer matches the message)', () => {+ const owner = makeSigner();+ const d = baseDelegation(owner.address);+ const sig = owner.sign(delegationMessage(d)).toString('base64');+ const tampered = { ...d, cap_lamports_per_epoch: String(BigInt(d.cap_lamports_per_epoch) * 100n) };+ assert.equal(verifyDelegationSignature(tampered, sig), false);+});++test('checkDelegationCap allows a debit within the remaining epoch headroom', () => {+ const d = baseDelegation('owner-address-placeholder');+ const out = checkDelegationCap({ delegation: d, epochSpentLamports: 0n, debitLamports: 500_000_000n });+ assert.equal(out.allow, true);+});++test('checkDelegationCap rejects a debit measured from realized spend that would exceed the cap', () => {+ const d = baseDelegation('owner-address-placeholder');+ // Already spent 900M lamports (realized, from the ledger) this epoch; a further+ // 500M debit would land the epoch total at 1.4B against a 1B cap.+ const out = checkDelegationCap({ delegation: d, epochSpentLamports: 900_000_000n, debitLamports: 500_000_000n });+ assert.equal(out.allow, false);+ assert.equal(out.code, 'DELEGATION_CAP_EXCEEDED');+});++test('checkDelegationCap rejects once not_after has passed', () => {+ const d = baseDelegation('owner-address-placeholder', { not_after: String(Math.floor(Date.now() / 1000) - 10) });+ const out = checkDelegationCap({ delegation: d, epochSpentLamports: 0n, debitLamports: 1n });+ assert.equal(out.allow, false);+ assert.equal(out.code, 'DELEGATION_EXPIRED');+});++test('canonicalDelegationFields requires every field', async () => {+ const { canonicalDelegationFields } = await import('../src/delegation.js');+ assert.throws(() => canonicalDelegationFields({ agent: 'a' }), TypeError);+});diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex c6137175a..092718c46 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,11 +1,11 @@{- "generated_at": "2026-10-14T21:30:35.104Z",+ "generated_at": "2026-10-14T22:09:58.191Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 4093,+ "total": 4094,"complete": false,"full_feed": "/changelog.json","entries": [@@ -31,6 +31,17 @@"docs"]},+ {+ "date": "2026-10-14",+ "type": "update",+ "title": "Agents can now carry an owner-signed, offline-verifiable spend cap",+ "summary": "A new Delegation tab in the agent wallet hub lets an owner sign a portable spend delegation with their own linked Solana wallet (a message, never a transaction): 'this agent may move at most CAP lamports per EPOCH, until NOT_AFTER.' The signed envelope is plain text and the verification math is a zero-dependency function any outside counterparty can run themselves (packages/agent-guards, spec in its README) to confirm the authorization without trusting three.ws's say-so. three.ws enforces the same cap server-side on every call through POST /api/agent/guard, measured from the agent wallet's REALIZED spend in the custody ledger rather than the agent's own claim, so an exact-output trade that ends up costing more than advertised still can't slip past the ceiling. A replayed nonce, an expired delegation, or a signature from the wrong wallet is rejected with a specific reason.",+ "link": "/docs/agent-wallet-api",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-14","type": "update",@@ -1545,17 +1556,6 @@"tags": ["feature"]- },- {- "date": "2026-10-10",- "type": "update",- "title": "Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels",- "summary": "Fifteen new tools for Claude or any MCP client, plus a portfolio API at /api/v1/agents/:id/portfolio. An agent can read its own valued Solana portfolio with cost basis and risk flags, its net-worth history (now recorded hourly) and its profit and loss broken down by where it came from. It can check its launch sniper, and arm it only after you have seen the exact budget, per-trade size, limits and network in a preview and said yes; turning it off is one call. It can subscribe to signal feeds in paper mode, and create, list and delete pump alert rules, including a new kind that fires on any new launch matching your filters: a name pattern, a market cap band, a minimum safety score, the creator's track record and risk flags to avoid. Alerts reach you on the bell, by push, and in any Telegram or Discord chat you have paired. Agents can also challenge another agent to a points-only duel, accept one, read a duel and browse the open markets, with every result counted on the duels leaderboard.",- "link": "/docs/mcp",- "tags": [- "feature",- "sdk"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 257f5f0fb..2e646a904 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-14T21:30:35.083Z",+ "generated_at": "2026-10-14T22:09:58.170Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -28,6 +28,17 @@"docs"]},+ {+ "date": "2026-10-14",+ "type": "update",+ "title": "Agents can now carry an owner-signed, offline-verifiable spend cap",+ "summary": "A new Delegation tab in the agent wallet hub lets an owner sign a portable spend delegation with their own linked Solana wallet (a message, never a transaction): 'this agent may move at most CAP lamports per EPOCH, until NOT_AFTER.' The signed envelope is plain text and the verification math is a zero-dependency function any outside counterparty can run themselves (packages/agent-guards, spec in its README) to confirm the authorization without trusting three.ws's say-so. three.ws enforces the same cap server-side on every call through POST /api/agent/guard, measured from the agent wallet's REALIZED spend in the custody ledger rather than the agent's own claim, so an exact-output trade that ends up costing more than advertised still can't slip past the ceiling. A replayed nonce, an expired delegation, or a signature from the wrong wallet is rejected with a specific reason.",+ "link": "/docs/agent-wallet-api",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-14","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex da281c2cc..e1e146b39 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,14 @@<category>infra</category><description>npm run mirrors:drift compares each of the ~105 standalone mirrors in data/standalone-mirrors.json against its monorepo source at the last synced commit (GitHub API, with a README-timestamp fallback when rate-limited), flags any package whose GitHub copy has diverged, and writes the result to tasks/mirror-drift-<date>.json. It never pushes or mutates a mirror; it is the audit step that found the two fixes above.</description></item>+ <item>+ <title>Agents can now carry an owner-signed, offline-verifiable spend cap</title>+ <link>https://three.ws/docs/agent-wallet-api</link>+ <guid isPermaLink="false">2026-10-14:Agents can now carry an owner-signed, offline-verifiable spend cap</guid>+ <pubDate>Wed, 14 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A new Delegation tab in the agent wallet hub lets an owner sign a portable spend delegation with their own linked Solana wallet (a message, never a transaction): 'this agent may move at most CAP lamports per EPOCH, until NOT_AFTER.' The signed envelope is plain text and the verification math is a zero-dependency function any outside counterparty can run themselves (packages/agent-guards, spec in its README) to confirm the authorization without trusting three.ws's say-so. three.ws enforces the same cap server-side on every call through POST /api/agent/guard, measured from the agent wallet's REALIZED spend in the custody ledger rather than the agent's own claim, so an exact-output trade that ends up costing more than advertised still can't slip past the ceiling. A replayed nonce, an expired delegation, or a signature from the wrong wallet is rejected with a specific reason.</description>+ </item><item><title>Atomic is now a six-tab Transaction V1 lab, not just an inspector</title><link>https://three.ws/atomic</link>diff --git a/public/features.json b/public/features.jsonindex d2de93c03..809d21390 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-14T21:30:35.070Z",+ "generated_at": "2026-10-14T22:09:58.157Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.jsindex 0d2175a26..15cdf96fe 100644--- a/src/agent-wallet-hub/index.js+++ b/src/agent-wallet-hub/index.js@@ -39,6 +39,7 @@ import './tabs/signals.js';import './tabs/pay.js';import './tabs/vanity.js';import './tabs/policy.js';+import './tabs/delegation.js';import './tabs/withdraw.js';import './tabs/whitelist.js';import './tabs/give.js';diff --git a/src/agent-wallet-hub/tabs/delegation.js b/src/agent-wallet-hub/tabs/delegation.jsnew file mode 100644index 000000000..bd0b97927--- /dev/null+++ b/src/agent-wallet-hub/tabs/delegation.js@@ -0,0 +1,347 @@+/**+ * Agent Wallet hub: spend delegation tab (owner-only).+ *+ * A signed, epoch-bounded spend delegation is a portable authorization the+ * owner signs with their OWN linked Solana wallet (a message, never a+ * transaction): "this agent may move at most CAP lamports per EPOCH, until+ * NOT_AFTER." Any counterparty can verify the signature offline: see+ * packages/agent-guards/src/delegation.js, the canonical spec this panel's+ * signing flow implements byte-for-byte. The platform enforces the same cap+ * server-side against the agent wallet's REALIZED spend (never the agent's+ * own claim), on every preflight through POST /api/agent/guard.+ *+ * The owner's wallet does the signing, not this page and not the agent. The+ * CLAUDE.md on-chain-signing confirmation gate is about an agent signing or+ * spending; an owner approving their own browser wallet's signMessage prompt+ * for their own agent is the normal, expected use of this feature.+ */++import { registerWalletTab } from '../registry.js';+import { shortAddress, timeAgo } from '../util.js';+import { consumeCsrfToken } from '../../api.js';+import { injectedProvider, connectLaunchWallet } from '../../launch/launch-wallet.js';++// Mirrors packages/agent-guards/src/delegation.js's delegationMessage() byte for+// byte. That module is not imported here on purpose: it pulls in node:crypto+// for the (server-only) signature *verification* path, which this browser+// bundle never needs and should not ship. The *format* below is frozen by the+// same spec (packages/agent-guards/README.md, "Spec: signed spend delegation")+// and covered by tests/agent-guard-endpoint.test.js registering a delegation+// signed over exactly this string.+const DELEGATION_DOMAIN = 'three.ws/agent-spend-delegation/v1';+export function delegationMessage(d) {+ return [+ DELEGATION_DOMAIN,+ `agent: ${d.agent}`,+ `owner: ${d.owner}`,+ `cap_lamports_per_epoch: ${d.cap_lamports_per_epoch}`,+ `epoch_seconds: ${d.epoch_seconds}`,+ `not_after: ${d.not_after}`,+ `nonce: ${d.nonce}`,+ ].join('\n');+}++const STYLE_ID = 'awh-delegation-style';+const STYLE = `+.awd-intro { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); line-height:1.55; margin:0 0 var(--space-3,12px); max-width:62ch; }+.awd-active { 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)); padding:12px 14px; display:flex; flex-direction:column; gap:8px; }+.awd-row { display:flex; justify-content:space-between; gap:12px; font-size: var(--text-sm,.764rem); padding:5px 0; border-top:1px solid var(--stroke,rgba(255,255,255,.06)); }+.awd-row:first-child { border-top:none; }+.awd-row .k { color: var(--ink-dim,#888); }+.awd-row .v { color: var(--ink,#e8e8e8); font-family: var(--font-mono,ui-monospace,monospace); text-align:right; }+.awd-badge { display:inline-flex; align-items:center; gap:5px; font-size: var(--text-2xs,.6875rem); font-weight:600; padding:2px 9px; border-radius: var(--radius-pill,999px); border:1px solid transparent; }+.awd-badge.ok { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 12%, transparent); border-color: color-mix(in srgb, var(--success,#4ade80) 32%, transparent); }+.awd-badge.exp { color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 12%, transparent); border-color: color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); }+.awd-form { display:grid; grid-template-columns: repeat(auto-fit,minmax(150px,1fr)); gap:10px; margin-bottom: var(--space-3,12px); }+.awd-field label { display:block; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); margin-bottom:5px; }+.awd-field input, .awd-field select { width:100%; box-sizing:border-box; font:inherit; font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); background: var(--surface-1,rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:8px 11px; transition: border-color var(--duration-fast,140ms); }+.awd-field input:focus, .awd-field select:focus { outline:none; border-color: var(--stroke-strong,rgba(255,255,255,.2)); }+.awd-owner { display:flex; align-items:center; gap:8px; font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); margin-bottom: var(--space-3,12px); }+.awd-owner .addr { font-family: var(--font-mono,ui-monospace,monospace); color: var(--ink-dim,#888); }+.awd-actions { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }+.awd-hint { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }+.awd-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(255,255,255,.3); border-top-color: currentColor; border-radius:50%; animation: awd-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }+@keyframes awd-rot { to { transform: rotate(360deg); } }+.awd-err { background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); margin-bottom: var(--space-3,12px); line-height:1.45; }+.awd-skel { height:14px; border-radius:6px; background: var(--surface-2,rgba(255,255,255,.05)); animation: awd-pulse 1.4s ease-in-out infinite; margin:9px 0; }+@keyframes awd-pulse { 0%,100%{opacity:1} 50%{opacity:.4} }+@media (prefers-reduced-motion: reduce) { .awd-spin, .awd-skel { animation:none; } }+`;++const EPOCH_PRESETS = [+ { key: '3600', label: '1 hour' },+ { key: '21600', label: '6 hours' },+ { key: '86400', label: '1 day' },+ { key: '604800', label: '1 week' },+];++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = STYLE_ID;+ tag.textContent = STYLE;+ document.head.appendChild(tag);+}++async function call(url, { method = 'GET', body = null } = {}) {+ try {+ const opts = { method, credentials: 'include', headers: {} };+ if (body != null) {+ opts.headers['content-type'] = 'application/json';+ opts.body = JSON.stringify(body);+ }+ if (method !== 'GET') {+ const token = await consumeCsrfToken();+ if (token) opts.headers['x-csrf-token'] = token;+ }+ const r = await fetch(url, opts);+ let j = null;+ try { j = await r.json(); } catch { /* empty body */ }+ if (!r.ok) {+ return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, extra: j || null };+ }+ return { ok: true, status: r.status, data: j?.data ?? j };+ } catch (err) {+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };+ }+}++// Decimal SOL string -> integer lamports string, without floating-point+// rounding: the signed message carries lamports as an exact decimal string+// and a float would risk a byte-level mismatch that breaks the signature.+function solToLamports(input) {+ const s = String(input ?? '').trim();+ if (!/^\d+(\.\d+)?$/.test(s) || s === '0' || /^0\.0*$/.test(s)) return null;+ const [whole, frac = ''] = s.split('.');+ const fracLamports = (frac + '000000000').slice(0, 9);+ const lamports = BigInt(whole || '0') * 1_000_000_000n + BigInt(fracLamports || '0');+ return lamports > 0n ? lamports.toString() : null;+}++function lamportsToSol(lamports) {+ const n = BigInt(lamports ?? 0);+ const whole = n / 1_000_000_000n;+ const frac = (n % 1_000_000_000n).toString().padStart(9, '0').replace(/0+$/, '');+ return frac ? `${whole}.${frac}` : whole.toString();+}++function toBase64(bytes) {+ let out = '';+ for (let i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]);+ return btoa(out);+}++function freshNonce() {+ return typeof crypto?.randomUUID === 'function' ? crypto.randomUUID() : `nonce-${Date.now()}-${Math.round(Math.random() * 1e9)}`;+}++const DELEGATION_ERROR_COPY = {+ invalid_delegation: 'That delegation was malformed before it even reached your wallet. Try again.',+ expired_delegation: 'The expiry you chose is already in the past.',+ agent_not_found: 'This agent has no linked owner wallet to delegate from. Link a Solana wallet to your account first.',+ wrong_signer: "The signature doesn't match your linked owner wallet. Make sure you approved the prompt with the same wallet shown below.",+ replayed_nonce: 'That exact delegation has already been registered. Try again to get a fresh nonce.',+};++registerWalletTab({+ id: 'delegation',+ label: 'Delegation',+ order: 59,+ ownerOnly: true,+ mount({ panel, ctx }) {+ injectStyle();+ const esc = ctx.escapeHtml;+ const toast = ctx.toast;+ const base = (sub) => `/api/agents/${encodeURIComponent(ctx.agentId)}/solana/${sub}`;++ let destroyed = false;+ let detachNet = null;+ const state = {+ loaded: false,+ signedOut: false,+ active: null, // delegation row | { error } | null+ ownerWallet: null, // address | null while unresolved+ ownerLoaded: false,+ form: { capSol: '0.5', epoch: '86400', expiryDays: '30' },+ signing: false,+ signError: null,+ };++ function render() {+ if (destroyed) return;+ if (state.signedOut) { panel.innerHTML = renderSignedOut(); return; }+ panel.innerHTML = `${renderActive()}${renderComposer()}`;+ wire();+ }++ function renderSignedOut() {+ const next = encodeURIComponent(location.pathname + location.search + location.hash);+ return `<div class="awh-card">+ <div class="awh-card-h">Spend delegation</div>+ <p class="awd-intro">Spend delegations are private to the wallet owner. Sign in to review or sign one for your agent.</p>+ <div class="awd-actions"><a class="awh-btn awh-btn--primary" href="/login?next=${next}">Sign in</a></div>+ </div>`;+ }++ function renderActive() {+ if (!state.loaded) {+ return `<div class="awh-card"><div class="awh-card-h">Active delegation</div><div class="awd-skel" style="width:60%"></div><div class="awd-skel"></div><div class="awd-skel" style="width:40%"></div></div>`;+ }+ if (state.active?.error) {+ return `<div class="awh-card"><div class="awh-card-h">Active delegation</div><div class="awd-err" role="alert">Couldn't load your delegation.<br>${esc(state.active.error)}</div><div class="awd-actions"><button class="awh-btn" type="button" data-act="reload">Retry</button></div></div>`;+ }+ const d = state.active;+ if (!d) {+ return `<div class="awh-card">+ <div class="awh-card-h">Active delegation</div>+ <p class="awd-intro" style="margin-bottom:0;">No spend delegation on file. This is optional, on top of the numeric caps and policy rules below: a delegation is a portable, offline-verifiable receipt any counterparty can check, capping this agent to at most a fixed amount per rolling window until a fixed expiry.</p>+ </div>`;+ }+ const notAfterMs = new Date(d.not_after).getTime();+ const expired = Number.isFinite(notAfterMs) && notAfterMs < Date.now();+ const epochLabel = EPOCH_PRESETS.find((p) => p.key === String(d.epoch_seconds))?.label || `${d.epoch_seconds}s`;+ return `<div class="awh-card">+ <div class="awh-card-h">Active delegation</div>+ <div class="awd-active">+ <div class="awd-row"><span class="k">Status</span><span class="v"><span class="awd-badge ${expired ? 'exp' : 'ok'}">${expired ? 'Expired' : 'Active'}</span></span></div>+ <div class="awd-row"><span class="k">Cap per epoch</span><span class="v">${esc(lamportsToSol(d.cap_lamports_per_epoch))} SOL</span></div>+ <div class="awd-row"><span class="k">Epoch length</span><span class="v">${esc(epochLabel)}</span></div>+ <div class="awd-row"><span class="k">${expired ? 'Expired' : 'Expires'}</span><span class="v">${esc(new Date(d.not_after).toLocaleString())} (${esc(timeAgo(Math.floor(notAfterMs / 1000)))})</span></div>+ <div class="awd-row"><span class="k">Owner wallet</span><span class="v">${esc(shortAddress(d.owner_wallet))}</span></div>+ <div class="awd-row"><span class="k">Nonce</span><span class="v">${esc(shortAddress(d.nonce, 6, 6))}</span></div>+ </div>+ <p class="awd-hint" style="margin-top:8px;">Signing a new delegation below replaces this one once the new nonce registers.</p>+ </div>`;+ }++ function renderComposer() {+ const ownerLine = !state.ownerLoaded+ ? `<div class="awd-owner"><span class="awd-spin" aria-hidden="true"></span>Looking up your linked wallet…</div>`+ : state.ownerWallet+ ? `<div class="awd-owner">Signing as <span class="addr">${esc(shortAddress(state.ownerWallet))}</span></div>`+ : `<div class="awd-owner">No Solana wallet linked to your account yet. Connecting below will link one.</div>`;+ return `<div class="awh-card">+ <div class="awh-card-h">Sign a new delegation</div>+ <p class="awd-intro">Choose a cap and a window, then approve a sign-message prompt in your own wallet: never a transaction, nothing moves. Any counterparty can verify the signature offline.</p>+ ${state.signError ? `<div class="awd-err" role="alert">${esc(state.signError)}</div>` : ''}+ ${ownerLine}+ <div class="awd-form">+ <div class="awd-field">+ <label for="awd-cap">Cap per epoch (SOL)</label>+ <input id="awd-cap" type="text" inputmode="decimal" value="${esc(state.form.capSol)}" />+ </div>+ <div class="awd-field">+ <label for="awd-epoch">Epoch length</label>+ <select id="awd-epoch">+ ${EPOCH_PRESETS.map((p) => `<option value="${p.key}" ${state.form.epoch === p.key ? 'selected' : ''}>${esc(p.label)}</option>`).join('')}+ </select>+ </div>+ <div class="awd-field">+ <label for="awd-expiry">Expires in (days)</label>+ <input id="awd-expiry" type="text" inputmode="numeric" value="${esc(state.form.expiryDays)}" />+ </div>+ </div>+ <div class="awd-actions">+ <button class="awh-btn awh-btn--primary" type="button" id="awd-sign" ${state.signing ? 'disabled' : ''}>+ ${state.signing ? '<span class="awd-spin" aria-hidden="true"></span>Waiting on your wallet…' : 'Sign & activate'}+ </button>+ <span class="awd-hint grow">Opens your browser wallet's sign-message prompt.</span>+ </div>+ </div>`;+ }++ function wire() {+ panel.querySelector('[data-act="reload"]')?.addEventListener('click', () => { state.loaded = false; render(); loadActive(); });+ const capEl = panel.querySelector('#awd-cap');+ const epochEl = panel.querySelector('#awd-epoch');+ const expiryEl = panel.querySelector('#awd-expiry');+ capEl?.addEventListener('input', () => { state.form.capSol = capEl.value; });+ epochEl?.addEventListener('change', () => { state.form.epoch = epochEl.value; });+ expiryEl?.addEventListener('input', () => { state.form.expiryDays = expiryEl.value; });+ panel.querySelector('#awd-sign')?.addEventListener('click', signAndActivate);+ }++ async function loadActive() {+ const res = await call(base('delegation'));+ if (destroyed) return;+ state.loaded = true;+ if (res.status === 401) { state.signedOut = true; render(); return; }+ state.signedOut = false;+ state.active = res.ok ? res.data?.delegation ?? null : { error: res.message };+ render();+ }++ async function loadOwnerWallet() {+ const res = await call('/api/auth/wallets');+ if (destroyed) return;+ state.ownerLoaded = true;+ if (res.ok) {+ const solWallets = (res.data?.wallets || []).filter((w) => w.chain_type === 'solana');+ solWallets.sort((a, b) => (b.is_primary ? 1 : 0) - (a.is_primary ? 1 : 0));+ state.ownerWallet = solWallets[0]?.address || null;+ }+ render();+ }++ async function signAndActivate() {+ if (state.signing) return;+ const capLamports = solToLamports(state.form.capSol);+ if (!capLamports) { state.signError = 'Enter a cap greater than 0 SOL.'; render(); return; }+ const epochSeconds = Number(state.form.epoch);+ const expiryDays = Number(state.form.expiryDays);+ if (!Number.isFinite(expiryDays) || expiryDays <= 0) { state.signError = 'Enter an expiry at least 1 day out.'; render(); return; }++ state.signing = true; state.signError = null; render();+ try {+ const { address: connected } = await connectLaunchWallet();+ if (state.ownerWallet && connected !== state.ownerWallet) {+ throw Object.assign(new Error(`Your wallet is connected as ${shortAddress(connected)}, but your account's linked owner wallet is ${shortAddress(state.ownerWallet)}. Switch accounts in your wallet extension and try again.`), { code: 'wrong_wallet' });+ }+ const provider = injectedProvider();+ if (!provider?.signMessage) throw Object.assign(new Error('This wallet cannot sign messages.'), { code: 'no_provider' });++ const delegation = {+ agent: ctx.agentId,+ owner: connected,+ cap_lamports_per_epoch: capLamports,+ epoch_seconds: String(epochSeconds),+ not_after: String(Math.floor(Date.now() / 1000) + Math.round(expiryDays * 86400)),+ nonce: freshNonce(),+ };+ const message = delegationMessage(delegation);+ const { signature } = await provider.signMessage(new TextEncoder().encode(message), 'utf8');+ const delegationSignature = toBase64(signature);++ const res = await call(base('delegation'), { method: 'POST', body: { delegation, delegationSignature } });+ if (destroyed) return;+ if (!res.ok) {+ state.signError = DELEGATION_ERROR_COPY[res.code] || res.message || 'Could not register that delegation.';+ render();+ return;+ }+ state.active = res.data?.delegation ?? null;+ state.ownerWallet = connected;+ toast('Delegation signed and active');+ render();+ } catch (e) {+ if (destroyed) return;+ state.signError = e?.code === 'NO_PROVIDER'+ ? 'No Solana wallet extension found. Install Phantom, Backpack, or Solflare and try again.'+ : (e?.message || 'Could not sign that delegation.');+ render();+ } finally {+ if (!destroyed) { state.signing = false; render(); }+ }+ }++ detachNet = ctx.onNetworkChange(() => { state.loaded = false; render(); loadActive(); });+ render();+ loadActive();+ loadOwnerWallet();++ return {+ onShow() { if (!state.loaded) loadActive(); },+ destroy() { destroyed = true; detachNet?.(); },+ };+ },+});diff --git a/tests/agent-guard-endpoint.test.js b/tests/agent-guard-endpoint.test.jsindex 8c768b34f..53e6a5634 100644--- a/tests/agent-guard-endpoint.test.js+++ b/tests/agent-guard-endpoint.test.js@@ -1,7 +1,9 @@import { describe, it, expect, vi, beforeEach } from 'vitest';+import { generateKeyPairSync, sign as cryptoSign } from 'node:crypto';// The endpoint is pure policy evaluation over the request body; the only-// impure edges are the rate limiter and the env-backed http helpers.+// impure edges are the rate limiter, the env-backed http helpers, and (since+// the signed spend delegation is opt-in persisted state) the database.const agentGuardIp = vi.fn();vi.mock('../api/_lib/rate-limit.js', async (importOriginal) => ({...(await importOriginal()),@@ -16,7 +18,96 @@ vi.mock('../api/_lib/avatar-wallet.js', () => ({solUsdPrice: (...a) => solUsdPrice(...a),}));+// A minimal fake database, keyed on query substrings, in the same style as+// tests/agent-custody-guards.test.js: enough to exercise the real+// registerDelegation / checkDelegationSpend logic (not a mock of those+// functions themselves) without a live Postgres connection.+const dbState = { owners: new Map(), wallets: new Map(), active: new Map(), nonces: new Set(), custodySpentLamports: 0n };+vi.mock('../api/_lib/db.js', () => ({+ sql: (strings, ...values) => {+ const query = strings.join('?');+ if (query.includes('INSERT INTO agent_spend_delegations')) {+ const [agentId, owner, cap, epochSeconds, notAfterSec, nonce, signature] = values;+ const key = `${agentId}:${nonce}`;+ if (dbState.nonces.has(key)) {+ throw new Error('duplicate key value violates unique constraint "agent_spend_delegations_nonce_unique"');+ }+ dbState.nonces.add(key);+ const row = {+ id: `deleg-${dbState.nonces.size}`,+ agent_id: agentId,+ owner_wallet: owner,+ cap_lamports_per_epoch: String(cap),+ epoch_seconds: Number(epochSeconds),+ not_after: new Date(Number(notAfterSec) * 1000).toISOString(),+ nonce,+ signature,+ status: 'active',+ created_at: new Date().toISOString(),+ };+ dbState.active.set(agentId, row);+ return [row];+ }+ if (query.includes('FROM agent_spend_delegations')) {+ const [agentId] = values;+ const row = dbState.active.get(agentId);+ return row ? [row] : [];+ }+ if (query.includes('FROM agent_identities')) {+ const [agentId] = values;+ const userId = dbState.owners.get(agentId);+ return userId ? [{ user_id: userId }] : [];+ }+ if (query.includes('FROM user_wallets')) {+ const [userId] = values;+ const address = dbState.wallets.get(userId);+ return address ? [{ address }] : [];+ }+ if (query.includes('FROM agent_custody_events')) {+ return [{ lamports: String(dbState.custodySpentLamports) }];+ }+ return [];+ },+}));+const { default: guardHandler } = await import('../api/agent/guard.js');+const { delegationMessage } = await import('../packages/agent-guards/src/delegation.js');++const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+function b58encode(buf) {+ let num = 0n;+ for (const b of buf) num = num * 256n + BigInt(b);+ let out = '';+ while (num > 0n) {+ out = B58[Number(num % 58n)] + out;+ num /= 58n;+ }+ let leadingZeros = 0;+ for (const b of buf) {+ if (b === 0) leadingZeros++;+ else break;+ }+ return B58[0].repeat(leadingZeros) + (out || '');+}+function makeSigner() {+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');+ const raw = publicKey.export({ type: 'spki', format: 'der' }).subarray(-32);+ return { address: b58encode(raw), sign: (msg) => cryptoSign(null, Buffer.from(msg, 'utf8'), privateKey) };+}+function baseDelegation(agent, owner, overrides = {}) {+ return {+ agent,+ owner,+ cap_lamports_per_epoch: '1000000000', // 1 SOL per epoch+ epoch_seconds: '86400',+ not_after: String(Math.floor(Date.now() / 1000) + 3600),+ nonce: 'nonce-' + Math.random().toString(36).slice(2),+ ...overrides,+ };+}+function signDelegation(signer, delegation) {+ return signer.sign(delegationMessage(delegation)).toString('base64');+}function mkReq({ method = 'POST', url = '/api/agent/guard', headers = {}, body = null } = {}) {return {@@ -59,6 +150,11 @@ const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);beforeEach(() => {agentGuardIp.mockReset().mockResolvedValue({ success: true, limit: 300, remaining: 299, reset: Date.now() + 1000 });solUsdPrice.mockReset().mockResolvedValue(200);+ dbState.owners.clear();+ dbState.wallets.clear();+ dbState.active.clear();+ dbState.nonces.clear();+ dbState.custodySpentLamports = 0n;});describe('POST /api/agent/guard', () => {@@ -197,3 +293,147 @@ describe('POST /api/agent/guard', () => {expect(res.statusCode).toBe(429);});});++describe('POST /api/agent/guard - signed spend delegation', () => {+ const agentId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';+ const userId = 'owner-user-1';++ function linkOwner(owner) {+ dbState.owners.set(agentId, userId);+ dbState.wallets.set(userId, owner.address);+ }++ it('stores a valid owner-signed delegation', async () => {+ const owner = makeSigner();+ linkOwner(owner);+ const delegation = baseDelegation(agentId, owner.address);+ const signature = signDelegation(owner, delegation);+ const res = mkRes();+ await guardHandler(mkReq({ body: { agentId, calls: [], delegation, delegationSignature: signature } }), res);+ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body.delegationRegistration.ok).toBe(true);+ expect(body.delegationRegistration.capLamportsPerEpoch).toBe('1000000000');+ });++ it('rejects a wrong signer (claims an owner it was not signed by)', async () => {+ const owner = makeSigner();+ const impostor = makeSigner();+ linkOwner(owner);+ const delegation = baseDelegation(agentId, owner.address);+ const signature = signDelegation(impostor, delegation);+ const res = mkRes();+ await guardHandler(mkReq({ body: { agentId, calls: [], delegation, delegationSignature: signature } }), res);+ const body = parse(res);+ expect(body.delegationRegistration.ok).toBe(false);+ expect(body.delegationRegistration.code).toBe('wrong_signer');+ });++ it('rejects an already-expired delegation at registration time', async () => {+ const owner = makeSigner();+ linkOwner(owner);+ const delegation = baseDelegation(agentId, owner.address, { not_after: String(Math.floor(Date.now() / 1000) - 10) });+ const signature = signDelegation(owner, delegation);+ const res = mkRes();+ await guardHandler(mkReq({ body: { agentId, calls: [], delegation, delegationSignature: signature } }), res);+ const body = parse(res);+ expect(body.delegationRegistration.ok).toBe(false);+ expect(body.delegationRegistration.code).toBe('expired_delegation');+ });++ it('rejects a replayed nonce (the exact same signed envelope resubmitted)', async () => {+ const owner = makeSigner();+ linkOwner(owner);+ const delegation = baseDelegation(agentId, owner.address);+ const signature = signDelegation(owner, delegation);+ const first = mkRes();+ await guardHandler(mkReq({ body: { agentId, calls: [], delegation, delegationSignature: signature } }), first);+ expect(parse(first).delegationRegistration.ok).toBe(true);++ const second = mkRes();+ await guardHandler(mkReq({ body: { agentId, calls: [], delegation, delegationSignature: signature } }), second);+ const body = parse(second);+ expect(body.delegationRegistration.ok).toBe(false);+ expect(body.delegationRegistration.code).toBe('replayed_nonce');+ });++ it('blocks a call whose realized-plus-proposed epoch spend would exceed the signed cap', async () => {+ const owner = makeSigner();+ linkOwner(owner);+ // 1 SOL/epoch cap; 0.9 SOL already realized this epoch from the custody+ // ledger (not a self-reported amount) leaves 0.1 SOL of headroom.+ const delegation = baseDelegation(agentId, owner.address, { cap_lamports_per_epoch: '1000000000' });+ const signature = signDelegation(owner, delegation);+ const register = mkRes();+ await guardHandler(mkReq({ body: { agentId, calls: [], delegation, delegationSignature: signature } }), register);+ expect(parse(register).delegationRegistration.ok).toBe(true);++ dbState.custodySpentLamports = 900_000_000n;+ const res = mkRes();+ await guardHandler(+ mkReq({+ body: { agentId, calls: [{ identifier: 'solana_transfer', arguments: { token: 'SOL', amount: 0.2 } }] },+ }),+ res,+ );+ const { verdicts } = parse(res);+ expect(verdicts[0].delegation.allow).toBe(false);+ expect(verdicts[0].delegation.code).toBe('DELEGATION_CAP_EXCEEDED');+ expect(verdicts[0].verdict.decision).toBe('block');+ expect(verdicts[0].verdict.blockedBy).toBe('spend_delegation');+ });++ it('allows a call within the signed cap and remaining realized headroom', async () => {+ const owner = makeSigner();+ linkOwner(owner);+ const delegation = baseDelegation(agentId, owner.address, { cap_lamports_per_epoch: '1000000000' });+ const signature = signDelegation(owner, delegation);+ const register = mkRes();+ await guardHandler(mkReq({ body: { agentId, calls: [], delegation, delegationSignature: signature } }), register);+ expect(parse(register).delegationRegistration.ok).toBe(true);++ dbState.custodySpentLamports = 0n;+ const res = mkRes();+ await guardHandler(+ mkReq({+ body: { agentId, calls: [{ identifier: 'solana_transfer', arguments: { token: 'SOL', amount: 0.1 } }] },+ }),+ res,+ );+ const { verdicts } = parse(res);+ expect(verdicts[0].delegation.allow).toBe(true);+ expect(verdicts[0].verdict.decision).not.toBe('block');+ });++ it('rejects a call against a delegation whose not_after has since passed', async () => {+ const owner = makeSigner();+ linkOwner(owner);+ // Seeded directly as "on file", bypassing registration, to model a+ // delegation that was valid when signed and has since lapsed: the DB+ // row is still `status = 'active'` (nothing flips it), so the cap check+ // at call time is what has to catch the expiry, not the registration path.+ dbState.active.set(agentId, {+ id: 'deleg-lapsed',+ agent_id: agentId,+ owner_wallet: owner.address,+ cap_lamports_per_epoch: '1000000000',+ epoch_seconds: 86400,+ not_after: new Date(Date.now() - 1000).toISOString(),+ nonce: 'lapsed-nonce',+ status: 'active',+ created_at: new Date().toISOString(),+ });+ const res = mkRes();+ await guardHandler(+ mkReq({+ body: { agentId, calls: [{ identifier: 'solana_transfer', arguments: { token: 'SOL', amount: 0.01 } }] },+ }),+ res,+ );+ const { verdicts } = parse(res);+ expect(verdicts[0].delegation.allow).toBe(false);+ expect(verdicts[0].delegation.code).toBe('DELEGATION_EXPIRED');+ expect(verdicts[0].verdict.decision).toBe('block');+ expect(verdicts[0].verdict.blockedBy).toBe('spend_delegation');+ });+});diff --git a/tests/delegation-message-parity.test.js b/tests/delegation-message-parity.test.jsnew file mode 100644index 000000000..f92e6dcbf--- /dev/null+++ b/tests/delegation-message-parity.test.js@@ -0,0 +1,41 @@+// The owner's browser never imports packages/agent-guards/src/delegation.js+// (it pulls in node:crypto for the signature-verification path, which has no+// browser build). src/agent-wallet-hub/tabs/delegation.js instead carries a+// local copy of delegationMessage() for building the bytes the owner's wallet+// signs. This test is the tripwire that keeps the two in byte-for-byte sync:+// if either format ever drifts, a delegation signed in the browser would fail+// server-side signature verification with no obvious cause.+import { describe, it, expect } from 'vitest';+import { delegationMessage as canonicalDelegationMessage } from '../packages/agent-guards/src/delegation.js';+import { delegationMessage as browserDelegationMessage } from '../src/agent-wallet-hub/tabs/delegation.js';++describe('delegation message format parity (browser tab vs. agent-guards spec)', () => {+ const cases = [+ {+ agent: '11111111111111111111111111111111',+ owner: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ cap_lamports_per_epoch: '500000000',+ epoch_seconds: '86400',+ not_after: String(Math.floor(Date.now() / 1000) + 30 * 86400),+ nonce: 'a1b2c3d4-e5f6-7890-aaaa-bbbbccccdddd',+ },+ {+ agent: 'So11111111111111111111111111111111111111112',+ owner: 'So11111111111111111111111111111111111111112',+ cap_lamports_per_epoch: '1',+ epoch_seconds: '3600',+ not_after: '0',+ nonce: 'x',+ },+ ];++ it('produces byte-identical signing bytes for the same fields', () => {+ for (const d of cases) {+ expect(browserDelegationMessage(d)).toBe(canonicalDelegationMessage(d));+ }+ });++ it('leads with the shared domain tag', () => {+ expect(browserDelegationMessage(cases[0]).split('\n')[0]).toBe('three.ws/agent-spend-delegation/v1');+ });+});