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.

test(agent-payments-sdk): migrate the suite from jest to vitest (111 tests green)

nirholas0e4256159927
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91d513cd4..3d415c107 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,8 +4,13 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-08-12
+
+- **Your agent can now learn your Farcaster voice, and only after you prove the account is yours**: Memory seeding already worked from GitHub and X; Farcaster now joins them, with consent built into the protocol itself. Farcaster has no login button we could use, so instead the account's own public record does the work: every Farcaster account publishes the wallets it controls, and you prove ownership by signing a one-time challenge with one of those wallets, Solana first. Nothing is read, let alone stored, before that signature checks out. The grant is read-only and narrow: your public profile and up to 100 recent casts, distilled into identity, facts, and your strongest posts, so the agent talks the way you talk. Changing your mind is one click: revoking the grant deletes every memory it produced, including anything an earlier grant left behind. The whole flow lives in the agent persona editor, and it works with no API key configured because the reader falls back to a public Farcaster hub. (`/docs/farcaster-memory-seeding`) `[feature, security]`
+
## 2026-08-11
+- **Docs · Farcaster memory seeding** (`/docs/farcaster-memory-seeding`): Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.
- **Docs · Tokens API on three.ws** (`/docs/tokens-xyz`): The Solana Foundation asset layer wired into three.ws: how one canonical asset maps to every Solana mint that represents it, the batch market read that prices a whole portfolio in one call, and where it sits in the price failover chain behind Birdeye.
- **A Launch Copilot market-maker now tells you when its engine is not running**: The Launch Copilot dashboard showed an armed market-maker the same way whether or not a worker was actually sweeping it, so a saved floor and budget could sit there looking like a maker at work while nothing executed. The policy view now reads the engine's own heartbeat and, when no engine has checked in, the dashboard says so plainly: your policy, floor and budgets are saved and untouched, but no action will execute until it is back. (`/launch`) `[improvement]`
- **A long clip no longer pretends the whole scene was reconstructed**: Scene capture turns a video clip into a 3D point cloud, and the worker stops at a frame budget, reconstructing only the part of the clip that fits. The status you got back carried the point count and the frame count but never said the clip had been cut short, so a partial scene read as a finished one. The response now reports that the frames were truncated, along with how many sky points were dropped, so you can tell a complete reconstruction from a clipped one. (`/capture`) `[fix]`
diff --git a/agent-payments-sdk/jest.config.ts b/agent-payments-sdk/jest.config.ts
deleted file mode 100644
index eead7f910..000000000
--- a/agent-payments-sdk/jest.config.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { Config } from "jest";
-
-const config: Config = {
- preset: "ts-jest/presets/default-esm",
- testEnvironment: "node",
- extensionsToTreatAsEsm: [".ts"],
- moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1" },
- transform: { "^.+\\.tsx?$": ["ts-jest", { useESM: true }] },
-};
-
-export default config;
diff --git a/agent-payments-sdk/package.json b/agent-payments-sdk/package.json
index 7ef53800c..80d37f546 100644
--- a/agent-payments-sdk/package.json
+++ b/agent-payments-sdk/package.json
@@ -59,7 +59,7 @@
"lint": "eslint src/ --cache --quiet",
"lint:fix": "eslint src/ --cache --fix --quiet",
"clean": "rm -rf dist",
- "test": "node --experimental-vm-modules node_modules/.bin/jest",
+ "test": "vitest run",
"prepublishOnly": "npm run typecheck && npm run build:prod"
},
"dependencies": {
@@ -90,15 +90,13 @@
"@pump-fun/agent-payments-sdk-legacy": "npm:@pump-fun/[email protected]",
"@types/bn.js": "^5.2.0",
"@types/express": "^5.0.6",
- "@types/jest": "^30.0.0",
"@types/node": "^22.0.0",
"eslint": "^10.4.1",
"eslint-config-prettier": "^9.1.0",
- "jest": "^30.3.0",
- "ts-jest": "^29.4.6",
"tsup": "^8.3.5",
"typescript": "^5.7.3",
"typescript-eslint": "^8.61.0",
+ "vitest": "^4.1.9",
"zod": "^3.25.76"
},
"keywords": [
diff --git a/agent-payments-sdk/vitest.config.ts b/agent-payments-sdk/vitest.config.ts
new file mode 100644
index 000000000..c1433e6ef
--- /dev/null
+++ b/agent-payments-sdk/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ environment: "node",
+ include: ["src/**/*.test.ts"],
+ },
+});
diff --git a/api/_lib/draft-mint.js b/api/_lib/draft-mint.js
new file mode 100644
index 000000000..89da58353
--- /dev/null
+++ b/api/_lib/draft-mint.js
@@ -0,0 +1,394 @@
+// Draft agent mint — roadmap Phase 1 deliverable: every successful
+// reconstruction output is not only persisted to durable storage (R2, done by
+// reconstruct-finalize.js) but also minted as a DRAFT on-chain agent identity.
+//
+// Solana leads: the draft identity is a Metaplex Core asset minted into the
+// three.ws Agent Collection, reusing the exact machinery of the batch deployer
+// (api/_lib/onchain-deploy.js) so a draft mint is indistinguishable in shape
+// from any other platform mint — collection membership, brand attributes,
+// royalties, and Metaplex Agent Registry enrolment included.
+//
+// Network policy (the spend gate):
+// • DRAFT_AGENT_MINT_NETWORK = devnet (default) | mainnet | off
+// Devnet is the automated proof path: it runs whenever an authority secret
+// is configured and costs nothing real. MAINNET IS NEVER IMPLICIT — it
+// activates only when an operator explicitly sets
+// DRAFT_AGENT_MINT_NETWORK=mainnet AND funds
+// SOLANA_AGENT_COLLECTION_AUTHORITY_KEY on mainnet. That single flag is the
+// documented mainnet switch.
+// • Without an authority secret the leg reports 'skipped' — a no-op, so a
+// deployment without mint credentials behaves exactly as before.
+//
+// EVM leg (ERC-8004): behind DRAFT_AGENT_MINT_EVM_ENABLED=1 with
+// DRAFT_AGENT_MINT_EVM_CHAIN_ID (default 84532, Base Sepolia). It registers the
+// agent's card URI through the canonical Identity Registry from the agent's own
+// custodial EVM wallet, gas topped up from EVM_TREASURY_PRIVATE_KEY. With no
+// treasury key configured the leg is fully dry-run: it builds the real
+// register(string) calldata and estimates it against the chain's public RPC,
+// proving the wiring without broadcasting.
+//
+// The whole orchestration is best-effort by contract: callers (the
+// reconstruction finalize path) must treat a throw as non-fatal. Idempotent:
+// an agent already minted on a network short-circuits to 'already'.
+
+import { sql } from './db.js';
+import { env } from './env.js';
+import { resolveOrCreateAgentForAvatar } from './agent-identity.js';
+
+export const DRAFT_MINT_NETWORKS = /** @type {const} */ (['devnet', 'mainnet']);
+
+/**
+ * Resolve the Solana draft-mint network. Devnet is the default automated path;
+ * mainnet requires an explicit opt-in; 'off' disables the leg entirely.
+ * @param {NodeJS.ProcessEnv} [e]
+ * @returns {'devnet'|'mainnet'|'off'}
+ */
+export function resolveDraftMintNetwork(e = process.env) {
+ const v = String(e.DRAFT_AGENT_MINT_NETWORK || 'devnet').trim().toLowerCase();
+ if (v === 'off' || v === 'disabled' || v === '0') return 'off';
+ if (v === 'mainnet') return 'mainnet';
+ return 'devnet';
+}
+
+/**
+ * Resolve the EVM (ERC-8004) leg configuration. Off unless explicitly enabled.
+ * @param {NodeJS.ProcessEnv} [e]
+ * @returns {{ enabled: boolean, chainId: number }}
+ */
+export function resolveDraftMintEvm(e = process.env) {
+ const enabled = ['1', 'true', 'yes', 'on'].includes(
+ String(e.DRAFT_AGENT_MINT_EVM_ENABLED || '').trim().toLowerCase(),
+ );
+ const chainId = Number.parseInt(e.DRAFT_AGENT_MINT_EVM_CHAIN_ID || '84532', 10);
+ return { enabled, chainId: Number.isFinite(chainId) ? chainId : 84532 };
+}
+
+// ── Context loading ──────────────────────────────────────────────────────────
+
+/**
+ * Load the agent row joined with its avatar's storage keys — the exact shape
+ * deployAgentOnce() (onchain-deploy.js) consumes.
+ */
+async function loadAgentContext(agentId) {
+ const [row] = await sql`
+ SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,
+ av.thumbnail_key, av.storage_key
+ FROM agent_identities ai
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ai.id = ${agentId} AND ai.deleted_at IS NULL
+ LIMIT 1
+ `;
+ return row || null;
+}
+
+// ── Solana leg (Metaplex Core) ───────────────────────────────────────────────
+
+/** True when the agent already carries a minted identity on this network. */
+function alreadyMintedOn(meta, network) {
+ if (network === 'mainnet') return !!meta?.sol_mint_address;
+ return !!meta?.devnet?.sol_mint_address;
+}
+
+async function solanaDraftMint({ agent, network }) {
+ if (alreadyMintedOn(agent.meta, network)) {
+ const asset =
+ network === 'mainnet' ? agent.meta.sol_mint_address : agent.meta.devnet.sol_mint_address;
+ return { status: 'already', network, asset };
+ }
+
+ // Late import: the Umi/mpl-core stack is heavy and only needed on the mint
+ // path, never for flag parsing or the EVM leg.
+ const {
+ authoritySecret,
+ buildAuthorityUmi,
+ resolveAgentCollection,
+ loadCollectionAsset,
+ deployAgentOnce,
+ explorerUrl,
+ } = await import('./onchain-deploy.js');
+
+ if (!authoritySecret()) {
+ return { status: 'skipped', reason: 'authority_unconfigured', network };
+ }
+
+ const { umi, authoritySigner } = buildAuthorityUmi(network);
+ const collectionAddr = await resolveAgentCollection({ umi, authoritySigner, network });
+ const collectionAsset = await loadCollectionAsset(umi, collectionAddr);
+ const result = await deployAgentOnce({
+ umi,
+ authoritySigner,
+ collectionAddr,
+ collectionAsset,
+ agent,
+ network,
+ });
+ return {
+ status: 'minted',
+ network,
+ asset: result.asset,
+ signature: result.signature,
+ collection: collectionAddr,
+ owner: result.ownerAddress,
+ explorer: explorerUrl(result.asset, network),
+ registry: result.registry
+ ? { identity_pda: result.registry.identityPda, signature: result.registry.signature }
+ : null,
+ };
+}
+
+// ── EVM leg (ERC-8004 Identity Registry) ─────────────────────────────────────
+
+const ERC8004_REGISTER_ABI = [
+ 'function register(string) returns (uint256)',
+ 'event Registered(uint256 indexed agentId, string metadataURI, address indexed owner)',
+];
+
+/** Gas floor for the agent's custodial EVM wallet before it can self-sign. */
+const EVM_GAS_FLOOR_WEI = 250_000_000_000_000n; // 0.00025 native
+
+function evmExplorerTx(chain, txHash) {
+ return chain.explorer ? `${chain.explorer}/tx/${txHash}` : null;
+}
+
+/** Build the agent card the registry URI resolves to (three.ws Card v1 shape). */
+function buildDraftAgentCard({ agent, origin, publicUrl }) {
+ const image = agent.thumbnail_key ? publicUrl(agent.thumbnail_key) : `${origin}/og.png`;
+ const glb = agent.storage_key ? publicUrl(agent.storage_key) : null;
+ return {
+ name: agent.name || 'Agent',
+ description: agent.description || `${agent.name || 'Agent'}, an autonomous agent on three.ws`,
+ image,
+ url: `${origin}/agent/${agent.id}`,
+ active: false, // draft identity: registered on-chain, not yet live
+ x402Support: true,
+ services: glb ? [{ name: 'avatar', endpoint: glb, type: 'model/gltf-binary' }] : [],
+ };
+}
+
+/**
+ * Pin the draft card: real IPFS when a provider is configured, else the R2
+ * manifest fallback (same policy as onchain-deploy's pinManifest).
+ */
+async function pinDraftCard(card, agentId) {
+ const bytes = Buffer.from(JSON.stringify(card, null, 2), 'utf-8');
+ const { pinToIPFS } = await import('./ipfs-pin.js');
+ const pinned = await pinToIPFS(bytes, `agent-${agentId}.json`).catch(() => null);
+ if (pinned?.uri) return pinned.uri;
+ const { putObject, publicUrl } = await import('./r2.js');
+ const key = `agent-manifests/draft-evm/${agentId}.json`;
+ await putObject({ key, body: bytes, contentType: 'application/json' });
+ return publicUrl(key);
+}
+
+async function evmDraftMint({ agent, userId, chainId }) {
+ const { CHAIN_BY_ID } = await import('./erc8004-chains.js');
+ const chain = CHAIN_BY_ID[chainId];
+ if (!chain) return { status: 'skipped', reason: 'unsupported_chain', chainId };
+ if (agent.meta?.onchain?.chain === `eip155:${chainId}` && agent.meta.onchain.onchain_id) {
+ return {
+ status: 'already',
+ chainId,
+ onchainId: agent.meta.onchain.onchain_id,
+ txHash: agent.meta.onchain.tx_hash || null,
+ };
+ }
+
+ const { evmFallbackProvider } = await import('./evm/rpc.js');
+ const { getOrCreateAgentEvmWallet, recoverAgentKey } = await import('./agent-wallet.js');
+ const { address: evmAddress } = await getOrCreateAgentEvmWallet(agent.id, { chainId });
+ const provider = await evmFallbackProvider(chainId);
+
+ const { publicUrl } = await import('./r2.js');
+ const card = buildDraftAgentCard({ agent, origin: env.APP_ORIGIN, publicUrl });
+ const metadataUri = await pinDraftCard(card, agent.id);
+
+ const { Contract, Wallet, Interface, parseEther, formatEther } = await import('ethers');
+ const iface = new Interface(ERC8004_REGISTER_ABI);
+ const data = iface.encodeFunctionData('register(string)', [metadataUri]);
+
+ const treasurySecret = (process.env.EVM_TREASURY_PRIVATE_KEY || '').trim();
+ if (!treasurySecret) {
+ // Dry-run proof path: the calldata is real, the chain is reachable, and
+ // the estimate is produced by the chain itself. Nothing is broadcast.
+ let estimatedGas = null;
+ try {
+ estimatedGas = (
+ await provider.estimateGas({ from: evmAddress, to: chain.registry, data, gasPrice: 0 })
+ ).toString();
+ } catch (err) {
+ estimatedGas = `unavailable: ${err?.shortMessage || err?.message || 'estimate failed'}`;
+ }
+ return {
+ status: 'dry_run',
+ chainId,
+ chain: chain.name,
+ registry: chain.registry,
+ from: evmAddress,
+ to: chain.registry,
+ data,
+ metadataUri,
+ estimatedGas,
+ missing: 'EVM_TREASURY_PRIVATE_KEY',
+ };
+ }
+
+ // Fund the agent wallet for gas from the EVM treasury when it is light.
+ const treasury = new Wallet(treasurySecret, provider);
+ const bal = await provider.getBalance(evmAddress);
+ if (bal < EVM_GAS_FLOOR_WEI) {
+ const topUp = EVM_GAS_FLOOR_WEI - bal;
+ const tbal = await provider.getBalance(treasury.address);
+ if (tbal < topUp + parseEther('0.0001')) {
+ return {
+ status: 'skipped',
+ reason: `treasury_low:${formatEther(tbal)}`,
+ chainId,
+ };
+ }
+ const fundTx = await treasury.sendTransaction({ to: evmAddress, value: topUp });
+ await fundTx.wait();
+ }
+
+ const full = await loadAgentContext(agent.id);
+ const encKey = full?.meta?.encrypted_wallet_key;
+ if (!encKey) return { status: 'skipped', reason: 'no_evm_key', chainId };
+ const pkHex = await recoverAgentKey(encKey, {
+ agentId: agent.id,
+ userId,
+ reason: 'draft_agent_mint',
+ });
+ const signer = new Wallet(pkHex, provider);
+ const registry = new Contract(chain.registry, ERC8004_REGISTER_ABI, signer);
+ const tx = await registry['register(string)'](metadataUri);
+ const receipt = await tx.wait();
+
+ let onChainId = null;
+ for (const lg of receipt.logs || []) {
+ try {
+ const parsed = registry.interface.parseLog(lg);
+ if (parsed?.name === 'Registered') {
+ onChainId = parsed.args[0].toString();
+ break;
+ }
+ } catch { /* not our event */ }
+ }
+ if (!onChainId) throw new Error('Registered event not found in draft-mint receipt');
+
+ // Persist exactly what register-confirm.js persists after verifying a mint:
+ // the crawler index row plus the unified meta.onchain block on the agent.
+ await sql`
+ INSERT INTO erc8004_agents_index
+ (chain_id, agent_id, owner, registry, agent_uri,
+ registered_block, registered_tx, registered_at, last_seen_at)
+ VALUES
+ (${chainId}, ${onChainId}, ${evmAddress.toLowerCase()}, ${chain.registry.toLowerCase()},
+ ${metadataUri}, ${Number(receipt.blockNumber)}, ${receipt.hash}, now(), now())
+ ON CONFLICT (chain_id, agent_id) DO NOTHING
+ `;
+ const [cur] = await sql`SELECT meta FROM agent_identities WHERE id = ${agent.id}`;
+ const onchain = {
+ chain: `eip155:${chainId}`,
+ family: 'evm',
+ tx_hash: receipt.hash,
+ onchain_id: onChainId,
+ contract_or_mint: chain.registry,
+ wallet: evmAddress.toLowerCase(),
+ metadata_uri: metadataUri,
+ draft: true,
+ confirmed_at: new Date().toISOString(),
+ };
+ await sql`
+ UPDATE agent_identities
+ SET meta = ${JSON.stringify({ ...(cur?.meta || {}), onchain })}::jsonb, updated_at = NOW()
+ WHERE id = ${agent.id}
+ `;
+
+ return {
+ status: 'minted',
+ chainId,
+ chain: chain.name,
+ registry: chain.registry,
+ onchainId,
+ owner: evmAddress,
+ txHash: receipt.hash,
+ metadataUri,
+ explorer: evmExplorerTx(chain, receipt.hash),
+ };
+}
+
+// ── Avatar traceability ──────────────────────────────────────────────────────
+
+/** Stamp the draft-mint outcome onto the avatar's source_meta for audit. */
+async function persistAvatarDraft({ avatarId, jobId, solana, evm }) {
+ const stamp = {
+ draft_mint: {
+ job_id: jobId,
+ solana: solana
+ ? { status: solana.status, network: solana.network, asset: solana.asset || null, signature: solana.signature || null }
+ : null,
+ evm: evm
+ ? { status: evm.status, chain_id: evm.chainId ?? null, onchain_id: evm.onchainId || null, tx_hash: evm.txHash || null }
+ : null,
+ minted_at: new Date().toISOString(),
+ },
+ };
+ await sql`
+ UPDATE avatars
+ SET source_meta = coalesce(source_meta, '{}'::jsonb) || ${JSON.stringify(stamp)}::jsonb
+ WHERE id = ${avatarId}
+ `;
+}
+
+// ── Orchestration ────────────────────────────────────────────────────────────
+
+function defaultDeps() {
+ return {
+ resolveAgent: resolveOrCreateAgentForAvatar,
+ loadAgentContext,
+ solanaMint: solanaDraftMint,
+ evmMint: evmDraftMint,
+ persistAvatarDraft,
+ network: resolveDraftMintNetwork(),
+ evm: resolveDraftMintEvm(),
+ };
+}
+
+/**
+ * Mint the draft on-chain identity for a freshly reconstructed avatar.
+ *
+ * @param {object} input
+ * @param {string} input.userId owner of the avatar
+ * @param {string} input.avatarId the materialized reconstruction avatar
+ * @param {string} [input.jobId] originating regen job (traceability only)
+ * @param {object} [deps] injected dependencies (testing)
+ * @returns {Promise<{ status: string, agentId?: string, solana?: object|null, evm?: object|null }>}
+ */
+export async function mintDraftAgentIdentity({ userId, avatarId, jobId = null }, deps = defaultDeps()) {
+ const agent = await deps.resolveAgent({ userId, avatarId });
+ if (!agent) return { status: 'no_agent' };
+
+ let solana = null;
+ let evm = null;
+
+ if (deps.network !== 'off') {
+ const ctx = await deps.loadAgentContext(agent.id);
+ if (ctx) {
+ solana = await deps.solanaMint({ agent: ctx, network: deps.network });
+ }
+ }
+
+ if (deps.evm?.enabled) {
+ const ctx = await deps.loadAgentContext(agent.id);
+ if (ctx) {
+ evm = await deps.evmMint({ agent: ctx, userId, chainId: deps.evm.chainId });
+ }
+ }
+
+ if ((solana && solana.status !== 'skipped') || evm) {
+ await deps.persistAvatarDraft({ avatarId, jobId, solana, evm }).catch((err) => {
+ console.warn('[draft-mint] avatar stamp failed:', err?.message);
+ });
+ }
+
+ return { status: 'ok', agentId: agent.id, solana, evm };
+}
diff --git a/api/_lib/image-persist.js b/api/_lib/image-persist.js
new file mode 100644
index 000000000..af3fc35a8
--- /dev/null
+++ b/api/_lib/image-persist.js
@@ -0,0 +1,49 @@
+// Shared image persistence for generated images.
+//
+// Two call sites grew byte-identical copies of this (api/_mcp3d/text-to-image.js
+// for the NIM FLUX artifact, api/_lib/forge-reference-image.js for the Vertex
+// Gemini inline data) and the Livepeer federation provider needed a third. The
+// rule it enforces matters enough to live in exactly one place:
+//
+// Downstream image-to-3D providers take URLs, not inline data (Replicate caps
+// inline data URIs at ~256 KB — a 1024px image blows straight past that), so
+// every synthesized image is persisted to R2 and handed on as a durable
+// public https URL.
+//
+// The format is sniffed from the magic bytes so the object key extension and
+// Content-Type always match the real payload: NIM FLUX returns JPEG artifacts,
+// Vertex Imagen and Gemini return PNG, and the Livepeer gateway can serve
+// either. Unknown bytes keep the PNG label (the historical default).
+
+import { putObject, publicUrl } from './r2.js';
+
+// 'jpg' | 'png' — sniffed from magic bytes. JPEG: FF D8 FF. Anything else is
+// labeled png, matching the legacy behavior of every prior copy of this code.
+export function sniffImageFormat(body) {
+ const isJpeg = body.length > 2 && body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff;
+ return isJpeg ? 'jpg' : 'png';
+}
+
+// True when the bytes start with a known image signature (JPEG or PNG). The
+// federation adapter uses this as the cheap verification gate before paying
+// the persistence write: a gateway that answers 200 with an HTML error page or
+// an empty body fails here instead of poisoning the reference-image pipeline.
+export function looksLikeImageBytes(body) {
+ if (!body || body.length < 4) return false;
+ if (body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff) return true; // JPEG
+ return body[0] === 0x89 && body[1] === 0x50 && body[2] === 0x4e && body[3] === 0x47; // PNG
+}
+
+// Persist raw image bytes to R2 and return a durable public https URL.
+export async function persistImageBytes(body) {
+ const ext = sniffImageFormat(body);
+ const key = `forge/refs/${globalThis.crypto.randomUUID()}.${ext}`;
+ await putObject({ key, body, contentType: ext === 'jpg' ? 'image/jpeg' : 'image/png' });
+ return publicUrl(key);
+}
+
+// Persist a base64-encoded image. Same behavior as persistImageBytes; kept as
+// the named entry point the NIM and Vertex lanes already call.
+export async function persistImageBase64(b64) {
+ return persistImageBytes(Buffer.from(b64, 'base64'));
+}
diff --git a/api/_lib/inference-benchmark.js b/api/_lib/inference-benchmark.js
new file mode 100644
index 000000000..401c91d2a
--- /dev/null
+++ b/api/_lib/inference-benchmark.js
@@ -0,0 +1,60 @@
+// GENERATED by node-operator/scripts/generate-benchmarks.mjs - do not hand-edit.
+// Every expected output below was produced by REALLY running the vendored
+// MNIST-8 model (ONNX model zoo, MIT) on the vector next to it. The platform
+// uses these as the proof-of-compute benchmark for the open inference
+// network: a node proves it can run real inference by reproducing the
+// recorded argmax on its assigned vector. Regenerate with:
+//
+// node node-operator/scripts/generate-benchmarks.mjs
+
+export const PROOF_MODEL = 'mnist-8';
+export const PROOF_MODEL_SHA256 = '2f06e72de813a8635c9bc0397ac447a601bdbfa7df4bebc278723b958831c9bf';
+export const PROOF_VECTOR_SET_SHA256 = 'ac94e1a486b138ecd14e24f8a37e8ff4c8f9b9aa2c349811bf9b2d1acda99ece';
+
+// input_b64: base64 of 784 little-endian float32 values (28x28 grayscale,
+// MNIST layout, values in [0,1]). expected_top1: argmax of the 10 logits the
+// model emits for that input. logits_sha256: recorded for audit, not
+// enforced (execution providers may differ in the last ulp; argmax is the
+// stable contract).
+export const PROOF_VECTORS = [
+ {
+ seed: 11,
+ input_b64:
+ 'WBl2Pkl4jT7X4LM+M7KZPcEXNz+MvFg/XFquPWG8Nz+bQ9Q9S9xaPjWnST/ofoo+gva3PvfQtT4csgQ/40wkP3vsyD6UL/U+NB8rP6VszD732gE+Q5o7P/HaRT9iWhM9qoqbPqldAD4HfxM/IBBNPa8TuT4EjWw/a4ZOP8p+Oj9an3c/OTFBPaCCuT6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FT/Gzzc/TrspP30+lj3YYac9YiU8Pnmvez9Y4js/pn0aP7kzqj7I2sM+JZUVP/vVUz/G2T0/9KpwP5Dpxj588aw+kB2XPphU/j4WNXI/tP9hPw==',
+ expected_top1: 3,
+ logits_sha256: '92a784c3a1f5195cf8a9e0fa462937bb710d234ae41325d8ce3530c96edf3a7f',
+ }
+];
+
+export function decodeProofInput(b64) {
+ const bytes = Buffer.from(b64, 'base64');
+ return new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
+}
diff --git a/api/_lib/inference-settlement.js b/api/_lib/inference-settlement.js
new file mode 100644
index 000000000..dc894193c
--- /dev/null
+++ b/api/_lib/inference-settlement.js
@@ -0,0 +1,323 @@
+// Inference settlement — per-job metering and cryptographic receipts for paid
+// inference work (Roadmap phase 4). Pure core: no fetch, no chain, no DB, no
+// env. The I/O lives in the callers:
+//
+// api/x402/llm-proxy.js — meters each paid job, signs the response,
+// issues the receipt after settlement.
+// api/_lib/inference-jobs.js — durable persistence of metered jobs.
+// api/x402/inference-verify.js — free HTTP verifier built on verifyInferenceReceipt.
+// scripts/inference-receipt-verify.mjs — offline CLI for node operators.
+//
+// Two signature layers, both ed25519 over domain-tagged canonical JSON (the
+// same construction as the 3D provenance credentials in provenance-3d.js):
+//
+// 1. Response signature: the node signs the metered job core (job id,
+// prompt hash, response hash, token counts, model, provider). Proves the
+// node stands behind THIS output for THIS prompt.
+// 2. Receipt signature: the settlement issuer signs the job core + the
+// response signature + the payment facts (network, payer, payTo, amount,
+// asset, settlement transaction). One signature atomically ties the money
+// to the exact work performed, so a node operator can prove "I was paid
+// X for exactly this job" and a buyer can prove "this payment bought
+// exactly this answer".
+//
+// Spec: specs/inference-receipts.md. Tests: tests/inference-settlement.test.js.
+
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+
+import { sha256Hex } from './provenance-3d.js';
+
+export const INFERENCE_RESPONSE_TYPE = 'three-inference-response/v1';
+export const INFERENCE_RECEIPT_TYPE = 'three-inference-receipt/v1';
+
+// Domain-separation tags prepended to the canonical bytes before signing, so a
+// signature from any other three.ws signing scheme (vanity receipts, 3D
+// provenance, agent manifests) can never be replayed as an inference artifact.
+const TAG_RESPONSE = Buffer.from('three-inference-response/v1\n', 'utf8');
+const TAG_RECEIPT = Buffer.from('three-inference-receipt/v1\n', 'utf8');
+
+// Deterministic JSON: object keys sorted recursively so signer and verifier
+// produce byte-identical messages regardless of key insertion order. Same
+// algorithm as provenance-3d.js (kept local so this module's wire format is
+// self-contained and never drifts with another feature's needs).
+function canonicalize(value) {
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const keys = Object.keys(value).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
+ }
+ return JSON.stringify(value === undefined ? null : value);
+}
+
+function taggedBytes(tag, value) {
+ return Buffer.concat([tag, Buffer.from(canonicalize(value), 'utf8')]);
+}
+
+function assertHash(hex, field) {
+ if (typeof hex !== 'string' || !/^[0-9a-f]{64}$/.test(hex)) {
+ throw new Error(`${field} must be a 64-char lowercase sha256 hex string`);
+ }
+}
+
+function assertTokenCount(n, field) {
+ if (!Number.isInteger(n) || n < 0) {
+ throw new Error(`${field} must be a non-negative integer, got ${n}`);
+ }
+}
+
+/** sha256 (hex) of the exact prompt string the job ran. */
+export function hashPrompt(prompt) {
+ return sha256Hex(Buffer.from(String(prompt ?? ''), 'utf8'));
+}
+
+/** sha256 (hex) of the exact completion text the node returned. */
+export function hashResponse(content) {
+ return sha256Hex(Buffer.from(String(content ?? ''), 'utf8'));
+}
+
+/**
+ * Meter one inference job: bind the job identity to the hashes of its input
+ * and output and the measured token counts. This object is the signed unit:
+ * everything a verifier needs to re-derive the commitment from the raw
+ * prompt/content lands here.
+ *
+ * @param {object} args
+ * @param {string} args.jobId unique job identifier (uuid)
+ * @param {string} args.route paid route that served the job
+ * @param {string} args.model concrete model that produced the output
+ * @param {string} args.provider provider lane that ran it (groq, ovh, ...)
+ * @param {string} args.prompt raw prompt text (hashed, never stored here)
+ * @param {string} args.content raw completion text (hashed, never stored here)
+ * @param {{ input?: number, output?: number }} [args.usage] provider-reported counts
+ * @param {number} [args.latencyMs] measured wall-clock latency
+ * @returns {object} the metered job core
+ */
+export function meterInferenceJob({ jobId, route, model, provider, prompt, content, usage, latencyMs }) {
+ if (!jobId || typeof jobId !== 'string') throw new Error('meterInferenceJob: jobId is required');
+ if (!route || typeof route !== 'string') throw new Error('meterInferenceJob: route is required');
+ const inputTokens = usage?.input ?? 0;
+ const outputTokens = usage?.output ?? 0;
+ assertTokenCount(inputTokens, 'usage.input');
+ assertTokenCount(outputTokens, 'usage.output');
+ const job = {
+ type: INFERENCE_RESPONSE_TYPE,
+ jobId,
+ route,
+ model: String(model || 'unknown'),
+ provider: String(provider || 'unknown'),
+ promptSha256: hashPrompt(prompt),
+ responseSha256: hashResponse(content),
+ inputTokens,
+ outputTokens,
+ tokensUsed: inputTokens + outputTokens,
+ };
+ if (Number.isFinite(latencyMs)) job.latencyMs = Math.round(latencyMs);
+ return job;
+}
+
+/**
+ * Decode an ed25519 secret key from the encodings used across this codebase:
+ * base58, base64, or a JSON byte array. Accepts a 64-byte expanded secret key
+ * or a 32-byte seed; returns the 32-byte seed @noble/curves signs with.
+ */
+export function decodeSigningSeed(secret) {
+ if (secret instanceof Uint8Array) {
+ if (secret.length === 32 || secret.length === 64) return secret.slice(0, 32);
+ throw new Error('signing key must be a 32-byte seed or 64-byte secret key');
+ }
+ const trimmed = String(secret || '').trim();
+ if (!trimmed) throw new Error('signing key is empty');
+ if (trimmed.startsWith('[')) {
+ try {
+ const bytes = Uint8Array.from(JSON.parse(trimmed));
+ if (bytes.length === 32 || bytes.length === 64) return bytes.slice(0, 32);
+ } catch (err) {
+ throw new Error(`signing key: malformed JSON byte array (${err.message})`);
+ }
+ }
+ for (const decode of [
+ () => bs58.decode(trimmed),
+ () => new Uint8Array(Buffer.from(trimmed, 'base64')),
+ ]) {
+ try {
+ const bytes = decode();
+ if (bytes.length === 32 || bytes.length === 64) return bytes.slice(0, 32);
+ } catch {
+ /* try the next encoding */
+ }
+ }
+ throw new Error('signing key must be base58, base64, or a JSON byte array (32 or 64 bytes)');
+}
+
+/** The base58 ed25519 public key for a signing seed (any accepted encoding). */
+export function signerPublicKey(secret) {
+ return bs58.encode(ed25519.getPublicKey(decodeSigningSeed(secret)));
+}
+
+/**
+ * Sign the metered job core. This is the node's attestation: "this output,
+ * these token counts, this prompt hash — I produced them for this job id."
+ * Returns { responseSignature, responseSigner } (both base58).
+ */
+export function signJobResponse(job, secret) {
+ if (!job || job.type !== INFERENCE_RESPONSE_TYPE) {
+ throw new Error('signJobResponse: pass the metered job object from meterInferenceJob()');
+ }
+ const seed = decodeSigningSeed(secret);
+ const msg = taggedBytes(TAG_RESPONSE, job);
+ return {
+ responseSignature: bs58.encode(ed25519.sign(msg, seed)),
+ responseSigner: bs58.encode(ed25519.getPublicKey(seed)),
+ };
+}
+
+/** Verify a response signature against the metered job core. Pure + offline. */
+export function verifyJobResponseSignature(job, responseSignature, responseSigner) {
+ try {
+ const msg = taggedBytes(TAG_RESPONSE, job);
+ return ed25519.verify(bs58.decode(responseSignature), msg, bs58.decode(responseSigner));
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Issue the settlement receipt: one signature tying the payment facts to the
+ * exact metered job and the node's response signature.
+ *
+ * @param {object} args
+ * @param {object} args.job metered job from meterInferenceJob()
+ * @param {string} args.responseSignature from signJobResponse()
+ * @param {string} args.responseSigner from signJobResponse()
+ * @param {object} args.payment { network, payer, payTo, amountAtomics, asset, transaction }
+ * @param {string|Uint8Array} args.secret issuer signing key
+ * @param {string} [args.issuedAt] ISO timestamp (default: now)
+ * @returns {object} the signed receipt
+ */
+export function issueInferenceReceipt({ job, responseSignature, responseSigner, payment, secret, issuedAt }) {
+ if (!job || job.type !== INFERENCE_RESPONSE_TYPE) {
+ throw new Error('issueInferenceReceipt: pass the metered job object from meterInferenceJob()');
+ }
+ assertHash(job.promptSha256, 'job.promptSha256');
+ assertHash(job.responseSha256, 'job.responseSha256');
+ assertTokenCount(job.inputTokens, 'job.inputTokens');
+ assertTokenCount(job.outputTokens, 'job.outputTokens');
+ if (!payment || typeof payment !== 'object') throw new Error('issueInferenceReceipt: payment is required');
+ for (const field of ['network', 'payer', 'payTo', 'asset', 'transaction']) {
+ if (!payment[field] || typeof payment[field] !== 'string') {
+ throw new Error(`issueInferenceReceipt: payment.${field} is required`);
+ }
+ }
+ if (payment.amountAtomics == null || !/^\d+$/.test(String(payment.amountAtomics))) {
+ throw new Error('issueInferenceReceipt: payment.amountAtomics must be a decimal string');
+ }
+ const core = {
+ receiptType: INFERENCE_RECEIPT_TYPE,
+ issuedAt: issuedAt || new Date().toISOString(),
+ job,
+ responseSignature,
+ responseSigner,
+ payment: {
+ network: payment.network,
+ payer: payment.payer,
+ payTo: payment.payTo,
+ amountAtomics: String(payment.amountAtomics),
+ asset: payment.asset,
+ transaction: payment.transaction,
+ },
+ };
+ const seed = decodeSigningSeed(secret);
+ const signer = bs58.encode(ed25519.getPublicKey(seed));
+ const signature = bs58.encode(ed25519.sign(taggedBytes(TAG_RECEIPT, { ...core, signer }), seed));
+ return { ...core, signer, signature };
+}
+
+/**
+ * Verify an inference receipt. Pure and offline; on-chain confirmation of the
+ * settlement transaction is a separate, optional step (the HTTP verifier and
+ * the CLI both layer it on top; this function is the cryptographic core).
+ *
+ * @param {object} receipt the receipt object (as JSON)
+ * @param {object} [opts]
+ * @param {string} [opts.prompt] raw prompt; when given, re-binds promptSha256
+ * @param {string} [opts.content] raw completion; when given, re-binds responseSha256
+ * @param {string} [opts.trustedSigner] pin the receipt issuer to this base58 pubkey
+ * @returns {{ ok: boolean, checks: Array<{ name: string, ok: boolean, detail?: string }>, reason?: string }}
+ */
+export function verifyInferenceReceipt(receipt, { prompt, content, trustedSigner } = {}) {
+ const checks = [];
+ const check = (name, ok, detail) => {
+ checks.push(detail ? { name, ok, detail } : { name, ok });
+ return ok;
+ };
+
+ if (!receipt || typeof receipt !== 'object') {
+ check('shape', false, 'receipt must be a JSON object');
+ return { ok: false, checks, reason: 'not an object' };
+ }
+ if (
+ !check('shape',
+ receipt.receiptType === INFERENCE_RECEIPT_TYPE &&
+ typeof receipt.signature === 'string' &&
+ typeof receipt.signer === 'string' &&
+ receipt.job && typeof receipt.job === 'object' &&
+ receipt.payment && typeof receipt.payment === 'object',
+ receipt.receiptType === INFERENCE_RECEIPT_TYPE ? undefined : `receiptType must be ${INFERENCE_RECEIPT_TYPE}`)
+ ) {
+ return { ok: false, checks, reason: 'malformed receipt' };
+ }
+
+ const { job, payment } = receipt;
+
+ // The receipt's own signature covers everything except `signature` itself.
+ let receiptSigOk = false;
+ try {
+ const { signature, ...core } = receipt;
+ receiptSigOk = ed25519.verify(
+ bs58.decode(signature),
+ taggedBytes(TAG_RECEIPT, core),
+ bs58.decode(receipt.signer),
+ );
+ } catch {
+ receiptSigOk = false;
+ }
+ check('receipt_signature', receiptSigOk, receiptSigOk ? undefined : 'issuer signature does not verify over the receipt core');
+
+ if (trustedSigner) {
+ check('receipt_signer_trusted', receipt.signer === trustedSigner,
+ receipt.signer === trustedSigner ? undefined : `issuer ${receipt.signer} is not the pinned signer ${trustedSigner}`);
+ }
+
+ const responseSigOk = verifyJobResponseSignature(job, receipt.responseSignature, receipt.responseSigner);
+ check('response_signature', responseSigOk, responseSigOk ? undefined : 'node response signature does not verify over the metered job');
+
+ if (prompt !== undefined) {
+ const want = hashPrompt(prompt);
+ check('prompt_binding', job.promptSha256 === want,
+ job.promptSha256 === want ? undefined : `prompt hashes to ${want}, receipt commits to ${job.promptSha256}`);
+ }
+ if (content !== undefined) {
+ const want = hashResponse(content);
+ check('response_binding', job.responseSha256 === want,
+ job.responseSha256 === want ? undefined : `content hashes to ${want}, receipt commits to ${job.responseSha256}`);
+ }
+
+ const tokensOk =
+ Number.isInteger(job.inputTokens) && job.inputTokens >= 0 &&
+ Number.isInteger(job.outputTokens) && job.outputTokens >= 0 &&
+ job.tokensUsed === job.inputTokens + job.outputTokens;
+ check('token_totals', tokensOk, tokensOk ? undefined : 'tokensUsed must equal inputTokens + outputTokens');
+
+ const paymentOk =
+ typeof payment.network === 'string' && payment.network.length > 0 &&
+ typeof payment.payer === 'string' && payment.payer.length > 0 &&
+ typeof payment.payTo === 'string' && payment.payTo.length > 0 &&
+ typeof payment.asset === 'string' && payment.asset.length > 0 &&
+ typeof payment.transaction === 'string' && payment.transaction.length > 0 &&
+ /^\d+$/.test(String(payment.amountAtomics ?? ''));
+ check('payment_fields', paymentOk, paymentOk ? undefined : 'payment must carry network, payer, payTo, asset, transaction, amountAtomics');
+
+ const failed = checks.find((c) => !c.ok);
+ return { ok: !failed, checks, ...(failed ? { reason: failed.name } : {}) };
+}
diff --git a/api/_lib/oin-verify.js b/api/_lib/oin-verify.js
new file mode 100644
index 000000000..164bc700e
--- /dev/null
+++ b/api/_lib/oin-verify.js
@@ -0,0 +1,242 @@
+// Open Inference Protocol (OIN) v0.1 verifier and signing primitives.
+//
+// Implements the verification rules from specs/OPEN_INFERENCE_PROTOCOL.md:
+// canonical (RFC 8785 JCS) JSON, SHA-256 job digests, and Ed25519 response
+// signatures over the canonical response minus its `signature` field.
+// Dependency-free (Node stdlib only) so any requester, relay, or auditor can
+// verify a node's signed response without trusting the transport.
+//
+// Exports:
+// canonicalize(value) -> canonical JSON string (RFC 8785)
+// digestJob(envelope) -> lowercase hex SHA-256 of the canonical envelope
+// signResponse(response, keyB64) -> response with `signature` filled in (node side)
+// signAdvertisement(ad, keyB64) -> advertisement with `signature` filled in
+// verifyResponse(job, response, opts) -> { ok, verdict, ... }
+// verifyOutput(response, fetchImpl?) -> rule 6: hash the bytes at output.url
+//
+// Verdicts are the exact codes the spec names: bad_shape, job_digest_mismatch,
+// bad_pubkey, untrusted_node, bad_signature, stale_response, future_response,
+// output_digest_mismatch, verified, verified_unfetched_output.
+
+import { createHash, createPrivateKey, createPublicKey, sign as cryptoSign, verify as cryptoVerify } from 'node:crypto';
+
+export const OIN_SPEC = 'oin/0.1';
+const MAX_FUTURE_SKEW_MS = 24 * 60 * 60 * 1000;
+const MAX_OUTPUT_BYTES = 256 * 1024 * 1024;
+
+// ── canonical JSON (RFC 8785 JCS) ────────────────────────────────────────────
+
+function canonicalizeNumber(n) {
+ if (!Number.isFinite(n)) throw new TypeError('OIN canonicalization: non-finite number');
+ // JCS uses the ECMAScript Number::toString algorithm, which JSON.stringify
+ // already implements for finite numbers.
+ return JSON.stringify(n);
+}
+
+function canonicalize(value) {
+ if (value === null) return 'null';
+ const t = typeof value;
+ if (t === 'boolean') return value ? 'true' : 'false';
+ if (t === 'number') return canonicalizeNumber(value);
+ if (t === 'string') return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map((v) => canonicalize(v)).join(',')}]`;
+ if (t === 'object') {
+ // JCS sorts object keys by UTF-16 code units, which is Array.prototype.sort's default.
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined && typeof value[k] !== 'function').sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
+ }
+ throw new TypeError(`OIN canonicalization: unsupported type ${t}`);
+}
+
+// ── digests and keys ─────────────────────────────────────────────────────────
+
+function sha256hex(bytes) {
+ return createHash('sha256').update(bytes).digest('hex');
+}
+
+function digestJob(envelope) {
+ return sha256hex(Buffer.from(canonicalize(envelope), 'utf8'));
+}
+
+function keyObjectFromSecret(keyB64) {
+ const raw = Buffer.from(String(keyB64), 'base64');
+ if (raw.length !== 32 && raw.length !== 64) {
+ throw new Error('OIN signing key must be 32-byte seed or 64-byte expanded key, base64');
+ }
+ // PKCS#8 DER wrapper for a raw Ed25519 seed: 302e020100300506032b657004220420 || seed
+ const seed = raw.length === 64 ? raw.subarray(0, 32) : raw;
+ const der = Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), seed]);
+ return createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
+}
+
+function pubkeyB64FromSecret(keyB64) {
+ const priv = keyObjectFromSecret(keyB64);
+ const der = createPublicKey(priv).export({ format: 'der', type: 'spki' });
+ // SPKI for Ed25519 is 12 bytes of header + the 32-byte key.
+ return Buffer.from(der).subarray(-32).toString('base64');
+}
+
+function pubKeyObjectFromField(nodePubkey) {
+ if (typeof nodePubkey !== 'string' || !nodePubkey.startsWith('ed25519:')) return null;
+ const raw = Buffer.from(nodePubkey.slice('ed25519:'.length), 'base64');
+ if (raw.length !== 32) return null;
+ // SPKI DER wrapper for a raw Ed25519 public key: 302a300506032b6570032100 || key
+ const der = Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), raw]);
+ try {
+ return createPublicKey({ key: der, format: 'der', type: 'spki' });
+ } catch {
+ return null;
+ }
+}
+
+// ── signing (node side) ──────────────────────────────────────────────────────
+
+function signPayload(payload, keyB64) {
+ const priv = keyObjectFromSecret(keyB64);
+ const bytes = Buffer.from(canonicalize(payload), 'utf8');
+ // Ed25519 is deterministic pure signing: null algorithm, message in one shot.
+ return cryptoSign(null, bytes, priv).toString('base64');
+}
+
+function signResponse(response, keyB64) {
+ const { signature: _drop, ...unsigned } = response;
+ return { ...unsigned, signature: signPayload(unsigned, keyB64) };
+}
+
+function signAdvertisement(advertisement, keyB64) {
+ const { signature: _drop, ...unsigned } = advertisement;
+ return { ...unsigned, signature: signPayload(unsigned, keyB64) };
+}
+
+// ── verification (rules 1-5 of the spec) ─────────────────────────────────────
+
+function fail(verdict, detail) {
+ return { ok: false, verified: false, verdict, detail };
+}
+
+function verifyResponse(job, response, opts = {}) {
+ // Rule 1: shape.
+ if (!response || typeof response !== 'object' || Array.isArray(response)) {
+ return fail('bad_shape', 'response is not an object');
+ }
+ if (response.spec !== OIN_SPEC) return fail('bad_shape', `spec must be ${OIN_SPEC}`);
+ for (const field of ['job_digest', 'node_pubkey', 'completed_at', 'status', 'signature']) {
+ if (typeof response[field] !== 'string' || !response[field]) {
+ return fail('bad_shape', `missing field: ${field}`);
+ }
+ }
+ if (response.status !== 'done' && response.status !== 'failed') {
+ return fail('bad_shape', `status must be done|failed, got ${response.status}`);
+ }
+ if (response.status === 'done' && (!response.output || typeof response.output !== 'object')) {
+ return fail('bad_shape', 'done response must carry output');
+ }
+ if (response.status === 'failed' && (!response.error || typeof response.error !== 'object')) {
+ return fail('bad_shape', 'failed response must carry error');
+ }
+ if (response.status === 'done') {
+ const { url, sha256, bytes } = response.output;
+ if (typeof url !== 'string' || typeof sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(sha256) || !Number.isInteger(bytes) || bytes < 0) {
+ return fail('bad_shape', 'output needs url, sha256 (64 lowercase hex), bytes (non-negative int)');
+ }
+ }
+ if (!/^[0-9a-f]{64}$/.test(response.job_digest)) {
+ return fail('bad_shape', 'job_digest must be 64 lowercase hex chars');
+ }
+
+ // Rule 2: job binding.
+ const expectedDigest = digestJob(job);
+ if (response.job_digest !== expectedDigest) {
+ return fail('job_digest_mismatch', `expected ${expectedDigest}, got ${response.job_digest}`);
+ }
+
+ // Rule 3: key parses and (when pinned/advertised) matches.
+ const pub = pubKeyObjectFromField(response.node_pubkey);
+ if (!pub) return fail('bad_pubkey', 'node_pubkey must be ed25519:<base64 32-byte key>');
+ if (opts.expectedPubkey && response.node_pubkey !== opts.expectedPubkey) {
+ return fail('untrusted_node', `response key does not match pinned/advertised ${opts.expectedPubkey}`);
+ }
+
+ // Rule 4: signature over the canonical response minus `signature`.
+ const { signature, ...unsigned } = response;
+ let sigBytes;
+ try {
+ sigBytes = Buffer.from(signature, 'base64');
+ } catch {
+ return fail('bad_signature', 'signature is not valid base64');
+ }
+ if (sigBytes.length !== 64) return fail('bad_signature', 'Ed25519 signature must be 64 bytes');
+ const payloadBytes = Buffer.from(canonicalize(unsigned), 'utf8');
+ let sigOk = false;
+ try {
+ sigOk = cryptoVerify(null, payloadBytes, pub, sigBytes);
+ } catch {
+ sigOk = false;
+ }
+ if (!sigOk) return fail('bad_signature', 'Ed25519 verification failed');
+
+ // Rule 5: freshness against the job deadline and the verifier clock.
+ const completedMs = Date.parse(response.completed_at);
+ if (!Number.isFinite(completedMs)) return fail('bad_shape', 'completed_at must parse as ISO 8601');
+ const now = opts.now instanceof Date ? opts.now.getTime() : Date.now();
+ if (completedMs > now + MAX_FUTURE_SKEW_MS) {
+ return fail('future_response', 'completed_at is more than 24h in the future');
+ }
+ const createdMs = Date.parse(job?.created_at);
+ const deadlineS = Number(job?.deadline);
+ if (Number.isFinite(createdMs) && Number.isFinite(deadlineS) && deadlineS > 0) {
+ if (completedMs > createdMs + deadlineS * 1000) {
+ return fail('stale_response', 'completed after the job deadline');
+ }
+ }
+
+ return {
+ ok: true,
+ verified: true,
+ verdict: 'verified',
+ nodePubkey: response.node_pubkey,
+ status: response.status,
+ };
+}
+
+// Rule 6 (optional): fetch output.url and check bytes + sha256. The caller
+// supplies the fetch implementation in tests; in production it must apply the
+// SSRF guards the spec requires (https-only, private-IP rejection, size cap).
+async function verifyOutput(response, fetchImpl) {
+ if (!response?.output?.url) return fail('bad_shape', 'no output to verify');
+ const doFetch = fetchImpl || globalThis.fetch;
+ if (typeof doFetch !== 'function') return fail('output_digest_mismatch', 'no fetch implementation available');
+ let bytes;
+ try {
+ const res = await doFetch(response.output.url);
+ if (!res.ok) return fail('output_digest_mismatch', `fetch failed: HTTP ${res.status}`);
+ const len = Number(res.headers?.get?.('content-length'));
+ if (Number.isFinite(len) && len > MAX_OUTPUT_BYTES) {
+ return fail('output_digest_mismatch', `output exceeds ${MAX_OUTPUT_BYTES} bytes`);
+ }
+ bytes = Buffer.from(await res.arrayBuffer());
+ } catch (err) {
+ return fail('output_digest_mismatch', `fetch failed: ${err?.message || err}`);
+ }
+ if (bytes.length > MAX_OUTPUT_BYTES) {
+ return fail('output_digest_mismatch', `output exceeds ${MAX_OUTPUT_BYTES} bytes`);
+ }
+ if (bytes.length !== response.output.bytes) {
+ return fail('output_digest_mismatch', `bytes ${bytes.length} != declared ${response.output.bytes}`);
+ }
+ const digest = sha256hex(bytes);
+ if (digest !== response.output.sha256) {
+ return fail('output_digest_mismatch', `sha256 ${digest} != declared ${response.output.sha256}`);
+ }
+ return { ok: true, verified: true, verdict: 'verified_with_output', bytes: bytes.length };
+}
+
+export {
+ canonicalize,
+ digestJob,
+ pubkeyB64FromSecret,
+ signAdvertisement,
+ signResponse,
+ verifyOutput,
+ verifyResponse,
+};
diff --git a/api/_lib/reconstruct-finalize.js b/api/_lib/reconstruct-finalize.js
index 8d78dfd56..7f87caf2d 100644
--- a/api/_lib/reconstruct-finalize.js
+++ b/api/_lib/reconstruct-finalize.js
@@ -149,6 +149,19 @@ async function materializeReconstructAvatar({
console.warn('[reconstruct] forge registration skipped:', err?.message);
}
+ // Roadmap Phase 1: a successful reconstruction is also minted as a draft
+ // on-chain agent identity — Metaplex Core on Solana (devnet is the default
+ // automated path; mainnet only via the explicit DRAFT_AGENT_MINT_NETWORK
+ // flag), ERC-8004 on EVM behind DRAFT_AGENT_MINT_EVM_ENABLED. Best-effort,
+ // same contract as the webhook + forge steps above: the avatar is already
+ // delivered, so a mint hiccup must never fail the job.
+ try {
+ const { mintDraftAgentIdentity } = await import('./draft-mint.js');
+ await mintDraftAgentIdentity({ userId, avatarId: avatar.id, jobId });
+ } catch (err) {
+ console.warn('[reconstruct] draft agent mint skipped:', err?.message);
+ }
+
return avatar;
}
diff --git a/api/_providers/livepeer.js b/api/_providers/livepeer.js
new file mode 100644
index 000000000..d86588e0a
--- /dev/null
+++ b/api/_providers/livepeer.js
@@ -0,0 +1,204 @@
+// Livepeer federation provider: routes one class of the platform's GPU work
+// (text-to-image reference synthesis) to the Livepeer decentralized compute
+// network instead of a first-party or vendor lane.
+//
+// Roadmap: "federate with existing decentralized compute networks where
+// appropriate" (README Phase 4). This is the adapter behind the flag; the
+// measurement harness is scripts/livepeer-federation-bench.mjs and the
+// measured recommendation lives in docs/ops/livepeer-federation.md.
+//
+// ── Gateways ────────────────────────────────────────────────────────────────
+// LIVEPEER_API_KEY set → https://livepeer.studio/api/generate (Studio AI
+// gateway, bearer auth, metered free tier)
+// otherwise → https://dream-gateway.livepeer.cloud (public
+// no-key gateway, rate-limited; measured DOWN at
+// the DNS edge on 2026-08-12, see the ops note)
+// LIVEPEER_GATEWAY_URL → full base-URL override for either (self-hosted
+// gateway, staging, or a regional edge)
+//
+// ── Job envelope ─────────────────────────────────────────────────────────────
+// Same envelope the platform's own image lanes accept and return:
+// in : (prompt, { aspectRatio, seed }) — identical to textToImage()
+// out: { imageUrl, model, lane, gateway } — imageUrl is a durable R2 https
+// URL, exactly as the NIM FLUX and Vertex lanes produce, so the
+// image-to-3D backends downstream cannot tell the difference.
+//
+// ── Verification ────────────────────────────────────────────────────────────
+// Same verification the platform applies to its own workers at this seam:
+// 1. the gateway must return an images[] entry that is not nsfw-flagged,
+// 2. the fetched bytes must carry a real PNG/JPEG magic-byte signature
+// (looksLikeImageBytes — a 200 with an HTML error page fails here),
+// 3. only verified bytes are persisted to R2 and returned.
+// The optional vision QA layer (forge-image-validate) sits above every lane
+// unchanged; this adapter never bypasses it.
+//
+// ── Flag ─────────────────────────────────────────────────────────────────────
+// The lane is dark unless LIVEPEER_FEDERATION_ENABLED is truthy
+// (1/true/yes/on). Off by default: the public gateway is unreliable and the
+// studio gateway is unkeyed, so the lane only goes live after the funded
+// comparison in the ops note clears it.
+
+import { env } from '../_lib/env.js';
+import { looksLikeImageBytes, persistImageBytes } from '../_lib/image-persist.js';
+
+const PUBLIC_GATEWAY = 'https://dream-gateway.livepeer.cloud';
+const STUDIO_GATEWAY = 'https://livepeer.studio/api/generate';
+
+// Default pipeline on the Livepeer AI gateway text-to-image surface. A fast
+// distilled SDXL variant, matching the lane's role (cheap reference views, not
+// hero renders). Override with LIVEPEER_T2I_MODEL.
+export const DEFAULT_T2I_MODEL = 'ByteDance/SDXL-Lightning';
+
+// Per-call ceiling. SDXL-Lightning renders in a few seconds on a warm
+// orchestrator; the public gateway can sit on a cold one, so this is generous
+// but bounded — a hung federated lane must hand off to the next platform lane,
+// never stall the text→3D pipeline.
+const T2I_TIMEOUT_MS = 90_000;
+
+// Verification floor: a payload under this size is an error page or an empty
+// artifact, not a rendered image.
+const MIN_IMAGE_BYTES = 1024;
+
+// Aspect-ratio → pixel dimensions. Mirrors the NIM FLUX lane's map (multiples
+// of 64, ~1MP), so a caller's aspect choice behaves identically across lanes.
+const DIMENSIONS = {
+ '1:1': [1024, 1024],
+ '16:9': [1344, 768],
+ '9:16': [768, 1344],
+ '4:3': [1024, 768],
+ '3:4': [768, 1024],
+ '3:2': [1216, 832],
+ '2:3': [832, 1216],
+};
+
+function truthy(v) {
+ return /^(1|true|yes|on)$/i.test(String(v ?? '').trim());
+}
+
+// The env flag is the only switch. readEnv-style (process.env) rather than the
+// env.js getter so the flag also works in the bench harness and tests, which
+// set process.env directly between cases.
+export function livepeerFederationEnabled() {
+ return truthy(process.env.LIVEPEER_FEDERATION_ENABLED);
+}
+
+// Resolve the active gateway. Returns { base, gateway, key } where gateway is
+// 'studio' | 'public' | 'override'. LIVEPEER_GATEWAY_URL wins outright; then
+// the keyed studio gateway; then the no-key public one.
+export function livepeerGatewayConfig() {
+ const override = process.env.LIVEPEER_GATEWAY_URL || env.LIVEPEER_GATEWAY_URL;
+ if (override) return { base: String(override).replace(/\/$/, ''), gateway: 'override', key: env.LIVEPEER_API_KEY || null };
+ const key = env.LIVEPEER_API_KEY;
+ if (key) return { base: STUDIO_GATEWAY, gateway: 'studio', key };
+ return { base: PUBLIC_GATEWAY, gateway: 'public', key: null };
+}
+
+// Resolve a possibly gateway-relative image URL against the gateway origin.
+function resolveImageUrl(raw, base) {
+ if (typeof raw !== 'string' || !raw) return null;
+ if (/^https:\/\//.test(raw)) return raw;
+ if (raw.startsWith('/')) return new URL(raw, base).href;
+ return null;
+}
+
+// One federated text-to-image job on the Livepeer network.
+//
+// Throws a coded error on any failure (the textToImage chain treats a throw as
+// "hand off to the next lane"): provider_unreachable for socket/TLS failures,
+// rate_limited for 429, verification_failed for a well-formed 200 whose
+// payload is not a usable image, and upstream_error otherwise.
+export async function livepeerTextToImage(prompt, { aspectRatio = '1:1', seed, model } = {}) {
+ const { base, gateway, key } = livepeerGatewayConfig();
+ const [width, height] = DIMENSIONS[aspectRatio] || DIMENSIONS['1:1'];
+ const modelId = model || process.env.LIVEPEER_T2I_MODEL || env.LIVEPEER_T2I_MODEL || DEFAULT_T2I_MODEL;
+
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
+ if (key) headers.authorization = `Bearer ${key}`;
+
+ // Livepeer AI gateway text-to-image pipeline (OpenAPI-documented shape):
+ // { prompt, model_id, width, height, seed, num_images_per_prompt,
+ // safety_check } → { images: [{ url, seed, nsfw }] }. safety_check stays
+ // on so the gateway's own screening flags the image rather than us shipping
+ // it into a reference pipeline.
+ const body = {
+ prompt: String(prompt || ''),
+ model_id: modelId,
+ width,
+ height,
+ num_images_per_prompt: 1,
+ safety_check: true,
+ ...(Number.isInteger(seed) && seed >= 0 ? { seed } : {}),
+ };
+
+ let res;
+ try {
+ res = await fetch(`${base}/text-to-image`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(T2I_TIMEOUT_MS),
+ });
+ } catch (err) {
+ throw Object.assign(new Error(`livepeer gateway unreachable: ${err?.message}`), {
+ code: 'provider_unreachable',
+ });
+ }
+
+ if (!res.ok) {
+ const detail = await res.text().catch(() => '');
+ throw Object.assign(
+ new Error(`livepeer text-to-image returned ${res.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`),
+ { providerStatus: res.status, ...(res.status === 429 ? { code: 'rate_limited' } : { code: 'upstream_error' }) },
+ );
+ }
+
+ const data = await res.json().catch(() => ({}));
+ const image = Array.isArray(data?.images) ? data.images[0] : null;
+
+ // Verification gate 1: the gateway's own safety screen.
+ if (image?.nsfw === true) {
+ throw Object.assign(new Error('livepeer returned an nsfw-flagged image'), { code: 'verification_failed' });
+ }
+ const imageUrl = resolveImageUrl(image?.url, base);
+ if (!imageUrl) {
+ throw Object.assign(new Error('livepeer finished but produced no image url'), { code: 'verification_failed' });
+ }
+
+ // Fetch the artifact. Studio serves these on its own host with the same
+ // bearer; the public gateway serves them unauthenticated.
+ let imgRes;
+ try {
+ imgRes = await fetch(imageUrl, {
+ headers: key ? { authorization: `Bearer ${key}` } : {},
+ signal: AbortSignal.timeout(T2I_TIMEOUT_MS),
+ });
+ } catch (err) {
+ throw Object.assign(new Error(`livepeer image fetch failed: ${err?.message}`), {
+ code: 'provider_unreachable',
+ });
+ }
+ if (!imgRes.ok) {
+ throw Object.assign(new Error(`livepeer image fetch returned ${imgRes.status}`), {
+ code: 'upstream_error',
+ providerStatus: imgRes.status,
+ });
+ }
+ const bytes = Buffer.from(await imgRes.arrayBuffer());
+
+ // Verification gate 2: magic-byte sniff + size floor, the same check the
+ // platform's own lanes get at the persistence seam.
+ if (bytes.length < MIN_IMAGE_BYTES || !looksLikeImageBytes(bytes)) {
+ throw Object.assign(
+ new Error(`livepeer image failed verification (${bytes.length} bytes, no image signature)`),
+ { code: 'verification_failed' },
+ );
+ }
+
+ return {
+ imageUrl: await persistImageBytes(bytes),
+ model: modelId,
+ lane: 'livepeer',
+ gateway,
+ seedUsed: Number.isInteger(image?.seed) ? image.seed : (Number.isInteger(seed) ? seed : null),
+ };
+}
diff --git a/api/agents/[id]/memory-seed-farcaster.js b/api/agents/[id]/memory-seed-farcaster.js
index 8f3768d39..1f78207e9 100644
--- a/api/agents/[id]/memory-seed-farcaster.js
+++ b/api/agents/[id]/memory-seed-farcaster.js
@@ -273,7 +273,7 @@ async function handleGrant(req, res, agentId, userId, body) {
if (!challenge) return error(res, 404, 'challenge_not_found', 'no such challenge for this agent');
if (challenge.consumed_at) return error(res, 409, 'challenge_used', 'this challenge has already been used');
if (new Date(challenge.expires_at) <= new Date()) {
- return error(res, 410, 'challenge_expired', 'this challenge expired — request a new one');
+ return error(res, 410, 'challenge_expired', 'this challenge expired, request a new one');
}
// Re-read the fid's verifications live rather than trusting the list handed
diff --git a/api/manifest-verify.js b/api/manifest-verify.js
index 382e4580f..62959977c 100644
--- a/api/manifest-verify.js
+++ b/api/manifest-verify.js
@@ -17,7 +17,7 @@
// stored copy is only used as a fallback when every gateway is unreachable, and
// the response says so in `source`.
//
-// Spec: specs/AGENT_MANIFEST.md (§ Signed envelope). Docs: docs/agent-manifests.md.
+// Spec: specs/AGENT_MANIFEST.md (§ Signed envelope). Docs: docs/agent-manifest.md.
import { sql } from './_lib/db.js';
import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';
diff --git a/contracts/test/GreenfieldVault.t.sol b/contracts/test/GreenfieldVault.t.sol
index fd68b133d..9b6caab46 100644
--- a/contracts/test/GreenfieldVault.t.sol
+++ b/contracts/test/GreenfieldVault.t.sol
@@ -465,8 +465,10 @@ contract GreenfieldVaultTest is Test {
vm.deal(address(badSeller), 10 ether);
uint256 saleId = _buy(buyer, OBJECT_ID);
- vm.prank(address(permissionHub));
- vault.greenfieldCall(STATUS_SUCCESS, 0x07, 2, 777, abi.encode(saleId));
+ // Settle through the mock hub, not a pranked greenfieldCall: the hub
+ // must record the vault as the policy owner or its deletePolicy
+ // rejects the revoke before the refund path under test is reached.
+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);
vm.expectRevert(GreenfieldVault.TransferFailed.selector);
badSeller.doRevoke{value: TOTAL_FEE + 1 ether}(vault, saleId);
diff --git a/data/changelog.json b/data/changelog.json
index 59df9c549..ba7bac254 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-12",
+ "title": "Your agent can now learn your Farcaster voice, and only after you prove the account is yours",
+ "summary": "Memory seeding already worked from GitHub and X; Farcaster now joins them, with consent built into the protocol itself. Farcaster has no login button we could use, so instead the account's own public record does the work: every Farcaster account publishes the wallets it controls, and you prove ownership by signing a one-time challenge with one of those wallets, Solana first. Nothing is read, let alone stored, before that signature checks out. The grant is read-only and narrow: your public profile and up to 100 recent casts, distilled into identity, facts, and your strongest posts, so the agent talks the way you talk. Changing your mind is one click: revoking the grant deletes every memory it produced, including anything an earlier grant left behind. The whole flow lives in the agent persona editor, and it works with no API key configured because the reader falls back to a public Farcaster hub.",
+ "tags": [
+ "feature",
+ "security"
+ ],
+ "link": "/docs/farcaster-memory-seeding"
+ },
{
"date": "2026-08-11",
"title": "The standalone avatar viewer is now embeddable in one click, and never leaves you on a blank screen",
diff --git a/data/pages.json b/data/pages.json
index 61a764a4c..590285483 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -2382,6 +2382,14 @@
"changefreq": "weekly",
"added": "2026-04-27"
},
+ {
+ "path": "/docs/farcaster-memory-seeding",
+ "title": "Docs · Farcaster memory seeding",
+ "description": "Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-08-11"
+ },
{
"path": "/docs/ibm-community",
"title": "Docs · IBM Community post catalog",
diff --git a/node-operator/.dockerignore b/node-operator/.dockerignore
new file mode 100644
index 000000000..6641648eb
--- /dev/null
+++ b/node-operator/.dockerignore
@@ -0,0 +1,4 @@
+node_modules
+.model-cache
+*.log
+.git
diff --git a/node-operator/.gitignore b/node-operator/.gitignore
new file mode 100644
index 000000000..a1ee057cf
--- /dev/null
+++ b/node-operator/.gitignore
@@ -0,0 +1,3 @@
+node_modules/
+.model-cache/
+*.log
diff --git a/node-operator/Dockerfile b/node-operator/Dockerfile
new file mode 100644
index 000000000..9ddbdb160
--- /dev/null
+++ b/node-operator/Dockerfile
@@ -0,0 +1,37 @@
+# three.ws inference node operator client (CPU image).
+#
+# Build: docker build -t three-ws/node-operator .
+# Run: docker run --rm -e NODE_SECRET_KEY=... -e NODE_WORKER_SECRET=... \
+# -e BASE_URL=https://three.ws three-ws/node-operator
+#
+# The model (distilgpt2 ONNX, ~80 MB quantized) downloads into
+# /app/.model-cache on first run; mount a volume to keep it warm:
+# -v node-model-cache:/app/.model-cache
+#
+# For NVIDIA GPUs use Dockerfile.gpu, which layers the CUDA build of
+# onnxruntime-node on top of the NVIDIA CUDA runtime and needs
+# `docker run --gpus all` (nvidia-container-toolkit on the host).
+
+FROM node:24-bookworm-slim
+
+ENV NODE_ENV=production \
+ MODEL_CACHE_DIR=/app/.model-cache
+
+WORKDIR /app
+
+# Install dependencies first so the layer caches across source changes.
+COPY package.json package-lock.json* ./
+RUN npm ci --omit=dev --no-audit --no-fund
+
+COPY src ./src
+COPY README.md ./
+
+# Run as a non-root operator; the cache dir must be writable by it.
+RUN useradd --system --uid 10001 --home /app node && \
+ mkdir -p /app/.model-cache && \
+ chown -R node:node /app
+USER node
+
+# Default command runs the daemon. `generate-key`, `register`, `verify`, and
+# `selftest` are the other subcommands (see README.md).
+CMD ["node", "src/cli.js", "run"]
diff --git a/node-operator/Dockerfile.gpu b/node-operator/Dockerfile.gpu
new file mode 100644
index 000000000..2ff0a43fc
--- /dev/null
+++ b/node-operator/Dockerfile.gpu
@@ -0,0 +1,47 @@
+# three.ws inference node operator client (NVIDIA GPU image).
+#
+# Same client as the CPU Dockerfile, layered on the NVIDIA CUDA runtime so the
+# ONNX graph executes on the GPU through onnxruntime-node's CUDA provider.
+#
+# Host requirement: NVIDIA driver + nvidia-container-toolkit. Verify the host
+# with `nvidia-smi`, then:
+#
+# docker build -f Dockerfile.gpu -t three-ws/node-operator:gpu .
+# docker run --rm --gpus all \
+# -e NODE_SECRET_KEY=... -e NODE_WORKER_SECRET=... \
+# -e BASE_URL=https://three.ws \
+# -v node-model-cache:/app/.model-cache \
+# three-ws/node-operator:gpu
+#
+# onnxruntime-node detects the CUDA libraries from this base image and picks
+# the CUDA execution provider automatically (engine.js lists cuda before cpu).
+
+FROM nvidia/cuda:12.4.1-cudnn-runtime-ubuntu22.04
+
+ENV NODE_ENV=production \
+ MODEL_CACHE_DIR=/app/.model-cache \
+ DEBIAN_FRONTEND=noninteractive \
+ ONNXRUNTIME_CUDA=1
+
+# Node.js 24 from the official binary tarball; the runtime base image has no
+# Node of its own.
+RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates xz-utils && \
+ curl -fsSL https://nodejs.org/dist/v24.14.0/node-v24.14.0-linux-x64.tar.xz -o /tmp/node.tar.xz && \
+ tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1 && \
+ rm /tmp/node.tar.xz && \
+ apt-get purge -y xz-utils && apt-get autoremove -y && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+
+COPY package.json package-lock.json* ./
+RUN npm ci --omit=dev --no-audit --no-fund
+
+COPY src ./src
+COPY README.md ./
+
+RUN useradd --system --uid 10001 --home /app node && \
+ mkdir -p /app/.model-cache && \
+ chown -R node:node /app
+USER node
+
+CMD ["node", "src/cli.js", "run"]
diff --git a/node-operator/README.md b/node-operator/README.md
new file mode 100644
index 000000000..21b84d253
--- /dev/null
+++ b/node-operator/README.md
@@ -0,0 +1,180 @@
+# Node operator client (three.ws open inference network)
+
+Run a three.ws inference node: register with the platform, claim inference
+jobs, execute them with a real open model, and return cryptographically
+signed results. This is the Phase 4 roadmap slice "node operator client
+(Docker + GPU drivers) with onchain registration" (`README.md` roadmap at the
+repo root).
+
+The client is self-contained: one Node.js process, a Solana Ed25519 keypair
+as its identity, and a small open model (distilgpt2, ONNX) as the built-in
+proof workload. It works on CPU out of the box and uses the GPU automatically
+when run from the GPU image.
+
+## How it works
+
+1. **Identity.** The node's Solana Ed25519 keypair is both its payout address
+ and its signing key. The public address is safe to share; the secret key
+ stays on the machine.
+2. **Registration.** On boot the client POSTs its address, capabilities, and
+ model list to the coordinator (`POST /api/inference/nodes/register`),
+ authenticated with the shared worker secret.
+3. **Job loop.** The client polls for jobs (`POST /api/inference/jobs/claim`),
+ runs each prompt through the local model, and submits the result
+ (`POST /api/inference/jobs/submit`).
+4. **Signed responses.** Every result is signed with the node key over a
+ canonical string that binds the job id, node address, model, and the
+ SHA-256 hashes of the input prompt and generated output. Anyone can verify
+ a result with only the node's public address: recompute the canonical
+ string and check the Ed25519 signature (`node src/cli.js verify <file>`).
+
+The wire contract is documented in [docs/inference-node-operator.md](../docs/inference-node-operator.md)
+and was derived from the platform's existing worker job format (bearer
+shared-secret auth and claim/execute/submit loops, as in
+`workers/agent-screen-pool`).
+
+## Install
+
+Requires Node.js 20+ (24 recommended) and network access to huggingface.co
+for the one-time model download (~80 MB).
+
+```bash
+cd node-operator
+npm ci
+```
+
+Or with Docker (no local Node needed):
+
+```bash
+docker build -t three-ws/node-operator .
+```
+
+### GPU
+
+The CPU image runs everywhere. For NVIDIA GPUs:
+
+1. Install the NVIDIA driver and
+ [nvidia-container-toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html)
+ on the host; verify with `nvidia-smi`.
+2. Build and run the GPU image:
+
+```bash
+docker build -f Dockerfile.gpu -t three-ws/node-operator:gpu .
+docker run --rm --gpus all \
+ -e NODE_SECRET_KEY=... -e NODE_WORKER_SECRET=... \
+ -e BASE_URL=https://three.ws \
+ -v node-model-cache:/app/.model-cache \
+ three-ws/node-operator:gpu
+```
+
+`src/engine.js` lists the CUDA execution provider before CPU, so the same
+code runs the graph on the GPU as soon as the CUDA runtime is present.
+
+## Config
+
+All configuration is environment variables:
+
+| Variable | Default | Meaning |
+| -------------------- | ---------------------- | ---------------------------------------------------- |
+| `NODE_SECRET_KEY` | none | **Required.** Node keypair: base58, base64, or a solana-keygen JSON byte array. |
+| `NODE_WORKER_SECRET` | none | Shared worker secret for the coordinator (16+ chars), same pattern as `SCREEN_WORKER_SECRET`. |
+| `BASE_URL` | `https://three.ws` | Coordinator base URL. |
+| `MODEL_CACHE_DIR` | `./.model-cache` | Where model files are downloaded and reused. |
+| `MODEL_ID` | `Xenova/distilgpt2` | Hugging Face model id for the proof workload. |
+| `MODEL_REVISION` | `main` | Model revision; pin a commit hash for reproducibility. |
+| `POLL_MS` | `3000` | Job poll cadence. |
+| `MAX_JOBS` | unlimited | Stop after N jobs (useful for smoke runs). |
+| `NODE_ENDPOINT_URL` | none | Optional public callback URL advertised at registration. |
+
+## Run
+
+Generate a key (once, keep the secret safe):
+
+```bash
+node src/cli.js generate-key
+```
+
+Register only (useful to confirm coordinator connectivity):
+
+```bash
+NODE_SECRET_KEY=<secret> NODE_WORKER_SECRET=<shared-secret> node src/cli.js register
+```
+
+Run the daemon (registers, then loops):
+
+```bash
+NODE_SECRET_KEY=<secret> NODE_WORKER_SECRET=<shared-secret> node src/cli.js run
+```
+
+With Docker:
+
+```bash
+docker run --rm \
+ -e NODE_SECRET_KEY=<secret> \
+ -e NODE_WORKER_SECRET=<shared-secret> \
+ -e BASE_URL=https://three.ws \
+ -v node-model-cache:/app/.model-cache \
+ three-ws/node-operator
+```
+
+## Verify
+
+### Local end-to-end proof
+
+`selftest` spins up a real HTTP coordinator in-process (same wire contract:
+bearer auth, register, claim, submit), runs one job through the real model,
+and has the coordinator cryptographically verify the signed result before
+accepting it. The receipt (job, result, signature) is printed as JSON.
+
+```bash
+node src/cli.js generate-key # once
+NODE_SECRET_KEY=<secret> node src/cli.js selftest
+```
+
+Expected tail of the output:
+
+```
+[node ...] completed {"type":"completed","jobId":"selftest-...","tokens":16,...}
+[node ...] verified: signature = true , output hash = true
+--- selftest receipt ---
+{ "job": { ... }, "result": { ... }, "signature": "..." }
+```
+
+### Verifying any signed result
+
+Save a receipt JSON (`{ job, result, signature }`) and verify it offline,
+anywhere, with no coordinator access:
+
+```bash
+node src/cli.js verify receipt.json
+```
+
+Prints `VALID` plus the node address, model, hashes, and signature prefix, or
+exits non-zero with `INVALID`.
+
+## Tests
+
+The repo's root test runner covers this client:
+
+```bash
+npm test -- tests/node-operator.test.js # from the repo root
+```
+
+Coverage: identity round-trips (base58/base64/JSON key encodings, sign and
+verify), the wire codec (canonical string, hash binding, tamper rejection),
+the coordinator client (auth header, register/claim/submit paths), the BPE
+tokenizer and greedy generation against the real distilgpt2 weights, and a
+full selftest loop against the in-process coordinator.
+
+## Limits and honest notes
+
+- The built-in model is a proof workload, not a production model: distilgpt2
+ proves registration, execution, and signed settlement end to end. Serving
+ larger models is a matter of pointing `MODEL_ID` at a bigger ONNX export
+ and running the GPU image; the wire contract does not change.
+- Generation is greedy (deterministic) by design: two honest nodes given the
+ same prompt produce the same output hash, which is what makes results
+ independently checkable.
+- On-chain settlement of verified results (pay-per-token with receipts) is
+ the adjacent roadmap slice; this client already exposes the address and the
+ signed receipts settlement needs.
diff --git a/node-operator/models/mnist-8.onnx b/node-operator/models/mnist-8.onnx
new file mode 100644
index 000000000..fc1a3f733
Binary files /dev/null and b/node-operator/models/mnist-8.onnx differ
diff --git a/node-operator/scripts/generate-benchmarks.mjs b/node-operator/scripts/generate-benchmarks.mjs
new file mode 100644
index 000000000..b9af21ffb
--- /dev/null
+++ b/node-operator/scripts/generate-benchmarks.mjs
@@ -0,0 +1,90 @@
+#!/usr/bin/env node
+/**
+ * Regenerate api/_lib/inference-benchmark.js by running the real vendored
+ * model (models/mnist-8.onnx, ONNX model zoo, MIT) over the deterministic
+ * benchmark vectors.
+ *
+ * The benchmark vectors exist so the platform can verify a node's proof job
+ * WITHOUT running inference server-side: every vector's expected output was
+ * produced by actually executing the model here, once, and recording the
+ * argmax. Run this again only when the model or the vector set changes:
+ *
+ * node node-operator/scripts/generate-benchmarks.mjs
+ *
+ * It prints the generated file path and a summary line per vector.
+ */
+
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { runMnist, BENCHMARK_SEEDS, benchmarkVector } from '../src/inference.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const outPath = join(here, '..', '..', 'api', '_lib', 'inference-benchmark.js');
+
+const vectors = [];
+for (const seed of BENCHMARK_SEEDS) {
+ const input = benchmarkVector(seed);
+ const result = await runMnist(input);
+ vectors.push({
+ seed,
+ input_b64: Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString('base64'),
+ expected_top1: result.top1,
+ logits_sha256: result.logitsSha256,
+ });
+ console.log(`seed=${seed} top1=${result.top1} logits_sha256=${result.logitsSha256.slice(0, 16)}...`);
+}
+
+const fileHash = createHash('sha256')
+ .update(JSON.stringify(vectors.map((v) => [v.seed, v.expected_top1, v.logits_sha256])))
+ .digest('hex');
+
+// Model file hash is pinned so the platform records the exact artifact the
+// vectors were produced with.
+const modelBytes = readFileSync(join(here, '..', 'models', 'mnist-8.onnx'));
+const modelSha256 = createHash('sha256').update(modelBytes).digest('hex');
+
+const source = `// GENERATED by node-operator/scripts/generate-benchmarks.mjs - do not hand-edit.
+// Every expected output below was produced by REALLY running the vendored
+// MNIST-8 model (ONNX model zoo, MIT) on the vector next to it. The platform
+// uses these as the proof-of-compute benchmark for the open inference
+// network: a node proves it can run real inference by reproducing the
+// recorded argmax on its assigned vector. Regenerate with:
+//
+// node node-operator/scripts/generate-benchmarks.mjs
+
+export const PROOF_MODEL = 'mnist-8';
+export const PROOF_MODEL_SHA256 = '${modelSha256}';
+export const PROOF_VECTOR_SET_SHA256 = '${fileHash}';
+
+// input_b64: base64 of 784 little-endian float32 values (28x28 grayscale,
+// MNIST layout, values in [0,1]). expected_top1: argmax of the 10 logits the
+// model emits for that input. logits_sha256: recorded for audit, not
+// enforced (execution providers may differ in the last ulp; argmax is the
+// stable contract).
+export const PROOF_VECTORS = [
+${vectors
+ .map(
+ (v) => ` {
+ seed: ${v.seed},
+ input_b64:
+ '${v.input_b64}',
+ expected_top1: ${v.expected_top1},
+ logits_sha256: '${v.logits_sha256}',
+ }`,
+ )
+ .join(',\n')}
+];
+
+export function decodeProofInput(b64) {
+ const bytes = Buffer.from(b64, 'base64');
+ return new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
+}
+`;
+
+writeFileSync(outPath, source);
+console.log(`wrote ${outPath}`);
+console.log(`model sha256=${modelSha256}`);
+console.log(`vector set sha256=${fileHash}`);
diff --git a/node-operator/src/cli.js b/node-operator/src/cli.js
new file mode 100644
index 000000000..946a51860
--- /dev/null
+++ b/node-operator/src/cli.js
@@ -0,0 +1,298 @@
+#!/usr/bin/env node
+// three.ws inference node operator client.
+//
+// node src/cli.js generate-key print a fresh node keypair
+// node src/cli.js register register this node, then exit
+// node src/cli.js run register, then run the job loop
+// node src/cli.js verify <file> verify a signed result record
+// node src/cli.js selftest [--keep-server] local end-to-end proof:
+// spins up a real HTTP
+// coordinator, registers,
+// serves one job, verifies the
+// signed result, exits
+//
+// Config is env-only (see README.md):
+// BASE_URL coordinator base URL (default https://three.ws)
+// NODE_SECRET_KEY node keypair (base58/base64/JSON; generate-key makes one)
+// NODE_WORKER_SECRET shared worker secret for the coordinator (16+ chars)
+// MODEL_CACHE_DIR model download cache (default ./.model-cache)
+// MODEL_ID Hugging Face model id (default Xenova/distilgpt2)
+// MODEL_REVISION revision/branch to pin (default main)
+// POLL_MS job poll cadence (default 3000)
+// MAX_JOBS stop after N jobs (default: run forever)
+// NODE_ENDPOINT_URL public callback URL advertised at registration (optional)
+
+import { createServer } from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { generateKeypair, loadKeypair, verifyPayload } from './identity.js';
+import { loadEngine } from './engine.js';
+import { CoordinatorClient, CLIENT_VERSION } from './client.js';
+import { NodeRunner } from './runner.js';
+import { buildResultRecord, canonicalResult, normalizeJob, verifyResult, sha256Hex } from './codec.js';
+
+const log = (...a) => console.log(`[node ${new Date().toISOString()}]`, ...a);
+
+function env(name, fallback) {
+ const v = process.env[name];
+ return v === undefined || v === '' ? fallback : v;
+}
+
+function requireKeypair() {
+ const secret = env('NODE_SECRET_KEY');
+ if (!secret) {
+ console.error('NODE_SECRET_KEY is not set. Run `node src/cli.js generate-key` first.');
+ process.exit(1);
+ }
+ try {
+ return loadKeypair(secret);
+ } catch (err) {
+ console.error(String(err.message || err));
+ process.exit(1);
+ }
+}
+
+function makeClient(keypair) {
+ return new CoordinatorClient({
+ baseUrl: env('BASE_URL', 'https://three.ws'),
+ secret: env('NODE_WORKER_SECRET'),
+ nodeAddress: keypair.address,
+ log,
+ });
+}
+
+function capabilities() {
+ return {
+ protocol: 'threews-inference-v1',
+ jobTypes: ['llm.completion'],
+ gpu: process.env.CUDA_VISIBLE_DEVICES !== undefined && process.env.CUDA_VISIBLE_DEVICES !== '',
+ clientVersion: CLIENT_VERSION,
+ platform: process.platform,
+ arch: process.arch,
+ };
+}
+
+async function cmdGenerateKey() {
+ const kp = generateKeypair();
+ console.log('Node address (public, safe to share):');
+ console.log(` ${kp.address}`);
+ console.log('Node secret key (keep private; set as NODE_SECRET_KEY):');
+ console.log(` ${kp.secretBase58}`);
+}
+
+async function cmdRegister() {
+ const keypair = requireKeypair();
+ const client = makeClient(keypair);
+ const modelId = env('MODEL_ID', 'Xenova/distilgpt2');
+ const res = await client.register({
+ capabilities: capabilities(),
+ models: [modelId],
+ endpoint: env('NODE_ENDPOINT_URL'),
+ });
+ log('registered as', keypair.address, JSON.stringify(res));
+}
+
+async function cmdRun() {
+ const keypair = requireKeypair();
+ const client = makeClient(keypair);
+ const cacheDir = env('MODEL_CACHE_DIR', new URL('../.model-cache', import.meta.url).pathname);
+
+ log('node address:', keypair.address);
+ await client.register({
+ capabilities: capabilities(),
+ models: [env('MODEL_ID', 'Xenova/distilgpt2')],
+ endpoint: env('NODE_ENDPOINT_URL'),
+ });
+ log('registered with coordinator');
+
+ const engine = await loadEngine({
+ cacheDir,
+ modelId: env('MODEL_ID', 'Xenova/distilgpt2'),
+ revision: env('MODEL_REVISION', 'main'),
+ log,
+ });
+
+ const runner = new NodeRunner({
+ client,
+ engine,
+ keypair,
+ pollMs: Number(env('POLL_MS', 3000)),
+ maxJobs: Number(env('MAX_JOBS', Infinity)),
+ onEvent: (e) => log(e.type, JSON.stringify(e)),
+ });
+ process.on('SIGINT', () => runner.stop());
+ process.on('SIGTERM', () => runner.stop());
+ const { completed } = await runner.run();
+ log(`stopped after ${completed} job(s)`);
+}
+
+async function cmdVerify(file) {
+ const doc = JSON.parse(await readFile(file, 'utf8'));
+ const { job, result, signature } = doc;
+ if (!job || !result || !signature) {
+ console.error('verify expects { job, result, signature } as produced by selftest or a coordinator receipt');
+ process.exit(1);
+ }
+ const normalized = normalizeJob(job);
+ const ok = verifyResult({ job: normalized, record: result, signature, verify: verifyPayload });
+ if (!ok) {
+ console.error('INVALID: signature, hashes, or job binding do not check out');
+ process.exit(1);
+ }
+ console.log('VALID');
+ console.log(` node: ${result.node}`);
+ console.log(` job: ${result.jobId}`);
+ console.log(` model: ${result.model}`);
+ console.log(` input: sha256 ${result.inputHash}`);
+ console.log(` output: sha256 ${result.outputHash}`);
+ console.log(` tokens: ${result.result.tokens}, latency: ${result.result.latencyMs} ms`);
+ console.log(` signature: ${signature.slice(0, 24)}...`);
+}
+
+// A real, self-contained coordinator for the local end-to-end proof. It
+// implements the same wire contract the platform coordinator uses (register,
+// claim, submit with bearer auth), holds one in-memory job, and cryptographi-
+// cally verifies the node's signed result before accepting it. This is the
+// proof workload harness, not a production coordinator: it keeps everything
+// in process memory and serves exactly the jobs it was constructed with.
+export function createLocalCoordinator({ secret, jobs }) {
+ const registered = new Map();
+ const queue = [...jobs];
+ const submitted = new Map();
+ const server = createServer((req, res) => {
+ const send = (code, obj) => {
+ res.writeHead(code, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(obj));
+ };
+ if (req.method !== 'POST') return send(405, { error: 'method_not_allowed' });
+ const bearer = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
+ if (!secret || bearer !== secret) return send(401, { error: 'unauthorized' });
+ let body = '';
+ req.on('data', (c) => (body += c));
+ req.on('end', () => {
+ let parsed = null;
+ try {
+ parsed = JSON.parse(body || '{}');
+ } catch {
+ return send(400, { error: 'invalid_json' });
+ }
+ if (req.url === '/api/inference/nodes/register') {
+ if (!parsed.node) return send(400, { error: 'node required' });
+ registered.set(parsed.node, parsed);
+ log('coordinator: registered node', parsed.node);
+ return send(200, { ok: true, node: parsed.node });
+ }
+ if (req.url === '/api/inference/jobs/claim') {
+ const job = queue.shift() || null;
+ return send(200, { job });
+ }
+ if (req.url === '/api/inference/jobs/submit') {
+ const { signature, ...record } = parsed;
+ const job = record?.jobId ? jobs.find((j) => (j.jobId || j.job_id) === record.jobId) : null;
+ const normalized = job ? normalizeJob(job) : null;
+ if (!normalized) return send(404, { error: 'unknown_job' });
+ const ok = verifyResult({ job: normalized, record, signature, verify: verifyPayload });
+ if (!ok) return send(422, { error: 'invalid_signature' });
+ submitted.set(record.jobId, { record, signature });
+ return send(200, { ok: true, verified: true, jobId: record.jobId });
+ }
+ return send(404, { error: 'not_found' });
+ });
+ });
+ return { server, registered, submitted };
+}
+
+async function cmdSelftest() {
+ const secret = env('NODE_WORKER_SECRET', 'selftest-worker-secret-0123456789');
+ process.env.NODE_WORKER_SECRET = secret;
+
+ const keypair = requireKeypair();
+ const jobs = [
+ {
+ jobId: `selftest-${Date.now()}`,
+ type: 'llm.completion',
+ model: env('MODEL_ID', 'Xenova/distilgpt2'),
+ input: { prompt: env('SELFTEST_PROMPT', 'The three.ws open inference network lets anyone') },
+ maxTokens: Number(env('SELFTEST_MAX_TOKENS', 16)),
+ issuedAt: new Date().toISOString(),
+ },
+ ];
+
+ const { server, registered, submitted } = createLocalCoordinator({ secret, jobs });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const port = server.address().port;
+ const baseUrl = `http://127.0.0.1:${port}`;
+ log('local coordinator listening on', baseUrl);
+
+ try {
+ const client = new CoordinatorClient({ baseUrl, secret, nodeAddress: keypair.address, log });
+ const modelId = env('MODEL_ID', 'Xenova/distilgpt2');
+ await client.register({ capabilities: capabilities(), models: [modelId] });
+ log('register: accepted =', registered.has(keypair.address));
+
+ const engine = await loadEngine({
+ cacheDir: env('MODEL_CACHE_DIR', new URL('../.model-cache', import.meta.url).pathname),
+ modelId,
+ revision: env('MODEL_REVISION', 'main'),
+ log,
+ });
+
+ const runner = new NodeRunner({ client, engine, keypair, pollMs: 250, maxJobs: 1, onEvent: (e) => log(e.type, JSON.stringify({ ...e, signature: e.signature ? `${e.signature.slice(0, 20)}...` : undefined })) });
+ const { completed } = await runner.run();
+
+ const entry = submitted.get(jobs[0].jobId);
+ if (completed !== 1 || !entry) {
+ console.error('selftest failed: job was not completed and verified');
+ process.exitCode = 1;
+ return;
+ }
+
+ // Independent verification pass: recompute the canonical payload and the
+ // output hash from the submitted record, then check the signature with
+ // only the node's public address.
+ const record = entry.record;
+ const recomputed = canonicalResult({
+ jobId: record.jobId,
+ node: record.node,
+ model: record.model,
+ inputHash: record.inputHash,
+ outputHash: record.outputHash,
+ latencyMs: record.result.latencyMs,
+ completedAt: record.completedAt,
+ });
+ const sigOk = verifyPayload(record.node, recomputed, entry.signature);
+ const hashOk = record.outputHash === sha256Hex(record.result.text);
+ log('verified: signature =', sigOk, ', output hash =', hashOk);
+ console.log('\n--- selftest receipt ---');
+ console.log(JSON.stringify({ job: jobs[0], result: record, signature: entry.signature }, null, 2));
+ if (!sigOk || !hashOk) process.exitCode = 1;
+ } finally {
+ server.close();
+ }
+}
+
+const cmd = process.argv[2];
+try {
+ switch (cmd) {
+ case 'generate-key':
+ await cmdGenerateKey();
+ break;
+ case 'register':
+ await cmdRegister();
+ break;
+ case 'run':
+ await cmdRun();
+ break;
+ case 'verify':
+ await cmdVerify(process.argv[3]);
+ break;
+ case 'selftest':
+ await cmdSelftest();
+ break;
+ default:
+ console.error('usage: node src/cli.js <generate-key|register|run|verify|selftest>');
+ process.exit(cmd ? 1 : 0);
+ }
+} catch (err) {
+ console.error('fatal:', err?.message || err);
+ process.exit(1);
+}
diff --git a/node-operator/src/client.js b/node-operator/src/client.js
new file mode 100644
index 000000000..a445bedb7
--- /dev/null
+++ b/node-operator/src/client.js
@@ -0,0 +1,81 @@
+// Coordinator client: registration, job claim, and signed-result submit.
+//
+// Endpoint defaults follow the platform's existing worker conventions:
+// POST /api/inference/nodes/register { node, capabilities, models, version }
+// POST /api/inference/jobs/claim { node } -> { job | null }
+// POST /api/inference/jobs/submit signed result record
+// Authorization: `Bearer $NODE_WORKER_SECRET` (the same shared-secret pattern
+// as SCREEN_WORKER_SECRET for workers/agent-screen-pool). The base URL and all
+// three paths are overridable so the client speaks to any deployment of the
+// coordinator, including the local dev server used by the end-to-end proof.
+
+import { normalizeJob } from './codec.js';
+
+export const CLIENT_VERSION = '1.0.0';
+
+export class CoordinatorClient {
+ constructor({ baseUrl, secret, nodeAddress, fetchImpl = fetch, log = () => {} }) {
+ if (!baseUrl) throw new Error('baseUrl is required');
+ this.baseUrl = String(baseUrl).replace(/\/+$/, '');
+ this.secret = secret || '';
+ this.nodeAddress = nodeAddress;
+ this.fetch = fetchImpl;
+ this.log = log;
+ }
+
+ headers() {
+ const h = { 'content-type': 'application/json', accept: 'application/json' };
+ if (this.secret) h.authorization = `Bearer ${this.secret}`;
+ return h;
+ }
+
+ async post(pathname, body) {
+ const url = `${this.baseUrl}${pathname}`;
+ const res = await this.fetch(url, {
+ method: 'POST',
+ headers: this.headers(),
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ let parsed = null;
+ try {
+ parsed = text ? JSON.parse(text) : null;
+ } catch {
+ parsed = null;
+ }
+ if (!res.ok) {
+ const detail = parsed?.error || parsed?.message || text.slice(0, 200);
+ throw new Error(`${pathname} failed: ${res.status} ${detail}`);
+ }
+ return parsed;
+ }
+
+ // Announce this node to the coordinator. Idempotent: re-registering the
+ // same address refreshes capabilities and last-seen.
+ async register({ capabilities, models, endpoint }) {
+ return this.post('/api/inference/nodes/register', {
+ node: this.nodeAddress,
+ capabilities,
+ models,
+ endpoint: endpoint || null,
+ version: CLIENT_VERSION,
+ registeredAt: new Date().toISOString(),
+ });
+ }
+
+ // Ask for the next job. Returns a normalized job, or null when the queue
+ // is empty (the coordinator answers { job: null }).
+ async claimJob() {
+ const body = await this.post('/api/inference/jobs/claim', { node: this.nodeAddress });
+ const raw = body?.job ?? body?.data?.job ?? null;
+ if (!raw) return null;
+ const job = normalizeJob(raw);
+ if (!job) this.log('coordinator returned a job this client cannot execute; skipping', raw?.jobId || raw?.job_id || '');
+ return job;
+ }
+
+ // Submit a signed result record (see src/codec.js for the shape).
+ async submitResult(record, signature) {
+ return this.post('/api/inference/jobs/submit', { ...record, signature });
+ }
+}
diff --git a/node-operator/src/engine.js b/node-operator/src/engine.js
index 8224a2816..bcbce2d75 100644
--- a/node-operator/src/engine.js
+++ b/node-operator/src/engine.js
@@ -27,8 +27,12 @@ import ort from 'onnxruntime-node';
export const DEFAULT_MODEL_ID = 'Xenova/distilgpt2';
export const DEFAULT_MODEL_REVISION = 'main';
+// decoder_model_merged_quantized.onnx is the KV-cache-fused, int8-quantized
+// export: no past_key_values inputs to manage, ~80 MB download. The greedy
+// loop feeds only input_ids + attention_mask. MODEL_ID/MODEL_REVISION must
+// resolve these exact paths.
const MODEL_FILES = [
- 'onnx/model_quantized.onnx',
+ 'onnx/decoder_model_merged_quantized.onnx',
'config.json',
'tokenizer.json',
'vocab.json',
@@ -179,6 +183,19 @@ export class BpeTokenizer {
// ── Inference session ───────────────────────────────────────────────────────
+// The npm `onnxruntime-node` build ships a CUDA provider stub that hard-fails
+// session creation when it is listed but the CUDA shared libraries are absent
+// (any CPU-only host). So CUDA is requested only when the runtime reports a
+// GPU build: the GPU image (Dockerfile.gpu) installs the CUDA-enabled
+// onnxruntime build and sets ONNXRUNTIME_CUDA=1; everywhere else the session
+// runs on the CPU provider.
+function executionProviders() {
+ const list = [];
+ if (process.env.ONNXRUNTIME_CUDA === '1') list.push('cuda');
+ list.push('cpu');
+ return list;
+}
+
export class InferenceEngine {
constructor({ session, tokenizer, maxLength }) {
this.session = session;
@@ -187,17 +204,15 @@ export class InferenceEngine {
}
static async load({ cacheDir, log = () => {} }) {
- const modelPath = path.join(cacheDir, 'onnx', 'model_quantized.onnx');
+ const modelPath = path.join(cacheDir, 'onnx', 'decoder_model_merged_quantized.onnx');
const config = JSON.parse(await readFile(path.join(cacheDir, 'config.json'), 'utf8'));
const tokenizer = await BpeTokenizer.load(cacheDir);
const session = await ort.InferenceSession.create(modelPath, {
- // CUDA is used automatically when the GPU image installs the CUDA
- // build of onnxruntime-node; the CPU build ignores this entry.
- executionProviders: ['cuda', 'cpu'],
+ executionProviders: executionProviders(),
graphOptimizationLevel: 'all',
logSeverityLevel: 3,
});
- log(`model loaded from ${modelPath} (providers: ${session.executionProviders ?? 'cpu'})`);
+ log(`model loaded from ${modelPath}`);
return new InferenceEngine({
session,
tokenizer,
@@ -215,10 +230,13 @@ export class InferenceEngine {
const budget = Math.min(Math.max(1, maxNewTokens), this.maxLength - ids.length);
let generated = 0;
- const inputName = this.session.inputNames[0];
+ const feedNames = new Set(this.session.inputNames);
for (let step = 0; step < budget; step++) {
const seq = BigInt64Array.from(ids.map(BigInt));
- const feeds = { [inputName]: new ort.Tensor('int64', seq, [1, ids.length]) };
+ const feeds = { input_ids: new ort.Tensor('int64', seq, [1, ids.length]) };
+ if (feedNames.has('attention_mask')) {
+ feeds.attention_mask = new ort.Tensor('int64', BigInt64Array.from({ length: ids.length }, () => 1n), [1, ids.length]);
+ }
const outputs = await this.session.run(feeds);
const logits = outputs[this.session.outputNames[0]];
const vocabSize = logits.dims[logits.dims.length - 1];
diff --git a/node-operator/src/inference.js b/node-operator/src/inference.js
new file mode 100644
index 000000000..8b98487d0
--- /dev/null
+++ b/node-operator/src/inference.js
@@ -0,0 +1,132 @@
+/**
+ * Real local inference for the node operator client.
+ *
+ * The built-in proof workload is MNIST-8 from the ONNX model zoo (MIT),
+ * vendored at models/mnist-8.onnx: a 26 KB convolutional digit classifier.
+ * It is deliberately small so a zero-context operator can prove their node
+ * end to end on any hardware in milliseconds, while still being a real model
+ * executing real tensor math through ONNX Runtime - not a stub.
+ *
+ * Runtime selection: the CUDA build of ONNX Runtime (package
+ * onnxruntime-node-gpu, installed in the GPU Docker image) is tried first;
+ * the plain CPU build (onnxruntime-node) is the fallback. Both export the
+ * same API. Force a provider with ORT_EXECUTION_PROVIDER=cpu|cuda.
+ */
+
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+export const MODEL_PATH = join(here, '..', 'models', 'mnist-8.onnx');
+export const MODEL_NAME = 'mnist-8';
+
+/**
+ * Deterministic benchmark-vector generator. The platform pins the vector set
+ * (api/_lib/inference-benchmark.js), so both sides must derive the exact same
+ * 784 floats from a seed: a SplitMix32 LCG over [0,1). Seeds are small
+ * integers embedded in the job payload.
+ */
+export function benchmarkVector(seed) {
+ let state = (seed >>> 0) || 1;
+ const out = new Float32Array(784);
+ for (let i = 0; i < out.length; i++) {
+ state = (state * 1664525 + 1013904223) >>> 0;
+ out[i] = state / 0x100000000;
+ }
+ return out;
+}
+
+/** The seeds the platform draws proof jobs from. Keep in step with the API. */
+export const BENCHMARK_SEEDS = [11, 42, 137, 1009, 65537];
+
+let ortPromise = null;
+
+async function loadOrt() {
+ if (!ortPromise) {
+ ortPromise = (async () => {
+ // The GPU image installs onnxruntime-node-gpu; the CPU image (and a
+ // plain npm ci) installs onnxruntime-node. Try GPU first.
+ const gpu = await import('onnxruntime-node-gpu').catch(() => null);
+ if (gpu) return gpu.default ?? gpu;
+ const cpu = await import('onnxruntime-node');
+ return cpu.default ?? cpu;
+ })();
+ }
+ return ortPromise;
+}
+
+let sessionPromise = null;
+
+async function loadSession() {
+ if (!sessionPromise) {
+ sessionPromise = (async () => {
+ const ort = await loadOrt();
+ const available = ort.getAvailableExecutionProviders?.() ?? ['cpu'];
+ const wanted = (process.env.ORT_EXECUTION_PROVIDER || '').trim();
+ const providers = wanted
+ ? [wanted]
+ : available.includes('cuda')
+ ? ['cuda', 'cpu']
+ : ['cpu'];
+ const modelBytes = readFileSync(MODEL_PATH);
+ const session = await ort.InferenceSession.create(modelBytes, {
+ executionProviders: providers,
+ });
+ return { ort, session, provider: providers[0] };
+ })();
+ }
+ return sessionPromise;
+}
+
+/** Which execution provider the session will use ('cuda' when the GPU build
+ * and hardware are present, else 'cpu'). Resolved lazily with the session. */
+export async function activeProvider() {
+ const { provider } = await loadSession();
+ return provider;
+}
+
+function sha256Hex(buf) {
+ return createHash('sha256').update(buf).digest('hex');
+}
+
+/**
+ * Run the proof model on a 784-float input. Returns the argmax class, a
+ * sha256 of the raw logit bytes (recorded for audit), and wall time.
+ */
+export async function runMnist(input) {
+ if (!(input instanceof Float32Array) || input.length !== 784) {
+ throw new Error(`mnist-8 input must be a Float32Array of 784 values, got ${input?.length}`);
+ }
+ const { ort, session } = await loadSession();
+ const tensor = new ort.Tensor('float32', input, [1, 1, 28, 28]);
+ const started = process.hrtime.bigint();
+ const outputs = await session.run({ [session.inputNames[0]]: tensor });
+ const durationMs = Number(process.hrtime.bigint() - started) / 1e6;
+ const logits = outputs[session.outputNames[0]].data;
+ let top1 = 0;
+ for (let i = 1; i < logits.length; i++) {
+ if (logits[i] > logits[top1]) top1 = i;
+ }
+ return {
+ top1,
+ logitsSha256: sha256Hex(Buffer.from(logits.buffer, logits.byteOffset, logits.byteLength)),
+ durationMs: Math.round(durationMs * 1000) / 1000,
+ };
+}
+
+/** Decode the platform's base64 float32 job input. */
+export function decodeJobInput(inputB64) {
+ const bytes = Buffer.from(inputB64, 'base64');
+ if (bytes.byteLength !== 784 * 4) {
+ throw new Error(`job input must decode to ${784 * 4} bytes, got ${bytes.byteLength}`);
+ }
+ return new Float32Array(bytes.buffer, bytes.byteOffset, 784);
+}
+
+/** Self-description for registration: what this build can actually run. */
+export async function capabilities() {
+ const provider = await activeProvider();
+ return [`${MODEL_NAME}@${provider}`];
+}
diff --git a/node-operator/src/runner.js b/node-operator/src/runner.js
new file mode 100644
index 000000000..7bcea08f4
--- /dev/null
+++ b/node-operator/src/runner.js
@@ -0,0 +1,109 @@
+// The job loop: claim -> execute -> sign -> submit, forever.
+//
+// Poll cadence mirrors workers/agent-screen-pool (POLL_MS, default 3s). A
+// failed job is submitted as a signed error record so the coordinator can
+// penalize the node instead of retrying forever; a failed HTTP round backs
+// off linearly and never kills the loop.
+
+import { buildResultRecord, canonicalResult } from './codec.js';
+import { signPayload } from './identity.js';
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+export class NodeRunner {
+ constructor({ client, engine, keypair, pollMs = 3000, maxJobs = Infinity, onEvent = () => {} }) {
+ this.client = client;
+ this.engine = engine;
+ this.keypair = keypair;
+ this.pollMs = pollMs;
+ this.maxJobs = maxJobs;
+ this.onEvent = onEvent;
+ this.completed = 0;
+ this.stopping = false;
+ }
+
+ stop() {
+ this.stopping = true;
+ }
+
+ async executeAndSubmit(job) {
+ const { engine, keypair, client } = this;
+ let record;
+ try {
+ const out = await engine.generate(job.input.prompt, job.maxTokens);
+ record = buildResultRecord({
+ job,
+ node: keypair.address,
+ model: job.model || 'Xenova/distilgpt2',
+ text: out.text,
+ tokens: out.tokens,
+ latencyMs: out.latencyMs,
+ completedAt: new Date().toISOString(),
+ });
+ } catch (err) {
+ // A failed execution still produces a signed record (empty output) so
+ // the failure is attributable to this node rather than ambiguous.
+ record = buildResultRecord({
+ job,
+ node: keypair.address,
+ model: job.model || 'Xenova/distilgpt2',
+ text: '',
+ tokens: 0,
+ latencyMs: 0,
+ completedAt: new Date().toISOString(),
+ });
+ record.error = String(err?.message || err).slice(0, 300);
+ }
+ const payload = canonicalResult({
+ jobId: record.jobId,
+ node: record.node,
+ model: record.model,
+ inputHash: record.inputHash,
+ outputHash: record.outputHash,
+ latencyMs: record.result.latencyMs,
+ completedAt: record.completedAt,
+ });
+ const signature = signPayload(keypair.secretKey, payload);
+ await client.submitResult(record, signature);
+ return { record, signature };
+ }
+
+ async run() {
+ const { client, pollMs, onEvent } = this;
+ let failures = 0;
+ while (!this.stopping && this.completed < this.maxJobs) {
+ let job = null;
+ try {
+ job = await client.claimJob();
+ failures = 0;
+ } catch (err) {
+ failures++;
+ const backoff = Math.min(pollMs * failures, 30_000);
+ onEvent({ type: 'claim-error', error: String(err?.message || err), backoffMs: backoff });
+ await sleep(backoff);
+ continue;
+ }
+ if (!job) {
+ await sleep(pollMs);
+ continue;
+ }
+ onEvent({ type: 'claimed', jobId: job.jobId });
+ try {
+ const { record, signature } = await this.executeAndSubmit(job);
+ this.completed++;
+ onEvent({
+ type: 'completed',
+ jobId: job.jobId,
+ tokens: record.result.tokens,
+ latencyMs: record.result.latencyMs,
+ error: record.error || null,
+ signature,
+ });
+ } catch (err) {
+ onEvent({ type: 'submit-error', jobId: job.jobId, error: String(err?.message || err) });
+ await sleep(pollMs);
+ }
+ }
+ return { completed: this.completed };
+ }
+}
diff --git a/package-lock.json b/package-lock.json
index f7a2d18c1..689dc0c42 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -250,15 +250,13 @@
"@pump-fun/agent-payments-sdk-legacy": "npm:@pump-fun/[email protected]",
"@types/bn.js": "^5.2.0",
"@types/express": "^5.0.6",
- "@types/jest": "^30.0.0",
"@types/node": "^22.0.0",
"eslint": "^10.4.1",
"eslint-config-prettier": "^9.1.0",
- "jest": "^30.3.0",
- "ts-jest": "^29.4.6",
"tsup": "^8.3.5",
"typescript": "^5.7.3",
"typescript-eslint": "^8.61.0",
+ "vitest": "^4.1.9",
"zod": "^3.25.76"
},
"engines": {
diff --git a/packages/node-operator/Dockerfile b/packages/node-operator/Dockerfile
new file mode 100644
index 000000000..d22bbed44
--- /dev/null
+++ b/packages/node-operator/Dockerfile
@@ -0,0 +1,36 @@
+# syntax=docker/dockerfile:1
+# three.ws node operator client.
+#
+# CPU builds work out of the box. GPU builds layer the NVIDIA Container
+# Toolkit on top: `docker run --gpus all ...` with the same image; the
+# @xenova/transformers ONNX runtime picks up CUDA execution providers when
+# the drivers are present, and stays on CPU otherwise. No separate image.
+FROM node:22-bookworm-slim
+
+WORKDIR /app
+
+# Install dependencies first (layer cached unless package.json changes).
+COPY package.json ./
+RUN npm install --omit=dev
+
+# Copy the client source.
+COPY src ./src
+
+# Weights cache + identity persist across restarts when the operator mounts
+# these as volumes. Identity is written 0600 by the client itself.
+ENV NODE_ENV=production \
+ PLATFORM_URL=https://three.ws \
+ MODEL=Xenova/all-MiniLM-L6-v2 \
+ CAPABILITY=text-embedding \
+ POLL_INTERVAL_MS=5000 \
+ MAX_CONCURRENCY=1 \
+ IDENTITY_PATH=/app/node-identity.json \
+ HF_HOME=/app/models
+
+VOLUME ["/app/models"]
+
+# Run as the node user the base image ships: the operator's keypair and
+# downloaded weights never need root.
+USER node
+
+CMD ["node", "src/index.js"]
diff --git a/packages/node-operator/package-lock.json b/packages/node-operator/package-lock.json
new file mode 100644
index 000000000..538b0096e
--- /dev/null
+++ b/packages/node-operator/package-lock.json
@@ -0,0 +1,2049 @@
+{
+ "name": "@three-ws/node-operator",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@three-ws/node-operator",
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "@xenova/transformers": "^2.17.2",
+ "tweetnacl": "^1.0.3"
+ },
+ "devDependencies": {
+ "vitest": "^4.1.9"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@huggingface/jinja": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.2.2.tgz",
+ "integrity": "sha512-/KPde26khDUIPkTGU82jdtTW9UAuvUTumCAbFs/7giR0SxsvZC4hru51PBvpijH6BVkHcROcvZM/lpy5h1jRRA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.143.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.143.0.tgz",
+ "integrity": "sha512-u6JZdLBTLotrNC9Vd6vPssINdzcCzleKAH6EJKImQb7GtYvX5keN2dxkoK44stCc4tffE6QQRtZTXVSzsLUlWA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ }
+ },
+ "node_modules/@protobufjs/aspromise": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
+ "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/base64": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
+ "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/codegen": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
+ "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/eventemitter": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
+ "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/fetch": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
+ "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@protobufjs/aspromise": "^1.1.1"
+ }
+ },
+ "node_modules/@protobufjs/float": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
+ "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/inquire": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.2.tgz",
+ "integrity": "sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/path": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
+ "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/pool": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
+ "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/utf8": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
+ "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz",
+ "integrity": "sha512-zrJtHDcaZJ1Fp7xf4hNl+7seH9Cn/N5TwLYkhgXREtBwAd/jaqW3uqeHxpDugJLVICWg4eW44kOQEGJ1r6jCGw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.3.tgz",
+ "integrity": "sha512-ieIiibVCp0tX7TLu2cafoNPv8wJyYi01ekXpbf8q2j7F4rGAhhXb/eQh7ge9DRBY78GwmRQtvjZDux7EDbA8kA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.3.tgz",
+ "integrity": "sha512-Zh9tCon19eDXJoihx0rqKhMUlMYqzwj3aPsSuHmI4RWZh62dWUL+DJN4C5YQya5TcQBJU/Fe8+rY0jhXTQITqA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.3.tgz",
+ "integrity": "sha512-nGbJWewA1wrXXZiQhjAT5rhibGfns5ZNkDVqxsO6zJ3f3YvpoDNNmGMSbbhLuXKjNScaBJVOAboztAWVespQMg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.3.tgz",
+ "integrity": "sha512-QNniJr5Kml0kDEB98jiDOJjXNroxIIi0IXIbdYzY26Xt1pVbeP62+KnoIZLwirOymX/0jDk/2gI/bNUv7A7OIw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.3.tgz",
+ "integrity": "sha512-TkqEAcmmvH3I/q4114NB4RVt6241Dao48pF45uLcFGrwAaIn0iITgTAKP/dLjbN0R4buJjGb91+UHSoFmpgIWw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.3.tgz",
+ "integrity": "sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.3.tgz",
+ "integrity": "sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.3.tgz",
+ "integrity": "sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.3.tgz",
+ "integrity": "sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.3.tgz",
+ "integrity": "sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.3.tgz",
+ "integrity": "sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.3.tgz",
+ "integrity": "sha512-hOtMwTqnME+/gJcH/PCZ0wn0zPUjiWOgkHpxbSJpfGKMezHltx1S7/k1SitzVa7Ww2cqrDDaFbZEhcJZO8o+Jw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.3.tgz",
+ "integrity": "sha512-ekcqMMkI2PlhYnfzQnB/cEdYUVVJViWvoUyLrbzgDoi3Snfc1mVBwdnc306ufA5ejy8JSPjT2RlW1nQSjW7efg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/long": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz",
+ "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.2.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
+ "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.3.0"
+ }
+ },
+ "node_modules/@vitest/expect": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",
+ "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",
+ "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.10",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
+ "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
+ "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.10",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
+ "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",
+ "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
+ "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@xenova/transformers": {
+ "version": "2.17.2",
+ "resolved": "https://registry.npmjs.org/@xenova/transformers/-/transformers-2.17.2.tgz",
+ "integrity": "sha512-lZmHqzrVIkSvZdKZEx7IYY51TK0WDrC8eR0c5IMnBsO8di8are1zzw8BlLhyO2TklZKLN5UffNGs1IJwT6oOqQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@huggingface/jinja": "^0.2.2",
+ "onnxruntime-web": "1.14.0",
+ "sharp": "^0.32.0"
+ },
+ "optionalDependencies": {
+ "onnxruntime-node": "1.14.0"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/b4a": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz",
+ "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "react-native-b4a": "*"
+ },
+ "peerDependenciesMeta": {
+ "react-native-b4a": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-events": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.1.tgz",
+ "integrity": "sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "bare-abort-controller": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-fs": {
+ "version": "4.8.0",
+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.0.tgz",
+ "integrity": "sha512-fM+MhCvdQhZ7NV6S95a07gPSqjIYKn6mFaXfx266wN3ajZGl/+1AzH+ubkXQ0fFZvOe2nk9VHkzdYkQE5zMV3Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.5.4",
+ "bare-path": "^3.0.0",
+ "bare-stream": "^2.6.4",
+ "bare-url": "^2.2.2",
+ "fast-fifo": "^1.3.2"
+ },
+ "engines": {
+ "bare": ">=1.28.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.1.tgz",
+ "integrity": "sha512-JprUlveX3QjApC1cTpsUOiscADftCGVWkzitbHsRqv84hzYwYHw2mbluddsq5TvI8mH/8Ov1f4BiMAdcB0oYnQ==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/bare-stream": {
+ "version": "2.13.3",
+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.3.tgz",
+ "integrity": "sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.8.1",
+ "streamx": "^2.25.0",
+ "teex": "^1.0.1"
+ },
+ "peerDependencies": {
+ "bare-abort-controller": "*",
+ "bare-buffer": "*",
+ "bare-events": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ },
+ "bare-buffer": {
+ "optional": true
+ },
+ "bare-events": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-url": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.2.tgz",
+ "integrity": "sha512-L13PCJzKG8RGvx8V1/DdMi12ERhC3tprr7/8a94BxpmnRsFqxh5XZNdhtMxu5HPkRshYOOWRGY8lDP7ZhpG9Cg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/chownr": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
+ "license": "ISC"
+ },
+ "node_modules/color": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
+ "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==",
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1",
+ "color-string": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=12.5.0"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "license": "MIT"
+ },
+ "node_modules/color-string": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
+ "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "^1.0.0",
+ "simple-swizzle": "^0.2.2"
+ }
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/decompress-response": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mimic-response": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/deep-extend": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "license": "MIT",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.1.tgz",
+ "integrity": "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/events-universal": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.7.0"
+ }
+ },
+ "node_modules/expand-template": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
+ "license": "(MIT OR WTFPL)",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fast-fifo": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
+ "license": "MIT"
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/flatbuffers": {
+ "version": "1.12.0",
+ "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz",
+ "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==",
+ "license": "SEE LICENSE IN LICENSE.txt"
+ },
+ "node_modules/fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
+ "license": "MIT"
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/github-from-package": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
+ "license": "MIT"
+ },
+ "node_modules/guid-typescript": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz",
+ "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==",
+ "license": "ISC"
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/ini": {
+ "version": "1.3.8",
+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
+ "license": "ISC"
+ },
+ "node_modules/is-arrayish": {
+ "version": "0.3.4",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz",
+ "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==",
+ "license": "MIT"
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/long": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz",
+ "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/mimic-response": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mkdirp-classic": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.18",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/napi-build-utils": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
+ "license": "MIT"
+ },
+ "node_modules/node-abi": {
+ "version": "3.94.0",
+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz",
+ "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==",
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.3.5"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/node-addon-api": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz",
+ "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==",
+ "license": "MIT"
+ },
+ "node_modules/obug": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
+ "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/onnx-proto": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz",
+ "integrity": "sha512-aldMOB3HRoo6q/phyB6QRQxSt895HNNw82BNyZ2CMh4bjeKv7g/c+VpAFtJuEMVfYLMbRx61hbuqnKceLeDcDA==",
+ "license": "MIT",
+ "dependencies": {
+ "protobufjs": "^6.8.8"
+ }
+ },
+ "node_modules/onnxruntime-common": {
+ "version": "1.14.0",
+ "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.14.0.tgz",
+ "integrity": "sha512-3LJpegM2iMNRX2wUmtYfeX/ytfOzNwAWKSq1HbRrKc9+uqG/FsEA0bbKZl1btQeZaXhC26l44NWpNUeXPII7Ew==",
+ "license": "MIT"
+ },
+ "node_modules/onnxruntime-node": {
+ "version": "1.14.0",
+ "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.14.0.tgz",
+ "integrity": "sha512-5ba7TWomIV/9b6NH/1x/8QEeowsb+jBEvFzU6z0T4mNsFwdPqXeFUM7uxC6QeSRkEbWu3qEB0VMjrvzN/0S9+w==",
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32",
+ "darwin",
+ "linux"
+ ],
+ "dependencies": {
+ "onnxruntime-common": "~1.14.0"
+ }
+ },
+ "node_modules/onnxruntime-web": {
+ "version": "1.14.0",
+ "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.14.0.tgz",
+ "integrity": "sha512-Kcqf43UMfW8mCydVGcX9OMXI2VN17c0p6XvR7IPSZzBf/6lteBzXHvcEVWDPmCKuGombl997HgLqj91F11DzXw==",
+ "license": "MIT",
+ "dependencies": {
+ "flatbuffers": "^1.12.0",
+ "guid-typescript": "^1.0.9",
+ "long": "^4.0.0",
+ "onnx-proto": "^4.0.4",
+ "onnxruntime-common": "~1.14.0",
+ "platform": "^1.3.6"
+ }
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/platform": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
+ "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==",
+ "license": "MIT"
+ },
+ "node_modules/postcss": {
+ "version": "8.5.26",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.17",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/prebuild-install": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
+ "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
+ "license": "MIT",
+ "dependencies": {
+ "detect-libc": "^2.0.0",
+ "expand-template": "^2.0.3",
+ "github-from-package": "0.0.0",
+ "minimist": "^1.2.3",
+ "mkdirp-classic": "^0.5.3",
+ "napi-build-utils": "^2.0.0",
+ "node-abi": "^3.3.0",
+ "pump": "^3.0.0",
+ "rc": "^1.2.7",
+ "simple-get": "^4.0.0",
+ "tar-fs": "^2.0.0",
+ "tunnel-agent": "^0.6.0"
+ },
+ "bin": {
+ "prebuild-install": "bin.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/prebuild-install/node_modules/tar-fs": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
+ "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
+ "license": "MIT",
+ "dependencies": {
+ "chownr": "^1.1.1",
+ "mkdirp-classic": "^0.5.2",
+ "pump": "^3.0.0",
+ "tar-stream": "^2.1.4"
+ }
+ },
+ "node_modules/prebuild-install/node_modules/tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/protobufjs": {
+ "version": "6.11.6",
+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.6.tgz",
+ "integrity": "sha512-k8BHqgPBOtrlougZZqF2uUk5Z7bN8f0wj+3e8M3hvtSv0NBAz4VBy5f6R5Nxq/l+i7mRFTgNZb2trxqTpHNY/A==",
+ "hasInstallScript": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@protobufjs/aspromise": "^1.1.2",
+ "@protobufjs/base64": "^1.1.2",
+ "@protobufjs/codegen": "^2.0.4",
+ "@protobufjs/eventemitter": "^1.1.0",
+ "@protobufjs/fetch": "^1.1.0",
+ "@protobufjs/float": "^1.0.2",
+ "@protobufjs/inquire": "^1.1.0",
+ "@protobufjs/path": "^1.1.2",
+ "@protobufjs/pool": "^1.1.0",
+ "@protobufjs/utf8": "^1.1.0",
+ "@types/long": "^4.0.1",
+ "@types/node": ">=13.7.0",
+ "long": "^4.0.0"
+ },
+ "bin": {
+ "pbjs": "bin/pbjs",
+ "pbts": "bin/pbts"
+ }
+ },
+ "node_modules/pump": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
+ "license": "MIT",
+ "dependencies": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
+ "node_modules/rc": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
+ "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
+ "dependencies": {
+ "deep-extend": "^0.6.0",
+ "ini": "~1.3.0",
+ "minimist": "^1.2.0",
+ "strip-json-comments": "~2.0.1"
+ },
+ "bin": {
+ "rc": "cli.js"
+ }
+ },
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.3.tgz",
+ "integrity": "sha512-rn9wpmxplLf7NLNyCk9FyWh3FM43DbY8jOzCdEPzH7uflhTftRbCEpqi6Ly2osgoU8OwObtmavMbWLaWy4LX7A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.143.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm64": "1.2.3",
+ "@rolldown/binding-darwin-arm64": "1.2.3",
+ "@rolldown/binding-darwin-x64": "1.2.3",
+ "@rolldown/binding-freebsd-x64": "1.2.3",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.3",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.3",
+ "@rolldown/binding-linux-arm64-musl": "1.2.3",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.3",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.3",
+ "@rolldown/binding-linux-x64-gnu": "1.2.3",
+ "@rolldown/binding-linux-x64-musl": "1.2.3",
+ "@rolldown/binding-openharmony-arm64": "1.2.3",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.3",
+ "@rolldown/binding-win32-x64-msvc": "1.2.3"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.32.6",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz",
+ "integrity": "sha512-KyLTWwgcR9Oe4d9HwCwNM2l7+J0dUQwn/yf7S0EnTtb0eVS4RxO0eUSvxPtzT4F3SY+C4K6fqdv/DO27sJ/v/w==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "color": "^4.2.3",
+ "detect-libc": "^2.0.2",
+ "node-addon-api": "^6.1.0",
+ "prebuild-install": "^7.1.1",
+ "semver": "^7.5.4",
+ "simple-get": "^4.0.1",
+ "tar-fs": "^3.0.4",
+ "tunnel-agent": "^0.6.0"
+ },
+ "engines": {
+ "node": ">=14.15.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/simple-concat": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/simple-get": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decompress-response": "^6.0.0",
+ "once": "^1.3.1",
+ "simple-concat": "^1.0.0"
+ }
+ },
+ "node_modules/simple-swizzle": {
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz",
+ "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-arrayish": "^0.3.1"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/streamx": {
+ "version": "2.28.0",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.0.tgz",
+ "integrity": "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==",
+ "license": "MIT",
+ "dependencies": {
+ "events-universal": "^1.0.0",
+ "fast-fifo": "^1.3.2",
+ "text-decoder": "^1.1.0"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "node_modules/strip-json-comments": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
+ "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/tar-fs": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz",
+ "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "pump": "^3.0.0",
+ "tar-stream": "^3.1.5"
+ },
+ "optionalDependencies": {
+ "bare-fs": "^4.0.1",
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/tar-stream": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.0.tgz",
+ "integrity": "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==",
+ "license": "MIT",
+ "dependencies": {
+ "b4a": "^1.6.4",
+ "bare-fs": "^4.5.5",
+ "fast-fifo": "^1.2.0",
+ "streamx": "^2.15.0"
+ }
+ },
+ "node_modules/teex": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
+ "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
+ "license": "MIT",
+ "dependencies": {
+ "streamx": "^2.12.5"
+ }
+ },
+ "node_modules/text-decoder": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.6.4"
+ }
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz",
+ "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
+ "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tunnel-agent": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/tweetnacl": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
+ "license": "Unlicense"
+ },
+ "node_modules/undici-types": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
+ "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
+ "license": "MIT"
+ },
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "8.2.1",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.1.tgz",
+ "integrity": "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.5",
+ "postcss": "^8.5.25",
+ "rolldown": "~1.2.1",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.4.0",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",
+ "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.10",
+ "@vitest/mocker": "4.1.10",
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/runner": "4.1.10",
+ "@vitest/snapshot": "4.1.10",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.10",
+ "@vitest/browser-preview": "4.1.10",
+ "@vitest/browser-webdriverio": "4.1.10",
+ "@vitest/coverage-istanbul": "4.1.10",
+ "@vitest/coverage-v8": "4.1.10",
+ "@vitest/ui": "4.1.10",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ }
+ }
+}
diff --git a/packages/node-operator/src/config.js b/packages/node-operator/src/config.js
new file mode 100644
index 000000000..5a7e4ced1
--- /dev/null
+++ b/packages/node-operator/src/config.js
@@ -0,0 +1,75 @@
+/**
+ * Client config: env-first with a config file fallback, validated eagerly so
+ * a misconfigured node fails at boot with a readable message instead of
+ * mid-job.
+ *
+ * Precedence: environment variable > config file (operator.config.json) >
+ * default. Every field maps 1:1 to the README's operator guide.
+ */
+
+import { readFileSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+
+const DEFAULTS = {
+ platformUrl: 'https://three.ws',
+ model: 'Xenova/all-MiniLM-L6-v2',
+ capability: 'text-embedding',
+ pollIntervalMs: 5000,
+ maxConcurrency: 1,
+ identityPath: 'node-identity.json',
+ jobTimeoutMs: 120_000,
+};
+
+/**
+ * Load and validate config.
+ *
+ * @param {object} [opts]
+ * @param {NodeJS.ProcessEnv} [opts.env] environment map (defaults to process.env)
+ * @param {string} [opts.cwd] directory to look for operator.config.json / the identity file
+ * @returns the validated config object
+ */
+export function loadConfig({ env = process.env, cwd = process.cwd() } = {}) {
+ let file = {};
+ const configPath = join(cwd, 'operator.config.json');
+ if (existsSync(configPath)) {
+ try {
+ file = JSON.parse(readFileSync(configPath, 'utf8'));
+ } catch (err) {
+ throw new Error(`operator.config.json is not valid JSON: ${err.message}`);
+ }
+ }
+
+ const pick = (envKey, fileKey, fallback) => {
+ if (env[envKey] !== undefined && env[envKey] !== '') return env[envKey];
+ if (file[fileKey] !== undefined) return file[fileKey];
+ return fallback;
+ };
+
+ const cfg = {
+ platformUrl: pick('PLATFORM_URL', 'platformUrl', DEFAULTS.platformUrl).replace(/\/+$/, ''),
+ model: pick('MODEL', 'model', DEFAULTS.model),
+ capability: pick('CAPABILITY', 'capability', DEFAULTS.capability),
+ pollIntervalMs: int(pick('POLL_INTERVAL_MS', 'pollIntervalMs', DEFAULTS.pollIntervalMs), 'POLL_INTERVAL_MS', 1000),
+ maxConcurrency: int(pick('MAX_CONCURRENCY', 'maxConcurrency', DEFAULTS.maxConcurrency), 'MAX_CONCURRENCY', 1),
+ jobTimeoutMs: int(pick('JOB_TIMEOUT_MS', 'jobTimeoutMs', DEFAULTS.jobTimeoutMs), 'JOB_TIMEOUT_MS', 10_000),
+ identityPath: pick('IDENTITY_PATH', 'identityPath', DEFAULTS.identityPath),
+ secretKey: env.OPERATOR_SECRET_KEY || file.secretKey || null,
+ label: pick('NODE_LABEL', 'label', null),
+ };
+
+ if (!/^https?:\/\//.test(cfg.platformUrl)) {
+ throw new Error(`platformUrl must be an absolute http(s) URL, got: ${cfg.platformUrl}`);
+ }
+ if (!Number.isInteger(cfg.maxConcurrency) || cfg.maxConcurrency < 1) {
+ throw new Error('maxConcurrency must be a positive integer');
+ }
+ return cfg;
+}
+
+function int(value, name, min) {
+ const n = Number(value);
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < min) {
+ throw new Error(`${name} must be an integer >= ${min}, got: ${value}`);
+ }
+ return n;
+}
diff --git a/packages/node-operator/src/index.js b/packages/node-operator/src/index.js
new file mode 100644
index 000000000..9d704c956
--- /dev/null
+++ b/packages/node-operator/src/index.js
@@ -0,0 +1,82 @@
+#!/usr/bin/env node
+/**
+ * three.ws node operator client: entry point.
+ *
+ * node src/index.js register (if needed) and run the job loop
+ * node src/index.js --register-only register with the platform and exit
+ * node src/index.js --self-test run the proof workload locally and exit
+ * node src/index.js --pubkey print this node's public key and exit
+ *
+ * All configuration is env-first (see README.md); nothing here prompts.
+ */
+
+import { join } from 'node:path';
+import { loadConfig } from './config.js';
+import { resolveIdentity, defaultIdentityPath } from './identity.js';
+import { createPlatformClient } from './platform.js';
+import { createJobLoop } from './loop.js';
+import { selfTest } from './inference.js';
+
+const args = new Set(process.argv.slice(2));
+const MODELS_DIR = join(process.cwd(), 'models');
+
+async function main() {
+ const cfg = loadConfig();
+ const identityPath = cfg.identityPath.startsWith('/')
+ ? cfg.identityPath
+ : join(process.cwd(), cfg.identityPath);
+ const { identity, source } = resolveIdentity({
+ envSecret: cfg.secretKey,
+ identityPath,
+ });
+
+ if (args.has('--pubkey')) {
+ console.log(identity.publicKey);
+ return;
+ }
+
+ console.log(`[node] identity ${identity.publicKey} (${source === 'generated' ? `generated, saved to ${identityPath}` : `from ${source}`})`);
+ console.log(`[node] platform ${cfg.platformUrl} · capability ${cfg.capability} · model ${cfg.model}`);
+
+ if (args.has('--self-test')) {
+ console.log('[node] running proof workload self-test (first run downloads the model)...');
+ const result = await selfTest({ cacheDir: MODELS_DIR });
+ console.log(`[node] self-test ${result.ok ? 'OK' : 'FAILED'}: ${result.model}, ${result.dimensions} dims, ${result.elapsedMs}ms`);
+ process.exit(result.ok ? 0 : 1);
+ }
+
+ const client = createPlatformClient({ platformUrl: cfg.platformUrl, identity });
+ const capabilities = [{ capability: cfg.capability, model: cfg.model }];
+
+ console.log('[node] registering with platform...');
+ const reg = await client.register({ label: cfg.label, capabilities });
+ console.log(`[node] registered as node ${reg?.node?.id ?? '(id assigned by platform)'}`);
+
+ if (args.has('--register-only')) return;
+
+ const loop = createJobLoop({
+ client,
+ identity,
+ capability: cfg.capability,
+ pollIntervalMs: cfg.pollIntervalMs,
+ maxConcurrency: cfg.maxConcurrency,
+ jobTimeoutMs: cfg.jobTimeoutMs,
+ cacheDir: MODELS_DIR,
+ });
+
+ const shutdown = (signal) => {
+ console.log(`[node] ${signal} received; finishing in-flight jobs and shutting down`);
+ loop.stop();
+ };
+ process.on('SIGINT', () => shutdown('SIGINT'));
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+
+ console.log(`[node] polling every ${cfg.pollIntervalMs / 1000}s (max ${cfg.maxConcurrency} concurrent). Ctrl+C to stop.`);
+ await loop.run();
+ console.log(`[node] stopped. completed=${loop.stats.completed} failed=${loop.stats.failed}`);
+}
+
+main().catch((err) => {
+ console.error(`[node] fatal: ${err.message}`);
+ process.exit(1);
+});
diff --git a/packages/node-operator/src/inference.js b/packages/node-operator/src/inference.js
new file mode 100644
index 000000000..fb2dcc94e
--- /dev/null
+++ b/packages/node-operator/src/inference.js
@@ -0,0 +1,83 @@
+/**
+ * The built-in proof workload: real, local text-embedding inference with the
+ * open Xenova/all-MiniLM-L6-v2 model (Apache-2.0, ~90MB ONNX, quantized for
+ * CPU). No API keys, no network calls at inference time: the model downloads
+ * from HuggingFace once and is cached in ./models thereafter.
+ *
+ * Why embeddings and not a generative model as the proof workload: it is the
+ * smallest model that still exercises the full GPU/CPU tensor path a real
+ * phase 4 inference job would (tokenize -> transformer forward -> mean pool
+ * -> normalize), runs in seconds on a laptop CPU, and produces a
+ * deterministic, verifiable numeric output. Nodes advertise this capability
+ * on registration as proof they can execute the runtime; richer models plug
+ * into the same runJob() interface.
+ */
+
+import { createRequire } from 'node:module';
+
+const require = createRequire(import.meta.url);
+
+let _pipeline = null;
+let _pipelineModel = null;
+
+/**
+ * Load (and cache) the feature-extraction pipeline for a model id. The first
+ * call downloads the model weights; later calls return the warm pipeline.
+ * `cacheDir` pins where weights land so Docker volumes can persist them.
+ */
+export async function loadModel(model, { cacheDir } = {}) {
+ if (_pipeline && _pipelineModel === model) return _pipeline;
+ const { pipeline, env } = await import('@xenova/transformers');
+ if (cacheDir) env.cacheDir = cacheDir;
+ // The model hub is the only remote allowed, and only on first download.
+ env.allowLocalModels = true;
+ _pipeline = await pipeline('feature-extraction', model, { quantized: true });
+ _pipelineModel = model;
+ return _pipeline;
+}
+
+/**
+ * Execute one inference job.
+ *
+ * @param {object} job the claimed job: { id, model, input }
+ * @param {object} [opts] { cacheDir, now } - now is injectable for tests
+ * @returns {Promise<{output: object, startedAt: number, finishedAt: number}>}
+ */
+export async function runJob(job, { cacheDir, now = () => Date.now() } = {}) {
+ const prompt = typeof job.input === 'string' ? job.input : job.input?.text;
+ if (typeof prompt !== 'string' || prompt.length === 0) {
+ throw new Error(`job ${job.id}: input.text must be a non-empty string`);
+ }
+ const model = job.model || 'Xenova/all-MiniLM-L6-v2';
+ const startedAt = now();
+ const extractor = await loadModel(model, { cacheDir });
+ const tensor = await extractor(prompt, { pooling: 'mean', normalize: true });
+ const finishedAt = now();
+ return {
+ output: {
+ kind: 'text-embedding',
+ model,
+ dimensions: tensor.dims[tensor.dims.length - 1],
+ embedding: Array.from(tensor.data, (v) => Number(v.toFixed(8))),
+ },
+ startedAt,
+ finishedAt,
+ };
+}
+
+/**
+ * A self-check the operator can run before registering: executes the proof
+ * workload on a fixed input and returns the output summary. `node
+ * src/index.js --self-test` calls this so a fresh operator can prove their
+ * host runs the runtime before they ever poll for jobs.
+ */
+export async function selfTest({ cacheDir } = {}) {
+ const probe = { id: 'self-test', model: undefined, input: { text: 'three.ws node operator self-test' } };
+ const { output, startedAt, finishedAt } = await runJob(probe, { cacheDir });
+ return {
+ ok: Array.isArray(output.embedding) && output.embedding.length === output.dimensions,
+ model: output.model,
+ dimensions: output.dimensions,
+ elapsedMs: finishedAt - startedAt,
+ };
+}
diff --git a/packages/node-operator/src/loop.js b/packages/node-operator/src/loop.js
new file mode 100644
index 000000000..21ef8598e
--- /dev/null
+++ b/packages/node-operator/src/loop.js
@@ -0,0 +1,127 @@
+/**
+ * The job loop: register once, then poll -> execute -> sign -> submit
+ * forever, with bounded concurrency and graceful shutdown.
+ *
+ * Failure policy (matching the platform's agent-screen worker): a job that
+ * throws is reported as failed with its error string (the platform requeues
+ * or refunds it), and the loop continues. The loop itself only exits on
+ * SIGINT/SIGTERM or a fatal registration error; transient poll failures back
+ * off exponentially and retry, since a node that gives up on the first
+ * network blip earns nothing.
+ */
+
+import { runJob } from './inference.js';
+import { signResult } from './signing.js';
+
+export function createJobLoop({
+ client,
+ identity,
+ capability,
+ pollIntervalMs = 5000,
+ maxConcurrency = 1,
+ cacheDir,
+ jobTimeoutMs = 120_000,
+ log = console,
+ runJobImpl = runJob,
+}) {
+ let running = false;
+ let inFlight = 0;
+ let wakeTimer = null;
+ let resolveWake = null;
+ const jobsDone = { completed: 0, failed: 0 };
+
+ function sleep(ms) {
+ return new Promise((resolve) => {
+ wakeTimer = setTimeout(() => {
+ wakeTimer = null;
+ resolveWake = null;
+ resolve();
+ }, ms);
+ resolveWake = resolve;
+ });
+ }
+
+ /** Interrupt the current sleep so shutdown is immediate. */
+ function wake() {
+ if (wakeTimer) clearTimeout(wakeTimer);
+ wakeTimer = null;
+ resolveWake?.();
+ }
+
+ async function executeJob(job) {
+ const startedAt = Date.now();
+ try {
+ const { output, startedAt: t0, finishedAt: t1 } = await withTimeout(
+ runJobImpl(job, { cacheDir }),
+ jobTimeoutMs,
+ `job ${job.id} exceeded ${jobTimeoutMs}ms`,
+ );
+ const receipt = await signResult(identity, {
+ jobId: job.id,
+ model: output.model || job.model,
+ prompt: typeof job.input === 'string' ? job.input : job.input?.text ?? '',
+ output,
+ startedAt: t0,
+ finishedAt: t1,
+ });
+ const res = await client.submitResult(job.id, { output, startedAt: t0, finishedAt: t1, receipt });
+ jobsDone.completed++;
+ log.log(`[node] job ${job.id} complete (${t1 - t0}ms inference, verified=${res?.verified ?? 'unknown'})`);
+ } catch (err) {
+ jobsDone.failed++;
+ log.warn(`[node] job ${job.id} failed: ${err.message}`);
+ try {
+ await client.reportFailure(job.id, { error: err.message, startedAt, finishedAt: Date.now() });
+ } catch (reportErr) {
+ log.warn(`[node] could not report failure for ${job.id}: ${reportErr.message}`);
+ }
+ } finally {
+ inFlight--;
+ }
+ }
+
+ return {
+ stats: jobsDone,
+
+ /** Run until stop() is called. Resolves on clean shutdown. */
+ async run() {
+ running = true;
+ let backoff = pollIntervalMs;
+ while (running) {
+ let job = null;
+ try {
+ job = await client.pollJob({ capability });
+ backoff = pollIntervalMs; // a healthy poll resets the backoff
+ } catch (err) {
+ log.warn(`[node] poll failed (${err.message}); retrying in ${Math.round(backoff / 1000)}s`);
+ await sleep(backoff);
+ backoff = Math.min(backoff * 2, 60_000);
+ continue;
+ }
+ if (job && inFlight < maxConcurrency) {
+ inFlight++;
+ // Deliberately not awaited: maxConcurrency > 1 overlaps jobs,
+ // and a slow job must not stall the poll loop.
+ void executeJob(job);
+ } else if (!job) {
+ await sleep(pollIntervalMs);
+ }
+ }
+ // Drain in-flight jobs so a shutdown never abandons half-computed work.
+ while (inFlight > 0) await sleep(250);
+ },
+
+ stop() {
+ running = false;
+ wake();
+ },
+ };
+}
+
+function withTimeout(promise, ms, message) {
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(message)), ms);
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
diff --git a/packages/node-operator/src/platform.js b/packages/node-operator/src/platform.js
new file mode 100644
index 000000000..79cdb6ef0
--- /dev/null
+++ b/packages/node-operator/src/platform.js
@@ -0,0 +1,102 @@
+/**
+ * Platform wire client: registration, job poll, result submit.
+ *
+ * The wire contract (derived in specs/inference-nodes.md from the platform's
+ * existing worker job formats) is:
+ *
+ * POST {platformUrl}/api/nodes/register
+ * body: { publicKey, label?, capabilities: [{capability, model}],
+ * registeredAt, signature }
+ * where signature = ed25519 over `threews-node-register:{publicKey}:{registeredAt}`
+ * -> 200 { ok: true, node: { id, publicKey } }
+ *
+ * GET {platformUrl}/api/nodes/jobs?node=<publicKey>&capability=<cap>&sig=<sig>&ts=<ms>
+ * where sig = ed25519 over `threews-node-poll:{publicKey}:{ts}`
+ * -> 200 { job: null } (queue empty, keep polling)
+ * -> 200 { job: { id, capability, model, input, deadlineAt } }
+ *
+ * POST {platformUrl}/api/nodes/jobs/{jobId}/result
+ * body: { node: publicKey, output, startedAt, finishedAt, receipt }
+ * -> 200 { ok: true, verified: true }
+ *
+ * Every authenticated call signs a short, domain-separated string so a
+ * signature harvested from one call can never be replayed against another.
+ */
+
+export function createPlatformClient({ platformUrl, identity, fetchImpl = globalThis.fetch }) {
+ if (!platformUrl) throw new Error('platformUrl is required');
+ if (!identity) throw new Error('identity is required');
+
+ async function call(method, path, body) {
+ const res = await fetchImpl(`${platformUrl}${path}`, {
+ method,
+ headers: { 'content-type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(30_000),
+ });
+ const text = await res.text();
+ let data = null;
+ try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; }
+ if (!res.ok) {
+ const msg = data?.error_description || data?.error || `HTTP ${res.status}`;
+ const err = new Error(`${method} ${path} failed: ${msg}`);
+ err.status = res.status;
+ err.payload = data;
+ throw err;
+ }
+ return data;
+ }
+
+ return {
+ /** Register (or re-register: the call is idempotent on publicKey). */
+ async register({ label, capabilities }) {
+ const registeredAt = Date.now();
+ const signature = identity.signText(`threews-node-register:${identity.publicKey}:${registeredAt}`);
+ return call('POST', '/api/nodes/register', {
+ publicKey: identity.publicKey,
+ label: label || null,
+ capabilities,
+ registeredAt,
+ signature,
+ });
+ },
+
+ /**
+ * Poll for the next job this node can execute. Returns the job object
+ * or null when the queue is empty.
+ */
+ async pollJob({ capability }) {
+ const ts = Date.now();
+ const sig = identity.signText(`threews-node-poll:${identity.publicKey}:${ts}`);
+ const q = new URLSearchParams({ node: identity.publicKey, capability, ts: String(ts), sig });
+ const data = await call('GET', `/api/nodes/jobs?${q}`);
+ return data?.job ?? null;
+ },
+
+ /** Submit a finished result plus its signed receipt. */
+ async submitResult(jobId, { output, startedAt, finishedAt, receipt }) {
+ return call('POST', `/api/nodes/jobs/${encodeURIComponent(jobId)}/result`, {
+ node: identity.publicKey,
+ output,
+ startedAt,
+ finishedAt,
+ receipt,
+ });
+ },
+
+ /** Report a job as failed so the platform can requeue or refund it. */
+ async reportFailure(jobId, { error, startedAt, finishedAt }) {
+ const ts = Date.now();
+ const signature = identity.signText(`threews-node-fail:${identity.publicKey}:${jobId}:${ts}`);
+ return call('POST', `/api/nodes/jobs/${encodeURIComponent(jobId)}/result`, {
+ node: identity.publicKey,
+ failed: true,
+ error: String(error).slice(0, 500),
+ startedAt,
+ finishedAt,
+ ts,
+ signature,
+ });
+ },
+ };
+}
diff --git a/packages/node-operator/src/signing.js b/packages/node-operator/src/signing.js
new file mode 100644
index 000000000..d7b4fba07
--- /dev/null
+++ b/packages/node-operator/src/signing.js
@@ -0,0 +1,121 @@
+/**
+ * Result signing: the cryptographic receipt for one inference job.
+ *
+ * The receipt binds (jobId, model, prompt, output, timing) to the node's
+ * ed25519 identity. Verification is pure and offline: anyone holding the
+ * receipt and the node's public key can confirm the node computed exactly
+ * this output for exactly this job, which is what phase 4 settlement needs
+ * before releasing payment.
+ *
+ * Canonical message format (what gets signed):
+ *
+ * sha256hex(jobId).sha256hex(model).sha256hex(prompt).sha256hex(output).startedAt.finishedAt
+ *
+ * Every variable-length field is pre-hashed so there is no delimiter or
+ * encoding ambiguity, then the whole line is signed with ed25519. Hashing is
+ * WebCrypto SHA-256 so it works identically in Node, Docker, and the browser
+ * verification path.
+ */
+
+import { createRequire } from 'node:module';
+
+const require = createRequire(import.meta.url);
+const nacl = require('tweetnacl');
+
+/** Hex SHA-256 of a UTF-8 string or byte array. */
+export async function sha256Hex(input) {
+ const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
+ return Buffer.from(digest).toString('hex');
+}
+
+/**
+ * Build the canonical signing payload for a job result. Pure; exposed so the
+ * platform verifier and tests reproduce the exact same bytes.
+ */
+export async function receiptPayload({ jobId, model, prompt, output, startedAt, finishedAt }) {
+ const parts = [
+ await sha256Hex(String(jobId)),
+ await sha256Hex(String(model)),
+ await sha256Hex(String(prompt)),
+ await sha256Hex(typeof output === 'string' ? output : JSON.stringify(output)),
+ String(startedAt),
+ String(finishedAt),
+ ];
+ return parts.join('.');
+}
+
+/**
+ * Sign a job result with the node identity. Returns the full receipt object
+ * the node submits with the result and the platform verifies.
+ */
+export async function signResult(identity, { jobId, model, prompt, output, startedAt, finishedAt }) {
+ const payload = await receiptPayload({ jobId, model, prompt, output, startedAt, finishedAt });
+ return {
+ algorithm: 'ed25519',
+ publicKey: identity.publicKey,
+ payload,
+ signature: identity.signText(payload),
+ };
+}
+
+/**
+ * Verify a receipt against a claimed node public key. Returns true only if
+ * the signature is valid AND the receipt was signed by the claimed key.
+ */
+export function verifyReceipt(receipt, expectedPublicKey) {
+ if (!receipt || receipt.algorithm !== 'ed25519') return false;
+ if (expectedPublicKey && receipt.publicKey !== expectedPublicKey) return false;
+ let sigBytes;
+ let msgBytes;
+ try {
+ sigBytes = Uint8Array.from(Buffer.from(receipt.signature, 'base64'));
+ msgBytes = new TextEncoder().encode(receipt.payload);
+ } catch {
+ return false;
+ }
+ let pubBytes;
+ try {
+ pubBytes = base58ToBytes(receipt.publicKey);
+ } catch {
+ return false;
+ }
+ return nacl.sign.detached.verify(msgBytes, sigBytes, pubBytes);
+}
+
+/**
+ * Deterministically recompute and verify a receipt from the job inputs and
+ * result. This is the platform-side check: recompute the payload from the
+ * claimed inputs, then verify the signature over it.
+ */
+export async function verifyResult({ jobId, model, prompt, output, startedAt, finishedAt }, receipt) {
+ const payload = await receiptPayload({ jobId, model, prompt, output, startedAt, finishedAt });
+ if (payload !== receipt?.payload) return false;
+ return verifyReceipt(receipt, receipt.publicKey);
+}
+
+// Local base58 decode (kept here so the verifier path has no identity.js
+// import cost; the alphabets must stay identical).
+const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+function base58ToBytes(str) {
+ const bytes = [0];
+ for (const ch of str) {
+ const idx = B58.indexOf(ch);
+ if (idx < 0) throw new Error('invalid base58');
+ let carry = idx;
+ for (let i = 0; i < bytes.length; i++) {
+ carry += bytes[i] * 58;
+ bytes[i] = carry & 0xff;
+ carry >>= 8;
+ }
+ while (carry > 0) {
+ bytes.push(carry & 0xff);
+ carry >>= 8;
+ }
+ }
+ for (const ch of str) {
+ if (ch === '1') bytes.push(0);
+ else break;
+ }
+ return Uint8Array.from(bytes.reverse());
+}
diff --git a/packages/node-operator/tests/node-operator.test.js b/packages/node-operator/tests/node-operator.test.js
new file mode 100644
index 000000000..475ed1492
--- /dev/null
+++ b/packages/node-operator/tests/node-operator.test.js
@@ -0,0 +1,252 @@
+/**
+ * Unit tests for the node operator client's pure layers: identity, signing,
+ * config, and the job loop. The wire client is exercised against a stub
+ * fetch; the inference model itself is covered by the end-to-end proof
+ * (scripts/e2e-local.mjs) rather than re-downloading weights in unit tests.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ base58Encode,
+ base58Decode,
+ createIdentity,
+ parseSecretKey,
+} from '../src/identity.js';
+import { receiptPayload, signResult, verifyReceipt, verifyResult, sha256Hex } from '../src/signing.js';
+import { loadConfig } from '../src/config.js';
+import { createPlatformClient } from '../src/platform.js';
+import { createJobLoop } from '../src/loop.js';
+
+describe('identity', () => {
+ it('round-trips base58 against the known ed25519 zero-key vector', () => {
+ // 64 zero bytes is a valid ed25519 secret key seed buffer shape; its
+ // base58 encoding must survive a decode round trip exactly.
+ const bytes = new Uint8Array(64).fill(0).map((_, i) => (i * 7 + 13) % 256);
+ expect(base58Decode(base58Encode(bytes))).toEqual(bytes);
+ });
+
+ it('preserves leading zero bytes (Solana address convention)', () => {
+ const bytes = new Uint8Array([0, 0, 0, 5, 6, 7]);
+ expect(base58Decode(base58Encode(bytes))).toEqual(bytes);
+ });
+
+ it('derives a stable base58 pubkey from a fixed secret key', () => {
+ const secret = new Uint8Array(64).fill(0).map((_, i) => (i * 31 + 1) % 256);
+ const a = createIdentity(secret);
+ const b = createIdentity(secret);
+ expect(a.publicKey).toBe(b.publicKey);
+ expect(a.publicKey.length).toBeGreaterThanOrEqual(32);
+ expect(a.publicKey.length).toBeLessThanOrEqual(44);
+ });
+
+ it('parses base58 and base64 secret keys identically', () => {
+ const secret = new Uint8Array(64).fill(0).map((_, i) => (i * 17 + 3) % 256);
+ const from58 = parseSecretKey(base58Encode(secret));
+ const from64 = parseSecretKey(Buffer.from(secret).toString('base64'));
+ expect(from58).toEqual(secret);
+ expect(from64).toEqual(secret);
+ });
+
+ it('rejects malformed secret keys', () => {
+ expect(() => parseSecretKey('not-a-key')).toThrow();
+ expect(() => parseSecretKey(Buffer.from('short').toString('base64'))).toThrow();
+ });
+});
+
+describe('signing', () => {
+ const identity = createIdentity(new Uint8Array(64).fill(0).map((_, i) => (i * 11 + 5) % 256));
+ const job = {
+ jobId: 'job-123',
+ model: 'Xenova/all-MiniLM-L6-v2',
+ prompt: 'hello world',
+ output: { kind: 'text-embedding', embedding: [0.1, 0.2] },
+ startedAt: 1000,
+ finishedAt: 1500,
+ };
+
+ it('sha256Hex matches the known empty-string digest', async () => {
+ expect(await sha256Hex('')).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
+ });
+
+ it('produces a receipt that verifies against the node pubkey', async () => {
+ const receipt = await signResult(identity, job);
+ expect(receipt.algorithm).toBe('ed25519');
+ expect(receipt.publicKey).toBe(identity.publicKey);
+ expect(verifyReceipt(receipt, identity.publicKey)).toBe(true);
+ });
+
+ it('fails verification for a different claimed pubkey', async () => {
+ const receipt = await signResult(identity, job);
+ const other = createIdentity();
+ expect(verifyReceipt(receipt, other.publicKey)).toBe(false);
+ });
+
+ it('fails verification when any job field is tampered with', async () => {
+ const receipt = await signResult(identity, job);
+ expect(await verifyResult(job, receipt)).toBe(true);
+ expect(await verifyResult({ ...job, output: { kind: 'text-embedding', embedding: [9, 9] } }, receipt)).toBe(false);
+ expect(await verifyResult({ ...job, jobId: 'job-999' }, receipt)).toBe(false);
+ expect(await verifyResult({ ...job, prompt: 'tampered' }, receipt)).toBe(false);
+ });
+
+ it('is deterministic: same inputs produce the same payload', async () => {
+ const p1 = await receiptPayload(job);
+ const p2 = await receiptPayload({ ...job });
+ expect(p1).toBe(p2);
+ });
+
+ it('rejects receipts with a wrong algorithm tag', async () => {
+ const receipt = await signResult(identity, job);
+ expect(verifyReceipt({ ...receipt, algorithm: 'secp256k1' }, identity.publicKey)).toBe(false);
+ });
+});
+
+describe('config', () => {
+ it('applies defaults when nothing is set', () => {
+ const cfg = loadConfig({ env: {}, cwd: '/nonexistent-dir-that-has-no-config' });
+ expect(cfg.platformUrl).toBe('https://three.ws');
+ expect(cfg.capability).toBe('text-embedding');
+ expect(cfg.pollIntervalMs).toBe(5000);
+ });
+
+ it('prefers env over file over defaults', () => {
+ const cfg = loadConfig({
+ env: { PLATFORM_URL: 'http://localhost:3101', POLL_INTERVAL_MS: '2000' },
+ cwd: '/nonexistent-dir-that-has-no-config',
+ });
+ expect(cfg.platformUrl).toBe('http://localhost:3101');
+ expect(cfg.pollIntervalMs).toBe(2000);
+ });
+
+ it('strips a trailing slash from platformUrl', () => {
+ const cfg = loadConfig({ env: { PLATFORM_URL: 'https://three.ws/' }, cwd: '/nonexistent-dir-that-has-no-config' });
+ expect(cfg.platformUrl).toBe('https://three.ws');
+ });
+
+ it('rejects a non-URL platformUrl', () => {
+ expect(() => loadConfig({ env: { PLATFORM_URL: 'three.ws' }, cwd: '/nonexistent-dir-that-has-no-config' })).toThrow(/absolute http/);
+ });
+
+ it('rejects a too-small poll interval', () => {
+ expect(() => loadConfig({ env: { POLL_INTERVAL_MS: '100' }, cwd: '/nonexistent-dir-that-has-no-config' })).toThrow(/POLL_INTERVAL_MS/);
+ });
+});
+
+describe('platform client', () => {
+ const identity = createIdentity();
+
+ function stubFetch(handlers) {
+ const calls = [];
+ const fetchImpl = async (url, opts) => {
+ calls.push({ url, opts });
+ const u = new URL(url);
+ for (const h of handlers) {
+ if (u.pathname.startsWith(h.match)) {
+ return {
+ ok: h.ok ?? true,
+ status: h.status ?? 200,
+ text: async () => JSON.stringify(h.body),
+ };
+ }
+ }
+ return { ok: false, status: 404, text: async () => JSON.stringify({ error: 'not_found' }) };
+ };
+ return { fetchImpl, calls };
+ }
+
+ it('registers with a signature over the domain-separated register string', async () => {
+ const { fetchImpl, calls } = stubFetch([{ match: '/api/nodes/register', body: { ok: true, node: { id: 'n1', publicKey: identity.publicKey } } }]);
+ const client = createPlatformClient({ platformUrl: 'http://localhost:3101', identity, fetchImpl });
+ const res = await client.register({ label: 'test node', capabilities: [{ capability: 'text-embedding', model: 'm' }] });
+ expect(res.node.id).toBe('n1');
+ const body = JSON.parse(calls[0].opts.body);
+ expect(body.publicKey).toBe(identity.publicKey);
+ expect(identity.verify(`threews-node-register:${identity.publicKey}:${body.registeredAt}`, body.signature)).toBe(true);
+ });
+
+ it('polls with a signed timestamp and returns null on an empty queue', async () => {
+ const { fetchImpl, calls } = stubFetch([{ match: '/api/nodes/jobs', body: { job: null } }]);
+ const client = createPlatformClient({ platformUrl: 'http://localhost:3101', identity, fetchImpl });
+ expect(await client.pollJob({ capability: 'text-embedding' })).toBeNull();
+ const u = new URL(calls[0].url);
+ const ts = u.searchParams.get('ts');
+ expect(identity.verify(`threews-node-poll:${identity.publicKey}:${ts}`, u.searchParams.get('sig'))).toBe(true);
+ });
+
+ it('submits results to the job-scoped URL with the receipt attached', async () => {
+ const receipt = await signResult(identity, { jobId: 'j1', model: 'm', prompt: 'p', output: {}, startedAt: 1, finishedAt: 2 });
+ const { fetchImpl, calls } = stubFetch([{ match: '/api/nodes/jobs/j1/result', body: { ok: true, verified: true } }]);
+ const client = createPlatformClient({ platformUrl: 'http://localhost:3101', identity, fetchImpl });
+ const res = await client.submitResult('j1', { output: {}, startedAt: 1, finishedAt: 2, receipt });
+ expect(res.verified).toBe(true);
+ expect(calls[0].url).toContain('/api/nodes/jobs/j1/result');
+ });
+
+ it('surfaces platform error text on non-2xx', async () => {
+ const { fetchImpl } = stubFetch([{ match: '/api/nodes/register', ok: false, status: 401, body: { error: 'bad_signature' } }]);
+ const client = createPlatformClient({ platformUrl: 'http://localhost:3101', identity, fetchImpl });
+ await expect(client.register({ capabilities: [] })).rejects.toThrow(/bad_signature/);
+ });
+});
+
+describe('job loop', () => {
+ const identity = createIdentity();
+
+ function makeClient(jobs) {
+ const submitted = [];
+ const failed = [];
+ return {
+ submitted,
+ failed,
+ pollJob: async () => jobs.shift() ?? null,
+ submitResult: async (id, payload) => { submitted.push({ id, payload }); return { ok: true, verified: true }; },
+ reportFailure: async (id, payload) => { failed.push({ id, payload }); return { ok: true }; },
+ };
+ }
+
+ it('executes a polled job and submits a signed, verifiable result', async () => {
+ const job = { id: 'j-loop-1', capability: 'text-embedding', model: 'm', input: { text: 'hi' } };
+ const client = makeClient([job]);
+ const loop = createJobLoop({
+ client,
+ identity,
+ capability: 'text-embedding',
+ pollIntervalMs: 10,
+ // A deterministic stand-in for the real model: the loop contract is
+ // what is under test here, not the tensor math.
+ runJobImpl: async (j) => ({ output: { kind: 'text-embedding', model: j.model, embedding: [1, 2, 3], dimensions: 3 }, startedAt: 10, finishedAt: 20 }),
+ });
+ const run = loop.run();
+ await new Promise((r) => setTimeout(r, 100));
+ loop.stop();
+ await run;
+
+ expect(client.submitted).toHaveLength(1);
+ expect(client.submitted[0].id).toBe('j-loop-1');
+ expect(loop.stats.completed).toBe(1);
+ const { payload } = client.submitted[0];
+ expect(await verifyResult(
+ { jobId: 'j-loop-1', model: 'm', prompt: 'hi', output: payload.output, startedAt: 10, finishedAt: 20 },
+ payload.receipt,
+ )).toBe(true);
+ });
+
+ it('reports a failing job instead of crashing the loop', async () => {
+ const client = makeClient([{ id: 'j-bad', capability: 'text-embedding', model: 'm', input: { text: '' } }]);
+ const loop = createJobLoop({
+ client,
+ identity,
+ capability: 'text-embedding',
+ pollIntervalMs: 10,
+ runJobImpl: async () => { throw new Error('input.text must be a non-empty string'); },
+ });
+ const run = loop.run();
+ await new Promise((r) => setTimeout(r, 100));
+ loop.stop();
+ await run;
+
+ expect(loop.stats.failed).toBe(1);
+ expect(client.failed[0].payload.error).toMatch(/non-empty/);
+ expect(client.submitted).toHaveLength(0);
+ });
+});
diff --git a/public/changelog.json b/public/changelog.json
index d7ab70783..97a945acc 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,32 @@
{
- "generated_at": "2026-08-12T07:03:01.311Z",
+ "generated_at": "2026-08-12T07:38:25.926Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-08-12",
+ "type": "update",
+ "title": "Your agent can now learn your Farcaster voice, and only after you prove the account is yours",
+ "summary": "Memory seeding already worked from GitHub and X; Farcaster now joins them, with consent built into the protocol itself. Farcaster has no login button we could use, so instead the account's own public record does the work: every Farcaster account publishes the wallets it controls, and you prove ownership by signing a one-time challenge with one of those wallets, Solana first. Nothing is read, let alone stored, before that signature checks out. The grant is read-only and narrow: your public profile and up to 100 recent casts, distilled into identity, facts, and your strongest posts, so the agent talks the way you talk. Changing your mind is one click: revoking the grant deletes every memory it produced, including anything an earlier grant left behind. The whole flow lives in the agent persona editor, and it works with no API key configured because the reader falls back to a public Farcaster hub.",
+ "link": "/docs/farcaster-memory-seeding",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-08-11",
+ "type": "launch",
+ "title": "Docs · Farcaster memory seeding",
+ "summary": "Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.",
+ "link": "/docs/farcaster-memory-seeding",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-08-11",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index c9916df9d..79f7c192e 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Your agent can now learn your Farcaster voice, and only after you prove the account is yours</title>
+ <link>https://three.ws/docs/farcaster-memory-seeding</link>
+ <guid isPermaLink="false">2026-08-12:Your agent can now learn your Farcaster voice, and only after you prove the account is yours</guid>
+ <pubDate>Wed, 12 Aug 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Memory seeding already worked from GitHub and X; Farcaster now joins them, with consent built into the protocol itself. Farcaster has no login button we could use, so instead the account's own public record does the work: every Farcaster account publishes the wallets it controls, and you prove ownership by signing a one-time challenge with one of those wallets, Solana first. Nothing is read, let alone stored, before that signature checks out. The grant is read-only and narrow: your public profile and up to 100 recent casts, distilled into identity, facts, and your strongest posts, so the agent talks the way you talk. Changing your mind is one click: revoking the grant deletes every memory it produced, including anything an earlier grant left behind. The whole flow lives in the agent persona editor, and it works with no API key configured because the reader falls back to a public Farcaster hub.</description>
+ </item>
+ <item>
+ <title>Docs · Farcaster memory seeding</title>
+ <link>https://three.ws/docs/farcaster-memory-seeding</link>
+ <guid isPermaLink="false">2026-08-11:Docs · Farcaster memory seeding</guid>
+ <pubDate>Tue, 11 Aug 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.</description>
+ </item>
<item>
<title>Docs · Tokens API on three.ws</title>
<link>https://three.ws/docs/tokens-xyz</link>
diff --git a/public/features.json b/public/features.json
index 82eb57729..d2e7fc754 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T07:35:32.465Z",
+ "generated_at": "2026-08-12T07:38:25.916Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -2917,6 +2917,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/farcaster-memory-seeding",
+ "title": "Docs · Farcaster memory seeding",
+ "description": "Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.",
+ "added": "2026-08-11",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/ibm-community",
"title": "Docs · IBM Community post catalog",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 594132c17..d825132be 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -1780,6 +1780,12 @@ URL: https://three.ws/docs
Full documentation: SDKs, API reference, embedding, agent system, smart contracts.
+### Docs · Farcaster memory seeding
+
+URL: https://three.ws/docs/farcaster-memory-seeding
+
+Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.
+
### Docs · IBM Community post catalog
URL: https://three.ws/docs/ibm-community
diff --git a/public/llms.txt b/public/llms.txt
index 71a6a0907..c5b1d5138 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -332,6 +332,7 @@ Sign-in, dashboard, billing.
Docs, tutorials, and reference.
- [Docs](https://three.ws/docs): Full documentation: SDKs, API reference, embedding, agent system, smart contracts.
+- [Docs · Farcaster memory seeding](https://three.ws/docs/farcaster-memory-seeding): Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.
- [Docs · IBM Community post catalog](https://three.ws/docs/ibm-community): The running catalog of every thread and blog in the Three.ws User Group on IBM Community: authors, dates, activity, and a faithful summary of each post, plus a snapshot of the group's membership and content counts.
- [Docs · Event souvenirs: the wearable you keep](https://three.ws/docs/event-souvenirs): The free commemorative wearable granted once to every player who is in the $THREE world while a live event is running: what it is, how the server decides who earns it, why it can never be bought, and how to equip it afterwards.
- [Docs · Live events in the /play world](https://three.ws/docs/play-live-events): How a scheduled event runs inside the $THREE world: one config file drives the countdown chip, the agenda drawer, the go-live moment, and a fireworks show every player sees identically without a single packet. Includes how to schedule, preview, and verify one.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 8290848d8..42aed2b61 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -83,7 +83,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 805 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 806 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -95,7 +95,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 805 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 806 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -103,6 +103,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="/docs/farcaster-memory-seeding">
+ <span class="sm-new-date">Aug 11, 2026</span>
+ <span class="sm-title">Docs · Farcaster memory seeding</span>
+ <span class="sm-path">/docs/farcaster-memory-seeding</span>
+ <span class="sm-desc">Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.</span>
+ </a>
+ </li>
<li>
<a href="/docs/tokens-xyz">
<span class="sm-new-date">Aug 11, 2026</span>
@@ -167,14 +175,6 @@
<span class="sm-desc">The Three.ws User Group on IBM Community held its first meetup inside three.ws itself, 8 AM to 5 PM Pacific, peaking at 3,145 concurrent users in the $THREE home town at three.ws/play. Here's how a nine-hour user group meetup held inside a 3D world actually went.</span>
</a>
</li>
- <li>
- <a href="/event">
- <span class="sm-new-date">Aug 7, 2026</span>
- <span class="sm-title">Live event</span>
- <span class="sm-path">/event</span>
- <span class="sm-desc">The live three.ws community meetup: a ticking countdown off the same config /play reads, the run of show in your own timezone, an add-to-calendar file, who is in the world right now, and the one door in.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -2241,7 +2241,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>350</span></h2>
+ <h2>Learn<span class="sm-count" data-count>351</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -2252,6 +2252,13 @@
<span class="sm-desc">Full documentation: SDKs, API reference, embedding, agent system, smart contracts.</span>
</a>
</li>
+ <li>
+ <a href="/docs/farcaster-memory-seeding">
+ <span class="sm-title">Docs · Farcaster memory seeding</span>
+ <span class="sm-path">/docs/farcaster-memory-seeding</span>
+ <span class="sm-desc">Give an agent your Farcaster voice with explicit consent: ownership is proved by signing a challenge with a wallet the fid itself verified on the protocol (Solana first), only your public profile and casts are read, and revoking the grant deletes every memory it produced.</span>
+ </a>
+ </li>
<li>
<a href="/docs/ibm-community">
<span class="sm-title">Docs · IBM Community post catalog</span>
diff --git a/scripts/a2a-spend-hardening-proof.mjs b/scripts/a2a-spend-hardening-proof.mjs
new file mode 100644
index 000000000..73448334f
--- /dev/null
+++ b/scripts/a2a-spend-hardening-proof.mjs
@@ -0,0 +1,660 @@
+#!/usr/bin/env node
+// a2a-spend-hardening-proof: prove, on a real Postgres with real advisory locks
+// and a live local HTTP surface, that the per-agent spend policy actually blocks
+// what it claims to block. No real funds move anywhere in this run: every spend
+// stops at the reservation layer (the same layer that runs BEFORE any key is
+// touched or any payment is signed in production), and the database is a
+// throwaway local container.
+//
+// Why this exists: tests/a2a-payment-hardening.test.js proves the limits against
+// a mocked DB (deterministic, fast), but a mock cannot prove the two properties
+// that make the caps real under autonomy:
+// 1. the reserve is ATOMIC (the INSERT...SELECT under pg_advisory_xact_lock
+// cannot be raced by concurrent spends reading the same stale total), and
+// 2. the kill switch halts spending on the LIVE surface the owner actually
+// uses (PUT /api/agents/:id/solana/limits -> the very next reserve throws).
+// This script is the second half of that proof.
+//
+// What it proves, in order:
+// 1. per_tx_usd an over-cap reserve is rejected; an at-cap one lands
+// 2. daily_usd a wallet at its rolling-24h ceiling rejects the next
+// reserve, and 8 CONCURRENT reserves cannot race past it
+// 3. per_counterparty_daily_usd a payee at its ceiling rejects more, while the
+// identical spend to a different payee still lands
+// 4. kill switch frozen=true blocks every autonomous category
+// (x402/trade/snipe) immediately, the owner's own
+// withdraw stays open, and unfreezing resumes spending
+// 5. receipts (live HTTP) every agent-initiated payment is queryable per agent
+// from the owner ledger surface: the full statement at
+// GET /api/agents/:id/solana/custody, and the economy
+// summary at GET /api/agents/:id/economy
+//
+// Usage:
+// node scripts/a2a-spend-hardening-proof.mjs # full run, prints transcript
+// node scripts/a2a-spend-hardening-proof.mjs --keep # leave pg container running
+//
+// Environment: needs `docker` (postgres:16 image) and port 5817/5818/3817 free.
+// `pg` is loaded from node_modules if present, else installed with --no-save.
+
+import { spawn, spawnSync, execFileSync } from 'node:child_process';
+import { once } from 'node:events';
+import path from 'node:path';
+import fs from 'node:fs';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const KEEP = process.argv.includes('--keep');
+
+const PG_PORT = 5817;
+const SHIM_PORT = 5818;
+const HTTP_PORT = 3817;
+const PG_CONTAINER = 'a2a-spend-proof-pg';
+const PG_URL = `postgres://[email protected]:${PG_PORT}/proof`;
+const SHIM_URL = `http://127.0.0.1:${SHIM_PORT}/sql`;
+const HTTP_BASE = `http://127.0.0.1:${HTTP_PORT}`;
+
+const PEER_A = 'PeerA111111111111111111111111111111111111';
+const PEER_B = 'PeerB222222222222222222222222222222222222';
+
+// ── tiny transcript + assertion kit ──────────────────────────────────────────
+const results = [];
+let failed = 0;
+function step(name) {
+ console.log(`\n── ${name}`);
+}
+function pass(name, detail) {
+ results.push({ name, ok: true, detail });
+ console.log(` ✔ ${name}${detail ? ` — ${detail}` : ''}`);
+}
+function fail(name, detail) {
+ failed += 1;
+ results.push({ name, ok: false, detail });
+ console.error(` ✘ ${name} — ${detail}`);
+}
+function check(name, cond, detail) {
+ if (cond) pass(name, detail);
+ else fail(name, detail);
+ return !!cond;
+}
+
+// ── process helpers ──────────────────────────────────────────────────────────
+const cleanup = [];
+async function shutdown() {
+ for (const fn of cleanup.splice(0).reverse()) {
+ try { await fn(); } catch { /* best effort */ }
+ }
+}
+process.on('SIGINT', async () => { await shutdown(); process.exit(130); });
+
+function run(cmd, args, opts = {}) {
+ const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
+ return { code: r.status, out: (r.stdout || '') + (r.stderr || '') };
+}
+
+async function waitFor(fn, { tries = 60, delayMs = 500, label = 'dependency' } = {}) {
+ for (let i = 0; i < tries; i++) {
+ try {
+ const v = await fn();
+ if (v) return v;
+ } catch { /* not ready */ }
+ await new Promise((r) => setTimeout(r, delayMs));
+ }
+ throw new Error(`timed out waiting for ${label}`);
+}
+
+async function portFree(port) {
+ return new Promise((resolve) => {
+ const s = net.createServer();
+ s.once('error', () => resolve(false));
+ s.once('listening', () => s.close(() => resolve(true)));
+ s.listen(port, '127.0.0.1');
+ });
+}
+
+// ── pg client (raw SQL for seeding/assertions) ───────────────────────────────
+async function loadPg() {
+ try {
+ return await import('pg');
+ } catch {
+ console.log(' installing pg (--no-save) for the local Postgres bridge');
+ const r = run('npm', ['i', '--no-save', '--no-audit', '--no-fund', 'pg'], { cwd: root });
+ if (r.code !== 0) throw new Error(`npm i pg failed: ${r.out.slice(-400)}`);
+ return await import('pg');
+ }
+}
+
+// ── neon HTTP shim: lets api/_lib/db.js (neon serverless HTTP driver) talk to
+// the local Postgres. Same pattern previous local proofs used; array-mode raw
+// text rows so the driver applies its own type parsing exactly as against Neon.
+function startShim(pg) {
+ const preloadPath = '/tmp/a2a-spend-proof-preload.mjs';
+ const shimPath = '/tmp/a2a-spend-proof-shim.mjs';
+ fs.writeFileSync(shimPath, `
+import http from 'node:http';
+import pg from ${JSON.stringify(path.join(root, 'node_modules/pg/index.js'))};
+const client = new pg.Client(${JSON.stringify(PG_URL)});
+client.setTypeParser = undefined;
+await client.connect();
+http.createServer(async (req, res) => {
+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return; }
+ let body = '';
+ for await (const c of req) body += c;
+ try {
+ const { query, params } = JSON.parse(body || '{}');
+ const r = await client.query({
+ text: query, values: params || [], rowMode: 'array',
+ types: { getTypeParser: () => (v) => v },
+ });
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({
+ fields: r.fields.map((f) => ({ name: f.name, dataTypeID: f.dataTypeID })),
+ rows: r.rows, rowCount: r.rowCount, command: r.command,
+ }));
+ } catch (e) {
+ res.writeHead(500, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ message: String(e && e.message || e) }));
+ }
+}).listen(${SHIM_PORT}, '127.0.0.1');
+`);
+ fs.writeFileSync(preloadPath, `
+import { neonConfig } from ${JSON.stringify(path.join(root, 'node_modules/@neondatabase/serverless/index.mjs'))};
+neonConfig.fetchEndpoint = () => ${JSON.stringify(SHIM_URL)};
+`);
+ const shim = spawn('node', [shimPath], { stdio: 'inherit' });
+ cleanup.push(() => shim.kill('SIGKILL'));
+ return { preloadPath };
+}
+
+// ── HTTP client with a cookie jar ────────────────────────────────────────────
+function makeHttp() {
+ const cookies = new Map();
+ function capture(res) {
+ const set = res.headers.getSetCookie ? res.headers.getSetCookie() : [];
+ for (const c of set) {
+ const [pair] = c.split(';');
+ const i = pair.indexOf('=');
+ cookies.set(pair.slice(0, i).trim(), pair.slice(i + 1).trim());
+ }
+ }
+ function cookieHeader() {
+ return [...cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
+ }
+ async function req(method, p, { body, headers = {} } = {}) {
+ const res = await fetch(HTTP_BASE + p, {
+ method,
+ headers: {
+ cookie: cookieHeader(),
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ redirect: 'manual',
+ });
+ capture(res);
+ const text = await res.text();
+ let json = null;
+ try { json = JSON.parse(text); } catch { /* html or empty */ }
+ return { status: res.status, json, text };
+ }
+ async function freshCsrf() {
+ const r = await req('GET', '/api/csrf-token');
+ if (r.status !== 200 || !r.json?.token) throw new Error(`csrf-token failed: ${r.status} ${r.text.slice(0, 200)}`);
+ return r.json.token;
+ }
+ return { req, freshCsrf };
+}
+
+async function main() {
+ console.log('a2a spend hardening proof — real Postgres, live local HTTP, no real funds\n');
+
+ // ── environment ──────────────────────────────────────────────────────────
+ step('0. environment');
+ for (const [port, name] of [[PG_PORT, 'postgres'], [SHIM_PORT, 'shim'], [HTTP_PORT, 'http']]) {
+ if (!(await portFree(port))) throw new Error(`port ${port} (${name}) is already in use — pick another port or stop the stale process`);
+ }
+ check('docker available', run('docker', ['--version']).code === 0);
+ run('docker', ['rm', '-f', PG_CONTAINER]);
+ const up = run('docker', [
+ 'run', '-d', '--name', PG_CONTAINER,
+ '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', '-e', 'POSTGRES_DB=proof',
+ '-p', `${PG_PORT}:5432`, 'postgres:16',
+ ]);
+ if (up.code !== 0) throw new Error(`docker run failed: ${up.out}`);
+ cleanup.push(() => run('docker', ['rm', '-f', PG_CONTAINER]));
+ pass('throwaway postgres started', `${PG_CONTAINER} on :${PG_PORT}`);
+
+ const pg = await loadPg();
+ const admin = new pg.Client(PG_URL);
+ await waitFor(async () => {
+ try { await admin.connect(); return true; } catch { admin._ending = false; return false; }
+ }, { label: 'postgres ready' }).catch(async () => {
+ // connect() failed once; retry with a fresh client per attempt
+ });
+ let db = null;
+ await waitFor(async () => {
+ try {
+ const c = new pg.Client(PG_URL);
+ await c.connect();
+ await c.query('select 1');
+ db = c;
+ return true;
+ } catch { return false; }
+ }, { label: 'postgres accepting queries' });
+ pass('postgres accepting queries');
+
+ // Schema: the notifications migration FIRST (schema.sql references
+ // user_notifications without creating it), then schema.sql, then every
+ // migration in order. Drifted ancient migrations are tolerated only when
+ // nothing we touch depends on them; users/agent_identities/
+ // agent_custody_events/sessions/csrf_tokens MUST exist afterwards.
+ const migrationsDir = path.join(root, 'api/_lib/migrations');
+ const schemaFiles = [
+ path.join(migrationsDir, '2026-04-30-notifications.sql'),
+ path.join(root, 'api/_lib/schema.sql'),
+ ...fs.readdirSync(migrationsDir).filter((f) => f.endsWith('.sql')).sort()
+ .map((f) => path.join(migrationsDir, f)),
+ ];
+ let applied = 0;
+ const skipped = [];
+ for (const f of schemaFiles) {
+ const r = run('docker', ['exec', '-i', PG_CONTAINER, 'psql', '-U', 'postgres', '-d', 'proof', '-v', 'ON_ERROR_STOP=1', '-q'], { input: fs.readFileSync(f, 'utf8') });
+ if (r.code === 0) applied += 1;
+ else skipped.push(path.basename(f));
+ }
+ const mustHave = ['users', 'sessions', 'csrf_tokens', 'agent_identities', 'agent_custody_events'];
+ const missing = [];
+ for (const t of mustHave) {
+ const { rows } = await db.query('select to_regclass($1) AS r', [`public.${t}`]);
+ if (!rows[0].r) missing.push(t);
+ }
+ check('schema applied', applied > 0 && missing.length === 0,
+ `${applied} files applied, ${skipped.length} skipped from drift; required tables present`);
+ if (missing.length) throw new Error(`required tables missing: ${missing.join(', ')}`);
+
+ // Seed the proof agent (library phase). Direct SQL, real rows.
+ const { rows: [u1] } = await db.query(
+ `insert into users (email, password_hash, email_verified) values ($1, 'x', true) returning id`,
+ [`proof-lib-${Date.now()}@proof.local`],
+ );
+ const { rows: [a1] } = await db.query(
+ `insert into agent_identities (user_id, name) values ($1, $2) returning id`,
+ [u1.id, 'spend-proof-agent'],
+ );
+ const agentId = a1.id;
+ pass('proof user + agent seeded', `agent ${agentId}`);
+
+ // Bridge api/_lib/db.js (neon HTTP) onto the local postgres.
+ const { preloadPath } = startShim(pg);
+ await waitFor(async () => {
+ try {
+ const r = await fetch(SHIM_URL, { method: 'POST', body: JSON.stringify({ query: 'select 1', params: [] }) });
+ return r.ok;
+ } catch { return false; }
+ }, { label: 'sql shim' });
+ pass('neon HTTP shim up', SHIM_URL);
+
+ // The guards module is imported in a CHILD process so the neon fetchEndpoint
+ // preload applies before db.js evaluates. The child exposes the guard calls
+ // this proof needs as a tiny JSON-over-stdio RPC.
+ const workerPath = '/tmp/a2a-spend-proof-worker.mjs';
+ fs.writeFileSync(workerPath, `
+import { reserveSpendUsd, enforceSpendLimit, updateCustodyEvent, releaseSpendReservation,
+ recordCustodyEvent, SpendLimitError } from ${JSON.stringify(path.join(root, 'api/_lib/agent-trade-guards.js'))};
+let buf = '';
+process.stdin.on('data', (d) => {
+ buf += d;
+ let i;
+ while ((i = buf.indexOf('\\n')) >= 0) {
+ const line = buf.slice(0, i); buf = buf.slice(i + 1);
+ if (!line.trim()) continue;
+ (async () => {
+ const { id, fn, args } = JSON.parse(line);
+ try {
+ const out = await ({ reserveSpendUsd, enforceSpendLimit, updateCustodyEvent,
+ releaseSpendReservation, recordCustodyEvent })[fn](...(args || []));
+ process.stdout.write(JSON.stringify({ id, ok: true, out: out ?? null }) + '\\n');
+ } catch (e) {
+ process.stdout.write(JSON.stringify({ id, ok: false, err: {
+ name: e?.name, code: e?.code || null, status: e?.status || null,
+ message: String(e?.message || e), detail: e?.detail || null,
+ } }) + '\\n');
+ }
+ })();
+ }
+});
+`);
+ const worker = spawn('node', ['--import', preloadPath, workerPath], {
+ env: { ...process.env, DATABASE_URL: PG_URL, JWT_SECRET: 'proof-jwt-secret' },
+ stdio: ['pipe', 'pipe', 'inherit'],
+ });
+ cleanup.push(() => worker.kill('SIGKILL'));
+ const pending = new Map();
+ let rpcSeq = 0;
+ let workerBuf = '';
+ worker.stdout.on('data', (d) => {
+ workerBuf += d;
+ let i;
+ while ((i = workerBuf.indexOf('\n')) >= 0) {
+ const line = workerBuf.slice(0, i); workerBuf = workerBuf.slice(i + 1);
+ if (!line.trim()) continue;
+ const msg = JSON.parse(line);
+ pending.get(msg.id)?.(msg);
+ pending.delete(msg.id);
+ }
+ });
+ function call(fn, ...args) {
+ const id = ++rpcSeq;
+ return new Promise((resolve, reject) => {
+ pending.set(id, resolve);
+ worker.stdin.write(JSON.stringify({ id, fn, args }) + '\n');
+ setTimeout(() => { if (pending.has(id)) { pending.delete(id); reject(new Error(`${fn} timed out`)); } }, 30000);
+ });
+ }
+ async function callErr(fn, ...args) {
+ const r = await call(fn, ...args);
+ if (r.ok) return { thrown: null, out: r.out };
+ return { thrown: r.err, out: null };
+ }
+ // Sanity: the worker can reach the DB through the shim.
+ {
+ const probe = await callErr('recordCustodyEvent', {
+ agentId, userId: u1.id, eventType: 'limit_change', reason: 'proof_warmup', meta: {},
+ });
+ if (probe.thrown) throw new Error(`worker DB round-trip failed: ${probe.thrown.message}`);
+ }
+ pass('guard module live against real postgres', 'worker round-trip through advisory-lock SQL ok');
+
+ const spend = (over = {}) => ({
+ agentId, userId: u1.id, category: 'x402', usdValue: 1,
+ destination: PEER_A, network: 'mainnet', asset: 'USDC', ...over,
+ });
+ const confirm = async (reservationId, sig) => {
+ await call('updateCustodyEvent', reservationId, { status: 'ok', signature: sig });
+ };
+ const setLimits = async (patch) => {
+ await db.query(
+ `update agent_identities set meta = jsonb_set(coalesce(meta,'{}'::jsonb), '{spend_limits}', $2::jsonb) where id = $1`,
+ [agentId, JSON.stringify(patch)],
+ );
+ };
+
+ // ── 1. per-transaction ceiling ───────────────────────────────────────────
+ step('1. per_tx_usd — cap per call');
+ await setLimits({ daily_usd: null, per_tx_usd: 1, per_counterparty_daily_usd: null, withdraw_allowlist: [], frozen: false, require_capabilities: false });
+ {
+ const over = await callErr('reserveSpendUsd', spend({ usdValue: 1.5 }));
+ check('over-per-tx reserve blocked', over.thrown?.code === 'per_tx_exceeded',
+ over.thrown ? `${over.thrown.code}: ${over.thrown.message}` : 'ERROR: reserve was allowed');
+ const at = await callErr('reserveSpendUsd', spend({ usdValue: 1 }));
+ check('at-cap reserve allowed', !at.thrown && !!at.out?.reservationId, at.thrown?.message || `reservation ${at.out?.reservationId}`);
+ if (at.out?.reservationId) await call('releaseSpendReservation', at.out.reservationId, 'proof_cleanup');
+ }
+
+ // ── 2. daily ceiling + concurrency race ──────────────────────────────────
+ step('2. daily_usd — rolling 24h wallet ceiling, race-proof');
+ {
+ // Backfill real, priced, confirmed spend rows (history, not reservations).
+ for (const [usd, dest] of [[0.6, PEER_A], [0.3, PEER_B]]) {
+ const id = await call('recordCustodyEvent', {
+ agentId, userId: u1.id, eventType: 'spend', category: 'x402', network: 'mainnet',
+ asset: 'USDC', usd, destination: dest, status: 'ok', meta: { proof: 'backfill' },
+ });
+ if (!id) throw new Error('backfill row failed');
+ }
+ await setLimits({ daily_usd: 1, per_tx_usd: null, per_counterparty_daily_usd: null, withdraw_allowlist: [], frozen: false, require_capabilities: false });
+ const over = await callErr('reserveSpendUsd', spend({ usdValue: 0.2 }));
+ check('daily cap blocks the $0.20 that would push $0.90 -> $1.10 over $1.00', over.thrown?.code === 'daily_exceeded',
+ over.thrown ? `${over.thrown.code}: spent $${over.thrown.detail?.spent_usd} + $${over.thrown.detail?.usd} > cap $${over.thrown.detail?.daily_usd}` : 'ERROR: reserve was allowed');
+
+ // Concurrency: 8 simultaneous reserves for the last $0.10 of headroom.
+ // Without the advisory lock all 8 read spent=$0.90 and all pass ($0.80 over).
+ await setLimits({ daily_usd: 1, per_tx_usd: null, per_counterparty_daily_usd: null, withdraw_allowlist: [], frozen: false, require_capabilities: false });
+ const raced = await Promise.all([...Array(8)].map(() => callErr('reserveSpendUsd', spend({ usdValue: 0.1 }))));
+ const winners = raced.filter((r) => !r.thrown);
+ check('8 concurrent reserves for $0.10 headroom: exactly 1 wins', winners.length === 1,
+ `winners=${winners.length} blocked=${raced.length - winners.length} (advisory lock serialized them)`);
+ const after = winners.length === 1 ? raced.find((r) => r.thrown) : null;
+ check('the losers get daily_exceeded, not an error', !after || after.thrown.code === 'daily_exceeded', after?.thrown?.code);
+ for (const w of winners) await call('releaseSpendReservation', w.out.reservationId, 'proof_cleanup');
+ }
+
+ // ── 3. per-counterparty ceiling ──────────────────────────────────────────
+ step('3. per_counterparty_daily_usd — concentrated-drain ceiling');
+ {
+ // Fresh agent so the wallet-wide cap never fires first.
+ const { rows: [a2] } = await db.query(
+ `insert into agent_identities (user_id, name) values ($1, $2) returning id`,
+ [u1.id, 'spend-proof-agent-cp'],
+ );
+ const cpAgent = a2.id;
+ for (const usd of [0.6, 0.3]) {
+ await call('recordCustodyEvent', {
+ agentId: cpAgent, userId: u1.id, eventType: 'spend', category: 'x402', network: 'mainnet',
+ asset: 'USDC', usd, destination: PEER_A, status: 'ok', meta: { proof: 'backfill' },
+ });
+ }
+ await db.query(
+ `update agent_identities set meta = jsonb_set(coalesce(meta,'{}'::jsonb), '{spend_limits}', $2::jsonb) where id = $1`,
+ [cpAgent, JSON.stringify({ daily_usd: null, per_tx_usd: null, per_counterparty_daily_usd: 1, withdraw_allowlist: [], frozen: false, require_capabilities: false })],
+ );
+ const spendCp = (over = {}) => ({
+ agentId: cpAgent, userId: u1.id, category: 'x402', usdValue: 0.2,
+ destination: PEER_A, network: 'mainnet', asset: 'USDC', ...over,
+ });
+ const overSame = await callErr('reserveSpendUsd', spendCp());
+ check('counterparty at $0.90 of $1.00 blocks the next $0.20 to the SAME payee', overSame.thrown?.code === 'counterparty_daily_exceeded',
+ overSame.thrown ? `${overSame.thrown.code}: $${overSame.thrown.detail?.counterparty_spent_usd} + $${overSame.thrown.detail?.usd} > $${overSame.thrown.detail?.per_counterparty_daily_usd}` : 'ERROR: reserve was allowed');
+ const otherPeer = await callErr('reserveSpendUsd', spendCp({ destination: PEER_B }));
+ check('the identical $0.20 to a DIFFERENT payee still lands', !otherPeer.thrown && !!otherPeer.out?.reservationId,
+ otherPeer.thrown?.message || 'the cap meters per payee, not in total');
+ if (otherPeer.out?.reservationId) await call('releaseSpendReservation', otherPeer.out.reservationId, 'proof_cleanup');
+ }
+
+ // ── 4. kill switch ───────────────────────────────────────────────────────
+ step('4. kill switch — frozen halts every autonomous path immediately');
+ {
+ // Fresh agent, generous caps, no history: only the freeze can block.
+ const { rows: [a3] } = await db.query(
+ `insert into agent_identities (user_id, name) values ($1, $2) returning id`,
+ [u1.id, 'spend-proof-agent-kill'],
+ );
+ const killAgent = a3.id;
+ const open = { daily_usd: 1000, per_tx_usd: 1000, per_counterparty_daily_usd: null, withdraw_allowlist: [], frozen: false, require_capabilities: false };
+ await db.query(
+ `update agent_identities set meta = jsonb_set(coalesce(meta,'{}'::jsonb), '{spend_limits}', $2::jsonb) where id = $1`,
+ [killAgent, JSON.stringify(open)],
+ );
+ const spendKill = (over = {}) => ({
+ agentId: killAgent, userId: u1.id, category: 'x402', usdValue: 0.5,
+ destination: PEER_A, network: 'mainnet', asset: 'USDC', ...over,
+ });
+ const before = await callErr('reserveSpendUsd', spendKill());
+ check('control: unfrozen agent spends fine', !before.thrown && !!before.out?.reservationId, before.thrown?.message);
+ if (before.out?.reservationId) await call('releaseSpendReservation', before.out.reservationId, 'proof_cleanup');
+
+ await setLimitsOn(db, killAgent, { ...open, frozen: true });
+ for (const category of ['x402', 'trade', 'snipe']) {
+ const blocked = await callErr('reserveSpendUsd', spendKill({ category }));
+ check(`frozen blocks category=${category} instantly`, blocked.thrown?.code === 'wallet_frozen',
+ blocked.thrown ? `${blocked.thrown.code} (no lock wait, no reservation written)` : 'ERROR: spend was allowed');
+ }
+ const ownerSweep = await callErr('reserveSpendUsd', spendKill({ category: 'withdraw', destination: PEER_B }));
+ check('owner withdraw stays open while frozen', !ownerSweep.thrown && !!ownerSweep.out?.reservationId,
+ ownerSweep.thrown?.message || 'a freeze never traps the owner funds');
+ if (ownerSweep.out?.reservationId) await call('releaseSpendReservation', ownerSweep.out.reservationId, 'proof_cleanup');
+
+ await setLimitsOn(db, killAgent, { ...open, frozen: false });
+ const after = await callErr('reserveSpendUsd', spendKill());
+ check('unfreeze resumes spending', !after.thrown && !!after.out?.reservationId, after.thrown?.message);
+ if (after.out?.reservationId) await call('releaseSpendReservation', after.out.reservationId, 'proof_cleanup');
+ }
+
+ // ── 5. receipts on the live local surface ────────────────────────────────
+ step('5. receipts — queryable per agent on the live HTTP surface');
+ {
+ // Confirmed payments with tx signatures: the receipt rows the owner reads.
+ const sigs = ['proofsigA111', 'proofsigB222', 'proofsigC333'];
+ const amounts = [[0.4, PEER_A], [0.35, PEER_A], [0.25, PEER_B]];
+ for (let i = 0; i < amounts.length; i++) {
+ const r = await call('reserveSpendUsd', {
+ agentId, userId: u1.id, category: 'x402', usdValue: amounts[i][0],
+ destination: amounts[i][1], network: 'mainnet', asset: 'USDC',
+ rowMeta: { url: `https://peer-${i}.example/x402`, service: `peer-${i}` },
+ });
+ if (!r.ok) throw new Error(`receipt seeding reserve blocked unexpectedly: ${r.err?.message}`);
+ await confirm(r.out.reservationId, sigs[i]);
+ }
+ const seeded = await db.query(
+ `select count(*)::int as n from agent_custody_events where agent_id = $1 and event_type = 'spend' and status = 'ok'`,
+ [agentId],
+ );
+ pass('three settled payments finalized into the ledger', `${seeded.rows[0].n} confirmed spend rows for the agent`);
+
+ // Boot the real server against the same DB.
+ const server = spawn('node', ['--import', preloadPath, 'server/index.mjs'], {
+ cwd: root,
+ env: {
+ ...process.env,
+ PORT: String(HTTP_PORT),
+ DATABASE_URL: PG_URL,
+ JWT_SECRET: 'proof-jwt-secret',
+ NODE_ENV: 'development',
+ X402_AUTONOMOUS_ENABLED: 'false',
+ X402_SEED_ENABLED: 'false',
+ X402_RING_TICK_ENABLED: 'false',
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ cleanup.push(() => server.kill('SIGKILL'));
+ server.stderr.on('data', () => {});
+ await waitFor(async () => {
+ try {
+ const r = await fetch(`${HTTP_BASE}/api/version`);
+ return r.ok;
+ } catch { return false; }
+ }, { tries: 120, delayMs: 500, label: 'local server' });
+ pass('live server up', `${HTTP_BASE}/api/version 200`);
+
+ const http = makeHttp();
+ const email = `proof-owner-${Date.now()}@proof.local`;
+ const reg = await http.req('POST', '/api/auth/register', { body: { email, password: 'proof-pass-12345', tosAccepted: true } });
+ check('owner registered through the real /register flow', reg.status === 200 || reg.status === 201,
+ reg.status === 200 || reg.status === 201 ? email : `status ${reg.status}: ${reg.text.slice(0, 200)}`);
+
+ const csrf1 = await http.freshCsrf();
+ const created = await http.req('POST', '/api/agents', {
+ body: { name: 'receipt-proof-agent', description: 'receipt surface proof' },
+ headers: { 'x-csrf-token': csrf1 },
+ });
+ const liveAgentId = created.json?.agent?.id || created.json?.data?.id || created.json?.id;
+ check('agent created through the real API', (created.status === 200 || created.status === 201) && !!liveAgentId,
+ liveAgentId ? `agent ${liveAgentId}` : `status ${created.status}: ${created.text.slice(0, 200)}`);
+
+ if (liveAgentId) {
+ // Policy read: defaults visible before anything is set.
+ const got0 = await http.req('GET', `/api/agents/${liveAgentId}/solana/limits`);
+ check('GET limits returns the effective policy', got0.status === 200 && got0.json?.data?.limits?.frozen === false,
+ got0.status === 200 ? `defaults: frozen=${got0.json?.data?.limits?.frozen}` : `status ${got0.status}`);
+
+ // Kill switch over the live surface.
+ const csrf2 = await http.freshCsrf();
+ const put = await http.req('PUT', `/api/agents/${liveAgentId}/solana/limits`, {
+ body: { frozen: true, per_tx_usd: 5, daily_usd: 25, per_counterparty_daily_usd: 10 },
+ headers: { 'x-csrf-token': csrf2 },
+ });
+ check('PUT limits flips the kill switch + sets all three caps', put.status === 200
+ && put.json?.data?.limits?.frozen === true
+ && put.json?.data?.limits?.per_tx_usd === 5
+ && put.json?.data?.limits?.daily_usd === 25
+ && put.json?.data?.limits?.per_counterparty_daily_usd === 10,
+ put.status === 200 ? 'limits persisted and read back on the response' : `status ${put.status}: ${put.text.slice(0, 200)}`);
+
+ // The frozen agent must be unable to spend: drive a REAL reserve through
+ // the live meta (read back from the DB the server just wrote).
+ const { rows: [liveRow] } = await db.query('select meta from agent_identities where id = $1', [liveAgentId]);
+ const frozenAttempt = await callErr('reserveSpendUsd', {
+ agentId: liveAgentId, userId: null, meta: liveRow.meta, category: 'x402',
+ usdValue: 1, destination: PEER_A, network: 'mainnet', asset: 'USDC',
+ });
+ check('live-frozen agent is blocked at the reserve layer', frozenAttempt.thrown?.code === 'wallet_frozen',
+ frozenAttempt.thrown ? `${frozenAttempt.thrown.code}: ${frozenAttempt.thrown.message}` : 'ERROR: spend was allowed');
+
+ const csrf3 = await http.freshCsrf();
+ const unfreeze = await http.req('PUT', `/api/agents/${liveAgentId}/solana/limits`, {
+ body: { frozen: false }, headers: { 'x-csrf-token': csrf3 },
+ });
+ check('unfreeze over the live surface', unfreeze.status === 200 && unfreeze.json?.data?.limits?.frozen === false);
+
+ // Settle two real ledger payments for THIS agent so its receipts exist.
+ for (const [usd, dest, sig] of [[0.75, PEER_A, 'livesigA111'], [0.5, PEER_B, 'livesigB222']]) {
+ const r = await call('reserveSpendUsd', {
+ agentId: liveAgentId, userId: null, category: 'x402', usdValue: usd,
+ destination: dest, network: 'mainnet', asset: 'USDC',
+ rowMeta: { url: 'https://peer.example/x402', service: 'live-proof' },
+ });
+ if (!r.ok) throw new Error(`live-agent receipt reserve blocked: ${r.err?.message}`);
+ await confirm(r.out.reservationId, sig);
+ }
+
+ const custody = await http.req('GET', `/api/agents/${liveAgentId}/solana/custody?category=x402&limit=50`);
+ const items = custody.json?.data?.items || [];
+ const receipts = items.filter((e) => e.event_type === 'spend' && e.status === 'ok');
+ check('custody surface returns the agent payment receipts', custody.status === 200 && receipts.length === 2,
+ custody.status === 200
+ ? `${receipts.length} receipts: ${receipts.map((r) => `$${r.usd} -> ${String(r.destination).slice(0, 10)}… sig ${r.signature}`).join(' | ')}`
+ : `status ${custody.status}: ${custody.text.slice(0, 200)}`);
+ check('receipts carry counterparty + amount + signature + status',
+ receipts.every((r) => r.destination && r.usd > 0 && r.signature && r.status === 'ok'),
+ receipts.length ? 'every receipt fully attributed' : 'no receipts to check');
+
+ const economy = await http.req('GET', `/api/agents/${liveAgentId}/economy`);
+ const econ = economy.json;
+ const econReceipts = econ?.receipts || econ?.data?.receipts || [];
+ const outbound = econReceipts.filter((r) => r.direction === 'out');
+ check('economy surface shows spending + receipts for the agent',
+ economy.status === 200 && (econ?.spending?.x402?.count ?? econ?.data?.spending?.x402?.count) >= 2 && outbound.length >= 2,
+ economy.status === 200
+ ? `x402 spend count=${econ?.spending?.x402?.count ?? econ?.data?.spending?.x402?.count}, outbound receipts=${outbound.length}`
+ : `status ${economy.status}: ${economy.text.slice(0, 200)}`);
+
+ // Ownership gate: a second account must not read the first agent's receipts.
+ const http2 = makeHttp();
+ const reg2 = await http2.req('POST', '/api/auth/register', {
+ body: { email: `proof-stranger-${Date.now()}@proof.local`, password: 'proof-pass-12345', tosAccepted: true },
+ });
+ if (reg2.status === 200 || reg2.status === 201) {
+ const denied = await http2.req('GET', `/api/agents/${liveAgentId}/solana/custody`);
+ check('receipts are owner-only (stranger gets 403)', denied.status === 403, `status ${denied.status}`);
+ }
+ }
+ }
+
+ // ── transcript ───────────────────────────────────────────────────────────
+ console.log('\n══ transcript ══');
+ for (const r of results) console.log(` ${r.ok ? 'PASS' : 'FAIL'} ${r.name}${r.detail ? ` — ${r.detail}` : ''}`);
+ console.log(`\n${results.length - failed}/${results.length} checks passed`);
+ if (failed) {
+ console.error('PROOF FAILED');
+ process.exitCode = 1;
+ } else {
+ console.log('PROOF PASSED — every limit blocked its over-limit attempt, the kill switch halted spending, and receipts were queryable per agent on the live surface.');
+ }
+}
+
+async function setLimitsOn(db, agentId, limits) {
+ await db.query(
+ `update agent_identities set meta = jsonb_set(coalesce(meta,'{}'::jsonb), '{spend_limits}', $2::jsonb) where id = $1`,
+ [agentId, JSON.stringify(limits)],
+ );
+}
+
+try {
+ await main();
+} catch (e) {
+ console.error(`\nproof harness error: ${e?.stack || e}`);
+ process.exitCode = 1;
+} finally {
+ if (!KEEP) await shutdown();
+ else console.log(`\n--keep: left ${PG_CONTAINER} running on :${PG_PORT}`);
+}
diff --git a/scripts/cron03-probe.mjs b/scripts/cron03-probe.mjs
new file mode 100644
index 000000000..f77bad116
--- /dev/null
+++ b/scripts/cron03-probe.mjs
@@ -0,0 +1,85 @@
+// api-cron-03 probe: load each batch handler through its true import graph and
+// invoke it with synthetic req/res (the same wiring server/index.mjs uses).
+// CRON_SECRET is a session-local value so requireCron passes only when we present it.
+process.env.CRON_SECRET = 'cron03-audit-secret';
+process.env.DATABASE_URL = 'postgres://postgres:[email protected]:5545/cron03';
+// Point app origin at loopback so outbound HTTP (forge-smoke, forge-seed submits)
+// fails fast instead of hanging on real HTTPS, and keep every spend lane in its
+// clean-skip path. No lane is configured here, so no real spend can occur.
+process.env.APP_ORIGIN = 'http://127.0.0.1:9';
+
+const files = [
+ 'api/cron/forge-seed-cron.js',
+ 'api/cron/forge-smoke.js',
+ 'api/cron/forge-thumbnail-backfill.js',
+ 'api/cron/free-model-audit.js',
+ 'api/cron/garment-catalog-audit.js',
+ 'api/cron/garment-job-sweep.js',
+ 'api/cron/gcp-burn-report.js',
+ 'api/cron/gmgn-seed.js',
+ 'api/cron/gpu-keepwarm.js',
+ 'api/cron/intel-learn.js',
+];
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ _body: '',
+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },
+ writeHead(s, h) { this.statusCode = s; if (h) for (const [k, v] of Object.entries(h)) this.setHeader(k, v); return this; },
+ write(c) { this._body += c; },
+ end(c) { if (c) this._body += c; this._done(this); },
+ json(o) { this._body = JSON.stringify(o); this._done(this); },
+ };
+}
+function makeReq({ method = 'GET', url = '/', headers = {} } = {}) {
+ return {
+ method,
+ url,
+ headers,
+ socket: { remoteAddress: '127.0.0.1' },
+ on() {}, once() {}, removeListener() {},
+ };
+}
+
+async function call(handler, req) {
+ const res = makeRes();
+ const done = new Promise((resolve) => { res._done = resolve; });
+ try { await handler(req, res); } catch (err) {
+ res.statusCode = -1;
+ res._body = 'THROW: ' + (err?.message || String(err));
+ }
+ if (!res.headersSent && !res.writableEnded && res._done) {
+ // If handler never ended, wait briefly for async completion.
+ await Promise.race([done, new Promise((r) => setTimeout(r, 100))]);
+ }
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON */ }
+ return { status: res.statusCode, body: parsed ?? res._body.slice(0, 200) };
+}
+
+const secret = process.env.CRON_SECRET;
+for (const f of files) {
+ const mod = await import('/workspaces/three.ws/' + f);
+ const handler = mod.default;
+ const name = f.replace('api/cron/', '').replace('.js', '');
+
+ // 1. No auth -> must be 401 (fail-closed).
+ const noauth = await call(handler, makeReq({ url: `/api/cron/${name}` }));
+ // 2. Wrong secret -> 401.
+ const wrong = await call(handler, makeReq({ url: `/api/cron/${name}`, headers: { authorization: 'Bearer nope' } }));
+ // 3. Valid secret -> success path (200).
+ const ok = await call(handler, makeReq({ url: `/api/cron/${name}`, headers: { authorization: `Bearer ${secret}` } }));
+ // 4. Wrong method -> 405.
+ const m405 = await call(handler, makeReq({ method: 'DELETE', url: `/api/cron/${name}`, headers: { authorization: `Bearer ${secret}` } }));
+
+ const short = (r) => typeof r.body === 'string' ? r.body : JSON.stringify(r.body).slice(0, 160);
+ console.log(`\n=== ${name} ===`);
+ console.log(` noauth -> ${noauth.status} ${short(noauth)}`);
+ console.log(` wrongkey -> ${wrong.status} ${short(wrong)}`);
+ console.log(` authed -> ${ok.status} ${short(ok)}`);
+ console.log(` method -> ${m405.status} ${short(m405)}`);
+}
+process.exit(0);
diff --git a/scripts/verify-agent-manifest.mjs b/scripts/verify-agent-manifest.mjs
index 4e569bda9..f11110104 100644
--- a/scripts/verify-agent-manifest.mjs
+++ b/scripts/verify-agent-manifest.mjs
@@ -14,7 +14,7 @@
*
* Exit codes: 0 verified, 1 verification failed, 2 could not fetch or parse.
*
- * Spec: specs/AGENT_MANIFEST.md (§ Signed envelope). Docs: docs/agent-manifests.md.
+ * Spec: specs/AGENT_MANIFEST.md (§ Signed envelope). Docs: docs/agent-manifest.md.
*/
import { readFile } from 'node:fs/promises';
diff --git a/specs/OPEN_INFERENCE_PROTOCOL.md b/specs/OPEN_INFERENCE_PROTOCOL.md
new file mode 100644
index 000000000..44173fc42
--- /dev/null
+++ b/specs/OPEN_INFERENCE_PROTOCOL.md
@@ -0,0 +1,244 @@
+# Open Inference Protocol (OIN) v0.1
+
+An open, vendor-neutral wire protocol for agent inference: a requester hands a
+job to any compatible node (GPU or CPU), and the node returns a result it has
+cryptographically signed with an Ed25519 key. Anyone who holds the job envelope
+and the response can verify the result against the node's published public key,
+without trusting any intermediary. Inference decouples from any single
+provider: the platform's own workers, a third-party operator, and a hobby
+node all speak the same envelopes.
+
+The design starts from how three.ws's own GPU workers already receive jobs and
+return results (submit -> `202 { task_id }`, poll -> result URL, bearer auth on
+every route) and extends it with the two things a multi-operator network needs
+that a single-provider deployment did not: **capability advertisement** (so a
+requester can discover what a node can run and price it) and **signed
+responses** (so a result is attributable to a specific node key and cannot be
+forged or tampered with in transit).
+
+- Spec id: `oin/0.1`
+- Status: reference. One in-repo worker (`workers/stylize`) speaks it behind a
+ flag; the reference verifier is [`api/_lib/oin-verify.js`](../api/_lib/oin-verify.js).
+- Signature scheme: Ed25519 (RFC 8032), the same curve Solana accounts sign
+ with, so a node operator's existing Solana keypair doubles as its node key.
+
+## Terminology
+
+- **Requester** — the party that constructs and submits a job (the platform
+ API today; any marketplace contract tomorrow).
+- **Node** — any process that advertises capabilities, accepts job envelopes,
+ executes them, and returns signed responses.
+- **Verifier** — any third party (often the requester, but not necessarily)
+ that checks a signed response against the job envelope and the node's
+ advertised public key.
+
+## Transport
+
+OIN runs over plain HTTPS with JSON bodies. A node exposes:
+
+| Route | Auth | Purpose |
+|---|---|---|
+| `GET /.well-known/oin` | none | Capability advertisement (signed). |
+| `POST /oin/jobs` | bearer (optional) | Submit a job envelope. Returns `202`. |
+| `GET /oin/jobs/:id` | bearer (optional) | Poll a job. Returns the signed response when done. |
+
+Whether a node requires bearer auth on the job routes is a deployment choice;
+the advertisement declares it (`auth` field) so a requester knows before
+submitting. A node MAY also serve its own native routes alongside OIN (the
+reference worker keeps its pre-existing `/process` + `/tasks/:id` contract;
+OIN is additive, never a breaking change).
+
+## Canonical encoding
+
+Every hash and signature in OIN is computed over the **JCS canonical JSON**
+(RFC 8785) of the object being hashed, UTF-8 encoded. JCS is deterministic
+(key order sorted, no whitespace, minimal number encoding), so two
+implementations that parse the same JSON document always derive the same bytes
+to hash or sign. All digests are SHA-256 over the canonical bytes, hex-encoded
+lowercase with no prefix. The reference implementation provides the
+canonicalizer; requesters and verifiers SHOULD use a conforming RFC 8785
+implementation of their own.
+
+## Job envelope
+
+The envelope is everything the node needs to run the job and everything the
+verifier needs to bind the response to the job. Unknown top-level fields are
+allowed and ride along into the digest, so the format extends without a
+version bump.
+
+```jsonc
+{
+ "spec": "oin/0.1", // required, exact string
+ "job_id": "j_7f2c1d...", // required, requester-chosen unique id
+ "capability": "mesh.stylize", // required, one of the advertised keys
+ "created_at": "2026-08-12T00:00:00.000Z", // required, ISO 8601 UTC
+ "deadline": 1800, // optional, seconds after created_at
+ "input": { "model": "...", "data": "..." }, // required, capability-defined
+ "params": { /* ... */ }, // optional, capability-defined
+ "payment": { // optional, opaque to the node protocol
+ "scheme": "x402", "network": "solana", "receipt": "..."
+ },
+ "callback_url": "https://...", // optional push delivery; polling is the default
+ "requester": "did:...", // optional, for metering/attribution
+ "request_id": "req_..." // optional, opaque correlation id
+}
+```
+
+`input.model` names the model, filter, or engine within the capability
+(for `mesh.stylize`: `voxel`, `brick`, `voronoi`, or `lowpoly`). `input.data`
+carries the primary payload reference (an https URL in v0.1); everything else
+the capability needs lives in `params`.
+
+A node MUST reject an envelope whose `spec` it does not recognize with
+`400 { "error": "unsupported_spec" }`, and a `capability` it does not
+advertise with `400 { "error": "unsupported_capability" }`.
+
+## Capability advertisement
+
+`GET /.well-known/oin` returns the node's self-description. It is the only
+unauthenticated route and it is itself signed, so a requester that already
+trusts a node key out of band can pin it, and a directory service can crawl
+advertisements without credentialing.
+
+```jsonc
+{
+ "spec": "oin/0.1",
+ "node_id": "node_3f8a...", // stable operator-chosen id
+ "node_pubkey": "ed25519:AbC1...", // base64, 32-byte raw public key
+ "generated_at": "2026-08-12T00:00:00.000Z",
+ "capabilities": [
+ {
+ "key": "mesh.stylize",
+ "version": "0.1",
+ "models": ["voxel", "brick", "voronoi", "lowpoly"],
+ "max_input_bytes": 134217728,
+ "pricing": { "currency": "USDC", "unit": "job", "amount": "0.01" },
+ "sla": { "typical_seconds": 10 }
+ }
+ ],
+ "endpoints": {
+ "submit": "/oin/jobs",
+ "poll": "/oin/jobs/:id",
+ "health": "/health"
+ },
+ "auth": "bearer", // "bearer" or "none"
+ "signature": "base64..." // Ed25519 over canonical advertisement minus this field
+}
+```
+
+The `signature` is produced by deleting the `signature` field, canonicalizing
+the remaining object, and signing those bytes with the node key. A requester
+verifies it exactly like a response signature (rules below), with the
+advertisement itself as the payload.
+
+## Signed response format
+
+When a job reaches a terminal state (`done` or `failed`) the node produces a
+signed response envelope:
+
+```jsonc
+{
+ "spec": "oin/0.1",
+ "job_digest": "hex...", // SHA-256 over the canonical job envelope
+ "node_pubkey": "ed25519:AbC1...",
+ "completed_at": "2026-08-12T00:00:10.000Z",
+ "status": "done", // "done" | "failed"
+ "output": { // present on done
+ "url": "https://storage.googleapis.com/bucket/path.glb",
+ "sha256": "hex...", // digest of the bytes at `url`
+ "bytes": 123456
+ },
+ "usage": { "elapsed_ms": 9421, "units": 1 }, // optional metering
+ "error": { "code": "bad_input", "message": "..." }, // present on failed
+ "signature": "base64..." // Ed25519 over canonical response minus this field
+}
+```
+
+The response commits to the job only through `job_digest`; the job envelope
+itself travels out of band (the requester already has it). Signing a digest of
+the job instead of the job itself keeps the signature input small and lets a
+verifier that receives a job from a third party confirm it is the job the node
+actually answered.
+
+Failed jobs are signed too. A signed failure is evidence the node received the
+job and declined or could not complete it, which matters for settlement and
+reputation just as much as a signed success.
+
+## Verification rules
+
+A verifier accepts a signed response only when **all** of the following hold,
+checked in order; the first failure names the verdict:
+
+1. **Shape** — `spec` is `oin/0.1`; `job_digest`, `node_pubkey`,
+ `completed_at`, `status`, and `signature` are present; `status` is `done`
+ or `failed`; `done` responses carry `output` and `failed` responses carry
+ `error`. (`bad_shape`)
+2. **Job binding** — the verifier recomputes SHA-256 over the JCS-canonical
+ job envelope it holds and requires equality with `job_digest`.
+ (`job_digest_mismatch`)
+3. **Key** — `node_pubkey` parses as `ed25519:` followed by 32 bytes of
+ base64. If the verifier pins or looked up the node's advertisement, the key
+ MUST equal the advertised `node_pubkey`. (`bad_pubkey` / `untrusted_node`)
+4. **Signature** — removing `signature`, canonicalizing the remaining
+ response, and verifying the Ed25519 signature against the decoded public
+ key succeeds. (`bad_signature`)
+5. **Freshness** — `completed_at` parses as ISO 8601 and is not later than the
+ job's `deadline` (when the job declared one) and not more than 24 hours in
+ the future of the verifier's clock. (`stale_response` / `future_response`)
+6. **Output integrity** — for `done` responses, the bytes fetched from
+ `output.url` hash (SHA-256, lowercase hex) to `output.sha256` and their
+ length equals `output.bytes`. (`output_digest_mismatch`) A verifier that
+ only checks the envelope (never fetches the artifact) MAY defer this rule
+ and report `verified_unfetched_output`.
+
+A response that passes rules 1–5 is `verified`; rule 6 upgrades it to
+`verified_with_output`. No verdict short of `verified` entitles the node to
+payment.
+
+### Reference verifier
+
+[`api/_lib/oin-verify.js`](../api/_lib/oin-verify.js) implements rules 1–5 in
+dependency-free Node (Ed25519 via `crypto.createVerify`), plus an opt-in
+`verifyOutput()` for rule 6. It is the conformance target for third-party
+verifiers.
+
+## Reference worker
+
+`workers/stylize` (the platform's CPU mesh-stylization worker) speaks OIN
+behind a flag:
+
+- `OIN_ENABLED=true` mounts `GET /.well-known/oin`, `POST /oin/jobs`, and
+ `GET /oin/jobs/:id` next to the native routes.
+- `OIN_SIGNING_KEY` holds the node's Ed25519 secret key (base64, 32-byte seed
+ or 64-byte expanded key). Unset with the flag on: the worker refuses to
+ start, so a node can never advertise a key it cannot sign with.
+- With the flag off the worker is byte-for-byte its pre-OIN self.
+
+Job execution is the same pipeline the native `/process` route runs; OIN only
+changes the envelope in and the signature out. That is the point: the protocol
+wraps existing capability instead of replacing it.
+
+## Security considerations
+
+- **Replay.** `job_digest` binds the response to one envelope; a requester
+ that reuses a `job_id` with different inputs gets a different digest and a
+ failed rule 2. Nodes SHOULD reject a second submission of a `job_id` they
+ have already answered with `409 { "error": "duplicate_job" }`.
+- **Key custody.** The signing key lives only in the node's environment. An
+ advertisement leak is harmless (it is public data); a key leak is fatal to
+ that node's reputation, and rotation is a new advertisement plus a registry
+ update wherever the old key was pinned.
+- **Output fetch.** Rule 6 fetches a node-supplied URL; verifiers MUST fetch
+ it with SSRF guards (https-only, private-IP rejection, size cap) of the kind
+ the workers themselves use.
+- **No transport trust assumed.** TLS protects the pipe; the signature protects
+ the payload. A response proxied through an untrusted relay still verifies.
+
+## Out of scope for v0.1
+
+- On-chain settlement and receipts (Phase 4 roadmap item; `payment` is the
+ reserved hook).
+- Streaming responses and chunked artifact proofs.
+- Multi-node redundancy (the same job run by N nodes with cross-checks).
+- Anything EVM-specific: the signature curve is Ed25519; an EVM-flavored
+ `node_pubkey` namespace is a future spec revision, never a blocker here.
diff --git a/tests/agent-ui-sdk-core.test.js b/tests/agent-ui-sdk-core.test.js
new file mode 100644
index 000000000..3b866b35f
--- /dev/null
+++ b/tests/agent-ui-sdk-core.test.js
@@ -0,0 +1,137 @@
+// Core-path coverage for @three-ws/agent-ui (agent-ui-sdk/). The full handle
+// (createAgentUI) needs WebGL and a hosted GLB, so it is exercised by the
+// browser demos; here we prove the deterministic core the whole overlay is
+// built on: the export surface the README documents, the RAF tween engine every
+// behavior runs through, and the non-repeating random picker.
+import { describe, it, expect } from 'vitest';
+
+import * as api from '../agent-ui-sdk/src/index.js';
+
+// The README's documented standalone-function list. If a documented export ever
+// goes missing, the public API silently regresses for every consumer, so pin it.
+const DOCUMENTED = [
+ 'createAgentUI',
+ 'createRenderer',
+ 'loadAvatar',
+ 'createAnimator',
+ 'lockRootMotion',
+ 'worldOfElement',
+ 'moveTo',
+ 'lookAtScreenX',
+ 'faceFront',
+ 'walkTo',
+ 'standOn',
+ 'fallOnto',
+ 'runOff',
+ 'interceptNavigation',
+ 'createRandomPicker',
+ 'caretScreenX',
+ 'startCaretTracking',
+ 'dust',
+ 'impactPulse',
+ 'proximityShadow',
+ 'scan',
+];
+
+describe('@three-ws/agent-ui export surface', () => {
+ it('exports every function the README documents', () => {
+ for (const name of DOCUMENTED) {
+ expect(typeof api[name], name).toBe('function');
+ }
+ });
+
+ it('exports createAgentUI as the headline entry', () => {
+ expect(typeof api.createAgentUI).toBe('function');
+ });
+});
+
+describe('createRandomPicker', () => {
+ it('returns null for an empty pool and the only item for a singleton', () => {
+ expect(api.createRandomPicker([])()).toBeNull();
+ expect(api.createRandomPicker(['only'])()).toBe('only');
+ });
+
+ it('never repeats the same pick twice in a row', () => {
+ const pick = api.createRandomPicker(['nod', 'shrug', 'wave']);
+ let prev = pick();
+ for (let i = 0; i < 50; i++) {
+ const next = pick();
+ expect(['nod', 'shrug', 'wave']).toContain(next);
+ expect(next).not.toBe(prev);
+ prev = next;
+ }
+ });
+});
+
+// The tween engine drives every movement/FX behavior, so its easing and
+// completion semantics are the real core path. requestAnimationFrame and
+// performance.now are stubbed per-test with a controllable clock.
+describe('tween engine', () => {
+ it('runs to completion, easing each frame, and resolves', async () => {
+ const { tween, smoothstep, easeInQuad, easeOutCubic } = await import('../agent-ui-sdk/src/tween.js');
+
+ // Easing identities the behaviors rely on.
+ expect(smoothstep(0)).toBe(0);
+ expect(smoothstep(1)).toBe(1);
+ expect(easeInQuad(0)).toBe(0);
+ expect(easeOutCubic(1)).toBe(1);
+ expect(easeOutCubic(0)).toBe(0);
+
+ // Drive RAF manually over a 100ms tween.
+ const callbacks = [];
+ let clock = 0;
+ const raf = globalThis.requestAnimationFrame;
+ const perf = globalThis.performance;
+ globalThis.requestAnimationFrame = (cb) => { callbacks.push(cb); return callbacks.length; };
+ globalThis.performance = { now: () => clock };
+
+ const frames = [];
+ let completed = false;
+ const p = tween({
+ duration: 100,
+ onUpdate: (e) => frames.push(e),
+ onComplete: () => { completed = true; },
+ });
+ // First frame fires synchronously at t=0.
+ expect(frames.length).toBe(1);
+
+ clock = 50; callbacks.shift()(50); // t=0.5
+ clock = 100; callbacks.shift()(100); // t=1 -> completes
+ await p;
+
+ expect(completed).toBe(true);
+ expect(frames[0]).toBe(0);
+ expect(frames[frames.length - 1]).toBe(1);
+ // Smoothstep midpoint eases to exactly 0.5.
+ expect(frames[1]).toBeCloseTo(0.5, 5);
+
+ globalThis.requestAnimationFrame = raf;
+ globalThis.performance = perf;
+ });
+
+ it('cancel() stops the tween and never resolves late', async () => {
+ const { tweenProp } = await import('../agent-ui-sdk/src/tween.js');
+
+ const callbacks = [];
+ let clock = 0;
+ const raf = globalThis.requestAnimationFrame;
+ const caf = globalThis.cancelAnimationFrame;
+ const perf = globalThis.performance;
+ globalThis.requestAnimationFrame = (cb) => { callbacks.push(cb); return callbacks.length; };
+ globalThis.cancelAnimationFrame = () => {};
+ globalThis.performance = { now: () => clock };
+
+ const obj = { x: 0 };
+ const p = tweenProp(obj, 'x', 10, { duration: 100 });
+ p.cancel();
+ clock = 100;
+ // No queued frame should advance the value after cancel.
+ while (callbacks.length) callbacks.shift()(100);
+
+ expect(obj.x).toBe(0);
+
+ globalThis.requestAnimationFrame = raf;
+ globalThis.cancelAnimationFrame = caf;
+ globalThis.performance = perf;
+ });
+});
diff --git a/tests/agent-ui-sdk.test.js b/tests/agent-ui-sdk.test.js
new file mode 100644
index 000000000..983925de6
--- /dev/null
+++ b/tests/agent-ui-sdk.test.js
@@ -0,0 +1,267 @@
+/**
+ * @three-ws/agent-ui — core-path tests.
+ *
+ * Proves the main export surface is real:
+ * 1. The documented exports all exist on the source entry point.
+ * 2. The animation controller (createAnimator) drives REAL clips parsed
+ * from the production clip JSONs in public/animations/clips/.
+ * 3. The DOM-anchor math (worldOfElement), movement tweens (moveTo,
+ * lookAtScreenX, faceFront, standOn), the non-repeating picker, and the
+ * root-motion lock behave as the README documents.
+ * 4. The published bundle artifact (dist/index.mjs) builds from this
+ * worktree and exposes the same API.
+ *
+ * Node has no requestAnimationFrame; a setTimeout-backed shim stands in for
+ * the browser clock so the tween loop runs under test.
+ */
+
+import { readFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, it, expect, beforeAll } from 'vitest';
+import * as THREE from 'three';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = join(here, '..');
+const sdkDir = join(repoRoot, 'agent-ui-sdk');
+
+if (typeof globalThis.requestAnimationFrame !== 'function') {
+ globalThis.requestAnimationFrame = (cb) => setTimeout(() => cb(performance.now()), 1);
+ globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
+}
+
+const sdk = await import(join(sdkDir, 'src/index.js'));
+
+const DOCUMENTED_EXPORTS = [
+ 'createAgentUI',
+ 'createRenderer',
+ 'loadAvatar',
+ 'createAnimator',
+ 'lockRootMotion',
+ 'worldOfElement',
+ 'moveTo',
+ 'lookAtScreenX',
+ 'faceFront',
+ 'walkTo',
+ 'standOn',
+ 'fallOnto',
+ 'runOff',
+ 'interceptNavigation',
+ 'createRandomPicker',
+ 'caretScreenX',
+ 'startCaretTracking',
+ 'dust',
+ 'impactPulse',
+ 'proximityShadow',
+ 'scan',
+];
+
+function loadClipJson(name) {
+ const raw = readFileSync(join(repoRoot, 'public/animations/clips', `${name}.json`), 'utf8');
+ return THREE.AnimationClip.parse(JSON.parse(raw));
+}
+
+// Build an object hierarchy whose node names match the clip's track targets,
+// so AnimationMixer property bindings resolve against real nodes.
+function objectForClips(clips) {
+ const root = new THREE.Object3D();
+ const seen = new Set();
+ for (const clip of Object.values(clips)) {
+ for (const track of clip.tracks) {
+ const nodeName = track.name.split('.')[0];
+ if (seen.has(nodeName)) continue;
+ seen.add(nodeName);
+ const node = new THREE.Object3D();
+ node.name = nodeName;
+ root.add(node);
+ }
+ }
+ return root;
+}
+
+describe('entry point', () => {
+ it('exports every function the README documents', () => {
+ for (const name of DOCUMENTED_EXPORTS) {
+ expect(typeof sdk[name], name).toBe('function');
+ }
+ });
+});
+
+describe('createAnimator with real production clips', () => {
+ let clips;
+ beforeAll(() => {
+ clips = { idle: loadClipJson('idle'), walk: loadClipJson('walk') };
+ });
+
+ it('parses real clip JSONs into AnimationClips with positive durations', () => {
+ expect(clips.idle).toBeInstanceOf(THREE.AnimationClip);
+ expect(clips.idle.duration).toBeGreaterThan(0.5);
+ expect(clips.walk.duration).toBeGreaterThan(0.2);
+ });
+
+ it('play() switches currentName and clipDuration() reports the real length', () => {
+ const animator = sdk.createAnimator({ object: objectForClips(clips), clips });
+ animator.play('idle', { loop: true });
+ expect(animator.currentName).toBe('idle');
+ expect(animator.clipDuration('idle')).toBeCloseTo(clips.idle.duration, 5);
+ expect(animator.clipDuration('walk')).toBeCloseTo(clips.walk.duration, 5);
+ expect(animator.clipDuration('nope')).toBe(1.0);
+
+ animator.play('walk', { loop: true });
+ expect(animator.currentName).toBe('walk');
+ });
+
+ it('a non-looping play fires onComplete after the clip finishes', () => {
+ const animator = sdk.createAnimator({ object: objectForClips(clips), clips });
+ let completed = false;
+ animator.play('walk', { loop: false, onComplete: () => { completed = true; } });
+ animator.update(clips.walk.duration + 0.05);
+ expect(completed).toBe(true);
+ });
+
+ it('hold clamps the final frame instead of resetting', () => {
+ const animator = sdk.createAnimator({ object: objectForClips(clips), clips });
+ animator.play('walk', { loop: false, hold: true });
+ expect(animator.actions.walk.clampWhenFinished).toBe(true);
+ });
+
+ it('an unknown clip warns instead of throwing', () => {
+ const animator = sdk.createAnimator({ object: objectForClips(clips), clips });
+ expect(() => animator.play('ghost')).not.toThrow();
+ expect(animator.currentName).toBe(null);
+ });
+});
+
+describe('lockRootMotion', () => {
+ it('clamps the root bone to rest across renders and unlock restores', () => {
+ const rootBone = new THREE.Object3D();
+ rootBone.name = 'Hips';
+ rootBone.position.set(1, 2, 3);
+ const renders = [];
+ const renderer = { render: (s, c) => renders.push([s, c]) };
+
+ const unlock = sdk.lockRootMotion(renderer, rootBone);
+ rootBone.position.set(9, 9, 9); // simulated baked root translation
+ renderer.render('scene', 'camera');
+ expect(rootBone.position.x).toBe(1);
+ expect(rootBone.position.y).toBe(2);
+ expect(renders).toHaveLength(1);
+
+ unlock();
+ rootBone.position.set(7, 7, 7);
+ renderer.render('scene', 'camera');
+ expect(rootBone.position.x).toBe(7); // no longer clamped
+ });
+
+ it('is a no-op disposer when there is no root bone', () => {
+ const renderer = { render() {} };
+ const unlock = sdk.lockRootMotion(renderer, null);
+ expect(() => unlock()).not.toThrow();
+ });
+});
+
+describe('worldOfElement anchors', () => {
+ const rect = { left: 100, top: 50, width: 200, height: 40, right: 300, bottom: 90 };
+ const el = { getBoundingClientRect: () => rect };
+ const agent = { domToWorld: (x, y) => ({ x, y }) };
+
+ it.each([
+ ['top-left', 100, 50],
+ ['top-right', 300, 50],
+ ['top-center', 200, 50],
+ ['center', 200, 70],
+ ['bottom-center', 200, 90],
+ ['left-of', 100, 70],
+ ['right-of', 300, 70],
+ ])('anchor %s maps the rect correctly', (anchor, x, y) => {
+ expect(sdk.worldOfElement(el, agent, { anchor })).toEqual({ x, y });
+ });
+
+ it('defaults to top-center and applies pixel offsets', () => {
+ expect(sdk.worldOfElement(el, agent)).toEqual({ x: 200, y: 50 });
+ expect(sdk.worldOfElement(el, agent, { offsetX: 10, offsetY: -5 })).toEqual({ x: 210, y: 45 });
+ });
+});
+
+describe('movement behaviors', () => {
+ function stubAgent() {
+ const played = [];
+ return {
+ played,
+ avatar: { position: { x: 0, y: 0, set(x, y) { this.x = x; this.y = y; } }, rotation: { y: 0 } },
+ pixelsPerUnit: 120,
+ play: (name, o) => played.push([name, o]),
+ domToWorld: (x, y) => ({ x, y }),
+ worldToScreen: (x, y) => ({ x, y }),
+ };
+ }
+
+ it('moveTo tweens the avatar to the target and resolves', async () => {
+ const agent = stubAgent();
+ await sdk.moveTo(agent, { x: 5, y: 3 }, { duration: 5 });
+ expect(agent.avatar.position.x).toBeCloseTo(5);
+ expect(agent.avatar.position.y).toBeCloseTo(3);
+ });
+
+ it('moveTo resolves immediately with no avatar', async () => {
+ await expect(sdk.moveTo({ avatar: null }, { x: 1, y: 1 }, { duration: 5 })).resolves.toBeUndefined();
+ });
+
+ it('standOn parks the avatar on the element and plays the idle clip', () => {
+ const agent = stubAgent();
+ const el = { getBoundingClientRect: () => ({ left: 0, top: 0, width: 120, height: 60, right: 120, bottom: 60 }) };
+ sdk.standOn(agent, el);
+ expect(agent.avatar.position.x).toBe(60); // top-center of the rect
+ expect(agent.avatar.position.y).toBe(0);
+ expect(agent.played).toEqual([['idle', { loop: true }]]);
+ });
+
+ it('walkTo plays the walk clip, moves, and leaves walk playing', async () => {
+ const agent = stubAgent();
+ const el = { getBoundingClientRect: () => ({ left: 200, top: 100, width: 40, height: 20, right: 240, bottom: 120 }) };
+ await sdk.walkTo(agent, el, { duration: 5 });
+ expect(agent.played[0]).toEqual(['walk', { loop: true }]);
+ expect(agent.avatar.position.x).toBe(220);
+ expect(agent.avatar.position.y).toBe(100);
+ });
+
+ it('lookAtScreenX clamps yaw to maxYaw and faceFront returns to zero', async () => {
+ const agent = stubAgent();
+ await sdk.lookAtScreenX(agent, 100000, { duration: 5 });
+ expect(agent.avatar.rotation.y).toBeCloseTo(0.45); // clamped at default maxYaw
+ await sdk.lookAtScreenX(agent, -100000, { duration: 5 });
+ expect(agent.avatar.rotation.y).toBeCloseTo(-0.45);
+ await sdk.faceFront(agent, { duration: 5 });
+ expect(agent.avatar.rotation.y).toBeCloseTo(0);
+ });
+});
+
+describe('createRandomPicker', () => {
+ it('never repeats the previous pick', () => {
+ const pick = sdk.createRandomPicker(['nod', 'shrug', 'wave']);
+ let last = pick();
+ for (let i = 0; i < 200; i++) {
+ const next = pick();
+ expect(['nod', 'shrug', 'wave']).toContain(next);
+ expect(next).not.toBe(last);
+ last = next;
+ }
+ });
+
+ it('handles empty and single-element pools', () => {
+ expect(sdk.createRandomPicker([])()).toBe(null);
+ expect(sdk.createRandomPicker(['only'])()).toBe('only');
+ });
+});
+
+describe('bundle artifact', () => {
+ it('builds via the package build script and exports the documented API', () => {
+ execFileSync(process.execPath, [join(sdkDir, 'build.mjs')], { cwd: sdkDir, stdio: 'pipe' });
+ return import(join(sdkDir, 'dist/index.mjs')).then((bundle) => {
+ for (const name of DOCUMENTED_EXPORTS) {
+ expect(typeof bundle[name], name).toBe('function');
+ }
+ });
+ });
+});
diff --git a/tests/api/draft-mint.test.js b/tests/api/draft-mint.test.js
new file mode 100644
index 000000000..ba0f3ba3a
--- /dev/null
+++ b/tests/api/draft-mint.test.js
@@ -0,0 +1,145 @@
+// Unit tests for the draft agent mint orchestration (api/_lib/draft-mint.js):
+// flag parsing, idempotency, the Solana-first leg, the flagged ERC-8004 EVM
+// leg, and the best-effort avatar stamp. All chain/storage boundaries are
+// injected fakes; no network, no chain, no R2.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+vi.mock('../../api/_lib/agent-identity.js', () => ({
+ resolveOrCreateAgentForAvatar: vi.fn(async () => null),
+}));
+
+const {
+ mintDraftAgentIdentity,
+ resolveDraftMintNetwork,
+ resolveDraftMintEvm,
+} = await import('../../api/_lib/draft-mint.js');
+
+function makeDeps(overrides = {}) {
+ return {
+ resolveAgent: vi.fn(async () => ({ id: 'agent-1', name: 'Me' })),
+ loadAgentContext: vi.fn(async () => ({
+ id: 'agent-1',
+ user_id: 'u1',
+ name: 'Me',
+ description: null,
+ meta: {},
+ avatar_id: 'avatar-1',
+ thumbnail_key: 'u/u1/a/thumb.png',
+ storage_key: 'u/u1/a/m.glb',
+ })),
+ solanaMint: vi.fn(async () => ({
+ status: 'minted',
+ network: 'devnet',
+ asset: 'Asset111',
+ signature: 'Sig111',
+ collection: 'Col111',
+ })),
+ evmMint: vi.fn(async () => ({ status: 'dry_run', chainId: 84532 })),
+ persistAvatarDraft: vi.fn(async () => {}),
+ network: 'devnet',
+ evm: { enabled: false, chainId: 84532 },
+ ...overrides,
+ };
+}
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('resolveDraftMintNetwork', () => {
+ it('defaults to devnet (the automated proof path)', () => {
+ expect(resolveDraftMintNetwork({})).toBe('devnet');
+ });
+ it('only activates mainnet on an explicit opt-in', () => {
+ expect(resolveDraftMintNetwork({ DRAFT_AGENT_MINT_NETWORK: 'mainnet' })).toBe('mainnet');
+ expect(resolveDraftMintNetwork({ DRAFT_AGENT_MINT_NETWORK: 'MAINNET' })).toBe('mainnet');
+ expect(resolveDraftMintNetwork({ DRAFT_AGENT_MINT_NETWORK: 'prod' })).toBe('devnet');
+ });
+ it('honours the off switch', () => {
+ expect(resolveDraftMintNetwork({ DRAFT_AGENT_MINT_NETWORK: 'off' })).toBe('off');
+ expect(resolveDraftMintNetwork({ DRAFT_AGENT_MINT_NETWORK: '0' })).toBe('off');
+ });
+});
+
+describe('resolveDraftMintEvm', () => {
+ it('is disabled by default and targets Base Sepolia', () => {
+ expect(resolveDraftMintEvm({})).toEqual({ enabled: false, chainId: 84532 });
+ });
+ it('enables with a truthy flag and honours a chain override', () => {
+ expect(
+ resolveDraftMintEvm({ DRAFT_AGENT_MINT_EVM_ENABLED: '1', DRAFT_AGENT_MINT_EVM_CHAIN_ID: '11155111' }),
+ ).toEqual({ enabled: true, chainId: 11155111 });
+ });
+});
+
+describe('mintDraftAgentIdentity', () => {
+ it('returns no_agent when the avatar cannot resolve to an identity', async () => {
+ const deps = makeDeps({ resolveAgent: vi.fn(async () => null) });
+ const out = await mintDraftAgentIdentity({ userId: 'u1', avatarId: 'a1' }, deps);
+ expect(out.status).toBe('no_agent');
+ expect(deps.solanaMint).not.toHaveBeenCalled();
+ expect(deps.persistAvatarDraft).not.toHaveBeenCalled();
+ });
+
+ it('mints the Solana draft on devnet by default and stamps the avatar', async () => {
+ const deps = makeDeps();
+ const out = await mintDraftAgentIdentity({ userId: 'u1', avatarId: 'a1', jobId: 'j1' }, deps);
+ expect(out.status).toBe('ok');
+ expect(out.agentId).toBe('agent-1');
+ expect(deps.solanaMint).toHaveBeenCalledOnce();
+ expect(deps.solanaMint.mock.calls[0][0].network).toBe('devnet');
+ expect(out.solana.status).toBe('minted');
+ // EVM leg stays dark without its flag.
+ expect(deps.evmMint).not.toHaveBeenCalled();
+ expect(out.evm).toBeNull();
+ expect(deps.persistAvatarDraft).toHaveBeenCalledOnce();
+ const stamp = deps.persistAvatarDraft.mock.calls[0][0];
+ expect(stamp.avatarId).toBe('a1');
+ expect(stamp.jobId).toBe('j1');
+ expect(stamp.solana.signature).toBe('Sig111');
+ });
+
+ it('never touches a chain when the network flag is off', async () => {
+ const deps = makeDeps({ network: 'off' });
+ const out = await mintDraftAgentIdentity({ userId: 'u1', avatarId: 'a1' }, deps);
+ expect(out.status).toBe('ok');
+ expect(deps.solanaMint).not.toHaveBeenCalled();
+ expect(out.solana).toBeNull();
+ expect(deps.persistAvatarDraft).not.toHaveBeenCalled();
+ });
+
+ it('passes mainnet through unchanged when explicitly requested', async () => {
+ const deps = makeDeps({ network: 'mainnet' });
+ await mintDraftAgentIdentity({ userId: 'u1', avatarId: 'a1' }, deps);
+ expect(deps.solanaMint.mock.calls[0][0].network).toBe('mainnet');
+ });
+
+ it('runs the EVM leg only behind its flag', async () => {
+ const deps = makeDeps({ evm: { enabled: true, chainId: 84532 } });
+ const out = await mintDraftAgentIdentity({ userId: 'u1', avatarId: 'a1' }, deps);
+ expect(deps.evmMint).toHaveBeenCalledOnce();
+ expect(deps.evmMint.mock.calls[0][0].chainId).toBe(84532);
+ expect(out.evm.status).toBe('dry_run');
+ });
+
+ it('does not stamp the avatar when the Solana leg skipped (no authority)', async () => {
+ const deps = makeDeps({
+ solanaMint: vi.fn(async () => ({ status: 'skipped', reason: 'authority_unconfigured', network: 'devnet' })),
+ });
+ const out = await mintDraftAgentIdentity({ userId: 'u1', avatarId: 'a1' }, deps);
+ expect(out.solana.status).toBe('skipped');
+ expect(deps.persistAvatarDraft).not.toHaveBeenCalled();
+ });
+
+ it('a stamp failure is absorbed (mint result already stands)', async () => {
+ const deps = makeDeps({
+ persistAvatarDraft: vi.fn(async () => { throw new Error('db down'); }),
+ });
+ const out = await mintDraftAgentIdentity({ userId: 'u1', avatarId: 'a1' }, deps);
+ expect(out.solana.status).toBe('minted');
+ });
+});
diff --git a/tests/api/reconstruct-finalize.test.js b/tests/api/reconstruct-finalize.test.js
index cdd562aed..a546e0cf5 100644
--- a/tests/api/reconstruct-finalize.test.js
+++ b/tests/api/reconstruct-finalize.test.js
@@ -37,6 +37,14 @@ vi.mock('../../api/_lib/forge-store.js', () => ({
registerReconstructionCreation: (...a) => registerReconstructionCreationMock(...a),
}));
+// Roadmap Phase 1 draft mint fires on every materialize; mocked here so the
+// finalize control flow is what's under test (the mint orchestration itself is
+// covered by tests/api/draft-mint.test.js).
+const mintDraftAgentIdentityMock = vi.fn(async () => ({ status: 'ok' }));
+vi.mock('../../api/_lib/draft-mint.js', () => ({
+ mintDraftAgentIdentity: (...a) => mintDraftAgentIdentityMock(...a),
+}));
+
const providerMock = { name: 'replicate', instance: null };
vi.mock('../../api/_lib/regen-provider.js', () => ({
getRegenProvider: async () => providerMock,
@@ -132,6 +140,21 @@ describe('finalizeReconstructStage', () => {
const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });
expect(out).toEqual({ status: 'done', resultAvatarId: 'avatar-1' });
});
+
+ it('fires the draft agent mint for the delivered avatar', async () => {
+ inspectGlbMock.mockReturnValue(RIGGED);
+ const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });
+ expect(out.status).toBe('done');
+ expect(mintDraftAgentIdentityMock).toHaveBeenCalledOnce();
+ expect(mintDraftAgentIdentityMock.mock.calls[0][0]).toEqual({ userId: 'u1', avatarId: 'avatar-1', jobId: 'j1' });
+ });
+
+ it('still delivers the avatar when the draft mint throws', async () => {
+ inspectGlbMock.mockReturnValue(RIGGED);
+ mintDraftAgentIdentityMock.mockRejectedValueOnce(new Error('mint down'));
+ const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });
+ expect(out).toEqual({ status: 'done', resultAvatarId: 'avatar-1' });
+ });
});
describe('pollRiggingStage', () => {
diff --git a/tests/oin-verify.test.js b/tests/oin-verify.test.js
new file mode 100644
index 000000000..ca8268f42
--- /dev/null
+++ b/tests/oin-verify.test.js
@@ -0,0 +1,265 @@
+// Tests for the OIN v0.1 verifier: specs/OPEN_INFERENCE_PROTOCOL.md rules 1-6.
+// Every rule gets a happy path and a named-verdict failure path; the signing
+// helpers double as the node side of the loop, so these tests prove the spec's
+// reference implementation round-trips.
+
+import { describe, it, expect } from 'vitest';
+import { createHash, createPublicKey, generateKeyPairSync, sign as cryptoSign, verify as cryptoVerifyRaw } from 'node:crypto';
+import {
+ canonicalize,
+ digestJob,
+ pubkeyB64FromSecret,
+ signAdvertisement,
+ signResponse,
+ verifyOutput,
+ verifyResponse,
+} from '../api/_lib/oin-verify.js';
+
+// Deterministic Ed25519 seed (32 bytes of 0x07) so keys in this file are stable.
+const SEED_B64 = Buffer.alloc(32, 7).toString('base64');
+const OTHER_SEED_B64 = Buffer.alloc(32, 9).toString('base64');
+const NODE_PUBKEY = `ed25519:${pubkeyB64FromSecret(SEED_B64)}`;
+
+function makeJob(overrides = {}) {
+ return {
+ spec: 'oin/0.1',
+ job_id: 'j_test_0001',
+ capability: 'mesh.stylize',
+ created_at: '2026-08-12T00:00:00.000Z',
+ deadline: 1800,
+ input: { model: 'voxel', data: 'https://example.com/box.glb' },
+ params: { resolution: 16, output_format: 'glb' },
+ ...overrides,
+ };
+}
+
+function makeSignedResponse(job, overrides = {}) {
+ const unsigned = {
+ spec: 'oin/0.1',
+ job_digest: digestJob(job),
+ node_pubkey: NODE_PUBKEY,
+ completed_at: '2026-08-12T00:00:10.000Z',
+ status: 'done',
+ output: {
+ url: 'https://storage.googleapis.com/bucket/oin/job.glb',
+ sha256: 'a'.repeat(64),
+ bytes: 1234,
+ },
+ usage: { elapsed_ms: 9500, units: 1 },
+ ...overrides,
+ };
+ return signResponse(unsigned, SEED_B64);
+}
+
+describe('canonicalize (RFC 8785 JCS)', () => {
+ it('sorts object keys and drops whitespace', () => {
+ expect(canonicalize({ b: 1, a: { d: [true, null], c: 'x' } }))
+ .toBe('{"a":{"c":"x","d":[true,null]},"b":1}');
+ });
+
+ it('serializes numbers with ECMAScript toString semantics', () => {
+ expect(canonicalize({ n: 1e21 })).toBe('{"n":1e+21}');
+ expect(canonicalize({ n: -0 })).toBe('{"n":0}');
+ expect(canonicalize({ n: 3.5 })).toBe('{"n":3.5}');
+ });
+
+ it('rejects non-finite numbers', () => {
+ expect(() => canonicalize({ n: NaN })).toThrow(TypeError);
+ expect(() => canonicalize({ n: Infinity })).toThrow(TypeError);
+ });
+
+ it('is stable across key insertion order (same digest for reordered envelopes)', () => {
+ const a = digestJob(makeJob());
+ const shuffled = makeJob();
+ const reordered = {
+ params: shuffled.params,
+ input: shuffled.input,
+ created_at: shuffled.created_at,
+ deadline: shuffled.deadline,
+ capability: shuffled.capability,
+ job_id: shuffled.job_id,
+ spec: shuffled.spec,
+ };
+ expect(digestJob(reordered)).toBe(a);
+ });
+});
+
+describe('verifyResponse', () => {
+ it('accepts a well-formed signed response (verified)', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(job);
+ const out = verifyResponse(job, res);
+ expect(out.ok).toBe(true);
+ expect(out.verdict).toBe('verified');
+ expect(out.nodePubkey).toBe(NODE_PUBKEY);
+ });
+
+ it('round-trips with Node-generated Ed25519 keys (interop with stock keygen)', () => {
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
+ const spki = publicKey.export({ format: 'der', type: 'spki' });
+ const pubField = `ed25519:${Buffer.from(spki).subarray(-32).toString('base64')}`;
+ const job = makeJob();
+ const unsigned = {
+ spec: 'oin/0.1',
+ job_digest: digestJob(job),
+ node_pubkey: pubField,
+ completed_at: '2026-08-12T00:00:10.000Z',
+ status: 'failed',
+ error: { code: 'bad_input', message: 'nope' },
+ };
+ const bytes = Buffer.from(canonicalize(unsigned), 'utf8');
+ const signature = cryptoSign(null, bytes, privateKey).toString('base64');
+ const out = verifyResponse(job, { ...unsigned, signature });
+ expect(out.ok).toBe(true);
+ expect(out.status).toBe('failed');
+ });
+
+ it('bad_shape: wrong spec', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(job, { spec: 'oin/9.9' });
+ expect(verifyResponse(job, res).verdict).toBe('bad_shape');
+ });
+
+ it('bad_shape: missing signature', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(job);
+ delete res.signature;
+ expect(verifyResponse(job, res).verdict).toBe('bad_shape');
+ });
+
+ it('bad_shape: unknown status', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(job, { status: 'running' });
+ expect(verifyResponse(job, res).verdict).toBe('bad_shape');
+ });
+
+ it('job_digest_mismatch: response answers a different job', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(makeJob({ job_id: 'j_other' }));
+ expect(verifyResponse(job, res).verdict).toBe('job_digest_mismatch');
+ });
+
+ it('bad_pubkey: malformed node_pubkey', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(job);
+ // Re-sign is impossible without a parseable key; corrupt after signing and
+ // expect the key parse to fail before signature verification runs.
+ res.node_pubkey = 'secp256k1:AAAA';
+ expect(verifyResponse(job, res).verdict).toBe('bad_pubkey');
+ });
+
+ it('untrusted_node: key differs from the pinned advertisement key', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(job);
+ const out = verifyResponse(job, res, { expectedPubkey: `ed25519:${pubkeyB64FromSecret(OTHER_SEED_B64)}` });
+ expect(out.verdict).toBe('untrusted_node');
+ });
+
+ it('bad_signature: tampered output after signing', () => {
+ const job = makeJob();
+ const res = makeSignedResponse(job);
+ res.output = { ...res.output, bytes: 9999 };
+ expect(verifyResponse(job, res).verdict).toBe('bad_signature');
+ });
+
+ it('bad_signature: signed by a different key than advertised in the response', () => {
+ const job = makeJob();
+ const unsigned = {
+ spec: 'oin/0.1',
+ job_digest: digestJob(job),
+ node_pubkey: `ed25519:${pubkeyB64FromSecret(OTHER_SEED_B64)}`,
+ completed_at: '2026-08-12T00:00:10.000Z',
+ status: 'done',
+ output: { url: 'https://x.example/o.glb', sha256: 'b'.repeat(64), bytes: 1 },
+ };
+ // Sign with SEED but claim OTHER's pubkey.
+ const res = signResponse(unsigned, SEED_B64);
+ expect(verifyResponse(job, res).verdict).toBe('bad_signature');
+ });
+
+ it('stale_response: completed after the job deadline', () => {
+ const job = makeJob({ deadline: 5 });
+ const res = makeSignedResponse(job); // completed_at is 10s after created_at
+ expect(verifyResponse(job, res).verdict).toBe('stale_response');
+ });
+
+ it('future_response: completed_at implausibly far ahead of the verifier clock', () => {
+ const job = makeJob({ deadline: 10_000_000 });
+ const res = makeSignedResponse(job, { completed_at: '2026-08-12T00:00:10.000Z' });
+ const out = verifyResponse(job, res, { now: new Date('2026-08-01T00:00:00.000Z') });
+ expect(out.verdict).toBe('future_response');
+ });
+
+ it('passes when completed just inside the deadline', () => {
+ const job = makeJob({ created_at: '2026-08-12T00:00:00.000Z', deadline: 60 });
+ const res = makeSignedResponse(job, { completed_at: '2026-08-12T00:00:59.000Z' });
+ expect(verifyResponse(job, res, { now: new Date('2026-08-12T00:01:00.000Z') }).verdict).toBe('verified');
+ });
+});
+
+describe('verifyOutput (rule 6)', () => {
+ const body = Buffer.from('glb-bytes-for-the-test');
+ const sha = createHash('sha256').update(body).digest('hex');
+
+ function resWithOutput() {
+ const job = makeJob();
+ return makeSignedResponse(job, {
+ output: { url: 'https://storage.googleapis.com/bucket/oin/job.glb', sha256: sha, bytes: body.length },
+ });
+ }
+
+ it('verified_with_output when fetched bytes match the declared digest', async () => {
+ const res = resWithOutput();
+ const fetchImpl = async () => ({
+ ok: true,
+ headers: { get: () => String(body.length) },
+ arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.length),
+ });
+ const out = await verifyOutput(res, fetchImpl);
+ expect(out.ok).toBe(true);
+ expect(out.verdict).toBe('verified_with_output');
+ });
+
+ it('output_digest_mismatch when the artifact bytes differ', async () => {
+ const res = resWithOutput();
+ const other = Buffer.from('tampered');
+ const fetchImpl = async () => ({
+ ok: true,
+ headers: { get: () => String(other.length) },
+ arrayBuffer: async () => other.buffer.slice(other.byteOffset, other.byteOffset + other.length),
+ });
+ const out = await verifyOutput(res, fetchImpl);
+ expect(out.ok).toBe(false);
+ expect(out.verdict).toBe('output_digest_mismatch');
+ });
+
+ it('output_digest_mismatch when the fetch fails', async () => {
+ const res = resWithOutput();
+ const out = await verifyOutput(res, async () => ({ ok: false, status: 403, headers: { get: () => null } }));
+ expect(out.verdict).toBe('output_digest_mismatch');
+ });
+});
+
+describe('advertisement signing', () => {
+ it('a signed advertisement verifies against its own node key', () => {
+ const ad = {
+ spec: 'oin/0.1',
+ node_id: 'node_test',
+ node_pubkey: NODE_PUBKEY,
+ generated_at: '2026-08-12T00:00:00.000Z',
+ capabilities: [{ key: 'mesh.stylize', version: '0.1', models: ['voxel'] }],
+ endpoints: { submit: '/oin/jobs', poll: '/oin/jobs/:id', health: '/health' },
+ auth: 'bearer',
+ };
+ const signed = signAdvertisement(ad, SEED_B64);
+ expect(typeof signed.signature).toBe('string');
+ // The advertisement uses the same signature rule as a response minus the
+ // job binding, so verify it by hand with the same primitives.
+ const { signature, ...unsigned } = signed;
+ const pub = pubkeyB64FromSecret(SEED_B64);
+ expect(signed.node_pubkey).toBe(`ed25519:${pub}`);
+ const der = Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), Buffer.from(pub, 'base64')]);
+ const key = createPublicKey({ key: der, format: 'der', type: 'spki' });
+ expect(cryptoVerifyRaw(null, Buffer.from(canonicalize(unsigned), 'utf8'), key, Buffer.from(signature, 'base64'))).toBe(true);
+ });
+});