Skip to content

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.

feat(wallet): add Solana agent allowances with an on-chain allowance store, x402 prepaid reconcile script, agent upgrade billing, CLI signup, and the x-video page

nirholased75c5946ca0
diff --git a/.claude/agents/x402-economy-triage.md b/.claude/agents/x402-economy-triage.md
index db269d9e2..6e847fe83 100644
--- a/.claude/agents/x402-economy-triage.md
+++ b/.claude/agents/x402-economy-triage.md
@@ -26,9 +26,11 @@ You triage the three.ws x402 agent economy. Do not guess; run the checks in this
5. **Solana RPC lane exhaustion (upstream of classes 1 and 3).** Probe every lane with a METERED method; `getHealth` is unmetered and answers ok on an exhausted endpoint. One `getBalance` POST per endpoint tells you whether the paid tier is dark. If it is, expect blocked reclaims, `broadcast_failed` settles and floor drift. Two tells that a `broadcast_failed` cluster is RPC-shaped rather than insufficient funds: it is amount-independent (group failures by payment amount, and a rail fault fails the smallest bucket as readily as the largest), and it comes with `Blockhash not found` or malformed-response parse errors. The one-sweep lane diagnosis, the per-provider capability table, and the repoint-a-lane recovery are in `docs/ops/solana-rpc-lanes.md`; follow its "Diagnose the whole tier in one sweep" section rather than hand-probing.
+6. **Prepaid rail (batch settlement and ledger).** Applies when buyers report a balance that did not move, a charge for a failed call, or sellers not being paid. Run `node scripts/x402-prepaid-reconcile.mjs` first (add `--chain` to compare the deposit wallet's real USDC). Read the `PROBLEMS:` line: `balance_delta`/`drifted_accounts` mean the ledger arithmetic is broken (stop and escalate, do not hand-edit rows); `stale_reservations` means requests died mid-flight and the settle cron has not swept them (check the `x402-prepaid-settle` scheduler job ran); `stuck_batches` or batches in `unconfirmed` mean a send may have landed, so look the memo (batch ids) up on-chain before anything is released, never re-send; `wallet_short_of_held` means the deposit wallet holds less USDC than the ledger owes. If settle runs but nothing pays out, `X402_PREPAID_SETTLE_LIVE` is not `1` or `X402_PREPAID_SETTLER_SECRET_BASE58` is unset (the cron then only plans; this is deliberate, enabling it is an owner action), or every seller is under `X402_PREPAID_MIN_SETTLE_ATOMICS`. A settler below its SOL floor fails with the usual signer-balance error, and that is a funding fix on the settler only. Tables are `x402_prepaid_accounts`, `x402_prepaid_entries`, `x402_prepaid_batches`; design in `docs/ops/x402-prepaid.md`.
+
## Ground truth sources
-- `x402_self_facilitator_log` (Neon, `DATABASE_URL` in `.env.local`, never `.env`, which holds only the QA login) for per-settle outcomes, amounts and error strings. It is the ground truth for classes 1, 3 and 5.
+- `x402_self_facilitator_log` (Neon, `DATABASE_URL` in `.env.local`, never `.env`, which holds only the QA login) for per-settle outcomes, amounts and error strings. It is the ground truth for classes 1, 3 and 5. For class 6 the ground truth is the `x402_prepaid_*` tables.
- Cloud Run env is authoritative. Every credential there is a Secret Manager reference, so `describe` shows `valueFrom` instead of a value: read one with `node scripts/read-service-env.mjs '^NAME$' --raw`. Never trust `vercel env pull`.
- `docs/ops/production-log-triage.md` maps known log signatures to causes; check it before inventing a new failure class.
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 7051b6021..1512296c6 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -42,6 +42,7 @@ packages, a generated standalone GitHub mirror). See
| Pocket Console (`/pocket`) | [pages/pocket.html](pages/pocket.html) `→ /pocket`, app [src/pocket.js](src/pocket.js), styles [src/pocket.css](src/pocket.css), screen [pages/walk-embed.html](pages/walk-embed.html) via the typed contract in [src/walk-embed-events.js](src/walk-embed-events.js) | Live | A handheld with a live 3D agent inside the screen, built for the thing people actually share: the D-pad walks the agent, A waves, B jumps, L/R change the cartridge, START swaps the screen between PLAY, STATS (the agent record read live) and SELECT (a game menu over `GET /api/agents/public`), and the power LED is a real switch that unmounts the frame so an off screen stops rendering. Keyboard, touch and the Gamepad API drive the same controls. Four shell finishes and four scenes, all carried in the URL, so a share link is the device as you left it. `?chrome=off` is the embed: the device alone on a transparent background with no nav, footer or language pill, addressed by avatar id so the GLB streams through the same-origin proxy and renders identically on a third-party domain. The screen runs the walk embed at `zoom=0.74` (the param this surface added, documented in [docs/tutorials/walk-companion.md](docs/tutorials/walk-companion.md)). Docs: [docs/pocket.md](docs/pocket.md) |
| Live Docs (runnable code samples) | Pure decisions [public/docs-live-core.js](public/docs-live-core.js), runner [public/docs-live.js](public/docs-live.js), styles [public/docs-live.css](public/docs-live.css), mounted by the docs viewer [docs/index.html](docs/index.html) | Live | Every code sample across the ~318 documentation pages is editable, and the runnable ones execute in place: an `html` snippet containing `<agent-3d>` renders a real animated avatar in a sandboxed frame directly under the code, a single-`curl` `bash` block sends a real request and reports status, latency, size, body and response headers, and a `js` snippet runs as a module with its console streamed back. Slots such as `$API_KEY` or `<agent-id>` become input fields, with credential-shaped names held in memory and never written to storage. The safety split is the design: everything deciding what a reader may fire lives in the pure core and is unit-tested rather than trusted to a click handler. Only three.ws hosts are reachable, any path that can move funds or mint is refused outright on every verb, writes arm before they send, every fetch goes out with `credentials: omit`, and frames run `sandbox="allow-scripts"` without `allow-same-origin`. Authors opt a block out with `<!-- live:off -->`. Loaded lazily after the first page render, so a page with no runnable samples costs nothing. Docs: [docs/live-docs.md](docs/live-docs.md) `→ /docs/live-docs`. Tests: [tests/docs-live-core.test.js](tests/docs-live-core.test.js) |
| Docs World (immersive 3D docs) | [pages/docs-world.html](pages/docs-world.html) `→ /docs/world`, app [src/docs-world/](src/docs-world) (world/player/controls/overlays), styles [public/docs-world.css](public/docs-world.css), shared manifest [docs/nav.json](docs/nav.json) | Live | The documentation as a walkable place: each section of the docs sidebar is a glowing pavilion on a ring; walk up (WASD / touch joystick, four shared camera modes via [src/game/camera-modes.js](src/game/camera-modes.js)) or tap one to list its pages, and read the live markdown in an in-world DOM reader ([src/shared/markdown.js](src/shared/markdown.js)). One content source: both surfaces read `docs/nav.json` + `/docs/<slug>.md`, so classic and immersive docs cannot drift. Deep links mirror the classic hash routes (`/docs/world#forge`); the classic header's "3D world" button carries the open page across. Avatar is the platform's default rigged body (the same one `/walk` uses, since the agent mannequin ships unskinned and cannot be clip-driven) or any rigged GLB via `?avatar=`, animated by the canonical clip library. No-WebGL devices get a designed fallback routing to `/docs`. Docs: [docs/docs-world.md](docs/docs-world.md). Tests: [tests/docs-world.test.js](tests/docs-world.test.js) |
+| x402 prepaid balances and batch settlement | ledger [api/_lib/x402/prepaid-ledger.js](api/_lib/x402/prepaid-ledger.js), batcher [api/_lib/x402/prepaid-settle.js](api/_lib/x402/prepaid-settle.js), chain legs [api/_lib/x402/prepaid-chain.js](api/_lib/x402/prepaid-chain.js), route hook [api/_lib/x402/prepaid-route.js](api/_lib/x402/prepaid-route.js) (`paidEndpoint({ mode: 'prepaid' })`), endpoints [api/x402-prepaid/](api/x402-prepaid), crons [x402-prepaid-settle](api/cron/x402-prepaid-settle.js) and [x402-prepaid-reconcile](api/cron/x402-prepaid-reconcile.js), reconcile CLI [scripts/x402-prepaid-reconcile.mjs](scripts/x402-prepaid-reconcile.mjs), migration [api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql](api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql) | Built; live settlement gated on the owner | A buyer deposits USDC once and each paid call debits a ledger row (never negative, charged only on success), then one Solana transaction per window pays every seller above a floor, so cent-sized calls stop starving the settle floor. A nightly reconciliation proves deposits minus debits minus settled equals held and alerts on any drift. Docs: [docs/ops/x402-prepaid.md](docs/ops/x402-prepaid.md). Tests: [tests/x402-prepaid-ledger.test.js](tests/x402-prepaid-ledger.test.js) |
| Prompt library (`/prompts`) | Source [data/prompt-library.json](data/prompt-library.json), builder [scripts/build-prompt-library.mjs](scripts/build-prompt-library.mjs) → `public/prompts.json` + `public/prompts.txt`, page [pages/prompts.html](pages/prompts.html) `→ /prompts` + [src/prompt-library/](src/prompt-library) (page.js, page.css) | Live | Prompts written to be copied out and pasted into someone else's assistant, grouped by what they build (3D models and rigged avatars, site embeds, the x402 economy, platform integrations) and by what they need first (nothing at all, the free MCP server, the skills pack, a funded wallet). Every prompt names a real endpoint or tool, says what to do when a job comes back pending, and says what to hand back; the ones that can spend money are written so the assistant stops and shows the amount and the recipient first. Each card copies to the clipboard or opens straight in claude.ai with the text already in the box, and the whole library is fetchable as `/prompts.json` or `/prompts.txt` so an agent can read it without scraping. The builder validates the data on every build (unique kebab-case ids, known category and setup, balanced `<placeholder>` brackets, internal links that resolve to routes in [data/pages.json](data/pages.json)) and `npm run check:prompt-library` holds the published copies in sync inside `npm run gate`. Docs: [docs/prompts.md](docs/prompts.md) `→ /docs/prompts`. Tests: [tests/prompt-library.test.js](tests/prompt-library.test.js) |
| React avatar creator | [avatar-sdk/](avatar-sdk) `→ /react` `/creator` | Published as `@three-ws/avatar` | Same package, React subpath |
| Avatar CLI (manifests in the build pipeline) | [packages/avatar-cli/](packages/avatar-cli), landing [pages/avatar-cli.html](pages/avatar-cli.html) `→ /avatar-cli`, styles [public/avatar-cli.css](public/avatar-cli.css), page runtime [src/avatar-cli-page.js](src/avatar-cli-page.js) | Published as `@three-ws/avatar-cli` | The terminal half of the avatar story, and the half that makes an avatar auditable. Four commands over one file: `init` scaffolds a schema-valid manifest from a wallet plus a mesh (reading the GLB once to compute its SHA-256 and size, so the document cannot disagree with the bytes it was built from), `validate` checks it against [packages/avatar-schema/](packages/avatar-schema) and exits non-zero so it works as a build gate, `hash` prints a bare digest that composes in a shell, and `preview` emits a resolver URL, an `<agent-3d>` snippet paired with the loader that registers it, and a zero-install iframe. Offline and deterministic throughout: no account, no API key, no network call, which is what makes it safe in a release script. `preview` warns instead of printing a dead snippet when `mesh.uri` is still a local `file://` path. The landing page proves the emitted markup by rendering it live rather than screenshotting it. Docs: [docs/avatar-cli.md](docs/avatar-cli.md) `→ /docs/avatar-cli`, tutorial [docs/tutorials/ship-an-avatar-manifest.md](docs/tutorials/ship-an-avatar-manifest.md). Tests: [packages/avatar-cli/test/](packages/avatar-cli/test) |
diff --git a/api/_lib/migrations/20261023170000_agent_onchain_allowances.sql b/api/_lib/migrations/20261023170000_agent_onchain_allowances.sql
new file mode 100644
index 000000000..b2ca15dc9
--- /dev/null
+++ b/api/_lib/migrations/20261023170000_agent_onchain_allowances.sql
@@ -0,0 +1,37 @@
+begin;
+
+-- Owner-funded agent budgets enforced by the Solana Subscriptions and
+-- Allowances program. The chain is the source of truth for what is left; this
+-- table only remembers which delegation accounts belong to which agent, and the
+-- cap at creation (the program stores only the remaining amount), so the UI can
+-- show cap / spent / remaining and the guards know which PDA to read.
+--
+-- Writers: api/agents/solana-allowance.js (confirm, revoke)
+-- Readers: api/agents/solana-allowance.js, api/agent/guard.js
+
+create table if not exists agent_onchain_allowances (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ network text not null check (network in ('mainnet', 'devnet')),
+ kind text not null default 'fixed' check (kind in ('fixed', 'recurring')),
+ owner_wallet text not null,
+ delegatee text not null,
+ mint text not null,
+ nonce numeric(40, 0) not null,
+ delegation_pda text not null,
+ cap_raw numeric(40, 0) not null check (cap_raw > 0),
+ expiry_ts bigint not null default 0,
+ period_length_s bigint,
+ create_signature text,
+ revoke_signature text,
+ revoked_at timestamptz,
+ created_at timestamptz not null default now(),
+ unique (network, delegation_pda)
+);
+
+create index if not exists agent_onchain_allowances_agent
+ on agent_onchain_allowances (agent_id, network)
+ where revoked_at is null;
+
+commit;
diff --git a/api/_lib/onchain-allowance-store.js b/api/_lib/onchain-allowance-store.js
new file mode 100644
index 000000000..f19b99fa0
--- /dev/null
+++ b/api/_lib/onchain-allowance-store.js
@@ -0,0 +1,95 @@
+// Persistence + guard hook for owner-funded on-chain allowances.
+// Pure chain access lives in onchain-allowance.js; this module maps agents to
+// their delegation accounts (agent_onchain_allowances) and exposes the
+// "remaining allowance is a hard ceiling" check the spend guards call.
+
+import { sql } from './db.js';
+import { checkAllowancePull } from './onchain-allowance.js';
+
+const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+export function viewRow(r) {
+ return {
+ id: r.id,
+ agentId: r.agent_id,
+ network: r.network,
+ kind: r.kind,
+ ownerWallet: r.owner_wallet,
+ delegatee: r.delegatee,
+ mint: r.mint,
+ nonce: String(r.nonce),
+ delegationPda: r.delegation_pda,
+ capRaw: String(r.cap_raw),
+ expiryTs: Number(r.expiry_ts),
+ periodLengthS: r.period_length_s == null ? null : Number(r.period_length_s),
+ createSignature: r.create_signature,
+ revokeSignature: r.revoke_signature,
+ revokedAt: r.revoked_at,
+ createdAt: r.created_at,
+ };
+}
+
+export async function listAllowances(agentId, network, { includeRevoked = false } = {}) {
+ const rows = await sql`
+ SELECT * FROM agent_onchain_allowances
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND (${includeRevoked} OR revoked_at IS NULL)
+ ORDER BY created_at DESC
+ LIMIT 50
+ `;
+ return rows.map(viewRow);
+}
+
+export async function getAllowance(agentId, id) {
+ const [row] = await sql`SELECT * FROM agent_onchain_allowances WHERE id = ${id} AND agent_id = ${agentId}`;
+ return row ? viewRow(row) : null;
+}
+
+/** Idempotent on (network, delegation_pda): a repeated confirm never resets the recorded cap. */
+export async function recordAllowance(a) {
+ const [row] = await sql`
+ INSERT INTO agent_onchain_allowances
+ (agent_id, user_id, network, kind, owner_wallet, delegatee, mint, nonce,
+ delegation_pda, cap_raw, expiry_ts, period_length_s, create_signature)
+ VALUES (${a.agentId}, ${a.userId}, ${a.network}, ${a.kind}, ${a.ownerWallet}, ${a.delegatee}, ${a.mint},
+ ${String(a.nonce)}, ${a.delegationPda}, ${String(a.capRaw)}, ${a.expiryTs}, ${a.periodLengthS ?? null},
+ ${a.createSignature ?? null})
+ ON CONFLICT (network, delegation_pda) DO UPDATE SET create_signature = COALESCE(agent_onchain_allowances.create_signature, EXCLUDED.create_signature)
+ RETURNING *
+ `;
+ return viewRow(row);
+}
+
+export async function markRevoked(id, signature) {
+ const [row] = await sql`
+ UPDATE agent_onchain_allowances
+ SET revoked_at = COALESCE(revoked_at, now()), revoke_signature = COALESCE(revoke_signature, ${signature ?? null})
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ return row ? viewRow(row) : null;
+}
+
+/**
+ * Hard ceiling for the spend guards. An agent with no active allowance for the
+ * mint is not gated (the feature is owner opt-in, like every other cap). With
+ * one on file, the live on-chain remaining amount decides: a pull the program
+ * would reject is refused here, before any transaction is built.
+ *
+ * With several active allowances for the same mint the request is checked
+ * against each and allowed if any one of them covers it; `allowance` names the
+ * one a pull should use.
+ */
+export async function checkAgentAllowanceSpend({ agentId, network = 'mainnet', mint, amount, connection = null }) {
+ if (typeof mint !== 'string' || !SOLANA_ADDRESS_RE.test(mint)) return { gated: false };
+ const active = (await listAllowances(agentId, network)).filter((a) => a.mint === mint);
+ if (active.length === 0) return { gated: false };
+
+ let lastRefusal = null;
+ for (const a of active) {
+ const verdict = await checkAllowancePull({ network, kind: a.kind, delegationPda: a.delegationPda, amount, connection });
+ if (verdict.allow) return { gated: true, allow: true, code: verdict.code, reason: verdict.reason, detail: verdict.detail, allowance: a, live: verdict.live };
+ lastRefusal = { ...verdict, allowance: a };
+ }
+ return { gated: true, allow: false, code: lastRefusal.code, reason: lastRefusal.reason, detail: lastRefusal.detail, allowance: lastRefusal.allowance, live: lastRefusal.live };
+}
diff --git a/api/_lib/onchain-allowance.js b/api/_lib/onchain-allowance.js
index 632b204d3..334be1d01 100644
--- a/api/_lib/onchain-allowance.js
+++ b/api/_lib/onchain-allowance.js
@@ -33,7 +33,6 @@ import {
getTransferFixedOverlayInstructionAsync,
getTransferRecurringOverlayInstructionAsync,
getSubscriptionsErrorMessage,
- isSubscriptionsError,
} from '@solana/subscriptions';
export const ALLOWANCE_PROGRAM_ID = SUBSCRIPTIONS_PROGRAM_ADDRESS;
@@ -415,19 +414,20 @@ export async function buildSignedPull({ network = 'mainnet', kind = 'fixed', del
}
/**
- * Translate a program rejection (simulation logs or a thrown RPC error) into the
- * program's own message, e.g. AmountExceedsLimit after a pull above the cap.
+ * Translate a program rejection (simulation error plus logs, or a thrown RPC
+ * error) into a message an owner can act on: the program's own text for its
+ * custom errors (e.g. "Transfer amount exceeds delegation limit"), and a plain
+ * explanation when the delegation account has been closed by a revoke.
*/
export function describeProgramFailure(err) {
const msg = String(err?.message ?? err ?? '');
- const custom = msg.match(/custom program error: 0x([0-9a-f]+)/i) || msg.match(/"Custom":\s*(\d+)/);
- if (custom) {
- const code = custom[1].length && /^[0-9a-f]+$/i.test(custom[1]) && msg.includes('0x') ? parseInt(custom[1], 16) : Number(custom[1]);
- try {
- if (isSubscriptionsError({ context: { code } }, code)) return getSubscriptionsErrorMessage(code);
- } catch {
- // fall through to the raw message
- }
+ if (msg.includes('InvalidAccountOwner')) {
+ return 'the allowance account no longer exists on chain (revoked or closed)';
+ }
+ const hex = msg.match(/custom program error: 0x([0-9a-f]+)/i);
+ const dec = msg.match(/"Custom":\s*(\d+)/);
+ const code = hex ? parseInt(hex[1], 16) : dec ? Number(dec[1]) : null;
+ if (code != null) {
try {
return getSubscriptionsErrorMessage(code);
} catch {
diff --git a/api/_lib/x402/prepaid-chain.js b/api/_lib/x402/prepaid-chain.js
index dc269b7a2..2162203a8 100644
--- a/api/_lib/x402/prepaid-chain.js
+++ b/api/_lib/x402/prepaid-chain.js
@@ -25,12 +25,9 @@ import { ataExists } from '../solana/read-guards.js';
import { submitProtected } from '../execution-engine.js';
import { tokenProgramIdForMint } from '../token/token-program.js';
import { loadSignerKeypair, SOLANA_SIGNERS } from '../solana-signers.js';
-import { NETWORK_SOLANA_MAINNET } from '../x402-spec.js';
+import { PREPAID_NETWORK, USDC_MINT_SOLANA, USDC_DECIMALS, PREPAID_ASSET } from './prepaid-constants.js';
-export const PREPAID_NETWORK = NETWORK_SOLANA_MAINNET;
-export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
-export const USDC_DECIMALS = 6;
-export const PREPAID_ASSET = USDC_MINT_SOLANA;
+export { PREPAID_NETWORK, USDC_MINT_SOLANA, USDC_DECIMALS, PREPAID_ASSET };
const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
const SETTLER_SPEC = SOLANA_SIGNERS.find((s) => s.name === 'x402-prepaid-settler');
diff --git a/api/_lib/x402/prepaid-constants.js b/api/_lib/x402/prepaid-constants.js
new file mode 100644
index 000000000..79fd96fe7
--- /dev/null
+++ b/api/_lib/x402/prepaid-constants.js
@@ -0,0 +1,12 @@
+// api/_lib/x402/prepaid-constants.js
+//
+// Network and asset the prepaid rail runs on. Kept free of chain imports so the
+// ledger, the route hook and the tests can read them without loading the
+// transaction stack. Solana only; USDC only.
+
+import { NETWORK_SOLANA_MAINNET } from './solana-networks.js';
+
+export const PREPAID_NETWORK = NETWORK_SOLANA_MAINNET;
+export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+export const USDC_DECIMALS = 6;
+export const PREPAID_ASSET = USDC_MINT_SOLANA;
diff --git a/api/_lib/x402/prepaid-ledger.js b/api/_lib/x402/prepaid-ledger.js
index fd0b5f3f4..aa0917542 100644
--- a/api/_lib/x402/prepaid-ledger.js
+++ b/api/_lib/x402/prepaid-ledger.js
@@ -244,7 +244,7 @@ export async function reconcile({ stuckBatchMinutes = 30 } = {}) {
(select count(*) from x402_prepaid_entries where state = 'reserved'
and created_at < now() - make_interval(secs => ${PREPAID_RESERVATION_TTL_SECONDS}::double precision))::int as stale,
(select count(*) from x402_prepaid_batches where status in ('pending', 'unconfirmed')
- and created_at < now() - make_interval(mins => ${Number(stuckBatchMinutes)}::double precision))::int as stuck
+ and created_at < now() - make_interval(secs => ${Number(stuckBatchMinutes) * 60}::double precision))::int as stuck
`;
const drifted = await sql`
select a.payer, a.network, a.asset,
diff --git a/api/_lib/x402/prepaid-reconcile.js b/api/_lib/x402/prepaid-reconcile.js
index 8a1b4c270..b7201d0e6 100644
--- a/api/_lib/x402/prepaid-reconcile.js
+++ b/api/_lib/x402/prepaid-reconcile.js
@@ -5,7 +5,6 @@
// scripts/x402-prepaid-reconcile.mjs.
import { reconcile } from './prepaid-ledger.js';
-import { depositWalletUsdcBalance } from './prepaid-chain.js';
const usd = (a) => (Number(a) / 1e6).toFixed(6);
@@ -25,6 +24,7 @@ export async function reconcileReport({ checkChain = false } = {}) {
let chainBalance = null;
if (checkChain) {
+ const { depositWalletUsdcBalance } = await import('./prepaid-chain.js');
chainBalance = await depositWalletUsdcBalance();
if (chainBalance !== null && chainBalance < r.heldAtomics) problems.push('wallet_short_of_held');
}
diff --git a/api/_lib/x402/prepaid-route.js b/api/_lib/x402/prepaid-route.js
index 3ba925866..bc529f117 100644
--- a/api/_lib/x402/prepaid-route.js
+++ b/api/_lib/x402/prepaid-route.js
@@ -23,7 +23,7 @@ import {
refundDebit,
reserveDebit,
} from './prepaid-ledger.js';
-import { USDC_MINT_SOLANA } from './prepaid-chain.js';
+import { USDC_MINT_SOLANA } from './prepaid-constants.js';
export const PREPAID_EXTENSION_KEY = 'prepaid';
diff --git a/api/agent/guard.js b/api/agent/guard.js
index 8769994f0..423f52210 100644
--- a/api/agent/guard.js
+++ b/api/agent/guard.js
@@ -29,6 +29,7 @@ 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';
+import { checkAgentAllowanceSpend } from '../_lib/onchain-allowance-store.js';
const MAX_CALLS = 20;
const SOL_MINT = 'So11111111111111111111111111111111111111112';
@@ -272,7 +273,38 @@ export default wrap(async function handler(req, res) {
}
}
- verdicts.push({ apiName: call.apiName, identifier: call.identifier, verdict, delegation });
+ // An owner-funded on-chain allowance is a hard ceiling on pulls from the
+ // owner's wallet: the live remaining amount is read from the program's
+ // own account, so a pull the program would reject is refused here, before
+ // any transaction is built. Only `allowance_pull` calls are measured.
+ let allowance;
+ if (isUuid(agentId) && call.apiName === 'allowance_pull') {
+ const mint = call.arguments?.mint ?? call.token;
+ const amount = call.arguments?.amountRaw ?? call.arguments?.amount_raw;
+ try {
+ const result = await checkAgentAllowanceSpend({ agentId, network: body.network || 'mainnet', mint, amount });
+ if (result.gated) {
+ allowance = {
+ allow: result.allow,
+ code: result.code,
+ reason: result.reason,
+ detail: result.detail,
+ allowanceId: result.allowance?.id,
+ remaining: result.live?.remaining,
+ };
+ if (!result.allow && verdict.decision !== 'block') {
+ verdict.decision = 'block';
+ verdict.blockedBy = 'onchain_allowance';
+ verdict.code = result.code;
+ verdict.reason = result.reason;
+ }
+ }
+ } catch (e) {
+ verdict.blindSpots = [...(verdict.blindSpots || []), `onchain allowance unreadable: ${e?.message || 'rpc error'}`];
+ }
+ }
+
+ verdicts.push({ apiName: call.apiName, identifier: call.identifier, verdict, delegation, allowance });
}
const payload = { engine: '@three-ws/agent-runtime', verdicts };
diff --git a/api/agents/solana-allowance.js b/api/agents/solana-allowance.js
new file mode 100644
index 000000000..6dd4cce28
--- /dev/null
+++ b/api/agents/solana-allowance.js
@@ -0,0 +1,291 @@
+// Owner-funded agent budgets enforced on-chain by the Solana Subscriptions and
+// Allowances program. Dispatched from api/agents/solana-wallet.js with the
+// `allowance` action. Docs: docs/agent-allowance-budgets.md
+//
+// The owner keeps funds in their own wallet. The server only ever PREPARES the
+// owner's transactions (create, revoke) and returns them unsigned; the owner
+// signs in their own wallet. The agent pulls with its custodial key, and only
+// after the live on-chain remaining amount has cleared the guard ceiling.
+//
+// GET /allowance[?network=] list allowances with live status
+// POST /allowance { op: 'prepare', mint, amount, expiresInDays, kind?, ... }
+// POST /allowance { op: 'confirm', signature, delegationPda, nonce, ... }
+// POST /allowance { op: 'revoke', id } unsigned revoke tx for the owner
+// POST /allowance { op: 'revoked', id, signature } record a confirmed revoke
+// POST /allowance { op: 'pull', id, amount } agent pulls within the cap
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
+import { solanaConnection } from '../_lib/agent-pumpfun.js';
+import { confirmOrThrow } from '../_lib/solana/confirm.js';
+import { logAudit } from '../_lib/audit.js';
+import { recordCustodyEvent } from '../_lib/agent-trade-guards.js';
+import {
+ AllowanceError,
+ prepareCreateAllowance,
+ prepareRevokeAllowance,
+ readAllowance,
+ checkAllowancePull,
+ buildSignedPull,
+ describeProgramFailure,
+ recurringEnabled,
+} from '../_lib/onchain-allowance.js';
+import { listAllowances, getAllowance, recordAllowance, markRevoked, checkAgentAllowanceSpend } from '../_lib/onchain-allowance-store.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const MAX_EXPIRY_DAYS = 365;
+const ERROR_STATUS = {
+ invalid_request: 400,
+ feature_disabled: 403,
+ mint_not_found: 404,
+ allowance_not_found: 404,
+ mint_unsupported: 422,
+};
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ assertBearerMaySpend(bearer, req);
+ return { userId: bearer.userId };
+}
+
+async function loadOwnedAgent(req, res, id) {
+ const auth = await resolveAuth(req);
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return null; }
+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return null; }
+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'not your agent'); return null; }
+ return { auth, meta: row.meta || {}, address: row.meta?.solana_address || null };
+}
+
+async function ownerWallets(userId) {
+ const rows = await sql`SELECT address FROM user_wallets WHERE user_id = ${userId} AND chain_type = 'solana'`;
+ return rows.map((r) => r.address);
+}
+
+function statusOf(row, live) {
+ if (row.revokedAt) return 'revoked';
+ if (!live) return 'closed';
+ if (live.expired) return 'expired';
+ if (BigInt(live.remaining) === 0n) return 'exhausted';
+ return 'active';
+}
+
+function toRaw(humanAmount, decimals) {
+ const s = String(humanAmount ?? '').trim();
+ if (!/^\d+(\.\d+)?$/.test(s)) throw new AllowanceError('invalid_request', 'amount must be a positive decimal number');
+ const [whole, frac = ''] = s.split('.');
+ if (frac.length > decimals) throw new AllowanceError('invalid_request', `this token supports at most ${decimals} decimal places`);
+ const raw = BigInt(whole + frac.padEnd(decimals, '0'));
+ if (raw <= 0n) throw new AllowanceError('invalid_request', 'amount must be greater than zero');
+ return raw;
+}
+
+async function mintDecimals(conn, mint) {
+ const { getMint } = await import('@solana/spl-token');
+ const { PublicKey } = await import('@solana/web3.js');
+ const info = await conn.getAccountInfo(new PublicKey(mint), 'confirmed');
+ if (!info) throw new AllowanceError('mint_not_found', 'that token mint does not exist on this network');
+ return (await getMint(conn, new PublicKey(mint), 'confirmed', info.owner)).decimals;
+}
+
+async function present(row) {
+ let live = null;
+ let liveError = null;
+ if (!row.revokedAt) {
+ try {
+ live = await readAllowance({ network: row.network, kind: row.kind, delegationPda: row.delegationPda });
+ } catch (e) {
+ liveError = e?.message || 'rpc error';
+ }
+ }
+ const cap = BigInt(row.capRaw);
+ const remaining = live ? BigInt(live.remaining) : 0n;
+ return {
+ ...row,
+ status: liveError ? 'unknown' : statusOf(row, live),
+ remainingRaw: live ? remaining.toString() : null,
+ spentRaw: live ? (cap > remaining ? cap - remaining : 0n).toString() : null,
+ expired: live?.expired ?? false,
+ liveError,
+ };
+}
+
+export async function handleAllowance(req, res, id) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const owned = await loadOwnedAgent(req, res, id);
+ if (!owned) return;
+ const { auth, address } = owned;
+
+ const rl = await limits.walletRead(auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+
+ if (req.method === 'GET') {
+ const network = url.searchParams.get('network') || 'mainnet';
+ if (!NETWORKS.has(network)) return error(res, 400, 'invalid_request', 'network must be mainnet or devnet');
+ const rows = await listAllowances(id, network, { includeRevoked: url.searchParams.get('history') === '1' });
+ const conn = rows.length ? solanaConnection(network) : null;
+ const decimalsByMint = new Map();
+ for (const mint of new Set(rows.map((r) => r.mint))) {
+ decimalsByMint.set(mint, await mintDecimals(conn, mint).catch(() => null));
+ }
+ const allowances = (await Promise.all(rows.map(present))).map((a) => ({ ...a, decimals: decimalsByMint.get(a.mint) ?? null }));
+ return json(res, 200, { data: { network, agentAddress: address, recurringEnabled: recurringEnabled(), allowances } });
+ }
+
+ 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');
+ }
+ const network = body?.network || 'mainnet';
+ if (!NETWORKS.has(network)) return error(res, 400, 'invalid_request', 'network must be mainnet or devnet');
+
+ try {
+ switch (body?.op) {
+ case 'prepare': return await opPrepare({ req, res, id, auth, address, body, network });
+ case 'confirm': return await opConfirm({ req, res, id, auth, address, body, network });
+ case 'revoke': return await opRevoke({ res, id, body });
+ case 'revoked': return await opRevoked({ req, res, id, auth, body });
+ case 'pull': return await opPull({ req, res, id, auth, owned, body });
+ default: return error(res, 400, 'invalid_request', 'op must be prepare, confirm, revoke, revoked or pull');
+ }
+ } catch (e) {
+ if (e instanceof AllowanceError) return error(res, ERROR_STATUS[e.code] || 400, e.code, e.message);
+ throw e;
+ }
+}
+
+async function opPrepare({ res, auth, address, body, network }) {
+ if (!address) throw new AllowanceError('invalid_request', 'this agent has no Solana wallet yet');
+ const owner = typeof body.owner === 'string' ? body.owner : '';
+ if (!(await ownerWallets(auth.userId)).includes(owner)) {
+ throw new AllowanceError('invalid_request', 'owner must be a Solana wallet linked to your account');
+ }
+ const days = Number(body.expiresInDays);
+ if (!Number.isFinite(days) || days <= 0 || days > MAX_EXPIRY_DAYS) {
+ throw new AllowanceError('invalid_request', `expiresInDays must be between 1 and ${MAX_EXPIRY_DAYS}`);
+ }
+ const conn = solanaConnection(network);
+ const decimals = await mintDecimals(conn, body.mint);
+ const amount = toRaw(body.amount, decimals);
+ const kind = body.kind === 'recurring' ? 'recurring' : 'fixed';
+ const prep = await prepareCreateAllowance({
+ network,
+ owner,
+ delegatee: address,
+ mint: body.mint,
+ amount,
+ expiryTs: Math.floor(Date.now() / 1000) + Math.round(days * 86400),
+ kind,
+ periodLengthS: kind === 'recurring' ? Number(body.periodLengthS) : undefined,
+ connection: conn,
+ });
+ return json(res, 200, { data: { ...prep, amount: prep.amount.toString(), nonce: prep.nonce.toString(), decimals } });
+}
+
+async function opConfirm({ req, res, id, auth, address, body, network }) {
+ const { signature, delegationPda } = body;
+ if (typeof signature !== 'string' || typeof delegationPda !== 'string') {
+ throw new AllowanceError('invalid_request', 'signature and delegationPda are required');
+ }
+ const kind = body.kind === 'recurring' ? 'recurring' : 'fixed';
+ const conn = solanaConnection(network);
+ await confirmOrThrow(conn, signature, 'confirmed').catch((e) => {
+ throw new AllowanceError('invalid_request', `the create transaction did not confirm: ${e?.message || 'unknown error'}`);
+ });
+ const live = await readAllowance({ network, kind, delegationPda, connection: conn });
+ if (!live) throw new AllowanceError('allowance_not_found', 'no allowance account exists at that address');
+ if (live.delegatee !== address) throw new AllowanceError('invalid_request', 'that allowance does not delegate to this agent');
+ if (!(await ownerWallets(auth.userId)).includes(live.owner)) {
+ throw new AllowanceError('invalid_request', 'that allowance was not created by a wallet linked to your account');
+ }
+ const row = await recordAllowance({
+ agentId: id,
+ userId: auth.userId,
+ network,
+ kind,
+ ownerWallet: live.owner,
+ delegatee: live.delegatee,
+ mint: live.mint,
+ nonce: body.nonce ?? '0',
+ delegationPda,
+ capRaw: kind === 'recurring' ? live.capOnChain : live.remaining,
+ expiryTs: live.expiryTs,
+ periodLengthS: live.periodLengthS,
+ createSignature: signature,
+ });
+ logAudit({ userId: auth.userId, action: 'custody.allowance_created', resourceId: id, meta: { delegationPda, mint: live.mint, cap: row.capRaw, network, signature }, req });
+ return json(res, 200, { data: { allowance: await present(row) } });
+}
+
+async function opRevoke({ res, id, body }) {
+ const row = await getAllowance(id, body.id);
+ if (!row || row.revokedAt) throw new AllowanceError('allowance_not_found', 'no active allowance with that id');
+ const prep = await prepareRevokeAllowance({ network: row.network, owner: row.ownerWallet, delegationPda: row.delegationPda });
+ return json(res, 200, { data: { ...prep, id: row.id } });
+}
+
+async function opRevoked({ req, res, id, auth, body }) {
+ const row = await getAllowance(id, body.id);
+ if (!row) throw new AllowanceError('allowance_not_found', 'no allowance with that id');
+ const live = await readAllowance({ network: row.network, kind: row.kind, delegationPda: row.delegationPda });
+ if (live) throw new AllowanceError('invalid_request', 'that allowance is still open on chain; submit the revoke transaction first');
+ const updated = await markRevoked(row.id, typeof body.signature === 'string' ? body.signature : null);
+ logAudit({ userId: auth.userId, action: 'custody.allowance_revoked', resourceId: id, meta: { delegationPda: row.delegationPda, network: row.network, signature: body.signature || null }, req });
+ return json(res, 200, { data: { allowance: await present(updated) } });
+}
+
+async function opPull({ req, res, id, auth, owned, body }) {
+ const row = await getAllowance(id, body.id);
+ if (!row || row.revokedAt) throw new AllowanceError('allowance_not_found', 'no active allowance with that id');
+ let amount;
+ try { amount = BigInt(body.amountRaw); } catch { throw new AllowanceError('invalid_request', 'amountRaw must be an integer string'); }
+
+ // Hard ceiling first: nothing is built or signed when the program would refuse.
+ const verdict = await checkAgentAllowanceSpend({ agentId: id, network: row.network, mint: row.mint, amount });
+ const mine = verdict.allowance?.id === row.id ? verdict : await checkAllowancePull({ network: row.network, kind: row.kind, delegationPda: row.delegationPda, amount });
+ if (!mine.allow) {
+ await recordCustodyEvent({
+ agentId: id, userId: auth.userId, eventType: 'blocked', category: 'allowance_pull', network: row.network,
+ asset: row.mint, amountRaw: amount, reason: mine.code, status: 'blocked',
+ meta: { allowanceId: row.id, detail: mine.detail ?? null },
+ }).catch(() => {});
+ return json(res, 422, { error: mine.code, error_description: mine.reason, data: { detail: mine.detail ?? null } });
+ }
+
+ if (!owned.meta.encrypted_solana_secret) throw new AllowanceError('invalid_request', 'this agent has no custodial Solana key to sign with');
+ const agentKeypair = await recoverSolanaAgentKeypair(owned.meta.encrypted_solana_secret, {
+ agentId: id, userId: auth.userId, reason: 'allowance_pull',
+ meta: { allowanceId: row.id, mint: row.mint, network: row.network },
+ });
+ const conn = solanaConnection(row.network);
+ const built = await buildSignedPull({ network: row.network, kind: row.kind, delegationPda: row.delegationPda, owner: row.ownerWallet, mint: row.mint, amount, agentKeypair, connection: conn });
+ const sim = await conn.simulateTransaction(built.tx);
+ if (sim.value.err) {
+ const msg = describeProgramFailure(new Error(`${JSON.stringify(sim.value.err)}\n${(sim.value.logs || []).join('\n')}`));
+ return error(res, 422, 'program_rejected', msg);
+ }
+ const signature = await conn.sendRawTransaction(built.tx.serialize(), { skipPreflight: false, maxRetries: 3 });
+ await confirmOrThrow(conn, { signature, blockhash: built.blockhash, lastValidBlockHeight: built.lastValidBlockHeight }, 'confirmed');
+ await recordCustodyEvent({
+ agentId: id, userId: auth.userId, eventType: 'allowance_pull', category: 'allowance_pull', network: row.network,
+ asset: row.mint, amountRaw: amount, signature, reason: 'owner_funded_allowance', status: 'ok',
+ meta: { allowanceId: row.id, delegationPda: row.delegationPda, owner: row.ownerWallet },
+ }).catch((e) => console.warn('[allowance] custody record failed', e?.message));
+ logAudit({ userId: auth.userId, action: 'custody.allowance_pull', resourceId: id, meta: { allowanceId: row.id, mint: row.mint, amountRaw: amount.toString(), signature, network: row.network }, req });
+ return json(res, 200, { data: { signature, receiverAta: built.receiverAta, allowance: await present(row) } });
+}
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index a88ebdcd8..b84114e4a 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -2743,6 +2743,10 @@ export default async function handler(req, res, id, action) {
}
if (action === 'policy') return handlePolicy(req, res, id);
if (action === 'delegation') return handleDelegation(req, res, id);
+ if (action === 'allowance') {
+ const mod = await import('./solana-allowance.js');
+ return mod.handleAllowance(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/api/billing/agent-upgrade.js b/api/billing/agent-upgrade.js
new file mode 100644
index 000000000..5634d74c4
--- /dev/null
+++ b/api/billing/agent-upgrade.js
@@ -0,0 +1,145 @@
+// POST /api/billing/agent-upgrade?plan=builder|scale
+//
+// An agent that signed itself up (POST /api/auth/agent-signup) buys a paid
+// developer plan with one x402 payment, no human and no form.
+//
+// 1. Call with the account's API key. Without a payment header the answer is
+// 402 with the exact price (USDC on Solana) for moving this account to the
+// plan today: the full price from Free, the pro-rata difference mid-period.
+// 2. Pay that requirement and repeat the call with the x402 payment header.
+// The payment settles BEFORE the handler runs (settle-then-handler), so the
+// plan is granted only against a landed transaction, and the transaction
+// signature is unique in dev_plan_receipts: the same payment never funds
+// two plan changes.
+// 3. The 200 body carries the receipt and a scoped API key for the upgraded
+// account (read, generate, agents, wallet:read; it can never spend).
+//
+// The price differs per account and moment, and paidEndpoint prices a route
+// statically, so this dispatcher authenticates first, quotes, and delegates to
+// a paidEndpoint cached per (plan, price). $THREE is not offered on this route:
+// its x402 amount is a fixed env value, which would sell a variable-price plan
+// at a flat token price. Pay in $THREE through the dev-plan checkout instead.
+
+import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';
+import { extractBearer, authenticateBearer, hasScope } from '../_lib/auth.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { getDevSubscription } from '../_lib/dev-plans/subscription.js';
+import { quoteDevPlanChange, recordX402DevPlanPayment } from '../_lib/dev-plans/billing.js';
+import { listDevPlans } from '../_lib/dev-plans/config.js';
+import { usdToUsdcAtomics } from '../_lib/subscription-pricing.js';
+import { mintApiKey } from '../_lib/api-keys.js';
+
+const ROUTE = '/api/billing/agent-upgrade';
+const REQUIRED_SCOPE = 'agents:write';
+const UPGRADED_KEY_SCOPES = ['read', 'generate', 'agents:read', 'agents:write', 'wallet:read'];
+
+const OUTPUT_EXAMPLE = {
+ ok: true,
+ plan: 'builder',
+ receipt: { plan: 'builder', tx_signature: '5Vx...', amount_usd: 29 },
+ credentials: { api_key: 'sk_live_...', scope: UPGRADED_KEY_SCOPES.join(' ') },
+};
+
+const BAZAAR = {
+ discoverable: false,
+ info: {
+ input: { type: 'http', method: 'POST', bodyType: 'json', body: {} },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodySchema: { type: 'object' },
+ outputSchema: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: { ok: { type: 'boolean' }, plan: { type: 'string' }, receipt: { type: 'object' }, credentials: { type: 'object' } },
+ },
+ }),
+};
+
+const SELF_SERVE_PLANS = listDevPlans().filter((p) => p.purchasable && !p.contactSales).map((p) => p.id);
+
+const endpoints = new Map();
+
+function endpointFor(plan, atomics) {
+ const key = `${plan}:${atomics}`;
+ let ep = endpoints.get(key);
+ if (ep) return ep;
+ ep = paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: String(atomics),
+ networks: ['solana'],
+ acceptThree: false,
+ streaming: true,
+ description: `three.ws developer plan upgrade (${plan}). Pay the quoted USDC on Solana to move the calling account to the ${plan} plan and receive a scoped API key.`,
+ bazaar: BAZAAR,
+ resourceUrlBuilder: () => `${ROUTE}?plan=${encodeURIComponent(plan)}`,
+ async handler({ req, res, requirement, payer, settled }) {
+ const { userId, apiKeyId } = req.agentUpgrade;
+ const receipt = await recordX402DevPlanPayment({
+ userId,
+ planId: plan,
+ payer,
+ payTo: requirement?.payTo ?? null,
+ txSignature: settled?.transaction ?? req.settledTransaction ?? null,
+ amountAtomics: requirement?.amount ?? requirement?.maxAmountRequired ?? null,
+ req,
+ });
+ const { row, secret } = await mintApiKey({
+ userId,
+ name: `agent-upgrade-${plan}`,
+ scopes: UPGRADED_KEY_SCOPES,
+ req,
+ via: 'agent-upgrade',
+ });
+ return json(res, 200, {
+ ok: true,
+ plan,
+ receipt,
+ credentials: { api_key: secret, key_id: row.id, scope: row.scope, replaces: apiKeyId ?? null },
+ });
+ },
+ });
+ endpoints.set(key, ep);
+ return ep;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const bearer = await authenticateBearer(extractBearer(req), { ip: clientIp(req) });
+ if (!bearer) {
+ res.setHeader('www-authenticate', 'Bearer realm="three.ws"');
+ return error(res, 401, 'unauthorized', 'send the account API key from /api/auth/agent-signup as a Bearer token');
+ }
+ if (!hasScope(bearer.scope, REQUIRED_SCOPE)) {
+ return error(res, 403, 'insufficient_scope', `this key needs the ${REQUIRED_SCOPE} scope`);
+ }
+
+ const limit = await limits.agentUpgradeKey(bearer.apiKeyId || bearer.userId);
+ if (!limit.success) return rateLimited(res, limit, 'too many upgrade attempts for this key');
+
+ const plan = String(req.query?.plan || '').toLowerCase();
+ if (!SELF_SERVE_PLANS.includes(plan)) {
+ return error(res, 400, 'validation_error', `plan must be one of ${SELF_SERVE_PLANS.join(' or ')}`, { plans: SELF_SERVE_PLANS });
+ }
+
+ let quote;
+ try {
+ const sub = await getDevSubscription(bearer.userId, { fresh: true });
+ quote = quoteDevPlanChange(sub, plan, 'USDC');
+ } catch (err) {
+ if (err?.status && err.status < 500) return error(res, err.status, err.code || 'validation_error', err.message);
+ throw err;
+ }
+
+ const atomics = usdToUsdcAtomics(quote.amountUsd);
+ if (atomics <= 0n) return error(res, 400, 'nothing_to_pay', 'this account already holds that plan for the whole period');
+
+ req.agentUpgrade = { userId: bearer.userId, apiKeyId: bearer.apiKeyId ?? null };
+ return endpointFor(plan, atomics)(req, res);
+});
diff --git a/api/x402-prepaid/README.md b/api/x402-prepaid/README.md
new file mode 100644
index 000000000..485597b1e
--- /dev/null
+++ b/api/x402-prepaid/README.md
@@ -0,0 +1,13 @@
+# api/x402-prepaid
+
+Buyer-facing endpoints for the x402 prepaid rail. Full design, invariants and
+configuration: [docs/ops/x402-prepaid.md](../../docs/ops/x402-prepaid.md).
+
+| Route | Method | Purpose |
+| --- | --- | --- |
+| `/api/x402-prepaid/deposit` | GET | The deposit wallet, network and asset. |
+| `/api/x402-prepaid/deposit` | POST `{ tx_signature }` | Verify a finalized USDC deposit and credit its sender. Idempotent; `202` while the transaction is not yet finalized. |
+| `/api/x402-prepaid/balance` | GET `?payer=` | A payer's balance. |
+
+Ledger, batcher and route hook live in [api/_lib/x402/](../_lib/x402) (`prepaid-*.js`).
+Crons: [x402-prepaid-settle](../cron/x402-prepaid-settle.js), [x402-prepaid-reconcile](../cron/x402-prepaid-reconcile.js).
diff --git a/data/guards.json b/data/guards.json
index 3c225a471..95f8b48df 100644
--- a/data/guards.json
+++ b/data/guards.json
@@ -1,5 +1,5 @@
{
- "updated": "2026-10-09",
+ "updated": "2026-10-23",
"summary": "Every mechanical guard that protects this repository, and the stage each one runs in. This file is the single source of truth: scripts/audit-guards.mjs proves every entry is real and every stage claim is true, docs/guards.md explains them, and /guards renders them.",
"stages": [
{
@@ -1701,6 +1701,48 @@
"reason": "The thing under test is what xAI serves today, read from its models API or its public model docs. There is no offline input whose mutation proves anything about a third party's live catalog, and the comparison never sends a prompt or spends a token. The key, when set, is only ever sent to api.x.ai."
}
},
+ {
+ "id": "check-mcp-counts",
+ "script": "scripts/check-mcp-counts.mjs",
+ "npm": "check:mcp-counts",
+ "title": "Quoted MCP counts match the census",
+ "protects": "Every tool, resource and prompt count a living doc quotes for a three.ws MCP server equals the census in public/tools.json.",
+ "why": "MCP tools are added weekly and the same number is quoted in READMEs, plugin docs and the architecture overview. Without a check each quote drifts on its own schedule, and a buyer reads 22 tools on a server that serves 40. Counts are written through a marker, so a stale number fails the gate and `--fix` rewrites it from the census.",
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A living doc whose marker claims a tool count the census does not have.",
+ "violation": {
+ "write": {
+ "docs/guard-proof-mcp-count.md": "# Proof fixture\n\nThe 3D server has <!-- mcp-count:mcp-3d.tools -->9999<!-- /mcp-count --> tools.\n"
+ }
+ },
+ "expect": "guard-proof-mcp-count.md"
+ }
+ },
+ {
+ "id": "check-site-builder-embeds",
+ "script": "scripts/check-site-builder-embeds.mjs",
+ "npm": "check:site-builder-embeds",
+ "title": "Site-builder pinned releases match the ledger",
+ "protects": "The WordPress, Framer and Webflow pinned-release files name the same <agent-3d> release as the release ledger.",
+ "why": "Each site-builder integration ships a pinned copy of the agent-3d version it embeds, so a customer's site never floats onto an unreviewed build. When the ledger moves and a pin does not, one integration silently serves an old component. The guard regenerates the expected bytes from the ledger and fails on any difference; `--fix` rewrites them.",
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A pinned-release file edited by hand so it no longer matches the ledger.",
+ "violation": {
+ "append": {
+ "integrations/webflow/src/pinned-release.ts": "\n// Hand-edited inside the guard sandbox, so the pin no longer matches the ledger.\n"
+ }
+ },
+ "expect": "does not match the ledger"
+ }
+ },
{
"id": "i18n-home",
"script": "scripts/i18n-home-keys.mjs",
diff --git a/data/pages.json b/data/pages.json
index 1766cdc1f..c382e160a 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -919,6 +919,14 @@
"changefreq": "monthly",
"added": "2026-06-26"
},
+ {
+ "path": "/x-video",
+ "title": "X Video Downloader",
+ "description": "Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.",
+ "priority": 0.7,
+ "changefreq": "monthly",
+ "added": "2026-10-23"
+ },
{
"path": "/capture",
"title": "Scene Capture: Video to 3D Point Cloud",
diff --git a/data/upstream-baseline.json b/data/upstream-baseline.json
index 1c801c9ff..6dfec6a3b 100644
--- a/data/upstream-baseline.json
+++ b/data/upstream-baseline.json
@@ -1,20 +1,20 @@
{
"generated": "scripts/audit-upstreams.mjs",
"summary": {
- "total": 248,
+ "total": 264,
"grades": {
"A": 0,
- "B": 55,
- "C": 107,
- "D": 86,
+ "B": 57,
+ "C": 115,
+ "D": 92,
"F": 0
},
"protections": {
- "deadline": 248,
- "retry": 112,
- "failover": 50,
- "lastGood": 5,
- "breaker": 103
+ "deadline": 264,
+ "retry": 121,
+ "failover": 51,
+ "lastGood": 6,
+ "breaker": 112
}
},
"sites": {
@@ -70,7 +70,6 @@
"api/_providers/replicate.js::api.replicate.com::fetchUpstream": "C",
"api/_providers/rodin.js::api.hyper3d.com::fetchUpstream": "C",
"api/_providers/stability.js::api.stability.ai::fetchUpstream": "C",
- "api/_providers/tripo.js::api.tripo3d.ai::fetchUpstream": "C",
"api/agents/[id]/memory-seed-x.js::api.twitter.com::fetchUpstream": "C",
"api/agents/alpha.js::frontend-api-v3.pump.fun::pumpFetchJson": "C",
"api/agents/alpha.js::api.dexscreener.com::fetchUpstreamJson": "C",
@@ -112,7 +111,6 @@
"api/pinning/[action].js::api.pinata.cloud::fetch": "D",
"api/pinning/[action].js::api.web3.storage::fetch": "D",
"api/portfolio/[action].js::coins.llama.fi::fetchFirstOrNull": "B",
- "api/pump-fun-mcp.js::publish.twitter.com::fetch": "D",
"api/pump/[action].js::api.github.com::fetch": "D",
"api/pump/dex-trades.js::api.geckoterminal.com::fetch": "D",
"api/pump/launch-og.js::frontend-api-v3.pump.fun::pumpFetchJson": "C",
@@ -192,7 +190,6 @@
"src/agent-skills-pumpfun-compose.js::pump-fun-sdk.modelcontextprotocol.name::fetch": "D",
"src/erc8004/agent-registry.js::api.pinata.cloud::fetch": "D",
"src/shared/wallet-networth.js::lite-api.jup.ag::fetch": "D",
- "src/social/x-post-impact.js::publish.twitter.com::fetch": "D",
"api/_lib/print/ops-notify.js::api.telegram.org::fetchUpstream": "C",
"workers/agent-sniper/risk-officer.js::openrouter.ai::fetch": "D",
"api/_lib/globe-sources.js::data.gdeltproject.org::fetchUpstream": "C",
@@ -213,6 +210,23 @@
"api/_lib/predictions/solana-venue.js::clob.polymarket.com::fetchUpstreamJson": "C",
"api/_lib/predictions/solana-venue.js::api.elections.kalshi.com::fetchUpstreamJson": "C",
"api/_lib/tool-gateway/web.js::api.duckduckgo.com::fetchUpstreamJson": "C",
- "src/dextools-boost-embed.js::api.dexscreener.com::fetch": "D"
+ "src/dextools-boost-embed.js::api.dexscreener.com::fetch": "D",
+ "api/_lib/cloud-domains.js::iamcredentials.googleapis.com::fetchUpstream": "C",
+ "api/_lib/gateway/discord-activity-auth.js::discord.com::fetch": "D",
+ "api/_lib/market-anomaly-sources.js::api.llama.fi::fetchUpstreamJson": "C",
+ "api/_lib/market-anomaly-sources.js::stablecoins.llama.fi::fetchUpstreamJson": "C",
+ "api/_lib/papertrade/index.js::exchange.papertrade.xyz__expr__::fetchUpstreamJson": "C",
+ "api/_lib/papertrade/index.js::rpc.hyperliquid.xyz::fetchUpstreamJson": "B",
+ "api/_lib/papertrade/index.js::api.hyperliquid.xyz::fetchUpstreamJson": "C",
+ "api/_lib/papertrade/index.js::exchange.papertrade.xyz::fetchUpstream": "C",
+ "api/_lib/pump-claims-github.js::api.github.com__expr__::fetch": "D",
+ "api/_lib/pump-claims-github.js::frontend-api-v3.pump.fun::fetch": "D",
+ "api/_lib/shopify/graphql.js::__expr__::fetch": "D",
+ "api/_lib/vroid/client.js::hub.vroid.com::fetchUpstream": "C",
+ "api/_lib/x402-services/places.js::overpass-api.de::fetch": "D",
+ "api/_providers/tripo.js::openapi.tripo3d.com::fetchUpstream": "C",
+ "api/shopify/callback.js::__expr__::fetch": "D",
+ "src/desktop/os/apps/weather-data.js::api.open-meteo.com::fetch": "D",
+ "src/runtime/whisper-stt.js::esm.sh::loadModule": "B"
}
}
diff --git a/docs/guards.md b/docs/guards.md
index 27e1dfdc2..1345f4910 100644
--- a/docs/guards.md
+++ b/docs/guards.md
@@ -108,6 +108,8 @@ Run `npm run audit:guards` to print the current count and per-stage breakdown. T
| Published 3D skill bundle | `npm run check:openai-skills` | `public/skills/3d-studio/` is byte-identical to the `.agents/skills` folders it is generated from, so the bundle strangers download is the one this repo ships. |
| Motion signature index | `npm run audit:motion` | `public/animations/signatures.json` describes the clips that are actually baked, so a rebake cannot leave `/gestures` and the walk-layer tables describing motion that no longer exists. |
| One `<model-viewer>` build | `npm run check:model-viewer` | Every `<model-viewer>` reference in tracked source names one version, no version is served under two integrity hashes, and the vendored copy matches. |
+| Quoted MCP counts | `npm run check:mcp-counts` | Every tool, resource and prompt count a living doc quotes for a three.ws MCP server equals the census in `public/tools.json`; `--fix` rewrites the markers. |
+| Site-builder pinned releases | `npm run check:site-builder-embeds` | The WordPress, Framer and Webflow pinned-release files name the same `<agent-3d>` release as the release ledger; `--fix` regenerates them. |
| Design-token ratchet | `npm run audit:tokens` | Hardcoded colour hexes cannot creep back past a committed baseline. |
| Interactive-state ratchet | `npm run audit:states` | A selector that declares cursor:pointer cannot ship without a hover rule behind it. |
| Motion ratchet | `npm run audit:motion-tokens` | A transition cannot spell its duration or easing as a literal past a committed baseline. |
diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.md
index e6770380b..edbff2877 100644
--- a/docs/ops/gcp-production.md
+++ b/docs/ops/gcp-production.md
@@ -468,6 +468,7 @@ only on Vercel, was never carried to Cloud Run, and nothing alerted. Restored
| CoinCommunities API key | `CC_API_KEY` | Town chat renders its designed locked state. `/api/community/worlds` and `/api/clash/state` + `/api/clash/leaderboard` no longer die: they fail over to the live pump.fun trending feed (`api/_lib/pump-trending.js`) and tag the response `source: "pump-trending"`, so the world picker and the Clash arena stay alive (the Clash roster is frozen per round). The Play holders gate shows its `unavailable` state ("Holder check is offline") and offers a one-click path into the coin's open world, so a gated world is never a dead end. | Keys are provisioned manually by the CoinCommunities team (their docs say "contact support": no self-serve signup, and the SDK's `business/register` endpoints are not deployed on `api.coin-communities.xyz`). Owner outreach to @CoinComms required; set `CC_API_KEY` (+ optional `CC_SERVER_KEY`/`CC_SERVER_SECRET`) on the Cloud Run service when granted. |
| Agent mail to and from the internet | (not a var: DNS records for `agents.three.ws`) | Mail between two `agents.three.ws` mailboxes works (delivered inside the platform). Mail to any outside address fails with `send_failed` (credits are refunded), and outside senders cannot reach an agent, because the mail provider reports the `agents.three.ws` domain as `failed`: none of its records exist at the DNS host. Checked 2026-10-10. | In the Resend dashboard, open the `agents.three.ws` domain and add every record it lists at the DNS host for `three.ws`: the DKIM TXT at `resend._domainkey.agents`, the SPF MX and TXT at `send.agents`, the return-path CNAME, and the receiving MX at `agents` (priority 10). Then press **Verify** and point the domain's inbound webhook at `https://three.ws/api/mail/inbound` with the secret in `RESEND_WEBHOOK_SECRET`. See [docs/agent-mail.md](../agent-mail.md). |
| x402 ring payer USDC float | — (not a var: an on-chain balance) | The autonomous loop's payer wallet holds $0 USDC, so every paid call is skipped. Since 2026-07-09 this manifested as ~1 failed settle/minute (`broadcast_failed:Simulation failed`); the loop now skips paid calls instead. Free + monitoring entries are unaffected. | Send USDC to the payer wallet (`X402_SEED_SOLANA_SECRET_BASE58`'s pubkey). Floor is `X402_RING_PAYER_USDC_FLOOR_ATOMIC` (default $5) — fund meaningfully above it or it re-drains. See **x402 ring payer float** below. |
+| x402 prepaid settler | `X402_PREPAID_SETTLER_SECRET_BASE58`, `X402_PREPAID_SETTLE_LIVE`, `X402_PREPAID_DEPOSIT_WALLET`, `X402_PREPAID_MIN_SETTLE_ATOMICS`, `X402_PREPAID_MAX_PAYEES_PER_TX` | Unset settler or `X402_PREPAID_SETTLE_LIVE` not `1`: the settle cron only plans, committed debits accumulate unpaid. | Owner action: fund the settler (SOL fees plus USDC float), review the planned window, then set the flag with `--update-env-vars`. See [x402-prepaid.md](x402-prepaid.md). |
### x402 ring payer float — why an empty wallet used to storm Solana
diff --git a/docs/ops/x402-prepaid.md b/docs/ops/x402-prepaid.md
new file mode 100644
index 000000000..ae4fa1bfd
--- /dev/null
+++ b/docs/ops/x402-prepaid.md
@@ -0,0 +1,77 @@
+# x402 prepaid balances and batch settlement
+
+Small x402 calls (a cent or less) used to starve the settle floor: every call
+was its own on-chain transfer, and the network fee per transfer rivals the
+price. The prepaid rail fixes that. A buyer deposits once, each request debits a
+ledger row, and the platform pays every seller for a whole window in **one**
+Solana transaction. Solana and USDC only.
+
+## Flow
+
+1. **Deposit.** `GET /api/x402-prepaid/deposit` returns the deposit wallet. The
+ buyer sends USDC there, then `POST /api/x402-prepaid/deposit {"tx_signature"}`.
+ The server reads the finalized transaction, requires exactly one signing
+ sender, and credits that sender. Crediting is idempotent on the signature.
+2. **Spend.** A route declared with `paidEndpoint({ mode: 'prepaid', ... })`
+ still answers 402 as before (per-call payment keeps working). A buyer with a
+ balance instead sends a `SIGN-IN-WITH-X` header and no `X-PAYMENT`. The price
+ is **reserved** before the handler runs.
+3. **Charge only success.** A normal return commits the debit. A thrown handler,
+ a 5xx the handler wrote, a cancelled request or a closed response refunds the
+ reservation in full. Reservations abandoned by a dead process are refunded by
+ the settle cron after `PREPAID_RESERVATION_TTL_SECONDS` (600).
+4. **Settle.** `x402-prepaid-settle` (hourly) sums committed, unbatched debits
+ per seller, keeps sellers at or above the floor, and pays them together.
+ Sellers under the floor roll into the next window.
+5. **Reconcile.** `x402-prepaid-reconcile` (03:17 UTC) checks the books and
+ alerts through `sendOpsAlert` on any problem.
+
+## Why the balance is never wrong
+
+- Debit is one statement: `UPDATE ... WHERE balance >= amount` plus the entry
+ insert, so 100 parallel debits against a balance that covers 71 of them
+ produce exactly 71 successes. A `CHECK (balance_atomic >= 0)` is the backstop.
+- Deposits are unique on `(kind, ref)`; replaying a signature credits once.
+- A debit belongs to at most one batch (claimed by a single statement), so racing
+ settle crons cannot pay twice.
+- A **definitive** send failure (chain rejected it, simulation failed, never left
+ the process) releases the debits for the next window. An **ambiguous** failure
+ parks the batches as `unconfirmed` and alerts. It is never auto-retried,
+ because the transfer may have landed. Each transaction carries a memo naming
+ its batch ids so an unrecorded landing can be found on-chain.
+
+## Reconciliation
+
+```
+node scripts/x402-prepaid-reconcile.mjs # DATABASE_URL, read-only
+node scripts/x402-prepaid-reconcile.mjs --chain # also compare the wallet's real USDC
+node scripts/x402-prepaid-reconcile.mjs --dev # in-process Postgres with real operations
+```
+
+Invariants: `deposits - debits - balances = 0`, batched debits equal batch totals,
+confirmed batches equal their debits, no payer drifted, no stale reservation, no
+batch stuck pending. Exit 0 clean, 1 problems, 2 unusable setup.
+
+## Configuration
+
+| Variable | Default | Meaning |
+| --- | --- | --- |
+| `X402_PREPAID_SETTLER_SECRET_BASE58` | unset | Keypair that pays sellers. Needs about 0.05 SOL for fees and the USDC float. Registered as signer `x402-prepaid-settler`. |
+| `X402_PREPAID_DEPOSIT_WALLET` | the settler's address | Where buyers deposit. |
+| `X402_PREPAID_SETTLE_LIVE` | unset | Must be `1` for the cron to move USDC. Otherwise it only plans and reports. |
+| `X402_PREPAID_MIN_SETTLE_ATOMICS` | `1000000` | Seller floor per window (1 USDC). |
+| `X402_PREPAID_MAX_PAYEES_PER_TX` | `8` | Sellers per transaction (max 12); more are split across transactions. |
+
+Enabling live settlement moves real funds. Check `npm run db:status` first, then
+`npm run db:migrate` (migration `20261023160000_x402_prepaid_ledger.sql`), fund the
+settler, review the plan the cron logs, then set `X402_PREPAID_SETTLE_LIVE=1` with
+`gcloud run services update ... --update-env-vars`.
+
+## Tables
+
+`x402_prepaid_accounts` (balance per payer, network, asset), `x402_prepaid_entries`
+(every deposit and debit with state `credited | reserved | committed | refunded`),
+`x402_prepaid_batches` (one row per seller per window: `pending | confirmed |
+failed | unconfirmed`).
+
+Tests: `tests/x402-prepaid-ledger.test.js` runs the real migration on PGlite.
diff --git a/docs/x-video.md b/docs/x-video.md
new file mode 100644
index 000000000..93acb9526
--- /dev/null
+++ b/docs/x-video.md
@@ -0,0 +1,39 @@
+# X post reader and free video tool
+
+One keyless reader for public X posts, shared by the price-impact tools and the free `/x-video` page.
+
+## Reader: `api/_lib/x-syndication.js`
+
+`readXPost(postUrl)` returns `{ id, url, ts, createdAt, author, text, metrics, media, source }`.
+
+Rungs, in order. The first that answers wins; a failing rung falls through.
+
+1. **X syndication** (`cdn.syndication.twimg.com`): no auth, widest mp4 ladder. Gives likes and replies.
+2. **fxtwitter** (`api.fxtwitter.com`): independent third party. Adds reposts, quotes, views and bookmarks.
+3. **Guest-token GraphQL** (`api.x.com`): runs only when `X_BEARER_TOKEN` is set. Full metrics.
+
+Metrics a rung does not report are `null`, never guessed.
+
+Errors: `XPostError` with `status` 400 (not a post URL), 404 `PostUnavailableError` (deleted, private or missing), 502 (no rung reachable).
+
+Video extraction approach adapted from `download-x-twitter-videos` (Apache-2.0).
+
+## Callers
+
+- `pumpfun_social_x_post_impact` in `api/pump-fun-mcp.js` and `correlateXPost` in `src/social/x-post-impact.js` return `post` with `metrics` and a media summary. In a browser the second goes through `POST /api/x-video/extract`, since X blocks cross-origin page reads.
+
+## Endpoints
+
+`POST /api/x-video/extract` body `{ "url": "https://x.com/<handle>/status/<id>" }`
+
+```json
+{ "post": { "...": "..." }, "videos": [{ "url": "...", "quality": "720p", "width": 1280, "height": 720, "bitrate": 2176000, "contentType": "video/mp4" }], "thumbnail": "...", "duration_ms": 12000, "source": "syndication" }
+```
+
+Errors: `invalid_url` 400, `post_unavailable` 404, `no_video` 404, `upstream_unreachable` 502, 429 when rate limited (20 per minute per IP).
+
+`GET /api/x-video/download?url=<media url>&handle=<h>&id=<postId>` streams the file as an attachment. Only https `video.twimg.com` and `pbs.twimg.com` are accepted, with no credentials or ports, and redirects are never followed.
+
+## Tests
+
+`tests/x-syndication.test.js`, `tests/x-post-impact.test.js`, `tests/api/x-video.test.js`.
diff --git a/package.json b/package.json
index fd837f901..986ac7c8c 100644
--- a/package.json
+++ b/package.json
@@ -648,6 +648,7 @@
"@solana/kit": "^8.5.0",
"@solana/pay": "^0.2.6",
"@solana/spl-token": "^0.4.14",
+ "@solana/subscriptions": "^0.5.0",
"@solana/wallet-standard-features": "^1.5.0",
"@solana/web3.js": "^1.99.0",
"@sparkjsdev/spark": "^2.3.1",
diff --git a/packages/three-ws-cli/src/commands/signup.js b/packages/three-ws-cli/src/commands/signup.js
new file mode 100644
index 000000000..9043d2b4a
--- /dev/null
+++ b/packages/three-ws-cli/src/commands/signup.js
@@ -0,0 +1,131 @@
+// `three-ws signup --agent`: an agent signs itself up for three.ws.
+//
+// No email, no browser, no human. The local Solana key from `three-ws wallet`
+// (created here when it does not exist yet) proves it owns its address by
+// signing a challenge the server issues; the server answers with an account, a
+// custodial agent wallet and an API key, which this command stores so every other
+// `three-ws` command works at once.
+//
+// three-ws signup --agent [--name <label>] [--storage auto|keychain|file]
+//
+// The account starts on the free plan in paper mode. Buying a plan is a separate,
+// explicit x402 payment (printed at the end, never made here).
+
+import { getBase58Decoder } from '@solana/kit';
+import * as p from '@clack/prompts';
+import { createKeystore } from '../pay/keystore.js';
+import { PayError, EXIT } from '../pay/errors.js';
+import { requestJson } from '../http.js';
+import { readStore, updateStore } from '../store.js';
+import { credentialsPath } from '../paths.js';
+import { answer } from './common.js';
+import { c, line, printJson, rows, sym, tildify } from '../ui.js';
+
+const interactive = (ctx) => Boolean(process.stdin.isTTY && process.stderr.isTTY && !ctx.flags.json);
+
+function keystoreFor(ctx) {
+ return createKeystore({
+ env: ctx.env,
+ askPassphrase: interactive(ctx) ? async (question) => answer(await p.password({ message: question })) : undefined,
+ });
+}
+
+/** Sign `message` (UTF-8 text) with the wallet key; returns the base58 signature. */
+export async function signChallenge(signer, message) {
+ const content = new TextEncoder().encode(message);
+ const [signatures] = await signer.signMessages([{ content, signatures: {} }]);
+ const bytes = signatures[signer.address];
+ if (!bytes) throw new Error('the wallet did not return a signature');
+ return getBase58Decoder().decode(bytes);
+}
+
+/** Wallet to use: the existing one, or a freshly created one. */
+async function ensureWallet(ctx, keystore) {
+ if (keystore.meta()) return { ...keystore.address(), created: false };
+ const storage = ctx.flags.storage ?? 'auto';
+ const made = await keystore.init({ storage });
+ return { ...made, created: true };
+}
+
+/**
+ * Run the two-call flow against `origin` and return the server's 201 body.
+ * Exported so tests drive it against a real local server.
+ */
+export async function runAgentSignup({ origin, signer, name }) {
+ const url = `${origin}/api/auth/agent-signup`;
+ const publicKey = signer.address;
+ const { challenge } = await requestJson(url, { method: 'POST', json: { public_key: publicKey } });
+ const signature = await signChallenge(signer, challenge.message);
+ return requestJson(url, { method: 'POST', json: { public_key: publicKey, nonce: challenge.nonce, signature, ...(name ? { name } : {}) } });
+}
+
+export async function signup(ctx) {
+ const { flags } = ctx;
+ if (flags.agent === undefined) {
+ throw new Error('signup is for autonomous agents: run `three-ws signup --agent`. To sign a person in, run `three-ws login`.');
+ }
+ const store = readStore(ctx.env);
+ if (store.auth && !flags.yes) {
+ throw new Error(`already signed in (${tildify(credentialsPath(ctx.env))}). Pass --yes to sign up a new account and replace those credentials.`);
+ }
+ if (flags.name && flags.name.length > 100) throw new Error('--name must be 1-100 characters');
+
+ const keystore = keystoreFor(ctx);
+ let wallet;
+ try {
+ wallet = await ensureWallet(ctx, keystore);
+ } catch (err) {
+ if (err instanceof PayError) throw err;
+ throw new PayError(EXIT.WALLET_UNAVAILABLE, 'wallet_unavailable', err.message);
+ }
+ const signer = await keystore.signer();
+ const body = await runAgentSignup({ origin: ctx.origin, signer, name: flags.name });
+
+ updateStore((s) => {
+ s.origin = ctx.origin;
+ s.account = { user_id: body.account.id, email: null };
+ s.auth = {
+ type: 'apikey',
+ key: body.credentials.api_key,
+ prefix: body.credentials.api_key_prefix,
+ scope: body.credentials.scope,
+ key_id: null,
+ };
+ s.agent_signup = {
+ account_id: body.account.id,
+ agent_id: body.agent.id,
+ public_key: signer.address,
+ claim_code: body.claim?.code ?? null,
+ claim_expires_at: body.claim?.expires_at ?? null,
+ };
+ return s;
+ }, ctx.env);
+
+ const upgradeCommand = `three-ws pay "${body.upgrade.endpoint.replace('<plan>', 'builder')}" --method POST -H "Authorization: Bearer $THREE_WS_API_KEY" --dry-run`;
+ if (flags.json) {
+ printJson({
+ account: body.account,
+ agent: body.agent,
+ wallets: body.wallets,
+ wallet_created: wallet.created,
+ credential: { type: 'apikey', prefix: body.credentials.api_key_prefix, scope: body.credentials.scope },
+ store: credentialsPath(ctx.env),
+ upgrade: body.upgrade,
+ });
+ return 0;
+ }
+ line(`${c.green(sym.ok)} Signed up. Account ${c.bold(body.account.id)}`);
+ rows(
+ [
+ ['agent', `${body.agent.name} (${body.agent.url})`],
+ ['identity key', `${signer.address}${wallet.created ? ' (new)' : ''}`],
+ ['agent wallet', body.wallets.agent_solana || 'none'],
+ ['plan', `${body.account.plan}, paper mode`],
+ ['credentials', tildify(credentialsPath(ctx.env))],
+ ],
+ ' ',
+ );
+ line(c.dim(' The API key is stored owner-only and is not shown again.'));
+ line(c.dim(` Buy a plan with an x402 payment: preview with \`${upgradeCommand}\`.`));
+ return 0;
+}
diff --git a/pages/x-video.html b/pages/x-video.html
new file mode 100644
index 000000000..f63572d0f
--- /dev/null
+++ b/pages/x-video.html
@@ -0,0 +1,92 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>X Video Downloader · three.ws</title>
+ <meta name="description" content="Paste an X post link and download its video or GIF in every quality. Free, no account, no API key. Also shows the post's likes, replies, reposts and views." />
+ <meta name="theme-color" content="#000000" />
+ <link rel="canonical" href="https://three.ws/x-video" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="X Video Downloader · three.ws" />
+ <meta property="og:description" content="Paste an X post link and download its video or GIF in every quality. Free, no account." />
+ <meta property="og:url" content="https://three.ws/x-video" />
+ <meta name="twitter:card" content="summary" />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ .xv-page { min-height: 100vh; background: var(--bg, #050505); color: var(--text, #f6f6f6); font-family: var(--font-body, 'Inter', system-ui, sans-serif); -webkit-font-smoothing: antialiased; }
+ .xv-wrap { max-width: 760px; margin: 0 auto; padding: 48px 24px 80px; }
+ .xv-chip { display: inline-block; padding: 4px 11px; border: 1px solid var(--border, #2a2a2a); border-radius: 20px; font-size: 11px; letter-spacing: 0.05em; text-transform: uppercase; color: var(--text-muted, #a0a0a0); margin-bottom: 16px; }
+ .xv-wrap h1 { font-size: clamp(28px, 5vw, 40px); line-height: 1.1; margin: 0 0 12px; letter-spacing: -0.02em; }
+ .xv-lede { color: var(--text-muted, #a0a0a0); margin: 0 0 28px; line-height: 1.55; }
+ .xv-form { display: flex; gap: 10px; flex-wrap: wrap; }
+ .xv-input { flex: 1 1 320px; min-width: 0; padding: 13px 14px; font: inherit; color: inherit; background: var(--surface, #0e0e0e); border: 1px solid var(--border, #2a2a2a); border-radius: 10px; }
+ .xv-input:hover { border-color: #444; }
+ .xv-input:focus-visible, .xv-btn:focus-visible, .xv-dl:focus-visible { outline: 2px solid var(--accent-violet, #7c5df3); outline-offset: 2px; }
+ .xv-btn { padding: 13px 22px; font: inherit; font-weight: 600; color: #fff; background: var(--accent-violet, #7c5df3); border: 0; border-radius: 10px; cursor: pointer; transition: filter 0.15s, transform 0.05s; }
+ .xv-btn:hover { filter: brightness(1.12); }
+ .xv-btn:active { transform: translateY(1px); }
+ .xv-btn[disabled] { opacity: 0.55; cursor: progress; }
+ .xv-status { margin-top: 18px; min-height: 22px; }
+ .xv-error { padding: 14px 16px; border: 1px solid #6b2a2a; background: rgba(220, 70, 70, 0.08); border-radius: 10px; line-height: 1.5; }
+ .xv-error strong { display: block; margin-bottom: 2px; }
+ .xv-card { margin-top: 24px; border: 1px solid var(--border, #2a2a2a); background: var(--surface, #0e0e0e); border-radius: 14px; overflow: hidden; }
+ .xv-author { display: flex; align-items: center; gap: 12px; padding: 16px 18px 0; }
+ .xv-avatar { width: 40px; height: 40px; border-radius: 50%; background: #222; object-fit: cover; flex: none; }
+ .xv-name { font-weight: 600; overflow-wrap: anywhere; }
+ .xv-handle { color: var(--text-muted, #a0a0a0); font-size: 13px; }
+ .xv-text { padding: 12px 18px 0; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
+ .xv-metrics { display: flex; flex-wrap: wrap; gap: 6px 18px; padding: 12px 18px 16px; margin: 0; list-style: none; color: var(--text-muted, #a0a0a0); font-size: 13px; }
+ .xv-metrics b { color: var(--text, #f6f6f6); font-variant-numeric: tabular-nums; }
+ .xv-video { display: block; width: 100%; max-height: 420px; background: #000; }
+ .xv-list { list-style: none; margin: 0; padding: 6px 18px 16px; }
+ .xv-row { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-top: 1px solid var(--border, #2a2a2a); }
+ .xv-row:first-child { border-top: 0; }
+ .xv-q { font-weight: 600; min-width: 64px; }
+ .xv-meta { color: var(--text-muted, #a0a0a0); font-size: 13px; flex: 1; }
+ .xv-dl { padding: 8px 16px; color: #fff; background: var(--accent-violet, #7c5df3); border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px; transition: filter 0.15s; }
+ .xv-dl:hover { filter: brightness(1.12); }
+ .xv-skel { height: 14px; border-radius: 6px; background: linear-gradient(90deg, #1a1a1a, #262626, #1a1a1a); background-size: 200% 100%; animation: xv-shimmer 1.2s linear infinite; margin: 18px; }
+ @keyframes xv-shimmer { to { background-position: -200% 0; } }
+ @media (prefers-reduced-motion: reduce) { .xv-skel { animation: none; } }
+ .xv-foot { margin-top: 32px; color: var(--text-muted, #a0a0a0); font-size: 13px; line-height: 1.6; }
+ .xv-foot a { color: inherit; }
+ </style>
+ </head>
+ <body>
+ <div class="xv-page">
+ <div id="nav-container"></div>
+ <script type="module" src="/nav.js"></script>
+
+ <main class="xv-wrap">
+ <span class="xv-chip">Free tool</span>
+ <h1>X video downloader.</h1>
+ <p class="xv-lede">Paste the link to any public X post. Get its video or GIF in every quality, plus the post's likes, replies, reposts and views. No account, no API key.</p>
+
+ <form class="xv-form" id="xv-form" novalidate>
+ <label for="xv-url" class="sr-only" style="position:absolute;left:-9999px">X post link</label>
+ <input class="xv-input" id="xv-url" name="url" type="url" inputmode="url" autocomplete="off" spellcheck="false" placeholder="https://x.com/trythreews/status/1234567890" required />
+ <button class="xv-btn" id="xv-go" type="submit">Get video</button>
+ </form>
+
+ <div class="xv-status" id="xv-status" role="status" aria-live="polite"></div>
+ <div id="xv-result"></div>
+
+ <p class="xv-foot">Works on public posts only. Downloads stream through three.ws from X's own media servers; nothing is stored. Only download content you have the right to save. Developers: the same reader powers <code>POST /api/x-video/extract</code>.</p>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js" defer></script>
+ </div>
+ <script type="module" src="/src/x-video.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/public/guard-proofs.json b/public/guard-proofs.json
index cd0d67b10..3037351de 100644
--- a/public/guard-proofs.json
+++ b/public/guard-proofs.json
@@ -1,72 +1,292 @@
{
"$comment": "Generated by scripts/prove-guards.mjs. Each result is the outcome of running the guard twice in a sandbox: once on a clean baseline, once after a declared violation. The fixtures live in data/guards.json.",
"generator": "scripts/prove-guards.mjs",
- "commit": "91a14bd51403f38f35eb694b965df1dc9f7204e6",
- "guardCount": 45,
+ "commit": "8eb931119deeb513a96283d144b3c199509078e4",
+ "guardCount": 90,
"summary": {
- "proven": 28,
- "liveOnly": 17,
- "failing": 0,
- "redBaseline": 6
+ "proven": 37,
+ "liveOnly": 32,
+ "failing": 21,
+ "redBaseline": 26
},
"results": [
{
- "id": "check-merge-conflicts",
- "npm": "check:conflicts",
+ "id": "audit-agent-operability",
+ "npm": "audit:agent-operability",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Drives five real pages with Playwright role/label locators against a running server, including a signed-in session for avatar-limited steps. A static fixture cannot prove an accessibility-tree locator resolves against live markup.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-console",
+ "npm": "audit:console",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Drives a real browser over the live page set and reads the console, so it needs Playwright and a running server. A static fixture cannot produce a runtime console error.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-cron-liveness",
+ "npm": "audit:cron-liveness",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "The run stage boots the real server on a free port and probes every cron URL, so the check is inherently live. The probe is deliberately unauthenticated and every handler fails closed on CRON_SECRET, so no job body executes: nothing is paid, swapped, minted, transferred, or written. `--static` skips the boot for a route-and-load-only pass.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-csp",
+ "npm": "audit:csp",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Needs Playwright plus a server serving dist/, because the thing under test is the browser's own policy evaluation against a real response. A static fixture cannot produce a securitypolicyviolation event.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-custodial-key-health",
+ "npm": "audit:custodial-keys",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "It reads the production wallet table and the live encryption key, then decrypts in memory to test each secret against the current key. There is no offline fixture for 'this ciphertext no longer opens' that would prove anything about the real fleet. Read-only: it never writes, signs, or broadcasts.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-deploy-artifacts",
+ "npm": "audit:deploy",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A symlink committed to the index, which the deploy bundler cannot resolve.",
+ "reason": null,
+ "evidence": null,
+ "ms": 102
+ },
+ {
+ "id": "audit-docs",
+ "npm": "audit:docs",
+ "verdict": "proven",
+ "baseline": "red",
+ "summary": "A doc whose relative link points at a file that does not exist.",
+ "reason": null,
+ "evidence": "docs/guard-proof-dead-link.md:3 ./guard-proof-nowhere.md",
+ "ms": 1942
+ },
+ {
+ "id": "audit-empty-handlers",
+ "npm": "audit:handlers",
"verdict": "proven",
"baseline": "clean",
- "summary": "A staged source file carrying an unresolved conflict marker.",
+ "summary": "An API file that is routable but exports nothing, so it can never serve a response.",
"reason": null,
- "evidence": "src/guard-proof-conflict.js (line 2)",
- "ms": 29785
+ "evidence": "api/guard-proof-empty.js: empty file",
+ "ms": 386
},
{
- "id": "check-claude-md",
- "npm": "check:claude",
+ "id": "audit-garments",
+ "npm": "audit:garments",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Fetches every published garment asset over the network and inspects the returned GLB, so there is no offline input to mutate.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-guards",
+ "npm": "audit:guards",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "A registry entry naming a guard script that is not in the repository.",
+ "reason": null,
+ "evidence": "[audit-guards] guard `audit-agent-operability` names script `scripts/guard-proof-missing.mjs`, which does not exist",
+ "ms": 144
+ },
+ {
+ "id": "audit-hidden-guard",
+ "npm": "audit:hidden-guard",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "A product page that links no shared stylesheet, so [hidden] never hides anything.",
+ "reason": null,
+ "evidence": "pages/guard-proof-unguarded.html",
+ "ms": 209
+ },
+ {
+ "id": "audit-home-credential-health",
+ "npm": "audit:home-credentials",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "It reads the production home_connections table and the live encryption key, then decrypts in memory to test each token against the current key. There is no offline fixture for \"this ciphertext no longer opens\" that would prove anything about the real fleet. Read-only: it never writes and never opens a socket to any house.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-ibm-hosted-page",
+ "npm": "audit:ibm-hosted",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Serves pages/ibm/ from a throwaway origin and lets it talk to a real three.ws over the network, because the thing under test is the browser enforcing cross-origin rules against live response headers. Any stub or proxy would answer for three.ws and satisfy CORS on the browser behalf, blinding the audit to the only failure it exists to catch.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-image-loading",
+ "npm": "check:images",
"verdict": "proven",
"baseline": "red",
- "summary": "CLAUDE.md telling an agent to run an npm script that does not exist.",
+ "summary": "A JS-rendered image with no loading attribute, which fetches eagerly off-screen.",
"reason": null,
- "evidence": "[check-claude] npm script `guard-proof-nonexistent` is referenced but missing from package.json",
- "ms": 1488
+ "evidence": "src/guard-proof-img.js:2",
+ "ms": 2251
},
{
- "id": "sync-studio-openapi",
- "npm": "check:studio-openapi",
+ "id": "audit-inline-handlers",
+ "npm": "audit:inline-handlers",
"verdict": "proven",
"baseline": "clean",
- "summary": "The submission kit shipping an Actions contract that no longer matches the schema the site serves.",
+ "summary": "A page wiring a click through an onclick attribute, which no script hash can cover.",
"reason": null,
- "evidence": "3D Studio OpenAPI drift: prompts/store-submissions/_generated/openai-actions.yaml does not match public/.well-known/3d-studio-openapi.yaml.",
- "ms": 1325
+ "evidence": "pages/guard-proof-inline-handler.html:4 inline event handler",
+ "ms": 910
},
{
- "id": "check-rules",
- "npm": "check:rules",
+ "id": "audit-interactive-states",
+ "npm": "audit:states",
+ "verdict": "control-failed",
+ "baseline": "red",
+ "summary": "A stylesheet declaring a clickable selector with no hover rule for it.",
+ "reason": null,
+ "evidence": null,
+ "ms": 190
+ },
+ {
+ "id": "audit-links",
+ "npm": "audit:links",
"verdict": "proven",
+ "baseline": "clean",
+ "summary": "A route in vercel.json whose destination file was never created.",
+ "reason": null,
+ "evidence": "✗ /guard-proof-dangling → /guard-proof-dangling.html",
+ "ms": 13073
+ },
+ {
+ "id": "audit-llm-metering",
+ "npm": "audit:llm-metering",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Aggregates the usage_events ledger over a time window, so it has no offline input. The rule it applies is unit-tested without a database in tests/llm-metering-rule.test.js.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-mcp-catalog",
+ "npm": "audit:mcp-catalog",
+ "verdict": "wrong-reason",
"baseline": "red",
- "summary": "A new source file whose added lines break a CLAUDE.md hard rule.",
+ "summary": "A new MCP tool landing without regenerating the public catalog.",
"reason": null,
- "evidence": "[check-rules] src/guard-proof-rule.js:1 [todo]",
- "ms": 17074
+ "evidence": null,
+ "ms": 127
},
{
- "id": "check-secrets",
- "npm": "check:secrets",
+ "id": "audit-mcp-golden",
+ "npm": "audit:mcp-golden",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A tool contract appearing on the wire without being declared in the golden fixture.",
+ "reason": null,
+ "evidence": null,
+ "ms": 123
+ },
+ {
+ "id": "audit-mcp-listing",
+ "npm": "audit:mcp-listing",
"verdict": "proven",
"baseline": "clean",
- "summary": "An SSH private key staged as a tracked file.",
+ "summary": "A new MCP server landing with no listing copy, so its directory card would be blank.",
"reason": null,
- "evidence": "[check-secrets] id_ed25519:1 [ssh-key]",
- "ms": 6046
+ "evidence": "[mcp-listing-source] no curated listing copy for io.github.nirholas/guard-proof-mcp (packages/guard-proof-mcp/server.json). Add it to OVERLAY",
+ "ms": 140
},
{
- "id": "check-cron-drift",
- "npm": "check:cron-drift",
+ "id": "audit-mcp-surfaces",
+ "npm": "audit:mcp-surfaces",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "The public MCP directory advertising no guided prompts for the main server while the code still serves them.",
+ "reason": null,
+ "evidence": null,
+ "ms": 74
+ },
+ {
+ "id": "check-pay-skills",
+ "npm": "check:pay-skills",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A committed provider listing edited by hand, so it no longer matches what the catalog generates.",
+ "reason": null,
+ "evidence": null,
+ "ms": 116
+ },
+ {
+ "id": "audit-mcp-manifests",
+ "npm": "audit:mcp",
+ "verdict": "control-failed",
+ "baseline": "red",
+ "summary": "A registry manifest whose description exceeds the 100-character schema limit.",
+ "reason": null,
+ "evidence": null,
+ "ms": 52
+ },
+ {
+ "id": "audit-mcp-reviewer",
+ "npm": "audit:mcp-reviewer",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "Compares the crons declared in vercel.json against the jobs actually deployed to Cloud Scheduler, so it needs an authenticated gcloud session and the live project. There is nothing offline to mutate.",
+ "reason": "It spawns the real published server over stdio and calls every tool, and several tools reach live upstreams. A static fixture cannot produce a payment challenge from the x402 wrapper, which is the thing under test.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-mcp-safety",
+ "npm": "audit:mcp-safety",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A tool shipping with no safety annotations at all, so a client cannot judge it.",
+ "reason": null,
+ "evidence": null,
+ "ms": 99
+ },
+ {
+ "id": "audit-motion-drift",
+ "npm": "audit:motion-tokens",
+ "verdict": "control-failed",
+ "baseline": "red",
+ "summary": "A stylesheet whose transition states its duration and easing as literals instead of tokens.",
+ "reason": null,
+ "evidence": null,
+ "ms": 244
+ },
+ {
+ "id": "audit-overlays",
+ "npm": "audit:overlays",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Drives a real Chromium over real routes at real viewports and measures painted geometry, so the input is a rendered page rather than a file a fixture could write.",
"evidence": null,
"ms": 0
},
@@ -78,385 +298,615 @@
"summary": "A public page route in vercel.json that no data/pages.json entry documents.",
"reason": null,
"evidence": "/guard-proof-orphan",
- "ms": 915
+ "ms": 292
},
{
- "id": "check-pages",
- "npm": "check:pages",
+ "id": "audit-play-failure-modes",
+ "npm": "audit:play-failures",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Needs Playwright plus a running server, because the thing under test is how the page behaves when a specific request is aborted or rewritten mid-load. A static fixture cannot fail a fetch the page has not made yet.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-rig-coverage",
+ "npm": "audit:rig-coverage",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Loads real avatar rigs from production storage and retargets clips onto them, which needs live credentials and the model bucket.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-route-shadowing",
+ "npm": "audit:route-shadowing",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "The audit currently reports a real backlog of 46 shadowed handlers, so it exits non-zero against the live repo and cannot yet pass the control half of a sandboxed proof. It stays a manual audit until that backlog is cleared, at which point it can move into the gate with a two-sided proof.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-seo",
+ "npm": "audit:seo",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Reads the served response from a live origin, because only that proves what a crawler receives after routing, the shell rewrite and the CDN. A local fixture cannot show a canonical or a sitemap status the CDN produced.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-service-wallets",
+ "npm": "audit:service-wallets",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Reads live balances for the service wallets over RPC using the production keys in .env.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-token-drift",
+ "npm": "audit:tokens",
+ "verdict": "control-failed",
+ "baseline": "red",
+ "summary": "A token-covered page hardcoding a hex that is literally a design token.",
+ "reason": null,
+ "evidence": null,
+ "ms": 244
+ },
+ {
+ "id": "audit-tour-atlas",
+ "npm": "audit:tour-atlas",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "The check re-renders the committed atlas from data/tour-atlas.json and verifies 160 captured screenshots exist on disk; a sandbox proof would need the full media tree copied per run, so it is exercised by the real gate instead.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-upstreams",
+ "npm": "audit:upstreams",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A new outbound call to a third-party host with no deadline behind it.",
+ "reason": null,
+ "evidence": null,
+ "ms": 103
+ },
+ {
+ "id": "audit-wallet-flows",
+ "npm": "audit:wallet-flows",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Reconstructs on-chain transfer history for the fleet wallets from live RPC, so it has no offline input.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "audit-x402-catalog",
+ "npm": "audit:x402-catalog",
"verdict": "proven",
"baseline": "clean",
- "summary": "A page advertised in data/pages.json with no built file behind it.",
+ "summary": "A paid x402 endpoint that no buyer can find, because the catalog never mentions it.",
"reason": null,
- "evidence": "[check-pages] /guards : not built into dist/ (missing vite input entry?)",
- "ms": 1187
+ "evidence": "/api/x402/guard-proof-endpoint",
+ "ms": 100
},
{
- "id": "verify-routes",
- "npm": "audit:routes",
+ "id": "build-motion-signatures",
+ "npm": "audit:motion",
"verdict": "proven",
+ "baseline": "clean",
+ "summary": "A stored signature index that no longer matches the baked clips.",
+ "reason": null,
+ "evidence": "signatures.json is stale. Run: npm run build:motion-signatures",
+ "ms": 1076
+ },
+ {
+ "id": "build-openai-skills-bundle",
+ "npm": "check:openai-skills",
+ "verdict": "control-failed",
"baseline": "red",
- "summary": "Deleting the route that serves a catalogued page, so its pretty URL 404s.",
+ "summary": "A published bundle file edited by hand, so it no longer matches the skill it was generated from.",
"reason": null,
- "evidence": "COVERAGE /guards canonical → notfound (404) /404.html",
- "ms": 9446
+ "evidence": null,
+ "ms": 78
},
{
- "id": "audit-empty-handlers",
- "npm": "audit:handlers",
+ "id": "build-skills-pack",
+ "npm": "check:skills-pack",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A generated manifest edited by hand, so it no longer matches the skill folders.",
+ "reason": null,
+ "evidence": null,
+ "ms": 158
+ },
+ {
+ "id": "build-skills-seed",
+ "npm": "check:skills-seed",
"verdict": "proven",
"baseline": "clean",
- "summary": "An API file that is routable but exports nothing, so it can never serve a response.",
+ "summary": "A seed entry whose stored body no longer matches its SKILL.md.",
"reason": null,
- "evidence": "api/guard-proof-empty.js: empty file",
- "ms": 4562
+ "evidence": "DRIFT: data/skills/seed.json does not match its sources (1 difference(s)):",
+ "ms": 218
},
{
- "id": "audit-hidden-guard",
- "npm": "audit:hidden-guard",
+ "id": "build-standalone-skill-repos",
+ "npm": "check:skill-repos",
"verdict": "proven",
"baseline": "clean",
- "summary": "A product page that links no shared stylesheet, so [hidden] never hides anything.",
+ "summary": "A skill folder that lost its SKILL.md while a repo spec still selects it.",
"reason": null,
- "evidence": "pages/guard-proof-unguarded.html",
- "ms": 2249
+ "evidence": "throw new Error(`${entry.name}: missing SKILL.md`);",
+ "ms": 121
},
{
- "id": "audit-inline-handlers",
- "npm": "audit:inline-handlers",
+ "id": "check-announce",
+ "npm": "check:announce",
+ "verdict": "proven",
+ "baseline": "red",
+ "summary": "An announcement pack whose post opens with banned marketing copy and declares no media.",
+ "reason": null,
+ "evidence": "guard-proof-pack: post is 99 weighted chars; under 100 it says a thing exists and not how it works",
+ "ms": 139
+ },
+ {
+ "id": "check-api-imports",
+ "npm": "check:api-imports",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A shared API module that throws at load time, the way a dependency with a changed constructor does.",
+ "reason": null,
+ "evidence": null,
+ "ms": 78
+ },
+ {
+ "id": "check-apple-widget",
+ "npm": "check:apple-widget",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "The Swift client stops reading a header api/glance/mine.js still sets.",
+ "reason": null,
+ "evidence": null,
+ "ms": 99
+ },
+ {
+ "id": "check-asset-encoding",
+ "npm": "check:asset-encoding",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "It requests assets from the live CDN and compares the promised length against the bytes that actually arrive, so the failure it catches exists only in a served response. A local file has no content-encoding negotiation to get wrong.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "check-awesome",
+ "npm": "check:awesome",
"verdict": "proven",
"baseline": "clean",
- "summary": "A page wiring a click through an onclick attribute, which no script hash can cover.",
+ "summary": "A generated output edited by hand, so it no longer matches data/awesome.json.",
"reason": null,
- "evidence": "pages/guard-proof-inline-handler.html:4 inline event handler",
- "ms": 7971
+ "evidence": "[build-awesome] out of date: awesome/README.md",
+ "ms": 110
},
{
- "id": "audit-csp",
- "npm": "audit:csp",
+ "id": "check-awesome-links",
+ "npm": "awesome:links",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Fetches every listed url from the real hosts, so only the live answer distinguishes a moved link, a bot filter and a dead one. A static fixture cannot produce any of the three.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "check-browser-graph",
+ "npm": "check:browser-graph",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "A Node built-in reaching the browser bundle through a real import chain.",
+ "reason": null,
+ "evidence": "src/solana/sns.js imports \"node:util\"",
+ "ms": 1694
+ },
+ {
+ "id": "check-claude-md",
+ "npm": "check:claude",
+ "verdict": "proven",
+ "baseline": "red",
+ "summary": "CLAUDE.md telling an agent to run an npm script that does not exist.",
+ "reason": null,
+ "evidence": "[check-claude] npm script `guard-proof-nonexistent` is referenced but missing from package.json",
+ "ms": 190
+ },
+ {
+ "id": "check-cron-drift",
+ "npm": "check:cron-drift",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Compares the crons declared in vercel.json against the jobs actually deployed to Cloud Scheduler, so it needs an authenticated gcloud session and the live project. There is nothing offline to mutate.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "check-deps",
+ "npm": "audit:deps",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Queries the OSV database over its public API for every pinned requirement, so the answer changes as advisories are published and there is nothing offline to mutate. The requirement parsing it depends on is covered by tests/check-deps.test.js instead.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "check-dist",
+ "npm": "check:dist",
+ "verdict": "proven",
+ "baseline": "red",
+ "summary": "A build that finished without producing the published embed bundle.",
+ "reason": null,
+ "evidence": "[check-dist] MISSING: dist/dist-lib/agent-3d.umd.cjs",
+ "ms": 624
+ },
+ {
+ "id": "check-doc-media",
+ "npm": "check:doc-media",
+ "verdict": "proven",
+ "baseline": "red",
+ "summary": "A doc figure whose image file does not exist on disk.",
+ "reason": null,
+ "evidence": "FAIL /docs/img/guard-proof-missing.png is referenced by docs/guard-proof-media.md but does not exist. Run: node scripts/capture-doc-media.mjs --only guard-proof-missing",
+ "ms": 487
+ },
+ {
+ "id": "check-docs-freshness",
+ "npm": "check:docs-freshness",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "The input is git history, not a file: a doc is stale because of the commits that landed after it, which a sandbox cannot fabricate without rewriting history. The corpus is also over its budget of 5 at the time of registering, so the control half of a two-sided proof would fail against the real repo until the queue is refreshed.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "check-earnings-board",
+ "npm": "check:earnings-board",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Pages through the live board and asks each ranked agent for its own earnings over public GET requests, so the rows it compares only exist in a running deployment. It is read-only. The offline half of the same comparison is tests/agent-earnings-board.test.js.",
+ "evidence": null,
+ "ms": 0
+ },
+ {
+ "id": "check-erc7710-addresses",
+ "npm": "check:erc7710",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "Needs Playwright plus a server serving dist/, because the thing under test is the browser's own policy evaluation against a real response. A static fixture cannot produce a securitypolicyviolation event.",
+ "reason": "Resolves the delegation-framework contract addresses against live chain RPC, so the values it compares only exist on-chain.",
"evidence": null,
"ms": 0
},
{
- "id": "audit-docs",
- "npm": "audit:docs",
+ "id": "check-event-window",
+ "npm": "check:event",
"verdict": "proven",
"baseline": "clean",
- "summary": "A doc whose relative link points at a file that does not exist.",
+ "summary": "An event window whose end has already passed, which every surface reads as 'no event' and mounts nothing.",
"reason": null,
- "evidence": "docs/guard-proof-dead-link.md:3 ./guard-proof-nowhere.md",
- "ms": 20345
+ "evidence": "[check-event] the event window ENDED 59708h ago (2020-01-01T02:00:00Z UTC), so the countdown, agenda, fireworks, souvenir grant and event leaderboard are all silently dormant. Reschedule with `npm run event:schedule -- --start <ISO> --dur",
+ "ms": 136
},
{
- "id": "sync-tutorial-pages",
- "npm": "check:tutorials",
+ "id": "check-fetch-timeouts",
+ "npm": "check:fetch-timeouts",
"verdict": "proven",
"baseline": "clean",
- "summary": "A tutorial markdown file that no manifest entry points at, so nothing can reach it.",
+ "summary": "A fetch to a third-party host added with no signal and no bounding wrapper.",
"reason": null,
- "evidence": "markdown with no manifest entry (unreachable): guard-proof-orphan",
- "ms": 758
+ "evidence": "api/_lib/rugcheck.js:103",
+ "ms": 842
},
{
- "id": "audit-mcp-catalog",
- "npm": "audit:mcp-catalog",
+ "id": "check-gcloudignore",
+ "npm": "check:gcloudignore",
"verdict": "proven",
"baseline": "clean",
- "summary": "A new MCP tool landing without regenerating the public catalog.",
+ "summary": "A missing .gcloudignore, which silently hands the upload set back to .gitignore.",
"reason": null,
- "evidence": "[audit:mcp-catalog] public/mcp-catalog.json is stale.",
- "ms": 24307
+ "evidence": "FAIL: ignore file not found: /home/user/projects/.guard-proof-wt-378639/.gcloudignore",
+ "ms": 564
},
{
- "id": "audit-x402-catalog",
- "npm": "audit:x402-catalog",
- "verdict": "proven",
- "baseline": "clean",
- "summary": "A paid x402 endpoint that no buyer can find, because the catalog never mentions it.",
+ "id": "check-home-matrix",
+ "npm": "check:home-matrix",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "The measured matrix says one thing and the published table another.",
"reason": null,
- "evidence": "/api/x402/guard-proof-endpoint",
- "ms": 1019
+ "evidence": null,
+ "ms": 107
},
{
- "id": "audit-mcp-manifests",
- "npm": "audit:mcp",
- "verdict": "proven",
- "baseline": "clean",
- "summary": "A registry manifest whose description exceeds the 100-character schema limit.",
- "reason": null,
- "evidence": "[audit:mcp] server.json: description is 150 chars (registry max is 100)",
- "ms": 1463
+ "id": "check-home-voice",
+ "npm": "check:home-voice",
+ "verdict": "declared-live",
+ "baseline": null,
+ "summary": null,
+ "reason": "Drives a real Chromium against the running voice loop with a synthesized microphone stream. The behaviours under test (a wake word firing, playback stopping on barge-in, a capture track actually ending) only exist at runtime, so there is no static fixture that could stand in for them.",
+ "evidence": null,
+ "ms": 0
},
{
- "id": "audit-mcp-golden",
- "npm": "audit:mcp-golden",
+ "id": "check-ios-app",
+ "npm": "check:ios-app",
"verdict": "proven",
"baseline": "clean",
- "summary": "A tool contract appearing on the wire without being declared in the golden fixture.",
+ "summary": "The share extension loses the Swift file that hands a shared model to the app.",
"reason": null,
- "evidence": "[audit:mcp-golden] api/_mcp/tools/guard-proof-golden.js: tool ADDED: guard_proof_golden",
- "ms": 8497
+ "evidence": "[ios-app] FAIL ios/native/App/ShareExtension/ShareViewController.swift is missing",
+ "ms": 120
},
{
- "id": "audit-mcp-safety",
- "npm": "audit:mcp-safety",
- "verdict": "proven",
- "baseline": "clean",
- "summary": "A tool shipping with no safety annotations at all, so a client cannot judge it.",
+ "id": "check-ios-icons",
+ "npm": "check:ios-icons",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "The committed app icon replaced with bytes the brand mark does not produce.",
"reason": null,
- "evidence": "[audit:mcp-safety] api/_mcp/tools/guard-proof-safety.js: guard_proof_safety: no annotations. destructiveHint defaults to TRUE when omitted, so this tool is advertised as destructive. Declare them explicitly.",
- "ms": 21312
+ "evidence": null,
+ "ms": 117
},
{
- "id": "audit-token-drift",
- "npm": "audit:tokens",
- "verdict": "proven",
- "baseline": "clean",
- "summary": "A token-covered page hardcoding a hex that is literally a design token.",
+ "id": "check-macos-icon",
+ "npm": "check:macos-icon",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A committed Mac icon size replaced with bytes the brand mark does not produce.",
"reason": null,
- "evidence": "✗ design-token drift increased: 2 hardcoded token-hexes (baseline 0).",
- "ms": 3234
+ "evidence": null,
+ "ms": 124
},
{
- "id": "check-browser-graph",
- "npm": "check:browser-graph",
+ "id": "check-mcp-catalog",
+ "npm": "check:mcp-catalog",
"verdict": "proven",
"baseline": "clean",
- "summary": "A Node built-in reaching the browser bundle through a real import chain.",
+ "summary": "A catalog file that is no longer valid JSON.",
"reason": null,
- "evidence": "src/solana/sns.js imports \"node:util\"",
- "ms": 11561
+ "evidence": "check:mcp-catalog: data/mcp-catalog.json is not valid JSON (Unexpected token 'g', ...\"rvers\": [ guard proo\"... is not valid JSON)",
+ "ms": 106
},
{
- "id": "check-dist",
- "npm": "check:dist",
+ "id": "check-merge-conflicts",
+ "npm": "check:conflicts",
"verdict": "proven",
"baseline": "clean",
- "summary": "A build that finished without producing the published embed bundle.",
- "reason": null,
- "evidence": "[check-dist] MISSING: dist/dist-lib/agent-3d.umd.cjs",
- "ms": 883
- },
- {
- "id": "audit-deploy-artifacts",
- "npm": "audit:deploy",
- "verdict": "proven",
- "baseline": "red",
- "summary": "A symlink committed to the index, which the deploy bundler cannot resolve.",
+ "summary": "A staged source file carrying an unresolved conflict marker.",
"reason": null,
- "evidence": "data/guard-proof-link.md → replace with a real copy of the target",
- "ms": 16619
+ "evidence": "src/guard-proof-conflict.js (line 2)",
+ "ms": 3143
},
{
- "id": "check-gcloudignore",
- "npm": "check:gcloudignore",
+ "id": "check-model-viewer-version",
+ "npm": "check:model-viewer",
"verdict": "proven",
"baseline": "clean",
- "summary": "A missing .gcloudignore, which silently hands the upload set back to .gitignore.",
- "reason": null,
- "evidence": "FAIL: ignore file not found: /workspaces/.guard-proof-wt-568274/.gcloudignore",
- "ms": 3007
- },
- {
- "id": "audit-links",
- "npm": "audit:links",
- "verdict": "proven",
- "baseline": "red",
- "summary": "A route in vercel.json whose destination file was never created.",
+ "summary": "A model-viewer reference bumped to a version the rest of the tree does not use.",
"reason": null,
- "evidence": "✗ /guard-proof-dangling → /guard-proof-dangling.html",
- "ms": 178926
+ "evidence": "9.9.9 in 1 file(s):",
+ "ms": 6716
},
{
- "id": "audit-console",
- "npm": "audit:console",
+ "id": "check-openai-fields",
+ "npm": "check:openai-fields",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "Drives a real browser over the live page set and reads the console, so it needs Playwright and a running server. A static fixture cannot produce a runtime console error.",
+ "reason": "The fields it measures are constants defined inside the script itself, so the only way to plant an over-long field is to replace the checker with a modified copy of itself, which would prove the copy rather than the guard. The proof sandbox mutates inputs, and this guard has none outside its own source.",
"evidence": null,
"ms": 0
},
{
- "id": "audit-image-loading",
- "npm": "check:images",
+ "id": "check-pages",
+ "npm": "check:pages",
"verdict": "proven",
"baseline": "clean",
- "summary": "A JS-rendered image with no loading attribute, which fetches eagerly off-screen.",
+ "summary": "A page advertised in data/pages.json with no built file behind it.",
"reason": null,
- "evidence": "src/guard-proof-img.js:2",
- "ms": 36764
- },
- {
- "id": "audit-garments",
- "npm": "audit:garments",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "Fetches every published garment asset over the network and inspects the returned GLB, so there is no offline input to mutate.",
- "evidence": null,
- "ms": 0
+ "evidence": "[check-pages] /guards : not built into dist/ (missing vite input entry?)",
+ "ms": 144
},
{
- "id": "audit-rig-coverage",
- "npm": "audit:rig-coverage",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "Loads real avatar rigs from production storage and retargets clips onto them, which needs live credentials and the model bucket.",
- "evidence": null,
- "ms": 0
+ "id": "check-prompt-library",
+ "npm": "check:prompt-library",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "A generated copy edited by hand, so it no longer matches data/prompt-library.json.",
+ "reason": null,
+ "evidence": "Prompt library outputs are stale: public/prompts.txt",
+ "ms": 117
},
{
- "id": "audit-service-wallets",
- "npm": "audit:service-wallets",
+ "id": "check-relayer-balances",
+ "npm": "check:relayer-balances",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "Reads live balances for the service wallets over RPC using the production keys in .env.",
+ "reason": "Queries the funded relayer accounts over RPC and compares them against the operating floor, which only exists on-chain.",
"evidence": null,
"ms": 0
},
{
- "id": "audit-wallet-flows",
- "npm": "audit:wallet-flows",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "Reconstructs on-chain transfer history for the fleet wallets from live RPC, so it has no offline input.",
- "evidence": null,
- "ms": 0
+ "id": "check-rules",
+ "npm": "check:rules",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "A new source file whose added lines break a CLAUDE.md hard rule.",
+ "reason": null,
+ "evidence": "[check-rules] src/guard-proof-rule.js:1 [todo]",
+ "ms": 366
},
{
- "id": "audit-llm-metering",
- "npm": "audit:llm-metering",
+ "id": "check-runnable-docs",
+ "npm": "check:runnable-docs",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "Aggregates the usage_events ledger over a time window, so it has no offline input. The rule it applies is unit-tested without a database in tests/llm-metering-rule.test.js.",
+ "reason": "Executes the documented calls against the live API and compares real response statuses, so there is no offline input to mutate.",
"evidence": null,
"ms": 0
},
{
- "id": "check-relayer-balances",
- "npm": "check:relayer-balances",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "Queries the funded relayer accounts over RPC and compares them against the operating floor, which only exists on-chain.",
- "evidence": null,
- "ms": 0
+ "id": "check-secrets",
+ "npm": "check:secrets",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "An SSH private key staged as a tracked file.",
+ "reason": null,
+ "evidence": "[check-secrets] id_ed25519:1 [ssh-key]",
+ "ms": 422
},
{
- "id": "audit-guards",
- "npm": "audit:guards",
+ "id": "check-sri-pins",
+ "npm": "check:sri-pins",
"verdict": "proven",
"baseline": "clean",
- "summary": "A registry entry naming a guard script that is not in the repository.",
+ "summary": "A doc snippet pinning a released version to a hash that is not the released one.",
"reason": null,
- "evidence": "[audit-guards] guard `check-merge-conflicts` names script `scripts/guard-proof-missing.mjs`, which does not exist",
- "ms": 1414
+ "evidence": "[sri-pins] docs/guard-proof-sri-pin.md:3 agent-3d.js 1.5.2 is pinned to sha384-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA but the release is sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q; brow",
+ "ms": 654
},
{
- "id": "check-erc7710-addresses",
- "npm": "check:erc7710",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "Resolves the delegation-framework contract addresses against live chain RPC, so the values it compares only exist on-chain.",
+ "id": "check-tdz-bootstrap",
+ "npm": "check:tdz-bootstrap",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "A page whose top-level bootstrap writes a `let` declared further down the module.",
+ "reason": null,
"evidence": null,
- "ms": 0
+ "ms": 99
},
{
- "id": "audit-overlays",
- "npm": "audit:overlays",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "Drives a real Chromium over real routes at real viewports and measures painted geometry, so the input is a rendered page rather than a file a fixture could write.",
+ "id": "check-vendored-workers",
+ "npm": "check:vendored",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "One worker's copy of worker_security.py edited so it no longer matches the other sixteen.",
+ "reason": null,
+ "evidence": "worker_security.py: 1 of 26 copies differ from workers/avatar-pipeline-controller/worker_security.py",
+ "ms": 108
+ },
+ {
+ "id": "check-windows-widget",
+ "npm": "check:windows-widget",
+ "verdict": "wrong-reason",
+ "baseline": "clean",
+ "summary": "A screenshot the manifest advertises to the widget picker is gone from the tree.",
+ "reason": null,
"evidence": null,
- "ms": 0
+ "ms": 449
},
{
- "id": "check-runnable-docs",
- "npm": "check:runnable-docs",
+ "id": "check-xai-models",
+ "npm": "check:xai-models",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "Executes the documented calls against the live API and compares real response statuses, so there is no offline input to mutate.",
+ "reason": "The thing under test is what xAI serves today, read from its models API or its public model docs. There is no offline input whose mutation proves anything about a third party's live catalog, and the comparison never sends a prompt or spends a token. The key, when set, is only ever sent to api.x.ai.",
"evidence": null,
"ms": 0
},
{
- "id": "check-doc-media",
- "npm": "check:doc-media",
+ "id": "check-mcp-counts",
+ "npm": "check:mcp-counts",
"verdict": "proven",
- "baseline": "red",
- "summary": "A doc figure whose image file does not exist on disk.",
+ "baseline": "clean",
+ "summary": "A living doc whose marker claims a tool count the census does not have.",
"reason": null,
- "evidence": "FAIL /docs/img/guard-proof-missing.png is referenced by docs/guard-proof-media.md but does not exist. Run: node scripts/capture-doc-media.mjs --only guard-proof-missing",
- "ms": 5155
+ "evidence": "docs/guard-proof-mcp-count.md:3: mcp-3d.tools says 9999, the census says 40",
+ "ms": 2852
},
{
- "id": "check-event-window",
- "npm": "check:event",
+ "id": "check-site-builder-embeds",
+ "npm": "check:site-builder-embeds",
"verdict": "proven",
"baseline": "clean",
- "summary": "An event window whose end has already passed, which every surface reads as 'no event' and mounts nothing.",
+ "summary": "A pinned-release file edited by hand so it no longer matches the ledger.",
"reason": null,
- "evidence": "[check-event] the event window ENDED 57999h ago (2020-01-01T02:00:00Z UTC), so the countdown, agenda, fireworks, souvenir grant and event leaderboard are all silently dormant. Reschedule with `npm run event:schedule -- --start <ISO> --dur",
- "ms": 1797
+ "evidence": "[site-builder-embeds] integrations/webflow/src/pinned-release.ts does not match the ledger (agent-3d 1.5.2); run: npm run build:site-builder-embeds",
+ "ms": 104
},
{
- "id": "audit-tour-atlas",
- "npm": "audit:tour-atlas",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "The check re-renders the committed atlas from data/tour-atlas.json and verifies 160 captured screenshots exist on disk; a sandbox proof would need the full media tree copied per run, so it is exercised by the real gate instead.",
+ "id": "i18n-home",
+ "npm": "i18n:home",
+ "verdict": "wrong-reason",
+ "baseline": "red",
+ "summary": "The catalog's English keeps a sentence the code no longer says.",
+ "reason": null,
"evidence": null,
- "ms": 0
+ "ms": 87
},
{
- "id": "audit-route-shadowing",
- "npm": "audit:route-shadowing",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "The audit currently reports a real backlog of 46 shadowed handlers, so it exits non-zero against the live repo and cannot yet pass the control half of a sandboxed proof. It stays a manual audit until that backlog is cleared, at which point it can move into the gate with a two-sided proof.",
- "evidence": null,
- "ms": 0
+ "id": "sync-studio-openapi",
+ "npm": "check:studio-openapi",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "The submission kit shipping an Actions contract that no longer matches the schema the site serves.",
+ "reason": null,
+ "evidence": "3D Studio OpenAPI drift: prompts/store-submissions/_generated/openai-actions.yaml does not match public/.well-known/3d-studio-openapi.yaml.",
+ "ms": 91
},
{
- "id": "audit-cron-liveness",
- "npm": "audit:cron-liveness",
+ "id": "sync-tour-global",
+ "npm": "audit:tour-global",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "The run stage boots the real server on a free port and probes every cron URL, so the check is inherently live. The probe is deliberately unauthenticated and every handler fails closed on CRON_SECRET, so no job body executes: nothing is paid, swapped, minted, transferred, or written. `--static` skips the boot for a route-and-load-only pass.",
+ "reason": "The check is a comparison against a fresh `npm run build` of tour-sdk, so proving it needs that build to reproduce byte-for-byte. It does not inside the proof sandbox, which reports the served copy as stale before any fixture is applied and leaves nothing attributable to the fixture. Run `npm run audit:tour-global` on a real tree instead.",
"evidence": null,
"ms": 0
},
{
- "id": "audit-custodial-key-health",
- "npm": "audit:custodial-keys",
- "verdict": "declared-live",
- "baseline": null,
- "summary": null,
- "reason": "It reads the production wallet table and the live encryption key, then decrypts in memory to test each secret against the current key. There is no offline fixture for 'this ciphertext no longer opens' that would prove anything about the real fleet. Read-only: it never writes, signs, or broadcasts.",
- "evidence": null,
- "ms": 0
+ "id": "sync-tutorial-pages",
+ "npm": "check:tutorials",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "A tutorial markdown file that no manifest entry points at, so nothing can reach it.",
+ "reason": null,
+ "evidence": "markdown with no manifest entry (unreachable): guard-proof-orphan",
+ "ms": 102
},
{
- "id": "audit-play-failure-modes",
- "npm": "audit:play-failures",
+ "id": "verify-routes",
+ "npm": "audit:routes",
+ "verdict": "proven",
+ "baseline": "clean",
+ "summary": "Deleting the route that serves a catalogued page, so its pretty URL 404s.",
+ "reason": null,
+ "evidence": "COVERAGE /guards canonical → notfound (404) /404.html",
+ "ms": 855
+ },
+ {
+ "id": "check-trading-routes",
+ "npm": "check:trading-routes",
"verdict": "declared-live",
"baseline": null,
"summary": null,
- "reason": "Needs Playwright plus a running server, because the thing under test is how the page behaves when a specific request is aborted or rewritten mid-load. A static fixture cannot fail a fetch the page has not made yet.",
+ "reason": "Quotes and simulates against live aggregators and a mainnet RPC for a funded wallet's public key.",
"evidence": null,
"ms": 0
}
diff --git a/public/guards.json b/public/guards.json
index 3c225a471..95f8b48df 100644
--- a/public/guards.json
+++ b/public/guards.json
@@ -1,5 +1,5 @@
{
- "updated": "2026-10-09",
+ "updated": "2026-10-23",
"summary": "Every mechanical guard that protects this repository, and the stage each one runs in. This file is the single source of truth: scripts/audit-guards.mjs proves every entry is real and every stage claim is true, docs/guards.md explains them, and /guards renders them.",
"stages": [
{
@@ -1701,6 +1701,48 @@
"reason": "The thing under test is what xAI serves today, read from its models API or its public model docs. There is no offline input whose mutation proves anything about a third party's live catalog, and the comparison never sends a prompt or spends a token. The key, when set, is only ever sent to api.x.ai."
}
},
+ {
+ "id": "check-mcp-counts",
+ "script": "scripts/check-mcp-counts.mjs",
+ "npm": "check:mcp-counts",
+ "title": "Quoted MCP counts match the census",
+ "protects": "Every tool, resource and prompt count a living doc quotes for a three.ws MCP server equals the census in public/tools.json.",
+ "why": "MCP tools are added weekly and the same number is quoted in READMEs, plugin docs and the architecture overview. Without a check each quote drifts on its own schedule, and a buyer reads 22 tools on a server that serves 40. Counts are written through a marker, so a stale number fails the gate and `--fix` rewrites it from the census.",
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A living doc whose marker claims a tool count the census does not have.",
+ "violation": {
+ "write": {
+ "docs/guard-proof-mcp-count.md": "# Proof fixture\n\nThe 3D server has <!-- mcp-count:mcp-3d.tools -->9999<!-- /mcp-count --> tools.\n"
+ }
+ },
+ "expect": "guard-proof-mcp-count.md"
+ }
+ },
+ {
+ "id": "check-site-builder-embeds",
+ "script": "scripts/check-site-builder-embeds.mjs",
+ "npm": "check:site-builder-embeds",
+ "title": "Site-builder pinned releases match the ledger",
+ "protects": "The WordPress, Framer and Webflow pinned-release files name the same <agent-3d> release as the release ledger.",
+ "why": "Each site-builder integration ships a pinned copy of the agent-3d version it embeds, so a customer's site never floats onto an unreviewed build. When the ledger moves and a pin does not, one integration silently serves an old component. The guard regenerates the expected bytes from the ledger and fails on any difference; `--fix` rewrites them.",
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "A pinned-release file edited by hand so it no longer matches the ledger.",
+ "violation": {
+ "append": {
+ "integrations/webflow/src/pinned-release.ts": "\n// Hand-edited inside the guard sandbox, so the pin no longer matches the ledger.\n"
+ }
+ },
+ "expect": "does not match the ledger"
+ }
+ },
{
"id": "i18n-home",
"script": "scripts/i18n-home-keys.mjs",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index f6dff10cd..69cc15a8d 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -652,6 +652,12 @@ URL: https://three.ws/splat
Render Gaussian-splat and radiance-field avatars in the browser: the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.
+### X Video Downloader
+
+URL: https://three.ws/x-video
+
+Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.
+
### Scene Capture: Video to 3D Point Cloud
URL: https://three.ws/capture
@@ -6856,6 +6862,8 @@ The selection is enforced whichever way you signed in. With a browser sign-in, s
| `provider use three-ws` / `provider show` | Point this machine's model clients at three.ws inference, billed to your credits |
| `usage` | Credits, burn rate, days left and recent top-ups |
| `ask "<prompt>"` | One completion through the active provider |
+| `wallet <init\|address\|export-public>` | A local payer key held in the OS keychain (or an encrypted file behind a passphrase); never printed |
+| `pay <url>` / `pay --dry-run <url>` | Settle an x402 or MPP 402 challenge on Solana with that key, inside `pay-permissions.json`; `pay init`, `pay mcp` (stdio MCP server). See the [package README](../packages/three-ws-cli/README.md#pay-for-x402-and-mpp-resources-from-the-terminal) |
## One command per client
diff --git a/public/llms.txt b/public/llms.txt
index 4a3634307..9d0857b05 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -103,6 +103,6 @@ Machine-readable entry points. Fetch these instead of scraping HTML.
## Optional
-- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (1022) with full descriptions, plus the full markdown of the curated docs.
+- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (1023) with full descriptions, plus the full markdown of the curated docs.
- [Sitemap](https://three.ws/sitemap): The same index for people, with search.
- [sitemap.xml](https://three.ws/sitemap.xml): XML sitemap for crawlers, including every agent and avatar page.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index cec05e134..9759cd24f 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -96,7 +96,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p><span>1086</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p>
+ <p><span>1087</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p>
<div class="sm-formats">
<a href="/everything"><code>/everything</code> · browse by goal, not by section</a>
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
@@ -109,7 +109,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 1086 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 1087 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd id="sm-filter-kbd" aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>
@@ -117,6 +117,14 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/x-video">
+ <span class="sm-new-date" translate="no">Oct 23, 2026</span>
+ <span class="sm-title"><span data-i18n="sitemap_index.t_x_video">X Video Downloader</span></span>
+ <span class="sm-path" translate="no">/x-video</span>
+ <span class="sm-desc" data-i18n="sitemap_index.d_x_video">Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.</span>
+ </a>
+ </li>
<li>
<a href="/readme-3d">
<span class="sm-new-date" translate="no">Oct 23, 2026</span>
@@ -181,14 +189,6 @@
<span class="sm-desc" data-i18n="sitemap_index.d_docs_event_markets_staking">Decision record for staked Event Markets on Solana: the parimutuel model, fee and buyback split, limits, void and refund rules, and the jurisdiction and age questions that stay with the owner.</span>
</a>
</li>
- <li>
- <a href="/docs/google-adk">
- <span class="sm-new-date" translate="no">Oct 13, 2026</span>
- <span class="sm-title"><span data-i18n="sitemap_index.t_docs_google_adk">Docs · three.ws with Google ADK</span></span>
- <span class="sm-path" translate="no">/docs/google-adk</span>
- <span class="sm-desc" data-i18n="sitemap_index.d_docs_google_adk">Connect a Google Agent Development Kit agent to the free three.ws 3D studio over MCPToolset: discover the tool catalog, forge and rig models, and run a full LlmAgent conversation. No account, payment or API key for the studio tools.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -740,7 +740,7 @@
<section class="sm-section" id="build">
<header>
- <h2><span data-i18n="sitemap_index.section_build">Build</span><span class="sm-count" data-count>95</span></h2>
+ <h2><span data-i18n="sitemap_index.section_build">Build</span><span class="sm-count" data-count>96</span></h2>
<p class="sm-section-desc">Create and customize an agent.</p>
</header>
<ul class="sm-list">
@@ -926,6 +926,13 @@
<span class="sm-desc" data-i18n="sitemap_index.d_splat">Render Gaussian-splat and radiance-field avatars in the browser: the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.</span>
</a>
</li>
+ <li>
+ <a href="/x-video">
+ <span class="sm-title"><span data-i18n="sitemap_index.t_x_video">X Video Downloader</span></span>
+ <span class="sm-path" translate="no">/x-video</span>
+ <span class="sm-desc" data-i18n="sitemap_index.d_x_video">Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.</span>
+ </a>
+ </li>
<li>
<a href="/capture">
<span class="sm-title"><span data-i18n="sitemap_index.t_capture">Scene Capture: Video to 3D Point Cloud</span></span>
diff --git a/scripts/allowance-devnet-proof.mjs b/scripts/allowance-devnet-proof.mjs
index 18c93cb98..aefd6a18a 100644
--- a/scripts/allowance-devnet-proof.mjs
+++ b/scripts/allowance-devnet-proof.mjs
@@ -27,14 +27,17 @@ const DECIMALS = 6;
const unit = (n) => BigInt(Math.round(n * 10 ** DECIMALS));
const conn = new Connection(RPC, 'confirmed');
-if (!/devnet/i.test(RPC) && !process.env.ALLOW_NON_DEVNET_NAMED_RPC) {
- console.error('refusing to run: DEVNET_RPC_URL must be a devnet endpoint');
- process.exit(2);
-}
-const genesis = await conn.getGenesisHash();
-if (genesis !== 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG') {
- console.error(`refusing to run: genesis ${genesis} is not devnet`);
- process.exit(2);
+// DEVNET_GENESIS is the real cluster. A local validator that cloned the program
+// from devnet (LOCAL_VALIDATOR=1, http://127.0.0.1) is accepted only for fast
+// iteration; the recorded transcript for the work order is the devnet run.
+const DEVNET_GENESIS = 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG';
+const local = process.env.LOCAL_VALIDATOR === '1' && /^http:\/\/(127\.0\.0\.1|localhost)/.test(RPC);
+if (!local) {
+ const genesis = await conn.getGenesisHash();
+ if (genesis !== DEVNET_GENESIS) {
+ console.error(`refusing to run: genesis ${genesis} is not devnet`);
+ process.exit(2);
+ }
}
const transcript = [];
diff --git a/scripts/x402-prepaid-reconcile.mjs b/scripts/x402-prepaid-reconcile.mjs
new file mode 100644
index 000000000..7f5cae3f7
--- /dev/null
+++ b/scripts/x402-prepaid-reconcile.mjs
@@ -0,0 +1,119 @@
+#!/usr/bin/env node
+// scripts/x402-prepaid-reconcile.mjs
+//
+// Reconciles the x402 prepaid ledger: deposits - debits - settled = held, and
+// each payer balance equals deposits - debits. Prints a zero delta when the
+// books are clean; exits 1 on any problem, 2 on an unusable setup.
+//
+// node scripts/x402-prepaid-reconcile.mjs # reads DATABASE_URL (read-only)
+// node scripts/x402-prepaid-reconcile.mjs --chain # also compare the deposit wallet's USDC
+// node scripts/x402-prepaid-reconcile.mjs --dev # in-process Postgres (PGlite): applies the
+// # migration, runs real deposits, debits, a
+// # refund and a batch settlement, then reconciles
+// --json # machine-readable output
+//
+// DATABASE_URL mode never writes. --dev never touches any remote database.
+
+import { readFileSync } from 'node:fs';
+import { register } from 'node:module';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const args = new Set(process.argv.slice(2));
+const asJson = args.has('--json');
+const dev = args.has('--dev');
+const checkChain = args.has('--chain');
+
+const root = new URL('../', import.meta.url);
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+async function useDevDatabase() {
+ const { PGlite } = await import('@electric-sql/pglite');
+ const pg = new PGlite();
+ await pg.exec(readFileSync(new URL('api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql', root), 'utf8'));
+ globalThis.__prepaidDevPg = pg;
+ const shim = `
+ export const sql = async (strings, ...values) => {
+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? '$' + (i + 1) : ''), '');
+ return (await globalThis.__prepaidDevPg.query(text, values)).rows;
+ };
+ export const isDbUnavailableError = () => false;
+ export const isDbCapacityError = () => false;
+ `;
+ const shimUrl = 'data:text/javascript,' + encodeURIComponent(shim);
+ const hooks = `
+ export async function resolve(specifier, context, next) {
+ if (specifier.endsWith('/_lib/db.js') || specifier === '../db.js') return { url: ${JSON.stringify(shimUrl)}, shortCircuit: true };
+ return next(specifier, context);
+ }
+ `;
+ register('data:text/javascript,' + encodeURIComponent(hooks), pathToFileURL('./'));
+}
+
+async function seedDevLedger() {
+ const ledger = await import('../api/_lib/x402/prepaid-ledger.js');
+ const settle = await import('../api/_lib/x402/prepaid-settle.js');
+ const { PREPAID_NETWORK, PREPAID_ASSET } = await import('../api/_lib/x402/prepaid-constants.js');
+ const key = (payer) => ({ payer, network: PREPAID_NETWORK, asset: PREPAID_ASSET });
+ const payers = ['THREEsyntheticPayer1111111111111111111111', 'THREEsyntheticPayer2222222222222222222222'];
+ const payees = [THREE_MINT, 'THREEsyntheticPayee1111111111111111111111'];
+
+ for (const [i, payer] of payers.entries()) {
+ await ledger.creditDeposit({ ...key(payer), amountAtomics: 5_000_000n, ref: `dev-deposit-${i}` });
+ }
+ const reserved = await Promise.all(
+ Array.from({ length: 40 }, (_, i) =>
+ ledger.reserveDebit({ ...key(payers[i % 2]), amountAtomics: 150_000n, ref: `dev-debit-${i}`, payee: payees[i % 2], route: '/dev' }),
+ ),
+ );
+ let n = 0;
+ for (const r of reserved) {
+ if (!r?.entryId) continue;
+ if (n++ % 5 === 4) await ledger.refundDebit(r.entryId, 'upstream_5xx');
+ else await ledger.commitDebit(r.entryId);
+ }
+ const sent = [];
+ await settle.runSettlementWindow({
+ minSettleAtomics: 1_000_000n,
+ send: async (batches) => {
+ sent.push(batches.length);
+ return `dev-signature-${sent.length}`;
+ },
+ });
+ return { payers: payers.length, debitsAttempted: reserved.length, transactions: sent.length };
+}
+
+async function main() {
+ let seeded = null;
+ if (dev) {
+ await useDevDatabase();
+ } else if (!process.env.DATABASE_URL) {
+ console.error('DATABASE_URL is not set. Use --dev for the in-process ledger, or load .env.local.');
+ process.exit(2);
+ }
+ if (dev) seeded = await seedDevLedger();
+
+ const { reconcileReport } = await import('../api/_lib/x402/prepaid-reconcile.js');
+ let report;
+ try {
+ report = await reconcileReport({ checkChain });
+ } catch (err) {
+ if (/x402_prepaid_/.test(String(err?.message)) && /does not exist/.test(String(err?.message))) {
+ console.error('The x402_prepaid_* tables do not exist yet. Run `npm run db:status`, then `npm run db:migrate` at deploy.');
+ process.exit(2);
+ }
+ throw err;
+ }
+
+ if (asJson) {
+ console.log(JSON.stringify({ ok: report.ok, problems: report.problems, summary: report.summary, seeded }, null, 2));
+ } else {
+ if (seeded) console.log(`dev ledger: ${seeded.payers} payers, ${seeded.debitsAttempted} debits, ${seeded.transactions} settlement tx\n`);
+ console.log(report.lines.join('\n'));
+ }
+ process.exit(report.ok ? 0 : 1);
+}
+
+main().catch((err) => {
+ console.error(err?.stack || err);
+ process.exit(2);
+});
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index 15cdf96fe..549b7dc07 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -40,6 +40,7 @@ import './tabs/pay.js';
import './tabs/vanity.js';
import './tabs/policy.js';
import './tabs/delegation.js';
+import './tabs/allowance.js';
import './tabs/withdraw.js';
import './tabs/whitelist.js';
import './tabs/give.js';
diff --git a/src/agent-wallet-hub/tabs/allowance.js b/src/agent-wallet-hub/tabs/allowance.js
new file mode 100644
index 000000000..05b21818a
--- /dev/null
+++ b/src/agent-wallet-hub/tabs/allowance.js
@@ -0,0 +1,264 @@
+/**
+ * Agent Wallet hub: owner-funded budget tab (owner-only).
+ *
+ * The owner keeps the funds in their OWN wallet and signs one transaction that
+ * creates a fixed-delegation allowance (mint, cap, expiry) to the agent wallet
+ * on the Solana Subscriptions and Allowances program. The agent can only pull
+ * through the program, and the program itself rejects anything past the cap or
+ * after a revoke. The owner can revoke at any time with one signature.
+ *
+ * Every transaction here is prepared by the server and returned UNSIGNED; the
+ * owner's browser wallet signs it. See docs/agent-allowance-budgets.md.
+ */
+
+import { registerWalletTab } from '../registry.js';
+import { shortAddress } from '../util.js';
+import { consumeCsrfToken } from '../../api.js';
+import { connectLaunchWallet, signAndBroadcast, waitForConfirmation } from '../../launch/launch-wallet.js';
+
+const STYLE_ID = 'awh-allowance-style';
+const STYLE = `
+.awa-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:64ch; }
+.awa-list { display:flex; flex-direction:column; gap:10px; }
+.awa-item { 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:10px; }
+.awa-head { display:flex; justify-content:space-between; align-items:center; gap:10px; flex-wrap:wrap; }
+.awa-mint { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); overflow-wrap:anywhere; }
+.awa-badge { display:inline-flex; align-items:center; font-size: var(--text-2xs,.6875rem); font-weight:600; padding:2px 9px; border-radius: var(--radius-pill,999px); border:1px solid transparent; }
+.awa-badge.active { 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); }
+.awa-badge.expired, .awa-badge.exhausted, .awa-badge.unknown { 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); }
+.awa-badge.revoked, .awa-badge.closed { color: var(--ink-dim,#888); border-color: var(--stroke,rgba(255,255,255,.12)); }
+.awa-meter { height:8px; border-radius:99px; background: var(--surface-2,rgba(255,255,255,.07)); overflow:hidden; }
+.awa-meter > i { display:block; height:100%; background: var(--accent,#7c9cff); border-radius:99px; transition: width var(--duration-fast,140ms); }
+.awa-stats { display:grid; grid-template-columns: repeat(auto-fit,minmax(120px,1fr)); gap:8px; }
+.awa-stat .k { display:block; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
+.awa-stat .v { font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); }
+.awa-form { display:grid; grid-template-columns: repeat(auto-fit,minmax(170px,1fr)); gap:10px; margin-bottom: var(--space-3,12px); }
+.awa-field label { display:block; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); margin-bottom:5px; }
+.awa-field input, .awa-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); }
+.awa-field input:hover, .awa-field select:hover { border-color: var(--stroke-strong,rgba(255,255,255,.2)); }
+.awa-field input:focus-visible, .awa-field select:focus-visible { outline:2px solid var(--accent,#7c9cff); outline-offset:1px; }
+.awa-actions { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
+.awa-hint { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
+.awa-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(255,255,255,.3); border-top-color: currentColor; border-radius:50%; animation: awa-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }
+@keyframes awa-rot { to { transform: rotate(360deg); } }
+.awa-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; }
+.awa-skel { height:14px; border-radius:6px; background: var(--surface-2,rgba(255,255,255,.05)); animation: awa-pulse 1.4s ease-in-out infinite; margin:9px 0; }
+@keyframes awa-pulse { 0%,100%{opacity:1} 50%{opacity:.4} }
+@media (prefers-reduced-motion: reduce) { .awa-spin, .awa-skel { animation:none; } .awa-meter > i { transition:none; } }
+`;
+
+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})` };
+ 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' };
+ }
+}
+
+// Raw integer string -> decimal string using the mint's decimals.
+function fromRaw(raw, decimals) {
+ if (raw == null) return '-';
+ const n = BigInt(raw);
+ const base = 10n ** BigInt(decimals);
+ const whole = n / base;
+ const frac = (n % base).toString().padStart(decimals, '0').replace(/0+$/, '');
+ return frac ? `${whole}.${frac}` : whole.toString();
+}
+
+const STATUS_LABEL = { active: 'Active', expired: 'Expired', exhausted: 'Fully used', revoked: 'Revoked', closed: 'Closed on chain', unknown: 'Status unavailable' };
+
+registerWalletTab({
+ id: 'allowance',
+ label: 'Budget',
+ order: 58,
+ ownerOnly: true,
+ mount({ panel, ctx }) {
+ injectStyle();
+ const esc = ctx.escapeHtml;
+ const toast = ctx.toast;
+ const base = `/api/agents/${encodeURIComponent(ctx.agentId)}/solana/allowance`;
+
+ let destroyed = false;
+ const state = {
+ loaded: false,
+ signedOut: false,
+ error: null,
+ data: null,
+ form: { mint: '', amount: '', days: '30' },
+ busy: null, // 'create' | `revoke:${id}`
+ actionError: null,
+ };
+ const network = () => ctx.getNetwork();
+
+ function render() {
+ if (destroyed) return;
+ if (state.signedOut) { panel.innerHTML = renderSignedOut(); return; }
+ panel.innerHTML = `${renderList()}${renderComposer()}`;
+ wire();
+ }
+
+ function renderSignedOut() {
+ const next = encodeURIComponent(location.pathname + location.search + location.hash);
+ return `<div class="awh-card"><div class="awh-card-h">Owner-funded budget</div>
+ <p class="awa-intro">Budgets are private to the wallet owner. Sign in to review or create one.</p>
+ <div class="awa-actions"><a class="awh-btn awh-btn--primary" href="/login?next=${next}">Sign in</a></div></div>`;
+ }
+
+ function renderList() {
+ if (!state.loaded) {
+ return `<div class="awh-card"><div class="awh-card-h">On-chain allowances</div><div class="awa-skel" style="width:55%"></div><div class="awa-skel"></div><div class="awa-skel" style="width:40%"></div></div>`;
+ }
+ if (state.error) {
+ return `<div class="awh-card"><div class="awh-card-h">On-chain allowances</div><div class="awa-err" role="alert">Couldn't load your allowances.<br>${esc(state.error)}</div><div class="awa-actions"><button class="awh-btn" type="button" data-act="reload">Retry</button></div></div>`;
+ }
+ const items = state.data?.allowances || [];
+ if (!items.length) {
+ return `<div class="awh-card"><div class="awh-card-h">On-chain allowances</div>
+ <p class="awa-intro" style="margin-bottom:0;">No owner-funded budget yet. Your funds stay in your own wallet; you sign once to let this agent pull up to a cap, until an expiry, and you can revoke at any time. The Solana program itself rejects anything past the cap.</p></div>`;
+ }
+ return `<div class="awh-card"><div class="awh-card-h">On-chain allowances</div><div class="awa-list">${items.map(renderItem).join('')}</div></div>`;
+ }
+
+ function renderItem(a) {
+ const dec = a.decimals ?? 0;
+ const cap = BigInt(a.capRaw);
+ const spent = a.spentRaw == null ? 0n : BigInt(a.spentRaw);
+ const pct = cap > 0n ? Number((spent * 100n) / cap) : 0;
+ const open = a.status === 'active' || a.status === 'exhausted' || a.status === 'expired' || a.status === 'unknown';
+ const expiry = a.expiryTs ? new Date(a.expiryTs * 1000).toLocaleString() : 'No expiry';
+ const revoking = state.busy === `revoke:${a.id}`;
+ return `<div class="awa-item">
+ <div class="awa-head"><span class="awa-mint" title="${esc(a.mint)}">${esc(shortAddress(a.mint))}</span><span class="awa-badge ${esc(a.status)}">${esc(STATUS_LABEL[a.status] || a.status)}</span></div>
+ <div class="awa-meter" role="img" aria-label="${pct}% of the cap used"><i style="width:${Math.min(100, pct)}%"></i></div>
+ <div class="awa-stats">
+ <div class="awa-stat"><span class="k">Cap</span><span class="v">${esc(fromRaw(a.capRaw, dec))}</span></div>
+ <div class="awa-stat"><span class="k">Spent</span><span class="v">${esc(fromRaw(a.spentRaw, dec))}</span></div>
+ <div class="awa-stat"><span class="k">Remaining</span><span class="v">${esc(fromRaw(a.remainingRaw, dec))}</span></div>
+ <div class="awa-stat"><span class="k">Expires</span><span class="v">${esc(expiry)}</span></div>
+ </div>
+ ${a.liveError ? `<div class="awa-hint">Live balance unavailable: ${esc(a.liveError)}</div>` : ''}
+ ${open ? `<div class="awa-actions"><button class="awh-btn" type="button" data-revoke="${esc(a.id)}" ${state.busy ? 'disabled' : ''}>${revoking ? '<span class="awa-spin" aria-hidden="true"></span>Waiting on your wallet…' : 'Revoke'}</button><span class="awa-hint">One signature closes the allowance on chain. Further pulls fail immediately.</span></div>` : ''}
+ </div>`;
+ }
+
+ function renderComposer() {
+ if (!state.loaded || state.error) return '';
+ const creating = state.busy === 'create';
+ return `<div class="awh-card"><div class="awh-card-h">Fund a budget from your wallet</div>
+ <p class="awa-intro">Pick a token, a cap and an expiry, then approve one transaction in your own wallet. Funds never leave your wallet until the agent pulls them, and never beyond the cap.</p>
+ ${state.actionError ? `<div class="awa-err" role="alert">${esc(state.actionError)}</div>` : ''}
+ <div class="awa-form">
+ <div class="awa-field"><label for="awa-mint">Token mint</label><input id="awa-mint" type="text" autocomplete="off" spellcheck="false" placeholder="USDC mint address" value="${esc(state.form.mint)}" /></div>
+ <div class="awa-field"><label for="awa-amount">Cap (token units)</label><input id="awa-amount" type="text" inputmode="decimal" placeholder="25" value="${esc(state.form.amount)}" /></div>
+ <div class="awa-field"><label for="awa-days">Expires in (days)</label><input id="awa-days" type="text" inputmode="numeric" value="${esc(state.form.days)}" /></div>
+ </div>
+ <div class="awa-actions">
+ <button class="awh-btn awh-btn--primary" type="button" id="awa-create" ${state.busy ? 'disabled' : ''}>${creating ? '<span class="awa-spin" aria-hidden="true"></span>Waiting on your wallet…' : 'Sign & fund budget'}</button>
+ <span class="awa-hint">Opens your browser wallet's transaction prompt (${esc(network())}).</span>
+ </div>
+ </div>`;
+ }
+
+ function wire() {
+ panel.querySelector('[data-act="reload"]')?.addEventListener('click', () => { state.loaded = false; render(); load(); });
+ panel.querySelector('#awa-mint')?.addEventListener('input', (e) => { state.form.mint = e.target.value.trim(); });
+ panel.querySelector('#awa-amount')?.addEventListener('input', (e) => { state.form.amount = e.target.value; });
+ panel.querySelector('#awa-days')?.addEventListener('input', (e) => { state.form.days = e.target.value; });
+ panel.querySelector('#awa-create')?.addEventListener('click', create);
+ panel.querySelectorAll('[data-revoke]').forEach((b) => b.addEventListener('click', () => revoke(b.getAttribute('data-revoke'))));
+ }
+
+ async function load() {
+ const res = await call(`${base}?network=${encodeURIComponent(network())}`);
+ if (destroyed) return;
+ state.loaded = true;
+ if (res.status === 401) { state.signedOut = true; render(); return; }
+ state.signedOut = false;
+ state.error = res.ok ? null : res.message;
+ state.data = res.ok ? res.data : null;
+ render();
+ }
+
+ async function sendOwnerTx(prep, address) {
+ const signature = await signAndBroadcast({ txBase64: prep.transaction, version: 0, address });
+ const confirmed = await waitForConfirmation(signature);
+ if (!confirmed) throw new Error('The transaction was sent but has not confirmed yet. Reload in a minute to see it.');
+ return signature;
+ }
+
+ async function create() {
+ if (state.busy) return;
+ state.actionError = null;
+ if (network() !== 'mainnet') { state.actionError = 'Switch the network selector to mainnet. Devnet budgets are created with scripts/allowance-devnet-proof.mjs.'; render(); return; }
+ if (!state.form.mint || !state.form.amount) { state.actionError = 'Enter the token mint and a cap.'; render(); return; }
+ state.busy = 'create'; render();
+ try {
+ const { address } = await connectLaunchWallet();
+ const prepRes = await call(base, { method: 'POST', body: { op: 'prepare', network: network(), owner: address, mint: state.form.mint, amount: state.form.amount, expiresInDays: Number(state.form.days) } });
+ if (!prepRes.ok) throw new Error(prepRes.message);
+ const prep = prepRes.data;
+ const signature = await sendOwnerTx(prep, address);
+ const conf = await call(base, { method: 'POST', body: { op: 'confirm', network: network(), signature, delegationPda: prep.delegationPda, nonce: prep.nonce, kind: prep.kind } });
+ if (!conf.ok) throw new Error(conf.message);
+ state.form = { mint: '', amount: '', days: state.form.days };
+ toast('Budget funded on chain');
+ await load();
+ } catch (e) {
+ state.actionError = e?.message || 'Could not create that budget.';
+ } finally {
+ if (!destroyed) { state.busy = null; render(); }
+ }
+ }
+
+ async function revoke(id) {
+ if (state.busy) return;
+ state.actionError = null;
+ state.busy = `revoke:${id}`; render();
+ try {
+ const { address } = await connectLaunchWallet();
+ const prepRes = await call(base, { method: 'POST', body: { op: 'revoke', network: network(), id } });
+ if (!prepRes.ok) throw new Error(prepRes.message);
+ if (prepRes.data.owner !== address) throw new Error(`Connect the owner wallet ${shortAddress(prepRes.data.owner)} to revoke this budget.`);
+ const signature = await sendOwnerTx(prepRes.data, address);
+ const done = await call(base, { method: 'POST', body: { op: 'revoked', network: network(), id, signature } });
+ if (!done.ok) throw new Error(done.message);
+ toast('Budget revoked');
+ await load();
+ } catch (e) {
+ state.actionError = e?.message || 'Could not revoke that budget.';
+ } finally {
+ if (!destroyed) { state.busy = null; render(); }
+ }
+ }
+
+ const detachNet = ctx.onNetworkChange(() => { state.loaded = false; render(); load(); });
+ render();
+ load();
+
+ return {
+ onShow() { if (!state.loaded) load(); },
+ destroy() { destroyed = true; detachNet?.(); },
+ };
+ },
+});
diff --git a/src/x-video.js b/src/x-video.js
new file mode 100644
index 000000000..0dff690d9
--- /dev/null
+++ b/src/x-video.js
@@ -0,0 +1,135 @@
+// Free X video tool page: POST /api/x-video/extract, then one download link per mp4 variant
+// routed through GET /api/x-video/download (restricted to X's media CDNs).
+
+const form = document.getElementById('xv-form');
+const input = document.getElementById('xv-url');
+const button = document.getElementById('xv-go');
+const statusEl = document.getElementById('xv-status');
+const result = document.getElementById('xv-result');
+
+const nf = new Intl.NumberFormat(undefined, { notation: 'compact', maximumFractionDigits: 1 });
+
+function el(tag, props = {}, ...children) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else node.setAttribute(k, v);
+ }
+ for (const c of children) if (c) node.append(c);
+ return node;
+}
+
+function showError(title, message) {
+ result.replaceChildren();
+ statusEl.replaceChildren(el('div', { class: 'xv-error' }, el('strong', { text: title }), document.createTextNode(message)));
+}
+
+function showLoading() {
+ statusEl.replaceChildren();
+ result.replaceChildren(
+ el('div', { class: 'xv-card', 'aria-hidden': 'true' }, el('div', { class: 'xv-skel' }), el('div', { class: 'xv-skel' }), el('div', { class: 'xv-skel' })),
+ );
+}
+
+function metricItem(label, value) {
+ if (value == null) return null;
+ return el('li', {}, el('b', { text: nf.format(value) }), document.createTextNode(` ${label}`));
+}
+
+function formatBytesEstimate(variant, durationMs) {
+ if (!variant.bitrate || !durationMs) return '';
+ const mb = (variant.bitrate * (durationMs / 1000)) / 8 / 1e6;
+ return `about ${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`;
+}
+
+function render(data) {
+ const { post, videos, duration_ms: durationMs, thumbnail } = data;
+ const card = el('div', { class: 'xv-card' });
+
+ const video = el('video', { class: 'xv-video', controls: '', playsinline: '', preload: 'metadata' });
+ if (thumbnail) video.setAttribute('poster', thumbnail);
+ video.src = videos[0].url;
+ card.append(video);
+
+ const author = el('div', { class: 'xv-author' });
+ if (post.author.avatar) author.append(el('img', { class: 'xv-avatar', src: post.author.avatar, alt: '', width: '40', height: '40' }));
+ author.append(el('div', {}, el('div', { class: 'xv-name', text: post.author.name }), el('div', { class: 'xv-handle', text: `@${post.author.handle}` })));
+ card.append(author);
+
+ if (post.text) card.append(el('div', { class: 'xv-text', text: post.text }));
+
+ const metrics = el('ul', { class: 'xv-metrics', 'aria-label': 'Post engagement' });
+ for (const item of [
+ metricItem('likes', post.metrics.likes),
+ metricItem('replies', post.metrics.replies),
+ metricItem('reposts', post.metrics.reposts),
+ metricItem('quotes', post.metrics.quotes),
+ metricItem('views', post.metrics.views),
+ ]) if (item) metrics.append(item);
+ card.append(metrics);
+
+ const list = el('ul', { class: 'xv-list' });
+ for (const v of videos) {
+ const href = `/api/x-video/download?url=${encodeURIComponent(v.url)}&handle=${encodeURIComponent(post.author.handle)}&id=${encodeURIComponent(post.id)}`;
+ list.append(
+ el(
+ 'li',
+ { class: 'xv-row' },
+ el('span', { class: 'xv-q', text: v.quality }),
+ el('span', { class: 'xv-meta', text: [v.width && v.height ? `${v.width} x ${v.height}` : '', formatBytesEstimate(v, durationMs)].filter(Boolean).join(' · ') }),
+ el('a', { class: 'xv-dl', href, download: '', 'aria-label': `Download ${v.quality} video` , text: 'Download' }),
+ ),
+ );
+ }
+ card.append(list);
+
+ statusEl.replaceChildren();
+ result.replaceChildren(card);
+}
+
+async function extract(url) {
+ button.disabled = true;
+ button.textContent = 'Reading post...';
+ showLoading();
+ try {
+ const res = await fetch('/api/x-video/extract', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ url }),
+ });
+ const data = await res.json().catch(() => null);
+ if (!res.ok || !data?.videos?.length) {
+ const titles = { invalid_url: 'That is not an X post link', post_unavailable: 'Post unavailable', no_video: 'No video in this post', upstream_unreachable: 'X did not answer' };
+ const hint = { invalid_url: ' Copy the link from the post, for example https://x.com/user/status/123.', post_unavailable: '', no_video: '', upstream_unreachable: '' };
+ showError(titles[data?.error] || 'Something went wrong', `${data?.message || `The request failed (HTTP ${res.status}). Try again.`}${hint[data?.error] || ''}`);
+ return;
+ }
+ render(data);
+ } catch {
+ showError('Network problem', 'Could not reach three.ws. Check your connection and try again.');
+ } finally {
+ button.disabled = false;
+ button.textContent = 'Get video';
+ }
+}
+
+form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const url = input.value.trim();
+ if (!url) {
+ showError('Paste a link first', 'Copy the link of an X post that has a video and paste it above.');
+ input.focus();
+ return;
+ }
+ const u = new URL(location.href);
+ u.searchParams.set('url', url);
+ history.replaceState(null, '', u);
+ extract(url);
+});
+
+const preset = new URLSearchParams(location.search).get('url');
+if (preset) {
+ input.value = preset;
+ extract(preset);
+}
diff --git a/tests/agent-onboarding.test.js b/tests/agent-onboarding.test.js
new file mode 100644
index 000000000..4a57d8bea
--- /dev/null
+++ b/tests/agent-onboarding.test.js
@@ -0,0 +1,199 @@
+// Challenge-response signup (api/_lib/agent-onboarding.js) and the x402 plan
+// upgrade quote (api/billing/agent-upgrade.js). The database is a small
+// stateful stand-in that executes the exact statements the module issues, so the
+// replay, binding, expiry and single-use rules are tested as the code runs them.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58mod from 'bs58';
+
+const bs58 = bs58mod.default || bs58mod;
+
+const state = { challenges: new Map(), signups: 0 };
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = (strings, ...values) => {
+ const text = strings.join('?').replace(/\s+/g, ' ').trim();
+ const run = () => {
+ if (text.startsWith('delete from agent_signup_challenges')) return [];
+ if (text.startsWith('insert into agent_signup_challenges')) {
+ const [nonce, public_key, ip, issued_at, expires_at] = values;
+ state.challenges.set(nonce, { nonce, public_key, ip, issued_at, expires_at, consumed_at: null });
+ return [];
+ }
+ if (text.startsWith('select nonce, public_key, issued_at')) {
+ const row = state.challenges.get(values[0]);
+ return row ? [{ ...row }] : [];
+ }
+ if (text.startsWith('update agent_signup_challenges set consumed_at')) {
+ const [nonce, publicKey, notAfter] = values;
+ const row = state.challenges.get(nonce);
+ if (!row || row.public_key !== publicKey || row.consumed_at || new Date(row.expires_at) <= new Date(notAfter)) return [];
+ row.consumed_at = new Date().toISOString();
+ return [{ nonce }];
+ }
+ if (text.startsWith('select count(*)::int as n from agent_self_signups')) return [{ n: state.signups }];
+ throw new Error(`unexpected statement: ${text}`);
+ };
+ const result = Promise.resolve().then(run);
+ return result;
+ };
+ sql.transaction = async () => [];
+ return { sql };
+});
+
+vi.mock('../api/_lib/env.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ env: new Proxy(actual.env, {
+ get: (t, k) => (k === 'APP_ORIGIN' ? 'https://three.ws' : k === 'AGENT_SIGNUP_DAILY_CAP' ? 3 : t[k]),
+ }),
+ };
+});
+
+const {
+ buildChallengeMessage,
+ issueChallenge,
+ redeemChallenge,
+ assertUnderDailyCap,
+ assertPublicKey,
+ verifyChallengeSignature,
+ CHALLENGE_TTL_SECONDS,
+} = await import('../api/_lib/agent-onboarding.js');
+
+function keypair() {
+ const priv = ed25519.utils.randomSecretKey();
+ return { priv, publicKey: bs58.encode(ed25519.getPublicKey(priv)) };
+}
+const sign = (priv, message) => bs58.encode(ed25519.sign(new TextEncoder().encode(message), priv));
+const codeOf = async (promise) => {
+ try {
+ await promise;
+ return null;
+ } catch (err) {
+ return err;
+ }
+};
+
+beforeEach(() => {
+ state.challenges.clear();
+ state.signups = 0;
+});
+
+describe('challenge message', () => {
+ it('is deterministic and names every bound field', () => {
+ const fields = { domain: 'three.ws', publicKey: 'K', nonce: 'N', issuedAt: 'I', expiresAt: 'E' };
+ expect(buildChallengeMessage(fields)).toBe(buildChallengeMessage({ ...fields }));
+ const msg = buildChallengeMessage(fields);
+ for (const part of ['domain: three.ws', 'public_key: K', 'nonce: N', 'issued_at: I', 'expires_at: E']) expect(msg).toContain(part);
+ });
+
+ it('rejects a malformed public key before any challenge exists', () => {
+ expect(() => assertPublicKey('not-a-key')).toThrow();
+ expect(() => assertPublicKey(bs58.encode(new Uint8Array(31)))).toThrow();
+ const { publicKey } = keypair();
+ expect(assertPublicKey(publicKey)).toBe(publicKey);
+ });
+});
+
+describe('redeemChallenge', () => {
+ it('accepts a correct signature once', async () => {
+ const { priv, publicKey } = keypair();
+ const ch = await issueChallenge({ publicKey, ip: '203.0.113.7' });
+ expect(ch.ttl_seconds).toBe(CHALLENGE_TTL_SECONDS);
+ await expect(redeemChallenge({ publicKey, nonce: ch.nonce, signature: sign(priv, ch.message) })).resolves.toBeUndefined();
+ });
+
+ it('rejects a replayed nonce with 409 nonce_reused', async () => {
+ const { priv, publicKey } = keypair();
+ const ch = await issueChallenge({ publicKey, ip: null });
+ const signature = sign(priv, ch.message);
+ await redeemChallenge({ publicKey, nonce: ch.nonce, signature });
+ const err = await codeOf(redeemChallenge({ publicKey, nonce: ch.nonce, signature }));
+ expect(err.code).toBe('nonce_reused');
+ expect(err.status).toBe(409);
+ });
+
+ it('rejects a wrong signature with 401 bad_signature and does not burn the nonce', async () => {
+ const { priv, publicKey } = keypair();
+ const other = keypair();
+ const ch = await issueChallenge({ publicKey, ip: null });
+ const err = await codeOf(redeemChallenge({ publicKey, nonce: ch.nonce, signature: sign(other.priv, ch.message) }));
+ expect(err.code).toBe('bad_signature');
+ expect(err.status).toBe(401);
+ await expect(redeemChallenge({ publicKey, nonce: ch.nonce, signature: sign(priv, ch.message) })).resolves.toBeUndefined();
+ });
+
+ it('rejects a signature over a different message', async () => {
+ const { priv, publicKey } = keypair();
+ const ch = await issueChallenge({ publicKey, ip: null });
+ const err = await codeOf(redeemChallenge({ publicKey, nonce: ch.nonce, signature: sign(priv, `${ch.message}\nextra`) }));
+ expect(err.code).toBe('bad_signature');
+ });
+
+ it('rejects a nonce issued to a different key', async () => {
+ const a = keypair();
+ const b = keypair();
+ const ch = await issueChallenge({ publicKey: a.publicKey, ip: null });
+ const err = await codeOf(redeemChallenge({ publicKey: b.publicKey, nonce: ch.nonce, signature: sign(b.priv, ch.message) }));
+ expect(err.code).toBe('invalid_nonce');
+ expect(err.status).toBe(400);
+ });
+
+ it('rejects an unknown nonce', async () => {
+ const { priv, publicKey } = keypair();
+ const err = await codeOf(redeemChallenge({ publicKey, nonce: 'A'.repeat(32), signature: sign(priv, 'x') }));
+ expect(err.code).toBe('invalid_nonce');
+ });
+
+ it('rejects an expired challenge with 410', async () => {
+ const { priv, publicKey } = keypair();
+ const past = new Date(Date.now() - 2 * CHALLENGE_TTL_SECONDS * 1000);
+ const ch = await issueChallenge({ publicKey, ip: null, now: past });
+ const err = await codeOf(redeemChallenge({ publicKey, nonce: ch.nonce, signature: sign(priv, ch.message) }));
+ expect(err.code).toBe('nonce_expired');
+ expect(err.status).toBe(410);
+ });
+
+ it('requires a nonce and a signature', async () => {
+ const { publicKey } = keypair();
+ expect((await codeOf(redeemChallenge({ publicKey, nonce: undefined, signature: 'x' }))).code).toBe('validation_error');
+ const ch = await issueChallenge({ publicKey, ip: null });
+ expect((await codeOf(redeemChallenge({ publicKey, nonce: ch.nonce, signature: '' }))).code).toBe('validation_error');
+ });
+
+ it('two concurrent redemptions of one challenge: exactly one wins', async () => {
+ const { priv, publicKey } = keypair();
+ const ch = await issueChallenge({ publicKey, ip: null });
+ const signature = sign(priv, ch.message);
+ const results = await Promise.allSettled([
+ redeemChallenge({ publicKey, nonce: ch.nonce, signature }),
+ redeemChallenge({ publicKey, nonce: ch.nonce, signature }),
+ ]);
+ expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
+ expect(results.find((r) => r.status === 'rejected').reason.code).toBe('nonce_reused');
+ });
+});
+
+describe('verifyChallengeSignature', () => {
+ it('returns false rather than throwing on a well-formed but wrong signature', () => {
+ const { publicKey } = keypair();
+ expect(verifyChallengeSignature({ message: 'm', signature: bs58.encode(new Uint8Array(64)), publicKey })).toBe(false);
+ });
+ it('throws a 400 on a signature of the wrong length', () => {
+ const { publicKey } = keypair();
+ expect(() => verifyChallengeSignature({ message: 'm', signature: bs58.encode(new Uint8Array(10)), publicKey })).toThrow(/64 bytes/);
+ });
+});
+
+describe('daily account cap', () => {
+ it('allows signups below the cap and refuses at it with 429', async () => {
+ state.signups = 2;
+ await expect(assertUnderDailyCap()).resolves.toBeUndefined();
+ state.signups = 3;
+ const err = await codeOf(assertUnderDailyCap());
+ expect(err.status).toBe(429);
+ expect(err.code).toBe('daily_cap_reached');
+ });
+});
diff --git a/tests/api/x-video.test.js b/tests/api/x-video.test.js
new file mode 100644
index 000000000..19539c29f
--- /dev/null
+++ b/tests/api/x-video.test.js
@@ -0,0 +1,157 @@
+/**
+ * Tests for the free X video tool: POST /api/x-video/extract and the
+ * GET /api/x-video/download proxy. The reader is exercised against stubbed
+ * network responses; the proxy tests pin that it never reaches any host other
+ * than X's two media CDNs.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ clientIp: () => '203.0.113.9',
+ limits: {
+ ...actual.limits,
+ xVideoExtract: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ xVideoDownload: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ };
+});
+
+const fetchMock = vi.fn();
+vi.stubGlobal('fetch', fetchMock);
+
+const { default: extract } = await import('../../api/x-video/extract.js');
+const { default: download } = await import('../../api/x-video/download.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(n, v) {
+ this.headers[String(n).toLowerCase()] = v;
+ },
+ end(b) {
+ this.body = b ?? null;
+ },
+ };
+}
+
+function makeReq({ method = 'POST', url = '/api/x-video/extract', body = null } = {}) {
+ const stream = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body), 'utf8')]);
+ stream.method = method;
+ stream.url = url;
+ stream.headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9' };
+ return stream;
+}
+
+const POST_URL = 'https://x.com/trythreews/status/1894000000000000000';
+const ok = (body) => ({ ok: true, status: 200, text: async () => JSON.stringify(body) });
+
+const videoPost = {
+ text: 'demo',
+ created_at: '2026-10-01T12:00:00.000Z',
+ favorite_count: 3,
+ conversation_count: 1,
+ user: { name: 'three.ws', screen_name: 'trythreews' },
+ mediaDetails: [
+ {
+ type: 'video',
+ media_url_https: 'https://pbs.twimg.com/ext_tw_video_thumb/1/t.jpg',
+ video_info: {
+ duration_millis: 5000,
+ variants: [{ content_type: 'video/mp4', bitrate: 832000, url: 'https://video.twimg.com/a/640x360/v.mp4' }],
+ },
+ },
+ ],
+};
+
+beforeEach(() => fetchMock.mockReset());
+
+describe('POST /api/x-video/extract', () => {
+ it('returns the post and its mp4 variants', async () => {
+ fetchMock.mockResolvedValue(ok(videoPost));
+ const res = makeRes();
+ await extract(makeReq({ body: { url: POST_URL } }), res);
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(res.body);
+ expect(out.videos[0]).toMatchObject({ quality: '480p', contentType: 'video/mp4' });
+ expect(out.post.metrics.likes).toBe(3);
+ expect(out.duration_ms).toBe(5000);
+ expect(out.source).toBe('syndication');
+ });
+
+ it('answers 404 post_unavailable for a deleted post', async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 404, text: async () => '' });
+ const res = makeRes();
+ await extract(makeReq({ body: { url: POST_URL } }), res);
+ expect(res.statusCode).toBe(404);
+ expect(JSON.parse(res.body).error).toBe('post_unavailable');
+ });
+
+ it('answers 404 no_video for a post without video', async () => {
+ fetchMock.mockResolvedValue(ok({ ...videoPost, mediaDetails: [] }));
+ const res = makeRes();
+ await extract(makeReq({ body: { url: POST_URL } }), res);
+ expect(res.statusCode).toBe(404);
+ expect(JSON.parse(res.body).error).toBe('no_video');
+ });
+
+ it('answers 400 invalid_url without any network call', async () => {
+ const res = makeRes();
+ await extract(makeReq({ body: { url: 'https://example.com/a' } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_url');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/x-video/download', () => {
+ it.each([
+ 'https://evil.example/a.mp4',
+ 'http://video.twimg.com/a.mp4',
+ 'https://video.twimg.com.evil.example/a.mp4',
+ 'https://169.254.169.254/latest/meta-data',
+ '',
+ ])('refuses %s without fetching', async (target) => {
+ const res = makeRes();
+ await download(makeReq({ method: 'GET', url: `/api/x-video/download?url=${encodeURIComponent(target)}` }), res);
+ expect(res.statusCode).toBe(400);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('streams an allowed CDN file as an attachment and never follows redirects', async () => {
+ fetchMock.mockResolvedValue(
+ new Response(Buffer.from('mp4-bytes'), { status: 200, headers: { 'content-type': 'video/mp4', 'content-length': '9' } }),
+ );
+ const chunks = [];
+ const res = Object.assign(new (await import('node:stream')).Writable({
+ write(c, _e, cb) {
+ chunks.push(c);
+ cb();
+ },
+ }), { statusCode: 200, headers: {}, setHeader(n, v) { this.headers[String(n).toLowerCase()] = v; } });
+ await download(
+ makeReq({
+ method: 'GET',
+ url: `/api/x-video/download?url=${encodeURIComponent('https://video.twimg.com/a/v.mp4')}&handle=trythreews&id=123`,
+ }),
+ res,
+ );
+ expect(fetchMock.mock.calls[0][1].redirect).toBe('manual');
+ expect(res.headers['content-disposition']).toBe('attachment; filename="trythreews_123.mp4"');
+ expect(Buffer.concat(chunks).toString()).toBe('mp4-bytes');
+ });
+
+ it('does not stream a redirect to another host', async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 302, headers: { location: 'https://evil.example/x' } }));
+ const res = makeRes();
+ await download(makeReq({ method: 'GET', url: `/api/x-video/download?url=${encodeURIComponent('https://video.twimg.com/a/v.mp4')}` }), res);
+ expect(res.statusCode).toBe(502);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/tests/onchain-allowance.test.js b/tests/onchain-allowance.test.js
new file mode 100644
index 000000000..448f66b37
--- /dev/null
+++ b/tests/onchain-allowance.test.js
@@ -0,0 +1,196 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Keypair } from '@solana/web3.js';
+import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
+
+// Owner-funded agent budgets: the remaining on-chain allowance is a hard
+// ceiling. The chain reads (delegation account, owner token balance) are the
+// only impure edges; they are stubbed at the RPC boundary so the real ceiling
+// math, store and guard code run unmodified.
+const fetchFixed = vi.fn();
+vi.mock('@solana/subscriptions', async (importOriginal) => ({
+ ...(await importOriginal()),
+ fetchMaybeFixedDelegation: (...a) => fetchFixed(...a),
+}));
+
+const dbState = { rows: [] };
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ const q = strings.join('?');
+ if (q.includes('FROM agent_onchain_allowances') && q.includes('agent_id')) {
+ const [agentId, network] = values;
+ return Promise.resolve(dbState.rows.filter((r) => r.agent_id === agentId && r.network === network && !r.revoked_at));
+ }
+ throw new Error(`unexpected query: ${q}`);
+ },
+}));
+
+const {
+ checkAllowanceCeiling,
+ recurringRemaining,
+ recurringEnabled,
+ kitInstructionToWeb3,
+ prepareCreateAllowance,
+ checkAllowancePull,
+ AllowanceError,
+} = await import('../api/_lib/onchain-allowance.js');
+const { checkAgentAllowanceSpend } = await import('../api/_lib/onchain-allowance-store.js');
+
+const NOW = 1_800_000_000;
+
+describe('checkAllowanceCeiling', () => {
+ it('allows a request within remaining and owner balance', () => {
+ const v = checkAllowanceCeiling({ remaining: 60n, expiryTs: NOW + 100, ownerBalance: 500n, amount: 40n, nowTs: NOW });
+ expect(v).toMatchObject({ allow: true, code: 'ok' });
+ });
+
+ it('refuses a request above the remaining allowance', () => {
+ const v = checkAllowanceCeiling({ remaining: 60n, expiryTs: 0n, ownerBalance: 500n, amount: 80n, nowTs: NOW });
+ expect(v).toMatchObject({ allow: false, code: 'allowance_exceeded', detail: { remaining: '60', requested: '80' } });
+ });
+
+ it('refuses after expiry, but treats expiry 0 as never', () => {
+ expect(checkAllowanceCeiling({ remaining: 60n, expiryTs: NOW - 1, amount: 1n, nowTs: NOW }).code).toBe('allowance_expired');
+ expect(checkAllowanceCeiling({ remaining: 60n, expiryTs: 0, amount: 1n, nowTs: NOW }).allow).toBe(true);
+ });
+
+ it('refuses when the owner no longer holds the funds', () => {
+ const v = checkAllowanceCeiling({ remaining: 60n, ownerBalance: 5n, amount: 10n, nowTs: NOW });
+ expect(v).toMatchObject({ allow: false, code: 'owner_balance_low' });
+ });
+
+ it('refuses zero, negative and missing allowances', () => {
+ expect(checkAllowanceCeiling({ remaining: 60n, amount: 0n }).code).toBe('invalid_amount');
+ expect(checkAllowanceCeiling({ remaining: null, amount: 1n }).code).toBe('no_allowance');
+ });
+});
+
+describe('recurringRemaining', () => {
+ const d = { amountPerPeriod: 100n, amountPulledInPeriod: 70n, currentPeriodStartTs: 1000n, periodLengthS: 500n };
+ it('is the unspent part of the current period', () => {
+ expect(recurringRemaining(d, 1200)).toBe(30n);
+ });
+ it('resets once the period has fully elapsed', () => {
+ expect(recurringRemaining(d, 1500)).toBe(100n);
+ });
+ it('is zero before the first period starts', () => {
+ expect(recurringRemaining(d, 900)).toBe(0n);
+ });
+});
+
+describe('recurring delegation feature flag', () => {
+ it('is off unless ALLOWANCE_RECURRING_ENABLED is set', () => {
+ expect(recurringEnabled({})).toBe(false);
+ expect(recurringEnabled({ ALLOWANCE_RECURRING_ENABLED: '1' })).toBe(true);
+ expect(recurringEnabled({ ALLOWANCE_RECURRING_ENABLED: 'true' })).toBe(true);
+ });
+
+ it('refuses to prepare a recurring allowance while the flag is off', async () => {
+ const [owner, agent, mint] = [0, 1, 2].map(() => Keypair.generate().publicKey.toBase58());
+ await expect(
+ prepareCreateAllowance({ network: 'devnet', owner, delegatee: agent, mint, amount: 10n, expiryTs: NOW, kind: 'recurring', periodLengthS: 3600, env: {} }),
+ ).rejects.toMatchObject({ code: 'feature_disabled' });
+ });
+});
+
+describe('kitInstructionToWeb3', () => {
+ it('maps kit account roles to web3.js signer and writable flags', () => {
+ const keys = [0, 1, 2, 3].map(() => Keypair.generate().publicKey.toBase58());
+ const ix = kitInstructionToWeb3({
+ programAddress: keys[0],
+ accounts: [
+ { address: keys[0], role: 0 },
+ { address: keys[1], role: 1 },
+ { address: keys[2], role: 2 },
+ { address: keys[3], role: 3 },
+ ],
+ data: new Uint8Array([1, 2, 3]),
+ });
+ expect(ix.keys.map((k) => [k.isSigner, k.isWritable])).toEqual([[false, false], [false, true], [true, false], [true, true]]);
+ expect([...ix.data]).toEqual([1, 2, 3]);
+ });
+});
+
+describe('guard: remaining on-chain allowance is a hard ceiling', () => {
+ const owner = Keypair.generate().publicKey.toBase58();
+ const agentWallet = Keypair.generate().publicKey.toBase58();
+ const mint = Keypair.generate().publicKey.toBase58();
+ const pda = Keypair.generate().publicKey.toBase58();
+ const agentId = '11111111-1111-4111-8111-111111111111';
+
+ // A connection double at the RPC edge. getLatestBlockhash is what every
+ // transaction build needs; asserting it is never called proves the refusal
+ // happens before a transaction is built.
+ const conn = {
+ rpcEndpoint: 'http://127.0.0.1:1',
+ getAccountInfo: vi.fn(async () => ({ owner: TOKEN_PROGRAM_ID })),
+ getTokenAccountBalance: vi.fn(async () => ({ value: { amount: '500000000' } })),
+ getLatestBlockhash: vi.fn(),
+ };
+
+ function onChain(remaining, expiryTs = 0) {
+ fetchFixed.mockResolvedValue({
+ exists: true,
+ data: { mint, amount: BigInt(remaining), expiryTs: BigInt(expiryTs), header: { delegator: owner, delegatee: agentWallet } },
+ });
+ }
+
+ beforeEach(() => {
+ fetchFixed.mockReset();
+ conn.getLatestBlockhash.mockReset();
+ dbState.rows = [
+ {
+ id: 'a1', agent_id: agentId, user_id: 'u1', network: 'devnet', kind: 'fixed', owner_wallet: owner, delegatee: agentWallet,
+ mint, nonce: '1', delegation_pda: pda, cap_raw: '100000000', expiry_ts: 0, period_length_s: null,
+ create_signature: 's', revoke_signature: null, revoked_at: null, created_at: new Date(),
+ },
+ ];
+ });
+
+ it('refuses a pull above the remaining allowance without building a transaction', async () => {
+ onChain(60_000_000);
+ const v = await checkAgentAllowanceSpend({ agentId, network: 'devnet', mint, amount: 80_000_000n, connection: conn });
+ expect(v).toMatchObject({ gated: true, allow: false, code: 'allowance_exceeded' });
+ expect(v.detail).toEqual({ remaining: '60000000', requested: '80000000' });
+ expect(conn.getLatestBlockhash).not.toHaveBeenCalled();
+ });
+
+ it('allows a pull within the remaining allowance', async () => {
+ onChain(60_000_000);
+ const v = await checkAgentAllowanceSpend({ agentId, network: 'devnet', mint, amount: 40_000_000n, connection: conn });
+ expect(v).toMatchObject({ gated: true, allow: true, code: 'ok' });
+ expect(v.allowance.id).toBe('a1');
+ });
+
+ it('refuses once the delegation account is gone (revoked on chain)', async () => {
+ fetchFixed.mockResolvedValue({ exists: false });
+ const v = await checkAgentAllowanceSpend({ agentId, network: 'devnet', mint, amount: 1n, connection: conn });
+ expect(v).toMatchObject({ gated: true, allow: false, code: 'no_allowance' });
+ });
+
+ it('refuses an expired allowance', async () => {
+ onChain(60_000_000, 1);
+ const v = await checkAgentAllowanceSpend({ agentId, network: 'devnet', mint, amount: 1n, connection: conn });
+ expect(v).toMatchObject({ gated: true, allow: false, code: 'allowance_expired' });
+ });
+
+ it('does not gate an agent or token with no allowance on file', async () => {
+ const other = Keypair.generate().publicKey.toBase58();
+ expect(await checkAgentAllowanceSpend({ agentId, network: 'devnet', mint: other, amount: 1n, connection: conn })).toEqual({ gated: false });
+ expect(await checkAgentAllowanceSpend({ agentId, network: 'devnet', mint: 'not-an-address', amount: 1n, connection: conn })).toEqual({ gated: false });
+ });
+
+ it('checkAllowancePull reads the live owner balance as part of the ceiling', async () => {
+ onChain(60_000_000);
+ conn.getTokenAccountBalance.mockResolvedValueOnce({ value: { amount: '1000' } });
+ const v = await checkAllowancePull({ network: 'devnet', kind: 'fixed', delegationPda: pda, amount: 5_000_000n, connection: conn });
+ expect(v).toMatchObject({ allow: false, code: 'owner_balance_low' });
+ });
+});
+
+describe('AllowanceError', () => {
+ it('carries a machine-readable code', () => {
+ const e = new AllowanceError('invalid_request', 'bad');
+ expect(e).toBeInstanceOf(Error);
+ expect(e.code).toBe('invalid_request');
+ });
+});
diff --git a/tests/x-post-impact.test.js b/tests/x-post-impact.test.js
index 14585bf36..f312b38df 100644
--- a/tests/x-post-impact.test.js
+++ b/tests/x-post-impact.test.js
@@ -88,9 +88,9 @@ describe('correlateXPost', () => {
expect(r.deltaVolPct).toBeLessThan(0);
});
- it('returns post=null when every post rung throws, still computes price delta', async () => {
+ it('returns post=null when every post rung fails mid-body, still computes price delta', async () => {
route({
- post: () => Promise.reject(new Error('network error')),
+ post: { ok: true, status: 200, text: async () => '{not json' },
quotes: [quoteRes(10000, 50_000_000_000), quoteRes(10000, 50_000_000_000)],
});
diff --git a/tests/x-syndication.test.js b/tests/x-syndication.test.js
index c3f4f6aa3..22d3c1757 100644
--- a/tests/x-syndication.test.js
+++ b/tests/x-syndication.test.js
@@ -60,7 +60,7 @@ describe('readXPost', () => {
expect(p.metrics).toMatchObject({ likes: 120, replies: 9, views: null });
expect(p.ts).toBe(Date.parse('2026-10-01T12:00:00.000Z'));
const v = postVideoVariants(p);
- expect(v.map((x) => x.quality)).toEqual(['720p', '360p'].map((q, i) => (i === 0 ? q : v[1].quality)));
+ expect(v.map((x) => x.quality)).toEqual(['720p', '320p']);
expect(v[0].width).toBe(1280);
expect(v.every((x) => x.url.endsWith('.mp4') || x.url.includes('.mp4?'))).toBe(true);
expect(v).toHaveLength(2);
diff --git a/tests/x402-prepaid-ledger.test.js b/tests/x402-prepaid-ledger.test.js
index c4bf41181..49644bfee 100644
--- a/tests/x402-prepaid-ledger.test.js
+++ b/tests/x402-prepaid-ledger.test.js
@@ -21,7 +21,7 @@ const ledger = await import('../api/_lib/x402/prepaid-ledger.js');
const settle = await import('../api/_lib/x402/prepaid-settle.js');
const { reconcileReport } = await import('../api/_lib/x402/prepaid-reconcile.js');
const { servePrepaid } = await import('../api/_lib/x402/prepaid-route.js');
-const { PREPAID_ASSET, PREPAID_NETWORK } = await import('../api/_lib/x402/prepaid-chain.js');
+const { PREPAID_ASSET, PREPAID_NETWORK } = await import('../api/_lib/x402/prepaid-constants.js');
const MIGRATION = new URL(
'../api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql',
diff --git a/vercel.json b/vercel.json
index 1e32703e3..9c33aa7de 100644
--- a/vercel.json
+++ b/vercel.json
@@ -3169,6 +3169,14 @@
"src": "/splat/",
"dest": "/splat.html"
},
+ {
+ "src": "/x-video",
+ "dest": "/x-video.html"
+ },
+ {
+ "src": "/x-video/",
+ "dest": "/x-video.html"
+ },
{
"src": "/capture",
"dest": "/capture.html"
@@ -5768,6 +5776,14 @@
"src": "/api/auth/extension-token",
"dest": "/api/auth/extension-token.js"
},
+ {
+ "src": "/api/auth/agent-signup",
+ "dest": "/api/auth/agent-signup.js"
+ },
+ {
+ "src": "/api/billing/agent-upgrade",
+ "dest": "/api/billing/agent-upgrade.js"
+ },
{
"src": "/api/auth/handoff",
"dest": "/api/auth/handoff.js"
diff --git a/vite.config.js b/vite.config.js
index 878ec2871..fcbbf4da4 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1116,6 +1116,7 @@ const appConfig = {
wardrobe: resolve(__dirname, 'pages/wardrobe.html'),
'avatar-engines': resolve(__dirname, 'pages/avatar-engines.html'),
splat: resolve(__dirname, 'pages/splat.html'),
+ 'x-video': resolve(__dirname, 'pages/x-video.html'),
capture: resolve(__dirname, 'pages/capture.html'),
'motion-swap': resolve(__dirname, 'pages/motion-swap.html'),
'video-to-motion': resolve(__dirname, 'pages/video-to-motion.html'),
@@ -2091,6 +2092,8 @@ const appConfig = {
'/avatar-engines/': resolve(root, 'pages/avatar-engines.html'),
'/splat': resolve(root, 'pages/splat.html'),
'/splat/': resolve(root, 'pages/splat.html'),
+ '/x-video': resolve(root, 'pages/x-video.html'),
+ '/x-video/': resolve(root, 'pages/x-video.html'),
'/capture': resolve(root, 'pages/capture.html'),
'/capture/': resolve(root, 'pages/capture.html'),
'/motion-swap': resolve(root, 'pages/motion-swap.html'),
diff --git a/workers/robinhood-feed/tests/rpc.test.js b/workers/robinhood-feed/tests/rpc.test.js
index c7e75b127..ffd10d400 100644
--- a/workers/robinhood-feed/tests/rpc.test.js
+++ b/workers/robinhood-feed/tests/rpc.test.js
@@ -71,3 +71,24 @@ test('withRpcRetry: a non-transient error throws immediately, no retries', async
);
assert.equal(calls, 1);
});
+
+test('rateLimitWaitMs reads the provider reset window, caps it, and ignores other errors', async () => {
+ const { rateLimitWaitMs } = await import('../src/rpc.js');
+ assert.equal(rateLimitWaitMs(Object.assign(new Error('x'), { cause: { code: 429, message: 'Rate Limit Hit, limit will reset in 60 seconds' } })), 60_000);
+ assert.equal(rateLimitWaitMs(new Error('Rate Limit Hit')), 10_000);
+ assert.equal(rateLimitWaitMs(new Error('limit will reset in 900 seconds, rate limit')), 65_000);
+ assert.equal(rateLimitWaitMs(new Error('execution reverted')), null);
+});
+
+test('withRpcPatience waits out a rate limit window and then succeeds', async () => {
+ const { withRpcPatience } = await import('../src/rpc.js');
+ let calls = 0;
+ const waits = [];
+ const out = await withRpcPatience(async () => {
+ calls += 1;
+ if (calls <= 4) throw Object.assign(new Error('Rate Limit Hit, limit will reset in 30 seconds'), { status: 429 });
+ return 'ok';
+ }, { baseDelayMs: 1, sleep: async (ms) => { waits.push(ms); } });
+ assert.equal(out, 'ok');
+ assert.deepEqual(waits, [30_000]);
+});