Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
style(prose): replace the banned em-dashes flagged across this cycle's changes
nirholas68878e08ddb4
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 35ac923f1..4ede71c26 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -189,7 +189,7 @@ bottom.| Market tools II (screener, categories, exchanges, derivatives, converter, DeFi, chains, stablecoins) | Pages+JS `→ /screener /categories /exchanges /derivatives /converter /defi /chains /stablecoins`; backend [api/coin/](api/coin) (categories, exchanges, derivatives, rates) over CoinGecko + [api/defi/](api/defi) (protocols, chains, stablecoins) over DeFiLlama | In-repo | Eight more Markets tools, same design system: token screener + category rankings + exchange/derivatives tables + crypto⇄fiat converter (CoinGecko), plus a DeFiLlama trio — DeFi TVL by protocol, chains by TVL, stablecoins with peg health. All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Market surfaces III (protocol/chain/stablecoin detail + fees, DEX volumes, hacks, trending) | Detail pages `→ /protocol/:slug /chain/:name /stablecoin/:id` over [api/defi/protocol.js](api/defi/protocol.js), [api/defi/chain.js](api/defi/chain.js), [api/defi/stablecoin.js](api/defi/stablecoin.js); surfaces `→ /fees /dex-volumes /hacks` over [api/defi/](api/defi) (fees, dex-volumes, hacks over DeFiLlama) + `→ /markets/trending` over [api/coin/trending.js](api/coin/trending.js) (CoinGecko /search/trending); list rows in [src/defi.js](src/defi.js), [src/chains.js](src/chains.js), [src/stablecoins.js](src/stablecoins.js) now deep-link into the detail pages | In-repo | Turns the DeFiLlama list pages into full detail experiences: a protocol page (TVL history + hallmark markers, per-chain breakdown, fees/revenue, funding rounds, methodology), a chain page (TVL + stablecoin + DEX-volume charts, top protocols), a stablecoin page (supply history, per-chain distribution, peg-deviation badge). Plus three new market surfaces — protocol fees & revenue, the DEX-volume leaderboard, and a searchable DeFi hacks database ($16.7B all-time) — and a CoinGecko trending page (most-searched coins/categories/NFTs). All real key-free data, cross-linked. Docs: [docs/coin-pages.md](docs/coin-pages.md) || Market detail pages (exchange, category) + DeFi yields | [pages/exchange.html](pages/exchange.html) + [src/exchange-page.js](src/exchange-page.js) `→ /exchange/:id` over [api/coin/exchange.js](api/coin/exchange.js), [pages/category.html](pages/category.html) + [src/category-page.js](src/category-page.js) `→ /category/:id` over [api/coin/category.js](api/coin/category.js) + [api/coin/markets.js](api/coin/markets.js) (`?category=`), [pages/yields.html](pages/yields.html) + [src/yields.js](src/yields.js) `→ /yields` over [api/defi/yields.js](api/defi/yields.js) | In-repo | Rich detail pages that turn list rows into full profiles. Exchange: trust badge, normalized-volume stat, BTC-volume history chart, and a per-pair markets table (spot + derivatives fallback), reached from `/exchanges` and the new Derivatives Exchanges table. Category: rank, sector stats, the full sortable coins table for that sector, and related categories, reached from `/categories`. Yields: an explorer over ~15k live DeFiLlama pools with chain/project/stablecoin/min-TVL filters, APY/TVL sort, URL-synced state, and a per-pool APY+TVL history chart on row expand. Docs: [docs/coin-pages.md](docs/coin-pages.md) |-| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, knowledge, archive, digest, rss, image) over [api/_lib/article-extract.js](api/_lib/article-extract.js) (page→reader→feed→preview ladder) and [api/_lib/news-rights.js](api/_lib/news-rights.js) (publisher rights layer, enforced at every read path), [api/_lib/news-coins.js](api/_lib/news-coins.js) (ticker→live market snapshot), [api/_lib/news-knowledge-store.js](api/_lib/news-knowledge-store.js) (durable `news_knowledge` corpus) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive`, purge tooling [scripts/news-takedown-purge.mjs](scripts/news-takedown-purge.mjs) | In-repo | The Markets news wing + front door: /markets/news is “Your briefing” — live news aggregated natively from 197 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), a rich article reader that shows a bounded lead excerpt plus our own summary/key points/entities/market context and sends the reader to the publisher for the rest (the excerpt cap and any rightsholder takedowns are enforced server-side across the reader, RSS mirror, archive search, and agent knowledge corpus, never just hidden client-side), renders **live coin cards** (price/24h/7d/sparkline→/coin/:id) for detected tickers, and related coverage — and records every read story to a durable **news knowledge base** (`GET /api/news/knowledge`) that grounds the 3D agents, itself subject to the same excerpt limit. Plus the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted) and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md), [docs/news-rights.md](docs/news-rights.md) (publisher takedown path) |+| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, knowledge, archive, digest, rss, image) over [api/_lib/article-extract.js](api/_lib/article-extract.js) (page→reader→feed→preview ladder) and [api/_lib/news-rights.js](api/_lib/news-rights.js) (publisher rights layer, enforced at every read path), [api/_lib/news-coins.js](api/_lib/news-coins.js) (ticker→live market snapshot), [api/_lib/news-knowledge-store.js](api/_lib/news-knowledge-store.js) (durable `news_knowledge` corpus) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive`, purge tooling [scripts/news-takedown-purge.mjs](scripts/news-takedown-purge.mjs) | In-repo | The Markets news wing + front door: /markets/news is “Your briefing”: live news aggregated natively from 197 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), a rich article reader that shows a bounded lead excerpt plus our own summary/key points/entities/market context and sends the reader to the publisher for the rest (the excerpt cap and any rightsholder takedowns are enforced server-side across the reader, RSS mirror, archive search, and agent knowledge corpus, never just hidden client-side), and renders **live coin cards** (price/24h/7d/sparkline→/coin/:id) for detected tickers, and related coverage. Every read story is recorded to a durable **news knowledge base** (`GET /api/news/knowledge`) that grounds the 3D agents, itself subject to the same excerpt limit. Plus the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted) and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md), [docs/news-rights.md](docs/news-rights.md) (publisher takedown path) || Robinhood Chain markets + buy flow | Hub + detail pages [pages/markets-robinhood.html](pages/markets-robinhood.html) + [src/markets-robinhood.js](src/markets-robinhood.js) `→ /markets/robinhood`, [pages/robinhood-stock.html](pages/robinhood-stock.html) + [src/robinhood-stock.js](src/robinhood-stock.js) `→ /markets/robinhood/stock/:symbol`, [pages/robinhood-coin.html](pages/robinhood-coin.html) + [src/robinhood-coin.js](src/robinhood-coin.js) `→ /markets/robinhood/coin/:address`, buy flow [src/robinhood-purchase.js](src/robinhood-purchase.js); backend [api/_lib/robinhood.js](api/_lib/robinhood.js) + `api/v1/robinhood/{chain,stocks,stocks-detail,coins,coins-detail,launches}.js` (free) + [api/x402/robinhood-portfolio.js](api/x402/robinhood-portfolio.js) (x402 paid) | In-repo | The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs. Uniswap DEX premium for every Stock Token (one multicall, never 95 RPC calls), a memecoin screener across NOXA/The Odyssey launchpads (CoinGecko categories + on-chain launch logs via Blockscout), and chain TVL/gas/block stats. Detail pages add NAV history, holders, transfers, and contract links. Coin pages carry a real buy panel — injected-wallet connect, chain-switch to 4663, live Uniswap v3 `QuoterV2` quote + `SwapRouter02` swap with slippage, LI.FI bridge deep-link; Stock Tokens are display-only (tokenized securities, not offered to US persons) with an eligibility-gated outbound DEX link instead. Paid `portfolio` endpoint returns ERC-8056 `uiMultiplier`-correct holdings. Docs: [docs/robinhood-chain-markets.md](docs/robinhood-chain-markets.md) || Premium Data API pass | [api/premium/](api/premium) + [api/_lib/premium.js](api/_lib/premium.js), dashboards [src/dashboard-next/pages/data-api.js](src/dashboard-next/pages/data-api.js) `→ /dashboard/data-api` + [src/dashboard-next/pages/billing.js](src/dashboard-next/pages/billing.js) `→ /dashboard/billing` | In-repo | Monthly pass in three tiers (Developer $19.99, Pro $99, Enterprise $499 per 30d, tiered rate limits) paid on Solana in $THREE (20% off), SOL, or USDC — replaces per-call x402 on the news archive with an `x402_live_` API key (existing access-control lane) + SIWX browser grants. Quote→sign→verify flow with on-chain balance-delta verification; tables `premium_passes`/`premium_quotes`. Docs: [docs/premium.md](docs/premium.md) || Liquidations pulse (/coins) | Collector [services/liquidation-collector/](services/liquidation-collector) (standalone always-on Node service, ported from SperaxOS), proxy [api/coin/liquidations.js](api/coin/liquidations.js) `→ GET /api/coin/liquidations`, UI strip in [src/coins-index.js](src/coins-index.js) `→ /coins` | Live — collector on Cloud Run (`liquidation-collector`, min-instances 1, unthrottled CPU) since 2026-07-10 | Real-time long/short liquidation pain across Binance, Bybit, and OKX public futures WebSocket streams: dominant-side badge (LONG PAIN / SHORT SQUEEZE / BALANCED), 1h long-vs-short bars, and the 3 largest recent liquidations, polled every 30s (pauses on hidden tab). The collector holds long-lived WebSockets so it can't run as a Vercel function — deploy it separately and point `LIQUIDATION_COLLECTOR_URL` at it. No fallback data: the proxy 503s `collector_offline` (never fabricated numbers) when unset or unreachable, and the strip degrades to a quiet single-line offline state. Docs: [docs/api-reference.md#liquidations](docs/api-reference.md#liquidations) |diff --git a/mcp-server/README.md b/mcp-server/README.mdindex 18b0348d3..ccd36112d 100644--- a/mcp-server/README.md+++ b/mcp-server/README.md@@ -89,7 +89,7 @@ All 25 tools are listed below. Most quote a fixed USDC price and settle `exact`| `vanity_premium` | FREE | Browse the **premium** vanity inventory: long (4-5+ char) brandable Solana addresses ground ahead of time on batch CPU and sold from stock, which the live grinder cannot reach. Read-only and free: returns each address, its rarity tier, a difficulty-scaled price ($1-$50), and a ready-to-pay x402 `buyUrl`. Paying that URL (USDC on Base or Solana) reveals the private key exactly once; the ciphertext is destroyed on delivery. Filter by prefix or tier, sort by rarity/price/newest. Keys are platform-generated: use as a token mint or sweep to self-generated custody, not as a treasury. || `aixbt_intel` | $0.01 | aixbt narrative intelligence feed — recent intel items across crypto with category, description, observation count, official-source flag, and the project/ticker concerned. Optional category/chain filter. Live aixbt REST API. || `aixbt_projects` | $0.01 | aixbt momentum scan — projects ranked by spiking/climbing/active scores, with ticker, chain, market metrics (price, mcap, 24h volume + change), and recent intel. Filter by names or chain. Live aixbt REST API. |-| `crypto_news` | FREE | Live crypto headlines aggregated natively by three.ws from 197 publisher RSS/Atom feeds in 17 languages — filter by category, source, or language, or full-text search. Each article carries the publisher link, publish time, detected tickers, and lexicon sentiment. No payment, no key. |+| `crypto_news` | FREE | Live crypto headlines aggregated natively by three.ws from 197 publisher RSS/Atom feeds in 17 languages. Filter by category, source, or language, or full-text search. Each article carries the publisher link, publish time, detected tickers, and lexicon sentiment. No payment, no key. || `crypto_news_digest` | FREE | The last 1–72h of coverage clustered into distinct narratives — title, plain-language summary, bullish/bearish stance, tickers, coverage count, and every real article behind each story. Names its engine honestly (`llm` semantic grouping or `heuristic` Jaccard clustering). No payment, no key. || `crypto_news_archive` | FREE tier | Search 660,000+ archived articles back to September 2017 (refreshed hourly) by keyword, ticker, source, date range, sentiment, or language — with market context at publication where captured. `mode: stats` and `mode: trending` for corpus statistics and most-covered tickers (always free, no key). Search has a free daily quota (60/day per IP), then $0.001 USDC per search via x402 on the HTTP API; an exhausted quota returns a `payment_required` envelope with the price and networks. |diff --git a/mcp-server/src/tools/crypto-news.js b/mcp-server/src/tools/crypto-news.jsindex aa1d14692..225b11408 100644--- a/mcp-server/src/tools/crypto-news.js+++ b/mcp-server/src/tools/crypto-news.js@@ -12,7 +12,7 @@ import { NEWS_API_BASE, newsApiGet, slimArticle } from './_news-core.js';const TOOL_NAME = 'crypto_news';const TOOL_DESCRIPTION =- 'Live crypto news headlines aggregated by three.ws directly from 197 publisher RSS/Atom feeds — ' ++ 'Live crypto news headlines aggregated by three.ws directly from 197 publisher RSS/Atom feeds, ' +'CoinDesk, The Block, Decrypt, CoinTelegraph, SEC press, exchange blogs, research desks, and ' +'international outlets in 17 languages. Filter by category (bitcoin, ethereum, solana, defi, nft, ' +'trading, research, security, regulation-adjacent geopolitical, and more), by a single source key, ' +diff --git a/node-operator/.dockerignore b/node-operator/.dockerignoredeleted file mode 100644index 6641648eb..000000000--- a/node-operator/.dockerignore+++ /dev/null@@ -1,4 +0,0 @@-node_modules-.model-cache-*.log-.gitdiff --git a/node-operator/.gitignore b/node-operator/.gitignoredeleted file mode 100644index a1ee057cf..000000000--- a/node-operator/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-node_modules/-.model-cache/-*.logdiff --git a/node-operator/Dockerfile b/node-operator/Dockerfiledeleted file mode 100644index 9ddbdb160..000000000--- a/node-operator/Dockerfile+++ /dev/null@@ -1,37 +0,0 @@-# 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.gpudeleted file mode 100644index 2ff0a43fc..000000000--- a/node-operator/Dockerfile.gpu+++ /dev/null@@ -1,47 +0,0 @@-# 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.mddeleted file mode 100644index 21b84d253..000000000--- a/node-operator/README.md+++ /dev/null@@ -1,180 +0,0 @@-# 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/package-lock.json b/node-operator/package-lock.jsondeleted file mode 100644index 3c5715cd3..000000000--- a/node-operator/package-lock.json+++ /dev/null@@ -1,276 +0,0 @@-{- "name": "@three-ws/node-operator",- "version": "1.0.0",- "lockfileVersion": 3,- "requires": true,- "packages": {- "": {- "name": "@three-ws/node-operator",- "version": "1.0.0",- "dependencies": {- "@noble/curves": "^1.9.0 || ^2.2.0",- "bs58": "^6.0.0",- "onnxruntime-node": "^1.20.0"- },- "engines": {- "node": ">=20"- }- },- "node_modules/@noble/curves": {- "version": "2.3.0",- "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.3.0.tgz",- "integrity": "sha512-v7cY+4oWYPQszRj6ZFGzTVL7uP2TaLo1xMhWHzYC5wj0ZhOXQ5x+sBre8rF3hi8cAoi0bh1qXoovoOkdFtvqEg==",- "license": "MIT",- "dependencies": {- "@noble/hashes": "2.3.0"- },- "engines": {- "node": ">= 20.19.0"- },- "funding": {- "url": "https://paulmillr.com/funding/"- }- },- "node_modules/@noble/hashes": {- "version": "2.3.0",- "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.3.0.tgz",- "integrity": "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==",- "license": "MIT",- "engines": {- "node": ">= 20.19.0"- },- "funding": {- "url": "https://paulmillr.com/funding/"- }- },- "node_modules/adm-zip": {- "version": "0.5.18",- "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz",- "integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==",- "license": "MIT",- "engines": {- "node": ">=12.0"- }- },- "node_modules/base-x": {- "version": "5.0.1",- "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz",- "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==",- "license": "MIT"- },- "node_modules/bs58": {- "version": "6.0.0",- "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz",- "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==",- "license": "MIT",- "dependencies": {- "base-x": "^5.0.0"- }- },- "node_modules/define-data-property": {- "version": "1.1.4",- "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",- "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",- "license": "MIT",- "dependencies": {- "es-define-property": "^1.0.0",- "es-errors": "^1.3.0",- "gopd": "^1.0.1"- },- "engines": {- "node": ">= 0.4"- },- "funding": {- "url": "https://github.com/sponsors/ljharb"- }- },- "node_modules/define-properties": {- "version": "1.2.1",- "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",- "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",- "license": "MIT",- "dependencies": {- "define-data-property": "^1.0.1",- "has-property-descriptors": "^1.0.0",- "object-keys": "^1.1.1"- },- "engines": {- "node": ">= 0.4"- },- "funding": {- "url": "https://github.com/sponsors/ljharb"- }- },- "node_modules/es-define-property": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",- "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",- "license": "MIT",- "engines": {- "node": ">= 0.4"- }- },- "node_modules/es-errors": {- "version": "1.3.0",- "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",- "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",- "license": "MIT",- "engines": {- "node": ">= 0.4"- }- },- "node_modules/escape-string-regexp": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",- "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",- "license": "MIT",- "engines": {- "node": ">=10"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/global-agent": {- "version": "4.1.3",- "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-4.1.3.tgz",- "integrity": "sha512-KUJEViiuFT3I97t+GYMikLPJS2Lfo/S2F+DQuBWzuzaMPnvt5yyZePzArx36fBzpGTxZjIpDbXLeySLgh+k76g==",- "license": "BSD-3-Clause",- "dependencies": {- "globalthis": "^1.0.2",- "matcher": "^4.0.0",- "semver": "^7.3.5",- "serialize-error": "^8.1.0"- },- "engines": {- "node": ">=10.0"- }- },- "node_modules/globalthis": {- "version": "1.0.4",- "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",- "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",- "license": "MIT",- "dependencies": {- "define-properties": "^1.2.1",- "gopd": "^1.0.1"- },- "engines": {- "node": ">= 0.4"- },- "funding": {- "url": "https://github.com/sponsors/ljharb"- }- },- "node_modules/gopd": {- "version": "1.2.0",- "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",- "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",- "license": "MIT",- "engines": {- "node": ">= 0.4"- },- "funding": {- "url": "https://github.com/sponsors/ljharb"- }- },- "node_modules/has-property-descriptors": {- "version": "1.0.2",- "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",- "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",- "license": "MIT",- "dependencies": {- "es-define-property": "^1.0.0"- },- "funding": {- "url": "https://github.com/sponsors/ljharb"- }- },- "node_modules/matcher": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/matcher/-/matcher-4.0.0.tgz",- "integrity": "sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==",- "license": "MIT",- "dependencies": {- "escape-string-regexp": "^4.0.0"- },- "engines": {- "node": ">=10"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/object-keys": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",- "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",- "license": "MIT",- "engines": {- "node": ">= 0.4"- }- },- "node_modules/onnxruntime-common": {- "version": "1.27.0",- "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.27.0.tgz",- "integrity": "sha512-3KxL5wIVqa8Ex08jxSzncm9CMgw8CjOFyOQ7SxvG9o0cVLlhTNKXyIQuTbtX4tGPJEf73OER2xrjt4HJSBL4ow==",- "license": "MIT"- },- "node_modules/onnxruntime-node": {- "version": "1.27.0",- "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.27.0.tgz",- "integrity": "sha512-QEzGwrvNBgv4uPVdnbHsOGG4G6T96mdlcFI8aAKPjMU8wOPpVocPXb6k3QGkaZagVTv2G9Bnnbo6Z3JdXr1fQw==",- "hasInstallScript": true,- "license": "MIT",- "os": [- "win32",- "darwin",- "linux"- ],- "dependencies": {- "adm-zip": "^0.5.16",- "global-agent": "^4.1.3",- "onnxruntime-common": "1.27.0"- }- },- "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/serialize-error": {- "version": "8.1.0",- "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz",- "integrity": "sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==",- "license": "MIT",- "dependencies": {- "type-fest": "^0.20.2"- },- "engines": {- "node": ">=10"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/type-fest": {- "version": "0.20.2",- "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz",- "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",- "license": "(MIT OR CC0-1.0)",- "engines": {- "node": ">=10"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- }- }-}diff --git a/node-operator/package.json b/node-operator/package.jsondeleted file mode 100644index ddd03bb1a..000000000--- a/node-operator/package.json+++ /dev/null@@ -1,22 +0,0 @@-{- "name": "@three-ws/node-operator",- "version": "1.0.0",- "description": "three.ws open inference network node operator client: register, claim jobs, run real inference, return signed results.",- "type": "module",- "private": true,- "main": "src/identity.js",- "scripts": {- "start": "node src/cli.js run",- "generate-key": "node src/cli.js generate-key",- "register": "node src/cli.js register",- "verify": "node src/cli.js verify"- },- "engines": {- "node": ">=20"- },- "dependencies": {- "@noble/curves": "^1.9.0 || ^2.2.0",- "bs58": "^6.0.0",- "onnxruntime-node": "^1.20.0"- }-}diff --git a/node-operator/src/cli.js b/node-operator/src/cli.jsdeleted file mode 100644index 31d269643..000000000--- a/node-operator/src/cli.js+++ /dev/null@@ -1,310 +0,0 @@-#!/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];-// Only run the CLI when invoked directly (`node src/cli.js ...`), not when a-// test imports createLocalCoordinator from this module.-const isMain = (() => {- try {- return process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href;- } catch {- return false;- }-})();--if (isMain) {- 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.jsdeleted file mode 100644index a445bedb7..000000000--- a/node-operator/src/client.js+++ /dev/null@@ -1,81 +0,0 @@-// 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/codec.js b/node-operator/src/codec.jsdeleted file mode 100644index 1d7290ea5..000000000--- a/node-operator/src/codec.js+++ /dev/null@@ -1,108 +0,0 @@-// Wire contract between a node and the three.ws coordinator.-//-// Derived from the platform's existing worker job format (no phase 4 spec had-// landed in specs/ when this client was built):-// - bearer auth with a shared worker secret, as in workers/agent-screen-pool-// (SCREEN_WORKER_SECRET on both sides, timing-safe compared by the API)-// - claim -> execute -> submit loops, as in workers/agent-screen-pool and-// workers/garment-forge (claim at execution time, submit signed result)-// - Ed25519 signatures over a canonical UTF-8 string, verified by-// api/_lib/siws.js-style logic (verifyPayload in src/identity.js)-//-// Job envelope (claim response item):-// { jobId, type: 'llm.completion', model, input: { prompt }, maxTokens,-// issuedAt }-//-// Canonical result payload (what the node actually signs):-// threews-inference-v1\n<jobId>\n<nodeAddress>\n<model>\n-// <sha256-hex of UTF-8 input.prompt>\n<sha256-hex of UTF-8 output text>\n-// <latencyMs>\n<completedAt ISO>-//-// Submit body:-// { jobId, node, model, result: { text, tokens, latencyMs },-// inputHash, outputHash, completedAt, signature }-//-// Anyone can recompute the canonical string from a job + result and check it-// against `signature` with only the node's public address.--import { createHash } from 'node:crypto';--export const PROTOCOL = 'threews-inference-v1';-export const JOB_TYPE = 'llm.completion';--export function sha256Hex(text) {- return createHash('sha256').update(String(text), 'utf8').digest('hex');-}--// Validate and normalize a claimed job. Returns null for anything that is not-// an executable llm.completion job, so a malformed queue entry never reaches-// the engine.-export function normalizeJob(raw) {- if (!raw || typeof raw !== 'object') return null;- const jobId = String(raw.jobId || raw.job_id || '');- if (!jobId) return null;- if (raw.type && raw.type !== JOB_TYPE) return null;- const input = raw.input && typeof raw.input === 'object' ? raw.input : {};- const prompt = typeof input.prompt === 'string' ? input.prompt : null;- if (!prompt) return null;- const maxTokensRaw = Number(raw.maxTokens ?? raw.max_tokens ?? 64);- const maxTokens = Number.isFinite(maxTokensRaw) ? Math.min(Math.max(Math.round(maxTokensRaw), 1), 512) : 64;- return {- jobId,- type: JOB_TYPE,- model: String(raw.model || ''),- input: { prompt },- maxTokens,- issuedAt: raw.issuedAt || raw.issued_at || null,- };-}--// Build the exact string the node signs. Field order is load-bearing; verifiers-// reproduce it byte for byte.-export function canonicalResult({ jobId, node, model, inputHash, outputHash, latencyMs, completedAt }) {- return [- PROTOCOL,- jobId,- node,- model,- inputHash,- outputHash,- String(Math.round(Number(latencyMs) || 0)),- completedAt,- ].join('\n');-}--// Assemble the unsigned result record for a finished job.-export function buildResultRecord({ job, node, model, text, tokens, latencyMs, completedAt }) {- const inputHash = sha256Hex(job.input.prompt);- const outputHash = sha256Hex(text);- return {- jobId: job.jobId,- node,- model,- result: { text, tokens: Math.max(0, Math.round(Number(tokens) || 0)), latencyMs: Math.round(latencyMs) },- inputHash,- outputHash,- completedAt,- };-}--// Verify a submitted result against the job and the node's public address.-// `verify` is the identity.verifyPayload function (injected so this module-// stays free of crypto imports and trivially testable).-export function verifyResult({ job, record, signature, verify }) {- if (!job || !record || !signature || typeof verify !== 'function') return false;- if (record.jobId !== job.jobId) return false;- if (record.inputHash !== sha256Hex(job.input.prompt)) return false;- if (record.outputHash !== sha256Hex(record.result?.text ?? '')) return false;- 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,- });- return verify(record.node, payload, signature);-}diff --git a/node-operator/src/engine.js b/node-operator/src/engine.jsdeleted file mode 100644index 71f18a682..000000000--- a/node-operator/src/engine.js+++ /dev/null@@ -1,304 +0,0 @@-// Built-in proof workload: real text generation with a small open model.-//-// The model is distilgpt2 (82M params, the distilled GPT-2, MIT-licensed-// weights from OpenAI's GPT-2 family), served from the ONNX export published-// by Xenova on Hugging Face. The quantized graph is ~80 MB, small enough that-// the image builds anywhere and fast enough on CPU to prove the job loop end-// to end; on a GPU host the same graph runs on the CUDA execution provider-// (see Dockerfile.gpu).-//-// Files are downloaded from huggingface.co into MODEL_CACHE_DIR on first run-// and checksummed by the hub's own ETag path (resolve/main pins the revision-// served today; set MODEL_REVISION to pin an exact commit).-//-// The tokenizer is a byte-level BPE (GPT-2 family). Rather than vendoring a-// tokenizer library, this module implements the exact algorithm from the-// Hugging Face tokenizers spec over the repo's real vocab.json/merges.txt:-// bytes-to-unicode mapping, the GPT-2 pre-tokenizer split regex, then BPE-// merge ranking. Generation is greedy argmax over the ONNX logits.--import { createWriteStream } from 'node:fs';-import { mkdir, readFile, stat, rename, rm } from 'node:fs/promises';-import path from 'node:path';-import { pipeline } from 'node:stream/promises';-import { Readable } from 'node:stream';-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/decoder_model_merged_quantized.onnx',- 'config.json',- 'tokenizer.json',- 'vocab.json',- 'merges.txt',-];--// ── Download ────────────────────────────────────────────────────────────────--async function fileExists(p) {- try {- await stat(p);- return true;- } catch {- return false;- }-}--async function download(url, dest) {- await mkdir(path.dirname(dest), { recursive: true });- const tmp = `${dest}.part-${process.pid}`;- const res = await fetch(url, { redirect: 'follow' });- if (!res.ok || !res.body) {- throw new Error(`model download failed: ${res.status} ${res.statusText} for ${url}`);- }- await pipeline(Readable.fromWeb(res.body), createWriteStream(tmp));- await rename(tmp, dest);-}--// Ensure every model file is present under cacheDir; returns the directory.-export async function ensureModel({ cacheDir, modelId = DEFAULT_MODEL_ID, revision = DEFAULT_MODEL_REVISION, log = () => {} }) {- await mkdir(cacheDir, { recursive: true });- for (const rel of MODEL_FILES) {- const dest = path.join(cacheDir, rel);- if (await fileExists(dest)) continue;- const url = `https://huggingface.co/${modelId}/resolve/${revision}/${rel}`;- log(`downloading ${rel}`);- await download(url, dest);- }- return cacheDir;-}--// ── Byte-level BPE tokenizer (GPT-2 family) ─────────────────────────────────--// The GPT-2 bytes-to-unicode table: printable bytes map to themselves, the-// rest map to codepoints 256+. Identical to transformers' bytes_to_unicode().-function buildBytesToUnicode() {- const bs = [];- for (let i = 33; i <= 126; i++) bs.push(i);- for (let i = 161; i <= 172; i++) bs.push(i);- for (let i = 174; i <= 255; i++) bs.push(i);- const cs = [...bs];- let n = 0;- const b2u = new Map();- for (let b = 0; b < 256; b++) {- if (!bs.includes(b)) {- bs.push(b);- cs.push(256 + n);- n++;- }- }- for (let i = 0; i < bs.length; i++) b2u.set(bs[i], String.fromCodePoint(cs[i]));- const u2b = new Map([...b2u].map(([b, u]) => [u, b]));- return { b2u, u2b };-}--// GPT-2 pre-tokenizer split pattern (the JS-safe equivalent of the original-// Python regex): contractions, words, numbers, symbol runs, whitespace runs.-const PRE_TOKENIZER_RE = /'s|'t|'re|'ve|'m|'ll|'d| ?[A-Za-z]+| ?[0-9]+| ?[^\sA-Za-z0-9]+|\s+(?!\S)|\s+/gu;--export class BpeTokenizer {- constructor({ vocab, merges, b2u, u2b, eosTokenId }) {- this.vocab = vocab; // token string -> id- this.idToToken = new Map(Object.entries(vocab).map(([t, id]) => [id, t]));- this.b2u = b2u;- this.u2b = u2b;- this.eosTokenId = eosTokenId;- // Merge rank lookup: "left right" -> rank.- this.ranks = new Map(merges.map((pair, i) => [`${pair[0]} ${pair[1]}`, i]));- this.cache = new Map();- }-- static async load(dir) {- const vocab = JSON.parse(await readFile(path.join(dir, 'vocab.json'), 'utf8'));- const mergesRaw = await readFile(path.join(dir, 'merges.txt'), 'utf8');- const merges = mergesRaw- .split('\n')- .map((l) => l.trim())- .filter((l) => l && !l.startsWith('#'))- .map((l) => l.split(' '));- const config = JSON.parse(await readFile(path.join(dir, 'config.json'), 'utf8'));- const { b2u, u2b } = buildBytesToUnicode();- return new BpeTokenizer({ vocab, merges, b2u, u2b, eosTokenId: config.eos_token_id ?? 50256 });- }-- encode(text) {- const preTokens = String(text).match(PRE_TOKENIZER_RE) || [];- const ids = [];- for (const pre of preTokens) {- // Map raw UTF-8 bytes through the bytes-to-unicode alphabet.- const bytes = new TextEncoder().encode(pre);- const word = [...bytes].map((b) => this.b2u.get(b));- for (const token of this.bpe(word)) {- const id = this.vocab[token];- if (id !== undefined) ids.push(id);- }- }- return ids;- }-- decode(ids) {- const tokens = ids.map((id) => this.idToToken.get(id) || '');- const text = tokens.join('');- const bytes = [];- for (const ch of text) {- const b = this.u2b.get(ch);- if (b !== undefined) bytes.push(b);- }- return new TextDecoder('utf-8', { fatal: false }).decode(Uint8Array.from(bytes));- }-- bpe(word) {- const key = word.join('');- if (this.cache.has(key)) return this.cache.get(key);- if (word.length <= 1) {- this.cache.set(key, word);- return word;- }- let current = word;- for (;;) {- // Find the lowest-rank adjacent pair.- let bestRank = Infinity;- let bestIdx = -1;- for (let i = 0; i < current.length - 1; i++) {- const rank = this.ranks.get(`${current[i]} ${current[i + 1]}`);- if (rank !== undefined && rank < bestRank) {- bestRank = rank;- bestIdx = i;- }- }- if (bestIdx === -1) break;- const merged = current[bestIdx] + current[bestIdx + 1];- current = [...current.slice(0, bestIdx), merged, ...current.slice(bestIdx + 2)];- }- this.cache.set(key, current);- return current;- }-}--// ── 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, config }) {- this.session = session;- this.tokenizer = tokenizer;- this.maxLength = maxLength;- this.config = config || {};- }-- static async load({ cacheDir, log = () => {} }) {- 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, {- executionProviders: executionProviders(),- graphOptimizationLevel: 'all',- logSeverityLevel: 3,- });- log(`model loaded from ${modelPath}`);- return new InferenceEngine({- session,- tokenizer,- config,- maxLength: Math.min(Number(config.n_positions) || 1024, 1024),- });- }-- // Greedy generation over the merged KV-cache graph. First pass feeds the- // whole prompt with an empty cache (zero-filled past_key_values of seq 0 and- // use_cache_branch=false); every later pass feeds only the new token plus- // the cache returned by the previous pass. Deterministic argmax decode is- // what a verifiable proof workload wants: the same prompt on an honest- // node produces the same output hash.- async generate(prompt, maxNewTokens = 48) {- const t0 = Date.now();- const promptIds = this.tokenizer.encode(prompt);- const startIds = promptIds.length ? promptIds : [this.tokenizer.eosTokenId];- const budget = Math.min(Math.max(1, maxNewTokens), this.maxLength - startIds.length);- const nLayers = Number(this.config.n_layer) || 6;- const nHeads = Number(this.config.n_head) || 12;- const headDim = Math.floor((Number(this.config.n_embd) || 768) / nHeads);- const empty = () => new ort.Tensor('float32', new Float32Array(0), [1, nHeads, 0, headDim]);-- let past = new Map();- for (let l = 0; l < nLayers; l++) {- past.set(`past_key_values.${l}.key`, empty());- past.set(`past_key_values.${l}.value`, empty());- }-- const inputIds = [...startIds];- let stepIds = inputIds; // first pass consumes the full prompt- let attentionLen = inputIds.length;- let generated = 0;- const feedNames = new Set(this.session.inputNames);-- for (let step = 0; step < budget; step++) {- const feeds = {- input_ids: new ort.Tensor('int64', BigInt64Array.from(stepIds.map(BigInt)), [1, stepIds.length]),- };- if (feedNames.has('attention_mask')) {- feeds.attention_mask = new ort.Tensor('int64', BigInt64Array.from({ length: attentionLen }, () => 1n), [1, attentionLen]);- }- if (feedNames.has('use_cache_branch')) {- feeds.use_cache_branch = new ort.Tensor('bool', new Uint8Array([step === 0 ? 0 : 1]), [1]);- }- for (const [name, tensor] of past) if (feedNames.has(name)) feeds[name] = tensor;-- const outputs = await this.session.run(feeds);- const logits = outputs.logits;- const vocabSize = logits.dims[logits.dims.length - 1];- const last = logits.data.subarray(logits.data.length - vocabSize);- let best = 0;- let bestVal = -Infinity;- for (let i = 0; i < last.length; i++) {- if (last[i] > bestVal) {- bestVal = last[i];- best = i;- }- }-- // Rotate the KV cache for the next step.- const nextPast = new Map();- for (let l = 0; l < nLayers; l++) {- const k = outputs[`present.${l}.key`];- const v = outputs[`present.${l}.value`];- if (k) nextPast.set(`past_key_values.${l}.key`, k);- if (v) nextPast.set(`past_key_values.${l}.value`, v);- }- if (nextPast.size === past.size) past = nextPast;-- inputIds.push(best);- stepIds = [best];- attentionLen += 1;- generated++;- if (best === this.tokenizer.eosTokenId) break;- }-- const text = this.tokenizer.decode(inputIds.slice(inputIds.length - generated));- return { text, tokens: generated, latencyMs: Date.now() - t0 };- }-}--// Load model + engine in one call, downloading on first use.-export async function loadEngine({ cacheDir, modelId, revision, log } = {}) {- const dir = await ensureModel({ cacheDir, modelId, revision, log });- return InferenceEngine.load({ cacheDir: dir, log });-}diff --git a/node-operator/src/identity.js b/node-operator/src/identity.jsdeleted file mode 100644index 5d85f2767..000000000--- a/node-operator/src/identity.js+++ /dev/null@@ -1,124 +0,0 @@-// Node identity: a Solana Ed25519 keypair that doubles as the node's on-chain-// address and its job-result signing key. Encoding follows the platform's-// existing conventions (api/_lib/siws.js, api/_lib/attest-event.js):-// - secret keys: base58 (also accepts base64 and solana-keygen JSON arrays)-// - public keys / node addresses: base58, 32 bytes-// - signatures: Ed25519 over the UTF-8 canonical string, emitted base58-// Only @noble/curves and bs58 are used so the same module loads in the repo's-// root test runner without pulling @solana/web3.js.--import { randomBytes } from 'node:crypto';-import { ed25519 } from '@noble/curves/ed25519.js';-import bs58 from 'bs58';--const BASE58_RE = /^[A-HJ-NP-Za-km-z1-9]+$/;--// Decode a node secret key from any encoding the platform already provisions:-// - JSON array of 64 (or 32) ints, as written by solana-keygen-// - base64 of the raw secret-key bytes-// - base58 of the raw secret-key bytes (the default this client emits)-// Returns a 64-byte secret key (32-byte seed + pubkey), or null on bad input.-export function decodeNodeSecret(secret) {- const raw = String(secret || '').trim();- if (!raw) return null;- let bytes = null;- if (raw.startsWith('[')) {- try {- const arr = JSON.parse(raw);- if (Array.isArray(arr) && arr.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) {- bytes = Uint8Array.from(arr);- }- } catch {- return null;- }- } else if (BASE58_RE.test(raw)) {- try {- bytes = bs58.decode(raw);- } catch {- return null;- }- } else {- try {- bytes = Uint8Array.from(Buffer.from(raw, 'base64'));- } catch {- return null;- }- }- if (!bytes) return null;- // A 32-byte seed expands to the full 64-byte secret key.- if (bytes.length === 32) {- const pub = ed25519.getPublicKey(bytes);- const full = new Uint8Array(64);- full.set(bytes, 0);- full.set(pub, 32);- return full;- }- if (bytes.length === 64) return bytes;- return null;-}--// Generate a fresh node identity.-export function generateKeypair() {- const seed = randomBytes(32);- const secretKey = decodeNodeSecret(bs58.encode(seed));- return {- secretKey,- publicKey: secretKey.slice(32),- address: bs58.encode(secretKey.slice(32)),- secretBase58: bs58.encode(secretKey),- };-}--// Load a node identity from an encoded secret key. Throws on bad input so a-// misconfigured operator fails at boot, not mid-job.-export function loadKeypair(secret) {- const secretKey = decodeNodeSecret(secret);- if (!secretKey) {- throw new Error(- 'NODE_SECRET_KEY could not be decoded: expected base58, base64, or a solana-keygen JSON byte array',- );- }- return {- secretKey,- publicKey: secretKey.slice(32),- address: bs58.encode(secretKey.slice(32)),- };-}--// Sign an arbitrary UTF-8 payload with the node's key. Base58 signature out,-// matching how the platform encodes Ed25519 signatures everywhere else.-export function signPayload(secretKey, payload) {- const bytes = new TextEncoder().encode(payload);- return bs58.encode(ed25519.sign(bytes, secretKey.slice(0, 32)));-}--// Verify a base58 (or base64) Ed25519 signature over `payload` against a-// base58 node address. Mirrors verifySiwsSignature in api/_lib/siws.js.-export function verifyPayload(address, payload, signature) {- let pubBytes;- try {- pubBytes = bs58.decode(String(address || ''));- } catch {- return false;- }- if (pubBytes.length !== 32) return false;-- const sigStr = String(signature || '');- let sigBytes;- if (BASE58_RE.test(sigStr)) {- try {- sigBytes = bs58.decode(sigStr);- } catch {- return false;- }- } else {- try {- sigBytes = Uint8Array.from(Buffer.from(sigStr, 'base64'));- } catch {- return false;- }- }- if (!sigBytes || sigBytes.length !== 64) return false;-- return ed25519.verify(sigBytes, new TextEncoder().encode(payload), pubBytes);-}diff --git a/node-operator/src/runner.js b/node-operator/src/runner.jsdeleted file mode 100644index 7bcea08f4..000000000--- a/node-operator/src/runner.js+++ /dev/null@@ -1,109 +0,0 @@-// 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/scripts/provision-audit-account.mjs b/scripts/provision-audit-account.mjsindex f317bc6d0..ef7e06d0f 100644--- a/scripts/provision-audit-account.mjs+++ b/scripts/provision-audit-account.mjs@@ -1,6 +1,6 @@#!/usr/bin/env node/**- * provision-audit-account.mjs — create the QA account the authed sweeps need.+ * provision-audit-account.mjs: create the QA account the authed sweeps need.** `npm run audit:web:login` (and the other authed harnesses: likeness-eval,* reconstruct-load-test, capture-bundles-media) sign in with AUDIT_EMAIL /diff --git a/tests/node-operator.test.js b/tests/node-operator.test.jsdeleted file mode 100644index 0f897a543..000000000--- a/tests/node-operator.test.js+++ /dev/null@@ -1,299 +0,0 @@-// Node operator client tests: identity round-trips, the wire codec, the-// coordinator client, the BPE tokenizer + greedy generation against the real-// distilgpt2 weights, and a full selftest loop against the in-process-// coordinator. Run from the repo root: npm test -- tests/node-operator.test.js--import { describe, expect, it, beforeAll } from 'vitest';-import { mkdtempSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';--import {- decodeNodeSecret,- generateKeypair,- loadKeypair,- signPayload,- verifyPayload,-} from '../node-operator/src/identity.js';-import {- PROTOCOL,- JOB_TYPE,- sha256Hex,- normalizeJob,- canonicalResult,- buildResultRecord,- verifyResult,-} from '../node-operator/src/codec.js';-import { CoordinatorClient, CLIENT_VERSION } from '../node-operator/src/client.js';-import { NodeRunner } from '../node-operator/src/runner.js';-import { createLocalCoordinator } from '../node-operator/src/cli.js';-import { BpeTokenizer, ensureModel, loadEngine } from '../node-operator/src/engine.js';--const CACHE = process.env.NODE_OPERATOR_MODEL_CACHE || path.join(mkdtempSync(path.join(tmpdir(), 'node-op-')), 'model');-const MODEL_ID = 'Xenova/distilgpt2';--describe('identity', () => {- it('generates a keypair whose secret decodes to the same address', () => {- const kp = generateKeypair();- expect(kp.address).toMatch(/^[A-HJ-NP-Za-km-z1-9]{32,44}$/);- expect(kp.secretBase58).toBeTruthy();- const loaded = loadKeypair(kp.secretBase58);- expect(loaded.address).toBe(kp.address);- expect(Buffer.from(loaded.secretKey).equals(Buffer.from(kp.secretKey))).toBe(true);- });-- it('decodes base64 and JSON-array encodings to the same key', () => {- const kp = generateKeypair();- const b64 = Buffer.from(kp.secretKey).toString('base64');- expect(loadKeypair(b64).address).toBe(kp.address);- const json = JSON.stringify([...kp.secretKey]);- expect(loadKeypair(json).address).toBe(kp.address);- // A 32-byte seed expands to the same 64-byte key.- const seed58 = (() => {- // base58 of the first 32 bytes- const bytes = kp.secretKey.slice(0, 32);- return decodeNodeSecretFromSeed(bytes);- })();- function decodeNodeSecretFromSeed(bytes) {- // round-trip through the module: base58-encode via generate path- // is tested above; here we call decodeNodeSecret with JSON of 32 bytes- const decoded = decodeNodeSecret(JSON.stringify([...bytes]));- return decoded;- }- expect(seed58.length).toBe(64);- expect(loadKeypair(JSON.stringify([...kp.secretKey.slice(0, 32)])).address).toBe(kp.address);- });-- it('signs and verifies payloads against the public address', () => {- const kp = generateKeypair();- const sig = signPayload(kp.secretKey, 'hello three.ws');- expect(verifyPayload(kp.address, 'hello three.ws', sig)).toBe(true);- expect(verifyPayload(kp.address, 'tampered', sig)).toBe(false);- const other = generateKeypair();- expect(verifyPayload(other.address, 'hello three.ws', sig)).toBe(false);- });-- it('accepts base64 signatures from external verifiers', () => {- const kp = generateKeypair();- const sig58 = signPayload(kp.secretKey, 'payload');- // bs58 -> bytes -> base64 (what some wallets emit)- const bs58 = { decode: (s) => {- const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';- const bytes = [0];- for (const c of s) {- const p = ALPHABET.indexOf(c);- let carry = p;- for (let j = 0; j < bytes.length; j++) {- carry += bytes[j] * 58;- bytes[j] = carry & 0xff;- carry >>= 8;- }- while (carry > 0) { bytes.push(carry & 0xff); carry >>= 8; }- }- for (const c of s) { if (c === '1') bytes.push(0); else break; }- return Uint8Array.from(bytes.reverse());- } };- const b64 = Buffer.from(bs58.decode(sig58)).toString('base64');- expect(verifyPayload(kp.address, 'payload', b64)).toBe(true);- });-- it('rejects malformed secrets and signatures', () => {- expect(decodeNodeSecret('')).toBeNull();- expect(decodeNodeSecret('not-a-key')).toBeNull();- expect(decodeNodeSecret('[1,2,3]')).toBeNull();- expect(() => loadKeypair('not-a-key')).toThrow(/NODE_SECRET_KEY/);- expect(verifyPayload('bad', 'x', 'bad')).toBe(false);- });-});--describe('codec', () => {- it('normalizes a claimed job and clamps maxTokens', () => {- const job = normalizeJob({- jobId: 'j1',- type: 'llm.completion',- model: 'Xenova/distilgpt2',- input: { prompt: 'hi' },- maxTokens: 99999,- });- expect(job.jobId).toBe('j1');- expect(job.maxTokens).toBe(512);- expect(normalizeJob({ jobId: 'j2', input: { prompt: '' } })).toBeNull();- expect(normalizeJob({ jobId: 'j3', type: 'image.gen', input: { prompt: 'x' } })).toBeNull();- expect(normalizeJob(null)).toBeNull();- });-- it('builds a canonical result string with a stable field order', () => {- const s = canonicalResult({- jobId: 'j', node: 'n', model: 'm',- inputHash: 'ih', outputHash: 'oh', latencyMs: 12.6, completedAt: 't',- });- expect(s).toBe([PROTOCOL, 'j', 'n', 'm', 'ih', 'oh', '13', 't'].join('\n'));- expect(s.startsWith('threews-inference-v1\n')).toBe(true);- });-- it('verifies a signed result and rejects tampering', () => {- const kp = generateKeypair();- const job = normalizeJob({ jobId: 'j9', input: { prompt: 'the prompt' }, model: 'm' });- const record = buildResultRecord({- job, node: kp.address, model: 'm', text: 'the output', tokens: 3,- latencyMs: 42, completedAt: '2026-08-12T00:00:00.000Z',- });- 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 sig = signPayload(kp.secretKey, payload);- expect(verifyResult({ job, record, signature: sig, verify: verifyPayload })).toBe(true);- // Tampered output hash.- expect(verifyResult({ job, record: { ...record, outputHash: sha256Hex('evil') }, signature: sig, verify: verifyPayload })).toBe(false);- // Tampered job binding.- expect(verifyResult({ job: { ...job, jobId: 'other' }, record, signature: sig, verify: verifyPayload })).toBe(false);- // Wrong signer.- const wrong = generateKeypair();- expect(verifyResult({ job, record: { ...record, node: wrong.address }, signature: sig, verify: verifyPayload })).toBe(false);- // Tampered text no longer matches the signed output hash.- expect(verifyResult({ job, record: { ...record, result: { ...record.result, text: 'changed' } }, signature: sig, verify: verifyPayload })).toBe(false);- });-});--describe('coordinator client', () => {- it('sends bearer auth and normalizes claim responses', async () => {- const seen = [];- const fetchImpl = async (url, init) => {- seen.push({ url, auth: init.headers.authorization, body: JSON.parse(init.body) });- if (url.endsWith('/jobs/claim')) {- return new Response(JSON.stringify({ job: { jobId: 'j1', input: { prompt: 'p' } } }), { status: 200 });- }- return new Response(JSON.stringify({ ok: true }), { status: 200 });- };- const client = new CoordinatorClient({- baseUrl: 'https://example.test/', secret: 's', nodeAddress: 'nodeAddr', fetchImpl,- });- await client.register({ capabilities: {}, models: ['m'] });- const job = await client.claimJob();- await client.submitResult({ jobId: 'j1' }, 'sig');- expect(seen[0].auth).toBe('Bearer s');- expect(seen[0].url).toBe('https://example.test/api/inference/nodes/register');- expect(seen[0].body.node).toBe('nodeAddr');- expect(seen[0].body.version).toBe(CLIENT_VERSION);- expect(seen[1].url).toBe('https://example.test/api/inference/jobs/claim');- expect(job.jobId).toBe('j1');- expect(seen[2].url).toBe('https://example.test/api/inference/jobs/submit');- expect(seen[2].body.signature).toBe('sig');- });-- it('returns null on an empty queue and throws on HTTP errors', async () => {- const empty = new CoordinatorClient({- baseUrl: 'https://example.test', nodeAddress: 'n',- fetchImpl: async () => new Response(JSON.stringify({ job: null }), { status: 200 }),- });- expect(await empty.claimJob()).toBeNull();- const failing = new CoordinatorClient({- baseUrl: 'https://example.test', nodeAddress: 'n',- fetchImpl: async () => new Response(JSON.stringify({ error: 'boom' }), { status: 500 }),- });- await expect(failing.claimJob()).rejects.toThrow(/500 boom/);- });-});--describe('engine (real model)', () => {- let tokenizer;- let engine;- beforeAll(async () => {- await ensureModel({ cacheDir: CACHE });- tokenizer = await BpeTokenizer.load(CACHE);- engine = await loadEngine({ cacheDir: CACHE, modelId: MODEL_ID });- }, 300_000);-- it('tokenizer round-trips text and matches known GPT-2 ids', () => {- // Ground truth from the GPT-2 tokenizer: "Hello" -> 15496, " world" -> 995.- const ids = tokenizer.encode('Hello world');- expect(ids).toEqual([15496, 995]);- expect(tokenizer.decode(ids)).toBe('Hello world');- // Contractions and punctuation exercise the pre-tokenizer branches.- const roundTrip = "I'm testing: 3.14, don't split weirdly!";- expect(tokenizer.decode(tokenizer.encode(roundTrip))).toBe(roundTrip);- });-- it('generates deterministic text from the real distilgpt2 weights', async () => {- const a = await engine.generate('The three.ws open inference network lets anyone', 8);- const b = await engine.generate('The three.ws open inference network lets anyone', 8);- expect(a.tokens).toBe(8);- expect(a.text.length).toBeGreaterThan(0);- expect(a.text).toBe(b.text);- expect(sha256Hex(a.text)).toBe(sha256Hex(b.text));- expect(a.latencyMs).toBeGreaterThan(0);- }, 120_000);-});--describe('end-to-end loop (in-process coordinator)', () => {- it('registers, claims one job, and the coordinator verifies the signature', async () => {- const kp = generateKeypair();- const secret = 'test-worker-secret-0123456789';- const job = {- jobId: `e2e-${Date.now()}`,- type: JOB_TYPE,- model: MODEL_ID,- input: { prompt: 'A node operator proves honest inference by' },- maxTokens: 6,- issuedAt: new Date().toISOString(),- };- const { server, registered, submitted } = createLocalCoordinator({ secret, jobs: [job] });- await new Promise((r) => server.listen(0, '127.0.0.1', r));- const baseUrl = `http://127.0.0.1:${server.address().port}`;- try {- const engine = await loadEngine({ cacheDir: CACHE, modelId: MODEL_ID });- const client = new CoordinatorClient({ baseUrl, secret, nodeAddress: kp.address });- await client.register({ capabilities: { jobTypes: [JOB_TYPE] }, models: [MODEL_ID] });- expect(registered.has(kp.address)).toBe(true);-- const events = [];- const runner = new NodeRunner({- client, engine, keypair: kp, pollMs: 50, maxJobs: 1, onEvent: (e) => events.push(e),- });- const { completed } = await runner.run();- expect(completed).toBe(1);-- const entry = submitted.get(job.jobId);- expect(entry).toBeTruthy();- // Independent verification pass on the receipt.- expect(verifyResult({ job: normalizeJob(job), record: entry.record, signature: entry.signature, verify: verifyPayload })).toBe(true);- expect(entry.record.node).toBe(kp.address);- expect(entry.record.result.text.length).toBeGreaterThan(0);- expect(entry.record.inputHash).toBe(sha256Hex(job.input.prompt));- expect(events.some((e) => e.type === 'claimed')).toBe(true);- expect(events.some((e) => e.type === 'completed')).toBe(true);- } finally {- server.close();- }- }, 180_000);-- it('the coordinator rejects a forged signature', async () => {- const kp = generateKeypair();- const attacker = generateKeypair();- const secret = 'test-worker-secret-0123456789';- const job = { jobId: `forgery-${Date.now()}`, input: { prompt: 'p' }, maxTokens: 4 };- const { server } = createLocalCoordinator({ secret, jobs: [job] });- await new Promise((r) => server.listen(0, '127.0.0.1', r));- const baseUrl = `http://127.0.0.1:${server.address().port}`;- try {- const client = new CoordinatorClient({ baseUrl, secret, nodeAddress: kp.address });- const normalized = normalizeJob(job);- const record = buildResultRecord({- job: normalized, node: kp.address, model: MODEL_ID, text: 'x', tokens: 1,- latencyMs: 1, completedAt: new Date().toISOString(),- });- // Sign with the WRONG key: must be refused.- 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 forged = signPayload(attacker.secretKey, payload);- await expect(client.submitResult(record, forged)).rejects.toThrow(/422/);- } finally {- server.close();- }- });-});diff --git a/tests/reputation-net-conviction.test.js b/tests/reputation-net-conviction.test.jsindex 2af221bff..cedb64160 100644--- a/tests/reputation-net-conviction.test.js+++ b/tests/reputation-net-conviction.test.js@@ -1,4 +1,4 @@-// Reputation Staking Market — net conviction (spec §3.3).+// Reputation Staking Market: net conviction (spec §3.3).//// `GET /api/agents/solana-reputation` reports what is STILL staked behind an// agent, not what was ever staked. A settled position's conviction is retired thediff --git a/vite.config.js b/vite.config.jsindex 3c2232db2..7ae83a463 100644--- a/vite.config.js+++ b/vite.config.js@@ -3039,8 +3039,8 @@ support: resolve(__dirname, 'pages/support.html'),// resolveEsbuildTranspileOptions in vite/dist/node): the assumption is that a// lib output is re-bundled by the consumer, so keeping whitespace preserves// `/*#__PURE__*/` annotations for their tree-shaker. Our lib output is not an-// npm dependency — it is the CDN bundle browsers download from-// /agent-3d/latest/agent-3d.js — and the option is forced, so no `build.minify`+// npm dependency: it is the CDN bundle browsers download from+// /agent-3d/latest/agent-3d.js, and the option is forced, so no `build.minify`// or `esbuild` setting can turn it back on. This renderChunk pass strips the// whitespace esbuild left behind, which took the shipped bundle from 4.24 MB to// 2.77 MB raw (1.03 MB → 792 KB gzipped) and cut the parse cost that dominated