Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(cli): script-friendly --json and --non-interactive with stable exit codes, plus offline HTML run reports

nirholas248d8d20a851
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 8856a1509..4b6f1a1f7 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -302,6 +302,7 @@ packages, a generated standalone GitHub mirror). See
| 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) |
+| CLI automation mode and run reports | [packages/three-ws-cli/src/automation.js](packages/three-ws-cli/src/automation.js) (exit-code table, `--non-interactive`), [src/commands/automation.js](packages/three-ws-cli/src/commands/automation.js) (agents, runs, wallet balance, orders, `report run`), generator [src/report/run-report.js](packages/three-ws-cli/src/report/run-report.js) (also imported by the run page [src/agent-run-replay.js](src/agent-run-replay.js)) | Live | Every command takes `--json` (one document on stdout) and `--non-interactive`, with exit codes 0 ok, 2 usage, 3 auth, 4 guard refusal, 5 payment required, 6 network (`pay` keeps 10 to 14). `report run <id> --out f.html` writes one offline file with the goal, tool calls, decisions, trades, outcome and the decision-trail head hash. Docs: [docs/cli.md](docs/cli.md). Tests: [packages/three-ws-cli/tests/automation.test.js](packages/three-ws-cli/tests/automation.test.js) |
| MPP on Solana (one URL, two challenge formats) and skill rails | Wire layer [api/_lib/mpp-solana.js](api/_lib/mpp-solana.js) (mppx core), seller option `mpp: true` in [api/_lib/x402-paid-endpoint.js](api/_lib/x402-paid-endpoint.js) (enabled on [api/x402/gas-oracle.js](api/x402/gas-oracle.js)), agent payer `dryRun` / `preferProtocol` in [api/_lib/x402-buyer-fetch.js](api/_lib/x402-buyer-fetch.js), skill router [api/skills/[id]/invoke.js](api/skills/[id]/invoke.js) + [api/_lib/skill-rails.js](api/_lib/skill-rails.js) | Live (mainnet settlement owner-gated) | A paid route answers an unpaid call with the x402 accepts list AND `WWW-Authenticate: Payment` (Solana `charge`, pull mode) at the same price; an `Authorization: Payment` credential settles through the existing x402 verify/settle path and the response carries `Payment-Receipt`. The agent payer reads either, applies its spending caps to the charge, and can quote in dry run. Marketplace skills are priced once and served over x402, MPP, A2A and AP2 with one split and one receipt. Docs: [docs/mpp-solana.md](docs/mpp-solana.md), [docs/skill-rails.md](docs/skill-rails.md). Tests: [tests/mpp-solana.test.js](tests/mpp-solana.test.js), [tests/skill-rails.test.js](tests/skill-rails.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) |
diff --git a/data/changelog.json b/data/changelog.json
index 00c48608d..fb719f0f6 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$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-24",
+ "title": "Drive the CLI from scripts and agents, and download a run report",
+ "summary": "Every three-ws command now takes --json (one JSON document on stdout, diagnostics on stderr) and --non-interactive (never prompts), with a stable exit-code table: 2 usage, 3 auth, 4 refused by a guard, 5 payment required, 6 network. New commands cover agents, runs, wallet balance, skill install and orders. `three-ws report run <id> --out run.html` writes one self-contained offline file with the goal, tool calls, decisions, trades, outcome and the decision-trail head hash, and the run page has a matching Download report button.",
+ "tags": ["feature", "sdk"],
+ "link": "/docs/cli"
+ },
{
"date": "2026-10-24",
"title": "Install the three.ws skills with one command on any agent runtime",
diff --git a/docs/cli.md b/docs/cli.md
index c320fa16f..b4e91efdd 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -277,7 +277,39 @@ npx @three-ws/cli team status <id-or-name>
Both are read-only.
-Global flags: `--json` for machine-readable output, `--origin <url>` (or `THREE_WS_ORIGIN`) to talk to another deployment, `--no-color`.
+Global flags: `--json` for machine-readable output, `--non-interactive` to never prompt, `--origin <url>` (or `THREE_WS_ORIGIN`) to talk to another deployment, `--no-color`.
+
+## Automation mode and run reports
+
+Every command takes `--json` and `--non-interactive`. The CLI is built to be driven by scripts and by other agents.
+
+- `--json`: stdout carries exactly one JSON document and nothing else. Progress, warnings and the human sentence for an error go to stderr. A failure prints `{ "error": "<reason>", "message": "...", "exit": <code> }` on stdout.
+- `--non-interactive` (or `THREE_WS_NON_INTERACTIVE=1`): never prompts and never opens a browser. Missing input is a usage error (exit 2), a missing credential is an auth error (exit 3), and an external skill install without `--yes` is refused (exit 4). Authenticate with `THREE_WS_API_KEY` or `--key`.
+
+| Exit | Meaning |
+| --- | --- |
+| 0 | Success |
+| 1 | Other error (an unknown run, an unexpected server answer) |
+| 2 | Usage: unknown flag or command, missing or malformed input |
+| 3 | Auth: no credential, expired or revoked key, or forbidden |
+| 4 | Refused by a guard: the spend policy, the trade firewall, or an unconfirmed external skill |
+| 5 | Payment required (HTTP 402) |
+| 6 | Network: host unreachable, RPC failure, rate limit or a 5xx |
+
+`three-ws pay` keeps its own stable codes 10 to 14 (see the `pay` section of the package README). They are the one exception to this table.
+
+| Command | Output (`--json`) |
+| --- | --- |
+| `agents list` / `agents get <id\|name>` | Your agents with their Solana address |
+| `runs list --agent <id\|name>` / `runs get <run-id>` | Run history, or one run with steps, tool traces and the receipt chain verdict |
+| `wallet balance [--agent <id\|name>]` | SOL and USDC of the local pay wallet (read from Solana RPC) or of an agent wallet |
+| `skill install <slug> --agent <id>` | Alias of `skills import` |
+| `orders list --agent <id\|name> [--network devnet]` | The agent's order-engine orders |
+| `report run <run-id> --out run.html` | One self-contained HTML report, see below |
+
+### Run report
+
+`three-ws report run <run-id> --out run.html` writes a single file with inline CSS and JS and no network access: the goal, outcome, decisions, trades, every tool call with input, output and receipt, the receipt chain head and the head hash of the agent's decision trail. It opens offline from disk and can be attached to a ticket or an audit. The same generator backs the "Download report" button on the run page. Run `three-ws report run` against a run you own; the decision trail head is fetched best-effort and the report says so when it could not be reached.
## Troubleshooting
diff --git a/packages/three-ws-cli/README.md b/packages/three-ws-cli/README.md
index 260da1347..632902c81 100644
--- a/packages/three-ws-cli/README.md
+++ b/packages/three-ws-cli/README.md
@@ -132,6 +132,38 @@ Solana offers are always tried first. EVM offers are skipped.
{ "mcpServers": { "three-ws-pay": { "command": "npx", "args": ["@three-ws/cli", "pay", "mcp"] } } }
```
+## Automation mode
+
+Every command takes `--json` and `--non-interactive`. The CLI is built to be driven by scripts and by other agents.
+
+- `--json`: stdout carries exactly one JSON document and nothing else. Progress, warnings and the human sentence for an error go to stderr. A failure prints `{ "error": "<reason>", "message": "...", "exit": <code> }` on stdout.
+- `--non-interactive` (or `THREE_WS_NON_INTERACTIVE=1`): never prompts and never opens a browser. Missing input is a usage error (exit 2), a missing credential is an auth error (exit 3), and an external skill install without `--yes` is refused (exit 4). Authenticate with `THREE_WS_API_KEY` or `--key`.
+
+| Exit | Meaning |
+| --- | --- |
+| 0 | Success |
+| 1 | Other error (an unknown run, an unexpected server answer) |
+| 2 | Usage: unknown flag or command, missing or malformed input |
+| 3 | Auth: no credential, expired or revoked key, or forbidden |
+| 4 | Refused by a guard: the spend policy, the trade firewall, or an unconfirmed external skill |
+| 5 | Payment required (HTTP 402) |
+| 6 | Network: host unreachable, RPC failure, rate limit or a 5xx |
+
+`three-ws pay` keeps its own stable codes 10 to 14 (see above). They are the one exception to this table.
+
+| Command | Output (`--json`) |
+| --- | --- |
+| `agents list` / `agents get <id\|name>` | Your agents with their Solana address |
+| `runs list --agent <id\|name>` / `runs get <run-id>` | Run history, or one run with steps, tool traces and the receipt chain verdict |
+| `wallet balance [--agent <id\|name>]` | SOL and USDC of the local pay wallet (read from Solana RPC) or of an agent wallet |
+| `skill install <slug> --agent <id>` | Alias of `skills import` |
+| `orders list --agent <id\|name> [--network devnet]` | The agent's order-engine orders |
+| `report run <run-id> --out run.html` | One self-contained HTML report, see below |
+
+### Run report
+
+`three-ws report run <run-id> --out run.html` writes a single file with inline CSS and JS and no network access: the goal, outcome, decisions, trades, every tool call with input, output and receipt, the receipt chain head and the head hash of the agent's decision trail. It opens offline from disk and can be attached to a ticket or an audit. The same generator backs the "Download report" button on the run page. Run `three-ws report run` against a run you own; the decision trail head is fetched best-effort and the report says so when it could not be reached.
+
## Grok Bot
Grok 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/automation.js b/packages/three-ws-cli/src/automation.js
new file mode 100644
index 000000000..b95b34975
--- /dev/null
+++ b/packages/three-ws-cli/src/automation.js
@@ -0,0 +1,73 @@
+// Automation mode: the stable exit-code table, the error type commands throw to
+// pick a code, the classifier that maps an API failure to a code, and the one
+// rule for "may this process prompt a human".
+//
+// 0 ok
+// 1 other error
+// 2 usage (bad flags, missing input, or a prompt that --non-interactive forbids)
+// 3 auth (not signed in, expired or revoked credential, missing scope)
+// 4 refused by a guard (spend policy, approval gate, scan verdict, firewall)
+// 5 payment required (HTTP 402 the command did not settle)
+// 6 network (unreachable host, timeout, rate limit, server fault)
+//
+// `three-ws pay` predates this table and keeps its own documented 10 to 14
+// codes; they are returned untouched because scripts already branch on them.
+
+import { ApiError } from './http.js';
+
+export const EXIT_CODES = Object.freeze({
+ OK: 0,
+ ERROR: 1,
+ USAGE: 2,
+ AUTH: 3,
+ GUARD: 4,
+ PAYMENT: 5,
+ NETWORK: 6,
+});
+
+export class CliError extends Error {
+ /**
+ * @param {number} exit one of EXIT_CODES
+ * @param {string} code short snake_case reason for --json
+ * @param {string} message what happened and how to fix it
+ * @param {object} [detail]
+ */
+ constructor(exit, code, message, detail = undefined) {
+ super(message);
+ this.name = 'CliError';
+ this.exit = exit;
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+const GUARD_CODE = /guard|policy|firewall|blocked|refused|limit|approval|not_allowed|spend/i;
+
+/** The exit code an error maps to. An error that already carries an integer `exit` keeps it. */
+export function exitCodeFor(err) {
+ if (Number.isInteger(err?.exit)) return err.exit;
+ if (err instanceof ApiError) {
+ const { status, code } = err;
+ if (code === 'login_required' || status === 401) return EXIT_CODES.AUTH;
+ if (status === 0) return EXIT_CODES.NETWORK;
+ if (status === 402) return EXIT_CODES.PAYMENT;
+ if (status === 403 || status === 422) return GUARD_CODE.test(String(code || '')) ? EXIT_CODES.GUARD : status === 403 ? EXIT_CODES.AUTH : EXIT_CODES.ERROR;
+ if (status === 429 || status >= 500) return EXIT_CODES.NETWORK;
+ if (code === 'validation_error' || status === 400) return EXIT_CODES.USAGE;
+ return EXIT_CODES.ERROR;
+ }
+ return EXIT_CODES.ERROR;
+}
+
+/** True when nothing may prompt: --non-interactive or THREE_WS_NON_INTERACTIVE=1. */
+export function isNonInteractive(flags = {}, env = { vars: {} }) {
+ return Boolean(flags['non-interactive']) || env.vars?.THREE_WS_NON_INTERACTIVE === '1';
+}
+
+/** Throw the usage error for a required input that was not supplied. */
+export function requireInput(value, what, hint) {
+ if (value === undefined || value === null || value === '') {
+ throw new CliError(EXIT_CODES.USAGE, 'missing_input', `${what} is required${hint ? `: ${hint}` : ''}.`);
+ }
+ return value;
+}
diff --git a/packages/three-ws-cli/src/cli.js b/packages/three-ws-cli/src/cli.js
index 41b4b64a9..af35e6685 100755
--- a/packages/three-ws-cli/src/cli.js
+++ b/packages/three-ws-cli/src/cli.js
@@ -11,6 +11,7 @@ import { VERSION, ApiError } from './http.js';
import { c, errorLine, line, printJson } from './ui.js';
import { CancelledError } from './commands/common.js';
import { clientsFromFlags } from './commands/quick.js';
+import { CliError, EXIT_CODES, exitCodeFor, isNonInteractive } from './automation.js';
export const HELP = `${c.bold('three-ws')} ${c.dim(`v${VERSION}`)}: connect any MCP client to three.ws
@@ -36,7 +37,11 @@ ${c.bold('Commands')}
mcp list Show three.ws servers configured in each client (--available lists all servers)
mcp add <server> Add one server to your clients without prompts
mcp remove <server> Remove one server from your clients
- skills <sub> Browse and import community agent skills (list, search, show, import, installed)
+ skills <sub> Browse and install community agent skills (list, search, show, import|install, installed)
+ agents list|get Your agents, for scripts: ids, names, pages and wallets
+ runs list|get An agent's runs (--agent), or one run with its steps, tool calls and receipt chain
+ orders list An agent's programmable orders (--agent, --network)
+ report run <id> One run as a single self-contained HTML file (--out report.html)
proxy <url> Run a stdio bridge to a hosted server (written into client configs by setup)
fund Top up credits from an agent wallet (--amount, --agent); mints an inference key once
provider use three-ws Point this machine's model clients at three.ws, billed to your credits
@@ -45,7 +50,7 @@ ${c.bold('Commands')}
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)
+ wallet <sub> The local pay key: init, address, export-public, balance (never prints the private key)
version Print the version
${c.bold('Sign-in options')} (setup, login)
@@ -110,6 +115,12 @@ ${c.bold('Pay options')} (pay, wallet)
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('Automation')} (every command)
+ --json One JSON document on stdout; diagnostics and errors' text go to stderr
+ --non-interactive Never prompt (also THREE_WS_NON_INTERACTIVE=1); missing input exits 2
+ Exit codes: 0 ok, 1 error, 2 usage, 3 auth, 4 refused by a guard, 5 payment required, 6 network.
+ (\`pay\` keeps its own 10 to 14, listed above.) Full table: docs/cli.md
+
${c.bold('Global')}
--json Machine-readable output on stdout
--origin <url> Talk to another three.ws deployment (or THREE_WS_ORIGIN)
@@ -120,6 +131,8 @@ Docs: https://three.ws/docs/cli`;
const OPTIONS = {
json: { type: 'boolean' },
+ 'non-interactive': { type: 'boolean' },
+ out: { type: 'string' },
origin: { type: 'string' },
'no-color': { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
@@ -214,7 +227,7 @@ const COMMANDS = {
if (sub === 'status') return (await import('./commands/live.js')).agentStatus(next);
if (sub === 'create') return (await import('./commands/agent.js')).create(next);
if (sub === 'launch') return (await import('./commands/agent.js')).launch(next);
- throw new Error('usage: three-ws agent <status [id]|create [name]|launch [status <id>]>');
+ throw new CliError(EXIT_CODES.USAGE, 'usage', 'usage: three-ws agent <status [id]|create [name]|launch [status <id>]>');
},
create: async (ctx) => (await import('./commands/agent.js')).create(ctx),
launch: async (ctx) => (await import('./commands/agent.js')).launch(ctx),
@@ -226,6 +239,10 @@ const COMMANDS = {
await runProxy({ url, server: ctx.flags.server || null, env: ctx.env });
return 0;
},
+ agents: async (ctx) => (await import('./commands/automation.js')).agents(ctx),
+ runs: async (ctx) => (await import('./commands/automation.js')).runs(ctx),
+ orders: async (ctx) => (await import('./commands/automation.js')).orders(ctx),
+ report: async (ctx) => (await import('./commands/automation.js')).report(ctx),
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),
@@ -243,31 +260,58 @@ const COMMANDS = {
},
};
+/**
+ * Print a failure and return its exit code. Under --json stdout carries exactly
+ * one JSON document (the error object) and the human sentence goes to stderr;
+ * otherwise the sentence goes to stderr alone.
+ */
+function failure(err, { json, env }) {
+ const exit = exitCodeFor(err);
+ if (json) {
+ printJson({ error: err.code || 'error', message: err.message, exit, detail: err.detail, status: err instanceof ApiError ? err.status : undefined });
+ }
+ errorLine(err.message);
+ if (env.vars.THREE_WS_DEBUG === '1' && err.stack) process.stderr.write(`${err.stack}\n`);
+ return exit;
+}
+
export async function main(argv = process.argv.slice(2), env = systemEnv()) {
- // `skills` owns its own argument grammar (see commands/skills.js).
- if (argv[0] === 'skills') {
- const { runSkills } = await import('./commands/skills.js');
- const originIdx = argv.indexOf('--origin');
- const { code, output } = await runSkills(argv.slice(1), { env, origin: originIdx > 0 ? argv[originIdx + 1] : undefined });
- if (output) (code === 0 ? process.stdout : process.stderr).write(`${output}\n`);
- return code;
+ // `skills` (alias `skill`) owns its own argument grammar (see commands/skills.js).
+ if (argv[0] === 'skills' || argv[0] === 'skill') {
+ const rest = argv.slice(1);
+ const json = rest.includes('--json');
+ try {
+ const { runSkills } = await import('./commands/skills.js');
+ const originIdx = rest.indexOf('--origin');
+ const { code, output } = await runSkills(rest, { env, origin: originIdx >= 0 ? rest[originIdx + 1] : undefined });
+ if (json && code !== 0) {
+ printJson({ error: code === EXIT_CODES.USAGE ? 'usage' : code === EXIT_CODES.GUARD ? 'refused_by_guard' : 'error', message: output, exit: code });
+ return code;
+ }
+ if (output) (code === 0 ? process.stdout : process.stderr).write(`${output}\n`);
+ return code;
+ } catch (err) {
+ return failure(err, { json, env });
+ }
}
let parsed;
try {
parsed = parse(argv);
} catch (err) {
+ if (argv.includes('--json')) printJson({ error: 'usage', message: err.message, exit: EXIT_CODES.USAGE });
errorLine(`${err.message}. Run \`three-ws --help\`.`);
- return 2;
+ return EXIT_CODES.USAGE;
}
const { command, positionals, flags } = parsed;
if (flags.help && command !== 'help') return COMMANDS.help();
const run = COMMANDS[command];
if (!run) {
+ if (flags.json) printJson({ error: 'usage', message: `unknown command "${command}"`, exit: EXIT_CODES.USAGE });
errorLine(`unknown command "${command}". Run \`three-ws --help\`.`);
- return 2;
+ return EXIT_CODES.USAGE;
}
const origin = resolveOrigin({ flag: flags.origin, env, store: readStore(env) });
- const ctx = { command, positionals, flags, env, origin };
+ const ctx = { command, positionals, flags, env, origin, nonInteractive: isNonInteractive(flags, env) };
try {
return await run(ctx);
} catch (err) {
@@ -275,10 +319,7 @@ 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, 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 Number.isInteger(err.exit) ? err.exit : 1;
+ return failure(err, { json: flags.json, env });
}
}
diff --git a/packages/three-ws-cli/src/commands/agent.js b/packages/three-ws-cli/src/commands/agent.js
index b8d50b2bc..f08c34616 100644
--- a/packages/three-ws-cli/src/commands/agent.js
+++ b/packages/three-ws-cli/src/commands/agent.js
@@ -17,6 +17,7 @@
import * as p from '@clack/prompts';
import { answer, canPrompt, signIn } from './common.js';
+import { CliError, EXIT_CODES } from '../automation.js';
import { c, line, rows, sym, printJson, shortAddress } from '../ui.js';
import { bearerFor } from '../oauth.js';
import { requestJson, ApiError } from '../http.js';
@@ -30,12 +31,13 @@ const COIN_DESCRIPTION_MAX = 500;
/** A bearer for the signed-in account, signing in first when a prompt is allowed. */
async function requireBearer(ctx) {
+ if (ctx.env.vars.THREE_WS_API_KEY) return ctx.env.vars.THREE_WS_API_KEY;
let bearer = await bearerFor(ctx.env, { origin: ctx.origin });
if (bearer) return bearer;
- if (!canPrompt(ctx)) throw new ApiError('sign in first: `npx three-ws login` (or pass --key / set THREE_WS_API_KEY)');
+ if (!canPrompt(ctx)) throw new ApiError('sign in first: `npx three-ws login` (or pass --key / set THREE_WS_API_KEY)', { code: 'login_required' });
await signIn(ctx, {});
bearer = await bearerFor(ctx.env, { origin: ctx.origin });
- if (!bearer) throw new ApiError('sign-in did not complete; run `npx three-ws login`');
+ if (!bearer) throw new ApiError('sign-in did not complete; run `npx three-ws login`', { code: 'login_required' });
return bearer;
}
@@ -47,7 +49,7 @@ async function ask(ctx, { flag, message, placeholder, max, required = true, vali
return given.slice(0, max);
}
if (!canPrompt(ctx)) {
- if (required) throw new Error(`${message.toLowerCase()} is required (pass it as a flag)`);
+ if (required) throw new CliError(EXIT_CODES.USAGE, 'missing_input', `${message.toLowerCase()} is required (pass it as a flag)`);
return '';
}
const value = answer(await p.text({
diff --git a/packages/three-ws-cli/src/commands/automation.js b/packages/three-ws-cli/src/commands/automation.js
new file mode 100644
index 000000000..9fd46a8e3
--- /dev/null
+++ b/packages/three-ws-cli/src/commands/automation.js
@@ -0,0 +1,205 @@
+// Read-side commands for scripts and other agents. Every one honors --json
+// (one JSON document on stdout, diagnostics on stderr) and --non-interactive
+// (never prompts; missing input is exit 2), and exits with the stable table in
+// src/automation.js.
+//
+// three-ws agents list | get <id|name>
+// three-ws runs list --agent <id|name> | get <run-id>
+// three-ws wallet balance [--agent <id|name>] [--network mainnet|devnet]
+// three-ws orders list --agent <id|name> [--network mainnet|devnet]
+// three-ws report run <run-id> --out <file.html> [--agent <id>]
+//
+// Backed by GET /api/agents, POST /api/agents/balances, GET
+// /api/agent-run-replay, GET /api/agents/:id/orders and GET
+// /api/agents/:id/decision-trail/verify. Nothing here signs or moves funds.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { createSolanaRpc } from '@solana/kit';
+import { c, line, printJson, rows, shortAddress } from '../ui.js';
+import { bearerFor } from '../oauth.js';
+import { requestJson, ApiError } from '../http.js';
+import { CliError, EXIT_CODES, requireInput } from '../automation.js';
+import { buildRunReport } from '../report/run-report.js';
+import { rpcUrlFor } from '../pay/x402.js';
+import { SOLANA_DEVNET, SOLANA_MAINNET, USDC_DEVNET, USDC_MAINNET } from '../pay/permissions.js';
+import { keystoreFor } from './pay.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+async function authed(ctx) {
+ const key = ctx.env.vars.THREE_WS_API_KEY;
+ const bearer = key || (await bearerFor(ctx.env, { origin: ctx.origin }));
+ if (!bearer) throw new ApiError('not signed in. Run `three-ws login`, or set THREE_WS_API_KEY.', { code: 'login_required' });
+ return { authorization: `Bearer ${bearer}` };
+}
+
+const get = (ctx, headers, p) => requestJson(`${ctx.origin}${p}`, { headers });
+
+function networkOf(flags) {
+ const n = String(flags.network || 'mainnet').toLowerCase();
+ if (n === 'mainnet' || n === 'devnet') return n;
+ throw new CliError(EXIT_CODES.USAGE, 'invalid_network', '--network must be mainnet or devnet.');
+}
+
+function out(ctx, json, render) {
+ if (ctx.flags.json) printJson(json);
+ else render();
+ return EXIT_CODES.OK;
+}
+
+/** Resolve an id, id prefix or exact name to one of the caller's agents. */
+export async function resolveAgent(ctx, headers, key) {
+ requireInput(key, 'an agent', 'pass --agent <id|name>');
+ const { agents = [] } = await get(ctx, headers, '/api/agents');
+ const k = String(key).toLowerCase();
+ const hit = agents.filter((a) => a.id === key || (key.length >= 8 && a.id.startsWith(key)) || String(a.name || '').toLowerCase() === k);
+ if (!hit.length) throw new CliError(EXIT_CODES.USAGE, 'agent_not_found', `no agent "${key}" on this account. List yours with \`three-ws agents list\`.`);
+ if (hit.length > 1) throw new CliError(EXIT_CODES.USAGE, 'agent_ambiguous', `"${key}" matches ${hit.length} agents (${hit.map((h) => h.id.slice(0, 8)).join(', ')}). Use an id.`);
+ return hit[0];
+}
+
+const agentView = (ctx, a) => ({
+ id: a.id,
+ name: a.name,
+ page: `${ctx.origin}/agents/${a.id}`,
+ has_body: Boolean(a.avatar_id),
+ wallet: a.solana_address || null,
+ wallet_ready: a.walletReady ?? null,
+ created_at: a.created_at ?? null,
+});
+
+export async function agents(ctx) {
+ const [sub = 'list', key] = ctx.positionals;
+ const headers = await authed(ctx);
+ if (sub === 'list') {
+ const { agents: list = [] } = await get(ctx, headers, '/api/agents');
+ const view = list.map((a) => agentView(ctx, a));
+ return out(ctx, { agents: view }, () => {
+ if (!view.length) return line('No agents on this account yet. Create one: three-ws create "Nova"');
+ for (const a of view) line(`${a.id} ${c.bold(a.name || '(unnamed)')} ${a.wallet ? shortAddress(a.wallet) : c.dim('no wallet')}`);
+ });
+ }
+ if (sub === 'get') {
+ const a = await resolveAgent(ctx, headers, key);
+ const view = agentView(ctx, a);
+ return out(ctx, { agent: view }, () => {
+ line(`${c.bold(view.name || '(unnamed)')} ${c.dim(view.id)}`);
+ rows([['Page', view.page], ['Body', view.has_body ? 'has a 3D avatar' : 'none yet'], ['Wallet', view.wallet || 'none']], ' ');
+ });
+ }
+ throw new CliError(EXIT_CODES.USAGE, 'usage', 'usage: three-ws agents <list|get <id|name>>');
+}
+
+const runLine = (r) => `${r.id} ${String(r.status).padEnd(16)} ${String(r.goal || '').replace(/\s+/g, ' ').slice(0, 70)}`;
+
+async function fetchRun(ctx, headers, id) {
+ if (!UUID_RE.test(id)) throw new CliError(EXIT_CODES.USAGE, 'invalid_run_id', 'a run id is a uuid. List yours with `three-ws runs list --agent <id>`.');
+ const { data } = await get(ctx, headers, `/api/agent-run-replay?run=${encodeURIComponent(id)}`);
+ return data;
+}
+
+export async function runs(ctx) {
+ const [sub = 'list', id] = ctx.positionals;
+ const headers = await authed(ctx);
+ if (sub === 'list') {
+ const agent = await resolveAgent(ctx, headers, ctx.flags.agent);
+ const { data } = await get(ctx, headers, `/api/agent-run-replay?agent=${encodeURIComponent(agent.id)}`);
+ return out(ctx, { agent: agent.id, runs: data.runs, has_more: data.hasMore }, () => {
+ if (!data.runs.length) return line(`${agent.name || agent.id} has not worked a goal on its own yet.`);
+ for (const r of data.runs) line(runLine(r));
+ });
+ }
+ if (sub === 'get') {
+ requireInput(id, 'a run id', 'usage: three-ws runs get <run-id>');
+ const data = await fetchRun(ctx, headers, id);
+ return out(ctx, data, () => {
+ line(`${c.bold(data.run.goal)}`);
+ rows([
+ ['Run', data.run.id],
+ ['Status', data.run.status],
+ ['Steps', String(data.steps.length)],
+ ['Tool calls', String(data.toolTraces.length)],
+ ['Receipt chain', data.receiptChain ? (data.receiptChain.verified ? `verified (${data.receiptChain.checked})` : `broken at ${data.receiptChain.brokenAt}`) : 'not recomputed'],
+ ], ' ');
+ });
+ }
+ throw new CliError(EXIT_CODES.USAGE, 'usage', 'usage: three-ws runs <list --agent <id|name>|get <run-id>>');
+}
+
+const num = (n, d = 2) => (Number.isFinite(Number(n)) ? Number(n).toFixed(d) : '?');
+
+/** Balance of the local pay wallet, read straight from Solana RPC. */
+async function localBalance(ctx, network) {
+ const { address } = keystoreFor(ctx).address();
+ const caip = network === 'devnet' ? SOLANA_DEVNET : SOLANA_MAINNET;
+ const usdc = network === 'devnet' ? USDC_DEVNET : USDC_MAINNET;
+ const rpc = createSolanaRpc(rpcUrlFor(caip, ctx.env));
+ try {
+ const [lamports, tokens] = await Promise.all([
+ rpc.getBalance(address).send(),
+ rpc.getTokenAccountsByOwner(address, { mint: usdc }, { encoding: 'jsonParsed' }).send(),
+ ]);
+ const usdcAtomic = tokens.value.reduce((sum, t) => sum + BigInt(t.account.data.parsed.info.tokenAmount.amount), 0n);
+ return { source: 'pay-wallet', network, address, sol: Number(lamports.value) / 1e9, usdc: Number(usdcAtomic) / 1e6 };
+ } catch (err) {
+ throw new ApiError(`could not read ${address} on ${network}: ${err.message}`, { status: 0 });
+ }
+}
+
+export async function walletBalance(ctx) {
+ const network = networkOf(ctx.flags);
+ if (ctx.flags.agent !== undefined && ctx.flags.agent !== '') {
+ const headers = await authed(ctx);
+ const agent = await resolveAgent(ctx, headers, ctx.flags.agent);
+ const { data = {} } = await requestJson(`${ctx.origin}/api/agents/balances`, { method: 'POST', headers, json: { ids: [agent.id] } });
+ const b = data[agent.id] || {};
+ const view = { source: 'agent-wallet', agent: agent.id, address: agent.solana_address || null, sol: b.sol ?? null, usdc: b.usdc ?? null, usd: b.usd ?? null };
+ return out(ctx, view, () => rows([['Agent', agent.name || agent.id], ['Wallet', view.address || 'none'], ['SOL', num(view.sol, 4)], ['USDC', num(view.usdc)], ['USD', num(view.usd)]]));
+ }
+ const view = await localBalance(ctx, network);
+ return out(ctx, view, () => rows([['Wallet', view.address], ['Network', network], ['SOL', num(view.sol, 4)], ['USDC', num(view.usdc)]]));
+}
+
+export async function orders(ctx) {
+ const [sub = 'list'] = ctx.positionals;
+ if (sub !== 'list') throw new CliError(EXIT_CODES.USAGE, 'usage', 'usage: three-ws orders list --agent <id|name> [--network mainnet|devnet]');
+ const network = networkOf(ctx.flags);
+ const headers = await authed(ctx);
+ const agent = await resolveAgent(ctx, headers, ctx.flags.agent);
+ const { data } = await get(ctx, headers, `/api/agents/${agent.id}/orders?network=${network}`);
+ return out(ctx, { agent: agent.id, network, orders: data.orders, summary: data.summary }, () => {
+ if (!data.orders.length) return line(`${agent.name || agent.id} has no ${network} orders. Place one at ${ctx.origin}/agents/${agent.id}.`);
+ for (const o of data.orders) line(`${o.id} ${String(o.status).padEnd(10)} ${String(o.type).padEnd(12)} ${o.side || ''} ${o.symbol ? `$${o.symbol}` : shortAddress(o.mint || '')}`);
+ });
+}
+
+/** The decision trail is public; a failure to read it must not block the report. */
+async function trailFor(ctx, agentId) {
+ try {
+ return await requestJson(`${ctx.origin}/api/agents/${agentId}/decision-trail/verify`);
+ } catch (err) {
+ process.stderr.write(`${c.yellow('!')} decision trail unavailable (${err.message}); the report will say so.\n`);
+ return null;
+ }
+}
+
+export async function report(ctx) {
+ const [sub, id] = ctx.positionals;
+ if (sub !== 'run') throw new CliError(EXIT_CODES.USAGE, 'usage', 'usage: three-ws report run <run-id> --out <file.html>');
+ requireInput(id, 'a run id', 'usage: three-ws report run <run-id> --out <file.html>');
+ const outFile = requireInput(typeof ctx.flags.out === 'string' ? ctx.flags.out : '', '--out <file.html>', 'the report is one file; say where to write it');
+ const headers = await authed(ctx);
+ const data = await fetchRun(ctx, headers, id);
+ const trail = await trailFor(ctx, data.run.agentId);
+ const html = buildRunReport({ run: data.run, steps: data.steps, toolTraces: data.toolTraces, receiptChain: data.receiptChain, trail, origin: ctx.origin });
+ const target = path.resolve(ctx.env.cwd || process.cwd(), outFile);
+ try {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, html);
+ } catch (err) {
+ throw new CliError(EXIT_CODES.ERROR, 'write_failed', `could not write ${target}: ${err.message}`);
+ }
+ const result = { run: data.run.id, file: target, bytes: Buffer.byteLength(html), steps: data.steps.length, tool_calls: data.toolTraces.length, decision_trail_head: trail?.chain?.head_hash ?? null };
+ return out(ctx, result, () => line(`Wrote ${target} (${result.bytes} bytes, ${result.steps} steps).`));
+}
diff --git a/packages/three-ws-cli/src/commands/common.js b/packages/three-ws-cli/src/commands/common.js
index 0bdfbc175..46aee2af8 100644
--- a/packages/three-ws-cli/src/commands/common.js
+++ b/packages/three-ws-cli/src/commands/common.js
@@ -4,6 +4,7 @@
import * as p from '@clack/prompts';
import { c, line, sym } from '../ui.js';
import { loginOAuth, loginDevice, loginKey, looksLikeKey } from '../auth.js';
+import { CliError, EXIT_CODES, isNonInteractive } from '../automation.js';
export class CancelledError extends Error {
constructor() {
@@ -18,9 +19,9 @@ export function answer(value) {
return value;
}
-/** Prompts are allowed only on a TTY, and never with --json or --yes. */
+/** Prompts are allowed only on a TTY, and never with --json, --yes or --non-interactive. */
export function canPrompt(ctx) {
- return Boolean(process.stdin.isTTY && process.stdout.isTTY && !ctx.flags.json && !ctx.flags.yes);
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY && !ctx.flags.json && !ctx.flags.yes && !isNonInteractive(ctx.flags, ctx.env));
}
export function authModeFromFlags(flags) {
@@ -41,6 +42,12 @@ function say(ctx, text) {
export async function signIn(ctx, { mode = null, financial = false, extraScopes = [] } = {}) {
const { origin, env } = ctx;
let chosen = mode;
+ if (isNonInteractive(ctx.flags, env)) {
+ chosen = mode || (env.vars.THREE_WS_API_KEY ? 'key' : null);
+ if (chosen !== 'key') {
+ throw new CliError(EXIT_CODES.AUTH, 'login_required', 'sign-in needs a human in --non-interactive mode. Pass --key <sk_live_...> or set THREE_WS_API_KEY.');
+ }
+ }
if (!chosen && canPrompt(ctx)) {
chosen = answer(await p.select({
message: 'How should this machine sign in to three.ws?',
@@ -62,7 +69,7 @@ export async function signIn(ctx, { mode = null, financial = false, extraScopes
validate: (v) => (looksLikeKey(v) ? undefined : 'Keys start with sk_live_ and are about 45 characters.'),
}));
}
- if (!key) throw new Error('pass the key with --key <sk_live_...> or THREE_WS_API_KEY');
+ if (!key) throw new CliError(isNonInteractive(ctx.flags, env) ? EXIT_CODES.AUTH : EXIT_CODES.USAGE, 'missing_key', 'pass the key with --key <sk_live_...> or THREE_WS_API_KEY');
return loginKey({ origin, key, env });
}
diff --git a/packages/three-ws-cli/src/commands/pay.js b/packages/three-ws-cli/src/commands/pay.js
index 13ee3aa92..70b58da87 100644
--- a/packages/three-ws-cli/src/commands/pay.js
+++ b/packages/three-ws-cli/src/commands/pay.js
@@ -12,8 +12,9 @@ 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';
+import { isNonInteractive } from '../automation.js';
-const interactive = (ctx) => Boolean(process.stdin.isTTY && process.stderr.isTTY && !ctx.flags.json);
+const interactive = (ctx) => Boolean(process.stdin.isTTY && process.stderr.isTTY && !ctx.flags.json && !isNonInteractive(ctx.flags, ctx.env));
export function keystoreFor(ctx) {
return createKeystore({
diff --git a/packages/three-ws-cli/src/commands/signup.js b/packages/three-ws-cli/src/commands/signup.js
index 9043d2b4a..cde3c5fad 100644
--- a/packages/three-ws-cli/src/commands/signup.js
+++ b/packages/three-ws-cli/src/commands/signup.js
@@ -19,9 +19,10 @@ import { requestJson } from '../http.js';
import { readStore, updateStore } from '../store.js';
import { credentialsPath } from '../paths.js';
import { answer } from './common.js';
+import { isNonInteractive } from '../automation.js';
import { c, line, printJson, rows, sym, tildify } from '../ui.js';
-const interactive = (ctx) => Boolean(process.stdin.isTTY && process.stderr.isTTY && !ctx.flags.json);
+const interactive = (ctx) => Boolean(process.stdin.isTTY && process.stderr.isTTY && !ctx.flags.json && !isNonInteractive(ctx.flags, ctx.env));
function keystoreFor(ctx) {
return createKeystore({
diff --git a/packages/three-ws-cli/src/commands/skills.js b/packages/three-ws-cli/src/commands/skills.js
index 801bc5c1a..3f3c2ff1f 100644
--- a/packages/three-ws-cli/src/commands/skills.js
+++ b/packages/three-ws-cli/src/commands/skills.js
@@ -23,12 +23,13 @@ import { bearerFor } from '../oauth.js';
import { readStore, resolveOrigin } from '../store.js';
import { systemEnv } from '../paths.js';
import { createInterface } from 'node:readline/promises';
+import { EXIT_CODES, isNonInteractive } from '../automation.js';
export const SKILLS_USAGE = `Usage:
three-ws skills list [--tag <tag>] [--author <name>] [--json]
three-ws skills search <query> [--json]
three-ws skills show <slug> [--json]
- three-ws skills import <slug> --agent <agent-id> [--disabled] [--yes] [--acknowledge-gated] [--json]
+ three-ws skills import <slug> --agent <agent-id> [--disabled] [--yes] [--acknowledge-gated] [--json] (alias: install)
three-ws skills import <openapi-url-or-owner/repo> [--json]
three-ws skills installed --agent <agent-id> [--json]
three-ws skills drafts [--json]
@@ -49,6 +50,9 @@ export function isImportUrl(arg) {
return typeof arg === 'string' && (/^https?:\/\//i.test(arg) || /^[\w.-]+\/[\w.-]+$/.test(arg));
}
+// Flags that never take a value, so `--json risk-manager` keeps `risk-manager` positional.
+const BOOLEAN_FLAGS = new Set(['json', 'yes', 'disabled', 'acknowledge-gated', 'non-interactive', 'no-color']);
+
/** Split argv into positionals and --flags (a flag followed by a non-flag takes it as its value). */
export function parseSkillsArgs(argv) {
const positional = [];
@@ -61,10 +65,11 @@ export function parseSkillsArgs(argv) {
}
const [key, inline] = a.slice(2).split('=', 2);
if (inline !== undefined) flags[key] = inline;
- else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[key] = argv[++i];
+ else if (!BOOLEAN_FLAGS.has(key) && argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[key] = argv[++i];
else flags[key] = true;
}
- return { sub: positional[0] || 'list', args: positional.slice(1), flags };
+ const sub = positional[0] === 'install' ? 'import' : positional[0] || 'list';
+ return { sub, args: positional.slice(1), flags };
}
async function authHeaders(env) {
@@ -142,7 +147,7 @@ async function importExternal({ skill, agent, headers, origin, flags, confirm })
const notice = externalNotice(skill);
if (!flags.yes && !(await confirm(`${notice}\nInstall onto agent ${agent}?`))) {
return {
- code: 1,
+ code: EXIT_CODES.GUARD,
output: `${notice}\n\nNot installed. Re-run with --yes to confirm (required when there is no terminal).`,
};
}
@@ -153,11 +158,11 @@ async function importExternal({ skill, agent, headers, origin, flags, confirm })
});
const request = scanned.request;
if (request.status === 'refused' || request.verdict === 'refused') {
- return { code: 1, output: `${notice}\n\nThe scan refused this skill (${request.verdict}); it was not installed. Details: ${origin}/skills/import` };
+ return { code: EXIT_CODES.GUARD, output: `${notice}\n\nThe scan refused this skill (${request.verdict}); it was not installed. Details: ${origin}/skills/import` };
}
if (request.gated && !flags['acknowledge-gated']) {
return {
- code: 1,
+ code: EXIT_CODES.GUARD,
output: `${notice}\n\nThis skill asks to spend, sign or send messages. It stays under the spend gate and needs --acknowledge-gated to install. Review the scan at ${origin}/skills/import first.`,
request,
};
@@ -178,12 +183,13 @@ export async function runSkills(argv, { env = systemEnv(), origin: originFlag, c
const { sub, args, flags } = parseSkillsArgs(argv);
const origin = resolveOrigin({ flag: originFlag || flags.origin, env, store: readStore(env) });
const json = Boolean(flags.json);
+ if (isNonInteractive(flags, env)) confirm = async () => false;
const done = (data, text) => ({ code: 0, output: json ? JSON.stringify(data, null, 2) : text });
if (sub === 'list' || sub === 'search') {
const q = new URLSearchParams();
if (sub === 'search') {
- if (!args.length) return { code: 2, output: SKILLS_USAGE };
+ if (!args.length) return { code: EXIT_CODES.USAGE, output: SKILLS_USAGE };
q.set('q', args.join(' '));
}
if (typeof flags.tag === 'string') q.set('tag', flags.tag);
@@ -193,7 +199,7 @@ export async function runSkills(argv, { env = systemEnv(), origin: originFlag, c
}
if (sub === 'show') {
- if (!args[0]) return { code: 2, output: SKILLS_USAGE };
+ if (!args[0]) return { code: EXIT_CODES.USAGE, output: SKILLS_USAGE };
const { skill } = await requestJson(`${origin}/api/skills/community/${encodeURIComponent(args[0])}`);
return done(skill, `${skill.name} (${skill.slug} v${skill.version}) by ${skill.author}\n${skill.description}\nTags: ${skill.tags.join(', ')} ~${skill.tokens} tokens\nSource: ${skill.source_url}\n\n${skill.body}`);
}
@@ -235,7 +241,7 @@ export async function runSkills(argv, { env = systemEnv(), origin: originFlag, c
const { data } = await requestJson(base, { headers });
return done(data, formatInstalled(data));
}
- if (!args[0]) return { code: 2, output: SKILLS_USAGE };
+ if (!args[0]) return { code: EXIT_CODES.USAGE, output: SKILLS_USAGE };
try {
const { data } = await requestJson(base, {
method: 'POST',
diff --git a/packages/three-ws-cli/src/commands/tools.js b/packages/three-ws-cli/src/commands/tools.js
index 51f5158e4..b9c7653e6 100644
--- a/packages/three-ws-cli/src/commands/tools.js
+++ b/packages/three-ws-cli/src/commands/tools.js
@@ -8,6 +8,7 @@
import * as p from '@clack/prompts';
import { answer, canPrompt } from './common.js';
+import { CliError, EXIT_CODES } from '../automation.js';
import { c, line, sym, printJson } from '../ui.js';
import { readStore, updateStore } from '../store.js';
import { loadDirectory, hostedServers } from '../servers.js';
@@ -96,7 +97,7 @@ async function chooseServer(ctx, all) {
if (!s) throw new Error(`unknown server "${flags.server}". Known: ${all.map((x) => x.slug).join(', ')}`);
return s;
}
- if (!canPrompt(ctx)) throw new Error(`pass --server <slug>. Servers: ${all.map((s) => s.slug).join(', ')}`);
+ if (!canPrompt(ctx)) throw new CliError(EXIT_CODES.USAGE, 'missing_input', `pass --server <slug>. Servers: ${all.map((s) => s.slug).join(', ')}`);
const store = readStore(ctx.env);
const configured = all.filter((s) => store.tools?.[s.slug]);
const slug = answer(await p.select({
diff --git a/packages/three-ws-cli/src/commands/wallet.js b/packages/three-ws-cli/src/commands/wallet.js
index 7e97c5a64..6a72ef1b0 100644
--- a/packages/three-ws-cli/src/commands/wallet.js
+++ b/packages/three-ws-cli/src/commands/wallet.js
@@ -33,6 +33,7 @@ export async function wallet(ctx) {
}
return EXIT.OK;
}
+ if (sub === 'balance') return (await import('./automation.js')).walletBalance(ctx);
if (sub === 'address') {
const a = store.address();
if (ctx.flags.json) printJson(a);
@@ -45,6 +46,6 @@ export async function wallet(ctx) {
else line(a.address);
return EXIT.OK;
}
- errorLine('usage: three-ws wallet <init [--storage auto|keychain|file]|address|export-public>');
+ errorLine('usage: three-ws wallet <init [--storage auto|keychain|file]|address|export-public|balance [--agent <id|name>] [--network mainnet|devnet]>');
return EXIT.USAGE;
}
diff --git a/packages/three-ws-cli/src/report/run-report.js b/packages/three-ws-cli/src/report/run-report.js
new file mode 100644
index 000000000..d4b06622a
--- /dev/null
+++ b/packages/three-ws-cli/src/report/run-report.js
@@ -0,0 +1,258 @@
+// One agent run as a single self-contained HTML file: inline CSS and JS, no
+// network, no external URL. The CLI (`three-ws report run <id>`) and the
+// "Download report" button on the run page both call buildRunReport, so the two
+// can never disagree about what a report contains.
+//
+// This module is pure (no node: imports, no DOM) so it runs in a browser bundle
+// and in Node. Input is the payload GET /api/agent-run-replay?run=<id> returns,
+// plus optionally the agent's decision-trail verification report.
+
+const TRADE_TOOL = /(swap|trade|buy|sell|order|transfer|snipe|launch|bridge|stake|perp|position)/i;
+
+const STATUS_LABEL = {
+ queued: 'Queued',
+ running: 'Running',
+ completed: 'Completed',
+ failed: 'Failed',
+ cancelled: 'Cancelled',
+ budget_exhausted: 'Stopped at its budget',
+ scheduled: 'Scheduled',
+ paused: 'Paused',
+};
+
+export function escapeHtml(value) {
+ return String(value ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+function pretty(value) {
+ if (value === undefined || value === null) return '';
+ if (typeof value === 'string') return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+function money(n) {
+ const v = Number(n) || 0;
+ return v === 0 ? '$0' : v < 0.01 ? `$${v.toFixed(4)}` : `$${v.toFixed(2)}`;
+}
+
+function when(iso) {
+ if (!iso) return 'not recorded';
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? String(iso) : d.toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' UTC');
+}
+
+function duration(run) {
+ const start = run.startedAt || run.createdAt;
+ if (!start || !run.finishedAt) return 'still running or not recorded';
+ const s = Math.round((new Date(run.finishedAt) - new Date(start)) / 1000);
+ if (!Number.isFinite(s) || s < 0) return 'not recorded';
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ return m < 60 ? `${m}m ${s % 60}s` : `${Math.floor(m / 60)}h ${m % 60}m`;
+}
+
+function isFailed(trace) {
+ return trace.status === 'error' || trace.status === 'blocked';
+}
+
+function toolCallsOf(step) {
+ const o = step.output;
+ if (!o || !Array.isArray(o.toolCalls)) return [];
+ return o.toolCalls.map((c) => c?.name || c?.function?.name).filter(Boolean);
+}
+
+/** The model's own words between tool calls: the decisions the agent took. */
+export function decisionsOf(steps) {
+ return steps
+ .filter((s) => s.kind === 'model_call')
+ .map((s) => ({ seq: s.seq, text: String(s.output?.content || '').trim(), calls: toolCallsOf(s), model: s.model, at: s.at }))
+ .filter((d) => d.text || d.calls.length);
+}
+
+/** Tool traces that look like trades, with the outcome of each. */
+export function tradesOf(traces) {
+ return traces.filter((t) => TRADE_TOOL.test(String(t.tool || '')));
+}
+
+/** The head of the run's receipt chain: the receipt on the last step that has one. */
+export function receiptHead(steps) {
+ for (let i = steps.length - 1; i >= 0; i -= 1) if (steps[i].receipt) return steps[i].receipt;
+ return null;
+}
+
+function block(label, value) {
+ const text = pretty(value);
+ if (!text) return '';
+ return `<div class="blk"><span class="lbl">${escapeHtml(label)}</span><pre>${escapeHtml(text)}</pre></div>`;
+}
+
+function traceRow(t) {
+ const tone = t.status === 'ok' ? 'ok' : t.status === 'pending' ? 'wait' : 'bad';
+ return `<details class="row ${tone}" data-status="${escapeHtml(t.status)}">
+<summary><span class="seq">#${escapeHtml(t.callSeq ?? t.resultSeq ?? '')}</span><span class="tool">${escapeHtml(t.tool)}</span><span class="chip ${tone}">${escapeHtml(t.status)}</span>${t.latencyMs != null ? `<span class="meta">${escapeHtml(t.latencyMs)} ms</span>` : ''}${t.receipt ? `<code class="hash" title="${escapeHtml(t.receipt)}">${escapeHtml(String(t.receipt).slice(0, 12))}</code>` : ''}</summary>
+${block('Input', t.input)}${block('Output', t.output)}${t.receipt ? `<div class="blk"><span class="lbl">Receipt</span><pre>${escapeHtml(t.receipt)}</pre></div>` : ''}
+</details>`;
+}
+
+function chainBadge(chain) {
+ if (!chain) return '<span class="chip wait">receipt chain not recomputed</span>';
+ if (chain.verified) return `<span class="chip ok">receipt chain verified, ${escapeHtml(chain.checked)} steps</span>`;
+ if (chain.brokenAt != null) return `<span class="chip bad">receipt chain broken at step ${escapeHtml(chain.brokenAt)}</span>`;
+ return '<span class="chip wait">run predates step receipts</span>';
+}
+
+function trailSection(trail) {
+ if (!trail) {
+ return `<p class="note">The decision trail could not be fetched when this report was made, so its head hash is not included. The run's own receipt chain above still vouches for every step.</p>`;
+ }
+ const head = trail.chain?.head_hash;
+ const status = String(trail.status || 'unknown').replace(/_/g, ' ');
+ const tone = trail.ok === false ? 'bad' : trail.status === 'verified' ? 'ok' : 'wait';
+ if (!head) {
+ return `<p><span class="chip ${tone}">${escapeHtml(status)}</span> This agent has no recorded decisions yet, so the trail has no head hash.</p>`;
+ }
+ return `<div class="kv">
+<div><span class="lbl">Status</span><span class="chip ${tone}">${escapeHtml(status)}</span></div>
+<div><span class="lbl">Entries</span><span>${escapeHtml(trail.chain?.count ?? 'unknown')}</span></div>
+<div><span class="lbl">Head hash</span><code class="full">${escapeHtml(head)}</code></div>
+${trail.anchor?.signature ? `<div><span class="lbl">On-chain anchor</span><code class="full">${escapeHtml(trail.anchor.signature)}</code></div>` : '<div><span class="lbl">On-chain anchor</span><span>none yet</span></div>'}
+<div><span class="lbl">Checked</span><span>${escapeHtml(when(trail.checked_at))}</span></div>
+</div>`;
+}
+
+const CSS = `
+:root{color-scheme:light dark;--bg:#fff;--fg:#14161a;--mut:#5a6270;--line:#dfe3ea;--card:#f6f8fb;--ok:#0f7b3f;--bad:#b3261e;--wait:#8a5a00;--acc:#3b3ff0}
+@media(prefers-color-scheme:dark){:root{--bg:#0d0f13;--fg:#e9ecf1;--mut:#9aa3b2;--line:#262b34;--card:#151920;--ok:#4cd68b;--bad:#ff8a80;--wait:#f0b84a;--acc:#8b8fff}}
+*{box-sizing:border-box}
+body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
+main{max-width:920px;margin:0 auto;padding:32px 16px 64px}
+h1{font-size:1.5rem;margin:0 0 4px}h2{font-size:1.1rem;margin:36px 0 12px;padding-top:12px;border-top:1px solid var(--line)}
+.sub{color:var(--mut);margin:0 0 20px}
+.goal{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px 16px;white-space:pre-wrap;overflow-wrap:anywhere}
+.meters{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:16px 0}
+.meter{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 12px}
+.meter b{display:block;font-size:1.05rem}.meter span,.lbl{color:var(--mut);font-size:.8rem;text-transform:uppercase;letter-spacing:.04em}
+.chip{display:inline-block;border-radius:999px;padding:1px 10px;font-size:.78rem;border:1px solid currentColor;margin-right:6px}
+.chip.ok{color:var(--ok)}.chip.bad{color:var(--bad)}.chip.wait{color:var(--wait)}
+.row{border:1px solid var(--line);border-radius:10px;margin:8px 0;background:var(--card)}
+.row.bad{border-color:var(--bad)}
+.row summary{cursor:pointer;padding:9px 12px;display:flex;flex-wrap:wrap;gap:8px;align-items:center}
+.row summary:focus-visible,button:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
+.seq,.meta{color:var(--mut);font-size:.85rem}.tool{font-weight:600}
+.hash{margin-left:auto;font-size:.78rem;color:var(--mut)}
+.blk{padding:0 12px 10px}pre{margin:4px 0 0;padding:10px;background:var(--bg);border:1px solid var(--line);border-radius:8px;overflow:auto;max-height:340px;font-size:.82rem;white-space:pre-wrap;overflow-wrap:anywhere}
+code.full{display:block;overflow-wrap:anywhere;font-size:.85rem}
+.kv{display:grid;gap:10px}.kv>div{display:grid;gap:2px}
+.dec{border-left:3px solid var(--acc);padding:4px 0 4px 12px;margin:10px 0;white-space:pre-wrap;overflow-wrap:anywhere}
+.note{color:var(--mut)}.empty{color:var(--mut);font-style:italic}
+.tools{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0}
+button{font:inherit;border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:8px;padding:6px 12px;cursor:pointer}
+button:hover{border-color:var(--acc)}button:active{transform:translateY(1px)}
+footer{margin-top:40px;color:var(--mut);font-size:.85rem}
+@media print{button{display:none}details{display:block}.row summary{cursor:default}}
+`;
+
+const SCRIPT = `
+(function(){
+ var rows=[].slice.call(document.querySelectorAll('.row'));
+ function setOpen(v){rows.forEach(function(r){r.open=v});}
+ var all=document.getElementById('expand'),fail=document.getElementById('failed'),copy=document.getElementById('copyhash');
+ if(all){all.addEventListener('click',function(){var open=all.getAttribute('aria-pressed')!=='true';all.setAttribute('aria-pressed',String(open));all.textContent=open?'Collapse all':'Expand all';setOpen(open);});}
+ if(fail){fail.addEventListener('click',function(){var on=fail.getAttribute('aria-pressed')!=='true';fail.setAttribute('aria-pressed',String(on));fail.textContent=on?'Show all calls':'Show failed calls only';
+ document.querySelectorAll('#calls .row').forEach(function(r){var bad=r.getAttribute('data-status')==='error'||r.getAttribute('data-status')==='blocked';r.hidden=on&&!bad;});});}
+ if(copy&&navigator.clipboard){copy.addEventListener('click',function(){navigator.clipboard.writeText(copy.getAttribute('data-hash')).then(function(){copy.textContent='Copied';});});}else if(copy){copy.hidden=true;}
+})();
+`;
+
+/**
+ * @param {{
+ * run: object, steps: object[], toolTraces?: object[], receiptChain?: object|null,
+ * trail?: object|null, origin?: string, generatedAt?: string
+ * }} input
+ * @returns {string} a complete HTML document
+ */
+export function buildRunReport({ run, steps = [], toolTraces = [], receiptChain = null, trail = null, origin = 'https://three.ws', generatedAt = new Date().toISOString() }) {
+ const traces = toolTraces;
+ const failed = traces.filter(isFailed);
+ const trades = tradesOf(traces);
+ const decisions = decisionsOf(steps);
+ const turns = steps.filter((s) => s.kind === 'model_call').length;
+ const head = receiptHead(steps);
+ const budget = run.budget?.creditsUsd || 0;
+ const spent = run.spent?.creditsUsd || 0;
+ const outcome = run.result || run.error || run.summary || null;
+ const outcomeTone = run.status === 'completed' ? 'ok' : run.status === 'failed' ? 'bad' : 'wait';
+ const title = `Run report ${run.id}`;
+ let host = origin;
+ try {
+ host = new URL(origin).host;
+ } catch {
+ host = String(origin).replace(/^https?:\/\//, '');
+ }
+
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>${escapeHtml(title)}</title>
+<style>${CSS}</style>
+</head>
+<body>
+<main>
+<h1>Agent run report</h1>
+<p class="sub">Run <code>${escapeHtml(run.id)}</code> for agent <code>${escapeHtml(run.agentId)}</code>. Generated ${escapeHtml(when(generatedAt))} from ${escapeHtml(host)}.</p>
+
+<h2>Goal</h2>
+<div class="goal">${escapeHtml(run.goal)}</div>
+<div class="meters">
+<div class="meter"><span>Status</span><b>${escapeHtml(STATUS_LABEL[run.status] || run.status)}</b></div>
+<div class="meter"><span>Model turns</span><b>${escapeHtml(turns)}${run.maxSteps ? ` of ${escapeHtml(run.maxSteps)}` : ''}</b></div>
+<div class="meter"><span>Tool calls</span><b>${escapeHtml(traces.length)}${failed.length ? ` (${escapeHtml(failed.length)} failed)` : ''}</b></div>
+<div class="meter"><span>Credits</span><b>${escapeHtml(budget ? `${money(spent)} of ${money(budget)}` : `${money(spent)} (free lanes)`)}</b></div>
+<div class="meter"><span>Duration</span><b>${escapeHtml(duration(run))}</b></div>
+<div class="meter"><span>Model</span><b>${escapeHtml(run.model || 'default')}</b></div>
+</div>
+<p class="note">Started ${escapeHtml(when(run.startedAt || run.createdAt))}. Finished ${escapeHtml(when(run.finishedAt))}.</p>
+
+<h2>Outcome</h2>
+${outcome ? `<p><span class="chip ${outcomeTone}">${escapeHtml(STATUS_LABEL[run.status] || run.status)}</span></p><div class="goal">${escapeHtml(pretty(outcome))}</div>` : '<p class="empty">The run has not recorded an outcome yet.</p>'}
+${run.summary && run.summary !== outcome ? `<p class="note">${escapeHtml(run.summary)}</p>` : ''}
+
+<h2>Decisions</h2>
+${decisions.length ? decisions.map((d) => `<div class="dec"><span class="meta">#${escapeHtml(d.seq)}${d.model ? ` ${escapeHtml(d.model)}` : ''}</span><br>${d.text ? escapeHtml(d.text) : '<span class="empty">No text.</span>'}${d.calls.length ? `<br><span class="meta">Asked for: ${escapeHtml(d.calls.join(', '))}</span>` : ''}</div>`).join('\n') : '<p class="empty">The model recorded no decisions in this run.</p>'}
+
+<h2>Trades</h2>
+${trades.length ? trades.map(traceRow).join('\n') : '<p class="empty">No trade, swap, order or transfer tool was called in this run. Runs use a read-only tool registry unless the agent was granted more.</p>'}
+
+<h2>Tool calls</h2>
+<div class="tools"><button type="button" id="expand" aria-pressed="false">Expand all</button>${failed.length ? '<button type="button" id="failed" aria-pressed="false">Show failed calls only</button>' : ''}</div>
+<div id="calls">
+${traces.length ? traces.map(traceRow).join('\n') : '<p class="empty">The run made no tool calls.</p>'}
+</div>
+
+<h2>Integrity</h2>
+<p>${chainBadge(receiptChain)}</p>
+<div class="kv">
+<div><span class="lbl">Receipt chain head</span>${head ? `<code class="full">${escapeHtml(head)}</code>` : '<span>none recorded</span>'}</div>
+</div>
+${head ? `<div class="tools"><button type="button" id="copyhash" data-hash="${escapeHtml(head)}">Copy head hash</button></div>` : ''}
+<h2>Decision trail head</h2>
+${trailSection(trail)}
+
+<footer>Self-contained report: no scripts or styles are loaded from the network. Verify live at ${escapeHtml(host)}/agents/${escapeHtml(run.agentId)}.</footer>
+</main>
+<script>${SCRIPT}</script>
+</body>
+</html>
+`;
+}
diff --git a/packages/three-ws-cli/tests/agent.test.js b/packages/three-ws-cli/tests/agent.test.js
index 476c4fd0a..3bbb2bf5c 100644
--- a/packages/three-ws-cli/tests/agent.test.js
+++ b/packages/three-ws-cli/tests/agent.test.js
@@ -69,7 +69,7 @@ describe('three-ws create', () => {
it('refuses to run without a credential when it cannot prompt', async () => {
const bare = tempEnv();
const { code, json } = await run(['create', 'Nova', '--json', '--origin', ORIGIN], bare);
- expect(code).toBe(1);
+ expect(code).toBe(3);
expect(json.message).toContain('npx three-ws login');
expect(fetchMock).not.toHaveBeenCalled();
});
diff --git a/packages/three-ws-cli/tests/automation.test.js b/packages/three-ws-cli/tests/automation.test.js
new file mode 100644
index 000000000..8d48265a3
--- /dev/null
+++ b/packages/three-ws-cli/tests/automation.test.js
@@ -0,0 +1,298 @@
+// Automation mode against a real local HTTP server and a real local JSON-RPC
+// node: every documented exit code is triggered, --json keeps stdout to one
+// JSON document, --non-interactive never prompts, and the HTML report is a
+// single self-contained file.
+
+import fs from 'node:fs';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { generateKeyPairSigner } from '@solana/kit';
+import { main } from '../src/cli.js';
+import { EXIT_CODES, exitCodeFor } from '../src/automation.js';
+import { ApiError } from '../src/http.js';
+import { buildRunReport } from '../src/report/run-report.js';
+import { createKeystore } from '../src/pay/keystore.js';
+import { USDC_MAINNET } from '../src/pay/permissions.js';
+
+const AGENT = '11111111-1111-4111-8111-111111111111';
+const RUN = '22222222-2222-4222-8222-222222222222';
+const GOAL = 'Watch the pool and report if liquidity drops <b>below</b> 50k';
+const HEAD = 'a'.repeat(64);
+
+const run = {
+ id: RUN,
+ agentId: AGENT,
+ goal: GOAL,
+ status: 'completed',
+ model: 'fixture-model',
+ maxSteps: 8,
+ budget: { creditsUsd: 0.5, usd: 0 },
+ spent: { creditsUsd: 0.0123, usd: 0 },
+ result: 'Liquidity held above 50k for the whole window.',
+ summary: 'Completed after 2 model turns.',
+ createdAt: '2026-10-20T10:00:00.000Z',
+ startedAt: '2026-10-20T10:00:01.000Z',
+ finishedAt: '2026-10-20T10:00:41.000Z',
+};
+const steps = [
+ { seq: 1, kind: 'status', output: { status: 'queued' }, receipt: null },
+ { seq: 2, kind: 'model_call', model: 'fixture-model', output: { content: 'I will read the pool first.', toolCalls: [{ name: 'get_pool' }] }, receipt: 'b'.repeat(64), at: run.startedAt },
+ { seq: 3, kind: 'tool_call', tool: 'get_pool', input: { pool: 'synthetic-pool' }, receipt: 'c'.repeat(64) },
+ { seq: 4, kind: 'tool_result', tool: 'get_pool', input: { pool: 'synthetic-pool' }, output: { liquidityUsd: 61000 }, receipt: 'd'.repeat(64), latencyMs: 120 },
+ { seq: 5, kind: 'model_call', model: 'fixture-model', output: { content: 'Liquidity is fine; trying a swap quote.', toolCalls: [{ name: 'swap_quote' }] }, receipt: 'e'.repeat(64) },
+ { seq: 6, kind: 'tool_blocked', tool: 'swap_quote', input: { amount: 1 }, output: { reason: 'not in the allowed tool set' }, receipt: 'f'.repeat(64) },
+ { seq: 7, kind: 'final', output: { result: run.result }, receipt: HEAD },
+];
+const toolTraces = [
+ { tool: 'get_pool', input: { pool: 'synthetic-pool' }, callSeq: 3, status: 'ok', output: { liquidityUsd: 61000 }, resultSeq: 4, receipt: 'd'.repeat(64), latencyMs: 120 },
+ { tool: 'swap_quote', input: { amount: 1 }, callSeq: null, status: 'blocked', output: { reason: 'not in the allowed tool set' }, resultSeq: 6, receipt: 'f'.repeat(64), latencyMs: null },
+];
+const trail = { agent_id: AGENT, status: 'verified_unanchored', ok: true, chain: { ok: true, count: 3, head_hash: '9'.repeat(64) }, anchor: null, checked_at: '2026-10-20T11:00:00.000Z' };
+
+let server;
+let origin;
+let rpcServer;
+let rpcUrl;
+const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'three-ws-automation-'));
+
+function reply(res, status, body) {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(body));
+}
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ const url = new URL(req.url, 'http://x');
+ const auth = req.headers.authorization || '';
+ if (url.pathname === '/api/skills/community/ext-skill') return reply(res, 200, { skill: { origin: 'external', name: 'Ext', slug: 'ext-skill', source: 'example/skills', ref: 'abc1234', license: 'MIT', tree_url: 'https://example.invalid/tree', import: { registry: 'r', skill: 's' } } });
+ if (url.pathname.endsWith('/decision-trail/verify')) return reply(res, 200, trail);
+ if (auth === 'Bearer sk_live_revoked') return reply(res, 401, { error: 'invalid_token', error_description: 'revoked' });
+ if (auth === 'Bearer sk_live_guarded') return reply(res, 403, { error: 'firewall_blocked', error_description: 'blocked by the trade firewall' });
+ if (auth === 'Bearer sk_live_pay') return reply(res, 402, { error: 'payment_required', error_description: 'upgrade your plan' });
+ if (auth !== 'Bearer sk_live_ok') return reply(res, 401, { error: 'unauthorized' });
+ if (url.pathname === `/api/agents/${AGENT}/custom-skills` && req.method === 'POST') return reply(res, 404, { error: 'not_found' });
+ if (url.pathname === '/api/agents' && req.method === 'POST') return reply(res, 201, { agent: { id: AGENT, name: 'x' } });
+ if (url.pathname === '/api/agents') return reply(res, 200, { agents: [{ id: AGENT, name: 'Scout', solana_address: 'SyntheticWalletAddress11111111111111111111111', avatar_id: 'av1' }] });
+ if (url.pathname === '/api/agents/balances') return reply(res, 200, { data: { [AGENT]: { sol: 1.5, usdc: 20, usd: 250 } } });
+ if (url.pathname === '/api/agent-run-replay' && url.searchParams.get('agent')) return reply(res, 200, { data: { runs: [run], hasMore: false, nextBefore: null } });
+ if (url.pathname === '/api/agent-run-replay' && url.searchParams.get('run') === RUN) {
+ return reply(res, 200, { data: { run, live: false, steps, toolTraces, receiptChain: { verified: true, checked: 6, brokenAt: null }, nextAfter: 7, hasMore: false } });
+ }
+ if (url.pathname === `/api/agents/${AGENT}/orders`) return reply(res, 200, { data: { orders: [{ id: 'o1', status: 'active', type: 'limit', side: 'buy', symbol: 'THREE' }], summary: { active: 1 } } });
+ return reply(res, 404, { error: 'not_found' });
+ });
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ origin = `http://127.0.0.1:${server.address().port}`;
+
+ rpcServer = http.createServer(async (req, res) => {
+ let body = '';
+ for await (const chunk of req) body += chunk;
+ const call = JSON.parse(body);
+ let result;
+ if (call.method === 'getBalance') result = { context: { slot: 1 }, value: 2_500_000_000 };
+ if (call.method === 'getTokenAccountsByOwner') {
+ result = { context: { slot: 1 }, value: [{ pubkey: 'x', account: { data: { parsed: { info: { tokenAmount: { amount: '7500000' } } } } } }] };
+ }
+ reply(res, 200, result === undefined ? { jsonrpc: '2.0', id: call.id, error: { code: -32601, message: 'unexpected' } } : { jsonrpc: '2.0', id: call.id, result });
+ });
+ await new Promise((r) => rpcServer.listen(0, '127.0.0.1', r));
+ rpcUrl = `http://127.0.0.1:${rpcServer.address().port}`;
+});
+
+afterAll(async () => {
+ await new Promise((r) => server.close(r));
+ await new Promise((r) => rpcServer.close(r));
+});
+afterEach(() => vi.restoreAllMocks());
+
+function envWith(key, extra = {}) {
+ const home = fs.mkdtempSync(path.join(scratch, 'home-'));
+ const vars = { THREE_WS_NO_BROWSER: '1', NO_COLOR: '1', XDG_CONFIG_HOME: path.join(home, '.config'), ...extra };
+ if (key) vars.THREE_WS_API_KEY = key;
+ return { home, platform: 'linux', cwd: home, vars };
+}
+
+async function cli(argv, env) {
+ let out = '';
+ let err = '';
+ vi.spyOn(process.stdout, 'write').mockImplementation((c) => ((out += c.toString()), true));
+ vi.spyOn(process.stderr, 'write').mockImplementation((c) => ((err += c.toString()), true));
+ const code = await main(argv, env);
+ vi.restoreAllMocks();
+ return { code, out, err };
+}
+
+describe('exit-code table', () => {
+ it('0: success, with --json stdout a single document and stderr empty', async () => {
+ const r = await cli(['agents', 'list', '--json', '--origin', origin], envWith('sk_live_ok'));
+ expect(r.code).toBe(EXIT_CODES.OK);
+ expect(JSON.parse(r.out).agents).toHaveLength(1);
+ expect(r.out.trim().split('\n').filter((l) => l.startsWith('{')).length).toBe(1);
+ expect(r.err).toBe('');
+ });
+
+ it('1: an error with no better code (the server does not know the run)', async () => {
+ const r = await cli(['runs', 'get', '33333333-3333-4333-8333-333333333333', '--json', '--origin', origin], envWith('sk_live_ok'));
+ expect(r.code).toBe(EXIT_CODES.ERROR);
+ expect(JSON.parse(r.out)).toMatchObject({ error: 'not_found', exit: 1 });
+ });
+
+ it('2: usage, for an unknown flag, a missing agent, an unknown command and a bad run id', async () => {
+ const env = envWith('sk_live_ok');
+ expect((await cli(['agents', 'list', '--bogus'], env)).code).toBe(2);
+ expect((await cli(['frobnicate', '--json'], env)).code).toBe(2);
+ const noAgent = await cli(['runs', 'list', '--json', '--origin', origin], env);
+ expect(noAgent.code).toBe(2);
+ expect(JSON.parse(noAgent.out)).toMatchObject({ error: 'missing_input', exit: 2 });
+ expect((await cli(['runs', 'get', 'not-a-uuid', '--origin', origin], env)).code).toBe(2);
+ });
+
+ it('3: auth, with no credential and with a revoked key', async () => {
+ const none = await cli(['agents', 'list', '--json', '--origin', origin], envWith(null));
+ expect(none.code).toBe(EXIT_CODES.AUTH);
+ expect(JSON.parse(none.out).error).toBe('login_required');
+ expect((await cli(['agents', 'list', '--origin', origin], envWith('sk_live_revoked'))).code).toBe(3);
+ });
+
+ it('4: refused by a guard, from the server and from the external-skill confirmation', async () => {
+ const r = await cli(['agents', 'list', '--json', '--origin', origin], envWith('sk_live_guarded'));
+ expect(r.code).toBe(EXIT_CODES.GUARD);
+ expect(JSON.parse(r.out).error).toBe('firewall_blocked');
+ expect(exitCodeFor(new ApiError('x', { status: 403, code: 'spend_policy' }))).toBe(4);
+ });
+
+ it('5: payment required', async () => {
+ const r = await cli(['agents', 'list', '--json', '--origin', origin], envWith('sk_live_pay'));
+ expect(r.code).toBe(EXIT_CODES.PAYMENT);
+ expect(JSON.parse(r.out).exit).toBe(5);
+ });
+
+ it('6: network, for an unreachable host and for a server fault', async () => {
+ const dead = await cli(['agents', 'list', '--json', '--origin', 'http://127.0.0.1:1'], envWith('sk_live_ok'));
+ expect(dead.code).toBe(EXIT_CODES.NETWORK);
+ expect(JSON.parse(dead.out).error).toBe('error');
+ expect(exitCodeFor(new ApiError('x', { status: 503 }))).toBe(6);
+ expect(exitCodeFor(new ApiError('x', { status: 429 }))).toBe(6);
+ });
+
+ it('keeps pay\'s own exit codes untouched', () => {
+ expect(exitCodeFor(Object.assign(new Error('x'), { exit: 11 }))).toBe(11);
+ });
+});
+
+describe('stdout purity under --json', () => {
+ it('puts exactly one JSON document on stdout for every command, success and failure', async () => {
+ const env = envWith('sk_live_ok', { THREE_WS_SOLANA_RPC_URL: rpcUrl });
+ const argvs = [
+ ['agents', 'list'],
+ ['agents', 'get', 'Scout'],
+ ['runs', 'list', '--agent', 'Scout'],
+ ['runs', 'get', RUN],
+ ['orders', 'list', '--agent', AGENT],
+ ['wallet', 'balance', '--agent', AGENT],
+ ['agents', 'get', 'nobody'],
+ ['version'],
+ ];
+ for (const argv of argvs) {
+ const r = await cli([...argv, '--json', '--origin', origin], env);
+ expect(() => JSON.parse(r.out), argv.join(' ')).not.toThrow();
+ }
+ });
+
+ it('reads the orders and run views from the real endpoints', async () => {
+ const env = envWith('sk_live_ok');
+ const orders = JSON.parse((await cli(['orders', 'list', '--agent', 'Scout', '--json', '--origin', origin], env)).out);
+ expect(orders.orders[0]).toMatchObject({ id: 'o1', symbol: 'THREE' });
+ const detail = JSON.parse((await cli(['runs', 'get', RUN, '--json', '--origin', origin], env)).out);
+ expect(detail.receiptChain).toMatchObject({ verified: true });
+ expect(detail.toolTraces).toHaveLength(2);
+ });
+
+ it('reads the local pay wallet balance from Solana RPC', async () => {
+ const env = envWith(null, { THREE_WS_SOLANA_RPC_URL: rpcUrl, THREE_WS_WALLET_PASSPHRASE: 'correct horse battery staple' });
+ const made = await createKeystore({ env }).init({ storage: 'file' });
+ const r = await cli(['wallet', 'balance', '--json'], env);
+ expect(r.code).toBe(0);
+ expect(JSON.parse(r.out)).toMatchObject({ source: 'pay-wallet', address: made.address, sol: 2.5, usdc: 7.5, network: 'mainnet' });
+ expect(USDC_MAINNET).toBeTruthy();
+ });
+
+ it('reads an agent wallet balance', async () => {
+ const r = await cli(['wallet', 'balance', '--agent', 'Scout', '--json', '--origin', origin], envWith('sk_live_ok'));
+ expect(JSON.parse(r.out)).toMatchObject({ source: 'agent-wallet', usdc: 20, sol: 1.5 });
+ });
+});
+
+describe('--non-interactive', () => {
+ it('never signs in with a browser: exit 3 and no request is made', async () => {
+ const spy = vi.fn();
+ const probe = http.createServer((req, res) => (spy(), reply(res, 500, {})));
+ await new Promise((r) => probe.listen(0, '127.0.0.1', r));
+ const o = `http://127.0.0.1:${probe.address().port}`;
+ const r = await cli(['login', '--non-interactive', '--json', '--origin', o], envWith(null));
+ await new Promise((res) => probe.close(res));
+ expect(r.code).toBe(3);
+ expect(JSON.parse(r.out).error).toBe('login_required');
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('treats missing input as a usage error instead of asking', async () => {
+ const r = await cli(['create', '--non-interactive', '--json', '--origin', origin], envWith('sk_live_ok'));
+ expect(r.code).toBe(2);
+ expect(JSON.parse(r.out).exit).toBe(2);
+ });
+
+ it('refuses an external skill install without --yes (exit 4), never asking', async () => {
+ const r2 = await cli(['skill', 'install', 'ext-skill', '--agent', AGENT, '--non-interactive', '--origin', origin], envWith('sk_live_ok'));
+ expect(r2.code).toBe(EXIT_CODES.GUARD);
+ expect(r2.out + r2.err).toContain('Not installed');
+ });
+});
+
+describe('run report', () => {
+ const html = buildRunReport({ run, steps, toolTraces, receiptChain: { verified: true, checked: 6, brokenAt: null }, trail, origin: 'https://three.ws', generatedAt: '2026-10-20T12:00:00.000Z' });
+
+ it('contains the goal, tool calls, decisions, outcome and both head hashes, escaped', () => {
+ expect(html).toContain('Watch the pool and report if liquidity drops &lt;b&gt;below&lt;/b&gt; 50k');
+ expect(html).not.toContain('<b>below</b>');
+ expect(html).toContain('get_pool');
+ expect(html).toContain('I will read the pool first.');
+ expect(html).toContain('Liquidity held above 50k');
+ expect(html).toContain(HEAD);
+ expect(html).toContain('9'.repeat(64));
+ expect(html).toContain('not in the allowed tool set');
+ });
+
+ it('names trade-like calls under Trades and says so when there are none', () => {
+ expect(html).toMatch(/<h2>Trades<\/h2>[\s\S]*swap_quote/);
+ const none = buildRunReport({ run, steps: [], toolTraces: [{ ...toolTraces[0] }], trail: null });
+ expect(none).toContain('No trade, swap, order or transfer tool was called');
+ expect(none).toContain('decision trail could not be fetched');
+ });
+
+ it('references no external URL at all', () => {
+ expect(html).not.toMatch(/https?:\/\//i);
+ expect(html).not.toMatch(/<(script|link|img|iframe)\b[^>]*\b(src|href)=/i);
+ expect(html).not.toMatch(/@import|url\(/i);
+ expect(html).not.toMatch(new RegExp(String.fromCharCode(0x2014) + '|' + String.fromCharCode(0x2013)));
+ });
+
+ it('is written by `report run` to --out as one file', async () => {
+ const file = path.join(scratch, 'out', 'run.html');
+ const r = await cli(['report', 'run', RUN, '--out', file, '--json', '--origin', origin], envWith('sk_live_ok'));
+ expect(r.code).toBe(0);
+ const summary = JSON.parse(r.out);
+ expect(summary).toMatchObject({ run: RUN, file, decision_trail_head: '9'.repeat(64) });
+ const written = fs.readFileSync(file, 'utf8');
+ expect(written.startsWith('<!doctype html>')).toBe(true);
+ expect(written).toContain(HEAD);
+ expect(written).not.toMatch(/https?:\/\//i);
+ });
+
+ it('requires --out', async () => {
+ const r = await cli(['report', 'run', RUN, '--json', '--origin', origin], envWith('sk_live_ok'));
+ expect(r.code).toBe(2);
+ });
+});
diff --git a/packages/three-ws-cli/tests/quick-doctor.test.js b/packages/three-ws-cli/tests/quick-doctor.test.js
index ffea2c834..744f1aef7 100644
--- a/packages/three-ws-cli/tests/quick-doctor.test.js
+++ b/packages/three-ws-cli/tests/quick-doctor.test.js
@@ -266,7 +266,7 @@ describe('three-ws agent status and team', () => {
const bare = tempEnv();
const a = await run(['agent', 'status', '--origin', ORIGIN], bare);
const t = await run(['team', '--origin', ORIGIN], bare);
- expect([a.code, t.code]).toEqual([1, 1]);
+ expect([a.code, t.code]).toEqual([3, 3]);
});
});
diff --git a/packages/three-ws-cli/tests/skills.test.js b/packages/three-ws-cli/tests/skills.test.js
index 5a4cd1f63..74673f9ee 100644
--- a/packages/three-ws-cli/tests/skills.test.js
+++ b/packages/three-ws-cli/tests/skills.test.js
@@ -192,7 +192,7 @@ describe('three-ws skills import <external slug>', () => {
it('refuses without --yes in a non-interactive shell, printing source and commit, and installs nothing', async () => {
fetchMock.mockResolvedValueOnce(notFound()).mockResolvedValueOnce(reply(200, { skill: EXTERNAL }));
const { code, out } = await run(['skills', 'import', 'fixture-skill', '--agent', agent, '--origin', ORIGIN], env);
- expect(code).toBe(1);
+ expect(code).toBe(4);
expect(out).toBe('');
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls.map(([u]) => u)).not.toContain(`${ORIGIN}/api/skill-imports/scan`);
@@ -202,7 +202,7 @@ describe('three-ws skills import <external slug>', () => {
fetchMock.mockResolvedValueOnce(notFound()).mockResolvedValueOnce(reply(200, { skill: EXTERNAL }));
const { runSkills } = await import('../src/commands/skills.js');
const result = await runSkills(['import', 'fixture-skill', '--agent', agent], { env, origin: ORIGIN });
- expect(result.code).toBe(1);
+ expect(result.code).toBe(4);
expect(result.output).toContain('fixture-org/skills-repo');
expect(result.output).toContain(SHA);
expect(result.output).toContain('not reviewed by three.ws');
@@ -232,13 +232,14 @@ describe('three-ws skills import <external slug>', () => {
.mockResolvedValueOnce(reply(201, { data: { request: { id: 'r2', status: 'pending', verdict: 'caution', gated: true } } }));
const { runSkills } = await import('../src/commands/skills.js');
const result = await runSkills(['import', 'fixture-skill', '--agent', agent, '--yes'], { env, origin: ORIGIN });
- expect(result.code).toBe(1);
+ expect(result.code).toBe(4);
expect(result.output).toContain('--acknowledge-gated');
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('reports a slug that is neither in-repo nor external as the original not-found error', async () => {
fetchMock.mockResolvedValueOnce(notFound()).mockResolvedValueOnce(notFound());
- await expect(run(['skills', 'import', 'fixture-skill', '--agent', agent, '--yes', '--origin', ORIGIN], env)).rejects.toMatchObject({ status: 404, code: 'not_found' });
+ const { code } = await run(['skills', 'import', 'fixture-skill', '--agent', agent, '--yes', '--json', '--origin', ORIGIN], env);
+ expect(code).toBe(1);
});
});
diff --git a/src/agent-run-replay.js b/src/agent-run-replay.js
index 9c573bd34..b421f3068 100644
--- a/src/agent-run-replay.js
+++ b/src/agent-run-replay.js
@@ -12,6 +12,7 @@
// kept in ?run= so a replay link from create_agent_run opens straight onto it.
import { apiFetch } from './api.js';
+import { buildRunReport } from '../packages/three-ws-cli/src/report/run-report.js';
import { emptyStateHTML, errorStateHTML, skeletonHTML } from './shared/state-kit.js';
const POLL_MS = 2500;
@@ -412,6 +413,7 @@ export function mountRunReplay(root, { agentId, agentName = 'This agent', initia
<div class="rr-actions">
${live && !run.cancelRequested ? '<button type="button" class="rr-btn rr-btn--danger" data-act="cancel">Cancel run</button>' : ''}
<button type="button" class="rr-btn" data-act="copy-link">Copy link</button>
+ <button type="button" class="rr-btn" data-act="download-report" title="One self-contained HTML file with the goal, tool calls, decisions, trades, outcome and decision-trail head">Download report</button>
</div>
</div>
<div class="rr-meters">
@@ -535,6 +537,40 @@ export function mountRunReplay(root, { agentId, agentName = 'This agent', initia
}
}
+ async function downloadReport(btn) {
+ const label = btn.textContent;
+ btn.disabled = true;
+ btn.textContent = 'Building report...';
+ try {
+ const { run, steps, toolTraces, receiptChain } = state.detail;
+ let trail = null;
+ try {
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/decision-trail/verify`);
+ if (res.ok) trail = await res.json();
+ } catch {
+ trail = null;
+ }
+ const html = buildRunReport({ run, steps, toolTraces: toolTraces || [], receiptChain, trail, origin: location.origin });
+ const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `run-${run.id}.html`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
+ btn.textContent = 'Report saved';
+ } catch (err) {
+ btn.textContent = 'Report failed, retry';
+ btn.title = err.message;
+ } finally {
+ btn.disabled = false;
+ setTimeout(() => {
+ if (btn.isConnected) btn.textContent = label;
+ }, 2200);
+ }
+ }
+
root.addEventListener('click', (e) => {
const item = e.target.closest('.rr-item');
if (item) return selectRun(item.dataset.run);
@@ -553,6 +589,7 @@ export function mountRunReplay(root, { agentId, agentName = 'This agent', initia
else renderNoSelection();
} else if (a === 'cancel') cancel(act);
else if (a === 'replay') toggleReplay(act);
+ else if (a === 'download-report') downloadReport(act);
else if (a === 'copy-link') {
const url = new URL(location.href);
url.searchParams.set('view', 'runs');