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(approvals): park agent spend above an approval threshold instead of failing it
nirholas9f40b6accf48
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6d7283f8f..b5e786dad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-10-15+- **A spend call above an agent's approval threshold now pauses for the owner instead of failing**: The requires_approval verdict agent payment sessions and agent-to-agent hires can already produce now actually does something: both /api/pay/execute and /api/agents/a2a-hire create a request on the existing approval inbox the moment a call crosses the caller's approval_threshold_usd, answer with 202 and a poll link to /approvals/<id> instead of failing the call, and resume automatically the moment the owner taps Approve there, re-probing or re-running the exact same reserve-then-settle path the call would have taken inline, with no re-entry point for a double-spend. A denied request answers 403 on the next poll, an expired one answers 410, and retrying with the same idempotency key before the owner answers just re-polls instead of parking a second request. Nothing new to build on the approval page itself: it already renders any venue generically from the request's summary, amount, and risk notes, so the two new venues (payment_session_execute, a2a_hire) show up with the right Approve/Decline card for free. Covered by 21 new handler tests across create, approve, decline, expire, and the executor's own idempotent re-run. (`/approvals`) `[feature, security]`- **Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts**: Agent payment sessions get three new governance knobs, settable at creation and editable while a session is active: blocked_hosts (a denylist checked after the allowlist, so an explicit block always wins over a broad allow, even with no allowlist set), approval_threshold_usd (a call priced above this amount now gets a distinct requires_approval verdict instead of either settling or silently failing), and per_rail_daily_usd (a rolling 24h spend cap per settlement network, reserved atomically the same way the session budget already is, closing the race a naive sum-of-past-executions check would leave open). Every governance verdict, allow or reject, now carries a policy_digest (a sha256 hash of the exact policy it was judged against) and an HMAC signature over the verdict, digest, request, and timestamp, stored with the execution: editing a session's policy after the fact changes the digest and breaks the signature on every verdict that preceded the edit, so a verdict record can be trusted even after the policy it was judged against has since moved. The dry-run simulator at /api/pay/simulate now predicts all three new rules through the exact same shared policy module the real enforcer calls, so a simulated verdict and an enforced one can never disagree; that parity is pinned by a new test running both over identical scenarios. The payments page gained matching fields in both the session creation and edit modals, with inline validation and a collapsed 'Advanced spend policy' section so the common case (budget, expiry, host allowlist) stays uncluttered. (`/docs/payment-sessions`) `[feature, security]`## 2026-10-14diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.jsindex 53ea47923..b34e3585b 100644--- a/api/_lib/agent-trade-guards.js+++ b/api/_lib/agent-trade-guards.js@@ -103,6 +103,11 @@ export const SPEND_LIMIT_DEFAULTS = Object.freeze({// every individual payment stays under `per_tx_usd`. Null means no per-payee// cap (unchanged behavior for wallets that never set one).per_counterparty_daily_usd: null,+ // Above this USD amount, an autonomous outbound payment (x402, a2a hire) does+ // not execute inline: it is parked as an approval request and the owner must+ // approve it before the agent's poll receives a one-time execution grant. Null+ // means no threshold (unchanged behavior for every wallet that never sets one).+ approval_threshold_usd: null,withdraw_allowlist: [],// Wallet freeze / kill switch. When true, every AUTONOMOUS outbound path// (trade, snipe, x402) is rejected immediately. The owner's own withdraw is@@ -214,6 +219,7 @@ export function normalizeSpendLimits(raw) {daily_usd: numOrNull(r.daily_usd),per_tx_usd: numOrNull(r.per_tx_usd),per_counterparty_daily_usd: numOrNull(r.per_counterparty_daily_usd),+ approval_threshold_usd: numOrNull(r.approval_threshold_usd),withdraw_allowlist: deduped,frozen: r.frozen === true,require_capabilities: r.require_capabilities === true,@@ -247,6 +253,8 @@ export async function setSpendLimits(agentId, userId, patch, { req = null } = {}'per_counterparty_daily_usd' in patch? patch.per_counterparty_daily_usd: prev.per_counterparty_daily_usd,+ approval_threshold_usd:+ 'approval_threshold_usd' in patch ? patch.approval_threshold_usd : prev.approval_threshold_usd,// The allowlist lives in destination_whitelist_entries now, where a new// address serves a cooldown (api/_lib/destination-whitelist.js). A patch can// no longer write it through here, so no path can skip the cooldown bydiff --git a/api/_lib/approvals.js b/api/_lib/approvals.jsindex a7de62fd2..ed49379cb 100644--- a/api/_lib/approvals.js+++ b/api/_lib/approvals.js@@ -69,6 +69,16 @@ export const VENUES = Object.freeze({// intent (api/_lib/pump-funded-launch.js). It signs the create transaction// and cannot be undone, so the owner answers every one.pump_launch: { label: 'Coin launches from the agent wallet', auto: false },+ // An x402 payment session call that crossed the session's own+ // approval_threshold_usdc (api/pay/execute.js). The threshold itself is a+ // numeric policy the owner already set on the session; it is never+ // auto-approved again here, so every one is answered by hand.+ payment_session_execute: { label: 'Agent payments above your approval threshold', auto: false },+ // An agent-to-agent hire whose price crossed the hiring agent's+ // approval_threshold_usd (api/agents/a2a-hire.js). Same reasoning: a+ // threshold the owner set is a decision to see each crossing, not to+ // pre-authorize it.+ a2a_hire: { label: 'Agent-to-agent hires above your approval threshold', auto: false },});// Ceiling on a single auto-approve policy. Anything bigger is a decision the@@ -292,8 +302,10 @@ export function publicApproval(row, { now = Date.now(), withLink = true } = {})// One per source. Lazy imports keep this module free of Solana/web3 weight and// break the cycle with the engines that create requests.//-// Contract: executor(row) -> { status: 'ok'|'error'|'paused'|'skipped', signature?, note?, usd? }.-// It receives the stored row and must execute ONLY row.payload.+// Contract: executor(row) -> { status: 'ok'|'error'|'paused'|'skipped', signature?, note?, usd?, data? }.+// It receives the stored row and must execute ONLY row.payload. `data` is optional:+// the full result of the action, for a caller that polls the approval record after+// an async approval to retrieve more than the signature/usd/note summary.const EXECUTORS = {wallet_intent: async () => (await import('./wallet-intents.js')).executeApprovedIntentAction,@@ -306,6 +318,10 @@ const EXECUTORS = {external_wallet: async () => (await import('./account-link/external-wallets.js')).executeApprovedPayoutWallet,// A funded launch intent the owner confirmed (api/_lib/pump-funded-launch.js).pump_funded_launch: async () => (await import('./pump-funded-launch.js')).executeApprovedFundedLaunch,+ // An x402 session call parked by the approval threshold (api/pay/execute.js).+ payment_session_execute: async () => (await import('../pay/execute.js')).executeApprovedPaymentSessionCall,+ // An a2a hire parked by the approval threshold (api/agents/a2a-hire.js).+ a2a_hire: async () => (await import('../agents/a2a-hire.js')).executeApprovedA2aHire,};export function hasExecutor(source) {@@ -759,6 +775,10 @@ export async function recordApprovalOutcome(id, outcome, { userId = null, req =note: outcome?.note ? String(outcome.note).slice(0, 280) : null,usd: Number.isFinite(Number(outcome?.usd)) ? Number(outcome.usd) : null,...(outcome?.integrity === false ? { integrity: false } : {}),+ // The full upstream result (an x402 resource body, a completed hire), for an+ // executor whose caller polls for it after the owner approved asynchronously.+ // Optional: every existing executor omits it and behaves exactly as before.+ ...(outcome?.data !== undefined ? { data: outcome.data } : {}),};const [row] = await sql`UPDATE approval_requestsdiff --git a/api/_lib/pay/policy.js b/api/_lib/pay/policy.jsindex 2caf0dcc2..e62bf0d70 100644--- a/api/_lib/pay/policy.js+++ b/api/_lib/pay/policy.js@@ -307,9 +307,13 @@ export function approvalVerdict(amountAtomics, approvalThresholdAtomics) {* @param {object} call.policy { status, expiresAt, allowedHosts, blockedHosts, maxPerTxAtomics, railSpentAtomics, railDailyCapAtomics, approvalThresholdAtomics }* @param {bigint|string|number} call.remainingAtomics budget left before this call* @param {Date} [call.now]+ * @param {boolean} [call.approvalGranted] skip the approval rule: an owner already+ * approved this exact call once and the governor is replaying it under that grant.+ * Every other rule still runs, so a grant never bypasses the allowlist, the rail+ * cap, or the budget, only the "ask a human" step it already satisfied.* @returns {{code: string, message: string, detail: object} | null}*/-export function evaluateCall({ url, amountAtomics, policy, remainingAtomics, now = new Date() }) {+export function evaluateCall({ url, amountAtomics, policy, remainingAtomics, now = new Date(), approvalGranted = false }) {return (statusVerdict(policy.status ?? 'active') ??expiryVerdict(policy.expiresAt ?? null, now) ??@@ -318,7 +322,7 @@ export function evaluateCall({ url, amountAtomics, policy, remainingAtomics, nowperTxVerdict(amountAtomics, policy.maxPerTxAtomics ?? null) ??railDailyVerdict(amountAtomics, policy.railSpentAtomics ?? 0, policy.railDailyCapAtomics ?? null) ??budgetVerdict(amountAtomics, remainingAtomics) ??- approvalVerdict(amountAtomics, policy.approvalThresholdAtomics ?? null)+ (approvalGranted ? null : approvalVerdict(amountAtomics, policy.approvalThresholdAtomics ?? null)));}diff --git a/api/_lib/pay/spend-governor.js b/api/_lib/pay/spend-governor.jsindex 3c1e75ea3..7f539aa1d 100644--- a/api/_lib/pay/spend-governor.js+++ b/api/_lib/pay/spend-governor.js@@ -181,6 +181,32 @@ export async function verifySessionToken(token) {return row;}+/**+ * Load a session by id with no token check.+ *+ * Used only to resume a call that already cleared authentication once: the+ * owner approval flow stores the session id (never the bearer token) on the+ * approval request's payload, and the executor that runs after the owner+ * clicks Approve re-enters the governor through here instead of re-deriving a+ * token the agent never gets to see again. Never expose this to a path that+ * takes a caller-supplied session id without its own authorization check.+ */+export async function verifySessionById(sessionId) {+ if (!isSessionId(sessionId)) throw new SpendGovernorError('invalid_token', 'Invalid session id format');+ const [row] = await sql`+ SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,+ max_per_tx_usdc, allowed_hosts, blocked_hosts,+ approval_threshold_usdc, per_rail_daily_usdc,+ network, connector_ref,+ status, expires_at, session_metadata+ FROM payment_sessions+ WHERE id = ${sessionId}+ LIMIT 1+ `;+ if (!row) throw new SpendGovernorError('invalid_token', 'Session not found');+ return row;+}+/*** Enforce governance policy and atomically reserve budget for a payment.*@@ -194,14 +220,17 @@ export async function verifySessionToken(token) {* advisory predictions of what those statements are about to decide for real.** @param {object} opts- * @param {string} opts.token - Session bearer token+ * @param {string} [opts.token] - Session bearer token (mutually exclusive with sessionId)+ * @param {string} [opts.sessionId] - Session id, for resuming an approved call that has no token* @param {string} opts.url - Target endpoint URL (for allowlist check)* @param {bigint} opts.amountAtomics - Payment amount in USDC atomics (6 decimals)+ * @param {boolean} [opts.approvalGranted] - Skip the approval-threshold rule: the owner+ * already approved this exact call through the approval inbox.* @returns {Promise<{ session: object, reservationId: string, railReservationId: string|null, policyDigest: string, verdictCode: string, verdictSignature: string, verdictSignedAt: string }>}* @throws {SpendGovernorError} on any policy violation*/-export async function reserveSessionSpend({ token, url, amountAtomics }) {- const session = await verifySessionToken(token);+export async function reserveSessionSpend({ token = null, sessionId = null, url, amountAtomics, approvalGranted = false }) {+ const session = token ? await verifySessionToken(token) : await verifySessionById(sessionId);const now = new Date();const amount = BigInt(amountAtomics);@@ -232,7 +261,7 @@ export async function reserveSessionSpend({ token, url, amountAtomics }) {approvalThresholdAtomics: session.approval_threshold_usdc,};- const verdict = evaluateCall({ url, amountAtomics: amount, policy, remainingAtomics, now });+ const verdict = evaluateCall({ url, amountAtomics: amount, policy, remainingAtomics, now, approvalGranted });const policyDigest = computePolicyDigest(session);const requestHash = computeRequestHash({ sessionId: session.id, url, amountAtomics: amount });diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.jsindex 25f7ae1ea..6b4706484 100644--- a/api/agents/a2a-hire.js+++ b/api/agents/a2a-hire.js@@ -49,9 +49,14 @@ import { recordInvocationReceipt } from '../_lib/agent-invocation-onchain.js';import {atomicsToUsdc,getOfferBySlug,+ getHireById,recordHire,updateHire,} from '../_lib/agent-economy.js';+import { createApprovalRequest, runApproved, TTL_MS } from '../_lib/approvals.js';++// Source key this file registers its executor under (api/_lib/approvals.js EXECUTORS).+export const APPROVAL_SOURCE = 'a2a_hire';// Pull the settlement signature out of the x402 receipt header object, whatever// shape the facilitator returned it in.@@ -218,6 +223,9 @@ export default wrap(async (req, res) => {if (row.status === 'completed') {return json(res, 200, { ok: true, idempotent: true, hire: publicHire(row, offer) });}+ if (row.status === 'pending' && row.meta?.awaiting_approval && row.meta?.approval_id) {+ return await respondHireApprovalStatus(res, { userId, approvalId: row.meta.approval_id, hireRow: row, offer });+ }if (row.status === 'pending') {return error(res, 409, 'hire_in_progress', 'a hire with this key is already in progress');}@@ -231,6 +239,20 @@ export default wrap(async (req, res) => {return error(res, 500, 'hire_record_failed', 'could not record the hire');}+ // ── Human approval above the hiring agent's spend threshold ─────────────+ // A threshold the owner set on this agent (approval_threshold_usd, settable+ // via PUT on /api/agents/solana-wallet's limits endpoint, same policy object+ // as per_tx_usd/daily_usd) is a decision to see every crossing by hand, not a+ // cap to enforce silently. Checked here, after the hire is recorded but+ // before any spend reservation, so a parked hire never holds funds while it+ // waits and a retry of the same idempotencyKey re-enters at the branch above.+ if (spendPolicy.approval_threshold_usd != null && usd > Number(spendPolicy.approval_threshold_usd) + 1e-9) {+ return await requestHireApproval(res, {+ hirer, offer, hireRow, usd, maxUsd, threshold: spendPolicy.approval_threshold_usd,+ input, pushPhase, capBadge,+ });+ }+// ── Reserve the spend against the hiring agent's spend policy ────────────// Per-tx + daily ceilings + kill switch (frozen), atomic, BEFORE payment.let reservationId = null;@@ -381,6 +403,251 @@ export default wrap(async (req, res) => {});});+// ── Park a hire that crossed the hiring agent's approval threshold ──────────+// Spend was never reserved for this hire (the threshold is checked before the+// "Reserve the spend" block), so there is nothing to roll back here: the hire+// row stays 'pending' and simply waits for executeApprovedA2aHire to run the+// rest of the flow once the owner approves.+async function requestHireApproval(res, { hirer, offer, hireRow, usd, maxUsd, threshold, input, pushPhase, capBadge }) {+ pushPhase('awaiting_approval', { cap: capBadge(null, usd) });+ const created = await createApprovalRequest({+ userId: hirer.user_id,+ agentId: hirer.id,+ source: APPROVAL_SOURCE,+ sourceRef: hireRow.id,+ actionType: 'a2a_hire',+ venue: 'a2a_hire',+ payload: {+ kind: 'a2a_hire',+ hire_id: hireRow.id,+ hirer_agent_id: hirer.id,+ provider_agent_id: offer.provider.id,+ service_slug: offer.slug,+ usd,+ max_usd: typeof maxUsd === 'number' ? maxUsd : null,+ input,+ },+ summary: `Agent "${hirer.name || hirer.id}" wants to hire "${offer.provider.name || offer.provider.id}" for ${offer.name} ($${usd.toFixed(2)})`,+ amount: usd,+ amountUsd: usd,+ asset: 'USDC',+ chain: 'solana',+ network: 'mainnet',+ recipient: offer.provider.name || offer.provider.id,+ riskNotes: [+ `This agent's approval threshold is $${Number(threshold).toFixed(2)}.`,+ `Service: ${offer.slug}`,+ ],+ gateReason: `Hire price $${usd.toFixed(2)} exceeds this agent's $${Number(threshold).toFixed(2)} approval threshold.`,+ idempotencyKey: `${APPROVAL_SOURCE}:${hireRow.id}`,+ ttlMs: TTL_MS.transfer,+ autoApprovable: false,+ });++ const req = created.request;+ await updateHire(hireRow.id, { meta: { awaiting_approval: true, approval_id: req.id } });++ if (created.autoApproved) {+ const { outcome } = await runApproved(req, (claim) => executeApprovedA2aHire(claim));+ if (outcome?.status === 'ok' && outcome.data) return json(res, 200, outcome.data);+ return error(res, 502, 'approved_execution_failed', outcome?.note || 'the auto-approved hire did not complete');+ }+ return renderHireApprovalStatus(res, req, hireRow, offer);+}++// Shared by the fresh-create 202 and the idempotent-retry poll: render the+// current state of a hire that is (or was) parked on an approval request.+async function respondHireApprovalStatus(res, { userId, approvalId, hireRow, offer }) {+ const [approvalRow] = await sql`+ SELECT * FROM approval_requests WHERE id = ${approvalId} AND user_id = ${userId}+ `;+ if (!approvalRow) return error(res, 404, 'not_found', 'approval request not found');+ return renderHireApprovalStatus(res, approvalRow, hireRow, offer);+}++function renderHireApprovalStatus(res, approvalRow, hireRow, offer) {+ const status = approvalRow.status;+ if (status === 'executed') {+ const data = approvalRow.result?.data;+ if (data) return json(res, 200, data);+ return error(res, 502, 'approved_execution_missing_result', 'the hire was approved and executed, but its result was not retained');+ }+ if (status === 'failed') {+ return error(res, 502, 'approved_execution_failed', approvalRow.result?.note || 'the approved hire did not complete');+ }+ if (status === 'denied') {+ return error(res, 403, 'approval_denied', 'the owner denied this hire');+ }+ if (status === 'expired') {+ return error(res, 410, 'approval_expired', 'this approval request expired before the owner answered; retry with a new idempotencyKey to ask again');+ }+ // pending, approved, executing: still waiting on the owner (or the executor).+ return json(res, 202, {+ ok: false,+ hire: publicHire(hireRow, offer),+ pending_approval: true,+ approval: {+ id: approvalRow.id,+ status: approvalRow.status,+ link: `/approvals/${approvalRow.id}`,+ expires_at: approvalRow.expires_at,+ },+ message: `this hire needs the owner's approval before it runs: ${approvalRow.summary}. Call this same request again to check status.`,+ });+}++/**+ * Executor registered for source 'a2a_hire' (api/_lib/approvals.js EXECUTORS).+ * Re-runs the reserve-spend → pay-over-x402 → receipt → finalize sequence from+ * the main handler, scoped to ONLY the data stashed in row.payload, after the+ * owner has approved. Mirrors the main handler's error handling exactly:+ * payment_failed still releases the spend reservation, and a receipt failure+ * still completes the hire (the payment already settled).+ */+export async function executeApprovedA2aHire(row) {+ const p = row.payload || {};+ if (p.kind !== 'a2a_hire') {+ return { status: 'error', note: 'unknown hire action, so nothing was executed' };+ }++ const hireRow = await getHireById(p.hire_id);+ if (!hireRow) return { status: 'error', note: 'the hire record for this approval no longer exists' };++ const offer = await getOfferBySlug(p.service_slug);+ if (!offer) return { status: 'error', note: `the service offer "${p.service_slug}" is no longer available` };++ if (hireRow.status === 'completed') {+ return {+ status: 'ok',+ signature: hireRow.payment_signature || undefined,+ usd: hireRow.usd != null ? Number(hireRow.usd) : undefined,+ note: 'hire already completed',+ data: { ok: true, hire: publicHire(hireRow, offer), result: null },+ };+ }++ const [hirer] = await sql`+ SELECT id, user_id, name, meta FROM agent_identities+ WHERE id = ${p.hirer_agent_id} AND deleted_at IS NULL+ `;+ if (!hirer) return { status: 'error', note: 'the hiring agent no longer exists' };+ if (!hirer.meta?.solana_address || !hirer.meta?.encrypted_solana_secret) {+ return { status: 'error', note: 'the hiring agent no longer has a Solana wallet provisioned' };+ }++ const usd = Number(p.usd ?? hireRow.usd ?? 0);+ const userId = hirer.user_id;++ let reservationId = null;+ try {+ const reservation = await reserveSpendUsd({+ agentId: hirer.id,+ userId,+ meta: hirer.meta,+ category: 'x402',+ usdValue: usd,+ asset: 'USDC',+ network: 'mainnet',+ rowMeta: { kind: 'a2a_hire', slug: offer.slug, provider_agent_id: offer.provider.id, hire_id: hireRow.id },+ });+ reservationId = reservation.reservationId;+ await sql`UPDATE agent_hires SET spend_reservation_id = ${reservationId}, updated_at = now() WHERE id = ${hireRow.id}`;+ } catch (err) {+ await updateHire(hireRow.id, { status: 'failed', error: err?.message || 'spend policy blocked' });+ return { status: 'error', note: err?.message || 'the hire could not be re-reserved after approval' };+ }++ let payment;+ try {+ payment = await payExternalX402({+ userId,+ agentId: hirer.id,+ url: serviceResourceUrl(offer.slug),+ method: offer.method === 'POST' ? 'POST' : 'GET',+ body: offer.method === 'POST' ? (p.input ?? {}) : undefined,+ maxUsd: usd,+ });+ } catch (err) {+ await releaseSpendReservation(reservationId, 'hire_payment_failed');+ await updateHire(hireRow.id, { status: 'failed', error: err?.message || String(err) });+ return {+ status: 'error',+ note: `the hire did not complete after approval, no funds were moved: ${err?.message || err?.code || 'payment_failed'}`,+ };+ }++ const paymentSignature = receiptSignature(payment.receipt);+ const payerAddress = payment.payer || hirer.meta.solana_address;+ const deliveredSummary = summarizeResult(payment.result);++ await updateCustodyEvent(reservationId, {+ status: 'confirmed',+ signature: paymentSignature,+ meta: { settled: true },+ }).catch(() => {});++ if (offer.provider.id) {+ recordCustodyEvent({+ agentId: offer.provider.id,+ userId: null,+ eventType: 'tip',+ category: null,+ network: 'mainnet',+ asset: 'USDC',+ usd,+ signature: paymentSignature,+ status: 'confirmed',+ meta: { source: 'a2a_hire', from_agent_id: hirer.id, from: payerAddress, hire_id: hireRow.id, skill: offer.name },+ }).catch(() => {});+ }++ let invocation = null;+ let invocationError = null;+ try {+ const invokerKeypair = await recoverSolanaAgentKeypair(hirer.meta.encrypted_solana_secret, {+ agentId: hirer.id,+ userId,+ reason: 'a2a_hire_invocation_receipt',+ });+ const targetAuthority = offer.provider.solana_address;+ if (!targetAuthority) throw new Error('provider has no Solana authority to record against');+ invocation = await recordInvocationReceipt({+ invokerKeypair,+ targetAuthority,+ skillName: offer.name,+ parameters: JSON.stringify({ slug: offer.slug, hire: hireRow.id, usd }).slice(0, 480),+ });+ } catch (err) {+ invocationError = err?.message || String(err);+ }++ const finalized = await updateHire(hireRow.id, {+ status: 'completed',+ paymentSignature,+ payerAddress,+ invocationSignature: invocation?.signature || null,+ invocationError,+ resultSummary: deliveredSummary,+ meta: {+ receipt: payment.receipt || null,+ invocation: invocation || null,+ awaiting_approval: false,+ },+ });++ return {+ status: 'ok',+ signature: paymentSignature || undefined,+ usd,+ note: 'hire executed after owner approval',+ data: {+ ok: true,+ hire: publicHire(finalized || hireRow, offer, { invocation, payment }),+ result: payment.result ?? null,+ },+ };+}+// Shape the hire for the client, including explorer links derived from the real// on-chain signatures. The embodied layer + money-cam consume `embodied`.function publicHire(row, offer, extra = {}) {diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex 61825d631..cb7be5a62 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -1183,7 +1183,7 @@ async function handleLimits(req, res, id) {// owner surface. A PUT may patch either or both: a `trade_limits` object// updates the discretionary-trade caps (per-trade SOL, daily budget, breaker,// kill switch); the top-level USD/allowlist keys update the spend policy.- const wantsSpend = ['daily_usd', 'per_tx_usd', 'per_counterparty_daily_usd', 'frozen'].some((k) => k in body);+ const wantsSpend = ['daily_usd', 'per_tx_usd', 'per_counterparty_daily_usd', 'approval_threshold_usd', 'frozen'].some((k) => k in body);let limitsOut = getSpendLimits(meta);let tradeLimitsOut = getTradeLimits(meta);let whitelistOut = null;diff --git a/api/pay/execute.js b/api/pay/execute.jsindex 549758875..db305a614 100644--- a/api/pay/execute.js+++ b/api/pay/execute.js@@ -53,9 +53,15 @@ import {recordExecution,SpendGovernorError,} from '../_lib/pay/spend-governor.js';+import { computeRequestHash } from '../_lib/pay/policy.js';+import { createApprovalRequest, runApproved, isUuid, TTL_MS } from '../_lib/approvals.js';+import { sql } from '../_lib/db.js';const SOLANA_RPC = env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+// Source key this file registers its executor under (api/_lib/approvals.js EXECUTORS).+export const APPROVAL_SOURCE = 'payment_session_execute';+// ── Platform payer: Solana ───────────────────────────────────────────────────let _solanaKeypair = null;@@ -243,9 +249,320 @@ function explorerUrl(txHash) {return `https://solscan.io/tx/${txHash}`;}+function hostOf(rawUrl) {+ try { return new URL(rawUrl).hostname; } catch { return String(rawUrl || ''); }+}++// ── Settle a reserved payment: sign, submit, record ─────────────────────────+// Everything after governance clears (build the signed payload, submit it,+// record the execution). Pulled out of the main handler so the exact same+// settlement path can run either synchronously (the direct call) or later,+// from the approval executor, once the owner has approved a call that crossed+// the session's approval threshold. Never writes to an HTTP response: it+// returns a plain result so both callers can shape their own response.+async function settlePayment({+ sessionRecord, railReservationId, policyDigest, verdictCode, verdictSignature, verdictSignedAt,+ targetUrl, method, requestBody, accept, resource, amountAtomics, amountUsd, idempotencyKey, t0,+}) {+ let keypair;+ try {+ keypair = loadSolanaKeypair();+ } catch (err) {+ await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});+ return {+ ok: false,+ status: err.status ?? 503,+ code: err.code ?? 'wallet_unconfigured',+ message: err.message || 'Platform Solana payment wallet is not configured',+ };+ }+ const payerAddress = keypair.publicKey.toBase58();+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });++ let paymentPayload;+ try {+ paymentPayload = await buildSolanaPayload({+ accept, amount: amountAtomics, buyer: keypair, conn, resourceUrl: resource.url || targetUrl,+ });+ } catch (err) {+ await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});+ if (isRpcUnavailable(err)) {+ return {+ ok: false, status: 503, code: 'rpc_unavailable',+ message: 'Solana RPC temporarily unavailable; payment not built, retry shortly',+ detail: { retryable: true, retry_after: RPC_RETRY_AFTER_SECONDS },+ headers: { 'retry-after': String(RPC_RETRY_AFTER_SECONDS) },+ };+ }+ return { ok: false, status: 502, code: 'build_failed', message: `Failed to build Solana payment: ${err?.message}` };+ }++ const xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');++ let paid;+ try {+ paid = await guardedFetch(targetUrl, { method, body: requestBody, headers: { 'X-PAYMENT': xPayment } });+ } catch (err) {+ // Network failure AFTER signing: chain state unknown, do NOT roll back.+ await recordExecution({+ sessionId: sessionRecord.id, userId: sessionRecord.user_id, endpointUrl: targetUrl, method,+ amountAtomics, network: accept.network, txHash: null, payerAddress, payeeAddress: accept.payTo,+ status: 'failed', errorCode: 'settle_uncertain', errorMessage: err?.message,+ durationMs: Date.now() - t0, idempotencyKey, policyDigest, verdictCode, verdictSignature, verdictSignedAt,+ }).catch(() => {});+ return {+ ok: false, status: 502, code: 'settle_uncertain',+ message: 'Payment was submitted but confirmation was not received. Do not retry immediately.',+ };+ }++ const paidJson = safeJson(paid.text) ?? paid.text;+ const settled = b64decodeJson(paid.headers.get('x-payment-response'));+ const txHash = settled?.transaction || settled?.txHash || null;+ const payer = settled?.payer || payerAddress;+ const durationMs = Date.now() - t0;++ if (paid.status === 402) {+ await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});+ await recordExecution({+ sessionId: sessionRecord.id, userId: sessionRecord.user_id, endpointUrl: targetUrl, method,+ amountAtomics, network: accept.network, txHash: null, payerAddress: payer, payeeAddress: accept.payTo,+ status: 'failed', errorCode: 'payment_rejected', errorMessage: 'Service rejected the payment before settlement',+ durationMs, idempotencyKey, policyDigest, verdictCode, verdictSignature, verdictSignedAt,+ }).catch(() => {});+ return {+ ok: false, status: 402, code: 'payment_rejected',+ message: 'Service rejected the payment before settlement. Budget has been restored.',+ detail: typeof paidJson === 'object' ? paidJson : null,+ };+ }++ if (!paid.ok) {+ await recordExecution({+ sessionId: sessionRecord.id, userId: sessionRecord.user_id, endpointUrl: targetUrl, method,+ amountAtomics, network: accept.network, txHash, payerAddress: payer, payeeAddress: accept.payTo,+ status: 'failed', errorCode: 'upstream_error', errorMessage: `Endpoint returned HTTP ${paid.status}`,+ responseBody: typeof paidJson === 'object' ? paidJson : null,+ durationMs, idempotencyKey, policyDigest, verdictCode, verdictSignature, verdictSignedAt,+ }).catch(() => {});+ return {+ ok: false, status: 502, code: 'upstream_error',+ message: `Endpoint returned HTTP ${paid.status} after payment. Check wallet activity before retrying.`,+ };+ }++ await recordExecution({+ sessionId: sessionRecord.id, userId: sessionRecord.user_id, endpointUrl: targetUrl, method,+ amountAtomics, network: accept.network, txHash, payerAddress: payer, payeeAddress: accept.payTo,+ status: 'settled', responseBody: typeof paidJson === 'object' ? paidJson : null,+ durationMs, idempotencyKey, policyDigest, verdictCode, verdictSignature, verdictSignedAt,+ }).catch(() => {});++ return {+ ok: true,+ body: {+ ok: true,+ paid: true,+ result: paidJson,+ payment: {+ session_id: sessionRecord.id,+ amount_usd: amountUsd,+ network: accept.network,+ payer,+ pay_to: accept.payTo,+ tx_hash: txHash,+ explorer: explorerUrl(txHash),+ },+ session: {+ id: sessionRecord.id,+ spent_usd: atomicsToUsd(BigInt(sessionRecord.spent_usdc)),+ remaining_usd: atomicsToUsd(BigInt(sessionRecord.budget_usdc) - BigInt(sessionRecord.spent_usdc)),+ },+ duration_ms: durationMs,+ },+ };+}++function sendSettlement(res, result) {+ if (result.ok) return json(res, 200, result.body);+ if (result.headers) for (const [k, v] of Object.entries(result.headers)) res.setHeader(k, v);+ return error(res, result.status, result.code, result.message, result.detail);+}++// ── Resume a call the owner approved, with no session token in hand ─────────+// The approval payload stores only the session id (never the bearer token: a+// polling agent should not need to have kept it, and the owner approving from+// the web UI never sees it either). approvalGranted:true lifts only the+// approval-threshold rule inside the governor; every other rule (allowlist,+// per-tx, rail cap, budget) still runs for real, so an approval can never+// widen anything but the one check it answered.+export async function runPaymentSessionApproval({ sessionId, url, method, body, idempotencyKey }) {+ const t0 = Date.now();+ const probeResult = await probe402(url, { method, body });+ if (probeResult.free) {+ return {+ ok: true,+ body: {+ ok: true, paid: false,+ note: 'Endpoint served response without a 402. No payment needed.',+ status: probeResult.status, result: probeResult.result,+ },+ };+ }+ const { accept, resource, amountAtomics } = probeResult;+ const amountUsd = atomicsToUsd(amountAtomics);+ const reservation = await reserveSessionSpend({ sessionId, url, amountAtomics, approvalGranted: true });+ return settlePayment({+ sessionRecord: reservation.session,+ railReservationId: reservation.railReservationId,+ policyDigest: reservation.policyDigest,+ verdictCode: reservation.verdictCode,+ verdictSignature: reservation.verdictSignature,+ verdictSignedAt: reservation.verdictSignedAt,+ targetUrl: url, method, requestBody: body, accept, resource, amountAtomics, amountUsd, idempotencyKey, t0,+ });+}++/**+ * Executor registered for source 'payment_session_execute' (api/_lib/approvals.js+ * EXECUTORS). Runs ONLY row.payload, once, after the owner approves.+ */+export async function executeApprovedPaymentSessionCall(row) {+ const p = row.payload || {};+ if (p.kind !== 'payment_session_execute') {+ return { status: 'error', note: 'Unknown payment action, so nothing was executed.' };+ }+ try {+ const result = await runPaymentSessionApproval({+ sessionId: p.session_id, url: p.url, method: p.method, body: p.body, idempotencyKey: p.idempotency_key,+ });+ if (!result.ok) return { status: 'error', note: result.message || 'The payment did not go through.' };+ return {+ status: 'ok',+ signature: result.body?.payment?.tx_hash || undefined,+ usd: result.body?.payment?.amount_usd ?? undefined,+ note: 'Payment executed after owner approval.',+ data: result.body,+ };+ } catch (err) {+ return { status: 'error', note: (err?.message || 'execution failed').slice(0, 240) };+ }+}++/** Shared by the direct 202 response and the GET poll: render the current state of a parked call. */+function respondFromApprovalStatus(res, approvalRow) {+ const status = approvalRow.status;+ if (status === 'executed') {+ const data = approvalRow.result?.data;+ if (data) return json(res, 200, data);+ return error(res, 502, 'approved_execution_missing_result', 'The payment was approved and executed, but its result was not retained.');+ }+ if (status === 'failed') {+ return error(res, 502, 'approved_execution_failed', approvalRow.result?.note || 'The approved payment did not go through.');+ }+ if (status === 'denied') {+ return error(res, 403, 'approval_denied', 'The owner denied this payment.');+ }+ if (status === 'expired') {+ return error(res, 410, 'approval_expired', 'This approval request expired before the owner answered. Call execute again to ask once more.');+ }+ // pending, approved, executing: still waiting on the owner (or the inline executor).+ return json(res, 202, {+ ok: false,+ paid: false,+ pending_approval: true,+ approval: {+ id: approvalRow.id,+ status: approvalRow.status,+ link: `/approvals/${approvalRow.id}`,+ expires_at: approvalRow.expires_at,+ },+ message: `This payment needs the owner's approval before it settles: ${approvalRow.summary}. Poll GET /api/pay/execute?approval_id=${approvalRow.id}&session_token=<token>, or call this same request again, to check status.`,+ });+}++/** Park a call that crossed the session's approval threshold and respond 202 with a poll URL. */+async function respondRequiresApproval(res, { session, targetUrl, method, requestBody, idempotencyKey, amountAtomics, amountUsd, detail }) {+ const reqHash = computeRequestHash({ sessionId: session.id, url: targetUrl, amountAtomics });+ const label = session.label || `session ${String(session.id).slice(0, 8)}`;+ const created = await createApprovalRequest({+ userId: session.user_id,+ agentId: session.agent_id || null,+ source: APPROVAL_SOURCE,+ sourceRef: reqHash,+ actionType: 'payment_session_execute',+ venue: 'payment_session_execute',+ payload: {+ kind: 'payment_session_execute',+ session_id: session.id,+ url: targetUrl,+ method,+ body: requestBody,+ idempotency_key: idempotencyKey,+ },+ summary: `Payment session "${label}" wants to pay $${amountUsd.toFixed(2)} to ${hostOf(targetUrl)}`,+ amount: amountUsd,+ amountUsd,+ asset: 'USDC',+ chain: session.network === 'base' ? 'base' : 'solana',+ network: 'mainnet',+ recipient: hostOf(targetUrl),+ riskNotes: [+ `This session's approval threshold is $${Number(detail?.threshold_usd ?? 0).toFixed(2)}.`,+ `Target endpoint: ${targetUrl}`,+ ],+ gateReason: detail?.message || 'Payment exceeds the session approval threshold.',+ idempotencyKey: `${APPROVAL_SOURCE}:${reqHash}`,+ ttlMs: TTL_MS.transfer,+ // A numeric threshold the owner set is a decision to see each crossing by+ // hand; it is never covered by an auto-approve policy (VENUES marks this+ // venue auto:false), so this branch never actually triggers today, but the+ // inline path is kept correct in case that ever changes.+ autoApprovable: false,+ });++ const req = created.request;+ if (created.autoApproved) {+ const { outcome } = await runApproved(req, (claim) => executeApprovedPaymentSessionCall(claim));+ if (outcome?.status === 'ok' && outcome.data) return json(res, 200, outcome.data);+ return error(res, 502, 'approved_execution_failed', outcome?.note || 'The auto-approved payment did not go through.');+ }+ return respondFromApprovalStatus(res, req);+}++// ── GET poll: an agent checking on a parked call with only its session token ──+async function handlePoll(req, res) {+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const approvalId = params.get('approval_id') || '';+ const sessionToken = params.get('session_token') || '';+ if (!approvalId || !isUuid(approvalId) || !sessionToken) {+ return error(res, 400, 'missing_params', 'approval_id (uuid) and session_token are required');+ }++ let session;+ try {+ session = await verifySessionToken(sessionToken);+ } catch (err) {+ if (err instanceof SpendGovernorError) return error(res, err.status, err.code, err.message, err.detail);+ throw err;+ }++ const [row] = await sql`+ SELECT * FROM approval_requests WHERE id = ${approvalId} AND source = ${APPROVAL_SOURCE}+ `;+ if (!row || row.payload?.session_id !== session.id) {+ return error(res, 404, 'not_found', 'No matching approval request for this session.');+ }+ return respondFromApprovalStatus(res, row);+}+// ── Main handler ─────────────────────────────────────────────────────────────export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (cors(req, res, { methods: 'POST,GET,OPTIONS', origins: '*' })) return;+ if (req.method?.toUpperCase() === 'GET') return handlePoll(req, res);if (req.method?.toUpperCase() !== 'POST') {return error(res, 405, 'method_not_allowed', 'POST required');}@@ -283,10 +600,12 @@ export default wrap(async (req, res) => {const t0 = Date.now();- // Phase 0: verify the token is valid before probing the endpoint.- // The atomic reservation happens later in phase 2.+ // Phase 0: verify the token is valid before probing the endpoint. Kept (not+ // discarded) because respondRequiresApproval needs the session's user_id and+ // label if the approval-threshold rule ends up parking this call in phase 2.+ let session0;try {- await verifySessionToken(sessionToken);+ session0 = await verifySessionToken(sessionToken);} catch (err) {if (err instanceof SpendGovernorError) {return error(res, err.status, err.code, err.message, err.detail);@@ -317,206 +636,37 @@ export default wrap(async (req, res) => {const amountUsd = atomicsToUsd(amountAtomics);// Phase 2: governance enforcement (check session, allowlist, budget) is atomic- let sessionRecord, reservationId, railReservationId, policyDigest, verdictCode, verdictSignature, verdictSignedAt;+ let reservation;try {- const reservation = await reserveSessionSpend({+ reservation = await reserveSessionSpend({token: sessionToken,url: targetUrl,amountAtomics,});- sessionRecord = reservation.session;- reservationId = reservation.reservationId;- railReservationId = reservation.railReservationId;- policyDigest = reservation.policyDigest;- verdictCode = reservation.verdictCode;- verdictSignature = reservation.verdictSignature;- verdictSignedAt = reservation.verdictSignedAt;} catch (err) {if (err instanceof SpendGovernorError) {+ if (err.code === 'requires_approval') {+ return await respondRequiresApproval(res, {+ session: session0, targetUrl, method, requestBody, idempotencyKey,+ amountAtomics, amountUsd, detail: err.detail,+ });+ }return error(res, err.status, err.code, err.message, err.detail);}throw err;}- // Phase 3: load platform Solana payer and build the signed payment payload- let paymentPayload;- let payerAddress;-- let keypair;- try {- keypair = loadSolanaKeypair();- } catch (err) {- await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});- // loadSolanaKeypair separates "no key configured" from "key present but- // undecodable". Collapsing both into wallet_unconfigured sent an operator- // looking for a missing env var that was in fact already set.- return error(- res,- err.status ?? 503,- err.code ?? 'wallet_unconfigured',- err.message || 'Platform Solana payment wallet is not configured',- );- }- payerAddress = keypair.publicKey.toBase58();- const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });- try {- paymentPayload = await buildSolanaPayload({- accept,- amount: amountAtomics,- buyer: keypair,- conn,- resourceUrl: resource.url || targetUrl,- });- } catch (err) {- await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});- if (isRpcUnavailable(err)) {- // No funds moved: the chain could not be read and nothing was cached.- // Typed + retryable so the agent backs off instead of treating it as a- // broken endpoint.- res.setHeader('retry-after', String(RPC_RETRY_AFTER_SECONDS));- return error(res, 503, 'rpc_unavailable', 'Solana RPC temporarily unavailable; payment not built, retry shortly', { retryable: true, retry_after: RPC_RETRY_AFTER_SECONDS });- }- return error(res, 502, 'build_failed', `Failed to build Solana payment: ${err?.message}`);- }-- const xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');-- // Phase 4: submit payment to the endpoint- let paid;- try {- paid = await guardedFetch(targetUrl, {- method,- body: requestBody,- headers: { 'X-PAYMENT': xPayment },- });- } catch (err) {- // Network failure AFTER signing: chain state unknown, do NOT roll back.- await recordExecution({- sessionId: sessionRecord.id,- userId: sessionRecord.user_id,- endpointUrl: targetUrl,- method,- amountAtomics,- network: accept.network,- txHash: null,- payerAddress,- payeeAddress: accept.payTo,- status: 'failed',- errorCode: 'settle_uncertain',- errorMessage: err?.message,- durationMs: Date.now() - t0,- idempotencyKey,- policyDigest,- verdictCode,- verdictSignature,- verdictSignedAt,- }).catch(() => {});- return error(res, 502, 'settle_uncertain',- 'Payment was submitted but confirmation was not received. Do not retry immediately.');- }-- const paidJson = safeJson(paid.text) ?? paid.text;- const settled = b64decodeJson(paid.headers.get('x-payment-response'));- const txHash = settled?.transaction || settled?.txHash || null;- const payer = settled?.payer || payerAddress;- const durationMs = Date.now() - t0;-- // Explicit pre-settlement rejection: no funds moved, safe to roll back- if (paid.status === 402) {- await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});- await recordExecution({- sessionId: sessionRecord.id,- userId: sessionRecord.user_id,- endpointUrl: targetUrl,- method,- amountAtomics,- network: accept.network,- txHash: null,- payerAddress: payer,- payeeAddress: accept.payTo,- status: 'failed',- errorCode: 'payment_rejected',- errorMessage: 'Service rejected the payment before settlement',- durationMs,- idempotencyKey,- policyDigest,- verdictCode,- verdictSignature,- verdictSignedAt,- }).catch(() => {});- return error(res, 402, 'payment_rejected',- 'Service rejected the payment before settlement. Budget has been restored.',- typeof paidJson === 'object' ? paidJson : null);- }-- // Non-402 non-success: chain state uncertain- if (!paid.ok) {- await recordExecution({- sessionId: sessionRecord.id,- userId: sessionRecord.user_id,- endpointUrl: targetUrl,- method,- amountAtomics,- network: accept.network,- txHash,- payerAddress: payer,- payeeAddress: accept.payTo,- status: 'failed',- errorCode: 'upstream_error',- errorMessage: `Endpoint returned HTTP ${paid.status}`,- responseBody: typeof paidJson === 'object' ? paidJson : null,- durationMs,- idempotencyKey,- policyDigest,- verdictCode,- verdictSignature,- verdictSignedAt,- }).catch(() => {});- return error(res, 502, 'upstream_error',- `Endpoint returned HTTP ${paid.status} after payment. Check wallet activity before retrying.`);- }-- // Phase 5: success, record the settled execution- await recordExecution({- sessionId: sessionRecord.id,- userId: sessionRecord.user_id,- endpointUrl: targetUrl,- method,- amountAtomics,- network: accept.network,- txHash,- payerAddress: payer,- payeeAddress: accept.payTo,- status: 'settled',- responseBody: typeof paidJson === 'object' ? paidJson : null,- durationMs,- idempotencyKey,- policyDigest,- verdictCode,- verdictSignature,- verdictSignedAt,- }).catch(() => {});-- return json(res, 200, {- ok: true,- paid: true,- result: paidJson,- payment: {- session_id: sessionRecord.id,- amount_usd: amountUsd,- network: accept.network,- payer,- pay_to: accept.payTo,- tx_hash: txHash,- explorer: explorerUrl(txHash),- },- session: {- id: sessionRecord.id,- spent_usd: atomicsToUsd(BigInt(sessionRecord.spent_usdc)),- remaining_usd: atomicsToUsd(- BigInt(sessionRecord.budget_usdc) - BigInt(sessionRecord.spent_usdc),- ),- },- duration_ms: durationMs,+ // Phase 3-5: sign, submit, record. Shared with the post-approval resume path+ // (runPaymentSessionApproval) so a call that got parked above and later gets+ // approved settles through the exact same code, not a parallel copy of it.+ const result = await settlePayment({+ sessionRecord: reservation.session,+ railReservationId: reservation.railReservationId,+ policyDigest: reservation.policyDigest,+ verdictCode: reservation.verdictCode,+ verdictSignature: reservation.verdictSignature,+ verdictSignedAt: reservation.verdictSignedAt,+ targetUrl, method, requestBody, accept, resource, amountAtomics, amountUsd, idempotencyKey, t0,});+ return sendSettlement(res, result);});diff --git a/data/changelog.json b/data/changelog.jsonindex 9e0a8187a..62845a4a8 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-15",+ "title": "A spend call above an agent's approval threshold now pauses for the owner instead of failing",+ "summary": "The requires_approval verdict agent payment sessions and agent-to-agent hires can already produce now actually does something: both /api/pay/execute and /api/agents/a2a-hire create a request on the existing approval inbox the moment a call crosses the caller's approval_threshold_usd, answer with 202 and a poll link to /approvals/<id> instead of failing the call, and resume automatically the moment the owner taps Approve there, re-probing or re-running the exact same reserve-then-settle path the call would have taken inline, with no re-entry point for a double-spend. A denied request answers 403 on the next poll, an expired one answers 410, and retrying with the same idempotency key before the owner answers just re-polls instead of parking a second request. Nothing new to build on the approval page itself: it already renders any venue generically from the request's summary, amount, and risk notes, so the two new venues (payment_session_execute, a2a_hire) show up with the right Approve/Decline card for free. Covered by 21 new handler tests across create, approve, decline, expire, and the executor's own idempotent re-run.",+ "tags": [+ "feature",+ "security"+ ],+ "link": "/approvals"+ },{"date": "2026-10-15","title": "Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts",diff --git a/docs/approvals.md b/docs/approvals.mdindex f530d2d24..f3b4dbc8e 100644--- a/docs/approvals.md+++ b/docs/approvals.md@@ -277,10 +277,16 @@ A source registers an executor in the `EXECUTORS` map in`executor(row)` receives the stored row, executes only `row.payload`, andreturns `{ status: 'ok'|'error'|'paused'|'skipped', signature?, note?, usd? }`.Registered sources include `wallet_intent` (agent transfers and swaps from-wallet intents) and `mail_rule` (an [agent mail](./agent-mail.md) rule in+wallet intents), `mail_rule` (an [agent mail](./agent-mail.md) rule in`approve` mode: approving starts a read-only, zero-budget run on the email thatmatched, and its table names the agent, the email and the instruction with-`Spend: None`). Then call `createApprovalRequest()` where the source hits+`Spend: None`), `payment_session_execute` (an agent payment session call+priced above its `approval_threshold_usd`: [api/pay/execute.js](../api/pay/execute.js)+parks the call instead of failing it, and the caller polls the same endpoint+with `GET` until it resumes), and `a2a_hire` (an agent-to-agent hire priced+above the hiring agent's `approval_threshold_usd`: [api/agents/a2a-hire.js](../api/agents/a2a-hire.js)+parks the hire and the caller's retry with the same idempotency key re-polls+it). Then call `createApprovalRequest()` where the source hitsits step-up gate, with an idempotency key derived from the action. Enginesthat execute inline (an auto-approved request) call `runApproved(row, run)`,which provides the same once-only and integrity guarantees.diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex ec2e47ee2..e2322c73c 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,25 @@{- "generated_at": "2026-10-15T00:43:42.304Z",+ "generated_at": "2026-10-15T02:04:13.683Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 4097,+ "total": 4098,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-15",+ "type": "update",+ "title": "A spend call above an agent's approval threshold now pauses for the owner instead of failing",+ "summary": "The requires_approval verdict agent payment sessions and agent-to-agent hires can already produce now actually does something: both /api/pay/execute and /api/agents/a2a-hire create a request on the existing approval inbox the moment a call crosses the caller's approval_threshold_usd, answer with 202 and a poll link to /approvals/<id> instead of failing the call, and resume automatically the moment the owner taps Approve there, re-probing or re-running the exact same reserve-then-settle path the call would have taken inline, with no re-entry point for a double-spend. A denied request answers 403 on the next poll, an expired one answers 410, and retrying with the same idempotency key before the owner answers just re-polls instead of parking a second request. Nothing new to build on the approval page itself: it already renders any venue generically from the request's summary, amount, and risk notes, so the two new venues (payment_session_execute, a2a_hire) show up with the right Approve/Decline card for free. Covered by 21 new handler tests across create, approve, decline, expire, and the executor's own idempotent re-run.",+ "link": "/approvals",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-15","type": "update",@@ -1546,17 +1557,6 @@"tags": ["launch"]- },- {- "date": "2026-10-10",- "type": "update",- "title": "A complete REST API for agents, with signed webhooks",- "summary": "Everything you can do with an agent in the app now works over plain HTTP with one API key: create and edit agents, start and stop them, chat, start runs and watch them live, schedule automations and fire them on demand, manage skills, and export or import an agent. Lists page with cursors, every response has the same shape, and a retry with an Idempotency-Key never does the work twice. Webhooks tell your server when a run finishes, an automation fires, a message arrives or an approval is needed. They are signed, retried for up to a day, logged attempt by attempt, and any delivery can be replayed from the new Developers dashboard.",- "link": "/docs/api-reference",- "tags": [- "feature",- "sdk"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 2cb8c044d..43d38acb5 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-10-15T00:43:42.282Z",+ "generated_at": "2026-10-15T02:04:13.661Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-10-15",+ "type": "update",+ "title": "A spend call above an agent's approval threshold now pauses for the owner instead of failing",+ "summary": "The requires_approval verdict agent payment sessions and agent-to-agent hires can already produce now actually does something: both /api/pay/execute and /api/agents/a2a-hire create a request on the existing approval inbox the moment a call crosses the caller's approval_threshold_usd, answer with 202 and a poll link to /approvals/<id> instead of failing the call, and resume automatically the moment the owner taps Approve there, re-probing or re-running the exact same reserve-then-settle path the call would have taken inline, with no re-entry point for a double-spend. A denied request answers 403 on the next poll, an expired one answers 410, and retrying with the same idempotency key before the owner answers just re-polls instead of parking a second request. Nothing new to build on the approval page itself: it already renders any venue generically from the request's summary, amount, and risk notes, so the two new venues (payment_session_execute, a2a_hire) show up with the right Approve/Decline card for free. Covered by 21 new handler tests across create, approve, decline, expire, and the executor's own idempotent re-run.",+ "link": "/approvals",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-15","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex a7442eb06..5475fb41f 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>A spend call above an agent's approval threshold now pauses for the owner instead of failing</title>+ <link>https://three.ws/approvals</link>+ <guid isPermaLink="false">2026-10-15:A spend call above an agent's approval threshold now pauses for the owner instead of failing</guid>+ <pubDate>Thu, 15 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The requires_approval verdict agent payment sessions and agent-to-agent hires can already produce now actually does something: both /api/pay/execute and /api/agents/a2a-hire create a request on the existing approval inbox the moment a call crosses the caller's approval_threshold_usd, answer with 202 and a poll link to /approvals/<id> instead of failing the call, and resume automatically the moment the owner taps Approve there, re-probing or re-running the exact same reserve-then-settle path the call would have taken inline, with no re-entry point for a double-spend. A denied request answers 403 on the next poll, an expired one answers 410, and retrying with the same idempotency key before the owner answers just re-polls instead of parking a second request. Nothing new to build on the approval page itself: it already renders any venue generically from the request's summary, amount, and risk notes, so the two new venues (payment_session_execute, a2a_hire) show up with the right Approve/Decline card for free. Covered by 21 new handler tests across create, approve, decline, expire, and the executor's own idempotent re-run.</description>+ </item><item><title>Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts</title><link>https://three.ws/docs/payment-sessions</link>diff --git a/public/features.json b/public/features.jsonindex 369db06a6..4788142b3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-15T00:43:42.269Z",+ "generated_at": "2026-10-15T02:04:13.647Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/a2a-hire-handler.test.js b/tests/a2a-hire-handler.test.jsindex f9fc4e01f..5e6bf3335 100644--- a/tests/a2a-hire-handler.test.js+++ b/tests/a2a-hire-handler.test.js@@ -34,11 +34,12 @@ vi.mock('../api/_lib/rate-limit.js', () => ({clientIp: () => '127.0.0.1',}));-const dbState = { hirer: null };+const dbState = { hirer: null, approval: null };vi.mock('../api/_lib/db.js', () => ({sql: vi.fn(async (strings) => {const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();if (/from agent_identities/.test(q)) return dbState.hirer ? [dbState.hirer] : [];+ if (/from approval_requests/.test(q)) return dbState.approval ? [dbState.approval] : [];return [];}),isDbUnavailableError: () => false,@@ -49,10 +50,26 @@ const offerState = { offer: null };vi.mock('../api/_lib/agent-economy.js', () => ({atomicsToUsdc: (a) => Number(a) / 1e6,getOfferBySlug: vi.fn(async () => offerState.offer),+ getHireById: vi.fn(async () => null),recordHire: vi.fn(async () => ({ row: { id: 'hire-1', status: 'pending' }, existing: false })),updateHire: vi.fn(async () => ({ id: 'hire-1', status: 'failed' })),}));+vi.mock('../api/_lib/real-funds-agreement.js', () => ({+ requireRealFundsAgreement: vi.fn(async () => true),+}));++vi.mock('../api/_lib/approvals.js', () => ({+ createApprovalRequest: vi.fn(async () => ({+ request: { id: 'appr-1', status: 'pending', summary: 'test approval', expires_at: '2026-10-16T00:00:00.000Z' },+ created: true,+ autoApproved: false,+ policy: null,+ })),+ runApproved: vi.fn(async () => ({ request: null, outcome: null })),+ TTL_MS: { transfer: 6 * 60 * 60 * 1000 },+}));+// Spend policy, screen frames, and the payment rails: the hire never reaches the// settlement leg in these tests, but every import still has to resolve.vi.mock('../api/_lib/agent-trade-guards.js', () => ({@@ -61,7 +78,7 @@ vi.mock('../api/_lib/agent-trade-guards.js', () => ({releaseSpendReservation: vi.fn(async () => {}),updateCustodyEvent: vi.fn(async () => {}),recordCustodyEvent: vi.fn(async () => {}),- getSpendLimits: vi.fn(() => ({ per_tx_usd: 5, daily_usd: 25 })),+ getSpendLimits: vi.fn(() => ({ per_tx_usd: 5, daily_usd: 25, approval_threshold_usd: null })),}));vi.mock('../api/_lib/agent-screen-frame.js', () => ({ writeScreenFrame: vi.fn(async () => {}) }));@@ -118,6 +135,7 @@ function ownedHirer() {beforeEach(() => {rateLimitCalls.length = 0;dbState.hirer = null;+ dbState.approval = null;offerState.offer = null;vi.clearAllMocks();});@@ -209,3 +227,212 @@ describe('POST /api/agents/a2a-hire', () => {expect(res.payload.error).toBe('unauthorized');});});++// Order 519: a hire priced above the hiring agent's approval_threshold_usd+// parks on the generic approval inbox instead of paying, and never reserves+// spend while it waits.+describe('POST /api/agents/a2a-hire: human approval above threshold', () => {+ const PRICEY_OFFER = {+ slug: 'pricey', name: 'Pricey skill', service_id: 's2', price_atomics: '2000000',+ network: 'solana', method: 'POST',+ provider: { id: 'provider-1', name: 'Them', is_public: true, solana_address: WALLET },+ };++ it('parks a hire above the threshold instead of paying, without reserving spend', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = PRICEY_OFFER;+ const { getSpendLimits } = await import('../api/_lib/agent-trade-guards.js');+ getSpendLimits.mockReturnValueOnce({ per_tx_usd: 5, daily_usd: 25, approval_threshold_usd: 1 });+ const { recordHire, updateHire } = await import('../api/_lib/agent-economy.js');+ recordHire.mockResolvedValueOnce({ row: { id: 'hire-1', status: 'pending', meta: {} }, existing: false });++ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey' });++ expect(res.statusCode).toBe(202);+ expect(res.payload.pending_approval).toBe(true);+ expect(res.payload.approval.id).toBe('appr-1');++ const { createApprovalRequest } = await import('../api/_lib/approvals.js');+ expect(createApprovalRequest).toHaveBeenCalledWith(expect.objectContaining({+ source: 'a2a_hire',+ sourceRef: 'hire-1',+ venue: 'a2a_hire',+ autoApprovable: false,+ payload: expect.objectContaining({ kind: 'a2a_hire', hire_id: 'hire-1', usd: 2 }),+ }));+ expect(updateHire).toHaveBeenCalledWith('hire-1', { meta: { awaiting_approval: true, approval_id: 'appr-1' } });++ const { reserveSpendUsd } = await import('../api/_lib/agent-trade-guards.js');+ expect(reserveSpendUsd).not.toHaveBeenCalled();+ const { payExternalX402 } = await import('../api/_lib/x402-user-payer.js');+ expect(payExternalX402).not.toHaveBeenCalled();+ });++ it('still pays inline when the price is at or below the threshold', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = PRICEY_OFFER;+ const { getSpendLimits } = await import('../api/_lib/agent-trade-guards.js');+ getSpendLimits.mockReturnValueOnce({ per_tx_usd: 5, daily_usd: 25, approval_threshold_usd: 2 });+ const { recordHire } = await import('../api/_lib/agent-economy.js');+ recordHire.mockResolvedValueOnce({ row: { id: 'hire-1', status: 'pending', meta: {} }, existing: false });++ await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey' });++ const { reserveSpendUsd } = await import('../api/_lib/agent-trade-guards.js');+ expect(reserveSpendUsd).toHaveBeenCalled();+ const { createApprovalRequest } = await import('../api/_lib/approvals.js');+ expect(createApprovalRequest).not.toHaveBeenCalled();+ });++ it('re-polls the parked approval on a retry with the same idempotency key instead of double-parking', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = PRICEY_OFFER;+ dbState.approval = { id: 'appr-1', status: 'pending', summary: 'test approval', expires_at: '2026-10-16T00:00:00.000Z' };+ const { recordHire } = await import('../api/_lib/agent-economy.js');+ recordHire.mockResolvedValueOnce({+ row: { id: 'hire-1', status: 'pending', meta: { awaiting_approval: true, approval_id: 'appr-1' } },+ existing: true,+ });++ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey' });++ expect(res.statusCode).toBe(202);+ expect(res.payload.pending_approval).toBe(true);+ const { createApprovalRequest } = await import('../api/_lib/approvals.js');+ expect(createApprovalRequest).not.toHaveBeenCalled();+ });++ it('reports a denied approval as 403 on retry', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = PRICEY_OFFER;+ dbState.approval = { id: 'appr-1', status: 'denied', summary: 'test approval', expires_at: '2026-10-16T00:00:00.000Z' };+ const { recordHire } = await import('../api/_lib/agent-economy.js');+ recordHire.mockResolvedValueOnce({+ row: { id: 'hire-1', status: 'pending', meta: { awaiting_approval: true, approval_id: 'appr-1' } },+ existing: true,+ });++ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey' });+ expect(res.statusCode).toBe(403);+ expect(res.payload.error).toBe('approval_denied');+ });++ it('reports an expired approval as 410 on retry', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = PRICEY_OFFER;+ dbState.approval = { id: 'appr-1', status: 'expired', summary: 'test approval', expires_at: '2026-10-16T00:00:00.000Z' };+ const { recordHire } = await import('../api/_lib/agent-economy.js');+ recordHire.mockResolvedValueOnce({+ row: { id: 'hire-1', status: 'pending', meta: { awaiting_approval: true, approval_id: 'appr-1' } },+ existing: true,+ });++ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey' });+ expect(res.statusCode).toBe(410);+ expect(res.payload.error).toBe('approval_expired');+ });++ it('returns the retained execution result once the owner approves and the executor finishes', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = PRICEY_OFFER;+ dbState.approval = {+ id: 'appr-1', status: 'executed', summary: 'test approval', expires_at: '2026-10-16T00:00:00.000Z',+ result: { data: { ok: true, hire: { id: 'hire-1', status: 'completed' } } },+ };+ const { recordHire } = await import('../api/_lib/agent-economy.js');+ recordHire.mockResolvedValueOnce({+ row: { id: 'hire-1', status: 'pending', meta: { awaiting_approval: true, approval_id: 'appr-1' } },+ existing: true,+ });++ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey' });+ expect(res.statusCode).toBe(200);+ expect(res.payload.ok).toBe(true);+ expect(res.payload.hire.status).toBe('completed');+ });++ it('still reports pending while the owner has approved but the executor has not run yet', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = PRICEY_OFFER;+ dbState.approval = { id: 'appr-1', status: 'approved', summary: 'test approval', expires_at: '2026-10-16T00:00:00.000Z' };+ const { recordHire } = await import('../api/_lib/agent-economy.js');+ recordHire.mockResolvedValueOnce({+ row: { id: 'hire-1', status: 'pending', meta: { awaiting_approval: true, approval_id: 'appr-1' } },+ existing: true,+ });++ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey' });+ expect(res.statusCode).toBe(202);+ expect(res.payload.approval.status).toBe('approved');+ });+});++// The executor api/_lib/approvals.js registers for source 'a2a_hire': runs+// ONLY after the owner approves, scoped to row.payload, independent of the+// original HTTP request (which already returned 202 and may be long gone).+describe('executeApprovedA2aHire (the a2a_hire approval executor)', () => {+ const OFFER = {+ slug: 'pricey', name: 'Pricey skill', service_id: 's2', price_atomics: '2000000',+ network: 'solana', method: 'POST',+ provider: { id: 'provider-1', name: 'Them', is_public: true, solana_address: WALLET },+ };+ const PAYLOAD = {+ kind: 'a2a_hire', hire_id: 'hire-1', hirer_agent_id: HIRER_ID,+ provider_agent_id: 'provider-1', service_slug: 'pricey', usd: 2, max_usd: null, input: null,+ };++ it('re-runs reserve + pay + finalize and returns a status-ok result with the completed hire', async () => {+ const { executeApprovedA2aHire } = await import('../api/agents/a2a-hire.js');+ const { getHireById, updateHire } = await import('../api/_lib/agent-economy.js');+ offerState.offer = OFFER;+ getHireById.mockResolvedValueOnce({ id: 'hire-1', status: 'pending', usd: 2, service_slug: 'pricey', meta: {} });+ dbState.hirer = ownedHirer();+ updateHire.mockResolvedValueOnce({ id: 'hire-1', status: 'completed', usd: 2 });+ const { payExternalX402 } = await import('../api/_lib/x402-user-payer.js');+ payExternalX402.mockResolvedValueOnce({ receipt: { transaction: 'sig-123' }, payer: WALLET, result: { ok: true } });++ const outcome = await executeApprovedA2aHire({ payload: PAYLOAD });++ expect(outcome.status).toBe('ok');+ expect(outcome.signature).toBe('sig-123');+ expect(outcome.data.ok).toBe(true);+ expect(outcome.data.hire.id).toBe('hire-1');++ const { reserveSpendUsd } = await import('../api/_lib/agent-trade-guards.js');+ expect(reserveSpendUsd).toHaveBeenCalled();+ });++ it('releases the spend reservation and reports status error when the payment fails, without faking a completion', async () => {+ const { executeApprovedA2aHire } = await import('../api/agents/a2a-hire.js');+ const { getHireById } = await import('../api/_lib/agent-economy.js');+ offerState.offer = OFFER;+ getHireById.mockResolvedValueOnce({ id: 'hire-1', status: 'pending', usd: 2, service_slug: 'pricey', meta: {} });+ dbState.hirer = ownedHirer();+ const { payExternalX402 } = await import('../api/_lib/x402-user-payer.js');+ payExternalX402.mockRejectedValueOnce(Object.assign(new Error('upstream 500'), { code: 'payment_failed' }));++ const outcome = await executeApprovedA2aHire({ payload: PAYLOAD });++ expect(outcome.status).toBe('error');+ expect(outcome.note).toMatch(/no funds were moved/);+ const { releaseSpendReservation } = await import('../api/_lib/agent-trade-guards.js');+ expect(releaseSpendReservation).toHaveBeenCalled();+ });++ it('short-circuits to ok without re-paying when the hire is already completed', async () => {+ const { executeApprovedA2aHire } = await import('../api/agents/a2a-hire.js');+ const { getHireById } = await import('../api/_lib/agent-economy.js');+ offerState.offer = OFFER;+ getHireById.mockResolvedValueOnce({+ id: 'hire-1', status: 'completed', usd: 2, service_slug: 'pricey',+ payment_signature: 'sig-already', meta: {},+ });++ const outcome = await executeApprovedA2aHire({ payload: PAYLOAD });++ expect(outcome.status).toBe('ok');+ expect(outcome.signature).toBe('sig-already');+ const { reserveSpendUsd } = await import('../api/_lib/agent-trade-guards.js');+ expect(reserveSpendUsd).not.toHaveBeenCalled();+ });+});diff --git a/tests/agent-custody-guards.test.js b/tests/agent-custody-guards.test.jsindex 11d2361ce..6cd7be178 100644--- a/tests/agent-custody-guards.test.js+++ b/tests/agent-custody-guards.test.js@@ -118,6 +118,15 @@ describe('normalizeSpendLimits', () => {expect(normalizeSpendLimits({ per_tx_usd: 'abc' }).per_tx_usd).toBeNull();});+ // Order 519: a wallet that never sets an approval threshold keeps today's+ // behavior (no human-approval gate on a2a hires); setting one is the minimal+ // threshold check that lets api/agents/a2a-hire.js park a hire above it.+ it('defaults approval_threshold_usd to null and coerces a numeric string', () => {+ expect(normalizeSpendLimits(undefined).approval_threshold_usd).toBeNull();+ expect(normalizeSpendLimits({ approval_threshold_usd: '10' }).approval_threshold_usd).toBe(10);+ expect(normalizeSpendLimits({ approval_threshold_usd: -1 }).approval_threshold_usd).toBeNull();+ });+it('filters invalid + de-dupes allowlist addresses', () => {const a = Keypair.generate().publicKey.toBase58();const n = normalizeSpendLimits({ withdraw_allowlist: [a, 'garbage', a] });diff --git a/tests/pay-execute-approval.test.js b/tests/pay-execute-approval.test.jsnew file mode 100644index 000000000..2f11ccb4b--- /dev/null+++ b/tests/pay-execute-approval.test.js@@ -0,0 +1,292 @@+/**+ * /api/pay/execute: human approval above a payment session's approval threshold.+ *+ * Order 519. A payment session already had a `requires_approval` verdict (the+ * governor's approval-threshold rule in api/_lib/pay/policy.js), but nothing+ * wired it to a human: the governor just rejected the call outright, so an+ * agent whose session carried a threshold could never spend above it, approved+ * or not. This file pins the wiring that uses the existing generic Approval+ * Inbox (api/_lib/approvals.js) instead of a bespoke mechanism:+ *+ * - a call that trips requires_approval parks on the inbox and answers 202+ * with a poll URL, instead of a bare 403,+ * - GET /api/pay/execute?approval_id=&session_token= reports the current+ * state (pending/executed/denied/expired) without re-spending,+ * - the registered executor (api/_lib/approvals.js EXECUTORS.payment_session_execute)+ * re-probes and settles through the exact same settlePayment() path a+ * direct call uses, scoped by approvalGranted:true to lift only the+ * approval-threshold rule, never any other governance check.+ *+ * The network is stubbed at the fetch boundary (same technique as+ * tests/pay-probe-endpoint-error.test.js); the SSRF guard chain is pinned by+ * its own suite. The session/approval persistence is stubbed at the module+ * boundary (api/_lib/pay/spend-governor.js, api/_lib/approvals.js, api/_lib/db.js)+ * so this file exercises execute.js's own orchestration, not Postgres.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Keypair } from '@solana/web3.js';++vi.mock('../api/_lib/ssrf.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ resolvePublicHost: async () => ['203.0.113.10'],+ pinnedAgent: () => ({ destroy: async () => {} }),+ };+});++const reserveState = { impl: null };+vi.mock('../api/_lib/pay/spend-governor.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ verifySessionToken: vi.fn(async () => SESSION),+ reserveSessionSpend: vi.fn(async (args) => reserveState.impl(args)),+ rollbackReservation: vi.fn(async () => {}),+ recordExecution: vi.fn(async () => {}),+ };+});++const approvalState = { row: null };+vi.mock('../api/_lib/approvals.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ createApprovalRequest: vi.fn(async () => ({+ request: {+ id: 'appr-1', status: 'pending', summary: 'test approval',+ expires_at: '2026-10-16T00:00:00.000Z',+ },+ created: true,+ autoApproved: false,+ policy: null,+ })),+ runApproved: vi.fn(async () => ({ request: null, outcome: null })),+ };+});++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async () => (approvalState.row ? [approvalState.row] : [])),+}));++const PAYER = Keypair.generate();+vi.mock('../api/_lib/x402/pay.js', () => ({+ loadSeedKeypair: vi.fn(() => PAYER),+}));++vi.mock('../api/_lib/solana/connection.js', () => ({+ solanaConnection: vi.fn(() => ({})),+}));++const BLOCKHASH = Keypair.generate().publicKey.toBase58();+vi.mock('../api/_lib/solana/read-guards.js', () => ({+ mintDecimals: vi.fn(async () => 6),+ ataExists: vi.fn(async () => true),+ getRecentBlockhash: vi.fn(async () => BLOCKHASH),+ isRpcUnavailable: vi.fn(() => false),+ RPC_RETRY_AFTER_SECONDS: 30,+}));++const { SpendGovernorError } = await import('../api/_lib/pay/spend-governor.js');+const { USDC_SOLANA_MINT } = await import('../api/_lib/pay/probe.js');+const execMod = await import('../api/pay/execute.js');+const { default: handler, executeApprovedPaymentSessionCall, APPROVAL_SOURCE } = execMod;++const SESSION = {+ id: 'sess-1', user_id: 'owner-1', agent_id: null, label: 'my session',+ network: 'solana', spent_usdc: '0', budget_usdc: '100000000',+};++const TARGET_URL = 'https://api.example.com/data';+const PAY_TO = Keypair.generate().publicKey.toBase58();+const FEE_PAYER = Keypair.generate().publicKey.toBase58();++function challengeBody() {+ return JSON.stringify({+ x402Version: 2,+ resource: TARGET_URL,+ accepts: [{+ scheme: 'exact', network: 'solana', amount: '2000000', asset: USDC_SOLANA_MINT,+ payTo: PAY_TO, extra: { feePayer: FEE_PAYER },+ }],+ });+}++function settledResponseHeaders() {+ const payload = { payer: PAYER.publicKey.toBase58(), transaction: 'tx-settled-123' };+ return { 'x-payment-response': Buffer.from(JSON.stringify(payload)).toString('base64') };+}++function queueFetch(...factories) {+ let i = 0;+ globalThis.fetch = vi.fn(async () => factories[Math.min(i++, factories.length - 1)]());+}++function makeReq({ method = 'POST', url = '/api/pay/execute', body = null } = {}) {+ return { method, url, headers: { 'content-type': 'application/json', origin: 'https://three.ws' }, body };+}++function makeRes() {+ return {+ statusCode: 0, payload: null, headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },+ writeHead(code) { this.statusCode = code; return this; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ end(chunk) {+ if (chunk) { try { this.payload = JSON.parse(String(chunk)); } catch { this.payload = String(chunk); } }+ return this;+ },+ };+}++async function post(body) {+ const res = makeRes();+ await handler(makeReq({ body }), res);+ return res;+}++async function get(qs) {+ const res = makeRes();+ await handler(makeReq({ method: 'GET', url: `/api/pay/execute?${qs}` }), res);+ return res;+}++let realFetch;+beforeEach(() => {+ realFetch = globalThis.fetch;+ approvalState.row = null;+ reserveState.impl = async () => {+ throw new SpendGovernorError('requires_approval', 'exceeds threshold', {+ amount_usd: 2, threshold_usd: 1, policy_digest: 'digest', verdict_signature: 'sig', verdict_signed_at: '2026-10-15T00:00:00.000Z',+ });+ };+ vi.clearAllMocks();+});+afterEach(() => { globalThis.fetch = realFetch; vi.restoreAllMocks(); });++describe('POST /api/pay/execute: parks a call above the session approval threshold', () => {+ it('answers 202 with a poll URL instead of a bare 403', async () => {+ queueFetch(() => new Response(challengeBody(), { status: 402 }));+ const res = await post({ session_token: 'pss_11111111-1111-4111-8111-111111111111_abc', url: TARGET_URL });++ expect(res.statusCode).toBe(202);+ expect(res.payload.pending_approval).toBe(true);+ expect(res.payload.approval.id).toBe('appr-1');++ const { createApprovalRequest } = await import('../api/_lib/approvals.js');+ expect(createApprovalRequest).toHaveBeenCalledWith(expect.objectContaining({+ source: APPROVAL_SOURCE,+ venue: 'payment_session_execute',+ autoApprovable: false,+ payload: expect.objectContaining({ kind: 'payment_session_execute', session_id: 'sess-1', url: TARGET_URL }),+ }));+ });++ it('never builds or submits a payment while parked', async () => {+ queueFetch(() => new Response(challengeBody(), { status: 402 }));+ await post({ session_token: 'pss_11111111-1111-4111-8111-111111111111_abc', url: TARGET_URL });+ // Exactly one fetch: the probe. No second fetch for a payment submission.+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ });+});++describe('GET /api/pay/execute: polling a parked approval', () => {+ it('400s without approval_id and session_token', async () => {+ const res = await get('');+ expect(res.statusCode).toBe(400);+ });++ it('404s when no approval matches this session', async () => {+ approvalState.row = null;+ const res = await get('approval_id=11111111-1111-4111-8111-111111111111&session_token=pss_11111111-1111-4111-8111-111111111111_abc');+ expect(res.statusCode).toBe(404);+ });++ it('202s with the current pending status', async () => {+ approvalState.row = {+ id: 'appr-1', status: 'pending', summary: 'test approval',+ expires_at: '2026-10-16T00:00:00.000Z', payload: { session_id: 'sess-1' },+ };+ const res = await get('approval_id=11111111-1111-4111-8111-111111111111&session_token=pss_11111111-1111-4111-8111-111111111111_abc');+ expect(res.statusCode).toBe(202);+ expect(res.payload.pending_approval).toBe(true);+ });++ it('returns the retained result body once executed', async () => {+ approvalState.row = {+ id: 'appr-1', status: 'executed', payload: { session_id: 'sess-1' },+ result: { data: { ok: true, paid: true, note: 'settled' } },+ };+ const res = await get('approval_id=11111111-1111-4111-8111-111111111111&session_token=pss_11111111-1111-4111-8111-111111111111_abc');+ expect(res.statusCode).toBe(200);+ expect(res.payload).toEqual({ ok: true, paid: true, note: 'settled' });+ });++ it('403s a denied approval', async () => {+ approvalState.row = { id: 'appr-1', status: 'denied', payload: { session_id: 'sess-1' } };+ const res = await get('approval_id=11111111-1111-4111-8111-111111111111&session_token=pss_11111111-1111-4111-8111-111111111111_abc');+ expect(res.statusCode).toBe(403);+ expect(res.payload.error).toBe('approval_denied');+ });++ it('410s an expired approval', async () => {+ approvalState.row = { id: 'appr-1', status: 'expired', payload: { session_id: 'sess-1' } };+ const res = await get('approval_id=11111111-1111-4111-8111-111111111111&session_token=pss_11111111-1111-4111-8111-111111111111_abc');+ expect(res.statusCode).toBe(410);+ expect(res.payload.error).toBe('approval_expired');+ });+});++describe('executeApprovedPaymentSessionCall: the payment_session_execute approval executor', () => {+ it('re-probes, settles with approvalGranted bypassing only the threshold rule, and returns the result', async () => {+ reserveState.impl = async ({ approvalGranted }) => {+ expect(approvalGranted).toBe(true);+ return {+ session: { id: 'sess-1', user_id: 'owner-1', spent_usdc: '2000000', budget_usdc: '100000000' },+ railReservationId: 'rail-1', policyDigest: 'digest', verdictCode: 'ok',+ verdictSignature: 'sig2', verdictSignedAt: '2026-10-15T00:00:01.000Z',+ };+ };+ queueFetch(+ () => new Response(challengeBody(), { status: 402 }),+ () => new Response(JSON.stringify({ served: true }), { status: 200, headers: settledResponseHeaders() }),+ );++ const outcome = await executeApprovedPaymentSessionCall({+ payload: {+ kind: 'payment_session_execute', session_id: 'sess-1', url: TARGET_URL,+ method: 'GET', body: null, idempotency_key: null,+ },+ });++ expect(outcome.status).toBe('ok');+ expect(outcome.signature).toBe('tx-settled-123');+ expect(outcome.data.ok).toBe(true);+ expect(outcome.data.paid).toBe(true);+ });++ it('reports status error without faking a completion when settlement fails', async () => {+ reserveState.impl = async () => ({+ session: { id: 'sess-1', user_id: 'owner-1', spent_usdc: '2000000', budget_usdc: '100000000' },+ railReservationId: 'rail-1', policyDigest: 'digest', verdictCode: 'ok',+ verdictSignature: 'sig2', verdictSignedAt: '2026-10-15T00:00:01.000Z',+ });+ queueFetch(+ () => new Response(challengeBody(), { status: 402 }),+ () => new Response(JSON.stringify({ error: 'rejected' }), { status: 402 }),+ );++ const outcome = await executeApprovedPaymentSessionCall({+ payload: {+ kind: 'payment_session_execute', session_id: 'sess-1', url: TARGET_URL,+ method: 'GET', body: null, idempotency_key: null,+ },+ });++ expect(outcome.status).toBe('error');+ });+});