Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(api): document the v1 agents REST API in OpenAPI, the API reference and the webhook guide
nirholasd1ba50222837
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex c24997c8e..b79b108c1 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -92,6 +92,7 @@ bottom.| Developer plans and quotas (`/developers`) | Config [api/_lib/dev-plans/config.js](api/_lib/dev-plans/config.js) (the only place plan numbers live), gate [api/_lib/dev-plans/quota.js](api/_lib/dev-plans/quota.js) wired into [api/_lib/gateway.js](api/_lib/gateway.js) for every `/api/v1` route, subscriptions [api/_lib/dev-plans/subscription.js](api/_lib/dev-plans/subscription.js), checkout + receipts [api/_lib/dev-plans/billing.js](api/_lib/dev-plans/billing.js), per-key analytics [api/_lib/dev-plans/analytics.js](api/_lib/dev-plans/analytics.js), key cache + immediate invalidation [api/_lib/api-key-cache.js](api/_lib/api-key-cache.js), allowlists [api/_lib/ip-allowlist.js](api/_lib/ip-allowlist.js); REST [api/v1/dev-plans.js](api/v1/dev-plans.js) `→ GET /api/v1/dev-plans`, [api/v1/me/dev-plan/](api/v1/me/dev-plan) `→ /api/v1/me/dev-plan{,/checkout,/confirm,/schedule,/receipts}`, key tools [api/keys/[id]/rotate.js](api/keys/%5Bid%5D/rotate.js), [allowlist.js](api/keys/%5Bid%5D/allowlist.js), [analytics.js](api/keys/%5Bid%5D/analytics.js); page [pages/developers.html](pages/developers.html) `→ /developers` + [public/developers.css](public/developers.css); dashboard Plan tab [src/dashboard-next/pages/developers-plan.js](src/dashboard-next/pages/developers-plan.js) `→ /dashboard/developers#plan`, key tools [src/dashboard-next/pages/api-key-tools.js](src/dashboard-next/pages/api-key-tools.js) | Live | Free, Builder, Scale, Enterprise. Monthly quota, burst and concurrency enforced at the gateway (429 + Retry-After, 402 `quota_exceeded` with the next plan). Upgrades in credits, USDC or $THREE on Solana, user wallet signs, proration, downgrade at period end, receipts. Migration `20261010230000_dev_plans.sql`. Doc [docs/developer-plans.md](docs/developer-plans.md) || Spend and token ceilings (`/spend`) | [pages/spend.html](pages/spend.html) `→ /spend` + [src/spend-page.js](src/spend-page.js), read model [api/spend/me.js](api/spend/me.js) `→ GET /api/me/spend`, ceilings [api/agents/_id/token-budget.js](api/agents/_id/token-budget.js) `→ /api/agents/:id/token-budget(/resume|/extend)` over [api/_lib/token-budgets.js](api/_lib/token-budgets.js), gate wired into `assertAgentBudget` in [api/_lib/inference-billing.js](api/_lib/inference-billing.js), counters [api/_lib/migrations/20261010173000_agent_token_budgets.sql](api/_lib/migrations/20261010173000_agent_token_budgets.sql), free-tier choices [api/_lib/free-tier.js](api/_lib/free-tier.js) | Live | Per-agent hourly, daily and per-run token ceilings enforced before the model call with one conditional upsert per window (two calls racing for the last token admit exactly one), next to the dollar budget. Hitting a ceiling pauses the agent, notifies the owner (`token_budget_paused`) and opens one extend-once approval (venue `token_budget`); resume refuses while the window is still full (`409 still_capped`). The spend page shows balance, month-to-date and projected month end, per-agent usage by day, model and tool, and every 50/80/100 percent alert (`spend_cap_alert`) from the same latches the bell uses. The free-tier `429 free_tier_exhausted` body carries `choices` (wait, top up, bring your own key, and a one-step `paid_fallback` on brain chat, copilot and v1 messages). Docs: [docs/inference-billing.md](docs/inference-billing.md). Tests: [tests/token-budgets.test.js](tests/token-budgets.test.js). || Agent lifecycle, runs and automations over MCP (Runs tab) | MCP tools [api/_mcp/tools/agent-lifecycle.js](api/_mcp/tools/agent-lifecycle.js) (`get_agent`, `update_agent`, `delete_agent`, `start_agent`, `stop_agent`, `upload_agent_avatar`, `create_agent_run`, `update_agent_run`, `cancel_agent_run`, `get_agent_run_steps`, `automation_list`, `automation_get`, `automation_create`, `automation_update`, `automation_delete`, `automation_trigger`) over the REST validators and engines in [api/_lib/agents-v1/](api/_lib/agents-v1) (runs, automations, run receipts), policy rows in [packages/mcp-policy/src/table.js](packages/mcp-policy/src/table.js); replay endpoint [api/agent-run-replay.js](api/agent-run-replay.js) `→ /api/agent-run-replay`; Runs tab [src/agent-run-replay.js](src/agent-run-replay.js), mounted from [src/avatar-page.js](src/avatar-page.js) on `/agents/:id?view=runs` | Built, ships with the next deploy | An MCP client can now edit, start, stop, re-skin and delete an agent, and drive autonomous runs and automations, with create and update validated by the same schemas as the REST path. `delete_agent` and `automation_delete` are destructive: refused without `confirm_delete` and a matching `get_agent` / `automation_get` preview. A run carries two budgets (model turns and dollars), honors cancel between steps, ends with a plain-language summary, and chains a sha256 receipt over every step; `get_agent_run_steps` returns each tool call paired with its result and receipt. The owner-only Runs tab lists every run, replays it step by step with a scrubber, polls a live run, verifies the receipt chain server-side, and cancels. Docs: [docs/mcp.md](docs/mcp.md) `→ /docs/mcp`, [docs/agent-runtime.md](docs/agent-runtime.md#autonomous-runs-budgets-receipts-and-replay). Tests: [tests/mcp-agent-lifecycle.test.js](tests/mcp-agent-lifecycle.test.js), [tests/agent-run-replay-endpoint.test.js](tests/agent-run-replay-endpoint.test.js) |+| Agents REST API (`/api/v1`) and webhooks | Router [api/v1/rest.js](api/v1/rest.js) over [api/_lib/agents-v1/](api/_lib/agents-v1) (http envelope, agents, runs, automations, skills, [webhooks.js](api/_lib/agents-v1/webhooks.js), [run-stream.js](api/_lib/agents-v1/run-stream.js), [agent-export.js](api/_lib/agents-v1/agent-export.js), [openapi.js](api/_lib/agents-v1/openapi.js)), delivery queue [api/_lib/webhook-dispatch.js](api/_lib/webhook-dispatch.js), retry cron [api/cron/webhook-deliveries.js](api/cron/webhook-deliveries.js), dashboard [src/dashboard-next/pages/developers.js](src/dashboard-next/pages/developers.js) `→ /dashboard/developers` | Built, ships with the next deploy | Agent CRUD, start/stop, sync chat and history, runs with resumable SSE, automations with trigger-now, skills, strategies, export/import, and HTTPS webhooks (`run.finished`, `automation.fired`, `message.received`, `approval.needed`) with HMAC signatures, 8-attempt backoff, a delivery log and replay. Cursor pagination, `{data, meta}` envelope, `Idempotency-Key`. Docs: [docs/api-reference.md](docs/api-reference.md#agents-api-v1), [docs/developer-platform.md](docs/developer-platform.md). Tests: [tests/api/v1-rest-router.test.js](tests/api/v1-rest-router.test.js), [tests/api/agent-export.test.js](tests/api/agent-export.test.js), [tests/api/run-stream.test.js](tests/api/run-stream.test.js), [tests/webhook-dispatch-signing.test.js](tests/webhook-dispatch-signing.test.js) || Agent mail (inbox, rules, send controls) | Page [pages/agent-mail.html](pages/agent-mail.html) `→ /agents/:id/mail` and `/agent-mail` + [src/agent-mail.js](src/agent-mail.js), REST [api/v1/agent-mail.js](api/v1/agent-mail.js) `→ /api/v1/agents/:id/mail/*`, MCP [api/_mcp/tools/mail.js](api/_mcp/tools/mail.js), service [api/_lib/mail/](api/_lib/mail) (service, controls, untrusted, rules, inbound, content rules, spam, threading), webhook [api/mail/inbound.js](api/mail/inbound.js), migration [api/_lib/migrations/20261010184500_agent_mail_controls.sql](api/_lib/migrations/20261010184500_agent_mail_controls.sql) | Built, ships with the next deploy; outside delivery waits on the `agents.three.ws` DNS records (owner) | Each agent can hold an address on `agents.three.ws`: quote-then-confirm mailbox creation and sends that show the exact recipients and body first, content rules, a per-agent recipient allowlist and daily send cap that only a signed-in owner can change, instant delivery between agent mailboxes, and received mail fenced as untrusted data on every surface. Owner rules turn matching mail into a read-only, zero-budget agent run, either at once or after a yes in /approvals. Docs: [docs/agent-mail.md](docs/agent-mail.md). Tests: [tests/agent-mail-controls.test.js](tests/agent-mail-controls.test.js) || Agent perps (perpetual futures desk) | Page [pages/agent-perps.html](pages/agent-perps.html) `→ /agents/:id/perps` and `/agent-perps` + [src/agent-perps.js](src/agent-perps.js) + [src/agent-perps.css](src/agent-perps.css), REST [api/v1/agents/[id]/perps/[...path].js](api/v1/agents/[id]/perps/[...path].js) over [api/_lib/perps/routes.js](api/_lib/perps/routes.js) `→ /api/v1/agents/:id/perps/*`, MCP [api/_mcpagent/perps-tools.js](api/_mcpagent/perps-tools.js) (`perps_*` on `/api/mcp-agent`), service [api/_lib/perps/service.js](api/_lib/perps/service.js), venue contract and registry [api/_lib/perps/index.js](api/_lib/perps/index.js), venue module [api/_lib/perps/phoenix.js](api/_lib/perps/phoenix.js), paper ledger [api/_lib/perps/paper.js](api/_lib/perps/paper.js), limits [api/_lib/perps/limits.js](api/_lib/perps/limits.js), alerts [api/_lib/perps/alerts.js](api/_lib/perps/alerts.js), cron [api/cron/perps-tick.js](api/cron/perps-tick.js), migration [api/_lib/migrations/20261010213000_perps_desk.sql](api/_lib/migrations/20261010213000_perps_desk.sql) | Built, ships with the next deploy (paper by default; live per agent once the owner turns it on) | An agent goes long or short with USDC collateral from its own Solana wallet. Every action is a preview then a confirmed, idempotent execute that refuses if the quote moved past tolerance. Mandatory per-agent leverage and per-position margin caps (2x and $25 by default), slippage and quote-move limits, a live tracker stream with PnL, funding and liquidation distance, owner alert thresholds delivered through notifications, and a kill switch that cancels and closes everything. Paper mode fills at live prices; live transactions are simulated before the agent wallet signs. Docs: [docs/perps.md](docs/perps.md). Tests: [tests/perps-desk.test.js](tests/perps-desk.test.js) || Papertrade reads (HyperEVM synthetic perps) | REST [api/papertrade.js](api/papertrade.js) `→ /api/papertrade?view=markets, quote, account or protocol`, MCP [api/_mcpagent/papertrade-tools.js](api/_mcpagent/papertrade-tools.js) (`papertrade_*` on `/api/mcp-agent`), client and service [api/_lib/papertrade/index.js](api/_lib/papertrade/index.js), position math [api/_lib/papertrade/math.js](api/_lib/papertrade/math.js) | Built, ships with the next deploy | Read-only window onto Papertrade: live markets priced at the Hyperliquid mid, exact open quotes (hard-bust price, capacity limits, and the payout ladder after the deadband, impact haircut and live win fee), any wallet's positions valued live, and protocol health including the payout queue. Nothing signs or trades. Docs: [docs/papertrade.md](docs/papertrade.md). Tests: [tests/papertrade-math.test.js](tests/papertrade-math.test.js) |diff --git a/api/_lib/agents-v1/agent-export.js b/api/_lib/agents-v1/agent-export.jsindex f4c84128e..94caa4b63 100644--- a/api/_lib/agents-v1/agent-export.js+++ b/api/_lib/agents-v1/agent-export.js@@ -47,10 +47,10 @@ export async function exportAgent(agent) {]);// Spend limits live on the backing wallet intent; read them so a re-import// keeps the same ceilings instead of falling back to defaults.- const limits = new Map();+ const spendLimits = new Map();for (const r of automations.filter((x) => x.intent_id)) {const full = await getAutomation(agent.user_id, r.id).catch(() => null);- if (full?.limits && Object.keys(full.limits).length) limits.set(r.id, full.limits);+ if (full?.limits && Object.keys(full.limits).length) spendLimits.set(r.id, full.limits);}return {format: EXPORT_FORMAT,@@ -73,7 +73,7 @@ export async function exportAgent(agent) {action: r.action_config,triggerOnce: r.trigger_once,enabled: r.enabled,- ...(limits.has(r.id) ? { limits: limits.get(r.id) } : {}),+ ...(spendLimits.has(r.id) ? { limits: spendLimits.get(r.id) } : {}),})),customSkills: skills.map(exportSkill),};diff --git a/api/_lib/agents-v1/openapi.js b/api/_lib/agents-v1/openapi.jsnew file mode 100644index 000000000..ad285fb6e--- /dev/null+++ b/api/_lib/agents-v1/openapi.js@@ -0,0 +1,192 @@+// OpenAPI paths for the v1 agents REST API (api/v1/rest.js).+//+// The operation list is read from the live route table, so a route added to+// rest.js shows up in /openapi.json with its method, path, auth and scope+// without anyone remembering to document it. This file adds what the table+// cannot know: a summary, the query parameters and the request body fields.+// A route with no entry in DOCS still appears, with a summary built from its+// name. Reference prose: docs/api-reference.md "Agents API (v1)".++import { ROUTES } from '../../v1/rest.js';++const TAG = {+ agents: 'Agents API',+ runs: 'Agents API',+ automations: 'Agents API',+ skills: 'Agents API',+ strategies: 'Agents API',+ webhooks: 'Agents API: webhooks',+ me: 'Agents API',+};++const cursor = { name: 'cursor', in: 'query', schema: { type: 'string' }, description: 'meta.nextCursor from the previous page.' };+const limit = (max = 100, dflt = 25) => ({+ name: 'limit',+ in: 'query',+ schema: { type: 'integer', minimum: 1, maximum: max, default: dflt },+ description: 'Page size.',+});+const str = (description, extra = {}) => ({ type: 'string', description, ...extra });++const AGENT_FIELDS = {+ name: str('Display name, up to 80 characters.'),+ persona: str('Short public description.'),+ systemPrompt: str('Instructions the agent follows on every turn.'),+ model: str('Model id from GET /api/v1/models.'),+ temperature: { type: 'number', minimum: 0, maximum: 2 },+ skills: { type: 'array', items: { type: 'string' }, description: 'Built-in skill ids from GET /api/v1/skills.' },+ strategy: str('Strategy preset id from GET /api/v1/strategies.'),+ inferenceBudget: {+ type: 'object',+ description: 'Credit ceilings in USD. Pass null to remove.',+ properties: { daily: { type: 'number' }, monthly: { type: 'number' } },+ },+};++const AUTOMATION_FIELDS = {+ title: str('Up to 80 characters; defaults to a description of the trigger and action.'),+ trigger: { type: 'object', description: 'One of: schedule (cron), price_threshold, balance_below, whale_buy and others listed in the guide.' },+ action: { type: 'object', description: 'One of: agent_prompt, notify, swap, transfer. swap and transfer spend funds: they need confirm: true and a key holding wallet:write.' },+ triggerOnce: { type: 'boolean' },+ limits: { type: 'object', description: 'Spend ceilings for swap and transfer actions.' },+ confirm: { type: 'boolean', description: 'Required for swap and transfer actions.' },+};++const WEBHOOK_FIELDS = {+ url: str('HTTPS endpoint that receives events.', { format: 'uri' }),+ events: { type: 'array', items: { type: 'string' }, description: 'Event types from GET /api/v1/webhooks/events. Empty means all.' },+ agentId: str('Limit the endpoint to one agent. Account events are then unavailable.', { format: 'uuid' }),+ description: str('Free text shown in the dashboard.'),+};++const body = (properties, required = []) => ({ properties, required });++// summary, query parameters and request body per route name.+const DOCS = {+ 'agents.list': { summary: 'List agents', query: [cursor, limit()] },+ 'agents.create': { summary: 'Create an agent', body: body(AGENT_FIELDS, ['name']) },+ 'agents.import': { summary: 'Create an agent from an export document', body: body({ document: { type: 'object' }, name: str('Overrides the exported name.'), confirm: { type: 'boolean', description: 'Also create exported swap and transfer automations (needs wallet:write).' } }) },+ 'agents.get': { summary: 'Get an agent' },+ 'agents.update': { summary: 'Update an agent (partial)', body: body(AGENT_FIELDS) },+ 'agents.delete': { summary: 'Delete an agent and its automations' },+ 'agents.export': { summary: 'Export an agent as portable JSON (no wallet, keys, memory or history)' },+ 'agents.start': { summary: 'Start an agent' },+ 'agents.stop': { summary: 'Stop an agent' },+ 'agents.messages.send': {+ summary: 'Send a message and wait for the reply',+ body: body({ message: str('The user message.'), model: str('Overrides the agent model for this call.'), temperature: { type: 'number' }, channel: str('Where the message came from.'), paid_fallback: { type: 'boolean' } }, ['message']),+ },+ 'agents.messages.list': { summary: 'List message history, newest first', query: [limit(), { name: 'before', in: 'query', schema: { type: 'string' }, description: 'meta.nextCursor from the previous page.' }] },+ 'runs.create': {+ summary: 'Start a run, or schedule a repeating one',+ body: body({+ goal: str('What the run should accomplish.'),+ maxSteps: { type: 'integer', minimum: 1, maximum: 60, default: 12 },+ budgetCreditsUsd: { type: 'number' },+ budgetUsd: { type: 'number', description: 'On-chain budget. Needs wallet:write.' },+ model: str('Model id.'),+ temperature: { type: 'number' },+ toolsAllowed: { type: 'array', items: { type: 'string' } },+ scheduledFor: str('ISO 8601 start time.', { format: 'date-time' }),+ schedule: str('Cron expression. Creates an automation that starts a run on that schedule.'),+ }, ['goal']),+ },+ 'runs.list': { summary: 'List an agent\'s runs', query: [cursor, limit(), { name: 'status', in: 'query', schema: { type: 'string' } }] },+ 'runs.get': { summary: 'Get a run' },+ 'runs.update': { summary: 'Pause, resume or raise limits of a run', body: body({ action: str('pause or resume.', { enum: ['pause', 'resume'] }), budgetCreditsUsd: { type: 'number' }, budgetUsd: { type: 'number' }, maxSteps: { type: 'integer' } }) },+ 'runs.cancel': { summary: 'Cancel a run' },+ 'runs.steps': { summary: 'List a run\'s steps', query: [cursor, { name: 'limit', in: 'query', schema: { type: 'integer', minimum: 1, maximum: 500, default: 200 } }] },+ 'runs.events': {+ summary: 'Stream a run as server-sent events',+ query: [+ { name: 'after', in: 'query', schema: { type: 'integer' }, description: 'Resume after this step seq. The Last-Event-ID header does the same.' },+ { name: 'drive', in: 'query', schema: { type: 'boolean', default: true }, description: 'Let the open stream step the run.' },+ { name: 'maxSeconds', in: 'query', schema: { type: 'integer', minimum: 5, maximum: 300 } },+ ],+ sse: true,+ },+ 'automations.create': { summary: 'Create an automation', body: body({ agentId: str('Owning agent.', { format: 'uuid' }), ...AUTOMATION_FIELDS }, ['agentId', 'trigger', 'action']) },+ 'automations.list': { summary: 'List automations across your agents', query: [cursor, limit()] },+ 'agents.automations.list': { summary: 'List one agent\'s automations', query: [cursor, limit()] },+ 'automations.get': { summary: 'Get an automation' },+ 'automations.update': { summary: 'Update an automation (partial)', body: body({ ...AUTOMATION_FIELDS, enabled: { type: 'boolean' } }) },+ 'automations.delete': { summary: 'Delete an automation' },+ 'automations.trigger': { summary: 'Run an automation now', body: body({ confirm: { type: 'boolean', description: 'Required when the action spends.' } }) },+ 'strategies.list': { summary: 'List strategy presets' },+ 'strategies.get': { summary: 'Get a strategy preset' },+ 'webhooks.events': { summary: 'List event types, the retry schedule and the signature format' },+ 'webhooks.list': { summary: 'List webhooks', query: [cursor, limit()] },+ 'webhooks.create': { summary: 'Create a webhook; the response carries its signing secret once', body: body(WEBHOOK_FIELDS, ['url']) },+ 'webhooks.get': { summary: 'Get a webhook with seven-day delivery stats' },+ 'webhooks.update': { summary: 'Update a webhook', body: body({ ...WEBHOOK_FIELDS, active: { type: 'boolean' } }) },+ 'webhooks.delete': { summary: 'Delete a webhook and its delivery log' },+ 'webhooks.rotate': { summary: 'Rotate the signing secret' },+ 'webhooks.test': { summary: 'Send a test event now and return the delivery' },+ 'webhooks.deliveries.list': {+ summary: 'List a webhook\'s delivery log',+ query: [cursor, limit(), { name: 'status', in: 'query', schema: { type: 'string', enum: ['pending', 'delivering', 'succeeded', 'failed'] } }, { name: 'eventType', in: 'query', schema: { type: 'string' } }],+ },+ 'webhooks.deliveries.get': { summary: 'Get a delivery with its payload and every attempt' },+ 'webhooks.deliveries.replay': { summary: 'Re-send a delivery as a new row with the same event id and payload' },+ 'v1.skills.list': { summary: 'List built-in skills' },+ 'v1.skills.community.list': { summary: 'List community skills', query: [cursor, limit()] },+ 'v1.skills.community.get': { summary: 'Get a community skill' },+ 'v1.agents.skills.custom.list': { summary: 'List an agent\'s custom skills' },+ 'v1.agents.skills.custom.create': { summary: 'Create a custom skill', body: body({ name: str('Skill name.'), description: str('What the skill does.'), content: str('Markdown instructions.'), tags: { type: 'array', items: { type: 'string' } }, version: str('Semver.'), enabled: { type: 'boolean' } }, ['name', 'content']) },+ 'v1.agents.skills.custom.import': { summary: 'Install a community skill on an agent', body: body({ slug: str('Community skill slug from GET /api/v1/skills/community.') }, ['slug']) },+ 'v1.agents.skills.custom.get': { summary: 'Get a custom skill' },+ 'v1.agents.skills.custom.update': { summary: 'Update a custom skill (partial)', body: body({ name: str('Skill name.'), description: str('What the skill does.'), content: str('Markdown instructions.'), tags: { type: 'array', items: { type: 'string' } }, version: str('Semver.'), enabled: { type: 'boolean' } }) },+ 'v1.agents.skills.custom.delete': { summary: 'Delete a custom skill' },+ 'me.get': { summary: 'Describe the caller: account, scopes and free-tier status' },+};++function titleFromName(name) {+ return name.replace(/^v1\./, '').replace(/\./g, ' ');+}++function operation(route) {+ const doc = DOCS[route.name] || {};+ const pathParams = [...route.path.matchAll(/:(\w+)/g)].map((m) => ({ name: m[1], in: 'path', required: true, schema: { type: 'string' } }));+ const writes = ['POST', 'PATCH', 'PUT'].includes(route.method);+ const op = {+ operationId: route.name.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()),+ summary: doc.summary || titleFromName(route.name),+ tags: [TAG[route.path.split('/')[1]] || 'Agents API'],+ security: route.auth === 'public' ? [] : [{ bearerAuth: [] }, { apiKeyAuth: [] }],+ parameters: [...pathParams, ...(doc.query || [])],+ responses: {+ 200: { description: doc.sse ? 'text/event-stream of step, status, done and reconnect events.' : 'The { data, meta: { requestId, timestamp } } envelope.' },+ ...(route.method === 'POST' && !doc.sse ? { 201: { description: 'Created. Same envelope.' } } : {}),+ 400: { description: 'invalid_parameter, bad_json or a route-specific validation code.' },+ ...(route.auth !== 'public' ? { 401: { description: 'unauthorized' }, 403: { description: 'insufficient_scope' } } : {}),+ 404: { description: 'not_found' },+ 429: { description: 'rate_limited, with Retry-After.' },+ },+ };+ if (route.scope) op['x-required-scope'] = route.scope;+ if (writes) {+ op.parameters.push({ name: 'Idempotency-Key', in: 'header', schema: { type: 'string', maxLength: 200 }, description: 'A retry with the same key and body replays the stored response for 24 hours.' });+ if (doc.body) {+ op.requestBody = {+ required: doc.body.required.length > 0,+ content: { 'application/json': { schema: { type: 'object', required: doc.body.required, properties: doc.body.properties } } },+ };+ }+ }+ return op;+}++/** OpenAPI `paths` for every route mounted by api/v1/rest.js. */+export function agentsV1Paths() {+ const paths = {};+ for (const route of ROUTES) {+ const key = `/api/v1${route.path.replace(/:(\w+)/g, '{$1}')}`;+ (paths[key] ||= {})[route.method.toLowerCase()] = operation(route);+ }+ return paths;+}++export const AGENTS_V1_TAGS = [+ { name: 'Agents API', description: 'Agents, chat, runs, automations, skills and strategies over plain HTTP with one bearer key. Guide: docs/api-reference.md "Agents API (v1)".' },+ { name: 'Agents API: webhooks', description: 'Signed event delivery with retries, a delivery log and replay. Guide: docs/developer-platform.md.' },+];diff --git a/api/openapi-json.js b/api/openapi-json.jsindex a4d255f1d..802a2b15f 100644--- a/api/openapi-json.js+++ b/api/openapi-json.js@@ -15,6 +15,7 @@ import { env } from './_lib/env.js';import { cors, json, method, wrap } from './_lib/http.js';import { providerCatalog } from './v1/_providers.js';import { PAID_SERVICES } from './_lib/service-catalog/services/index.js';+import { agentsV1Paths, AGENTS_V1_TAGS } from './_lib/agents-v1/openapi.js';// Single source of truth for the protocol list on every paid operation. Each// entry is one supported payment protocol; per-network payment lanes (Base /@@ -263,6 +264,7 @@ export default wrap(async (req, res) => {'rendered live from the provider registry (api/v1/_providers.js). See /crypto-api ' +'and docs/api-reference.md § Unified API.',},+ ...AGENTS_V1_TAGS,],components: {securitySchemes: {@@ -300,6 +302,7 @@ export default wrap(async (req, res) => {// Projected from the service catalog, spread before the hand-authored// operations below so a richer hand-written entry always wins....catalogPaidPaths(),+ ...agentsV1Paths(),'/api/mcp': {post: {operationId: 'mcp_call',diff --git a/data/changelog.json b/data/changelog.jsonindex 28972d342..1c7697140 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -29600,6 +29600,13 @@"summary": "The MCP tool catalog now shows the real totals for every server, worked out from the live servers with a plain note on how, and a release view that lists which tools each release added. Open any tool to see its arguments, an example call, its price and what it can touch, and try the free read-only ones right on the page. You can filter the catalog by category. Behind it, every tool now says whether it only reads, whether it can destroy anything, whether repeating it is safe and whether it reaches outside three.ws, and every tool says when to use it. Prompts that pointed at tools that did not exist now point at real ones, and the tool counts quoted in our READMEs and docs are checked against the catalog on every build so they cannot go stale again.","tags": ["feature", "improvement"],"link": "/mcp-tools"+ },+ {+ "date": "2026-10-10",+ "title": "A complete REST API for agents, with signed webhooks",+ "summary": "Everything you can do with an agent in the app now works over plain HTTP with one API key: create and edit agents, start and stop them, chat, start runs and watch them live, schedule automations and fire them on demand, manage skills, and export or import an agent. Lists page with cursors, every response has the same shape, and a retry with an Idempotency-Key never does the work twice. Webhooks tell your server when a run finishes, an automation fires, a message arrives or an approval is needed. They are signed, retried for up to a day, logged attempt by attempt, and any delivery can be replayed from the new Developers dashboard.",+ "tags": ["feature", "sdk"],+ "link": "/docs/api-reference"}]}diff --git a/docs/api-reference.md b/docs/api-reference.mdindex f1d09433d..0df89ef82 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -10116,3 +10116,81 @@ const { agents } = await res.json();- [x402](/docs/x402): how the paid `/api/x402/*` endpoints settle in USDC- [Payment sessions](/docs/payment-sessions): the buyer side, letting an agent spend a budget without holding a key- [Authentication](/docs/authentication): SIWE, sessions, API keys, and scopes++## Agents API (v1)++`/api/v1` is the stable, key-friendly face of the agent platform: create and+run agents, chat with them, start autonomous runs, manage automations and skills,+and receive signed webhooks, all with one bearer key. The full machine-readable+contract is in [/openapi.json](/openapi.json) under the tags `Agents API` and+`Agents API: webhooks`.++**Auth.** `Authorization: Bearer <key>` with an API key from+`/dashboard/api`, or a signed-in session (writes then need the CSRF token).+Scopes: `agents:read` for GETs, `agents:write` for everything that changes+state. Anything that moves funds (a `swap` or `transfer` automation, a run with+`budgetUsd`) additionally needs `wallet:write` and an explicit `confirm: true`;+an import never spends on its own.++**Envelope.** Every response is `{ "data": …, "meta": { "requestId", "timestamp" } }`+(`meta.nextCursor` on lists; pass it back as `cursor`, or `before` for message+history). Errors are `{ "error": { "code", "message", "details" }, "meta" }`.++| Status | `error.code` | Meaning |+|---|---|---|+| 400 | `invalid_parameter`, `bad_json`, `validation_error` | Body or query failed validation; `details` names the field |+| 401 | `unauthorized` | No or invalid key/session |+| 403 | `insufficient_scope`, `csrf_invalid`, `confirmation_required` | Key lacks the scope (`details.required`), CSRF missing, or a spend was not confirmed |+| 404 | `not_found` | Unknown id, not yours, or not a UUID |+| 405 | `method_not_allowed` | Known path, wrong method |+| 409 | `conflict` | State forbids it, for example cancelling a finished run |+| 422 | `idempotency_key_reused` | Same `Idempotency-Key` sent with a different body |+| 429 | `rate_limited` | Honor `Retry-After` |++**Idempotency.** Send `Idempotency-Key: <unique string>` on any POST/PATCH. A+retry with the same key and body replays the stored response for 24 hours and+adds `Idempotent-Replayed: true`.++### Routes++| Resource | Routes |+|---|---|+| Agents | `GET/POST /agents`, `GET/PATCH/DELETE /agents/:id`, `POST /agents/:id/start`, `POST /agents/:id/stop`, `GET /agents/:id/export`, `POST /agents/import` |+| Chat | `POST /agents/:id/messages` (body `{ "message" }`, waits for the reply), `GET /agents/:id/messages` |+| Runs | `POST/GET /agents/:id/runs`, `GET/PATCH /runs/:id` (`action: pause\|resume`, budgets can only rise), `POST /runs/:id/cancel`, `GET /runs/:id/steps`, `GET /runs/:id/events` (SSE, resumable with `Last-Event-ID`) |+| Automations | `POST/GET /automations`, `GET /agents/:id/automations`, `GET/PATCH/DELETE /automations/:id`, `POST /automations/:id/trigger` |+| Skills | `GET /skills`, `GET /skills/community[/:slug]`, `GET/POST /agents/:id/skills/custom`, `POST /agents/:id/skills/custom/import`, `GET/PATCH/DELETE /agents/:id/skills/custom/:skillId` |+| Webhooks | `GET/POST /webhooks`, `GET/PATCH/DELETE /webhooks/:id`, `POST /webhooks/:id/rotate-secret`, `POST /webhooks/:id/test`, `GET /webhooks/:id/deliveries`, `GET /webhooks/deliveries/:id`, `POST /webhooks/deliveries/:id/replay`, `GET /webhooks/events` |+| Other | `GET /strategies[/:id]`, `GET /models`, `GET /me` |++Passing `schedule` (a cron expression) to `POST /agents/:id/runs` creates an+automation that starts the run on that schedule and returns it.++### Example++```bash+KEY=sk_live_… # agents:read agents:write+curl -s https://three.ws/api/v1/agents \+ -H "authorization: Bearer $KEY" -H 'content-type: application/json' \+ -H 'idempotency-key: create-scout-1' \+ -d '{"name":"Scout","systemPrompt":"Be terse."}'++curl -s https://three.ws/api/v1/agents/$AGENT/messages \+ -H "authorization: Bearer $KEY" -H 'content-type: application/json' \+ -d '{"message":"What changed on-chain today?"}'++curl -N https://three.ws/api/v1/runs/$RUN/events -H "authorization: Bearer $KEY"+```++### Webhooks++Events: `run.finished`, `automation.fired`, `message.received`,+`approval.needed` (agent-scoped, so an endpoint pinned to one agent receives+only that agent's) plus the account events listed by `GET /webhooks/events`.+URLs must be HTTPS and resolve to a public address. Deliveries follow the+[Standard Webhooks](https://www.standardwebhooks.com) headers; see+[developer-platform.md](developer-platform.md#delivery-format-and-signature-verification)+for verification code. A failed delivery retries after 30s, 2m, 10m, 30m, 1h, 3h+and 8h (8 attempts total) and every attempt is kept in the delivery log; replay+a delivery from the log or the `/dashboard/developers` page. The signing secret+(`whsec_…`) is shown once at creation and on `rotate-secret`.diff --git a/docs/developer-platform.md b/docs/developer-platform.mdindex 8e7876d8b..8745e6f18 100644--- a/docs/developer-platform.md+++ b/docs/developer-platform.md@@ -466,7 +466,7 @@ Deliveries are `POST` requests in the| `content-type` | `application/json` || `webhook-id` | unique event ID (`evt_…`), stable across retries || `webhook-timestamp` | unix epoch seconds |-| `webhook-signature` | `v1,{base64url HMAC-SHA256}` |+| `webhook-signature` | `v1,{spec signature} v1,{legacy signature}`, space separated; accept either || `user-agent` | `three.ws-webhooks/1.0` |Body:@@ -481,7 +481,7 @@ Body:```The signature is HMAC-SHA256 over `` `${id}.${timestamp}.${rawBody}` `` keyed-with your `whsec_` secret, encoded as unpadded base64url. Verify it against the+with your `whsec_` secret. The spec signature decodes the secret as base64 and encodes the result as base64; the legacy signature keys on the secret string and encodes base64url. Official Standard Webhooks libraries verify the first. Verify it against the**raw** request body, before any JSON parsing:```js@@ -499,7 +499,7 @@ function verifyWebhook(secret, headers, rawBody) {Delivery behavior, exactly as implemented:-- Up to **3 attempts** with exponential backoff, 10-second timeout per attempt.+- Up to **8 attempts**: the first immediately, then after 30 seconds, 2 minutes, 10 minutes, 30 minutes, 1 hour, 3 hours and 8 hours. 10-second timeout per attempt. Every attempt is logged and any delivery can be replayed (`POST /api/v1/webhooks/deliveries/:id/replay`, or the replay button on `/dashboard/developers`); a replay keeps the event id and payload.- Redirects are **not followed**; a 3xx is recorded as a failure(`redirect_not_followed`).- Response bodies are stored truncated to 1024 characters for the deliveries