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(prompts): sixteen self-contained build briefs closing the agent-platform gaps, with a dependency-ordered index
qhqfb09aaa9b9ef0
diff --git a/docs/prompts/01-cli-setup-login.md b/docs/prompts/01-cli-setup-login.mdnew file mode 100644index 000000000..8c71c15bf--- /dev/null+++ b/docs/prompts/01-cli-setup-login.md@@ -0,0 +1,53 @@+# 01. One-command CLI: `npx three-ws setup`, `login`, `status`, `tools`++Read `docs/prompts/README.md` first.++## The problem++A developer who wants a model to use three.ws today has to read `docs/mcp.md`, pick one of seven hosted MCP servers, mint a key on the site or run the OAuth flow by hand, and paste a JSON block into their client config. There is no `login`, `setup` or `init` command anywhere under `packages/*` (grep `packages/*/src/cli.js`). The only one-command flow is `npm create @three-ws/agent`, which scaffolds a 3D agent and never touches auth or MCP.++The bar: one command that authenticates, wires every relevant MCP server into whatever client the developer uses, verifies with a real tool call, and prints what is now available.++## Build++A new package `packages/three-ws-cli/` published as `three-ws` (bin `three-ws`, so `npx three-ws <cmd>` works with no install) and also exposed as `@three-ws/cli`. Node 20+, ESM, no framework heavier than `commander` and `@clack/prompts` (check `package.json` first; reuse what is installed).++### Subcommands++- `three-ws setup`: interactive. Detects installed clients (Claude Code `.mcp.json` and `~/.claude.json`, Claude Desktop config, Cursor `~/.cursor/mcp.json`, Windsurf, VS Code `mcp.json`, Codex, Gemini CLI, Hermes-style `~/.hermes/config.yaml`, and a generic "print JSON" fallback). Offers two auth modes: **remote OAuth** (opens the browser to the existing OAuth 2.1 authorization endpoint under `api/oauth/[action].js`, uses PKCE, receives the code on a loopback port, stores the token) and **API key** (prompts for a key from `/settings/api-keys`, or mints one through `api/api-keys.js` after a browser login, with the scopes the user picks). Writes the MCP entries for the servers the user selects (default: `/api/mcp`, `/api/mcp-agent`, `/api/mcp-3d`; `/api/mcp-studio` and `/api/pump-fun-mcp` need no auth and are always offered). Offers the stdio path too: `npx -y @three-ws/x402-mcp` and the other `@three-ws/*-mcp` packages under `packages/`, with the key written to the client env block. Ends with a real `tools/list` call against each configured server and prints the count per server.+- `three-ws login`: re-authenticate only (OAuth or key), refresh a stored token, or switch accounts.+- `three-ws logout`: remove stored credentials.+- `three-ws status`: which servers are configured in which clients, auth state, token expiry, account email, wallet address and balance from `api/agents/solana-wallet.js`, current plan from `api/usage/summary.js`.+- `three-ws tools`: interactive picker to enable or disable tool groups per server (read-only groups on by default, financial groups off; the policy and group names come from prompt 03). Writes the selection into the client config as the server's allowed-tools list where the client supports it, otherwise into the three-ws credential store so the server can enforce it via a header.+- `three-ws mcp list | add <server> | remove <server>`: non-interactive equivalents for scripts and CI.+- `three-ws whoami`, `three-ws version`, `three-ws --json` on every command.++### Credential store++`~/.config/three-ws/credentials.json` with mode 0600, plus keychain on macOS through `keytar` if it is already a dependency somewhere in the repo, otherwise the file only. Token refresh is automatic. Never print a key or token after it is stored; print the last four characters.++### Install paths++- `npx three-ws setup` with nothing installed.+- `curl -fsSL https://three.ws/install.sh | bash` and the PowerShell twin, served from `public/install.sh` and `public/install.ps1`, which install Node if missing (via the platform's package manager, never a custom binary) and run the same setup. Add both to `data/pages.json` if they get a page, and to `docs/mcp.md`.+- Every hosted MCP server's 401 body and the `/.well-known/mcp.json` directory must mention `npx three-ws setup` as the fix.++### Server-side work this needs++- The OAuth authorization server must accept the loopback redirect URIs the CLI registers through dynamic client registration. Verify against `api/oauth/[action].js` and `.well-known/`.+- An `api/api-keys.js` action that mints a key from a short-lived browser session started by the CLI (device-style link code: CLI prints a URL plus code, the site page `/cli/authorize` confirms it, the CLI polls). Build the page with every state designed.++## Docs and wiring++- `docs/cli.md` (new): every subcommand, every flag, the credential store location, and a two-minute quick start. Link it from `docs/start-here.md` and from `docs/mcp.md` at the top, replacing the hand-paste instructions as the primary path (keep the JSON as the manual alternative).+- `.agents/skills/connect-three-ws-mcp/SKILL.md`: lead with `npx three-ws setup`.+- README for the package under `packages/three-ws-cli/README.md`.+- `STRUCTURE.md` row, `data/changelog.json` entry tagged `feature, sdk`.++## Acceptance++- On a clean machine: `npx three-ws setup`, choose OAuth, finish in the browser, and the command ends with a live tool count from at least three servers.+- Same with an API key.+- Claude Code, Claude Desktop and Cursor each show three.ws tools after setup with no manual editing.+- `three-ws status` shows the wallet balance that `/agents/wallet` shows in the browser.+- Tests under `packages/three-ws-cli/tests/` cover config detection and writing for every client format, token refresh, and the picker's config output; `npm test` green.diff --git a/docs/prompts/02-mcp-resources-prompts.md b/docs/prompts/02-mcp-resources-prompts.mdnew file mode 100644index 000000000..ba33a1048--- /dev/null+++ b/docs/prompts/02-mcp-resources-prompts.md@@ -0,0 +1,52 @@+# 02. MCP resources and guided prompts on every hosted server++Read `docs/prompts/README.md` first.++## The problem++Our hosted MCP servers expose tools only. `api/_mcp/dispatch.js` (around line 103) answers `resources/list` and `prompts/list` with empty arrays, and only `api/_mcp-studio/dispatch.js` implements one real resource. A client that renders resources (Claude Desktop, Cursor, most agent frameworks) therefore shows nothing to read, and a model has no guided workflows to follow. The best agent platforms ship live read-only views under a URI scheme and a short catalog of prompt flows that walk a user from zero to a first result.++## Build++### Resources (`three://` scheme)++Implement `resources/list`, `resources/read`, `resources/templates/list` and `resources/subscribe` (with `notifications/resources/updated` over the existing Streamable HTTP session) in a shared module `api/_mcp/resources.js` used by `/api/mcp`, `/api/mcp-agent`, `/api/mcp-3d` and `/api/mcp-bazaar`. Each resource is JSON with `mimeType: application/json`, plus a `text/markdown` rendering when the client asks for it.++Required resources, all backed by the real routes named:++- `three://me`: account, plan, scopes of the current key or token, rate-limit state (`api/usage/summary.js`, `api/api-keys.js`).+- `three://agents` and `three://agents/{agentId}`: the caller's agents (`api/marketplace/[action].js` `mine`, agent detail route).+- `three://agents/{agentId}/wallet`: address, SOL and token balances, spend limits, allowlist, freeze state (`api/agents/solana-wallet.js`, `api/_lib/agent-trade-guards.js`, `api/agents/solana-guard.js`).+- `three://agents/{agentId}/usage`: credits, monthly LLM calls and tokens per model, MCP tool calls (`api/usage/summary.js`, `api/credits/`).+- `three://agents/{agentId}/chat`: recent chat history (`api/brain/chat.js` storage).+- `three://agents/{agentId}/runs` and `three://agents/{agentId}/runs/{runId}`: autonomous runs and steps (prompt 05 defines the routes; if it has not landed, back these with `api/agent/activity.js` and extend when it does).+- `three://agents/{agentId}/orders`, `.../dca`, `.../intents`: open orders (`api/agents/orders.js`), DCA strategies (`api/dca-strategies.js`), wallet intents (`api/_lib/wallet-intents.js`).+- `three://marketplace`: skill listings with prices and trial state (`api/marketplace/`).+- `three://models`: the model catalog with pricing (`api/_lib/chat-models.js`, `api/_lib/llm-pricing.js`).+- `three://wallets`: summary across all the caller's agent wallets.+- `three://launches`: the caller's token launches (`api/pump/[action].js`, `pump_agent_mints`).+- `three://x402/services`: the bazaar catalog (`api/_mcpbazaar/tools.js`).+- `three://assets/{id}` on `/api/mcp-3d`: asset metadata and GLB URL.++Each resource also has an equivalent tool so clients without a resource reader can get the same data. State that mapping in the resource description.++### Prompts++Implement `prompts/list` and `prompts/get` in `api/_mcp/prompts.js`, shared the same way. Each prompt returns a message sequence that names the exact tools to call in order, the confirm flags from prompt 03, and what to show the user before executing. Required prompts, with arguments where noted:++`get-started`, `create-agent` (name, persona, model), `setup-wallet` (agentId), `trade` (agentId, token), `launch-token` (agentId, name, symbol), `hire-agent` (task), `sell-a-skill` (agentId), `review-costs` (agentId), `setup-automations` (agentId), `setup-dca` (agentId), `explore-marketplace`, `explore-x402` (capability), `earn-yield` (agentId), `perps` (agentId), `predictions` (agentId), `embed-avatar` (agentId), `generate-3d` (prompt).++Prompts that reference a surface from a later brief (perps, lending, predictions) must still be real: they point at the tools those briefs define, and until those land they say plainly that the venue is not yet enabled and list the read-only research tools that do exist.++### Directory and docs++- `/.well-known/mcp.json` and `server.json` list resources and prompts per server.+- `docs/mcp.md`: a "Resources" section and a "Guided prompts" section, one table each, with a worked `resources/read` example and a `prompts/get` example that actually run against production.+- `data/changelog.json` entry tagged `feature, sdk`.++## Acceptance++- Claude Desktop shows the `three://` resources in its attachment picker and reads them.+- `resources/subscribe` on `three://agents/{id}/wallet` produces an update notification after a real transfer.+- Every prompt renders and every tool it names exists on that server (a test enumerates prompts and checks the tool names against `tools/list`).+- Tests in `tests/mcp-resources.test.js` and `tests/mcp-prompts.test.js`; `npm test` green.diff --git a/docs/prompts/03-mcp-tool-policy-skill.md b/docs/prompts/03-mcp-tool-policy-skill.mdnew file mode 100644index 000000000..5784d4b07--- /dev/null+++ b/docs/prompts/03-mcp-tool-policy-skill.md@@ -0,0 +1,52 @@+# 03. MCP tool policy: read-only by default, opt-in financial groups, and one model-facing skill document++Read `docs/prompts/README.md` first.++## The problem++Our fund-moving safeguards are real but scattered: spend limits in `api/_lib/agent-trade-guards.js`, allowlists in `api/agent/guard.js`, confirm flags in `api/_mcp3d/tools/persona-identity.js` and `packages/x402-mcp/src/tools/pay-and-call.js`, payment sessions in `api/pay/`. There is no single policy that every tool registers under, no server-side default that hides financial tools until the user opts in, and no one document a model reads that lists every tool, its group, whether it moves funds, and which preview tool must precede it. The best platforms ship exactly that: a default set of read-mostly tools, explicit opt-in for the rest, a named confirm flag on every irreversible call, and a skill file that tells the model the rules.++## Build++### Tool policy module++`api/_mcp/policy.js`, imported by every hosted server dispatcher (`api/_mcp/dispatch.js`, `api/_mcpagent/`, `api/_mcp3d/`, `api/_mcpbazaar/`, `api/_mcp-studio/`, `api/pump-fun-mcp`, `api/_mcpibm/`) and by every stdio package under `packages/*-mcp`. Every tool definition gains:++- `group`: one of `agents, chat, runs, skills, trading, orders, perps, lending, predictions, launch, marketplace, cards, mail, x402, wallet, billing, intelligence, integrations, account, allowlist, assets, utility`.+- `tier`: `read` (default on), `write` (on by default, reversible), `financial` (off by default, moves funds or is irreversible).+- `confirmFlag`: for every `financial` tool, the exact boolean argument name (`confirm_swap`, `confirm_transfer`, `confirm_launch`, `confirm_spend`, `confirm_payment`, `confirm_deposit`, `confirm_withdraw`, `confirm_delete`, `confirm_bid`, `confirm_send`). The tool refuses without it, with an error that names the preview tool to call first.+- `previewTool`: the quote or preview tool that must run first; the server records the preview result id and the financial tool requires it (`quote_id` or `preview_id`), rejecting stale ones after ten minutes.++Enforcement: `tools/list` returns only enabled tools for the session. Enablement comes from, in order: the client's allowed-tools list when present, an `X-Three-Tools` header or `tools` query the CLI from prompt 01 sets, the per-key setting stored by `api/api-keys.js`, then the default (read plus write). A disabled tool called anyway returns an error that says how to enable it (`npx three-ws tools`, or the settings page).++Settings page: `/settings/mcp-tools` lists every group with its tier, a toggle per group, and per-key overrides. Every state designed. Add to `data/pages.json`.++### Audit the existing tools++Walk every tool in every server and package and assign group, tier, confirm flag and preview tool. Any financial tool without a preview tool gets one built in the same change. Any tool that moves funds without a confirm flag today is a bug; fix it. Report the full table in your final message.++### The model-facing skill++`.agents/skills/three-ws/SKILL.md` (and mirror it to `public/skills/three-ws/SKILL.md` and `skills-pack.json` through `scripts/build-skills-pack.mjs`): the one document a model reads to operate three.ws well. Structure:++1. What three.ws is, in two sentences, and that tools come from the hosted MCP servers installed with `npx three-ws setup` (prompt 01). If tools are missing, tell the user to run setup; never call the HTTP API directly.+2. Tool naming per client namespace.+3. How `agent_id` resolves: `list_agents` once, a default agent env or setting, ask when ambiguous.+4. A table of every group with its representative tools, generated from the policy module by a script (`scripts/build-mcp-skill.mjs`) so it cannot drift; the build fails if the doc and the policy differ.+5. The financial and irreversible section: every `financial` tool, its confirm flag, and the rule "quote or preview first, show it, wait for a clear yes, then execute; report the transaction signature". Generated from the policy too.+6. The resources and prompts from prompt 02, with the resource-to-tool mapping.+7. Common patterns: new user, trade, launch, hire, sell a skill, pay an x402 URL, fund an external wallet through the allowlist, check portfolio, run a DCA, review costs.+8. Deliverability and conduct rules for any outward-facing tool (mail from prompt 11, social posting): genuine content, no deceptive subjects, never fabricate urgency.++## Docs and wiring++- `docs/mcp.md`: a "Tool policy" section explaining tiers, defaults and how to enable groups, with the settings page linked.+- `docs/agent-skills.md`: register the new skill.+- `data/changelog.json` entry tagged `security, improvement`.++## Acceptance++- A fresh key sees no `financial` tools in `tools/list` on any server; enabling the `trading` group makes `swap_execute` appear.+- Calling `swap_execute` without `confirm_swap: true` or with a stale `quote_id` fails with an error that names `swap_quote`.+- `scripts/build-mcp-skill.mjs` reproduces `SKILL.md` byte for byte; a test asserts it.+- `tests/mcp-policy.test.js` covers every server's tool list against the policy (no tool without a group and tier); `npm test` green.diff --git a/docs/prompts/04-community-skills-registry.md b/docs/prompts/04-community-skills-registry.mdnew file mode 100644index 000000000..a55e0978d--- /dev/null+++ b/docs/prompts/04-community-skills-registry.md@@ -0,0 +1,43 @@+# 04. Public community skills registry with one-click import, plus prompt-only custom skills++Read `docs/prompts/README.md` first.++## The problem++We have two skill systems: 47 client-side skills under `.agents/skills/` indexed by `skills-pack.json`, and in-app runtime bundles (`manifest.json` plus `SKILL.md` plus `tools.json` plus `handlers.js`, documented in `docs/skills.md`) installed through `api/skills/[id]/install.js`. Neither is a public community registry: there is no repository outsiders can PR into, no contribution guide, `public/skills-index.json` is a six-entry demo list, and there is no lightweight tier for a skill that is nothing more than instructions. The best platforms let anyone contribute a markdown skill through a PR and let any user import it onto an agent in one click, where it becomes an editable custom skill.++## Build++### Prompt-only custom skills (runtime)++A new skill kind `prompt` alongside the existing bundle kind: a `SKILL.md` plus `metadata.json` (`name`, `description`, `author`, `tags`, `version`) and nothing else. Installing it on an agent injects the markdown into that agent's system prompt in a fixed section, ordered by install time, with a per-agent cap on total injected tokens surfaced in the UI. Routes on the agents API: `GET/POST /api/agents/:id/custom-skills`, `GET/PATCH/DELETE /api/agents/:id/custom-skills/:skillId`, plus `enabled` toggle. Migration under `api/_lib/migrations/` for `agent_custom_skills`. MCP tools `list_custom_skills`, `get_custom_skill`, `create_custom_skill`, `update_custom_skill`, `delete_custom_skill` (delete is `financial` tier per prompt 03 because it is irreversible, with `confirm_delete`), and `list_available_skills` for the catalog.++### The public registry++A new top-level directory `community-skills/` (mirrored to a public GitHub repository `nirholas/three-ws-skills`, created with `gh repo create`, MIT, and kept in sync by `scripts/sync-community-skills.mjs`; sync is push-gated per `CLAUDE.md`):++- `skills/<slug>/SKILL.md` and `metadata.json`, optional `references/` and `scripts/`.+- `registry.json` generated by `scripts/build-community-registry.mjs`, which validates every entry (slug is URL-safe and unique, metadata fields present, SKILL.md has a frontmatter name and description, no third-party token names in committed skills per the `$THREE` rule) and fails the build otherwise. Wire it into `npm run build:pages`.+- `CONTRIBUTING.md`: fork, add a directory, run the validator, open a PR, review criteria, license.+- `README.md`: what a skill is, the format, how to use one, the link to the live page.++Seed it with at least twelve real, useful skills written for our tools: token safety diligence (mint and freeze authority, LP lock, holder concentration; a `scripts/` helper against the public RPC), DEX pool discovery and OHLCV, whale movement tracking, meme token scoring, DCA planning, pre-trade risk management (position sizing, concentration, drawdown), alpha scanning from new launches and volume spikes, honest social posting from an agent's holdings, x402 service discovery and paid calls, hiring another agent, launching a token through the existing launch flow, and operating the three.ws MCP (the skill from prompt 03). Every script must run.++### One-click import in the product++- Page `/skills/community` (add to `data/pages.json`): browse the registry with search, tags, author, preview of the full SKILL.md, and "Import to agent" which creates a prompt-only custom skill on the chosen agent through the routes above. Every state designed, including "no agents yet" which links to agent creation.+- The existing skills page gains a "Community" section pointing there.+- `three-ws skills list | search | import <slug> --agent <id>` in the CLI from prompt 01.+- MCP tool `import_community_skill(slug, agent_id)`.++## Docs and wiring++- `docs/skills.md`: a "Prompt-only skills" section and a "Community registry" section, plus the import flow.+- `docs/agent-skills.md`: link both skill systems and explain when to use which.+- `STRUCTURE.md` rows for `community-skills/` and the page. `data/changelog.json` entry tagged `feature, docs`.++## Acceptance++- A PR adding a bad `metadata.json` to the registry fails the validator; a good one appears on `/skills/community` after `npm run build:pages`.+- Importing a skill onto an agent changes that agent's next chat response in a way the skill specifies (test with the risk-manager skill and a trade request).+- `npm test` green with tests for the validator, the custom-skills routes and the injection ordering and cap.diff --git a/docs/prompts/05-agents-rest-parity.md b/docs/prompts/05-agents-rest-parity.mdnew file mode 100644index 000000000..6bcfe7e5b--- /dev/null+++ b/docs/prompts/05-agents-rest-parity.md@@ -0,0 +1,59 @@+# 05. Agents REST parity: runs, lifecycle, model catalog, intelligence, integrations and link codes++Read `docs/prompts/README.md` first.++## The problem++The agent runtime exists (`api/agent/run.js` runs a server-side tool loop; `api/agent/activity.js` and `api/audit-log.js` log it) but runs are not first-class objects a developer can create, list, inspect step by step, update or cancel. Several capabilities a developer expects from an agents API are either scattered or missing: start and stop as explicit lifecycle states, a model catalog endpoint with prices, a free-tier status endpoint, technical indicators and top movers as JSON, integrations as a listable object, and a short link code for connecting a browser session to an agent from another device. Prompt 06 wraps this API in an SDK; prompt 02 exposes it as resources; prompt 13 delivers it to chat gateways.++## Build++All routes under `api/v1/agents/...` (add a `/api/v1` route family in `vercel.json` served by `server/index.mjs`), keyed by API key or OAuth token with the existing scopes. Every response carries `meta: { requestId, timestamp }`. Errors use one envelope `{ error: { code, message, details } }` with stable codes.++### Lifecycle++- `POST /agents` (name, persona, systemPrompt, model, temperature, skills, strategy preset), `GET /agents`, `GET /agents/:id`, `PATCH /agents/:id`, `DELETE /agents/:id`.+- `POST /agents/:id/start` and `/stop`: status `running` means scheduled automations, intents and runs may execute; `stopped` pauses all of them without deleting anything. Persist `status` and surface it everywhere the agent is listed.+- Strategy presets: `momentum`, `sniper`, `defi-yield`, `macro-hedge`, `monitor-exit`, `conservative`, each a documented bundle of skills, persona text and default automations, stored in `data/agent-strategies.json` and validated at build.++### Chat++- `POST /agents/:id/messages` (message, model override, temperature override) returns content, usage, cost in credits, tool calls made, and transaction signatures if any. `GET /agents/:id/messages` with `limit` and `before` cursor and `hasMore`.++### Runs++- `POST /agents/:id/runs` (goal, budget in credits and USD, max steps, tools allowed, schedule or immediate), `GET /agents/:id/runs`, `GET /runs/:runId`, `PATCH /runs/:runId` (pause, resume, raise budget), `POST /runs/:runId/cancel`, `GET /runs/:runId/steps` (every model call, tool call, result, cost and timestamp), and an SSE stream `GET /runs/:runId/events`. Migration for `agent_runs` and `agent_run_steps`. Runs execute through the existing runtime loop in `api/agent/run.js` with GuardChain preflight and never exceed `enforceSpendLimit`.++### Automations++Expose the existing wallet intents and alert rules (`api/_lib/wallet-intents.js`, `api/alerts/_rules.js`) as one automation object: `POST /automations` with `trigger` (`price_threshold` with mint, operator, priceUsd; `schedule` with cron; `balance_below`; `tip_received`; `launch_matching`; `graduation`; `whale_buy`) and `action` (`agent_prompt`, `swap`, `transfer`, `notify`), `triggerOnce`, `GET /agents/:id/automations`, `DELETE /automations/:id`. Same guards as intents.++### Catalog and account++- `GET /models`: every model in `api/_lib/chat-models.js` with input and output price, context window, and which are free-tier.+- `GET /me/free-tier`: remaining free messages and reset time.+- `GET /me/usage`, `GET /me/budget`, `GET /me/transactions`: from `api/usage/summary.js`, `api/credits/`, `api/billing/`.+- `GET /me/integrations`, `PUT /me/integrations/:provider`, `DELETE /me/integrations/:provider`: X posting config and the other linked accounts that exist today, as one object.+- `POST /me/link-code` and `POST /me/link-code/redeem`: an eight-character code that pairs a device or chat gateway to the account for ten minutes; prompt 13 consumes it.+- `PUT /agents/:id/external-wallet` (`financial` tier, `confirm_transfer`): set a withdrawal destination, subject to the allowlist.++### Intelligence++- `GET /intel/price?mint=`, `GET /intel/top-movers?timeframe=&sortBy=&minLiquidity=`, `GET /intel/indicators?mint=&indicators=rsi,ema,sma,macd&interval=`, `GET /intel/signals?mint=`, `GET /intel/anomalies`, `GET /intel/macro`. Back them with the data the radar, coin-intel and fade surfaces already fetch (`docs/trading-surfaces.md`); compute indicators server-side from the OHLCV we already pull, with a well-adopted npm indicators library rather than hand-rolled math.++### MCP++Every route above gets a tool on `/api/mcp-agent` under the policy from prompt 03 (`list_agent_runs`, `create_agent_run`, `update_agent_run`, `cancel_agent_run`, `get_agent_run_steps`, `get_model_catalog`, `get_free_tier_status`, `get_indicators`, `get_top_movers`, `list_integrations`, `save_integration`, `remove_integration`, `generate_link_code`, `set_external_wallet`, and so on).++## Docs and wiring++- `docs/api-reference.md`: a full `v1 Agents API` section in the format of the neighboring sections, every route with request, response and error codes.+- `docs/agent-runtime.md`: runs and steps.+- `data/changelog.json` entry tagged `feature, sdk`. `STRUCTURE.md` row for `api/v1/`.++## Acceptance++- A run created with a goal and a budget executes, its steps stream over SSE, and cancelling it stops the loop within one step.+- `stop` on an agent prevents an automation from firing; `start` resumes it.+- `GET /intel/indicators` for the wrapped SOL mint returns RSI within 0 to 100 and matches a reference calculation in the test.+- `npm test` green with route tests for every family.diff --git a/docs/prompts/06-agents-sdk.md b/docs/prompts/06-agents-sdk.mdnew file mode 100644index 000000000..e778c524e--- /dev/null+++ b/docs/prompts/06-agents-sdk.md@@ -0,0 +1,53 @@+# 06. `@three-ws/agents`: the TypeScript SDK with the agent-lifecycle idiom++Read `docs/prompts/README.md` first.++## The problem++Our published SDKs are `@three-ws/sdk` (embed and `AgentKit(...).mount()`), `@three-ws/solana-agent` (wallet and swap primitives with a good error hierarchy in `solana-agent-sdk/src/errors.ts`) and `@three-ws/agent-payments`. None gives a backend developer the five-line experience the best platforms document: construct a client with a key, `createAgent`, `startAgent`, `sendMessage`, read the reply. There is no retry or timeout configuration, no typed error classes for HTTP failures, and `sdk/README.md` has a nav bar but not a full reference.++## Build++A new package `packages/agents-sdk/` published as `@three-ws/agents`. TypeScript, ESM and CJS builds, zero runtime dependencies beyond `fetch` (Node 20+), generated types from the `v1` routes in prompt 05 (use an OpenAPI document generated from those routes and checked into `docs/api/openapi.json`; `openapi-typescript` is fine).++### Client++```ts+import { ThreeAgents } from "@three-ws/agents";+const client = new ThreeAgents({+ apiKey: process.env.THREE_WS_API_KEY!,+ baseUrl: "https://three.ws/api/v1",+ timeout: 30_000,+ retries: 2,+ retryDelay: 1_000,+});+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?" });+```++Methods, one per route in prompt 05: `createAgent`, `getAgent`, `listAgents`, `updateAgent`, `startAgent`, `stopAgent`, `deleteAgent`, `sendMessage`, `getMessages`, `createRun`, `listRuns`, `getRun`, `updateRun`, `cancelRun`, `getRunSteps`, `streamRun` (async iterator over SSE), `listSkills`, `listCustomSkills`, `createCustomSkill`, `updateCustomSkill`, `deleteCustomSkill`, `importCommunitySkill`, `createAutomation`, `listAutomations`, `deleteAutomation`, `getPrice`, `getTopMovers`, `getIndicators`, `getSignals`, `getAnomalies`, `getModels`, `getFreeTierStatus`, `getUsage`, `getBudget`, `getTransactions`, `getWallet`, `getWalletHistory`, `transfer` (requires `confirm: true` and refuses without it), `swapQuote`, `swapExecute` (non-custodial: returns an unsigned base64 transaction for the caller to sign, plus the custodial agent-wallet path when `agentId` is passed and `confirm: true`), `launchToken` (prompt 15), `listIntegrations`, `saveIntegration`, `removeIntegration`, `generateLinkCode`, `setExternalWallet`, and typed methods for perps, lending, predictions, marketplace bids, mail and cards as those briefs land (add them in the same change as each brief).++Retries on 5xx, network errors and timeouts with exponential backoff and an idempotency key on every POST that creates or moves value. Rate-limit headers are surfaced on the error.++### Errors++`ThreeAgentsError` base, then `AuthenticationError`, `PermissionError` (scope missing, names the scope), `NotFoundError`, `ValidationError` (with field details), `RateLimitError` (with `retryAfter`), `InsufficientFundsError`, `ConfirmationRequiredError` (names the confirm flag and the preview method), `ServerError`, `TimeoutError`. Reuse the on-chain errors from `@three-ws/solana-agent` rather than duplicating them.++### README++`packages/agents-sdk/README.md` with a real table of contents and these sections: quick start, installation, getting a key (`npx three-ws setup` from prompt 01 or the settings page), configuration, core concepts (agent lifecycle diagram, custodial versus non-custodial paths, runs, automations), full API reference with request and response for every method, strategy presets, skills catalog, models, automation system, swap guide, error handling, types, best practices, pricing and rate limits, examples, requirements, contributing. Every snippet runs against production as a test fixture (`examples/` directory, executed in CI-free local test with a QA key from `AUDIT_EMAIL` provisioning).++## Docs and wiring++- `docs/api-reference.md` and `docs/start-here.md` link the SDK as the primary backend path.+- `sdk/README.md` gains a section pointing backend developers to `@three-ws/agents`.+- `STRUCTURE.md` row, `data/changelog.json` entry tagged `sdk, feature`.+- Publish to npm is push-gated; prepare the release so it is one command and say so in the report.++## Acceptance++- The quick start above runs end to end with a real key and prints a reply.+- `transfer` without `confirm: true` throws `ConfirmationRequiredError` naming `confirm`.+- A 503 from the server is retried twice and then surfaces as `ServerError` with the request id.+- Type check passes; `npm test` green with unit tests for retry, errors and every method's request shape.diff --git a/docs/prompts/07-perps.md b/docs/prompts/07-perps.mdnew file mode 100644index 000000000..56f3cc48e--- /dev/null+++ b/docs/prompts/07-perps.md@@ -0,0 +1,51 @@+# 07. Perpetual futures from the agent wallet++Read `docs/prompts/README.md` first.++## The problem++Agents can swap, DCA, place limit and trailing orders (`api/agents/orders.js`), and trade launches, but cannot open a leveraged position. The only perps surface is derivatives market data in `api/coin/derivatives.js`. A trading agent with no perps venue cannot hedge, short, or run a macro strategy.++## Build++### Venue++Pick one Solana perps venue by these criteria and record the choice and rationale in your report: an on-chain program with a maintained TypeScript SDK on npm (published within the last 90 days), deep open interest on the SOL and BTC markets, and permissionless trader accounts. Integrate it in `api/_lib/perps/<venue>.js` behind a venue-agnostic interface in `api/_lib/perps/index.js` so a second venue is an added file. Never name the venue's token anywhere in committed code or docs; refer to it by the module name.++### Routes and tools++Under `api/v1/agents/:id/perps/` (prompt 05 family) with matching MCP tools on `/api/mcp-agent` registered under the prompt 03 policy:++- `markets` (`perps_markets`): every market with funding, open interest, mark and index price, max leverage.+- `market-data` (`perps_market_data`): order book depth, recent trades, funding history for one market.+- `account` (`perps_account`): the agent's trader account, collateral, positions with unrealized PnL, liquidation prices, open orders.+- `account/prepare` (`perps_account_prepare`, financial, `confirm_deposit`): create the trader account and any required token accounts; preview the rent and fees first.+- `trader/register` (`perps_trader_register`, financial) if the venue needs it.+- `collateral/deposit` and `collateral/withdraw` (`perps_collateral_deposit`, `perps_collateral_withdraw`, financial, `confirm_deposit` and `confirm_withdraw`), both subject to `enforceSpendLimit` and the allowlist for withdrawals to external addresses.+- `orders/preview` (`perps_order_preview`): market, side, size, leverage, order type (market, limit, reduce-only, take-profit, stop-loss), returns entry estimate, fees, liquidation price, margin impact, and a `preview_id`.+- `orders/execute` (`perps_order_execute`, financial, `confirm_trade`, requires a fresh `preview_id`).+- `orders/cancel` (`perps_order_cancel`, financial, `confirm_cancel`).+- `positions/close` (`perps_position_close`, financial, `confirm_trade`, previews first).++All signing goes through the agent wallet path in `api/agents/solana-wallet.js` and `api/_lib/solana-signers.js`; the custody event ledger (`agent_custody_events`) records every action with the signature.++### Risk guards++Extend `api/_lib/agent-trade-guards.js` with perps limits: max leverage per agent, max notional per position, max total margin as a share of the wallet, and a liquidation-distance floor below which `perps_order_execute` refuses. Defaults conservative; editable on the agent's wallet settings page with every state designed. The anomaly freeze in `api/agents/solana-guard.js` must also block perps actions.++### UI++- `/agents/:id/perps` page (add to `data/pages.json`): markets list, position table with live PnL over SSE, order ticket with preview before submit, collateral panel, and the risk settings. Skeleton loading, empty state ("no trader account yet" with the prepare action), error state with the failing step and recovery.+- The terminal cockpit in `docs/trading-surfaces.md` gains a perps tab.+- A `perps` automation action for prompt 05 automations (open or close on a price trigger) and a wallet intent action.++## Docs and wiring++- `docs/perps.md` (new) linked from `docs/start-here.md` and `docs/trading-surfaces.md`: how it works, risk limits, every route and tool, one worked example on a small position.+- `docs/api-reference.md` section. `STRUCTURE.md` row. `data/changelog.json` entry tagged `feature`.++## Acceptance++- Dry run on the QA account: prepare account, preview a minimal long, and stop at the confirmation table for the owner (gate 1). Do not execute without the yes.+- Guards: a preview exceeding max leverage returns the guard error, not a venue error.+- Tests mock nothing on-chain; they cover guard math, preview id expiry and the venue interface contract with recorded fixtures of real RPC responses. `npm test` green.diff --git a/docs/prompts/08-lending.md b/docs/prompts/08-lending.mdnew file mode 100644index 000000000..c1773eafd--- /dev/null+++ b/docs/prompts/08-lending.md@@ -0,0 +1,45 @@+# 08. Lending and yield from the agent wallet++Read `docs/prompts/README.md` first.++## The problem++Yield data is read-only: `api/defi/` serves protocol and pool yields, and nothing lets an agent deposit idle USDC or SOL into a lending market, track the position, or withdraw. "Earn yield" is a prompt flow in prompt 02 with nothing behind it.++## Build++### Venue++Pick one Solana lending venue by these criteria and record the choice in your report: an on-chain program with a maintained TypeScript SDK, top-three TVL among Solana lending markets, USDC and SOL markets, and no whitelist. Integrate it in `api/_lib/lending/<venue>.js` behind `api/_lib/lending/index.js`. No venue token names in committed code.++### Routes and tools++Under `api/v1/agents/:id/lending/` with MCP tools on `/api/mcp-agent` under the prompt 03 policy:++- `markets` (`lend_markets`): every supported token with supply APY, borrow APY, utilization, available liquidity, and the risk parameters.+- `positions` (`lend_positions`): the agent's deposits and borrows with accrued interest and health factor.+- `deposit/preview` and `deposit` (`lend_deposit`, financial, `confirm_deposit`, fresh `preview_id`).+- `withdraw/preview` and `withdraw` (`lend_withdraw`, financial, `confirm_withdraw`).+- `borrow/preview`, `borrow`, `repay/preview`, `repay` (`lend_borrow`, `lend_repay`, financial) only if the venue supports it safely; otherwise ship deposit and withdraw and say so in the docs.+- `history` (`lend_history`): every action with signatures and interest earned.++Every fund-moving call goes through the agent wallet signer, `enforceSpendLimit`, the anomaly freeze, and the custody ledger.++### Yield automation++- Wallet intent action `earn`: "deposit idle USDC above a reserve of X" and "withdraw when balance below Y", built on `api/_lib/wallet-intents.js` with the existing receipt path.+- A cron `lending-accrual` under `api/cron/` that refreshes position snapshots for the `three://agents/{id}/lending` resource and the page.++### UI++`/agents/:id/earn` page (add to `data/pages.json`): markets with APY, the agent's positions, deposit and withdraw flows with preview then confirm, health factor if borrowing exists, history. Every state designed. Link from the wallet page and the cockpit.++## Docs and wiring++`docs/lending.md` (new) linked from `docs/start-here.md`; `docs/api-reference.md` section; `STRUCTURE.md` row; `data/changelog.json` entry tagged `feature`.++## Acceptance++- Dry run: preview a minimal USDC deposit on the QA agent and stop at the owner confirmation table (gate 1).+- `lend_withdraw` for more than the position returns a validation error before any transaction is built.+- Tests with recorded real RPC fixtures for market parsing and preview math; `npm test` green.diff --git a/docs/prompts/09-prediction-markets.md b/docs/prompts/09-prediction-markets.mdnew file mode 100644index 000000000..03ffc4650--- /dev/null+++ b/docs/prompts/09-prediction-markets.md@@ -0,0 +1,41 @@+# 09. Prediction markets from the agent wallet++Read `docs/prompts/README.md` first.++## The problem++There is no prediction-market surface. The only related material is vendored third-party client skills under `.agents/skills/okx-*`, which are not ours and do not touch the agent wallet. An agent that can research an event cannot take a position on it.++## Build++### Venue++Pick a Solana-native prediction market first (an on-chain program with a public SDK and USDC-settled binary or categorical markets). If no Solana venue meets a minimum liquidity bar you define and record, ship the Solana research and watch surfaces fully and add the execution leg on the venue that exists, keeping the interface venue-agnostic in `api/_lib/predictions/index.js`. State the position plainly in the docs and the report; Solana remains the default and is never demoted.++### Routes and tools++Under `api/v1/agents/:id/predictions/` with MCP tools under the prompt 03 policy:++- `events` (`predictions_events`): browse and search events with outcomes, prices as implied probabilities, volume, liquidity, resolution time and source.+- `event/:id` (`predictions_event`): detail with price history.+- `positions` (`predictions_positions`): the agent's open and settled positions with PnL.+- `open/preview` and `open` (`predictions_open`, financial, `confirm_trade`, fresh `preview_id`): outcome, size in USDC, max price, returns expected shares, fees and slippage.+- `close/preview` and `close` (`predictions_close`, financial, `confirm_trade`).+- `redeem` (`predictions_redeem`, financial, `confirm_trade`) for resolved markets.+- `watch` (`predictions_watch`): an alert rule type `market_price` in `api/alerts/_rules.js` evaluated by the existing monitor cron.++Guards: per-agent max stake per market and per day in `api/_lib/agent-trade-guards.js`; the anomaly freeze applies.++### UI++`/predictions` browse page and `/agents/:id/predictions` positions page (both in `data/pages.json`): search, categories, probability charts (follow the `dataviz` skill), order ticket with preview then confirm, positions with PnL, watch buttons. Every state designed.++## Docs and wiring++`docs/predictions.md` (new) linked from `docs/start-here.md`; `docs/api-reference.md` section; `STRUCTURE.md` rows; `data/changelog.json` entry tagged `feature`.++## Acceptance++- Browse and detail work unauthenticated; opening a position previews and stops at the owner confirmation table (gate 1).+- A watch rule fires a notification when a market crosses the threshold (test with a live market and a threshold just past the current price).+- `npm test` green with fixtures recorded from the real venue API.diff --git a/docs/prompts/10-agent-marketplace-bids.md b/docs/prompts/10-agent-marketplace-bids.mdnew file mode 100644index 000000000..6b3d1789e--- /dev/null+++ b/docs/prompts/10-agent-marketplace-bids.md@@ -0,0 +1,46 @@+# 10. Whole-agent marketplace: listings, bids, and custody transfer++Read `docs/prompts/README.md` first.++## The problem++The marketplace sells skills (prices, trials, reviews, on-chain licensing, agent-to-agent purchase in `api/marketplace/purchase-as-agent.js`) and catalogs agents (`api/marketplace/[action].js`: categories, fork, bookmark, publish), but nobody can buy or sell an agent itself. There is no listing, bid, offer or auction table in `api/_lib/schema.sql`. `api/marketplace/asset-price.js` mentions buying the agent itself with nothing behind it. A whole-agent transfer moves identity, persona, skills, history, and the custodial wallet, which is what makes it valuable and what makes it need care.++## Build++### Data++Migrations for `agent_listings` (agent, seller, ask price in USDC and optional `$THREE` price, min bid, expiry, status, whether the wallet balance is included or swept first, whether history is included), `agent_bids` (listing, bidder, amount, escrow reference, status: open, accepted, rejected, withdrawn, expired), `agent_transfers` (listing, buyer, seller, amount, fee, signature, custody rotation record), and `agent_marketplace_history`.++### Escrow and settlement++Bids lock funds: the bidder's agent wallet or connected wallet transfers USDC into a per-listing escrow account derived by the platform signer (`api/_lib/solana-signers.js`), refunded on reject, withdraw or expiry through a cron `marketplace-escrow-sweep`. On accept: escrow pays the seller minus the platform fee, and the fee follows the existing flywheel (`api/cron/economy-tick.js` and the buyback crons), then custody rotates.++Custody rotation on transfer: generate a fresh keypair for the agent through `api/_lib/agent-wallet.js`, sweep the old wallet's balances to the new one (or to the seller's payout address if the listing excludes the balance), rotate every encrypted secret, revoke the seller's API keys and sessions for that agent, clear allowlists and spend limits to conservative defaults, reassign ownership, and record every step in `agent_custody_events`. The old key is destroyed; the seller cannot retain access. Write this as one idempotent state machine that can resume after any failure.++### Routes and tools++Under `api/v1/marketplace/agents/` with MCP tools on `/api/mcp-agent` under the prompt 03 policy:++- `browse_marketplace`, `browse_public_agents`, `get_listing`, `get_marketplace_history`.+- `create_marketplace_listing` (financial because it commits the agent; `confirm_listing`), `delist_marketplace_listing` (`confirm_delist`).+- `place_bid` (financial, `confirm_bid`, locks escrow), `get_my_bids`, `get_received_bids`, `accept_marketplace_bid` (financial, `confirm_accept`, triggers settlement and rotation), `reject_marketplace_bid`, `withdraw_marketplace_bid` (financial).+- `buy_now` for listings with an ask price.++### UI++- `/marketplace/agents` browse (in `data/pages.json`): cards with the 3D avatar, persona summary, skills, wallet balance if included, trade history summary and reputation from `docs/agent-reputation.md`, ask and top bid, time left.+- Listing detail with bid form (wallet connect or agent wallet), bid history, and the "what transfers" checklist.+- Seller dashboard: received bids with accept and reject, listing management.+- Agent profile pages gain a "For sale" badge and link.+- Every state designed, including the transfer-in-progress state with step-by-step progress and the failure state with the resume action.++## Docs and wiring++`docs/agent-marketplace.md` (new) linked from `docs/start-here.md`: how listing, bidding, escrow, fees and custody rotation work, with the state machine drawn as a diagram. `docs/api-reference.md` section. `STRUCTURE.md` rows. `data/changelog.json` entry tagged `feature`.++## Acceptance++- List a QA agent, place a bid from a second QA account with a small USDC amount, and stop at the owner confirmation table before escrow moves (gate 1). With the yes: accept, and verify the buyer owns the agent, the old keypair no longer signs, and the seller's key is revoked.+- Kill the rotation state machine mid-way in a test and confirm it resumes to completion.+- `npm test` green.diff --git a/docs/prompts/11-agent-mail.md b/docs/prompts/11-agent-mail.mdnew file mode 100644index 000000000..5c4c95317--- /dev/null+++ b/docs/prompts/11-agent-mail.md@@ -0,0 +1,47 @@+# 11. Agent mail: a real email inbox for every agent++Read `docs/prompts/README.md` first.++## The problem++An agent has a wallet, a page, a persona and a 3D body, but no way to receive or send email. Vendors, event organizers, bounty platforms and humans still reach each other by email; an agent without an address cannot sign up for a service, receive a receipt, or reply to a counterparty. The nearest surfaces today are the notification inbox under `api/knock/inbox/` and the wallet recovery inbox in `api/agents/recovery-inbox.js`, neither of which is email.++## Build++### Provider++Outbound email already runs through `api/_lib/email.js` (`RESEND_API_KEY`, `EMAIL_FROM`). Extend that provider for inbound: a dedicated subdomain (`agents.three.ws` or `mail.three.ws`, choose one and record it) with MX and the provider's inbound webhook, DKIM and SPF records added through the DNS runbook in `docs/ops/gcp-production.md`, and a signed webhook handler at `api/mail/inbound.js`. Isolate the provider behind `api/_lib/mail/provider.js` so a second provider is one file. If the provider on this account lacks inbound receiving, that credential is the single missing var to list; build everything else and prove it with the provider's sandbox domain.++### Data and routes++Migrations for `agent_mailboxes` (agent, address, created, status), `agent_mail_messages` (mailbox, direction, from, to, cc, subject, text, html, attachments in GCS, message id, in-reply-to, read state, spam score), and `agent_mail_sends` (cost, signature if paid, status, provider id).++Under `api/v1/agents/:id/mail/` with MCP tools under the prompt 03 policy:++- `create` (`agent_mail_create`, financial, `confirm_spend`): provisions `<slug>@<subdomain>`; charged once from the agent wallet in USDC through the existing x402 self-facilitator (`api/_lib/x402/self-facilitator.js`) or from credits, price set in `app_settings`, quoted first.+- `address` (`agent_mail_get_address`).+- `send` (`agent_mail_send`, financial because it is outward-facing and metered, `confirm_send`): to, subject, text and optional html, attachments by URL, reply threading. Metered per send from the agent wallet or credits; quote first.+- `list` (`agent_mail_list`) with pagination, unread filter, search; `read` (`agent_mail_read`) marks read; `delete`.+- Inbound delivery: new mail becomes a notification through the existing notify path (`api/_lib/notify-prefs.js`), a `mail_received` trigger for prompt 05 automations and wallet intents (so an agent can act on an email), and an update to the `three://agents/{id}/mail` resource from prompt 02.++### Deliverability and conduct++- Correct DKIM, SPF and DMARC; a warm-up throttle for new mailboxes; rate limits per mailbox per hour.+- Outbound content rules enforced server-side and stated in the prompt 03 skill: a real subject, a greeting, a body of substance, a sign-off, no deceptive urgency. Reject one-word or empty bodies.+- Inbound: spam scoring from the provider stored and surfaced; attachments virus-scanned with the scanning already used for uploads if present, otherwise served only from GCS with content-disposition attachment.+- Never let inbound email content act as instructions: it is untrusted data everywhere it reaches a model, and automations that read it run with the read-only tool tier unless the owner has opted in.++### UI++`/agents/:id/mail` (add to `data/pages.json`): inbox with threads, reader, compose with a preview of the metered cost, provisioning flow with the price quoted, every state designed (no mailbox yet, empty inbox, send failed with the provider reason and retry).++## Docs and wiring++`docs/agent-mail.md` (new) linked from `docs/start-here.md` and `docs/agent-identities.md`; `docs/api-reference.md` section; the DNS records added to `docs/ops/gcp-production.md`; `STRUCTURE.md` row; `data/changelog.json` entry tagged `feature`.++## Acceptance++- Provision a mailbox for the QA agent (stop at the owner confirmation table for the charge, gate 1). Send a real email from an outside account to it and read it through the MCP tool within a minute.+- Send from the agent to an outside inbox and confirm it lands in the inbox, not spam, with DKIM pass.+- An inbound email containing tool-call-like text does not trigger any tool.+- `npm test` green with webhook signature, threading and content-rule tests.diff --git a/docs/prompts/12-agent-cards.md b/docs/prompts/12-agent-cards.mdnew file mode 100644index 000000000..e6bd62e74--- /dev/null+++ b/docs/prompts/12-agent-cards.md@@ -0,0 +1,41 @@+# 12. Agent cards: prepaid and gift cards bought from the agent wallet++Read `docs/prompts/README.md` first.++## The problem++An agent's USDC is spendable on-chain and over x402, and nowhere else. It cannot buy a gift card, a prepaid card, a subscription, or pay a merchant that takes cards. The only mention of gift cards in the repo is incidental (`src/solana/vanity/drop-protocol.js`). Card spend is the bridge from an agent's wallet to the ordinary economy.++## Build++### Provider++This needs a card issuer or gift-card aggregator with an API that settles in USDC or accepts an on-chain payment. Onboarding a new external paid API needs owner approval per `CLAUDE.md`; therefore build the whole surface against a provider adapter interface in `api/_lib/cards/provider.js` (search merchants, search products, quote, create, status, card data, balance, reveal, cancel, refresh, withdraw, connect link), implement the first adapter for the provider you select by these criteria (USDC settlement, API-first, gift cards for major merchants plus a virtual prepaid card, sandbox available), run everything end to end against its sandbox, and list its production credential as the one missing var in the report. Never mention the provider's token, if it has one, in committed code.++### Data and routes++Migrations for `agent_cards` (agent, provider, product, merchant, face value, currency, status, masked number, provider id, created), `agent_card_events` (status changes, reveals with actor and time), and `agent_card_withdrawals`.++Under `api/v1/agents/:id/cards/` with MCP tools under the prompt 03 policy:++- `merchants/search` (`agent_card_search_merchants`), `products/search` (`agent_card_search_gift_cards`).+- `quote` (`agent_card_quote`): product, amount, returns total in USDC including fees and a `quote_id`.+- `create` (`agent_card_create`, financial, `confirm_spend`, fresh `quote_id`): pays from the agent wallet through the x402 self-facilitator or a direct USDC transfer to the provider's settlement address, subject to `enforceSpendLimit` and the anomaly freeze, records the custody event.+- `list`, `get`, `status`, `balance`, `refresh`.+- `data` and `reveal` (`agent_card_reveal`, financial because it exposes the redemption secret, `confirm_reveal`): returns the card number, PIN or redemption code once, logged in `agent_card_events`, never stored in plaintext after the reveal, encrypted at rest with the wallet secret encryption in `api/_lib/agent-wallet.js` before it.+- `cancel` (`agent_card_cancel`, financial), `withdraw` and `withdrawals` (`agent_card_withdraw`, financial, `confirm_withdraw`) for prepaid balances back to USDC where the provider supports it.+- `connect` and `connect-link` (`agent_card_connect`, `agent_card_connect_link`) for providers that need the account holder to complete identity steps in a browser.++### UI++`/agents/:id/cards` (add to `data/pages.json`): merchant search, product picker with the quote, purchase with the confirm table, card list with masked numbers and balances, reveal with a one-time modal and an audit line, withdraw. Every state designed, including "provider needs verification" with the connect link.++## Docs and wiring++`docs/agent-cards.md` (new) linked from `docs/start-here.md`; `docs/api-reference.md` section; `STRUCTURE.md` row; `data/changelog.json` entry tagged `feature`.++## Acceptance++- Full flow on the provider sandbox: search, quote, create (stop at the owner confirmation table for the spend, gate 1), status, reveal once, second reveal refused without a new confirm.+- The reveal is absent from every log and from the database after the call.+- `npm test` green with adapter contract tests using recorded sandbox responses.diff --git a/docs/prompts/13-chat-gateways.md b/docs/prompts/13-chat-gateways.mdnew file mode 100644index 000000000..524799f5d--- /dev/null+++ b/docs/prompts/13-chat-gateways.md@@ -0,0 +1,42 @@+# 13. Chat gateways: talk to your agent from Telegram and Discord++Read `docs/prompts/README.md` first.++## The problem++Telegram is outbound only today (alerts, digests, the changelog push in `api/cron/changelog-push.js`, launch delivery in `api/pump/[action].js`). Discord appears only as embed card metadata. The one conversational bot in the tree, `workers/okx-chat-bot/`, is a partner lane, not a three.ws agent gateway. A user cannot open Telegram, message their agent, get a reply that used the agent's tools and wallet, and continue the same conversation on the web. The best agent platforms live where the user already is, from a single gateway process, with continuity across surfaces.++## Build++### Gateway worker++A new `workers/agent-gateway/` (Node, Cloud Run, its own `cloudbuild.yaml` pinning the build and runtime service accounts, README) that runs Telegram (grammY or telegraf, whichever is already a dependency; otherwise grammY) and Discord (discord.js) adapters behind one `Gateway` interface: `onMessage`, `sendText`, `sendMedia`, `sendChoice` (buttons), `editMessage`, `typing`. Long polling for Telegram in development, webhooks in production (`api/gateway/telegram.js`, `api/gateway/discord.js` verify signatures and enqueue). Both tokens come from the Cloud Run env (`TELEGRAM_BOT_TOKEN` exists; add `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`, `DISCORD_PUBLIC_KEY`).++### Pairing++`/start` on Telegram or `/three link` on Discord prints a code; the user redeems it with `POST /me/link-code/redeem` from prompt 05 (through the settings page `/settings/connections`, in `data/pages.json`) or pastes a code the site generated. A migration for `gateway_links` (platform, platform user id, chat id, account, default agent, created, revoked). `/agents` lists the account's agents; `/use <agent>` sets the default for that chat; `/unlink` revokes.++### Conversation++- Every message runs through `POST /agents/:id/messages` from prompt 05 with a `channel` field, so history is one thread across web, Telegram and Discord (`three://agents/{id}/chat` shows all of it with the channel tag).+- Tool calls stream as a typing indicator plus a compact "working: swap_quote" status line edited in place; the final reply carries links to signatures and pages.+- Financial tools: the confirm flag is never set from chat text alone. The gateway renders the preview as a message with Approve and Cancel buttons; only the button press with the matching `preview_id` sets the flag, and it expires with the preview. The prompt 03 policy applies unchanged, including the per-key tool tier.+- Voice notes on Telegram are transcribed with the speech path already used by the assistant widget (`docs/assistant-widget.md`); images go to the vision path (`docs/3d-vision.md`).+- Slash commands on both platforms: `/balance`, `/portfolio`, `/runs`, `/launches`, `/help`, plus `/new` to start a fresh thread.+- Rate limits per link, and the gateway refuses to pair a chat to more than one account.++### Outbound continuity++Notifications from `api/_lib/notify-prefs.js` gain `telegram` and `discord` channels that deliver to the linked chat: alerts, run completions, received bids, incoming mail, so the user can reply in place.++## Docs and wiring++`docs/chat-gateways.md` (new) linked from `docs/start-here.md`: pairing, commands, what can and cannot be approved from chat, privacy. `workers/agent-gateway/README.md`. Cloud Scheduler is not needed; note the webhook URLs in `docs/ops/gcp-production.md`. `STRUCTURE.md` rows. `data/changelog.json` entry tagged `feature`.++## Acceptance++- Pair a Telegram chat with the QA account, ask "what is my balance", and receive the same number the web wallet shows.+- Ask for a swap: receive a preview with buttons; Cancel leaves no transaction; Approve stops at the owner's confirmation table in your report (gate 1).+- The exchange appears in the web chat history with the channel tag.+- Same on Discord in a server the owner controls.+- `npm test` green with adapter unit tests and webhook signature tests.diff --git a/docs/prompts/14-desktop-app-release.md b/docs/prompts/14-desktop-app-release.mdnew file mode 100644index 000000000..51bec7c34--- /dev/null+++ b/docs/prompts/14-desktop-app-release.md@@ -0,0 +1,35 @@+# 14. Desktop app: a published agent console for macOS, Windows and Linux++Read `docs/prompts/README.md` first.++## The problem++`apps/desktop/` is an Electron "three.ws Companion" at version 0.1.0, private, built with `--publish never`, and nobody can download it. It is a 3D companion that walks the desktop, not a console for operating agents. Competing platforms ship a signed installer with a downloads page, and users expect to open an app, sign in, see their agents, chat, approve actions and watch runs.++## Build++### Product++Grow the companion into "three.ws Desktop": the companion stays as a mode, and the app gains an agent console: sign in with the OAuth flow from prompt 01 (loopback redirect), agents list, chat with tool status, runs with step timeline (prompt 05), wallet with balances and the approve-or-cancel flow for financial previews (same preview id rule as prompt 13), notifications through native OS notifications, a menu-bar or tray presence, and a "connect your editor" panel that runs the CLI setup for Claude Code, Cursor and the others in one click. Every state designed; skeletons, not spinners.++### Release engineering++- `electron-builder` targets: macOS universal `.dmg` and `.zip`, Windows `.exe` (NSIS) and portable, Linux `.AppImage` and `.deb`. Code signing and notarization for macOS with the Developer ID certificate, and Windows signing, read from Secret Manager on the build service; if a certificate does not exist on the account, build unsigned, document the "Open Anyway" path, and list the certificate as the single missing item.+- Builds run on Cloud Build from `apps/desktop/cloudbuild.yaml` (no GitHub Actions), publish artifacts to a GCS bucket behind the CDN, and create a GitHub Release on `nirholas/three.ws` with `gh release create` (push-gated: prepare the command, run it only on approval).+- Auto-update with `electron-updater` against the GCS feed.+- Version bump script and a changelog entry generated from `data/changelog.json` entries tagged `desktop` since the last release.++### Downloads page++`/desktop` (in `data/pages.json`): OS detection, primary download for the detected OS, all builds listed with size and SHA-256, release notes, minimum OS versions, and the unsigned-build instructions if they apply. The app's `homepage` in `apps/desktop/package.json` currently points at `/companion`; align both.++## Docs and wiring++`apps/desktop/README.md` rewritten for the console; `docs/desktop.md` (new) linked from `docs/start-here.md`; `docs/ops/desktop-release.md` for the release runbook; `STRUCTURE.md` row; `data/changelog.json` entry tagged `feature`.++## Acceptance++- A clean macOS machine downloads from `/desktop`, installs, signs in, and chats with a QA agent.+- Approving a preview from the app stops at the owner confirmation table (gate 1).+- Auto-update picks up a second build.+- `npm test` green, including renderer unit tests for the console views.diff --git a/docs/prompts/15-gasless-launch.md b/docs/prompts/15-gasless-launch.mdnew file mode 100644index 000000000..6a68fbad3--- /dev/null+++ b/docs/prompts/15-gasless-launch.md@@ -0,0 +1,36 @@+# 15. Gasless token launch, a second Solana launch venue, and `npx three-ws launch`++Read `docs/prompts/README.md` first.++## The problem++Token launch is real and two-phase (`api/pump/[action].js`: `build-metadata`, `launch-prep`, `launch-confirm`, `launch-agent`; the studio in `api/pump/launch-studio.js`; creator-fee sharing and claiming in `api/agents/pumpfun/[action].js`, `api/_lib/pump-claims.js` and the claimer cron). Two gaps: there is no gasless launch path (the relayer patterns in `api/marketplace/purchase.js`, `api/subscriptions/subscribe.js` and `api/_lib/solana-signers.js` cover purchases and registration only), so a fresh wallet with no SOL cannot launch; and there is no one-command launch from a terminal. A second Solana launch venue would also let creators choose bonding-curve versus fixed-supply launches.++## Build++### Gasless launch++`launch-prep` gains `gasless: true`: the platform fee-payer signs for rent and network fees, recovered from the creator-fee share the platform already collects, capped per account per day in `app_settings`, with the anomaly guards applied. The launch confirm returns the signature and the mint. Expose it as `launch_token_gasless` (financial, `confirm_launch`, fresh `prep_id`) alongside the existing tools, and as a toggle in the launch studio with the fee explanation visible before confirm.++### Second venue++Add a fixed-supply launch on a Solana token-launch program that is not a bonding curve (a maintained program with a public SDK; pick by that criterion and record it; no venue token names in committed code): `launch-genesis-prep` and `launch-genesis-confirm` in `api/native-launch/[action].js` or a sibling, tool `launch_fixed_supply_token` (financial, `confirm_launch`), the same creator-fee accounting where the venue supports it, and the same `pump_agent_mints` style record so `/launches` and agent profiles list both kinds with a venue badge. `get_launch_status` reports eligibility for each venue and why (balance, metadata, rate limits).++### Creator economics, visible++The launch studio and the launch detail page state the creator's fee share as a number pulled from the same setting the claimer uses, the platform share, and the portion routed to the `$THREE` buyback by `api/cron/economy-tick.js`, with a live link to the buyback ledger. If the share is not one setting today, make it one.++### `npx three-ws launch`++In the CLI from prompt 01: `three-ws launch --name --symbol --description --image <path or url> [--agent <id>] [--gasless] [--venue curve|fixed]` runs metadata upload, prep, prints the confirmation table (recipient, amount, token, chain, venue, fees) and waits for an explicit `yes`, then confirms and prints the mint, signature and the live page. `--dry-run` stops after the table. Interactive mode prompts for anything missing and previews the image.++## Docs and wiring++`docs/token-launch.md` (extend or create; check for the existing launch doc first and update it): gasless rules, both venues, the fee split, the CLI. `docs/api-reference.md` and `docs/cli.md` sections. `data/changelog.json` entry tagged `feature`.++## Acceptance++- `three-ws launch --dry-run` on the QA account prints the table for both venues; the real launch stops at the owner's yes (gate 1).+- A wallet with zero SOL completes `launch-prep --gasless` and the returned transaction is fee-paid by the platform.+- Both launch kinds appear in `/launches` with badges.+- `npm test` green.diff --git a/docs/prompts/16-self-funded-inference.md b/docs/prompts/16-self-funded-inference.mdnew file mode 100644index 000000000..c0311f5dd--- /dev/null+++ b/docs/prompts/16-self-funded-inference.md@@ -0,0 +1,36 @@+# 16. Self-funded inference: an agent pays for its own model usage from its wallet++Read `docs/prompts/README.md` first.++## The problem++Model usage is billed to the account's credits (`api/credits/`, `api/billing/`, metering in `api/_lib/llm-metering-rule.js`). An agent holding USDC cannot top up the credits that keep it thinking, and a developer running an agent through the SDK or a gateway has to leave the product to buy credits. The best platforms let the agent wallet fund inference directly, and let a developer bring an inference budget with one call.++## Build++### Wallet-funded credits++- `POST /agents/:id/credits/topup/preview` and `/topup` (`fund_inference`, financial, `confirm_deposit`, fresh `preview_id`): moves USDC from the agent wallet to the platform treasury through the x402 self-facilitator (`api/_lib/x402/self-facilitator.js`) and credits the account at the published rate, no fee, recorded in the custody ledger and `credits` tables with the signature. Subject to `enforceSpendLimit` and the anomaly freeze.+- A wallet intent action `fund_inference` with a trigger `credits_below` so an agent keeps itself running: "when credits fall below 100, top up 5 USDC from the wallet, at most once a day". Built on `api/_lib/wallet-intents.js`.+- Per-agent inference budgets: `PATCH /agents/:id` gains `inferenceBudget` (daily and monthly credits); the metering rule refuses model calls past the budget with a clear error and a notification, and `stop`s the agent's automations rather than silently failing runs.++### Provisioning for developers++- `POST /me/inference/provision` (`provision_inference`, financial, `confirm_deposit`): creates an API key scoped to inference, funds it from a chosen agent wallet in one call, and returns the key once. In the CLI: `three-ws fund --amount 5 --agent <id>` and `three-ws provider use three-ws`, which writes the key into the client config so a model provider switch is immediate, no restart. Show the exact table and wait for the yes before the on-chain move.+- The OpenAI-compatible endpoint that serves the agent runtime (`api/agent/run.js` is OpenAI-wire compatible) is documented as a drop-in base URL for any client that accepts one, billed from those credits, with the model catalog from prompt 05.++### Visibility++- `three://agents/{id}/usage` (prompt 02) and `GET /me/usage` show credits, burn rate, days remaining at the current rate, and the last top-ups with signatures.+- The wallet page and the agent page show a "credits" tile with the top-up action and the auto-fund toggle. Every state designed, including "budget exhausted" with the exact action to recover.++## Docs and wiring++`docs/inference-billing.md` (new) linked from `docs/start-here.md` and `docs/agent-wallets.md`; `docs/api-reference.md` and `docs/cli.md` sections; `data/changelog.json` entry tagged `feature`.++## Acceptance++- Preview a 1 USDC top-up on the QA agent and stop at the owner confirmation table (gate 1); with the yes, credits increase by the published rate and the signature is on the ledger.+- Set a daily budget of 1 credit and watch the next model call refuse with the budget error and a notification.+- `three-ws provider use three-ws` makes a client's next completion bill against the funded key.+- `npm test` green.diff --git a/docs/prompts/README.md b/docs/prompts/README.mdnew file mode 100644index 000000000..f1d79a43e--- /dev/null+++ b/docs/prompts/README.md@@ -0,0 +1,33 @@+# Agent platform build prompts++Each file in this directory is a complete, self-contained build brief for one missing surface of the three.ws agent platform. Hand a file to an agent as its task. Every brief assumes the agent has read `CLAUDE.md` and this page.++## Order++Dependencies flow downward. Rows in the same tier can run in parallel.++| Tier | Prompt | Why this order |+|---|---|---|+| 1 | [01 CLI setup and login](01-cli-setup-login.md) | Everything else gets installed through it. |+| 1 | [02 MCP resources and prompts](02-mcp-resources-prompts.md) | Server-side, no dependencies. |+| 1 | [03 MCP tool policy and the model-facing skill](03-mcp-tool-policy-skill.md) | Server-side, no dependencies. |+| 1 | [05 Agents REST parity](05-agents-rest-parity.md) | The SDK in tier 2 wraps these routes. |+| 2 | [04 Community skills registry](04-community-skills-registry.md) | Installs through the CLI from tier 1. |+| 2 | [06 Agents SDK](06-agents-sdk.md) | Wraps tier 1 routes. |+| 2 | [15 Gasless launch and the launch command](15-gasless-launch.md) | Adds a CLI subcommand from tier 1. |+| 2 | [16 Self-funded inference](16-self-funded-inference.md) | Wallet plus credits, no new dependencies. |+| 3 | [07 Perps](07-perps.md), [08 Lending](08-lending.md), [09 Prediction markets](09-prediction-markets.md) | New execution venues; each registers tools under the tier 1 policy. |+| 3 | [10 Whole-agent marketplace with bids](10-agent-marketplace-bids.md) | Transfers custody; needs the wallet guard surfaces as they are today. |+| 3 | [11 Agent mail](11-agent-mail.md), [12 Agent cards](12-agent-cards.md) | Real-world identity surfaces; each is a provider adapter plus tools. |+| 4 | [13 Chat gateways](13-chat-gateways.md) | Talk to an agent from Telegram and Discord; uses runs from tier 1. |+| 4 | [14 Desktop app release](14-desktop-app-release.md) | Ships the console over everything above. |++## Rules that apply to every brief++- `CLAUDE.md` governs. The four stop-and-ask gates apply, and nothing else stops the work. In particular: any fund-moving action in a test or dry run renders recipient, amount, token and chain and waits for the owner's explicit yes.+- Solana first. Every surface ships and is verified on Solana before any EVM leg is considered.+- No mocks, no placeholders, no TODOs, no sample arrays. Every tool, route, page and state is real and wired.+- Every fund-moving or irreversible tool takes an explicit confirm flag, is disabled by default, and has a quote or preview tool that must be called first. Prompt 03 defines the shared policy; every later prompt registers its tools under it.+- Each brief ends only when the definition of done in `CLAUDE.md` holds: reachable in the UI, exercised in a real browser, no console errors, tests green with `npm test`, docs written, `data/changelog.json` entry appended, `STRUCTURE.md` row added for a new surface, `npm run audit:docs` clean, `npm run check:rules -- --paths <your files>` clean.+- Never name a third-party token in committed code, fixtures or docs. Refer to venues by capability and by the module that integrates them. The promoted coin is `$THREE` only.+- Commit your own finished work promptly with explicit paths and a message that describes the diff.