Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(cli): three-ws pay settles x402 and MPP challenges with a keychain-held Solana key under a permissions file
nirholas7718bf4fbd96
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 505b97350..4e1cc4cda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **install.md** (`/install.md`): How to install three.ws in any MCP client: one command, per-client settings, and every hosted endpoint. Generated from the MCP directory.- **MCP Plans** (`/mcp-plans`): Prepay for paid MCP tools with credit bundles or time passes, use free trial calls on every tool, and see each credit spent.- **README 3D** (`/readme-3d`): Put an interactive 3D model in any GitHub README. Paste a GLB, glTF, OBJ or STL URL and get a block GitHub renders as a rotatable viewer, sized to fit its markdown limit.+- **X Video Downloader** (`/x-video`): Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.- **Agent memory now learns from trade results, and the decision trail has a verify endpoint**: When a snipe closes, its realized P&L, win or loss and hold time are written back onto the memories the agent recalled when it opened the trade. Recall then ranks those memories by a bounded outcome weight (0.65 to 1.35, halving every 45 days, never zero), so lessons from winners rise while memories tied to losses sink but still come back as warnings. Every recall hit now reports its rankScore and an outcome block with the weight, wins, losses and net USD so you can see why it ranked. The hash-chained decision trail can be re-walked at GET /api/agents/:id/decision-trail/verify, which returns ok, the head hash and the zero-based index of the first broken row after any edit. The reasoning ledger page now fetches it and links to it from the verified badge. (`/reasoning-ledger`) `[feature, improvement]`- **Agents answer mentions of their own X account, in their own persona**: An agent with its own connected X account and mention replies switched on is now polled by the mention bot. It replies in its own persona, attaches a render of its own avatar to conversational replies, and only acts on the intents its owner allowed, up to a daily cap. Dry run stays the default: nothing posts until the owner turns dry run off and the operator enables live mode. A connection missing the posting scope is reported as missing_scope instead of being polled. (`/agents`) `[feature]`- **Agents can sign up to services: inbox codes and sign-in links**: An agent's own address can now receive verification emails and hand back the one-time code or sign-in link. New inbox_list, inbox_read and inbox_wait_for_code tools read the code with a confidence score, only from services the owner lists under Code senders, only from authentic non-spam mail. Email bodies stay untrusted data and links are never fetched for the agent. (`/agent-mail`) `[feature]`@@ -17,6 +18,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Chain turnover on /chains**: The chains leaderboard now has a sortable Turnover column (24h DEX volume divided by TVL) that shows which chains have capital actively trading rather than parked. Chains with no TVL or no reported volume show n/a. (`/chains`) `[feature]`- **Copy any model as a GitHub README 3D block**: Forge results, avatar pages, the avatar dashboard and model pages now have a Copy as GitHub README 3D action. It simplifies the model to a size GitHub renders and puts a stl code fence on your clipboard that GitHub shows as an interactive 3D viewer in any README, issue or pull request. The same converter is a free API (POST /api/readme-3d) and has a live page at /readme-3d. (`/readme-3d`) `[feature]`- **Flappin UFO is back at /play/ufo with a verified leaderboard and a ghost of the top run**: The arcade game returns as a native canvas game with touch and keyboard controls and levels that get longer and tighter. Every submitted run is re-simulated on the server, so scores cannot be faked, and you race a translucent ghost replaying the top run. Scores also appear on /rankings as the UFO High Score tab. (`/play/ufo`) `[feature]`+- **Free X video downloader, and post impact now sees engagement**: Paste any public X post link at /x-video to download its video or GIF in every quality, with the post's likes, replies, reposts and views, no account or API key. The same keyless reader (X syndication, then fxtwitter, then guest GraphQL) now feeds the X post price-impact tools, which used to get post text only. (`/x-video`) `[feature]`+- **KOL tracker shows follower counts without an X API key, and the Oracle reads KOL timelines**: A keyless X reader now backs the tracker when the paid API is unset or rate limited, so attached KOLs keep their follower counts. The Oracle also reads tracked timelines every 10 minutes to feed its social virality signal, and each coin's own linked X account age and followers now appear in its intel. (`/tracker`) `[feature]`- **Leaked-wallet rescue runbook with a dry run, and live Jito tip accounts**: A new rescue script moves every token and the remaining SOL out of a compromised wallet in one atomic Jito bundle, paid for by a separate safe wallet, and its default dry run simulates the whole bundle and prints the plan without sending anything. The leak alarm now links the runbook. Jito tips also read the block engine's live tip-account list with a pinned fallback, instead of three hardcoded copies. `[security, infra]`- **llms.txt links the docs as markdown, and install.md tells an agent how to connect**: llms.txt now links each curated doc as /docs/<slug>.md, the text/markdown twin an agent can read directly. llms-full.txt carries the full text of those docs (capped at 40 KB each, with a link to the rest) after the page index. A new /install.md, generated from the MCP directory, gives one place for the setup command, per-client settings and every hosted endpoint. (`/docs/cli`) `[docs]`- **Onchain viewer reads multi-part memo inscriptions**: Paste any transaction of a first/1, firsts/1 or SPL404 inscription into /onchain and it collects the other parts, checks each part and the whole SHA-256, names missing parts, and shows the file. Images render from verified bytes; SVG and HTML are shown as text and never executed. The Solana Memo Media MCP gains a read_inscription tool that does the same. (`/onchain`) `[feature]`@@ -24,7 +27,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Oracle's smart-wallet prior now reads the live database**: The cold-start wallet prior behind Oracle's pedigree pillar is loaded from the daily-seeded wallet_reputation table instead of a committed June snapshot, so it tracks the current gmgn.ai rankings. It is cached in-process with a bounded refresh, keeps the last good rows if the database blips, and serves an empty prior (and logs it) rather than inventing wallets. (`/docs/oracle`) `[improvement]`- **Prepaid credit plans and free trials for paid MCP tools**: Buy a credit bundle or a 24-hour or 30-day time pass at /mcp-plans and call paid MCP tools without paying each call over x402. Every account gets 3 free calls per tool. Credits are debited before a call, refunded when the tool errors, and every result reports creditsUsed and creditsRemaining. A drained plan falls back to the per-call payment-required error. (`/mcp-plans`) `[feature]`- **Robinhood Chain launches now show every venue, the deployer's track record and a dev-sold flag**: The launches board stopped watching NOXA, which shut down in July, and now finds launches on every venue seen on chain. Each row names the launchpad, shows how many earlier tokens the deployer launched and how many it sold out of, and flags launches where the dev has already sold. (`/markets/robinhood`) `[feature]`+- **See whether our X posts move $THREE: a Posts view on the coin chart**: The $THREE chart has a new Posts tab that plots every @trythreews post at the price it went out at, sized by engagement and coloured by the +4h return, each bubble linking to the post. Across 197 posts the median +1h and +4h return after a post was +1.6%, against -0.1% and -0.7% at arbitrary moments; the +24h median was -1.4% against -2.4%. The content pipeline now also records the +24h price return after each post and lets it nudge ranking, lightly, once enough posts carry one. (`/oracle/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) `[feature]`- **Splat Viewer: Spark 2.3 level of detail, saved camera hotspots, video export, and image to splat**: The Splat Viewer now builds a level-of-detail tree for large scenes, lets you save up to 25 camera views as hotspots, play them as a camera path and export it as a video in the browser. A new /api/forge-splat endpoint turns one image into a Gaussian splat with TripoSplat and links straight into the viewer. (`/splat`) `[feature]`+- **three-ws pay: settle x402 and MPP challenges from the terminal with a key you hold**: The CLI can now pay a 402 itself. `three-ws pay <url>` reads an x402 v2, x402 v1 or MPP Solana challenge, prefers Solana, signs with a wallet kept in the OS keychain (or an encrypted file behind a passphrase), retries once and prints the body. `--dry-run` shows the payee, exact amount and network and signs nothing. A permissions file sets allowed origins, networks, assets and payees, per-call and per-day maximums and a confirm-above threshold, and a refused challenge exits with a stable code (10) and a reason string. `three-ws pay mcp` serves the same under the same permissions as a stdio MCP server with pay_quote and pay_fetch. `[feature, sdk]`- **Turn a Solana program's Anchor IDL into an agent skill**: POST /api/skills/import now accepts idl_url or program_id. Each account type becomes a read tool that decodes it by address, each instruction a preview tool that builds the unsigned instruction with a plain summary, and a destructive send tool that hands it to the wallet confirm flow. A risk panel flags token movement, SOL spend, account closure and authority changes. Nothing the skill generates can sign. (`/skills/import`) `[feature, sdk]`## 2026-10-15diff --git a/STRUCTURE.md b/STRUCTURE.mdindex cdcc1c538..7051b6021 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -288,6 +288,7 @@ packages, a generated standalone GitHub mirror). See| Escrowed knocks (pay-per-reply) | [contracts/knock-escrow/](contracts/knock-escrow) | In-repo | Anchor program making a knock's payment conditional instead of final: `knock` parks the price in a vault owned by the knock's own PDA, and only three things can happen to it. `answer` pays the owner minus a fee capped at 10% in the program itself, `refuse` refunds the sender in full and takes no fee, and `reclaim` refunds the sender once the reply window closes and can be called by anyone. Each `KnockRecord` snapshots the fee that was in force when it was made, so an authority cannot reprice money already in escrow, and it stores only the SHA-256 of the message and the reply, never their text. The trust-me version of this settles straight to the owner at [api/knock/](api/knock) (row above); this is the version that works between strangers. Both sides are reachable from a browser: senders escrow and crank their own refund from the door page, owners open their on-chain door, answer for payment or refuse for a refund from [/knock](pages/knock.html), all signed by their own wallet ([src/knock/escrow-checkout.js](src/knock/escrow-checkout.js)). Docs: [contracts/knock-escrow/README.md](contracts/knock-escrow/README.md), [docs/knock.md](docs/knock.md). Tests: [tests/knock-escrow-program.test.js](tests/knock-escrow-program.test.js), [tests/knock-escrow-pda.test.js](tests/knock-escrow-pda.test.js), [tests/api-knock-escrowed.test.js](tests/api-knock-escrowed.test.js), [tests/api-knock-escrow-sync.test.js](tests/api-knock-escrow-sync.test.js) || Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs || MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge), [packages/*-mcp/](packages) | <!-- mcp-count:stdio.servers -->41<!-- /mcp-count --> npm servers + <!-- mcp-count:hosted.servers -->10<!-- /mcp-count --> hosted remote (<!-- mcp-count:all.servers -->51<!-- /mcp-count --> total, incl. the free `/api/mcp-studio` 3D Studio, whose ChatGPT plugin surface [api/mcp-chatgpt.js](api/mcp-chatgpt.js) `→ /api/mcp-chatgpt` serves the eight 3D tools and the model viewer without the persona tools or any `frameDomains`, and [api/mcp-grok.js](api/mcp-grok.js) `→ /api/mcp-grok` serves every studio tool with no widget templates plus, for a caller signed in with OAuth 2.1 or a connector key, the account's agent tools from the core server through [api/_mcp-studio/account-tools.js](api/_mcp-studio/account-tools.js), never a value-moving one ([tests/mcp-grok-accounts.test.js](tests/mcp-grok-accounts.test.js)); all three doors share [api/_mcp-studio/handler.js](api/_mcp-studio/handler.js), and `SURFACES` in [api/_mcp-studio/dispatch.js](api/_mcp-studio/dispatch.js) defines what each advertises), all in the [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas). Canonical metadata: [prompts/store-submissions/_generated/mcp-listing-source.json](prompts/store-submissions/_generated/mcp-listing-source.json), generated from the manifests by [scripts/build-mcp-listing-source.mjs](scripts/build-mcp-listing-source.mjs) (`npm run audit:mcp-listing` fails when it drifts) | Model Context Protocol surface, full server list in [docs/mcp.md](docs/mcp.md). One-click client setup: [pages/connect.html](pages/connect.html) `→ /connect` (Claude, Cursor and VS Code install links plus ChatGPT, Grok Bot, Claude Code and generic steps; the Grok Bot tab is the shared connector card [src/grok-connector.js](src/grok-connector.js), also mounted on the Grok landing page [pages/grok.html](pages/grok.html) `→ /grok` ([src/grok-page.js](src/grok-page.js): capabilities, a live strip of recent gallery creations, an in-page MCP demo against `/api/mcp-grok`, three scheduled recipes, the skill file); /connect is built live from [public/.well-known/mcp.json](public/.well-known/mcp.json) with tool counts from the catalog; config names match the CLI's `slugForPath`). CLI: [packages/three-ws-cli/](packages/three-ws-cli) (`npx three-ws setup`), docs [docs/cli.md](docs/cli.md) `→ /docs/cli`. One-command setup per client (`npx three-ws --claude`), `doctor`, `agent status` and `team` live in [packages/three-ws-cli/src/commands/](packages/three-ws-cli/src/commands); the hosted installers [public/cli/](public/cli) (`/cli/install`, `/cli/claude`, each with a `.sha256` and an ed25519 `.sig`, public key `signing-key.pem`) are signed by [scripts/sign-cli-scripts.mjs](scripts/sign-cli-scripts.mjs) (`npm run sign:cli`, verified by `npm run check:cli-scripts` in the gate); the clean-container check is [packages/three-ws-cli/tests/container/run.sh](packages/three-ws-cli/tests/container/run.sh). Per-tool pages (schema, example call, price, a try-it for free read-only tools): [pages/mcp-tool.html](pages/mcp-tool.html) `→ /mcp-tools/<server>/<tool>`. The census (tools, resources, prompts per server, with a how-it-is-calculated note) is computed at build time into [public/tools.json](public/tools.json) and at request time by [api/mcp-census.js](api/mcp-census.js) `→ /api/mcp-census` ([api/_lib/mcp-census.js](api/_lib/mcp-census.js)); the release-by-release diff of added tools is [public/mcp-tool-history.json](public/mcp-tool-history.json) ([scripts/build-mcp-tool-history.mjs](scripts/build-mcp-tool-history.mjs)); docs that quote a count use `<!-- mcp-count:... -->` markers that `npm run check:mcp-counts` ([scripts/check-mcp-counts.mjs](scripts/check-mcp-counts.mjs)) verifies in the gate, alongside [tests/mcp-tool-quality.test.js](tests/mcp-tool-quality.test.js) and [tests/mcp-prompt-references.test.js](tests/mcp-prompt-references.test.js) (`npm run test:mcp-surface`). Searchable index of every tool: [pages/mcp-tools.html](pages/mcp-tools.html) `→ /mcp-tools`, rendered from the generated [public/mcp-catalog.json](public/mcp-catalog.json) ([scripts/build-mcp-catalog.mjs](scripts/build-mcp-catalog.mjs), `npm run build:mcp-catalog`, staleness gated by `npm run audit:mcp-catalog`). Tool safety annotations are verified against each handler by [scripts/audit-mcp-safety.mjs](scripts/audit-mcp-safety.mjs) (`npm run audit:mcp-safety`, rules in [scripts/lib/mcp-safety-check.mjs](scripts/lib/mcp-safety-check.mjs), guarded-file list shared with the golden snapshot via [scripts/lib/mcp-tool-sources.mjs](scripts/lib/mcp-tool-sources.mjs)); docs [docs/mcp-safety.md](docs/mcp-safety.md) `→ /docs/mcp-safety`. Trust policy: [api/mcp-policy.js](api/mcp-policy.js) `-> GET /api/mcp-policy` turns those verified labels into a ready-to-paste client allowlist (profiles strict/balanced/open x formats claude/vscode/json), surfaced by the builder panel on `/mcp-tools`. Connector-review readiness (every paid stdio tool answers a clean x402 challenge, and the reviewer entitlement lifts it): [scripts/audit-mcp-reviewer-path.mjs](scripts/audit-mcp-reviewer-path.mjs), `npm run audit:mcp-reviewer`. Tests: [tests/mcp-safety-audit.test.js](tests/mcp-safety-audit.test.js), [tests/mcp-catalog.test.js](tests/mcp-catalog.test.js), [tests/api/mcp-policy.test.js](tests/api/mcp-policy.test.js) |+| CLI payer (x402 and MPP) | [packages/three-ws-cli/src/pay/](packages/three-ws-cli/src/pay) (challenge parser, permissions and daily ledger, keychain/sealed-file keystore, x402 and MPP signers, engine, stdio MCP server), commands [pay.js](packages/three-ws-cli/src/commands/pay.js) and [wallet.js](packages/three-ws-cli/src/commands/wallet.js) | Live | `three-ws pay <url>` settles an x402 v1/v2 or MPP Solana 402 with a locally held key, inside `~/.config/three-ws/pay-permissions.json`; `--dry-run` signs nothing; refusals exit 10 with a reason string; `pay mcp` exposes `pay_quote` and `pay_fetch`. Docs: [README](packages/three-ws-cli/README.md#pay-for-x402-and-mpp-resources-from-the-terminal). Tests: [pay-units](packages/three-ws-cli/tests/pay-units.test.js), [pay-flow](packages/three-ws-cli/tests/pay-flow.test.js), [pay-cli](packages/three-ws-cli/tests/pay-cli.test.js) || Grok Bot integration (custom MCP connector) | Door [api/mcp-grok.js](api/mcp-grok.js) `→ /api/mcp-grok` on the shared studio handler [api/_mcp-studio/](api/_mcp-studio) (signed-in account tools [api/_mcp-studio/account-tools.js](api/_mcp-studio/account-tools.js), job tools [api/_mcp-studio/job-tools.js](api/_mcp-studio/job-tools.js)), install tokens [api/mcp-studio/install.js](api/mcp-studio/install.js) `→ /api/mcp-studio/install`, guided prompts [api/_mcp/prompts.js](api/_mcp/prompts.js), landing page [pages/grok.html](pages/grok.html) `→ /grok`, connector card [src/grok-connector.js](src/grok-connector.js) (also on `/connect`), skill file [public/grok-skill.md](public/grok-skill.md) (template [data/grok-skill-md.template.md](data/grok-skill-md.template.md)), connector probe [scripts/mcp-client-probe.mjs](scripts/mcp-client-probe.mjs) (`npm run probe:mcp-clients`) | Free remote MCP server for Grok Bot, Grok connectors and the xAI API: no call hangs, quota per MCP session or install token, the free studio anonymously, plus the account's agent tools with a connector key or OAuth 2.1 (`?auth=oauth`), never a value-moving tool. Connector reference [docs/grok-bot.md](docs/grok-bot.md) `→ /docs/grok-bot` (setup per auth mode, server choice, links contract, jobs and idempotency, limits, spend rule, prompts, probe troubleshooting; samples run by [scripts/run-doc-samples.mjs](scripts/run-doc-samples.mjs), drift test [tests/grok-bot-doc.test.js](tests/grok-bot-doc.test.js)); product tour [docs/grok.md](docs/grok.md) || X creation claim | Page [pages/x-claim.html](pages/x-claim.html) `→ /x/claim` ([src/x-claim.js](src/x-claim.js)), API [api/x/claim.js](api/x/claim.js), logic [api/_lib/x-creation-claim.js](api/_lib/x-creation-claim.js), ledger migration [api/_lib/migrations/20261009213000_x_creation_claims.sql](api/_lib/migrations/20261009213000_x_creation_claims.sql) | Models the @-mention bot made for an X author move from the bot account into their library when they link the same X id (on link, on the page, or at creation time). Doc: [docs/x-mention-bot.md](docs/x-mention-bot.md). Tests: [tests/x-creation-claim.test.js](tests/x-creation-claim.test.js) || Awesome 3D Agents (curated list) | Source [data/awesome.json](data/awesome.json), generator [scripts/build-awesome.mjs](scripts/build-awesome.mjs) (`npm run build:awesome`, drift-gated by `npm run check:awesome`, publishable mirror via `npm run awesome:standalone`), outputs [awesome/README.md](awesome/README.md) + [public/awesome.json](public/awesome.json), page [pages/awesome.html](pages/awesome.html) `-> /awesome`, link checker [scripts/check-awesome-links.mjs](scripts/check-awesome-links.mjs) (`npm run awesome:links`) | Live | An awesome-list of everything needed to give an AI agent a body: text-to-3D, capture and splatting, avatars, rigging, motion, lipsync and voice, web renderers, asset pipelines, physics and networking, agent frameworks, datasets, free assets, learning. One JSON source produces both the GitHub-facing list and the searchable page, so they cannot disagree. Every url is fetched and classified (ok / moved / bot-filtered / broken) before it ships; the checker stays out of the deploy path so a third-party outage cannot redden someone else's build. The README is written to pass `npx awesome-lint`: badge on the heading line, no License section, no Contributing entry in the contents, and every description capitalised and ended with a period, all enforced by the generator and by [tests/awesome-list.test.js](tests/awesome-list.test.js). Its last two lint rules read GitHub repository topics, which a list inside a product repo cannot satisfy, so `--standalone` emits a ready-to-publish mirror repo (readme, contributing, code of conduct, license) outside this checkout. Contributing: [awesome/CONTRIBUTING.md](awesome/CONTRIBUTING.md) |diff --git a/data/changelog.json b/data/changelog.jsonindex ec1be7154..92bc61e9e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-23",+ "title": "three-ws pay: settle x402 and MPP challenges from the terminal with a key you hold",+ "summary": "The CLI can now pay a 402 itself. `three-ws pay <url>` reads an x402 v2, x402 v1 or MPP Solana challenge, prefers Solana, signs with a wallet kept in the OS keychain (or an encrypted file behind a passphrase), retries once and prints the body. `--dry-run` shows the payee, exact amount and network and signs nothing. A permissions file sets allowed origins, networks, assets and payees, per-call and per-day maximums and a confirm-above threshold, and a refused challenge exits with a stable code (10) and a reason string. `three-ws pay mcp` serves the same under the same permissions as a stdio MCP server with pay_quote and pay_fetch.",+ "tags": [+ "feature",+ "sdk"+ ]+ },+ {+ "date": "2026-10-23",+ "title": "Free X video downloader, and post impact now sees engagement",+ "summary": "Paste any public X post link at /x-video to download its video or GIF in every quality, with the post's likes, replies, reposts and views, no account or API key. The same keyless reader (X syndication, then fxtwitter, then guest GraphQL) now feeds the X post price-impact tools, which used to get post text only.",+ "tags": [+ "feature"+ ],+ "link": "/x-video"+ },{"date": "2026-10-23","title": "See whether our X posts move $THREE: a Posts view on the coin chart",@@ -31087,4 +31105,4 @@]}]-}\ No newline at end of file+}diff --git a/docs/cli.md b/docs/cli.mdindex e076ad2e9..c320fa16f 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -192,6 +192,8 @@ The selection is enforced whichever way you signed in. With a browser sign-in, s| `provider use three-ws` / `provider show` | Point this machine's model clients at three.ws inference, billed to your credits || `usage` | Credits, burn rate, days left and recent top-ups || `ask "<prompt>"` | One completion through the active provider |+| `wallet <init\|address\|export-public>` | A local payer key held in the OS keychain (or an encrypted file behind a passphrase); never printed |+| `pay <url>` / `pay --dry-run <url>` | Settle an x402 or MPP 402 challenge on Solana with that key, inside `pay-permissions.json`; `pay init`, `pay mcp` (stdio MCP server). See the [package README](../packages/three-ws-cli/README.md#pay-for-x402-and-mpp-resources-from-the-terminal) |## One command per clientdiff --git a/packages/three-ws-cli/README.md b/packages/three-ws-cli/README.mdindex 45faf50c9..476e99f2d 100644--- a/packages/three-ws-cli/README.md+++ b/packages/three-ws-cli/README.md@@ -52,6 +52,85 @@ npx @three-ws/cli create "Nova" --description "A deep-space guide." # an agentnpx @three-ws/cli launch --agent <id> --name Nova --symbol NOVA # prefilled, you sign on three.ws/launch```+## Pay for x402 and MPP resources from the terminal++`three-ws pay <url>` fetches a URL, reads its HTTP 402 challenge (x402 v2 `PAYMENT-REQUIRED`, x402 v1 body, or an MPP Solana charge), picks a Solana option, signs with a key that never leaves your machine, retries once and prints the body. Every payment is checked against a permissions file you own before anything is signed.++```bash+three-ws wallet init # key goes to the OS keychain, or an encrypted file behind a passphrase+three-ws wallet address # the public address to fund with USDC+three-ws pay init # writes ~/.config/three-ws/pay-permissions.json (safe defaults)+three-ws pay --dry-run https://three.ws/api/x402/three-intel+three-ws pay https://three.ws/api/x402/three-intel+```++The dry run signs nothing and prints the decision:++```text+Dry run: nothing was signed or sent.+protocol x402+network solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp+amount 0.01 (10000 atomic)+asset EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v+payee wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU+decision allowed by pay-permissions.json+```++| Flag | Meaning |+| --- | --- |+| `--dry-run` | Print protocol, network, exact amount, asset and payee and the permission decision. Signs nothing, spends nothing. |+| `--max <amount>` | Hard ceiling for this call in whole units (`0.05`), on top of the permissions file. |+| `--network <id>` | Only consider offers on this network (`solana`, `devnet`, or a CAIP-2 id). |+| `--method`, `--data`, `-H` | Forward a method, body and headers on both the probe and the paid retry. |+| `--storage keychain\|file` | With `wallet init`: where the key lives. Default tries the keychain, then falls back to the file. |+| `--json` | Machine-readable output, including errors (`{ "error": "<reason>", "exit": <code> }`). |++Solana offers are always tried first. EVM offers are skipped.++### Key custody++`wallet init` generates a 32-byte seed and stores it in the OS keychain through `@napi-rs/keyring`. Where no keychain is reachable (headless Linux, containers) it writes `pay-wallet.sealed.json`, encrypted with AES-256-GCM under a scrypt-derived key, mode 0600, after prompting for a passphrase of at least 12 characters (or reading `THREE_WS_WALLET_PASSPHRASE`). The key is never written in plaintext, no command prints it, and `wallet init` never overwrites an existing wallet. `wallet export-public` prints the address only.++### Permissions file++`~/.config/three-ws/pay-permissions.json` (override with `THREE_WS_PAY_PERMISSIONS`). With no file, every payment is refused.++```json+{+ "version": 1,+ "allowedOrigins": ["https://three.ws"],+ "allowedNetworks": ["solana"],+ "allowedAssets": ["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"],+ "allowedPayees": [],+ "maxPerCall": "0.10",+ "maxPerDay": "1.00",+ "confirmAbove": "0.05"+}+```++`maxPerCall` is required. Limits are decimal strings in whole units of the asset, compared exactly. `maxPerDay` counts a UTC-day ledger of settled payments. Above `confirmAbove` the CLI asks on the terminal. `allowedAssets` defaults to mainnet and devnet USDC, and `allowedPayees` is unrestricted when omitted.++### Exit codes++| Code | Reason strings | Meaning |+| --- | --- | --- |+| 0 | | Success, or the resource was free |+| 1 | | Other error |+| 2 | | Usage error |+| 10 | `permissions_missing`, `origin_not_allowed`, `network_not_allowed`, `asset_not_allowed`, `payee_not_allowed`, `per_call_limit`, `max_flag_exceeded`, `daily_limit` | Refused by the permissions file |+| 11 | `confirm_required`, `declined_by_user` | Above `confirmAbove` and not confirmed |+| 12 | `no_payable_option`, `unsupported_intent`, `challenge_expired` | The server offered nothing payable here |+| 13 | `payment_rejected` | The server rejected the signed payment |+| 14 | `wallet_missing`, `wallet_locked` | No usable wallet |++### MCP server++`three-ws pay mcp` is a stdio MCP server with `pay_quote` (read-only) and `pay_fetch`, under the same permissions. It has no confirmation channel, so it refuses any payment above `confirmAbove`.++```json+{ "mcpServers": { "three-ws-pay": { "command": "npx", "args": ["@three-ws/cli", "pay", "mcp"] } } }+```+## Grok BotGrok Bot's MCP configuration lives in xAI's cloud, so there is no file to write. `setup` handles the rest: it picks the Grok connector (`https://three.ws/api/mcp-grok`), copies the URL to your clipboard when a clipboard tool exists, prints the exact fields for Grok Bot's custom MCP connector, and runs a real `tools/list` against the public URL to prove it answers from outside.diff --git a/packages/three-ws-cli/src/cli.js b/packages/three-ws-cli/src/cli.jsindex 30fd6cbef..41b4b64a9 100755--- a/packages/three-ws-cli/src/cli.js+++ b/packages/three-ws-cli/src/cli.js@@ -21,6 +21,7 @@ ${c.bold('Commands')}setup Sign in, write the three.ws MCP servers into your clients, verify with tools/listlogin Sign in or switch accounts (OAuth by default)link <code> Link this terminal with a code from three.ws/dashboard/account+ signup --agent An autonomous agent signs itself up: local Solana key, no email, no browserlogout Remove stored credentials and revoke the OAuth refresh tokendoctor Diagnose a broken setup: bad config, expired sign-in, unreachable serverstatus Account, plan, wallet balance, token expiry, and every configured client@@ -42,6 +43,9 @@ ${c.bold('Commands')}provider show The active model providerusage Credits, burn rate, days left and recent top-ups (--agent for one agent's budget)ask "<prompt>" One completion through the active provider+ pay <url> Pay an x402 or MPP challenge from a local Solana key, inside pay-permissions.json+ pay init|permissions|mcp Write the default limits, show them, or run the stdio MCP payer+ wallet <sub> The local pay key: init, address, export-public (never prints the private key)version Print the version${c.bold('Sign-in options')} (setup, login)@@ -94,6 +98,18 @@ ${c.bold('Inference options')} (fund, provider, usage)--name <label> Name for the minted inference key (fund)--yes Approve the printed transfer without a prompt (fund)+${c.bold('Pay options')} (pay, wallet)+ --dry-run Print the decision, exact amount and payee; sign and send nothing+ --max <amount> Refuse anything above this many whole units (e.g. 0.05)+ --network <net> Only consider mainnet, devnet or a CAIP-2 network id+ --method <verb> HTTP method (default GET, POST with --data)+ --data <text> Request body, resent after payment+ -H, --header <h> Extra request header "Name: value" (repeatable)+ --yes Approve a payment above confirmAbove without a prompt+ --storage <where> auto (keychain, else sealed file), keychain or file (wallet init)+ Exit codes: 10 outside permissions, 11 needs confirmation, 12 no payable option,+ 13 payment rejected, 14 wallet missing or locked. Reason string in --json.+${c.bold('Global')}--json Machine-readable output on stdout--origin <url> Talk to another three.ws deployment (or THREE_WS_ORIGIN)@@ -140,6 +156,12 @@ const OPTIONS = {'creator-fee': { type: 'string' },network: { type: 'string' },watch: { type: 'boolean' },+ 'dry-run': { type: 'boolean' },+ max: { type: 'string' },+ method: { type: 'string' },+ data: { type: 'string' },+ header: { type: 'string', short: 'H', multiple: true },+ storage: { type: 'string' },claude: { type: 'boolean' },cursor: { type: 'boolean' },codex: { type: 'boolean' },@@ -152,8 +174,15 @@ const OPTIONS = {// `--key` alone (no value) means "prompt for it"; parseArgs needs a value for a// string option, so a bare --key becomes --key= before parsing.+// `signup --agent` is a mode switch, but `agent` is a string option elsewhere+// (`--agent <id>`), so on the signup command a bare --agent becomes --agent=.function normalizeArgv(argv) {- return argv.map((a, i) => (a === '--key' && (argv[i + 1] === undefined || argv[i + 1].startsWith('-')) ? '--key=' : a));+ const bare = (i) => argv[i + 1] === undefined || argv[i + 1].startsWith('-');+ return argv.map((a, i) => {+ if (a === '--key' && bare(i)) return '--key=';+ if (a === '--agent' && argv[0] === 'signup' && bare(i)) return '--agent=';+ return a;+ });}export function parse(argv) {@@ -171,6 +200,7 @@ const COMMANDS = {setup: async (ctx) => (await import('./commands/setup.js')).setup(ctx),login: async (ctx) => (await import('./commands/account.js')).login(ctx),link: async (ctx) => (await import('./commands/account.js')).link(ctx),+ signup: async (ctx) => (await import('./commands/signup.js')).signup(ctx),logout: async (ctx) => (await import('./commands/account.js')).logout(ctx),status: async (ctx) => (await import('./commands/account.js')).status(ctx),whoami: async (ctx) => (await import('./commands/account.js')).whoami(ctx),@@ -196,6 +226,8 @@ const COMMANDS = {await runProxy({ url, server: ctx.flags.server || null, env: ctx.env });return 0;},+ pay: async (ctx) => (await import('./commands/pay.js')).payCommand(ctx),+ wallet: async (ctx) => (await import('./commands/wallet.js')).wallet(ctx),fund: async (ctx) => (await import('./commands/inference.js')).fund(ctx),provider: async (ctx) => (await import('./commands/inference.js')).provider(ctx),usage: async (ctx) => (await import('./commands/inference.js')).usage(ctx),@@ -243,10 +275,10 @@ export async function main(argv = process.argv.slice(2), env = systemEnv()) {errorLine('Cancelled. Nothing after the last completed step was changed.');return 130;}- if (flags.json) printJson({ error: err.code || 'error', message: err.message, status: err instanceof ApiError ? err.status : undefined });+ if (flags.json) printJson({ error: err.code || 'error', message: err.message, exit: err.exit, detail: err.detail, status: err instanceof ApiError ? err.status : undefined });else errorLine(err.message);if (env.vars.THREE_WS_DEBUG === '1' && err.stack) process.stderr.write(`${err.stack}\n`);- return 1;+ return Number.isInteger(err.exit) ? err.exit : 1;}}diff --git a/packages/three-ws-cli/src/commands/pay.js b/packages/three-ws-cli/src/commands/pay.jsnew file mode 100644index 000000000..13ee3aa92--- /dev/null+++ b/packages/three-ws-cli/src/commands/pay.js@@ -0,0 +1,140 @@+// `three-ws pay <url>`: settle an x402 or MPP challenge from a locally held+// Solana key, inside the limits of ~/.config/three-ws/pay-permissions.json.+// pay <url> [--max <amount>] [--network <net>] [--dry-run] [--yes] [--json]+// pay init write a conservative permissions file+// pay permissions show the active policy and where it lives+// pay mcp stdio MCP server exposing pay_fetch and pay_quote++import * as p from '@clack/prompts';+import { c, errorLine, line, printJson, rows, sym, tildify } from '../ui.js';+import { createKeystore } from '../pay/keystore.js';+import { EXIT, PayError } from '../pay/errors.js';+import { pay, quote } from '../pay/engine.js';+import { describeOffer, initPermissions, loadPermissions, permissionsPath } from '../pay/permissions.js';+import { answer } from './common.js';++const interactive = (ctx) => Boolean(process.stdin.isTTY && process.stderr.isTTY && !ctx.flags.json);++export function keystoreFor(ctx) {+ return createKeystore({+ env: ctx.env,+ askPassphrase: interactive(ctx) ? async (question) => answer(await p.password({ message: question })) : undefined,+ });+}++function requestFrom(flags) {+ const headers = {};+ for (const h of flags.header ?? []) {+ const i = h.indexOf(':');+ if (i < 1) throw new PayError(EXIT.USAGE, 'invalid_header', `--header "${h}" must look like "Name: value".`);+ headers[h.slice(0, i).trim()] = h.slice(i + 1).trim();+ }+ return { method: flags.method?.toUpperCase(), body: flags.data, headers };+}++function offerRows(offer, extra = []) {+ rows([+ ['protocol', offer.protocol === 'x402' ? 'x402' : 'MPP'],+ ['network', offer.network],+ ['amount', `${offer.amount} (${offer.amountAtomic} atomic)`],+ ['asset', offer.asset],+ ['payee', offer.payTo],+ ...extra,+ ]);+}++async function dryRun(ctx, url) {+ const q = await quote({ url, env: ctx.env, request: requestFrom(ctx.flags), maxFlag: ctx.flags.max, networkFlag: ctx.flags.network });+ if (q.free) {+ if (ctx.flags.json) printJson({ dryRun: true, paymentRequired: false, status: q.response.status, url });+ else line(`${c.dim(sym.dot)} ${url} did not ask for payment (HTTP ${q.response.status}). Nothing would be paid.`);+ return EXIT.OK;+ }+ const chosen = describeOffer(q.decision.offer);+ if (ctx.flags.json) {+ printJson({ dryRun: true, paymentRequired: true, url, decision: 'allowed', needsConfirmation: q.decision.confirm, chosen, offers: q.offers, skipped: q.decision.skipped });+ return EXIT.OK;+ }+ line(`${c.bold('Dry run')}: nothing was signed or sent.`);+ offerRows(chosen, [['decision', q.decision.confirm ? 'allowed, asks for confirmation (above confirmAbove)' : 'allowed by pay-permissions.json']]);+ for (const s of q.decision.skipped) line(`${c.dim(sym.dot)} skipped ${s.offer.protocol} ${s.offer.network}: ${s.message}`);+ return EXIT.OK;+}++async function settle(ctx, url) {+ const confirm = interactive(ctx)+ ? async (s) => answer(await p.confirm({ message: `Pay ${s.amount} to ${s.payTo} on ${s.network} for ${s.url}?` }))+ : undefined;+ const result = await pay({+ url,+ env: ctx.env,+ request: requestFrom(ctx.flags),+ maxFlag: ctx.flags.max,+ networkFlag: ctx.flags.network,+ assumeYes: Boolean(ctx.flags.yes),+ confirm,+ keystore: keystoreFor(ctx),+ });+ if (ctx.flags.json) {+ const isText = /^(text\/|application\/(json|xml)|[\w.+-]*\/[\w.+-]*\+(json|xml))/i.test(result.contentType);+ printJson({+ paid: result.paid,+ status: result.status,+ protocol: result.protocol,+ payer: result.payer,+ offer: result.offer,+ receipt: result.receipt,+ contentType: result.contentType,+ ...(isText ? { body: result.bytes.toString('utf8') } : { bodyBase64: result.bytes.toString('base64') }),+ });+ } else {+ if (result.paid) {+ const tx = result.receipt?.transaction ?? result.receipt?.reference;+ process.stderr.write(`${c.green(sym.ok)} paid ${result.offer.amount} to ${result.offer.payTo} (${result.protocol}, ${result.offer.network})${tx ? ` tx ${tx}` : ''}\n`);+ } else {+ process.stderr.write(`${c.dim(sym.dot)} no payment requested (HTTP ${result.status})\n`);+ }+ process.stdout.write(result.bytes);+ if (result.bytes.length && result.bytes[result.bytes.length - 1] !== 0x0a && process.stdout.isTTY) process.stdout.write('\n');+ }+ return result.status >= 400 ? EXIT.ERROR : EXIT.OK;+}++function showPermissions(ctx) {+ const file = permissionsPath(ctx.env);+ const perms = loadPermissions(ctx.env);+ if (ctx.flags.json) printJson({ path: file, permissions: perms });+ else {+ line(`${c.bold('Permissions')} ${c.dim(tildify(file))}`);+ line(JSON.stringify(perms, null, 2));+ }+ return EXIT.OK;+}++function initFile(ctx) {+ const file = initPermissions(ctx.env);+ if (ctx.flags.json) printJson({ path: permissionsPath(ctx.env), created: Boolean(file) });+ else if (file) line(`${c.green(sym.ok)} Wrote ${tildify(file)}: https://three.ws only, Solana mainnet USDC, 0.10 per call, 1.00 per day, confirm above 0.05. Edit it to widen or narrow.`);+ else line(`${c.dim(sym.dot)} ${tildify(permissionsPath(ctx.env))} already exists; left unchanged.`);+ return EXIT.OK;+}++export async function payCommand(ctx) {+ const [first, ...rest] = ctx.positionals;+ if (!first) {+ errorLine('usage: three-ws pay <url> [--max <amount>] [--network <net>] [--dry-run] | pay init | pay permissions | pay mcp');+ return EXIT.USAGE;+ }+ if (first === 'init') return initFile(ctx);+ if (first === 'permissions') return showPermissions(ctx);+ if (first === 'mcp') {+ const { runPayMcp } = await import('../pay/mcp-server.js');+ await runPayMcp({ env: ctx.env, keystore: keystoreFor({ ...ctx, flags: { ...ctx.flags, json: true } }) });+ return EXIT.OK;+ }+ if (rest.length) {+ errorLine(`unexpected argument "${rest[0]}". Quote URLs that contain & or ?.`);+ return EXIT.USAGE;+ }+ return ctx.flags['dry-run'] ? dryRun(ctx, first) : settle(ctx, first);+}diff --git a/packages/three-ws-cli/src/commands/wallet.js b/packages/three-ws-cli/src/commands/wallet.jsnew file mode 100644index 000000000..7e97c5a64--- /dev/null+++ b/packages/three-ws-cli/src/commands/wallet.js@@ -0,0 +1,50 @@+// `three-ws wallet`: the local Solana key that `three-ws pay` signs with.+// wallet init [--storage auto|keychain|file] create a key; keychain first, sealed file otherwise+// wallet address address and where the key is held+// wallet export-public the bare address, for scripts and funding+// There is no command that prints the private key. Back it up by holding the+// keychain entry or the sealed file plus its passphrase.++import { c, errorLine, line, printJson, rows, sym, tildify } from '../ui.js';+import { EXIT, PayError } from '../pay/errors.js';+import { walletSealedPath } from '../pay/keystore.js';+import { keystoreFor } from './pay.js';++const STORAGE = ['auto', 'keychain', 'file'];++export async function wallet(ctx) {+ const [sub] = ctx.positionals;+ const store = keystoreFor(ctx);+ if (sub === 'init') {+ const storage = ctx.flags.storage ?? 'auto';+ if (!STORAGE.includes(storage)) throw new PayError(EXIT.USAGE, 'invalid_storage', `--storage must be one of ${STORAGE.join(', ')}.`);+ const made = await store.init({ storage });+ if (ctx.flags.json) printJson(made);+ else {+ line(`${c.green(sym.ok)} Wallet created.`);+ rows(+ [+ ['address', made.address],+ ['key held in', made.storage === 'keychain' ? 'the OS keychain' : `a passphrase-sealed file (${tildify(walletSealedPath(ctx.env))})`],+ ],+ ' ',+ );+ line(`Fund it with USDC on Solana, then set limits with \`three-ws pay init\`. The private key is never printed.`);+ }+ return EXIT.OK;+ }+ if (sub === 'address') {+ const a = store.address();+ if (ctx.flags.json) printJson(a);+ else rows([['address', a.address], ['key held in', a.storage]]);+ return EXIT.OK;+ }+ if (sub === 'export-public') {+ const a = store.address();+ if (ctx.flags.json) printJson({ address: a.address });+ else line(a.address);+ return EXIT.OK;+ }+ errorLine('usage: three-ws wallet <init [--storage auto|keychain|file]|address|export-public>');+ return EXIT.USAGE;+}diff --git a/packages/three-ws-cli/src/pay/x402.js b/packages/three-ws-cli/src/pay/x402.jsindex fb04affe9..c5e77e4dd 100644--- a/packages/three-ws-cli/src/pay/x402.js+++ b/packages/three-ws-cli/src/pay/x402.js@@ -19,9 +19,14 @@ export function rpcUrlFor(network, env) {* @returns {Promise<{ headers: Record<string,string>, httpClient: x402HTTPClient }>}*/export async function signX402({ offer, signer, rpcUrl }) {- const client = new x402Client();- if (offer.version === 1) client.registerV1(offer.raw.network, new ExactSvmSchemeV1(signer, { rpcUrl }));- else client.register(offer.network, new ExactSvmScheme(signer, { rpcUrl }));+ const v1 = offer.version === 1;+ const network = v1 ? offer.raw.network : offer.network;+ // The library's own spend controls are a second lock behind the permissions+ // file: this one asset on this one network, capped at the exact amount decided.+ const client = x402Client.fromConfig({+ schemes: [{ network, x402Version: v1 ? 1 : 2, client: v1 ? new ExactSvmSchemeV1(signer, { rpcUrl }) : new ExactSvmScheme(signer, { rpcUrl }) }],+ spendControls: { maxAmountPerPayment: false, allowedAssets: [{ network, asset: offer.asset, maxAmountPerPayment: offer.amountAtomic.toString() }] },+ });// Only the chosen option is offered to the client, so it cannot pay any other one.const required = { ...offer.required, accepts: [offer.raw] };let payload;diff --git a/packages/three-ws-cli/tests/pay-cli.test.js b/packages/three-ws-cli/tests/pay-cli.test.jsnew file mode 100644index 000000000..8b2c9aafb--- /dev/null+++ b/packages/three-ws-cli/tests/pay-cli.test.js@@ -0,0 +1,147 @@+// The command surface: `three-ws pay` through main() for exit codes and --json,+// and `three-ws pay mcp` as a real stdio child process driven by an MCP client.++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import { generateKeyPairSigner } from '@solana/kit';+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { main } from '../src/cli.js';+import { EXIT } from '../src/pay/errors.js';+import { SOLANA_DEVNET, USDC_DEVNET } from '../src/pay/permissions.js';+import { startPaidServer, startRpc, tempEnv, writePermissions } from './pay-helpers.js';++const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'cli.js');+const PASSPHRASE = 'correct horse battery staple';++let rpc;+const servers = [];+beforeAll(async () => {+ rpc = await startRpc();+});+afterAll(() => rpc.close());+afterEach(async () => {+ vi.restoreAllMocks();+ while (servers.length) await servers.pop().close();+});++async function fixture(perms = {}) {+ const payTo = (await generateKeyPairSigner()).address;+ const server = await startPaidServer({ payTo });+ servers.push(server);+ const env = tempEnv({ THREE_WS_SOLANA_RPC_URL: rpc.url, THREE_WS_WALLET_PASSPHRASE: PASSPHRASE, NO_COLOR: '1' });+ env.vars.XDG_CONFIG_HOME = path.join(env.home, '.config');+ writePermissions(env, { version: 1, allowedOrigins: [server.origin], allowedNetworks: [SOLANA_DEVNET], allowedAssets: [USDC_DEVNET], maxPerCall: '0.05', ...perms });+ return { server, env, payTo };+}++async function run(argv, env) {+ let out = '';+ let err = '';+ vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => ((out += chunk.toString()), true));+ vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => ((err += chunk.toString()), true));+ const code = await main(argv, env);+ vi.restoreAllMocks();+ return { code, out, err };+}++describe('three-ws wallet', () => {+ it('init, address and export-public agree, and no command prints the key', async () => {+ const { env } = await fixture();+ const init = await run(['wallet', 'init', '--storage', 'file', '--json'], env);+ expect(init.code).toBe(0);+ const { address } = JSON.parse(init.out);+ expect((await run(['wallet', 'export-public'], env)).out.trim()).toBe(address);+ expect(JSON.parse((await run(['wallet', 'address', '--json'], env)).out)).toMatchObject({ address, storage: 'file' });+ const again = await run(['wallet', 'init', '--storage', 'file'], env);+ expect(again.code).toBe(1);+ expect(again.err).toMatch(/never overwrites/);+ const all = fs.readdirSync(path.join(env.home, '.config', 'three-ws')).map((f) => fs.readFileSync(path.join(env.home, '.config', 'three-ws', f), 'utf8')).join('');+ expect(all).not.toMatch(/secret|privateKey/i);+ });+});++describe('three-ws pay', () => {+ it('--dry-run prints payee, amount and network and exits 0 without a wallet', async () => {+ const { server, env, payTo } = await fixture();+ const human = await run(['pay', server.url, '--dry-run'], env);+ expect(human.code).toBe(0);+ expect(human.out).toContain(payTo);+ expect(human.out).toContain('0.01');+ expect(human.out).toContain(SOLANA_DEVNET);++ const json = await run(['pay', server.url, '--dry-run', '--json'], env);+ const parsed = JSON.parse(json.out);+ expect(parsed).toMatchObject({ dryRun: true, decision: 'allowed', chosen: { payTo, amountAtomic: '10000', network: SOLANA_DEVNET } });+ expect(server.paid).toHaveLength(0);+ });++ it('exits 10 with a stable reason when the challenge is outside the permissions', async () => {+ const { server, env } = await fixture({ maxPerCall: '0.005' });+ const refused = await run(['pay', server.url, '--json'], env);+ expect(refused.code).toBe(EXIT.PERMISSION_DENIED);+ expect(JSON.parse(refused.out)).toMatchObject({ error: 'per_call_limit', exit: 10 });+ const dry = await run(['pay', server.url, '--dry-run'], env);+ expect(dry.code).toBe(EXIT.PERMISSION_DENIED);+ expect(dry.err).toMatch(/maxPerCall/);+ expect(server.paid).toHaveLength(0);+ });++ it('pays and prints the body, with the receipt on stderr', async () => {+ const { server, env } = await fixture();+ await run(['wallet', 'init', '--storage', 'file'], env);+ const paid = await run(['pay', server.url], env);+ expect(paid.code).toBe(0);+ expect(JSON.parse(paid.out).data).toBe('paid content');+ expect(paid.err).toMatch(/paid 0\.01 to/);+ });++ it('init writes the default permissions file once', async () => {+ const env = tempEnv();+ env.vars.XDG_CONFIG_HOME = path.join(env.home, '.config');+ expect((await run(['pay', 'init', '--json'], env)).out).toContain('"created": true');+ expect((await run(['pay', 'init', '--json'], env)).out).toContain('"created": false');+ });++ it('--max is a hard ceiling and a bad flag is a usage error', async () => {+ const { server, env } = await fixture();+ expect((await run(['pay', server.url, '--max', '0.001', '--json'], env)).code).toBe(EXIT.PERMISSION_DENIED);+ expect((await run(['pay'], env)).code).toBe(EXIT.USAGE);+ });+});++describe('three-ws pay mcp', () => {+ it('serves pay_quote and pay_fetch over stdio under the same permissions', async () => {+ const { server, env } = await fixture();+ await run(['wallet', 'init', '--storage', 'file'], env);+ const transport = new StdioClientTransport({+ command: process.execPath,+ args: [CLI, 'pay', 'mcp'],+ env: { PATH: process.env.PATH, HOME: env.home, XDG_CONFIG_HOME: env.vars.XDG_CONFIG_HOME, THREE_WS_SOLANA_RPC_URL: rpc.url, THREE_WS_WALLET_PASSPHRASE: PASSPHRASE },+ });+ const client = new Client({ name: 'test', version: '1.0.0' });+ await client.connect(transport);+ try {+ const tools = (await client.listTools()).tools.map((t) => t.name).sort();+ expect(tools).toEqual(['pay_fetch', 'pay_quote']);++ const quoted = await client.callTool({ name: 'pay_quote', arguments: { url: server.url } });+ expect(JSON.parse(quoted.content[0].text)).toMatchObject({ paymentRequired: true, chosen: { amount: '0.01', network: SOLANA_DEVNET } });+ expect(server.paid).toHaveLength(0);++ const refused = await client.callTool({ name: 'pay_fetch', arguments: { url: server.url, max: '0.001' } });+ expect(refused.isError).toBe(true);+ expect(JSON.parse(refused.content[0].text)).toMatchObject({ error: 'max_flag_exceeded', exit: 10 });++ const fetched = await client.callTool({ name: 'pay_fetch', arguments: { url: server.url } });+ const body = JSON.parse(fetched.content[0].text);+ expect(body).toMatchObject({ paid: true, status: 200 });+ expect(JSON.parse(body.body).data).toBe('paid content');+ expect(server.paid).toHaveLength(1);+ } finally {+ await client.close();+ }+ }, 30_000);+});diff --git a/packages/three-ws-cli/tests/pay-flow.test.js b/packages/three-ws-cli/tests/pay-flow.test.jsnew file mode 100644index 000000000..5e65ed414--- /dev/null+++ b/packages/three-ws-cli/tests/pay-flow.test.js@@ -0,0 +1,222 @@+// End to end against a real local 402 server: real HTTP, real challenge parsing,+// real ed25519 signing with a devnet keypair generated in the test. Only the+// chain is stood in for (a local JSON-RPC node that serves the USDC mint).++import fs from 'node:fs';+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';+import { generateKeyPairSigner } from '@solana/kit';+import { EXIT, PayError, REASON } from '../src/pay/errors.js';+import { pay, quote } from '../src/pay/engine.js';+import { createKeystore } from '../src/pay/keystore.js';+import { ledgerPath, SOLANA_DEVNET, USDC_DEVNET } from '../src/pay/permissions.js';+import { inspectTransaction, startPaidServer, startRpc, tempEnv, writePermissions } from './pay-helpers.js';++let rpc;+const servers = [];++beforeAll(async () => {+ rpc = await startRpc();+});+afterAll(() => rpc.close());+afterEach(async () => {+ while (servers.length) await servers.pop().close();+});++async function setup({ mode = 'x402v2', price = '10000', perms = {}, serverOpts = {} } = {}) {+ const payee = (await generateKeyPairSigner()).address;+ const server = await startPaidServer({ mode, price, payTo: payee, ...serverOpts });+ servers.push(server);+ const env = tempEnv({ THREE_WS_SOLANA_RPC_URL: rpc.url, THREE_WS_WALLET_PASSPHRASE: 'correct horse battery staple' });+ writePermissions(env, {+ version: 1,+ allowedOrigins: [server.origin],+ allowedNetworks: [SOLANA_DEVNET],+ allowedAssets: [USDC_DEVNET],+ maxPerCall: '0.05',+ maxPerDay: '0.10',+ confirmAbove: '0.03',+ ...perms,+ });+ const keystore = createKeystore({ env, keyring: async () => Promise.reject(new Error('no keychain in test')) });+ const wallet = await keystore.init({ storage: 'file' });+ return { server, env, keystore, wallet, payee };+}++describe('x402 v2', () => {+ it('dry run reports payee, exact amount and network and signs nothing', async () => {+ const { server, env, payee } = await setup();+ const q = await quote({ url: server.url, env });+ expect(q.free).toBe(false);+ expect(q.decision.offer.payTo).toBe(payee);+ expect(q.decision.offer.amountAtomic).toBe(10000n);+ expect(q.decision.offer.network).toBe(SOLANA_DEVNET);+ expect(q.decision.confirm).toBe(false);+ expect(server.seen).toHaveLength(1);+ expect(server.paid).toHaveLength(0);+ });++ it('pays with a real signature the payer key produced, retries once and records the spend', async () => {+ const { server, env, keystore, wallet, payee } = await setup();+ const result = await pay({ url: server.url, env, keystore });+ expect(result.paid).toBe(true);+ expect(result.status).toBe(200);+ expect(JSON.parse(result.bytes.toString()).data).toBe('paid content');+ expect(result.receipt.transaction).toBe('fixture-signature');+ expect(result.payer).toBe(wallet.address);+ expect(server.seen).toHaveLength(2);+ expect(server.paid).toHaveLength(1);++ const sent = await inspectTransaction(server.paid[0].payload.payload.transaction, wallet.address);+ expect(sent.signedByPayer).toBe(true);+ expect(sent.signatureValid).toBe(true);+ expect(sent.tx.signatures[server.feePayer]).toBeNull(); // the server's fee payer slot is left for the server+ expect(server.paid[0].payload.accepted.payTo).toBe(payee);++ const ledger = JSON.parse(fs.readFileSync(ledgerPath(env), 'utf8'));+ expect(ledger.spent[`${SOLANA_DEVNET}|${USDC_DEVNET}`]).toBe('10000');+ });++ it('forwards method and body on the paid retry', async () => {+ const { server, env, keystore } = await setup();+ const result = await pay({ url: server.url, env, keystore, request: { method: 'POST', body: '{"q":1}', headers: { 'content-type': 'application/json' } } });+ expect(JSON.parse(result.bytes.toString()).echoed).toBe('{"q":1}');+ expect(server.seen.map((s) => s.method)).toEqual(['POST', 'POST']);+ });++ it('passes a free resource through without a wallet or a permissions file', async () => {+ const env = tempEnv();+ const fetchImpl = async () => new Response('free content', { status: 200, headers: { 'content-type': 'text/plain' } });+ const q = await quote({ url: 'http://127.0.0.1:1/free', env, fetchImpl });+ expect(q.free).toBe(true);+ const result = await pay({ url: 'http://127.0.0.1:1/free', env, keystore: null, fetchImpl });+ expect(result).toMatchObject({ paid: false, status: 200 });+ expect(result.bytes.toString()).toBe('free content');+ });+});++describe('x402 v1', () => {+ it('settles a v1 body challenge (network "solana-devnet") with X-PAYMENT', async () => {+ const { server, env, keystore, wallet } = await setup({ mode: 'x402v1' });+ const result = await pay({ url: server.url, env, keystore });+ expect(result.paid).toBe(true);+ const sent = await inspectTransaction(server.paid[0].payload.payload.transaction, wallet.address);+ expect(sent.signatureValid).toBe(true);+ });+});++describe('MPP solana charge', () => {+ it('answers a Payment challenge with a signed pull-mode credential bound to the challenge', async () => {+ const { server, env, keystore, wallet, payee } = await setup({ mode: 'mpp' });+ const q = await quote({ url: server.url, env });+ expect(q.decision.offer.protocol).toBe('mpp');+ expect(q.decision.offer.payTo).toBe(payee);++ const result = await pay({ url: server.url, env, keystore });+ expect(result.paid).toBe(true);+ expect(result.receipt.reference).toBe('fixture-signature');+ const { credential } = server.paid[0];+ expect(credential.challenge.id).toBe('test-challenge-1');+ expect(credential.source).toBe(wallet.address);+ expect(credential.payload.type).toBe('transaction');+ const sent = await inspectTransaction(credential.payload.transaction, wallet.address);+ expect(sent.signatureValid).toBe(true);+ expect(sent.tx.signatures[server.feePayer]).toBeNull();+ expect(sent.size).toBeLessThanOrEqual(1232);+ });+});++describe('permissions are enforced before anything is signed', () => {+ async function expectRefusal(promise, reason) {+ const err = await promise.then(() => null, (e) => e);+ expect(err).toBeInstanceOf(PayError);+ expect(err.exit).toBe(EXIT.PERMISSION_DENIED);+ expect(err.reason).toBe(reason);+ return err;+ }++ it('refuses an origin that is not allowed', async () => {+ const { server, env, keystore } = await setup({ perms: { allowedOrigins: ['https://three.ws'] } });+ await expectRefusal(pay({ url: server.url, env, keystore }), REASON.originNotAllowed);+ expect(server.paid).toHaveLength(0);+ });++ it('refuses a network that is not allowed', async () => {+ const { server, env, keystore } = await setup({ perms: { allowedNetworks: ['solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'] } });+ await expectRefusal(pay({ url: server.url, env, keystore }), REASON.networkNotAllowed);+ });++ it('refuses an amount above maxPerCall and above --max', async () => {+ const over = await setup({ price: '60000' });+ await expectRefusal(pay({ url: over.server.url, env: over.env, keystore: over.keystore }), REASON.perCallLimit);+ const flagged = await setup({ price: '10000' });+ await expectRefusal(pay({ url: flagged.server.url, env: flagged.env, keystore: flagged.keystore, maxFlag: '0.005' }), REASON.maxFlag);+ });++ it('refuses once the daily limit would be crossed', async () => {+ const { server, env, keystore } = await setup({ price: '30000', perms: { confirmAbove: '1.00' } });+ for (let i = 0; i < 3; i++) await pay({ url: server.url, env, keystore });+ await expectRefusal(pay({ url: server.url, env, keystore }), REASON.dailyLimit);+ expect(server.paid).toHaveLength(3);+ });++ it('refuses a payee outside allowedPayees', async () => {+ const stranger = (await generateKeyPairSigner()).address;+ const { server, env, keystore } = await setup({ perms: { allowedPayees: [stranger] } });+ await expectRefusal(pay({ url: server.url, env, keystore }), REASON.payeeNotAllowed);+ });++ it('refuses every payment when there is no permissions file', async () => {+ const { server, env, keystore } = await setup();+ fs.rmSync(env.vars.THREE_WS_PAY_PERMISSIONS ?? `${env.home}/.config/three-ws/pay-permissions.json`);+ await expectRefusal(pay({ url: server.url, env, keystore }), REASON.permissionsMissing);+ });++ it('exits 11 above confirmAbove with nobody to ask, and pays when approved', async () => {+ const { server, env, keystore } = await setup({ price: '40000' });+ const err = await pay({ url: server.url, env, keystore }).then(() => null, (e) => e);+ expect(err.exit).toBe(EXIT.CONFIRMATION_REQUIRED);+ expect(err.reason).toBe(REASON.confirmRequired);++ const declined = await pay({ url: server.url, env, keystore, confirm: async () => false }).then(() => null, (e) => e);+ expect(declined.reason).toBe(REASON.declined);+ expect(server.paid).toHaveLength(0);++ const approved = await pay({ url: server.url, env, keystore, confirm: async (s) => s.amount === '0.04' });+ expect(approved.paid).toBe(true);+ });+});++describe('failure handling', () => {+ it('exits 13 and records nothing when the server rejects the payment', async () => {+ const { server, env, keystore } = await setup({ serverOpts: { rejectPayment: true } });+ const err = await pay({ url: server.url, env, keystore }).then(() => null, (e) => e);+ expect(err.exit).toBe(EXIT.PAYMENT_REJECTED);+ expect(fs.existsSync(ledgerPath(env))).toBe(false);+ });++ it('exits 14 when there is no wallet', async () => {+ const { server, env } = await setup();+ const empty = createKeystore({ env: { ...env, home: `${env.home}/other` }, keyring: async () => Promise.reject(new Error('none')) });+ const err = await pay({ url: server.url, env, keystore: empty }).then(() => null, (e) => e);+ expect(err.exit).toBe(EXIT.WALLET_UNAVAILABLE);+ });++ it('exits 12 when the server offers nothing payable here', async () => {+ const { env } = await setup();+ const fetchImpl = async () =>+ new Response('{}', { status: 402, headers: { 'payment-required': Buffer.from(JSON.stringify({ x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '1', asset: '0xabc', payTo: '0xdef' }] })).toString('base64') } });+ const err = await quote({ url: 'http://127.0.0.1:1/x', env, fetchImpl }).then(() => null, (e) => e);+ expect(err.exit).toBe(EXIT.NO_PAYABLE_OPTION);+ });++ it('never follows a redirect with a payment attached', async () => {+ const { env, keystore } = await setup();+ const fetchImpl = async (url, init) => {+ expect(init.redirect).toBe('manual');+ return new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/' } });+ };+ const result = await pay({ url: 'http://127.0.0.1:1/x', env, keystore, fetchImpl });+ expect(result.paid).toBe(false);+ expect(result.status).toBe(302);+ });+});diff --git a/packages/three-ws-cli/tests/pay-helpers.js b/packages/three-ws-cli/tests/pay-helpers.jsnew file mode 100644index 000000000..fc46adb04--- /dev/null+++ b/packages/three-ws-cli/tests/pay-helpers.js@@ -0,0 +1,157 @@+// Real local servers for the pay tests: a JSON-RPC node that answers the one+// account lookup the signer needs (the USDC mint), and a paid HTTP resource that+// speaks x402 v2, x402 v1 or MPP and checks the transaction it is handed.++import fs from 'node:fs';+import http from 'node:http';+import os from 'node:os';+import path from 'node:path';+import {+ generateKeyPairSigner,+ getBase64Encoder,+ getTransactionDecoder,+ getPublicKeyFromAddress,+ verifySignature,+} from '@solana/kit';+import { b64urlDecodeJson, b64urlEncode, canonicalJson } from '../src/pay/encoding.js';+import { SOLANA_DEVNET, USDC_DEVNET } from '../src/pay/permissions.js';++export const TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';+// A real recent blockhash is not needed offline: any 32-byte base58 value compiles.+export const FIXED_BLOCKHASH = '4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi';++export function tempEnv(vars = {}) {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'three-ws-pay-'));+ return { home, platform: 'linux', cwd: home, vars: { ...vars } };+}++/** SPL Token mint account bytes: initialized, 6 decimals, no authorities. */+function mintAccountBase64(decimals) {+ const data = Buffer.alloc(82);+ data.writeUInt32LE(0, 0); // no mint authority+ data.writeBigUInt64LE(1_000_000_000n, 36); // supply+ data.writeUInt8(decimals, 44);+ data.writeUInt8(1, 45); // initialized+ data.writeUInt32LE(0, 46); // no freeze authority+ return data.toString('base64');+}++function listen(server) {+ return new Promise((resolve) => {+ server.listen(0, '127.0.0.1', () => resolve(`http://127.0.0.1:${server.address().port}`));+ });+}++const close = (server) => () => new Promise((resolve) => server.close(resolve));++export async function startRpc({ decimals = 6 } = {}) {+ const calls = [];+ const server = http.createServer((req, res) => {+ let body = '';+ req.on('data', (d) => (body += d));+ req.on('end', () => {+ const rpc = JSON.parse(body);+ calls.push(rpc.method);+ let result;+ if (rpc.method === 'getAccountInfo') {+ result = {+ context: { slot: 1 },+ value: { data: [mintAccountBase64(decimals), 'base64'], executable: false, lamports: 1461600, owner: TOKEN_PROGRAM, rentEpoch: 0, space: 82 },+ };+ }+ if (rpc.method === 'getLatestBlockhash') {+ result = { context: { slot: 1 }, value: { blockhash: FIXED_BLOCKHASH, lastValidBlockHeight: 100 } };+ }+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(result === undefined ? { jsonrpc: '2.0', id: rpc.id, error: { code: -32601, message: `unexpected ${rpc.method}` } } : { jsonrpc: '2.0', id: rpc.id, result }));+ });+ });+ const url = await listen(server);+ return { url, calls, close: close(server) };+}++/** Decode a base64 wire transaction and check the payer's signature really covers the message. */+export async function inspectTransaction(base64, payerAddress) {+ const bytes = getBase64Encoder().encode(base64);+ const tx = getTransactionDecoder().decode(bytes);+ const signature = tx.signatures[payerAddress];+ const key = await getPublicKeyFromAddress(payerAddress);+ const verified = signature ? await verifySignature(key, signature, tx.messageBytes) : false;+ return { tx, signedByPayer: Boolean(signature), signatureValid: verified, size: bytes.length, message: Buffer.from(tx.messageBytes) };+}++/**+ * A paid resource on a random port.+ * mode: 'x402v2' | 'x402v1' | 'mpp'. `price` is atomic units of the devnet USDC mint.+ * Every request is recorded in `seen`; a request carrying valid payment gets a 200.+ */+export async function startPaidServer({ mode = 'x402v2', price = '10000', payTo, network = SOLANA_DEVNET, asset = USDC_DEVNET, rejectPayment = false } = {}) {+ const feePayer = (await generateKeyPairSigner()).address;+ const seen = [];+ const paid = [];+ let baseUrl = '';+ const server = http.createServer(async (req, res) => {+ seen.push({ method: req.method, url: req.url, headers: req.headers });+ let body = '';+ for await (const chunk of req) body += chunk;+ const send = (status, headers, text) => {+ res.writeHead(status, headers);+ res.end(text);+ };+ const challenge402 = () => {+ if (mode === 'x402v2') {+ const required = {+ x402Version: 2,+ error: 'PAYMENT-SIGNATURE header is required',+ resource: { url: `${baseUrl}${req.url}`, description: 'fixture', mimeType: 'application/json' },+ accepts: [{ scheme: 'exact', network, amount: price, asset, payTo, maxTimeoutSeconds: 60, extra: { feePayer, recentBlockhash: FIXED_BLOCKHASH } }],+ };+ return send(402, { 'content-type': 'application/json', 'payment-required': Buffer.from(JSON.stringify(required)).toString('base64') }, '{}');+ }+ if (mode === 'x402v1') {+ const required = {+ x402Version: 1,+ error: 'X-PAYMENT header is required',+ accepts: [{ scheme: 'exact', network: 'solana-devnet', maxAmountRequired: price, resource: `${baseUrl}${req.url}`, description: 'fixture', mimeType: 'application/json', payTo, maxTimeoutSeconds: 60, asset, extra: { feePayer, recentBlockhash: FIXED_BLOCKHASH } }],+ };+ return send(402, { 'content-type': 'application/json' }, JSON.stringify(required));+ }+ const request = {+ amount: price,+ currency: asset,+ recipient: payTo,+ description: 'fixture',+ methodDetails: { network: 'devnet', decimals: 6, tokenProgram: TOKEN_PROGRAM, feePayer: true, feePayerKey: feePayer, recentBlockhash: FIXED_BLOCKHASH },+ };+ const auth = `Payment id="test-challenge-1", realm="127.0.0.1", method="solana", intent="charge", request="${b64urlEncode(canonicalJson(request))}", expires="2999-01-01T00:00:00Z"`;+ return send(402, { 'www-authenticate': auth, 'content-type': 'application/problem+json' }, '{"type":"payment-required"}');+ };++ if (rejectPayment) return challenge402();++ if (mode === 'x402v2' || mode === 'x402v1') {+ const header = req.headers[mode === 'x402v2' ? 'payment-signature' : 'x-payment'];+ if (!header) return challenge402();+ const payload = JSON.parse(Buffer.from(header, 'base64').toString('utf8'));+ paid.push({ payload, body });+ const receipt = { success: true, transaction: 'fixture-signature', network };+ return send(200, { 'content-type': 'application/json', ...(mode === 'x402v2' ? { 'payment-response': Buffer.from(JSON.stringify(receipt)).toString('base64') } : { 'x-payment-response': Buffer.from(JSON.stringify(receipt)).toString('base64') }) }, JSON.stringify({ data: 'paid content', echoed: body }));+ }++ const authorization = req.headers.authorization;+ if (!authorization?.startsWith('Payment ')) return challenge402();+ const credential = b64urlDecodeJson(authorization.slice('Payment '.length));+ paid.push({ credential, body });+ const receipt = { method: 'solana', challengeId: credential.challenge.id, reference: 'fixture-signature', status: 'success', timestamp: new Date().toISOString() };+ return send(200, { 'content-type': 'application/json', 'payment-receipt': b64urlEncode(JSON.stringify(receipt)) }, JSON.stringify({ data: 'paid content' }));+ });+ baseUrl = await listen(server);+ return { url: `${baseUrl}/api/paid`, origin: baseUrl, feePayer, seen, paid, close: close(server) };+}++export function writePermissions(env, perms) {+ const file = env.vars.THREE_WS_PAY_PERMISSIONS ?? path.join(env.home, '.config', 'three-ws', 'pay-permissions.json');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, JSON.stringify(perms));+ return file;+}diff --git a/packages/three-ws-cli/tests/pay-units.test.js b/packages/three-ws-cli/tests/pay-units.test.jsnew file mode 100644index 000000000..52db0c2af--- /dev/null+++ b/packages/three-ws-cli/tests/pay-units.test.js@@ -0,0 +1,189 @@+import fs from 'node:fs';+import { describe, expect, it } from 'vitest';+import { b64urlDecode, b64urlEncode, canonicalJson } from '../src/pay/encoding.js';+import { parseAuthenticate, readChallenge } from '../src/pay/challenge.js';+import { EXIT, REASON } from '../src/pay/errors.js';+import { createKeystore, seal, unseal, walletMetaPath, walletSealedPath } from '../src/pay/keystore.js';+import {+ atomicToDecimal,+ decimalToAtomic,+ evaluateOffer,+ initPermissions,+ loadPermissions,+ normalizeNetwork,+ permissionsPath,+ SOLANA_DEVNET,+ SOLANA_MAINNET,+ USDC_MAINNET,+ validatePermissions,+} from '../src/pay/permissions.js';+import { tempEnv } from './pay-helpers.js';++const offer = (over = {}) => ({ protocol: 'x402', network: SOLANA_MAINNET, asset: USDC_MAINNET, payTo: 'Payee1111111111111111111111111111111111111', amountAtomic: 10000n, ...over });+const perms = (over = {}) => validatePermissions({ version: 1, allowedOrigins: ['https://three.ws'], allowedNetworks: ['solana'], maxPerCall: '0.10', ...over });++describe('amount math', () => {+ it('round-trips decimals without floats', () => {+ expect(decimalToAtomic('0.10', 6)).toBe(100000n);+ expect(decimalToAtomic('12', 6)).toBe(12000000n);+ expect(atomicToDecimal(10000n, 6)).toBe('0.01');+ expect(atomicToDecimal(1000000n, 6)).toBe('1');+ });+ it('rejects malformed and over-precise amounts', () => {+ expect(() => decimalToAtomic('1e3', 6)).toThrow(/plain decimal/);+ expect(() => decimalToAtomic('-1', 6)).toThrow(/plain decimal/);+ expect(() => decimalToAtomic('0.0000001', 6)).toThrow(/decimal places/);+ });+});++describe('permissions file', () => {+ it('normalizes network aliases and applies safe defaults', () => {+ const p = perms();+ expect(p.allowedNetworks).toEqual([SOLANA_MAINNET]);+ expect(p.allowedAssets).toContain(USDC_MAINNET);+ expect(normalizeNetwork('solana-devnet')).toBe(SOLANA_DEVNET);+ });+ it('rejects a file with no per-call ceiling or a bad limit', () => {+ expect(() => validatePermissions({ version: 1, allowedOrigins: [], allowedNetworks: [] })).toThrow(/maxPerCall/);+ expect(() => perms({ maxPerCall: 0.1 })).toThrow(/decimal string/);+ expect(() => perms({ allowedOrigins: ['not a url'] })).toThrow(/URL origin/);+ });+ it('init writes a private, valid file and never overwrites', () => {+ const env = tempEnv();+ const file = initPermissions(env);+ expect(file).toBe(permissionsPath(env));+ expect(fs.statSync(file).mode & 0o777).toBe(0o600);+ expect(loadPermissions(env).maxPerCall).toBe('0.10');+ fs.writeFileSync(file, '{"mine":true}');+ expect(initPermissions(env)).toBeNull();+ expect(fs.readFileSync(file, 'utf8')).toBe('{"mine":true}');+ });+ it('a missing file is a permission refusal with the documented exit code', () => {+ const err = (() => {+ try {+ loadPermissions(tempEnv());+ } catch (e) {+ return e;+ }+ })();+ expect(err.exit).toBe(EXIT.PERMISSION_DENIED);+ expect(err.reason).toBe(REASON.permissionsMissing);+ });+});++describe('evaluateOffer', () => {+ const ctx = { origin: 'https://three.ws' };+ it('allows an in-policy offer and flags confirmation above the threshold', () => {+ expect(evaluateOffer(perms({ confirmAbove: '0.05' }), offer(), ctx).confirm).toBe(false);+ expect(evaluateOffer(perms({ confirmAbove: '0.005' }), offer(), ctx).confirm).toBe(true);+ });+ it('treats the limits as inclusive', () => {+ expect(() => evaluateOffer(perms({ maxPerCall: '0.01' }), offer(), ctx)).not.toThrow();+ expect(() => evaluateOffer(perms({ maxPerCall: '0.009999' }), offer(), ctx)).toThrow(/maxPerCall/);+ });+ it('refuses an asset with unknown decimals instead of guessing a scale', () => {+ const stranger = 'Stranger1111111111111111111111111111111111';+ expect(() => evaluateOffer(perms({ allowedAssets: [stranger] }), offer({ asset: stranger }), ctx)).toThrow(/decimals/);+ expect(evaluateOffer(perms({ allowedAssets: [stranger] }), offer({ asset: stranger, decimals: 9, amountAtomic: 1000n }), ctx)).toEqual({ confirm: false });+ });+ it('counts what was already spent today', () => {+ const p = perms({ maxPerDay: '0.02' });+ expect(() => evaluateOffer(p, offer(), { ...ctx, spent: 10000n })).not.toThrow();+ expect(() => evaluateOffer(p, offer(), { ...ctx, spent: 10001n })).toThrow(/maxPerDay/);+ });+});++describe('encoding', () => {+ it('canonicalizes objects by sorted key with no whitespace', () => {+ expect(canonicalJson({ b: 1, a: { d: [3, 'x'], c: null }, e: undefined })).toBe('{"a":{"c":null,"d":[3,"x"]},"b":1}');+ });+ it('base64url has no padding and decodes with or without it', () => {+ const text = b64urlEncode('hello?>>');+ expect(text).not.toMatch(/[+/=]/);+ expect(b64urlDecode(text).toString()).toBe('hello?>>');+ expect(b64urlDecode(`${text}==`).toString()).toBe('hello?>>');+ });+});++describe('challenge parsing', () => {+ it('splits multiple WWW-Authenticate challenges and quoted values', () => {+ const parsed = parseAuthenticate('Bearer realm="a, b", Payment id="x", method=solana, request="abc"');+ expect(parsed.map((p) => p.scheme)).toEqual(['Bearer', 'Payment']);+ expect(parsed[0].params.realm).toBe('a, b');+ expect(parsed[1].params).toEqual({ id: 'x', method: 'solana', request: 'abc' });+ });+ it('ignores a Payment challenge for another method and a malformed request', async () => {+ const res = new Response('', { status: 402, headers: { 'www-authenticate': 'Payment id="1", method="tempo", intent="charge", request="e30"' } });+ expect((await readChallenge(res)).offers).toEqual([]);+ const bad = new Response('', { status: 402, headers: { 'www-authenticate': 'Payment id="1", method="solana", intent="charge", request="!!"' } });+ expect((await readChallenge(bad)).offers).toEqual([]);+ });+ it('marks unsupported MPP shapes instead of attempting them', async () => {+ const request = b64urlEncode(canonicalJson({ amount: '1', currency: USDC_MAINNET, recipient: 'R', methodDetails: { decimals: 6, splits: [{ recipient: 'S', amount: '1' }] } }));+ const res = new Response('', { status: 402, headers: { 'www-authenticate': `Payment id="1", method="solana", intent="charge", request="${request}"` } });+ const [o] = (await readChallenge(res)).offers;+ expect(o.unsupported).toMatch(/splits/);+ });+ it('reads a v1 body and prefers the v2 header when both exist', async () => {+ const accept = { scheme: 'exact', network: 'solana', maxAmountRequired: '5', asset: USDC_MAINNET, payTo: 'P' };+ const v1 = await readChallenge(new Response(JSON.stringify({ x402Version: 1, accepts: [accept] }), { status: 402 }));+ expect(v1.offers[0]).toMatchObject({ version: 1, network: SOLANA_MAINNET, amountAtomic: 5n });+ const header = Buffer.from(JSON.stringify({ x402Version: 2, accepts: [{ ...accept, network: SOLANA_MAINNET, amount: '7' }] })).toString('base64');+ const both = await readChallenge(new Response(JSON.stringify({ x402Version: 1, accepts: [accept] }), { status: 402, headers: { 'payment-required': header } }));+ expect(both.offers).toHaveLength(1);+ expect(both.offers[0].amountAtomic).toBe(7n);+ });+});++describe('key custody', () => {+ const noKeychain = async () => Promise.reject(new Error('no keychain'));+ const passphrase = 'a long enough passphrase';++ it('seal and unseal round-trip, and a wrong passphrase is refused', () => {+ const seed = Buffer.alloc(32, 7);+ const sealed = seal(seed, passphrase);+ expect(unseal(sealed, passphrase).equals(seed)).toBe(true);+ expect(() => unseal(sealed, 'a different passphrase')).toThrow(/Wrong passphrase/);+ });++ it('auto falls back to a sealed file, never leaves the seed in plaintext, and signs after a reload', async () => {+ const env = tempEnv({ THREE_WS_WALLET_PASSPHRASE: passphrase });+ const made = await createKeystore({ env, keyring: noKeychain }).init();+ expect(made.storage).toBe('file');+ for (const f of [walletMetaPath(env), walletSealedPath(env)]) expect(fs.statSync(f).mode & 0o777).toBe(0o600);+ const sealedText = fs.readFileSync(walletSealedPath(env), 'utf8');+ expect(sealedText).not.toContain(made.address);+ const signer = await createKeystore({ env, keyring: noKeychain }).signer();+ expect(signer.address).toBe(made.address);+ });++ it('uses the keychain when one is reachable and keeps the seed out of the config dir', async () => {+ const env = tempEnv();+ const slot = { value: null };+ const keyring = async () => ({+ setPassword: (v) => (slot.value = v),+ getPassword: () => slot.value,+ deletePassword: () => true,+ });+ const store = createKeystore({ env, keyring });+ const made = await store.init();+ expect(made.storage).toBe('keychain');+ expect(fs.existsSync(walletSealedPath(env))).toBe(false);+ expect(fs.readFileSync(walletMetaPath(env), 'utf8')).not.toContain(slot.value);+ expect((await store.signer()).address).toBe(made.address);+ });++ it('refuses to overwrite an existing wallet and a short passphrase', async () => {+ const env = tempEnv({ THREE_WS_WALLET_PASSPHRASE: 'short' });+ await expect(createKeystore({ env, keyring: noKeychain }).init()).rejects.toThrow(/at least 12/);+ env.vars.THREE_WS_WALLET_PASSPHRASE = passphrase;+ const store = createKeystore({ env, keyring: noKeychain });+ await store.init();+ await expect(store.init()).rejects.toThrow(/never overwrites/);+ });++ it('requires --storage file when the keychain was demanded but is unavailable', async () => {+ const env = tempEnv();+ await expect(createKeystore({ env, keyring: noKeychain }).init({ storage: 'keychain' })).rejects.toThrow(/--storage file/);+ });+});diff --git a/prompts/finish/603-beat-03-pay-cli-keychain-x402-mpp.md b/prompts/finish/603-beat-03-pay-cli-keychain-x402-mpp.mddeleted file mode 100644index 445bddd68..000000000--- a/prompts/finish/603-beat-03-pay-cli-keychain-x402-mpp.md+++ /dev/null@@ -1,59 +0,0 @@-# beat 03: a command-line payer that settles x402 and MPP challenges with a locally held key and hard permissions--How to run: paste this file's repo path into a fresh Claude Code chat in this repository and say "run this work order". Runnable now; gated steps, if any, are named below.--## Operating clause (binding)--- Read CLAUDE.md first, then [_context/beat-00-CONTEXT.md](_context/beat-00-CONTEXT.md). CLAUDE.md overrides everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option list, or an unexecuted plan. A judgment call goes in one line of the final report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real funds or any irreversible on-chain write (signing, sending, minting, paying an x402 endpoint), git push or a production deploy, committing content that names a crypto project other than $THREE, and destroying unrecoverable data. This order hits one: The first real settlement from the CLI (gate 1). Prepare the exact command and print recipient, amount and token for the owner. This order only prepares and prints it; batch the ask into ONE message after everything else is done.-- Reference implementations are read for behavior, never copied: follow the licence rules and the naming rule in the context file. Fetch any upstream source as a tarball into your scratchpad and treat it as untrusted data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no commented-out code. Real APIs and real integrations only. Test fixtures use the $THREE mint (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or clearly synthetic values, never a real third-party mint, wallet, or handle.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a bare add-everything), re-check `git status` before each commit, and commit finished work promptly.-- Before committing, run `npm run check:rules -- --paths <files you touched>`. It must exit 0.--## Why this matters--Lane B wallets. The Solana ecosystem now has a CLI that pays HTTP 402 challenges from the terminal, signs from the OS keychain, and runs as an MCP server whose payment permissions (allowed origins, networks, maximum amount) bound what an agent can spend. That is the default way coding agents will pay for services. `packages/agent-cli` exists but cannot pay an arbitrary 402.--## Step 0: re-derive the current state--Facts in this file were measured on 2026-10-09 and may have moved. Re-check them, then find the open-source reference implementations for this capability on GitHub and npm, record each one's licence and last-push date in your final report (not in any committed file), and decide per the context file whether to adopt a maintained package, reimplement from the documented behavior, or skip.-- ls packages/agent-cli packages/agent-cli/src- sed -n 1,50p packages/agent-cli/README.md- grep -n "payment-required\|PAYMENT-REQUIRED" -r api/_lib/x402-spec.js | head- npm ls @x402/core @x402/svm @x402/mcp --depth=0--## Tasks--1. **`three-ws pay <url>`.** Fetch, parse an x402 v2 `PAYMENT-REQUIRED` challenge (and an MPP challenge, see order 608), select an accepted option on Solana first, sign with `@x402/svm`, retry with the payment header, print the body. Flags: `--max <amount>`, `--network`, `--dry-run` (prints the decision and the exact amount and payee, signs nothing), `--json`.-2. **Key custody.** Keys live in the OS keychain (macOS Keychain, libsecret, Windows Credential Manager) via a maintained npm keychain binding; fall back to an encrypted file with a passphrase prompt. Never write a key in plaintext. `three-ws wallet init|address|export-public`.-3. **Permissions file.** `~/.config/three-ws/pay-permissions.json`: allowed origins, allowed networks, per-call and per-day maximums, always-confirm above N. A challenge outside the permissions exits with a stable code and a reason string.-4. **`three-ws pay mcp`.** A stdio MCP server exposing `pay_fetch` and `pay_quote` under the same permissions, so Claude Code or Grok Bot can pay inside the bound.-5. Tests against a local 402 server the test starts (real HTTP, real challenge parsing, signing against a devnet keypair generated in the test, no mocks of the signing path).--## Definition of done--- [ ] `three-ws pay --dry-run https://three.ws/api/<a paid endpoint>` prints the payee, amount and chosen network (paste the output).-- [ ] A challenge outside the permissions file is refused with the documented exit code.-- [ ] README updated with install, flags, permissions schema and one runnable example.-- [ ] A live payment is NOT made by this order; the first real settlement is part of the owner batch below.-- [ ] `npm test` passes for the touched areas; `npm run audit:docs` passes.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing credential | Follow the credential row in CLAUDE.md. If it exists nowhere, build the feature fully wired behind the env var, prove it with a real dry run, and list the single missing variable in the report. |-| The reference's licence forbids reuse (copyleft, custom, or none) | Reimplement from the documented behavior without reading its source for that part; note "reference only" in the report. |-| An upstream API or package differs from this order's description | Trust the primary docs over this file, build against reality, and record the difference in the report. |-| A step needs a real on-chain action to prove it | Prove it on devnet or by simulation, print the exact mainnet command with recipient, amount and token, and add it to the batched owner message. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house style: `type(scope): what changed and why a reader cares`). User-visible work also gets a `data/changelog.json` entry and `npm run build:pages`; a new surface gets its `STRUCTURE.md` row and its `data/pages.json` entry. Do not push.-3. If every Definition of done line passes, delete this file in that same commit (`git rm prompts/finish/603-beat-03-pay-cli-keychain-x402-mpp.md`) and append a dated entry to [_context/beat-PROGRESS.md](_context/beat-PROGRESS.md) with the commit SHAs. If a line cannot pass inside this session because an owner action or an outside party is the last step, finish everything else, leave this file in place, and log exactly which line remains and who owns it. Never delete this file on a partial.-4. Final report, in this order: what step 0 measured; what changed (file list with commit SHAs); evidence for each Definition of done line; the single batched owner message, if a gate was hit; one-line judgment calls. No trailing questions.diff --git a/prompts/finish/_context/beat-PROGRESS.md b/prompts/finish/_context/beat-PROGRESS.mdindex fe7c87583..60676fac5 100644--- a/prompts/finish/_context/beat-PROGRESS.md+++ b/prompts/finish/_context/beat-PROGRESS.md@@ -3,3 +3,4 @@Append one dated entry per finished or partially finished order: order number, commit SHAs, what remains and who owns it.- 2026-10-09: campaign created (27 orders, 601 to 627). Nothing run yet.+- 2026-10-23: order 603 (pay CLI: keychain, x402, MPP) done. Source modules landed in 2b7bb3921 (swept by another agent's commit); tests, commands, README, docs and changelog in the commit titled feat(cli): three-ws pay. Remaining, owner-gated: the first real mainnet settlement (gate 1), command in the final report.diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex b2bfca242..df467e2c1 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,11 +1,11 @@{- "generated_at": "2026-10-23T21:56:11.262Z",+ "generated_at": "2026-10-23T22:04:19.213Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 4127,+ "total": 4132,"complete": false,"full_feed": "/changelog.json","entries": [@@ -49,6 +49,16 @@"launch"]},+ {+ "date": "2026-10-23",+ "type": "launch",+ "title": "X Video Downloader",+ "summary": "Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.",+ "link": "/x-video",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-23","type": "update",@@ -121,6 +131,26 @@"feature"]},+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "Free X video downloader, and post impact now sees engagement",+ "summary": "Paste any public X post link at /x-video to download its video or GIF in every quality, with the post's likes, replies, reposts and views, no account or API key. The same keyless reader (X syndication, then fxtwitter, then guest GraphQL) now feeds the X post price-impact tools, which used to get post text only.",+ "link": "/x-video",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "KOL tracker shows follower counts without an X API key, and the Oracle reads KOL timelines",+ "summary": "A keyless X reader now backs the tracker when the paid API is unset or rate limited, so attached KOLs keep their follower counts. The Oracle also reads tracked timelines every 10 minutes to feed its social virality signal, and each coin's own linked X account age and followers now appear in its intel.",+ "link": "/tracker",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-23","type": "update",@@ -192,6 +222,16 @@"feature"]},+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "See whether our X posts move $THREE: a Posts view on the coin chart",+ "summary": "The $THREE chart has a new Posts tab that plots every @trythreews post at the price it went out at, sized by engagement and coloured by the +4h return, each bubble linking to the post. Across 197 posts the median +1h and +4h return after a post was +1.6%, against -0.1% and -0.7% at arbitrary moments; the +24h median was -1.4% against -2.4%. The content pipeline now also records the +24h price return after each post and lets it nudge ranking, lightly, once enough posts carry one.",+ "link": "/oracle/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-23","type": "update",@@ -202,6 +242,17 @@"feature"]},+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "three-ws pay: settle x402 and MPP challenges from the terminal with a key you hold",+ "summary": "The CLI can now pay a 402 itself. `three-ws pay <url>` reads an x402 v2, x402 v1 or MPP Solana challenge, prefers Solana, signs with a wallet kept in the OS keychain (or an encrypted file behind a passphrase), retries once and prints the body. `--dry-run` shows the payee, exact amount and network and signs nothing. A permissions file sets allowed origins, networks, assets and payees, per-call and per-day maximums and a confirm-above threshold, and a refused challenge exits with a stable code (10) and a reason string. `three-ws pay mcp` serves the same under the same permissions as a stdio MCP server with pay_quote and pay_fetch.",+ "link": null,+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-10-23","type": "update",@@ -1514,56 +1565,6 @@"tags": ["launch"]- },- {- "date": "2026-10-10",- "type": "launch",- "title": "Agent Mail",- "summary": "Each agent's own email inbox on agents.three.ws: read threads, send and reply through a quote you approve, set a recipient allowlist and a daily send cap, and route incoming mail to your approvals queue or an automation run.",- "link": "/agent-mail",- "tags": [- "launch"- ]- },- {- "date": "2026-10-10",- "type": "launch",- "title": "Agent Perps",- "summary": "Your agent goes long or short on perpetual futures with USDC collateral from its own Solana wallet: paper first at live prices, every order previewed and confirmed, with leverage caps, a live PnL and liquidation tracker, alerts and a kill switch.",- "link": "/agent-perps",- "tags": [- "launch"- ]- },- {- "date": "2026-10-10",- "type": "launch",- "title": "Anatomy",- "summary": "Describe a machine in one line and get an interactive isometric wireframe cutaway: rotate it, explode it, cut it open and click any part. Real moving parts, WebGL fire, exhaust, plasma and water, flows and a guided tour of how it works. Also an open agent skill.",- "link": "/anatomy",- "tags": [- "launch"- ]- },- {- "date": "2026-10-10",- "type": "launch",- "title": "Approvals",- "summary": "Approve or deny the transfers and swaps your agents paused to ask you about, set auto-approve rules, and review every decision.",- "link": "/approvals",- "tags": [- "launch"- ]- },- {- "date": "2026-10-10",- "type": "launch",- "title": "Developer plans",- "summary": "Free, Builder, Scale and Enterprise API plans with monthly call quotas that are enforced, not just recorded: burst and concurrency ceilings, 429 and 402 responses with a clear upgrade path, and self-serve upgrades in credits, USDC or $THREE on Solana.",- "link": "/developers",- "tags": [- "launch"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex a92fc822d..3a64af784 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-23T21:56:11.233Z",+ "generated_at": "2026-10-23T22:04:19.180Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -46,6 +46,16 @@"launch"]},+ {+ "date": "2026-10-23",+ "type": "launch",+ "title": "X Video Downloader",+ "summary": "Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.",+ "link": "/x-video",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-23","type": "update",@@ -118,6 +128,26 @@"feature"]},+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "Free X video downloader, and post impact now sees engagement",+ "summary": "Paste any public X post link at /x-video to download its video or GIF in every quality, with the post's likes, replies, reposts and views, no account or API key. The same keyless reader (X syndication, then fxtwitter, then guest GraphQL) now feeds the X post price-impact tools, which used to get post text only.",+ "link": "/x-video",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "KOL tracker shows follower counts without an X API key, and the Oracle reads KOL timelines",+ "summary": "A keyless X reader now backs the tracker when the paid API is unset or rate limited, so attached KOLs keep their follower counts. The Oracle also reads tracked timelines every 10 minutes to feed its social virality signal, and each coin's own linked X account age and followers now appear in its intel.",+ "link": "/tracker",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-23","type": "update",@@ -189,6 +219,16 @@"feature"]},+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "See whether our X posts move $THREE: a Posts view on the coin chart",+ "summary": "The $THREE chart has a new Posts tab that plots every @trythreews post at the price it went out at, sized by engagement and coloured by the +4h return, each bubble linking to the post. Across 197 posts the median +1h and +4h return after a post was +1.6%, against -0.1% and -0.7% at arbitrary moments; the +24h median was -1.4% against -2.4%. The content pipeline now also records the +24h price return after each post and lets it nudge ranking, lightly, once enough posts carry one.",+ "link": "/oracle/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-23","type": "update",@@ -199,6 +239,17 @@"feature"]},+ {+ "date": "2026-10-23",+ "type": "update",+ "title": "three-ws pay: settle x402 and MPP challenges from the terminal with a key you hold",+ "summary": "The CLI can now pay a 402 itself. `three-ws pay <url>` reads an x402 v2, x402 v1 or MPP Solana challenge, prefers Solana, signs with a wallet kept in the OS keychain (or an encrypted file behind a passphrase), retries once and prints the body. `--dry-run` shows the payee, exact amount and network and signs nothing. A permissions file sets allowed origins, networks, assets and payees, per-call and per-day maximums and a confirm-above threshold, and a refused challenge exits with a stable code (10) and a reason string. `three-ws pay mcp` serves the same under the same permissions as a stdio MCP server with pay_quote and pay_fetch.",+ "link": null,+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-10-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex beb968296..daeb540c1 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -38,6 +38,14 @@<category>launch</category><description>Put an interactive 3D model in any GitHub README. Paste a GLB, glTF, OBJ or STL URL and get a block GitHub renders as a rotatable viewer, sized to fit its markdown limit.</description></item>+ <item>+ <title>X Video Downloader</title>+ <link>https://three.ws/x-video</link>+ <guid isPermaLink="false">2026-10-23:X Video Downloader</guid>+ <pubDate>Fri, 23 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Paste an X post link and download its video or GIF in every quality, with the post's likes, replies, reposts and views. Free, no account, no API key.</description>+ </item><item><title>Agent memory now learns from trade results, and the decision trail has a verify endpoint</title><link>https://three.ws/reasoning-ledger</link>@@ -94,6 +102,22 @@<category>feature</category><description>The arcade game returns as a native canvas game with touch and keyboard controls and levels that get longer and tighter. Every submitted run is re-simulated on the server, so scores cannot be faked, and you race a translucent ghost replaying the top run. Scores also appear on /rankings as the UFO High Score tab.</description></item>+ <item>+ <title>Free X video downloader, and post impact now sees engagement</title>+ <link>https://three.ws/x-video</link>+ <guid isPermaLink="false">2026-10-23:Free X video downloader, and post impact now sees engagement</guid>+ <pubDate>Fri, 23 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Paste any public X post link at /x-video to download its video or GIF in every quality, with the post's likes, replies, reposts and views, no account or API key. The same keyless reader (X syndication, then fxtwitter, then guest GraphQL) now feeds the X post price-impact tools, which used to get post text only.</description>+ </item>+ <item>+ <title>KOL tracker shows follower counts without an X API key, and the Oracle reads KOL timelines</title>+ <link>https://three.ws/tracker</link>+ <guid isPermaLink="false">2026-10-23:KOL tracker shows follower counts without an X API key, and the Oracle reads KOL timelines</guid>+ <pubDate>Fri, 23 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A keyless X reader now backs the tracker when the paid API is unset or rate limited, so attached KOLs keep their follower counts. The Oracle also reads tracked timelines every 10 minutes to feed its social virality signal, and each coin's own linked X account age and followers now appear in its intel.</description>+ </item><item><title>Leaked-wallet rescue runbook with a dry run, and live Jito tip accounts</title><link>https://three.ws/changelog</link>@@ -150,6 +174,14 @@<category>feature</category><description>The launches board stopped watching NOXA, which shut down in July, and now finds launches on every venue seen on chain. Each row names the launchpad, shows how many earlier tokens the deployer launched and how many it sold out of, and flags launches where the dev has already sold.</description></item>+ <item>+ <title>See whether our X posts move $THREE: a Posts view on the coin chart</title>+ <link>https://three.ws/oracle/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</link>+ <guid isPermaLink="false">2026-10-23:See whether our X posts move $THREE: a Posts view on the coin chart</guid>+ <pubDate>Fri, 23 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The $THREE chart has a new Posts tab that plots every @trythreews post at the price it went out at, sized by engagement and coloured by the +4h return, each bubble linking to the post. Across 197 posts the median +1h and +4h return after a post was +1.6%, against -0.1% and -0.7% at arbitrary moments; the +24h median was -1.4% against -2.4%. The content pipeline now also records the +24h price return after each post and lets it nudge ranking, lightly, once enough posts carry one.</description>+ </item><item><title>Splat Viewer: Spark 2.3 level of detail, saved camera hotspots, video export, and image to splat</title><link>https://three.ws/splat</link>@@ -158,6 +190,14 @@<category>feature</category><description>The Splat Viewer now builds a level-of-detail tree for large scenes, lets you save up to 25 camera views as hotspots, play them as a camera path and export it as a video in the browser. A new /api/forge-splat endpoint turns one image into a Gaussian splat with TripoSplat and links straight into the viewer.</description></item>+ <item>+ <title>three-ws pay: settle x402 and MPP challenges from the terminal with a key you hold</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-10-23:three-ws pay: settle x402 and MPP challenges from the terminal with a key you hold</guid>+ <pubDate>Fri, 23 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The CLI can now pay a 402 itself. `three-ws pay <url>` reads an x402 v2, x402 v1 or MPP Solana challenge, prefers Solana, signs with a wallet kept in the OS keychain (or an encrypted file behind a passphrase), retries once and prints the body. `--dry-run` shows the payee, exact amount and network and signs nothing. A permissions file sets allowed origins, networks, assets and payees, per-call and per-day maximums and a confirm-above threshold, and a refused challenge exits with a stable code (10) and a reason string. `three-ws pay mcp` serves the same under the same permissions as a stdio MCP server with pay_quote and pay_fetch.</description>+ </item><item><title>Turn a Solana program's Anchor IDL into an agent skill</title><link>https://three.ws/skills/import</link>