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
docs(packages): READMEs for agent-cli, agents-sdk, mcp-policy and signal-bridge, and a working signal-bridge entrypoint
nirholas265db744f90b
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 3ae74b7ac..f84ad8155 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -349,6 +349,8 @@ surface-map row already covers:| [workers/model-video2scene/](workers/model-video2scene) | Streaming video to 3D point-cloud reconstruction on Cloud Run GPU (LingBot-Map). Built and weights staged, not deployed as its own service yet, so `/capture` runs its designed unconfigured state until `GCP_VIDEO2SCENE_URL` is set || [workers/texture/](workers/texture) | Text-guided texturing + magic-brush region retexture GPU server || [workers/pump-fun-mcp/](workers/pump-fun-mcp) | Cloudflare Workers mirror of the canonical pump.fun MCP server |+| [workers/agent-gateway/](workers/agent-gateway) | Chat gateway worker: drains `gateway_inbox` (filled by the webhook receivers in [api/gateway/](api/gateway)) through `handleEvent` in [api/_lib/gateway/core.js](api/_lib/gateway/core.js) and delivers replies, approval previews and notifications back to the chat. Not deployed |+| [workers/signal-bridge/](workers/signal-bridge) | Signal leg of the chat gateway: the signal-cli REST bridge with its registration snapshotted to a Cloud Storage bucket so it survives redeploys. Single instance by design. Builds and runs locally, not deployed || [services/agent-screen-caster/](services/agent-screen-caster) | Self-hosted Playwright caster: an agent owner runs it on their own host with their agent id + key, and it streams the browser it drives into the agent-screen feed. No managed instance exists (the platform's own casting runs in `workers/agent-screen-pool` and `workers/agent-screen-worker`). Tests: [tests/agent-screen-caster.test.js](tests/agent-screen-caster.test.js) || [services/fleet-console/](services/fleet-console) | Health console for an open-source fleet: enumerates a GitHub owner's repositories, probes every deployment URL and npm package they advertise, and scores what each one actually delivers. Ships an HTTP dashboard, a CLI (`scan --attention` exits 1 when anything is broken, so cron can gate on it) and an MCP server over the same snapshot. Not deployed and not meant to be: it runs from a terminal, a cron job, or beside an agent. Tests: [tests/fleet-console.test.js](tests/fleet-console.test.js), [tests/fleet-console-server.test.js](tests/fleet-console-server.test.js) || [services/pump-graduations/](services/pump-graduations) | Standalone watcher for pump.fun bonding-curve graduations |@@ -500,6 +502,9 @@ array. Runbook: [docs/contributing.md](docs/contributing.md#publishing-packages-| `@three-ws/render` | [packages/render/](packages/render) | [api/_lib/render-cpu.js](api/_lib/render-cpu.js) | The renderer behind every server-side avatar picture on three.ws: a pure-JavaScript software rasterizer that turns a rigged, animated GLB into PNG, animated PNG or truecolor terminal output with no GPU, no WebGL and no headless browser. It replaced a headless-chromium pipeline that cost a 300 MB browser launch and 3 to 15 seconds per cold render, which is what made social-card and batch rendering fit inside a serverless budget at all. Sibling of [packages/tty-3d/](packages/tty-3d), which owns the terminal-only path. Tests: [packages/render/tests/](packages/render/tests) || `@three-ws/avatar-stream` | [packages/avatar-stream/](packages/avatar-stream) | [api/avatar-stream.js](api/avatar-stream.js), [src/stream-demo.js](src/stream-demo.js), [pages/stream.html](pages/stream.html) `→ /stream` | Progressive 3D over plain HTTP. Packs a GLB into a layered A3S stream whose first 50 KB is already a complete, skinned, spec-valid avatar, then refines it in place with byte-range requests, so a viewer on a slow connection gets something posable immediately instead of a spinner until the last byte. No custom server, no WebSocket, no new codec: range requests are the whole transport. Tests: [packages/avatar-stream/test/](packages/avatar-stream/test) || `@three-ws/brownout` | [packages/brownout/](packages/brownout) | [docs/brownout.md](docs/brownout.md) | Data-provenance headers plus request-scoped fault injection: a response says which upstream its data came from and how fresh it is, and a caller can break those upstreams on purpose to prove the integration degrades the way its contract claims. The companion to the resilience audit above, which grades call sites statically; this proves the behaviour at runtime. Tests: [packages/brownout/test/](packages/brownout/test) |+| `@three-ws/agents` | [packages/agents-sdk/](packages/agents-sdk) | `/api/v1`, route logic in [api/_lib/agents-v1/](api/_lib/agents-v1) | Typed TypeScript client for the v1 Agents API (agents, chat, runs with SSE streaming, skills, automations, wallet, swap) with retries, idempotency keys, typed errors and a client-side confirm gate on fund-moving calls. tsup build, zero runtime dependencies. Not published yet, and most routes it calls are not mounted under `/api/v1` yet; its README lists which answer |+| `@three-ws/mcp-policy` | [packages/mcp-policy/](packages/mcp-policy) | [api/_mcp/policy.js](api/_mcp/policy.js), [api/mcp-policy.js](api/mcp-policy.js) | The tool policy table every MCP server enforces: each tool's group and tier, financial tools off by default and gated on a named confirm flag plus a fresh preview id. `./stdio` wires a stdio server in one call. Workspace package, not published yet |+| `@three-ws/agent` | [packages/agent-cli/](packages/agent-cli) | `@three-ws/agent-runtime`, `/api/mcp-agent`, `/api/mcp`, `/api/v1` | Local agent runtime: the agent loop on your own machine with workspace file tools, a resource-limited shell sandbox, the three.ws MCP tools, per-class approvals (financial always asks) and SQLite sessions with full-text search. The runtime core is in tree; the `three-ws-agent` CLI and TUI entry points it declares are not yet |## Where things actually livediff --git a/packages/agent-cli/README.md b/packages/agent-cli/README.mdnew file mode 100644index 000000000..dff4221ef--- /dev/null+++ b/packages/agent-cli/README.md@@ -0,0 +1,270 @@+# @three-ws/agent++**Run a three.ws agent on your own machine: the platform's tools and wallet over MCP, your files and shell in a sandbox, every risky call behind an approval gate.**++This package is the local runtime behind `three-ws-agent`. It runs the same+agent loop the server uses ([@three-ws/agent-runtime](../agent-runtime)) on this+machine, with tools from two places:++- **local**: read, list, write and edit files inside the workspace, run shell+ commands in a resource-limited sandbox, fetch public web pages as Markdown;+- **remote**: every tool on the three.ws MCP servers (`/api/mcp-agent` and+ `/api/mcp` by default), mounted over Streamable HTTP with your account's key.++The model is either the metered three.ws endpoint (`<origin>/api/v1`, billed to+your account's credits) or any OpenAI-compatible base URL you point it at: a+local llama.cpp, Ollama or vLLM server, or a hosted lane with its own key.++## Status++The runtime core in `src/` is complete and runs today (see the example below).+The terminal UI and the `three-ws-agent` command that `package.json` declares+(`bin/three-ws-agent.js`, `src/index.js`, `src/cli.js`) and its `tests/`+directory are not in the tree yet, so the package is not publishable and is not+on npm. Until they land, use the modules by path from inside this repository, as+the example does. The design brief for the full CLI (slash commands, subagents,+natural-language cron, Telegram gateway mode) is+[docs/prompts/20-local-agent-runtime-tui.md](../../docs/prompts/20-local-agent-runtime-tui.md).++`src/loop.js` and `src/tools/registry.js` import `@three-ws/agent-runtime`,+which resolves through the monorepo workspace link; it is not yet listed in this+package's `dependencies`.++## Requirements++Node **22.13+**: the session store uses the built-in `node:sqlite`, so there is+no native addon to compile and the same install works on Linux, macOS, Windows,+WSL and Termux. Run `npm install` at the repo root first.++## Example++Save as `agent-check.mjs` at the repo root and run `node agent-check.mjs`. It+needs no account: it loads the config, builds the local toolset, reads the+workspace, proves the approval gate and the sandbox's credential scrubbing, and+indexes a session for full-text search.++```js+import { loadConfig } from './packages/agent-cli/src/config.js';+import { databasePath, systemEnv } from './packages/agent-cli/src/paths.js';+import { openStore } from './packages/agent-cli/src/store.js';+import { localTools } from './packages/agent-cli/src/tools/local.js';+import { createToolset } from './packages/agent-cli/src/tools/registry.js';+import { gateCall } from './packages/agent-cli/src/loop.js';++const env = systemEnv();+const config = loadConfig(env);+console.log('origin', config.origin, 'model', config.model.provider, config.model.model);+console.log('db would live at', databasePath(env));++const toolset = createToolset({ local: localTools({ root: process.cwd(), config }), maxTools: config.mcp.maxTools });+console.log('tools', toolset.all().map((t) => `${t.name}:${t.toolClass}`).join(' '));+// read_file:read list_dir:read write_file:write edit_file:write shell:shell web_fetch:network++console.log(await toolset.get('list_dir').run({ path: 'packages/agent-cli', depth: 2 }));++// Shell is an `ask` class by default, and with nobody at the keyboard the gate refuses it.+const shell = toolset.get('shell');+console.log(await gateCall({ tool: shell, args: { command: 'ls' }, approvals: config.approvals, approve: null }));++// Run directly, the sandbox strips credentials from the child's environment.+const out = await shell.run({ command: 'echo "token=$THREE_WS_API_KEY sandbox=$THREE_WS_SANDBOX"' });+console.log(out.exitCode, out.stdout.trim()); // 0 token= sandbox=1++const store = openStore(':memory:');+const session = store.createSession({ title: 'readme check' });+store.appendMessages(session.id, [+ { role: 'user', content: 'check the wallet balance' },+ { role: 'assistant', content: 'The agent wallet balance covers this run.' },+]);+console.log(store.search('wallet balance').map((r) => r.snippet)); // [ 'check the [wallet] [balance]' ]+```++### One full turn with a model and the three.ws MCP tools++This needs either a three.ws key with the `inference` scope (`THREE_WS_API_KEY`,+or a signed-in credential store), or your own OpenAI-compatible model via+`THREE_WS_AGENT_BASE_URL` and `THREE_WS_AGENT_MODEL`.++```js+import { loadConfig } from './packages/agent-cli/src/config.js';+import { resolveCredential } from './packages/agent-cli/src/credentials.js';+import { createModel } from './packages/agent-cli/src/model.js';+import { connectMcp } from './packages/agent-cli/src/mcp.js';+import { localTools } from './packages/agent-cli/src/tools/local.js';+import { createToolset } from './packages/agent-cli/src/tools/registry.js';+import { runTurn } from './packages/agent-cli/src/loop.js';++const config = loadConfig();+const credential = resolveCredential();+const model = createModel(config, credential);+const remote = await connectMcp({ origin: config.origin, servers: config.mcp.servers, token: credential?.token });+for (const s of remote.servers) console.log(s.server, s.error || `${s.toolCount} tools`);++const toolset = createToolset({ local: localTools({ root: process.cwd(), config }), remote, maxTools: config.mcp.maxTools });+const messages = [+ { role: 'system', content: 'You are a three.ws agent running on the owner\'s machine.' },+ { role: 'user', content: 'How many lines are in packages/agent-cli/src/paths.js?' },+];+const turn = await runTurn({+ model,+ toolset,+ messages,+ query: messages.at(-1).content,+ approvals: config.approvals,+ budget: config.budget,+ onContent: (delta) => process.stdout.write(delta),+ onEvent: (e) => e.kind === 'tool_end' && console.error(`\n[${e.name} ${e.ms}ms]`),+});+console.log('\n', turn.usage, turn.toolsUsed, `$${turn.billedUsd}`);+await remote.close();+```++With no `approve` callback, any `ask`-class call (writes, shell, financial) is+refused with a message the model reads and routes around. A UI passes+`approve: async ({ tool, args }) => ({ ok: true })` after asking the person.++## How it works++### The loop ([src/loop.js](src/loop.js))++`runTurn` drives `AgentRuntime` from `@three-ws/agent-runtime`:++1. Call the model with this turn's tool list, streaming text through `onContent`.+2. Every planned tool call passes the runtime's `GuardChain` (with `TradeGuard`),+ then the approval gate for its class.+3. Allowed calls run concurrently; refused ones return an error result the+ model can read.+4. Repeat until the model answers, the turn's tool rounds (`budget.maxToolRounds`)+ are spent (the model is then asked to answer with no tools), the step budget+ (`budget.maxSteps`) ends it, or the `signal` aborts it (`InterruptedError`).++Tool output is capped at 24,000 characters per result. State is plain JSON: a+session's transcript is exactly `messages`.++### Approvals++Each tool belongs to one class, and `agent.json` sets a mode per class:++| Class | Default | Tools |+|---|---|---|+| `read` | `allow` | `read_file`, `list_dir`, MCP tools with policy tier `read` or `readOnlyHint` |+| `write` | `ask` | `write_file`, `edit_file`, MCP tools with tier `write` or no hint |+| `shell` | `ask` | `shell` |+| `network` | `allow` | `web_fetch` |+| `financial` | `ask` | MCP tools with tier `financial` or `destructiveHint` |++Modes are `ask`, `allow` and `deny`. **`financial` can never be `allow`**: a+config that says so is read as `ask`, so no tool that moves funds runs without a+person saying yes. Remote tools are classified from the+`_meta['three.ws/policy'].tier` block every three.ws MCP server stamps+([@three-ws/mcp-policy](../mcp-policy)).++### Tool selection ([src/tools/registry.js](src/tools/registry.js))++Local tools are always offered. The MCP servers expose far more tools than a+model should see at once, so each turn offers the top `mcp.maxTools` remote+tools by relevance to the request (the runtime's `ToolRelevanceScorer`), plus+every remote tool already used in the session. A name defined by two servers is+mounted once (first server in config order wins) and reported in+`remote.duplicates`. The platform's remote `web_fetch` supersedes the local one+when it is mounted.++### The sandbox ([src/tools/sandbox.js](src/tools/sandbox.js))++| Limit | How |+|---|---|+| Wall time | `sandbox.timeoutMs` (default 120 s, per-call up to 30 min); the whole process group is killed. |+| CPU time | `ulimit -t` (`sandbox.cpuSeconds`, default 60) on POSIX. |+| File size | `ulimit -f` (`sandbox.maxFileMb`, default 256) so a runaway write cannot fill the disk. |+| Output | stdout and stderr each capped at `sandbox.maxOutputBytes` (default 200,000). |+| Environment | Any variable whose name contains KEY, TOKEN, SECRET, PASSWORD, CREDENTIAL, PRIVATE, MNEMONIC, SEED, COOKIE or SESSION is removed unless listed in `sandbox.passEnv`. `THREE_WS_SANDBOX=1` is set. |+| Paths | Every file tool resolves against the workspace root and refuses `..`, absolute paths elsewhere, and symlinks that point out. |++`web_fetch` refuses URLs that resolve to loopback, private, link-local or CGNAT+addresses unless `webFetch.allowPrivate` is `true`, and rechecks every redirect hop.++### Sessions ([src/store.js](src/store.js))++One SQLite file (WAL mode, so a UI, a scheduler and a gateway can share it)+holds sessions, their full transcripts exactly as the model saw them (tool calls+included, so a resumed session continues with full fidelity), an FTS5 index over+user and assistant text, subagent and cron runs with token usage and billed USD,+cron schedules (`local` or `server` mode, with an atomic claim so two processes+never run the same job), and a small key-value table. `exportSession(id)`+returns a portable `three-ws-agent-session` v1 JSON document.++## Configuration++### Files++| What | Path | Override |+|---|---|---|+| Settings | `~/.config/three-ws/agent.json` | `THREE_WS_AGENT_CONFIG`, or `XDG_CONFIG_HOME` |+| Credentials | `~/.config/three-ws/credentials.json` (shared with the `three-ws` CLI) | `THREE_WS_CREDENTIALS` |+| Data (sessions DB) | `~/.local/share/three-ws/agent/agent.db`, `%LOCALAPPDATA%\three-ws\agent` on Windows | `THREE_WS_AGENT_HOME`, or `XDG_DATA_HOME` |++`agent.json` holds only what you changed; `loadConfig` deep-merges it over the+defaults. A minimal file that points the agent at a local Ollama server and+turns shell approvals off:++```json+{+ "model": { "provider": "openai", "baseUrl": "http://localhost:11434/v1", "model": "llama3.1" },+ "approvals": { "shell": "allow" }+}+```++Defaults: origin `https://three.ws`; model provider `three-ws`, model+`three-ws/agent`, `maxTokens` 4096, `temperature` 0.3; MCP servers+`/api/mcp-agent` and `/api/mcp` with `maxTools` 24; budget 12 tool rounds and+40 steps per turn; subagents 8 rounds, 24 steps, 4 concurrent.++### Environment overrides++| Variable | Effect |+|---|---|+| `THREE_WS_ORIGIN` | API origin (staging, a local `npm run dev`). |+| `THREE_WS_AGENT_ID` | Agent id, sent as `x-three-agent` on model calls. |+| `THREE_WS_AGENT_BASE_URL` | Switches to provider `openai` at this base URL. |+| `THREE_WS_AGENT_MODEL` | Model id. |+| `THREE_WS_AGENT_API_KEY`, `OPENAI_API_KEY` | Key for provider `openai` (or name your own with `model.apiKeyEnv`). |+| `THREE_WS_API_KEY` | three.ws key; wins over the credential store. |++### Credentials ([src/credentials.js](src/credentials.js))++Resolution order: `THREE_WS_API_KEY`, then the store's `agent_key` slot, then+the `three-ws` CLI's `stdio_key`, then its `auth` (an API key, or an OAuth token+that has not expired). The agent keeps its own key in `agent_key`, so signing in+here never replaces the credential your MCP clients use, and one+`npx three-ws setup` is enough to start. Sign-in uses the device-link flow at+`<origin>/api/cli/link` and `/api/cli/token` (RFC 8628 polling) and asks for+`profile agents:read agents:write memory:read memory:write wallet:read inference`;+money-moving scopes are opt-in. Files are written atomically with mode `0600`.++## Module reference++| Module | Exports |+|---|---|+| `src/config.js` | `loadConfig`, `saveConfig(patch)`, `readConfigFile`, `deepMerge`, `enforceApprovalFloor`, `DEFAULTS`, `DEFAULT_ORIGIN`, `THREE_WS_MODEL`, `APPROVAL_MODES`, `TOOL_CLASSES` |+| `src/paths.js` | `systemEnv`, `configDir`, `configPath`, `credentialsPath`, `dataDir`, `databasePath` |+| `src/credentials.js` | `resolveCredential`, `hasScope`, `startDeviceLink`, `pollDeviceLink`, `saveAgentKey`, `clearAgentKey`, `readStoreFile`, `writeStoreFile`, `mask`, `DEFAULT_SCOPES` |+| `src/http.js` | `request`, `requestJson`, `errorOf`, `ApiError`, `VERSION`, `USER_AGENT` |+| `src/model.js` | `createModel(config, credential)` returning `{ target, label, round, listModels }`, `resolveModelTarget`, `readSse` |+| `src/mcp.js` | `connectMcp({ origin, servers, token })` returning `{ servers, tools, duplicates, call, close }`, `classifyMcpTool`, `flattenToolResult` |+| `src/loop.js` | `runTurn`, `gateCall`, `roundsThisTurn`, `serializeToolResult`, `InterruptedError`, `MAX_TOOL_OUTPUT_CHARS` |+| `src/store.js` | `openStore(file)` (sessions, messages, search, export, runs, crons, kv), `ftsQuery`, `newId` |+| `src/tools/local.js` | `localTools({ root, config, fetchImpl? })`, `resolveInWorkspace`, `htmlToText`, `WorkspaceError` |+| `src/tools/registry.js` | `createToolset({ local, remote, extra, maxTools })` returning `{ get, all, schemasFor, size }` |+| `src/tools/sandbox.js` | `runCommand(command, opts)`, `scrubEnv` |+| `src/tools/netguard.js` | `assertPublicUrl`, `isPrivateAddress` |++## Related++- [packages/agent-runtime](../agent-runtime): the loop, guards and tool scorer this runtime is built on.+- [packages/mcp-policy](../mcp-policy): the tool tiers the approval gate reads.+- [packages/three-ws-cli](../three-ws-cli) and [docs/cli.md](../../docs/cli.md): `npx three-ws setup` writes the shared credential store.+- [docs/mcp.md](../../docs/mcp.md): the MCP servers the agent mounts.++## License++Apache-2.0. See [LICENSE](LICENSE).diff --git a/packages/agents-sdk/README.md b/packages/agents-sdk/README.mdnew file mode 100644index 000000000..0c9bacccf--- /dev/null+++ b/packages/agents-sdk/README.md@@ -0,0 +1,295 @@+# @three-ws/agents++**The typed TypeScript client for the three.ws v1 Agents API.**++Construct a client with an API key, then create, start and chat with agents,+run goals, schedule automations, and move funds from Solana agent wallets, with+retries, timeouts, idempotency keys, typed errors and a client-side confirm gate+on every call that moves money.++```ts+import { ThreeAgents } from "@three-ws/agents";++const client = new ThreeAgents({ apiKey: process.env.THREE_WS_API_KEY! });+const agent = await client.createAgent({ name: "Momentum Alpha", strategy: "momentum" });+await client.startAgent(agent.id);+const reply = await client.sendMessage(agent.id, { message: "What is trending right now?" });+console.log(reply.content);+```++## Contents++- [Status](#status)+- [Install and build](#install-and-build)+- [Getting a key](#getting-a-key)+- [Runnable example](#runnable-example)+- [Configuration](#configuration)+- [Core concepts](#core-concepts)+- [API reference](#api-reference)+- [Errors](#errors)+- [Requirements](#requirements)++## Status++Read this before building on the package.++- **Not on npm yet.** `@three-ws/agents` returns 404 from the registry. Build it+ from this directory (below) and depend on the built `dist/`. Publishing is an+ owner-approved step: `npm run release` from this directory runs `npm publish+ --access public`, and `prepublishOnly` gates it on `typecheck`, `test` and `build`.+- **The client is complete; most server routes are not mounted yet.** On+ 2026-10-08 production answered these methods: `getModels()` (`GET /models`),+ `getFreeTierStatus()` (`GET /me/free-tier`), `startAgent()` and `stopAgent()`+ (`POST /agents/:id/start|stop`). Every other method calls a `/api/v1` path that+ production answers with `404 not_found` (or, under `/agents/:id/...`, with the+ on-chain card resolver's `400 invalid_caip`). The server-side logic for those+ routes exists in [api/_lib/agents-v1/](../../api/_lib/agents-v1) but has no+ route entry under `api/v1/` yet. The errors are typed, so a caller sees a+ `NotFoundError` or `ValidationError`, never a crash.+- `npm test` (`vitest run packages/agents-sdk/tests`) and `npm run examples`+ (`scripts/run-examples.mjs`) name directories that are not in the tree; use+ `npm run typecheck` and `npm run build` to verify a change.++## Install and build++From the repo root (`tsup` and `typescript` resolve from the root `node_modules`):++```bash+cd packages/agents-sdk+npx tsup # writes dist/index.js (ESM), dist/index.cjs (CJS) and .d.ts types+npx tsc --noEmit # type check+```++One entry, ESM and CJS, with declarations and source maps. The on-chain error+classes are imported from [solana-agent-sdk/src/errors.ts](../../solana-agent-sdk/src/errors.ts)+by relative path and inlined by tsup, so the built package has **zero runtime+dependencies**. It runs on Node 20+, Deno, Bun and browsers (anything with `fetch`).++## Getting a key++`apiKey` is a three.ws API key (`sk_live_...`). Create one with+`npx three-ws setup` ([docs/cli.md](../../docs/cli.md)) or on+[/dashboard/api](https://three.ws/dashboard/api). Model calls need a key with the+`inference` scope; agent writes need `agents:write`.++## Runnable example++This runs today against production. Save it as `example.mjs` in this directory+after building:++```js+import { ThreeAgents, ConfirmationRequiredError, VERSION } from "./dist/index.js";++const client = new ThreeAgents({ apiKey: process.env.THREE_WS_API_KEY ?? "sk_live_example" });+console.log(VERSION, client.baseUrl); // 0.1.0 https://three.ws/api/v1++// Free-tier allowance and the models it covers.+console.log(await client.getFreeTierStatus());+// { limit: 20, used: 0, remaining: 20, reset_at: '...', anonymous: true, signed_in_limit: 100, models: [...] }++// The model catalog.+console.log(await client.getModels());++// Fund-moving calls are refused before any request unless confirm is literally true.+try {+ await client.transfer("agent-id", { quoteId: "q" });+} catch (err) {+ console.log(err instanceof ConfirmationRequiredError, err.confirmFlag, err.previewMethod); // true confirm transferQuote+}+```++```bash+node example.mjs+```++## Configuration++```ts+const client = new ThreeAgents({+ apiKey: process.env.THREE_WS_API_KEY!, // required+ baseUrl: "https://three.ws/api/v1", // default+ timeout: 30_000, // per attempt, ms+ retries: 2, // after the first attempt, on 5xx, network errors and timeouts+ retryDelay: 1_000, // retry n waits retryDelay * 2^n plus up to 20% jitter+ fetch: globalThis.fetch, // any fetch implementation+ headers: { "x-team": "research" }, // sent on every request+});+```++Every method takes `RequestOptions` as its last argument to override `timeout`+or `retries`, pass an `AbortSignal`, or supply your own `idempotencyKey`.++## Core concepts++**Agent lifecycle.** `createAgent` (optionally from a `strategy` preset:+`momentum`, `sniper`, `defi-yield`, `macro-hedge`, `monitor-exit`,+`conservative`) creates an agent; a preset fills the skills, persona and default+automations you leave out. An agent's status is `running` (its automations,+intents and runs may execute) or `stopped`. `startAgent` and `stopAgent` switch+between them without deleting anything; `deleteAgent` stops automations and+cancels open runs.++**Chat versus runs.** `sendMessage` is one turn and returns the reply with+usage, cost, tool calls and any transaction signatures. `createRun` hands the+agent a goal and lets the server-side tool loop work toward it inside a credit+budget, an on-chain budget and a step limit; follow it with `streamRun` (Server-Sent+Events, resumed from the last event id when the connection drops) or `getRunSteps`.++**Custodial versus non-custodial.** `swapQuote` with an `agentId` trades from the+agent's custodial wallet, and `swapExecute` then needs `confirm: true` and signs+server-side. Without `agentId` the quote is built for your own wallet and+`swapExecute` returns an unsigned base64 transaction for you to sign.++**Money needs a preview and a yes.** `transfer` and `setExternalWallet` throw+`ConfirmationRequiredError` before any request unless their `confirm` flag is+literally `true`. Call the preview method the error names (`transferQuote`,+`getWallet`) and show the result first.++**Idempotency.** Every non-GET request carries an `Idempotency-Key` that is+reused across retries, so a retried create, transfer or swap acts at most once.++**Pagination.** List methods return `Page<T>` (`data`, `hasMore`, `nextCursor`,+`requestId`). `client.paginate(fetchPage)` walks every page:++```ts+for await (const agent of client.paginate((cursor) => client.listAgents({ cursor }))) console.log(agent.name);+```++## API reference++Paths are relative to `baseUrl`. Live means production answered it on 2026-10-08.++### Agents++| Method | Route | Live |+|---|---|---|+| `createAgent(params)` | `POST /agents` | no |+| `getAgent(agentId)` | `GET /agents/:id` | no |+| `listAgents({ limit, cursor })` | `GET /agents` | no |+| `updateAgent(agentId, patch)` | `PATCH /agents/:id` | no |+| `startAgent(agentId)` | `POST /agents/:id/start` | yes |+| `stopAgent(agentId)` | `POST /agents/:id/stop` | yes |+| `deleteAgent(agentId)` | `DELETE /agents/:id` | no |++### Chat and runs++| Method | Route | Live |+|---|---|---|+| `sendMessage(agentId, { message, model?, temperature? })` | `POST /agents/:id/messages` | no |+| `getMessages(agentId, { limit, before })` | `GET /agents/:id/messages` | no |+| `createRun(agentId, { goal, budgetCreditsUsd?, budgetUsd?, maxSteps?, toolsAllowed?, schedule? })` | `POST /agents/:id/runs` | no |+| `listRuns(agentId, page)` | `GET /agents/:id/runs` | no |+| `getRun(runId)` | `GET /runs/:id` | no |+| `updateRun(runId, params)` | `PATCH /runs/:id` | no |+| `cancelRun(runId)` | `POST /runs/:id/cancel` | no |+| `getRunSteps(runId, page)` | `GET /runs/:id/steps` | no |+| `streamRun(runId)` | `GET /runs/:id/events` (SSE) | no |++### Skills++| Method | Route | Live |+|---|---|---|+| `listSkills()` | `GET /skills` | no |+| `listCommunitySkills({ q, tag, author, limit })` | `GET /skills/community` | no |+| `getCommunitySkill(slug)` | `GET /skills/community/:slug` | no |+| `listCustomSkills(agentId)`, `getCustomSkill(agentId, skillId)` | `GET /agents/:id/skills/custom[/:skillId]` | no |+| `createCustomSkill`, `updateCustomSkill`, `deleteCustomSkill` | `POST`, `PATCH`, `DELETE /agents/:id/skills/custom[/:skillId]` | no |+| `importCommunitySkill(agentId, slug, { enabled })` | `POST /agents/:id/skills/custom/import` | no |++### Automations++| Method | Route | Live |+|---|---|---|+| `createAutomation(params)` | `POST /automations` | no |+| `listAutomations(agentId, page)` | `GET /agents/:id/automations` | no |+| `deleteAutomation(automationId)` | `DELETE /automations/:id` | no |++### Intelligence++| Method | Route | Live |+|---|---|---|+| `getPrice(mint)` | `GET /intel/price` | no |+| `getTopMovers(params)` | `GET /intel/top-movers` | no |+| `getIndicators({ mint, indicators, interval })` | `GET /intel/indicators` | no |+| `getSignals(mint)` | `GET /intel/signals` | no |+| `getAnomalies()`, `getMacro()` | `GET /intel/anomalies`, `GET /intel/macro` | no |++### Catalog and account++| Method | Route | Live |+|---|---|---|+| `getModels()` | `GET /models` | yes |+| `getFreeTierStatus()` | `GET /me/free-tier` | yes |+| `getUsage()`, `getBudget()` | `GET /me/usage`, `GET /me/budget` | no |+| `getTransactions(page)` | `GET /me/transactions` | no |+| `listIntegrations()`, `saveIntegration(provider, params)`, `removeIntegration(provider)` | `/me/integrations[/:provider]` | no |+| `generateLinkCode(params)`, `redeemLinkCode({ code })` | `POST /me/link-code[/redeem]` | no |+| `setExternalWallet(agentId, { ..., confirm: true })` | `PUT /agents/:id/external-wallet` | no |++### Wallet and swap++| Method | Route | Live |+|---|---|---|+| `getWallet(agentId, { network })` | `GET /agents/:id/wallet` | no |+| `getWalletHistory(agentId, { limit, cursor, network, category })` | `GET /agents/:id/wallet/history` | no |+| `transferQuote(agentId, params)` | `POST /agents/:id/wallet/transfer/quote` | no |+| `transfer(agentId, { quoteId, confirm: true })` | `POST /agents/:id/wallet/transfer` | no |+| `swapQuote(params)` | `POST /swap/quote` | no |+| `swapExecute(params)` | `POST /swap/execute` | no |++Request and response types for every method are exported from the package+(`CreateAgentParams`, `MessageReply`, `Run`, `RunEvent`, `SwapQuote`, `Wallet`,+`Page<T>` and the rest, from [src/types.ts](src/types.ts)).++## Errors++Every HTTP failure is a subclass of `ThreeAgentsError` carrying `status`, the+stable `code`, the `requestId` (quote it to support), the envelope's `details`,+the `rateLimit` headers, `method` and `path`.++| Class | When |+|---|---|+| `AuthenticationError` | 401: key missing, malformed, revoked or expired. |+| `PermissionError` | 403: key lacks a scope (`scope` names it) or the resource is someone else's. |+| `NotFoundError` | 404. |+| `ValidationError` | 400/422, with per-field `fields`. Also thrown client-side for an empty id. |+| `RateLimitError` | 429, with `retryAfter` in seconds. |+| `InsufficientFundsError` | The wallet or credit balance cannot cover the call. |+| `ConfirmationRequiredError` | A fund-moving call without its confirm flag; names `confirmFlag` and `previewMethod`. |+| `ServerError` | 5xx after the retries are spent. |+| `TimeoutError` | An attempt exceeded `timeout` (`timeoutMs`). |+| `ConnectionError` | The request never got a response. |++On-chain failures reuse the classes from `@three-ws/solana-agent`:+`SolanaAgentError`, `SwapError`, `SimulationError`, `ConfirmationTimeoutError`,+`TransactionRejectedError`, `WalletNotConnectedError`, `WalletCapabilityError`,+`MissingTokenAccountError`.++```ts+import { RateLimitError, ThreeAgentsError } from "@three-ws/agents";++try {+ await client.getFreeTierStatus();+} catch (err) {+ if (err instanceof RateLimitError) console.log(`retry in ${err.retryAfter}s`);+ else if (err instanceof ThreeAgentsError) console.log(err.status, err.code, err.requestId);+ else throw err;+}+```++Also exported: `parseSse(stream)` (the SSE parser `streamRun` uses), `VERSION`,+`DEFAULT_BASE_URL`, and the `FetchLike` and `ResponseMeta` types.++## Requirements++Node 20+ (or any runtime with `fetch`, `AbortSignal` and `ReadableStream`).++## Related++- [docs/api-reference.md](../../docs/api-reference.md): the HTTP API.+- [solana-agent-sdk/](../../solana-agent-sdk): wallet and swap primitives, and the on-chain error classes.+- [packages/three-ws-cli](../three-ws-cli): `npx three-ws setup` mints the key.++## License++Apache-2.0. See [LICENSE](LICENSE).diff --git a/packages/mcp-policy/README.md b/packages/mcp-policy/README.mdnew file mode 100644index 000000000..d4bc6e0ca--- /dev/null+++ b/packages/mcp-policy/README.md@@ -0,0 +1,246 @@+# @three-ws/mcp-policy++**One tool policy for every three.ws MCP server: read-only by default, money behind a named confirm flag and a fresh preview.**++Every tool on every three.ws MCP server, hosted or stdio, is classified here by+**group** (what it is about) and **tier** (what it can do to the caller). A+session sees the read and write tiers by default. Financial tools, the ones that+move funds or cannot be undone, stay hidden until the person opts in, and even+then each call must carry a named confirm flag (`confirm_payment: true`,+`confirm_swap: true`, ...) plus a preview id issued by the matching preview tool+within the last ten minutes, bound to the same arguments.++The hosted servers (through [api/_mcp/policy.js](../../api/_mcp/policy.js)),+the [/api/mcp-policy](../../api/mcp-policy.js) allowlist builder, and the stdio+packages all read the same table, so a rule changes in one place.++## Install++The package is a workspace of this monorepo (`packages/mcp-policy`) and is not+on the npm registry yet. A root `npm install` links it, after which+`import '@three-ws/mcp-policy'` resolves from any file in the repo:++```bash+npm install+node -e "import('@three-ws/mcp-policy').then((p) => console.log(Object.keys(p.POLICY).length, 'servers'))"+```++Zero runtime dependencies. Node 20+. ESM only. Its `package.json` is already+set for a public release (`publishConfig.access: public`, `files: src, README.md,+LICENSE`), so publishing is `npm publish -w packages/mcp-policy`, an+owner-approved step.++## The model++### Tiers++| Tier | Meaning | Default |+|---|---|---|+| `read` | Changes nothing. | on |+| `write` | Changes account state, and a follow-up call can undo it. | on |+| `financial` | Moves funds or cannot be undone. | off; every call needs its confirm flag and a fresh preview id |++### Groups++`agents`, `chat`, `runs`, `skills`, `trading`, `orders`, `perps`, `lending`,+`predictions`, `launch`, `marketplace`, `cards`, `mail`, `x402`, `wallet`,+`billing`, `intelligence`, `integrations`, `account`, `allowlist`, `assets`,+`gateway`, `sandbox`, `utility`. Each has a label and a one-line summary in+`GROUPS` (exported), written for the person deciding whether to turn it on.++### Financial tools++A financial row names three things:++- **the confirm flag** the call must set to literally `true` (one of+ `CONFIRM_FLAGS`, e.g. `confirm_transfer`, `confirm_payment`, `confirm_run`);+- **the preview tool** that must run first (e.g. `inspect_endpoint` before+ `pay_and_call`);+- **the bound arguments** that must be identical between preview and call, so a+ quote for one destination can never authorize a payment to another.++The preview id is `quote_id` when the preview tool is a quote, `preview_id`+otherwise. It lives for `PREVIEW_TTL_MS` (10 minutes), belongs to the caller who+previewed, and is burned the moment the financial call it authorized succeeds.++A tool with **no** row in the table is treated as financial with no group: it is+hidden unless named explicitly, so an unclassified tool can never slip into a+default session.++### The spec grammar++One grammar is read from the `X-Three-Tools` header, the `tools` query+parameter, the `THREE_WS_TOOLS` env var of a stdio server, and the saved+settings. Tokens are comma- or space-separated and applied left to right:++| Token | Effect |+|---|---|+| `default` | read + write on, financial off (the implicit base) |+| `all` / `none` / `readonly` | every tier / nothing / only read |+| `financial`, `-write` | turn a tier on or off |+| `trading`, `-chat` | turn a whole group on (every tier) or off |+| `swap_execute`, `-forget` | turn one tool on or off |++Precedence is tool over group over tier: `-trading,swap_quote` hides the trading+group except `swap_quote`. A spec made only of plain tool names is an **exact+allow list**; to add a tool to the defaults instead, lead with a base:+`default,pay_and_call`.++Hosted servers resolve a session in this order, first present wins: the client's+`X-Three-Allowed-Tools` list, `X-Three-Tools`, the `tools` query parameter, the+per-key setting layered over the account setting, then the default. A stdio+process resolves `THREE_WS_ALLOWED_TOOLS`, then `THREE_WS_TOOLS`, then the+selection `npx three-ws tools` saved under `tools["three-ws-<name>"]` in+`~/.config/three-ws/credentials.json`, then the default.++## Quick start++The full preview, confirm, burn cycle against the real `x402-mcp` table:++```js+import { createPolicy, enablementFromSpec, describeEnablement } from '@three-ws/mcp-policy';++const policy = createPolicy({ serverId: 'x402-mcp' });+const en = enablementFromSpec('default,x402', 'example'); // the whole x402 group, financial tier included+console.log(describeEnablement(en));++const call = { url: 'https://three.ws/api/x402/example', method: 'GET' };++// 1. A financial call with no confirm flag is refused with a tool result the model can read.+const refused = await policy.beforeCall({ name: 'pay_and_call', args: call, en, principal: 'me' });+console.log(refused.ok, refused.result.structuredContent.reason); // false confirmation_required++// 2. The preview tool runs; afterCall stamps a preview id onto its result.+const preview = await policy.afterCall({+ name: 'inspect_endpoint',+ args: call,+ principal: 'me',+ result: { content: [{ type: 'text', text: 'price: $0.01 per call' }] },+});+const previewId = preview._meta['three.ws/preview'].preview_id;++// 3. The confirmed call with the fresh preview id passes, policy-only arguments stripped.+const gate = await policy.beforeCall({+ name: 'pay_and_call',+ args: { ...call, preview_id: previewId, confirm_payment: true },+ en,+ principal: 'me',+});+console.log(gate.ok, gate.args); // true { url: ..., method: 'GET' }++// 4. After it succeeds the preview id is burned, so it can never authorize a second payment.+await policy.afterCall({ name: 'pay_and_call', args: call, principal: 'me', result: { content: [] }, preview: gate.preview });+const replay = await policy.beforeCall({ name: 'pay_and_call', args: { ...call, preview_id: previewId, confirm_payment: true }, en, principal: 'me' });+console.log(replay.ok, replay.result.structuredContent.reason); // false preview_unknown+```++Refusals are MCP tool results with `isError: true` and a `structuredContent`+reason (`tool_disabled`, `confirmation_required`, `preview_required`,+`preview_unknown`, `preview_stale`, `preview_mismatch`), never JSON-RPC errors:+a model reads a tool result and acts on it, while most clients show a protocol+error only to the person.++## Wiring a stdio server++### High-level `McpServer`++Call `applyPolicy` before the `registerTool` loop. It wraps `registerTool`, so a+disabled tool is never registered (calling it anyway explains how to turn it+on), a financial tool gains its confirm flag and preview-id arguments in its zod+schema, and a preview tool stamps a preview id onto its result.++```js+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';+import { z } from 'zod';+import { applyPolicy } from '@three-ws/mcp-policy/stdio';++const server = new McpServer({ name: 'x402-mcp', version: '1.0.0' });+const { enablement, hidden } = applyPolicy(server, { serverId: 'x402-mcp', z });++server.registerTool(+ 'inspect_endpoint',+ { description: 'Price an x402 endpoint without paying.', inputSchema: { url: z.string().url(), method: z.string().default('GET') } },+ async ({ url, method }) => ({ content: [{ type: 'text', text: `${method} ${url}: $0.01 per call` }] }),+);+server.registerTool(+ 'pay_and_call',+ { description: 'Pay an x402 endpoint and return its response.', inputSchema: { url: z.string().url(), method: z.string().default('GET') } },+ async ({ url }) => ({ content: [{ type: 'text', text: `paid ${url}` }] }),+);++console.error(`policy source: ${enablement.source}; hidden: ${[...hidden].join(', ') || 'none'}`);+if (process.argv.includes('--serve')) await server.connect(new StdioServerTransport());+```++Run it bare and it prints `policy source: default; hidden: pay_and_call`. Run it+with `THREE_WS_TOOLS=default,x402` and it prints `policy source: env; hidden: none`.+Pass the package's own `z` so the added arguments match its zod version.++### Low-level `Server` with JSON-Schema tools++```js+import { createStdioPolicy } from '@three-ws/mcp-policy/stdio';++const gate = createStdioPolicy('x402-mcp');+// ListTools handler: return { tools: gate.listTools(TOOLS) };+// CallTool handler: return gate.callTool(name, args, (cleanArgs) => runTool(name, cleanArgs));+```++`listTools` drops disabled tools, appends the financial rule to each financial+tool's description, adds the confirm and preview arguments to its schema, and+stamps `_meta['three.ws/policy']` (group, tier, confirm flag, preview tool,+preview argument) on every tool.++## API++### `@three-ws/mcp-policy`++| Export | What it is |+|---|---|+| `GROUPS`, `GROUP_IDS` | Every group `{ id, label, summary }`, in settings-page order, and just the ids. |+| `TIERS`, `DEFAULT_TIERS` | `['read', 'write', 'financial']` and the tiers a fresh key sees (`['read', 'write']`). |+| `CONFIRM_FLAGS`, `PREVIEW_ARGS`, `PREVIEW_TTL_MS` | The confirm flag vocabulary, `['quote_id', 'preview_id']`, and the 10-minute preview lifetime. |+| `POLICY` | The table: `{ [serverId]: { [toolName]: { group, tier, confirmFlag?, previewTool?, bind?, ownsPreview? } } }`. The single source of truth. |+| `SERVERS` | Human names, endpoints and transport (`remote` or `stdio`) for every server id in `POLICY`. |+| `createPolicy({ serverId, table?, store?, settingsUrl?, now? })` | The runtime for one server: `listTools(tools, en)`, `beforeCall({ name, args, en, principal, ownArgs })`, `afterCall({ name, args, principal, result, preview })`, `enabled(name, en)`, `entry(name)`, `disabledResult`, `policyMeta`, `financialNote`. Throws when `serverId` has no table. |+| `createMemoryPreviewStore()` | An in-process `{ put, get, del }` preview store, right for a single stdio process. The hosted servers pass a Redis-backed store instead so a quote issued on one instance is honored on another. |+| `normalizeEntry(name, row)` | Expand a terse table row into the shape every consumer reads. |+| `parseSpec(spec)` | Spec string or array to `{ tokens, invalid }`; a typo lands in `invalid` instead of being silently dropped. |+| `enablementFromSpec(spec, source)` | A spec to an enablement, honoring the exact-allow-list rule. |+| `enablementFromTokens(tokens, source)`, `defaultEnablement()`, `allowListEnablement(names, source?)` | Build an enablement directly. |+| `settingsToTokens(settings)` | Saved `{ groups: { id: bool }, tools: { name: bool } }` settings to tokens; unknown groups are dropped. |+| `resolveEnablement({ allowedTools, headerSpec, querySpec, keySettings, accountSettings })` | The hosted resolution order above, in one call. |+| `enablementFromSelection(sel, source?)`, `selectionToTokens(sel)`, `specFromSelection(sel)` | Convert a `three-ws tools` selection (`{ tiers, allow, deny }`) to an enablement, tokens, or an `X-Three-Tools` spec. |+| `isToolEnabled(name, entry, en)` | Is this tool on for the session. |+| `describeEnablement(en)` | A compact, serializable view for logs and the settings API. |+| `SETTINGS_URL`, `CLI_COMMAND` | `https://three.ws/settings/mcp-tools` and `npx three-ws tools`, quoted in every refusal. |++### `@three-ws/mcp-policy/stdio`++| Export | What it is |+|---|---|+| `applyPolicy(server, { serverId, z, env?, enablement?, store? })` | Put the policy in front of every tool an `McpServer` registers from now on. Returns `{ policy, enablement, hidden }`. |+| `createStdioPolicy(serverId, { env?, enablement?, store? })` | The same policy for a low-level `Server`: `{ policy, enablement, listTools(tools), callTool(name, args, run, ownArgs?) }`. |+| `resolveStdioEnablement(serverId, env?)` | The stdio resolution order above. |+| `cliSlug(serverId)` | The CLI's config key for a package: `x402-mcp` becomes `three-ws-x402`. |++## Adding a tool++Add a row for it under its server in [src/table.js](src/table.js) with the row+helpers at the top of the file: `r(group)`, `w(group)`,+`f(group, flag, previewTool, bind)`, or `own(group, flag, previewTool)` for a+tool that verifies its own preview id. A financial tool must name the preview+tool a person sees before it runs. The audit that checks each tool's annotations+against its handler is `npm run audit:mcp-safety`+([docs/mcp-safety.md](../../docs/mcp-safety.md)).++## Related++- [docs/mcp.md](../../docs/mcp.md): every three.ws MCP server.+- [/mcp-tools](https://three.ws/mcp-tools): the searchable tool index and the allowlist builder.+- [packages/three-ws-cli](../three-ws-cli): `npx three-ws tools` writes the stdio selection this package reads.++## License++Apache-2.0. See [LICENSE](LICENSE).diff --git a/packages/mcp/LICENSE b/packages/mcp/LICENSEdeleted file mode 100644index b5ae2a4e1..000000000--- a/packages/mcp/LICENSE+++ /dev/null@@ -1,201 +0,0 @@- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright 2026 nirholas-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.diff --git a/workers/signal-bridge/README.md b/workers/signal-bridge/README.mdnew file mode 100644index 000000000..ae10ff488--- /dev/null+++ b/workers/signal-bridge/README.md@@ -0,0 +1,149 @@+# signal-bridge++The Signal leg of the three.ws agent chat gateway: a Cloud Run service that+holds one registered Signal number and exposes it over HTTP so the gateway can+send and receive Signal messages for agent owners.++It is a thin layer over the maintained+[signal-cli REST bridge](https://github.com/bbernhard/signal-cli-rest-api)+(`bbernhard/signal-cli-rest-api:0.100`). The upstream image does the hard part:+signal-cli, the REST surface, and the live receive websocket. This layer adds+the one thing Cloud Run lacks, **persistence**: a Signal registration is a set of+identity keys and ratchet state on disk, Cloud Run disks are in-memory, and+losing them means re-verifying the number. `persist.sh` restores that state from+a mounted Cloud Storage bucket on boot and snapshots it back on a timer.++## How it fits++```+Signal user ──► signal-bridge (this service) ◄── agent gateway worker ──► api/_lib/gateway/core.js+ signal-cli + REST + receive WS (workers/agent-gateway) pairing, commands,+ state snapshot in GCS conversation, approvals+```++The gateway core is platform-neutral and already lists Signal as a platform+([api/_lib/gateway/platforms.js](../../api/_lib/gateway/platforms.js): no+buttons, no in-place edits, voice notes on). The process that connects this+bridge to the core is the gateway worker in [workers/agent-gateway](../agent-gateway).++## Files++| File | Role |+|---|---|+| `Dockerfile` | `FROM bbernhard/signal-cli-rest-api:0.100`, sets the bridge mode and state env, installs `persist.sh` as the entrypoint. |+| `persist.sh` | Restores `signal-cli.tgz` from the state volume, starts a background snapshot loop, then `exec`s the upstream `/entrypoint.sh`. |+| `cloudbuild.yaml` | Creates the Artifact Registry repo and the versioned state bucket if missing, builds, pushes, deploys to Cloud Run, and grants the runtime service account `run.invoker`. |++## Configuration++Set in the Dockerfile; override with `-e` locally or `--update-env-vars` on Cloud Run.++| Variable | Default | Meaning |+|---|---|---|+| `MODE` | `json-rpc` | Keeps one signal-cli process resident, so a send takes milliseconds instead of a JVM start, and serves the receive websocket. |+| `PORT` | `8080` | The REST port. |+| `JSON_RPC_TRUST_NEW_IDENTITIES` | `on-first-use` | Trust a contact's identity key the first time it is seen. |+| `JSON_RPC_IGNORE_STORIES`, `JSON_RPC_IGNORE_STICKERS` | `true` | Drop message types the gateway never handles. |+| `SIGNAL_STATE_DIR` | `/state` | Where the state volume is mounted. The snapshot is `$SIGNAL_STATE_DIR/signal-cli.tgz`. |+| `SIGNAL_SNAPSHOT_SECONDS` | `120` | Snapshot interval. A snapshot is written only when a file under the signal-cli config dir changed since the last one, so an idle bridge does not rewrite the object. |+| `SIGNAL_CLI_CONFIG_DIR` | `/home/.local/share/signal-cli` | Set by the upstream image: the tree that is snapshotted and restored. |++Snapshots are written to a temporary name and renamed, so a restart in the+middle of a write restores the previous complete tarball rather than a torn one.++## Run locally++From the repo root:++```bash+docker build -t signal-bridge workers/signal-bridge+mkdir -p .signal-state+docker run --rm -p 8080:8080 -v "$PWD/.signal-state:/state" signal-bridge+```++The first boot logs `no snapshot at /state/signal-cli.tgz, starting unregistered`.+Once the API is up:++```bash+curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/v1/health # 204+curl -s http://localhost:8080/v1/about # {"versions":["v1","v2"],...,"mode":"json-rpc","version":"0.100",...}+curl -s http://localhost:8080/v1/accounts # [] until a number is registered+```++Within one snapshot interval the log shows `snapshot written <time>`, and the+next container started on the same volume logs `restoring state from+/state/signal-cli.tgz`.++## Register the number++Do this once per number. The registration then lives in the state bucket and+survives every redeploy. These are the upstream bridge's endpoints+([full reference](https://bbernhard.github.io/signal-cli-rest-api/)); `+15551234567`+stands for the gateway's own number in E.164 form.++```bash+BRIDGE=http://localhost:8080++# Ask Signal for an SMS code. Signal usually requires a captcha token first:+# solve https://signalcaptchas.org/registration/generate.html and copy the+# signalcaptcha:// link it produces.+curl -X POST "$BRIDGE/v1/register/+15551234567" \+ -H 'content-type: application/json' \+ -d '{"use_voice": false, "captcha": "signalcaptcha://..."}'++# Confirm with the code that arrived by SMS.+curl -X POST "$BRIDGE/v1/register/+15551234567/verify/123456"++# Send a test message.+curl -X POST "$BRIDGE/v2/send" \+ -H 'content-type: application/json' \+ -d '{"number": "+15551234567", "recipients": ["+15557654321"], "message": "three.ws gateway online"}'+```++To use an existing phone's Signal account instead of a dedicated number, link+the bridge as a secondary device: open `$BRIDGE/v1/qrcodelink?device_name=three-ws-gateway`+in a browser and scan the QR code from Signal on the phone (Settings, Linked devices).++Inbound messages stream over the websocket at `ws://<bridge>/v1/receive/<number>`+in `json-rpc` mode; that is the socket a gateway Signal adapter consumes.++## Deploy++Production deploys are owner-gated (see CLAUDE.md). The command, from the repo root:++```bash+gcloud builds submit workers/signal-bridge --config workers/signal-bridge/cloudbuild.yaml \+ --region us-central1 --project aerial-vehicle-466722-p5 \+ --substitutions=SHORT_SHA=manual$(date +%s)+```++The build runs as `three-ws-build@`, the service runs as `three-ws@`, and the+deploy flags are load-bearing:++| Flag | Why |+|---|---|+| `--max-instances=1` | signal-cli owns one number's key material. Two instances would each advance the ratchets and corrupt the other's sessions. |+| `--min-instances=1`, `--no-cpu-throttling` | The gateway holds the receive websocket open; scale-to-zero would drop inbound messages. |+| `--no-allow-unauthenticated` | The upstream bridge has no auth of its own. Only the runtime service account (the gateway) may invoke it, with a Google ID token. |+| `--add-volume ... bucket=three-ws-signal-bridge-state` | The versioned bucket holds `signal-cli.tgz`, so a new revision restores the registration instead of needing the number verified again. |+| `--startup-probe=httpGet.path=/v1/health` | The JVM daemon takes a few seconds; traffic waits for it. |++To register the number against the deployed service, call the same endpoints+through an authenticated proxy:++```bash+gcloud run services proxy signal-bridge --region us-central1 --port 8080+# then use BRIDGE=http://localhost:8080 with the commands above+```++## Operations++- **Logs:** `gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="signal-bridge"' --freshness=1h`. Look for `restoring state from`, `snapshot written`, and `snapshot failed`.+- **Roll back the registration state:** the bucket has object versioning on, so an earlier `signal-cli.tgz` generation can be restored with `gcloud storage cp gs://three-ws-signal-bridge-state/signal-cli.tgz#<generation> gs://three-ws-signal-bridge-state/signal-cli.tgz` before restarting the service.+- **Upgrading the upstream image:** bump the `FROM` tag, then run it locally on a copy of the state tarball before deploying, since a signal-cli upgrade can migrate the on-disk format.++## Related++- [api/_lib/gateway/](../../api/_lib/gateway): the platform-neutral gateway core, inbox and pairing.+- [api/gateway/](../../api/gateway): the Telegram and Discord webhook receivers and the connections API.+- [workers/agent-gateway](../agent-gateway): the gateway worker.diff --git a/workers/signal-bridge/persist.sh b/workers/signal-bridge/persist.shindex 4119bcbbd..4f0b3a423 100755--- a/workers/signal-bridge/persist.sh+++ b/workers/signal-bridge/persist.sh@@ -1,6 +1,8 @@#!/bin/sh# Restore the signal-cli state tree from the mounted state volume, keep it-# snapshotted there, then hand PID 1 to the upstream s6 init.+# snapshotted there, then hand PID 1 to the upstream entrypoint+# (/entrypoint.sh in bbernhard/signal-cli-rest-api, which starts the json-rpc+# daemon under supervisor and execs the REST API as the signal-api user).## The snapshot is written to a temp name and renamed, so a restart mid-write# restores the previous complete tarball rather than a torn one. The loop only@@ -43,4 +45,4 @@ snapshot() {done) &-exec /init+exec /entrypoint.sh