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(mcp): manage agents, runs and automations from any MCP client
nirholas3e5e46f8e55f
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.jsindex d546ab363..986f1fbf0 100644--- a/api/_mcp/catalog.js+++ b/api/_mcp/catalog.js@@ -23,6 +23,7 @@ import { toolDefs as homeDefs } from './tools/home.js';import { toolDefs as libraryDefs } from './tools/library.js';import { toolDefs as cardDefs } from './tools/cards.js';import { toolDefs as pairedDefs } from './tools/paired.js';+import { toolDefs as agentLifecycleDefs } from './tools/agent-lifecycle.js';import { toolDefs as customSkillDefs } from './tools/custom-skills.js';import { toolDefs as resourceDefs } from './tools/resources.js';@@ -49,6 +50,7 @@ const baseDefs = [...resourceDefs,...cardDefs,...pairedDefs,+ ...agentLifecycleDefs,];// Free, public entry point — listed first so discovery clients see it up top.diff --git a/api/_mcp/tools/agent-lifecycle.js b/api/_mcp/tools/agent-lifecycle.jsnew file mode 100644index 000000000..732681b04--- /dev/null+++ b/api/_mcp/tools/agent-lifecycle.js@@ -0,0 +1,831 @@+// Agent lifecycle, runs and automations over MCP.+//+// Everything an owner can do to an agent from the dashboard, as tools: edit+// it, start and stop it, give it a body or a portrait, delete it, hand it a+// goal to pursue on its own (a run), watch that run step by step with a+// receipt per tool call, and wire it to triggers (automations).+//+// These tools are a thin MCP skin over api/_lib/agents-v1: update_agent calls+// updateAgent and automation_create calls createAutomation, so the REST path+// and MCP validate with the same code and can never disagree about what a+// valid agent or automation is.+//+// Money: runs use a read-only tool registry and can never sign. A swap or+// transfer automation spends from the agent wallet later, on its own, so+// creating, editing or firing one refuses a connector key, needs wallet:write,+// and needs confirm_spend: true after the tool has shown the recipient, amount,+// asset and chain. Execution still passes the wallet-intent spend policy.++import { sql } from '../../_lib/db.js';+import { limits } from '../../_lib/rate-limit.js';+import { logAudit } from '../../_lib/audit.js';+import { hasScope } from '../../_lib/auth.js';+import { env } from '../../_lib/env.js';+import { putObject, publicUrl } from '../../_lib/r2.js';+import { fetchSafePublicUrl, SsrfBlockedError } from '../../_lib/ssrf-guard.js';+import { isValidGlbHeader, inspectGlb } from '../../_lib/glb-inspect.js';+import { storageKeyFor, createAvatar, defaultAvatarVisibilityFor, isPlanLimitError } from '../../_lib/avatars.js';+import { maybeAutoRigAvatar } from '../../_lib/auto-rig.js';+import { getSolanaAddressBalances } from '../../_lib/agent-wallet.js';+import { ApiError } from '../../_lib/agents-v1/http.js';+import { loadOwnedAgent, updateAgent, deleteAgent, setAgentStatus, serializeAgent } from '../../_lib/agents-v1/agents.js';+import {+ createRun,+ getOwnedRun,+ listRunSteps,+ cancelRun,+ updateRun,+ driveRun,+ serializeRun,+ TERMINAL_RUN_STATUSES,+} from '../../_lib/agents-v1/runs.js';+import { toolTraces, verifyReceiptChain } from '../../_lib/agents-v1/run-receipts.js';+import {+ TRIGGER_TYPES,+ ACTION_TYPES,+ normalizeAutomation,+ createAutomation,+ getAutomation,+ updateAutomation,+ deleteAutomation,+ triggerAutomation,+ listAgentAutomations,+ listUserAutomations,+} from '../../_lib/agents-v1/automations.js';+import { connectorSpendError } from '../policy.js';++const SPEND_ACTIONS = new Set(['swap', 'transfer']);+const MAX_GLB_BYTES = 64 * 1024 * 1024;+const MAX_IMAGE_BYTES = 10 * 1024 * 1024;+const MAX_WAIT_SECONDS = 25;+const SOLANA_MAINNET = 'Solana mainnet';++const UUID = { type: 'string', format: 'uuid' };+const AGENT_ID = { ...UUID, description: 'The agent id (from list_my_agents or create_agent).' };+const RUN_ID = { ...UUID, description: 'The run id (from create_agent_run).' };+const AUTOMATION_ID = { ...UUID, description: 'The automation id (from automation_list or automation_create).' };+const WAIT = {+ type: 'integer',+ minimum: 0,+ maximum: MAX_WAIT_SECONDS,+ default: 15,+ description: `Seconds to drive the run inline before returning (0 to ${MAX_WAIT_SECONDS}). A run that is not done keeps going on the per-minute run cron; read it back with get_agent_run_steps.`,+};++const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };+const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };+const IDEMPOTENT_WRITE = { ...WRITE, idempotentHint: true };+const DESTRUCTIVE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };++const TRIGGER_DOC =+ 'trigger.type is one of: price_threshold { mint, operator: "above"|"below", priceUsd }, schedule { cron (5-field UTC, at most every 5 minutes) }, ' ++ 'balance_below { thresholdSol }, tip_received { minSol? }, launch_matching { creator?, maxMcapUsd?, minMcapUsd? } (creator or maxMcapUsd required), ' ++ 'graduation { mint? }, whale_buy { mint, minSol }. Any trigger takes cooldownMinutes.';+const ACTION_DOC =+ 'action.type is one of: agent_prompt { prompt, maxSteps? (1-30), budgetCreditsUsd? (0-100) } which starts a run, ' ++ 'swap { mint (omit on launch_matching/graduation to buy the coin the event names), amountSol, slippagePct? } and transfer { destination (address or .sol name), amountSol } which spend from the agent wallet, ' ++ 'and notify { message? } which emails the owner.';++function toolResult(structured, { isError = false, text = null } = {}) {+ return {+ content: [{ type: 'text', text: text ? `${text}\n\n${JSON.stringify(structured, null, 2)}` : JSON.stringify(structured, null, 2) }],+ structuredContent: structured,+ ...(isError ? { isError: true } : {}),+ };+}++function designedError(status, message, extra = {}) {+ return toolResult({ status, error: status, message, ...extra }, { isError: true, text: message });+}++function signInRequired(what) {+ return designedError('sign_in_required', `Sign in to three.ws to ${what}. Connect with an account (OAuth) or an API key.`);+}++/**+ * Run a lib call and turn its ApiError into a designed tool error, so the+ * model reads the same stable code and message a REST client would get.+ */+async function api(fn) {+ try {+ return await fn();+ } catch (err) {+ if (err instanceof ApiError) {+ return { __error: designedError(err.code, err.message, { http_status: err.status, ...(err.details ? { details: err.details } : {}) }) };+ }+ throw err;+ }+}++const failed = (r) => r && typeof r === 'object' && '__error' in r;++/** Optional fields from MCP snake_case onto the REST body's camelCase. */+function pick(args, map) {+ const out = {};+ for (const [from, to] of Object.entries(map)) {+ if (Object.hasOwn(args, from)) out[to] = args[from];+ }+ return out;+}++// ── spend gate ───────────────────────────────────────────────────────────────++/** Refuse a connector key, or a bearer without wallet:write, before any spend config is touched. */+function assertMaySpend(auth, toolName) {+ if (auth?.connector) throw connectorSpendError(toolName);+ if (!hasScope(auth?.scope, 'wallet:write')) {+ return designedError(+ 'insufficient_scope',+ 'This automation spends from the agent wallet, so the connection needs the wallet:write scope. Reconnect with wallet access, or use an agent_prompt or notify action.',+ );+ }+ return null;+}++/** The recipient, amount, asset and chain a spend action will move, for the owner to approve. */+function spendTerms(action, trigger, limitsCfg = {}) {+ const terms = {+ action: action.type,+ recipient:+ action.type === 'transfer'+ ? action.destination+ : action.mint+ ? `Swap into token ${action.mint} (the agent wallet receives the tokens)`+ : 'Swap into the coin named by each matching trigger event (the agent wallet receives the tokens)',+ amount: `${action.amountSol} SOL per fire`,+ asset: 'SOL',+ chain: SOLANA_MAINNET,+ when: trigger,+ };+ if (action.type === 'swap') terms.slippage = `${action.slippagePct ?? 5}%`;+ const caps = Object.entries(limitsCfg || {}).map(([k, v]) => `${k} $${v}`);+ if (caps.length) terms.caps = caps.join(', ');+ return terms;+}++function spendConfirmation(toolName, terms, extra = {}) {+ const lines = [+ `${toolName} would let this agent spend on its own. Show the owner these terms and call again with confirm_spend: true only after they clearly say yes:`,+ ` Recipient: ${terms.recipient}`,+ ` Amount: ${terms.amount}`,+ ` Asset: ${terms.asset}`,+ ` Chain: ${terms.chain}`,+ ];+ if (terms.slippage) lines.push(` Slippage: ${terms.slippage}`);+ if (terms.caps) lines.push(` Caps: ${terms.caps}`);+ return toolResult(+ { status: 'confirmation_required', error: 'confirmation_required', confirm_flag: 'confirm_spend', terms, ...extra },+ { isError: true, text: lines.join('\n') },+ );+}++/** Resolve a transfer destination for display only; createAutomation resolves it again for real. */+async function displayDestination(action) {+ if (action.type !== 'transfer') return action;+ try {+ const { resolveSolanaRecipient } = await import('../../../src/solana/sns.js');+ const r = await resolveSolanaRecipient(action.destination);+ if (r?.address && r.address !== action.destination) return { ...action, destination: `${action.destination} (${r.address})` };+ } catch {+ // Unresolvable names are refused by createAutomation with a designed error.+ }+ return action;+}++// ── run helpers ──────────────────────────────────────────────────────────────++/** Drive a run inline for up to `seconds`, then return its fresh row. */+async function driveFor(runId, userId, seconds) {+ const s = Math.min(MAX_WAIT_SECONDS, Math.max(0, Number(seconds) || 0));+ if (s > 0) await driveRun(runId, { deadlineMs: s * 1000 });+ return getOwnedRun(runId, userId);+}++function runView(row) {+ const run = serializeRun(row);+ const live = !TERMINAL_RUN_STATUSES.has(row.status);+ return {+ run,+ live,+ replay_url: `${env.APP_ORIGIN}/agents/${row.agent_id}?view=runs&run=${row.id}`,+ next: live+ ? 'The run keeps going on the per-minute run cron. Read progress with get_agent_run_steps; stop it with cancel_agent_run (it stops before its next step).'+ : run.summary || `The run ${row.status}.`,+ };+}++// ── avatar ingest ────────────────────────────────────────────────────────────++/** Bytes from a data: URI or bare base64 string. */+function decodeData(data) {+ const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(data);+ if (m) return { buf: m[2] ? Buffer.from(m[3], 'base64') : Buffer.from(decodeURIComponent(m[3]), 'utf8'), declared: m[1] || null };+ return { buf: Buffer.from(data.replace(/\s+/g, ''), 'base64'), declared: null };+}++/** The image type of a buffer from its magic bytes, or null. */+function sniffImage(buf) {+ if (buf.length < 12) return null;+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return { ext: 'png', type: 'image/png' };+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return { ext: 'jpg', type: 'image/jpeg' };+ if (buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', type: 'image/webp' };+ if (buf.toString('ascii', 0, 4) === 'GIF8') return { ext: 'gif', type: 'image/gif' };+ return null;+}++async function fetchUpload(url) {+ let resp;+ try {+ resp = await fetchSafePublicUrl(url, {}, { allowHttp: false });+ } catch (err) {+ if (err instanceof SsrfBlockedError) return { error: designedError('invalid_url', 'url must be a public https URL.') };+ return { error: designedError('fetch_failed', 'Could not fetch that URL. Check the link and try again.') };+ }+ if (!resp.ok) return { error: designedError('fetch_failed', `That URL answered ${resp.status}.`) };+ const declared = Number(resp.headers.get('content-length') || 0);+ if (declared > MAX_GLB_BYTES) return { error: designedError('payload_too_large', `That file is ${declared} bytes; the limit is ${MAX_GLB_BYTES}.`) };+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > MAX_GLB_BYTES) return { error: designedError('payload_too_large', `That file is ${buf.length} bytes; the limit is ${MAX_GLB_BYTES}.`) };+ return { buf };+}++async function attachGlb({ auth, agent, buf, sourceUrl, name, visibility }) {+ if (!hasScope(auth.scope, 'avatars:write')) {+ return designedError('insufficient_scope', 'Saving a 3D body to your library needs the avatars:write scope.');+ }+ const info = inspectGlb(buf) || {};+ const slug = `agent-${Math.random().toString(36).slice(2, 8)}`;+ const storageKey = storageKeyFor({ userId: auth.userId, slug });+ let avatar;+ try {+ await putObject({ key: storageKey, body: buf, contentType: 'model/gltf-binary', metadata: { source: 'mcp', user_id: auth.userId } });+ avatar = await createAvatar({+ userId: auth.userId,+ storageKey,+ input: {+ slug,+ name: (name || agent.name || 'Agent body').slice(0, 80),+ description: null,+ size_bytes: buf.length,+ content_type: 'model/gltf-binary',+ source: 'mcp',+ source_meta: {+ source_glb_url: sourceUrl,+ uploaded_for_agent: agent.id,+ is_rigged: typeof info.isRigged === 'boolean' ? info.isRigged : null,+ mesh_count: info.meshCount ?? null,+ animation_count: info.animationCount ?? null,+ },+ visibility: visibility || (await defaultAvatarVisibilityFor(auth.userId, 'unlisted')),+ tags: [],+ checksum_sha256: null,+ parent_avatar_id: null,+ },+ });+ } catch (err) {+ if (isPlanLimitError(err)) return designedError(err.code, err.message, { upgrade_url: `${env.APP_ORIGIN}/pricing` });+ throw err;+ }+ await sql`UPDATE agent_identities SET avatar_id = ${avatar.id}, updated_at = now() WHERE id = ${agent.id}`;+ // A static mesh is rigged in the background so the body can animate; the+ // rig decision reads the server-side inspection, never the caller.+ queueMicrotask(() =>+ maybeAutoRigAvatar({+ userId: auth.userId,+ avatar,+ rigInfo: { is_rigged: info.isRigged === true, skeleton_joint_count: info.skeletonJointCount ?? null },+ source: 'mcp',+ visibility: avatar.visibility,+ prompt: null,+ }),+ );+ logAudit({ userId: auth.userId, action: 'upload_agent_avatar', resourceId: agent.id, meta: { kind: 'glb', avatar_id: avatar.id, bytes: buf.length } });+ return toolResult({+ status: 'attached',+ kind: 'glb',+ agent_id: agent.id,+ avatar_id: avatar.id,+ model_url: avatar.model_url,+ rigged: info.isRigged === true,+ auto_rig: info.isRigged === true ? 'not needed' : 'queued: the body is rigged in the background so it can animate',+ agent_url: `${env.APP_ORIGIN}/agents/${agent.id}`,+ avatar_url: `${env.APP_ORIGIN}/avatars/${avatar.id}`,+ });+}++async function attachImage({ auth, agent, buf, kind }) {+ if (buf.length > MAX_IMAGE_BYTES) return designedError('payload_too_large', `Portrait images are capped at ${MAX_IMAGE_BYTES} bytes.`);+ const key = `u/${auth.userId}/agent-images/${agent.id}/${Date.now().toString(36)}.${kind.ext}`;+ await putObject({ key, body: buf, contentType: kind.type, metadata: { source: 'mcp', user_id: auth.userId, agent_id: agent.id } });+ const url = publicUrl(key);+ await sql`UPDATE agent_identities SET profile_image_url = ${url}, updated_at = now() WHERE id = ${agent.id}`;+ logAudit({ userId: auth.userId, action: 'upload_agent_avatar', resourceId: agent.id, meta: { kind: 'image', bytes: buf.length } });+ return toolResult({+ status: 'attached',+ kind: 'image',+ agent_id: agent.id,+ profile_image_url: url,+ agent_url: `${env.APP_ORIGIN}/agents/${agent.id}`,+ note: 'The image is now the agent portrait (cards, leaderboards, share images). To give the agent a 3D body, upload a GLB.',+ });+}++// ── tools ────────────────────────────────────────────────────────────────────++export const toolDefs = [+ {+ name: 'get_agent',+ title: 'Get one agent you own',+ annotations: READ,+ description:+ "Read one of your agents: its settings, status, wallet, and everything deleting it would destroy (open runs, automations, memories, logged actions, wallet balance). Call this before delete_agent and show the user the result: its preview_id authorizes the delete.",+ inputSchema: {+ type: 'object',+ properties: { agent_id: AGENT_ID },+ required: ['agent_id'],+ additionalProperties: false,+ },+ scope: 'agents:read',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('read your agents');+ const row = await api(() => loadOwnedAgent(args.agent_id, auth.userId));+ if (failed(row)) return row.__error;+ const agent = serializeAgent(row);+ const [[counts], recent] = await Promise.all([+ sql`+ SELECT+ (SELECT count(*)::int FROM agent_runs WHERE agent_id = ${row.id} AND status IN ('scheduled', 'queued', 'running', 'paused')) AS open_runs,+ (SELECT count(*)::int FROM agent_automations WHERE agent_id = ${row.id} AND enabled) AS enabled_automations,+ (SELECT count(*)::int FROM agent_automations WHERE agent_id = ${row.id}) AS automations,+ (SELECT count(*)::int FROM agent_memories WHERE agent_id = ${row.id}) AS memories,+ (SELECT count(*)::int FROM agent_actions WHERE agent_id = ${row.id}) AS actions+ `,+ sql`SELECT id, goal, status, summary, created_at FROM agent_runs WHERE agent_id = ${row.id} ORDER BY created_at DESC LIMIT 5`,+ ]);+ const balance = agent.wallet.solana ? await getSolanaAddressBalances(agent.wallet.solana, 'mainnet') : null;+ const funded = balance && ((balance.sol || 0) > 0 || (balance.usdc || 0) > 0);+ return toolResult({+ agent,+ counts,+ wallet_balance: balance,+ recent_runs: recent.map((r) => ({ id: r.id, goal: r.goal.slice(0, 200), status: r.status, summary: r.summary, created_at: r.created_at })),+ delete_impact:+ `Deleting ${agent.name} cancels ${counts.open_runs} open run(s), switches off ${counts.enabled_automations} automation(s), and permanently erases ${counts.memories} memories and ${counts.actions} logged actions.` ++ (funded ? ' Its wallet still holds funds: withdraw them first from the agent wallet page.' : ''),+ });+ },+ },+ {+ name: 'update_agent',+ title: 'Edit an agent you own',+ annotations: IDEMPOTENT_WRITE,+ description:+ 'Change an agent\'s settings. Pass only the fields to change. Validated by the same code as the REST API: name (1-80 chars), persona (public one-liner, up to 500), system_prompt (up to 8000), model (an id from the model catalog that supports tools), temperature (0-2), skills (up to 30 skill ids), strategy (a strategy preset id, or null to clear), inference_budget ({ daily, monthly } credit caps in USD, or null to remove).',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ name: { type: 'string', minLength: 1, maxLength: 80 },+ persona: { type: ['string', 'null'], maxLength: 500 },+ system_prompt: { type: ['string', 'null'], maxLength: 8000 },+ model: { type: ['string', 'null'] },+ temperature: { type: ['number', 'null'], minimum: 0, maximum: 2 },+ skills: { type: 'array', items: { type: 'string' }, maxItems: 30 },+ strategy: { type: ['string', 'null'] },+ inference_budget: {+ type: ['object', 'null'],+ properties: { daily: { type: ['number', 'null'], minimum: 0 }, monthly: { type: ['number', 'null'], minimum: 0 } },+ additionalProperties: false,+ },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('edit your agents');+ const body = pick(args, {+ name: 'name',+ persona: 'persona',+ system_prompt: 'systemPrompt',+ model: 'model',+ temperature: 'temperature',+ skills: 'skills',+ strategy: 'strategy',+ inference_budget: 'inferenceBudget',+ });+ if (!Object.keys(body).length) return designedError('nothing_to_update', 'Pass at least one field to change.');+ const out = await api(async () => updateAgent(await loadOwnedAgent(args.agent_id, auth.userId), body));+ if (failed(out)) return out.__error;+ logAudit({ userId: auth.userId, action: 'update_agent', resourceId: args.agent_id, meta: { fields: Object.keys(body) } });+ return toolResult({ status: 'updated', agent: out, changed: Object.keys(args).filter((k) => k !== 'agent_id') });+ },+ },+ {+ name: 'delete_agent',+ title: 'Delete an agent you own',+ annotations: DESTRUCTIVE,+ description:+ 'Delete an agent. Its open runs are cancelled, its automations are switched off, and its memories and logged actions are erased for good. Call get_agent first, show the user its delete_impact, and only after they clearly say yes call this with the preview_id and confirm_delete: true. Without confirm_delete the call is refused.',+ inputSchema: {+ type: 'object',+ properties: { agent_id: AGENT_ID },+ required: ['agent_id'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('delete your agents');+ const out = await api(async () => deleteAgent(await loadOwnedAgent(args.agent_id, auth.userId)));+ if (failed(out)) return out.__error;+ logAudit({ userId: auth.userId, action: 'delete_agent', resourceId: args.agent_id, meta: { via: 'mcp' } });+ return toolResult({ status: 'deleted', agent_id: args.agent_id });+ },+ },+ {+ name: 'start_agent',+ title: 'Start an agent',+ annotations: IDEMPOTENT_WRITE,+ description:+ 'Set an agent to running. Its automations fire again, its strategy loop ticks again, and its paused runs can be resumed. Starting a running agent is a no-op.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID }, required: ['agent_id'], additionalProperties: false },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('start your agents');+ const out = await api(async () => setAgentStatus(await loadOwnedAgent(args.agent_id, auth.userId), 'running'));+ if (failed(out)) return out.__error;+ logAudit({ userId: auth.userId, action: 'start_agent', resourceId: args.agent_id, meta: { via: 'mcp' } });+ return toolResult({ status: 'running', agent: out });+ },+ },+ {+ name: 'stop_agent',+ title: 'Stop an agent',+ annotations: IDEMPOTENT_WRITE,+ description:+ 'Set an agent to stopped. Its automations stop firing, its strategy loop stops ticking, and its runs hold before their next step until it is started again. Nothing is deleted.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID }, required: ['agent_id'], additionalProperties: false },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('stop your agents');+ const out = await api(async () => setAgentStatus(await loadOwnedAgent(args.agent_id, auth.userId), 'stopped'));+ if (failed(out)) return out.__error;+ logAudit({ userId: auth.userId, action: 'stop_agent', resourceId: args.agent_id, meta: { via: 'mcp' } });+ return toolResult({ status: 'stopped', agent: out });+ },+ },+ {+ name: 'upload_agent_avatar',+ title: 'Give an agent a 3D body or a portrait',+ annotations: { ...WRITE, openWorldHint: true },+ description:+ 'Upload a GLB or an image for an agent, from a public https url or inline data (a data: URI or base64, up to about 1.4 MB; use url for anything bigger). A GLB is saved to your avatar library through the normal avatar ingest, attached as the agent\'s 3D body, and auto-rigged in the background if it arrived static. A PNG, JPEG, WebP or GIF becomes the agent\'s portrait image. Pass exactly one of url or data.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ url: { type: 'string', format: 'uri', maxLength: 2048, description: 'Public https URL of a .glb or an image.' },+ data: { type: 'string', maxLength: 2_000_000, description: 'The file inline, as a data: URI or base64.' },+ name: { type: 'string', maxLength: 80, description: 'Name for the saved avatar (GLB only). Defaults to the agent name.' },+ visibility: { type: 'string', enum: ['public', 'unlisted', 'private'], description: 'Avatar visibility (GLB only). Defaults to your account default.' },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('upload an agent avatar');+ if (!args.url === !args.data) return designedError('invalid_request', 'Pass exactly one of url or data.');+ const agent = await api(() => loadOwnedAgent(args.agent_id, auth.userId));+ if (failed(agent)) return agent.__error;+ const rl = await limits.upload(auth.userId);+ if (!rl.success) return designedError('rate_limited', 'Too many uploads this hour. Try again shortly.');++ let buf;+ if (args.url) {+ const got = await fetchUpload(args.url);+ if (got.error) return got.error;+ buf = got.buf;+ } else {+ buf = decodeData(args.data).buf;+ if (!buf.length) return designedError('invalid_data', 'data decoded to zero bytes. Send a data: URI or base64.');+ }+ if (isValidGlbHeader(buf)) return attachGlb({ auth, agent, buf, sourceUrl: args.url || null, name: args.name, visibility: args.visibility });+ const kind = sniffImage(buf);+ if (kind) return attachImage({ auth, agent, buf, kind });+ return designedError('unsupported_file', 'That file is not a binary glTF (.glb) or a PNG, JPEG, WebP or GIF image.');+ },+ },+ {+ name: 'create_agent_run',+ title: 'Give an agent a goal to pursue on its own',+ annotations: WRITE,+ description:+ 'Start an autonomous run: the agent works the goal through its read-only tool loop, one checkpointed step at a time. A run has a step budget (max_steps) and a dollar budget (budget_usd, credits spent on paid models; 0 keeps it on free model lanes and it can never spend a cent). Cancel takes effect between steps. When it ends it writes a plain-language summary, and every tool call it made is logged with a chained receipt (read them with get_agent_run_steps, or watch the replay on the agent page). Runs never sign or move funds.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ goal: { type: 'string', minLength: 1, maxLength: 8000, description: 'What the agent should accomplish, in plain language.' },+ max_steps: { type: 'integer', minimum: 1, maximum: 60, default: 12, description: 'Step budget: model turns the run may take.' },+ budget_usd: { type: 'number', minimum: 0, maximum: 100, default: 0, description: 'Dollar budget for paid model calls, charged to your credits. 0 means free lanes only.' },+ tools_allowed: { type: 'array', items: { type: 'string' }, maxItems: 64, description: 'Restrict the run to these tools from the agent tool registry. Omit for all.' },+ model: { type: 'string', maxLength: 120, description: 'Preferred model id. Omit to use the agent\'s brain.' },+ temperature: { type: 'number', minimum: 0, maximum: 2 },+ scheduled_for: { type: 'string', format: 'date-time', description: 'Start later, at this ISO time. Omit to start now.' },+ wait_seconds: WAIT,+ },+ required: ['agent_id', 'goal'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('start agent runs');+ const row = await api(async () => {+ await loadOwnedAgent(args.agent_id, auth.userId);+ return createRun({+ agentId: args.agent_id,+ userId: auth.userId,+ goal: args.goal,+ model: args.model ?? null,+ temperature: args.temperature ?? null,+ toolsAllowed: args.tools_allowed ?? null,+ maxSteps: args.max_steps,+ budgetCreditsUsd: args.budget_usd,+ scheduledFor: args.scheduled_for ?? null,+ source: 'mcp',+ });+ });+ if (failed(row)) return row.__error;+ if (!row) return designedError('run_not_created', 'The run was not created. Try again.');+ const fresh = row.status === 'scheduled' ? row : await driveFor(row.id, auth.userId, args.wait_seconds);+ return toolResult({ status: 'created', ...runView(fresh) });+ },+ },+ {+ name: 'update_agent_run',+ title: 'Pause, resume, or raise the budget of a run',+ annotations: WRITE,+ description:+ 'Pause a live run, resume a paused one, or raise its dollar budget (budget_usd; a budget can only be raised). A finished run cannot be changed.',+ inputSchema: {+ type: 'object',+ properties: {+ run_id: RUN_ID,+ action: { type: 'string', enum: ['pause', 'resume'] },+ budget_usd: { type: 'number', minimum: 0, maximum: 100, description: 'The new, higher dollar budget for paid model calls.' },+ wait_seconds: { ...WAIT, default: 0 },+ },+ required: ['run_id'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('manage agent runs');+ if (!args.action && args.budget_usd == null) return designedError('nothing_to_update', 'Pass action (pause or resume) or a higher budget_usd.');+ const row = await api(() => updateRun(args.run_id, auth.userId, { action: args.action ?? null, budgetCreditsUsd: args.budget_usd ?? null }));+ if (failed(row)) return row.__error;+ const fresh = args.action === 'resume' ? await driveFor(row.id, auth.userId, args.wait_seconds) : row;+ return toolResult({ status: 'updated', ...runView(fresh) });+ },+ },+ {+ name: 'cancel_agent_run',+ title: 'Cancel a run',+ annotations: IDEMPOTENT_WRITE,+ description:+ 'Cancel a run. A queued, scheduled or paused run ends now; a running one ends before its next step, so the cancel lands within one step. The run keeps its steps, receipts and summary.',+ inputSchema: { type: 'object', properties: { run_id: RUN_ID }, required: ['run_id'], additionalProperties: false },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('manage agent runs');+ const row = await api(() => cancelRun(args.run_id, auth.userId));+ if (failed(row)) return row.__error;+ const run = serializeRun(row);+ return toolResult({+ status: TERMINAL_RUN_STATUSES.has(row.status) ? row.status : 'cancel_requested',+ run,+ note: TERMINAL_RUN_STATUSES.has(row.status) ? run.summary || `The run ${row.status}.` : 'The run stops before its next step.',+ });+ },+ },+ {+ name: 'get_agent_run_steps',+ title: 'Read a run step by step',+ annotations: READ,+ description:+ 'Read a run and its step trace: every model call, and every tool call paired with its result and a receipt. Receipts are sha256 digests chained step to step, and receipt_chain reports whether the chain recomputes cleanly (it does whenever no step was edited, dropped or reordered). Page with after (the last seq you have).',+ inputSchema: {+ type: 'object',+ properties: {+ run_id: RUN_ID,+ after: { type: 'integer', minimum: 0, default: 0, description: 'Return steps after this seq.' },+ limit: { type: 'integer', minimum: 1, maximum: 500, default: 200 },+ },+ required: ['run_id'],+ additionalProperties: false,+ },+ scope: 'agents:read',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('read agent runs');+ const out = await api(async () => {+ const row = await getOwnedRun(args.run_id, auth.userId);+ const steps = await listRunSteps(args.run_id, auth.userId, { after: args.after, limit: args.limit });+ return { row, steps };+ });+ if (failed(out)) return out.__error;+ const { row, steps } = out;+ const full = args.after === 0 && steps.length < args.limit;+ return toolResult({+ ...runView(row),+ steps,+ tool_traces: toolTraces(steps),+ receipt_chain: full ? verifyReceiptChain(row.id, steps) : { verified: null, note: 'Read from after: 0 in one page to verify the full chain.' },+ next_after: steps.length ? steps.at(-1).seq : args.after,+ has_more: steps.length === args.limit,+ });+ },+ },+ {+ name: 'automation_list',+ title: 'List automations',+ annotations: READ,+ description:+ 'List automations: one agent\'s (pass agent_id) or every automation across your agents plus your account alert rules. Wallet rules and alert rules appear as the same shape with source wallet_intent or alert_rule.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID }, additionalProperties: false },+ scope: 'agents:read',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('read your automations');+ const items = await api(async () => {+ if (args.agent_id) {+ const agent = await loadOwnedAgent(args.agent_id, auth.userId);+ return listAgentAutomations(agent.id);+ }+ return listUserAutomations(auth.userId);+ });+ if (failed(items)) return items.__error;+ return toolResult({ items, count: items.length, trigger_types: TRIGGER_TYPES, action_types: ACTION_TYPES });+ },+ },+ {+ name: 'automation_get',+ title: 'Get one automation',+ annotations: READ,+ description:+ 'Read one automation: its trigger, action, spend limits, fire stats, next scheduled fire, and the runs it started. Call this before automation_delete and show the user the result: its preview_id authorizes the delete.',+ inputSchema: { type: 'object', properties: { automation_id: AUTOMATION_ID }, required: ['automation_id'], additionalProperties: false },+ scope: 'agents:read',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('read your automations');+ const a = await api(() => getAutomation(auth.userId, args.automation_id));+ if (failed(a)) return a.__error;+ return toolResult({ automation: a });+ },+ },+ {+ name: 'automation_create',+ title: 'Create an automation',+ annotations: WRITE,+ description:+ `Wire an agent to a trigger. Validated by the same code as the REST API. ${TRIGGER_DOC} ${ACTION_DOC} ` ++ 'limits caps spend actions in USD: { perActionUsd, dailyUsd, totalUsd }. trigger_once switches it off after the first fire. ' ++ 'A swap or transfer spends from the agent wallet on its own: the first call returns the recipient, amount, asset and chain for the owner to approve, then call again with confirm_spend: true. Connector keys cannot create spending automations.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ title: { type: 'string', maxLength: 80 },+ trigger: { type: 'object', properties: { type: { type: 'string', enum: [...TRIGGER_TYPES] } }, required: ['type'] },+ action: { type: 'object', properties: { type: { type: 'string', enum: [...ACTION_TYPES] } }, required: ['type'] },+ trigger_once: { type: 'boolean', default: false },+ limits: {+ type: 'object',+ properties: { perActionUsd: { type: 'number' }, dailyUsd: { type: 'number' }, totalUsd: { type: 'number' } },+ additionalProperties: false,+ },+ confirm_spend: { type: 'boolean', description: 'Required for swap and transfer, only after the owner approved the terms.' },+ },+ required: ['agent_id', 'trigger', 'action'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('create automations');+ const body = { title: args.title, trigger: args.trigger, action: args.action, triggerOnce: args.trigger_once === true, limits: args.limits };+ const norm = await api(async () => normalizeAutomation(body));+ if (failed(norm)) return norm.__error;+ if (SPEND_ACTIONS.has(norm.action.type)) {+ const refused = assertMaySpend(auth, 'automation_create');+ if (refused) return refused;+ if (args.confirm_spend !== true) {+ return spendConfirmation('automation_create', spendTerms(await displayDestination(norm.action), norm.trigger, norm.limits), { title: norm.title });+ }+ }+ const created = await api(async () => {+ const agent = await loadOwnedAgent(args.agent_id, auth.userId);+ return createAutomation({ agent, userId: auth.userId, body: { ...body, confirm: args.confirm_spend === true }, source: 'mcp' });+ });+ if (failed(created)) return created.__error;+ logAudit({ userId: auth.userId, action: 'automation_create', resourceId: args.agent_id, meta: { automation_id: created.id, trigger: created.trigger.type, action: created.action.type } });+ return toolResult({ status: 'created', automation: created });+ },+ },+ {+ name: 'automation_update',+ title: 'Edit an automation',+ annotations: IDEMPOTENT_WRITE,+ description:+ 'Change an automation. trigger and action patches merge over the stored config (send a new type to replace it), and the result is re-validated with the same rules as automation_create. enabled switches it on or off. Changing a swap or transfer automation (anything but switching it off) shows the spend terms first and needs confirm_spend: true.',+ inputSchema: {+ type: 'object',+ properties: {+ automation_id: AUTOMATION_ID,+ title: { type: 'string', maxLength: 80 },+ trigger: { type: 'object' },+ action: { type: 'object' },+ trigger_once: { type: 'boolean' },+ limits: {+ type: 'object',+ properties: { perActionUsd: { type: 'number' }, dailyUsd: { type: 'number' }, totalUsd: { type: 'number' } },+ additionalProperties: false,+ },+ enabled: { type: 'boolean' },+ confirm_spend: { type: 'boolean' },+ },+ required: ['automation_id'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('edit automations');+ const current = await api(() => getAutomation(auth.userId, args.automation_id));+ if (failed(current)) return current.__error;+ const body = pick(args, { title: 'title', trigger: 'trigger', action: 'action', trigger_once: 'triggerOnce', limits: 'limits', enabled: 'enabled' });+ if (!Object.keys(body).length) return designedError('nothing_to_update', 'Pass at least one field to change.');+ // Wallet rules and alert rules listed as automations are edited on their own pages; the lib refuses them with not_editable.+ const nextType = current.source === 'automation' ? args.action?.type || current.action?.type : null;+ const onlyDisabling = args.enabled === false && Object.keys(body).length === 1;+ if (SPEND_ACTIONS.has(nextType) && !onlyDisabling) {+ const refused = assertMaySpend(auth, 'automation_update');+ if (refused) return refused;+ if (args.confirm_spend !== true) {+ const action = args.action && args.action.type && args.action.type !== current.action.type ? args.action : { ...current.action, ...(args.action || {}) };+ const trigger = args.trigger ? { ...current.trigger, ...args.trigger } : current.trigger;+ return spendConfirmation('automation_update', spendTerms(await displayDestination(action), trigger, { ...current.limits, ...(args.limits || {}) }), { automation_id: args.automation_id });+ }+ }+ const out = await api(() => updateAutomation({ userId: auth.userId, id: args.automation_id, body: { ...body, confirm: args.confirm_spend === true } }));+ if (failed(out)) return out.__error;+ logAudit({ userId: auth.userId, action: 'automation_update', resourceId: out.agentId, meta: { automation_id: out.id, fields: Object.keys(body) } });+ return toolResult({ status: 'updated', automation: out });+ },+ },+ {+ name: 'automation_delete',+ title: 'Delete an automation',+ annotations: DESTRUCTIVE,+ description:+ 'Delete an automation (or a wallet rule or alert rule listed as one). Call automation_get first, show the user what it does, and only after they say yes call this with the preview_id and confirm_delete: true. Runs it already started keep going; cancel them with cancel_agent_run.',+ inputSchema: { type: 'object', properties: { automation_id: AUTOMATION_ID }, required: ['automation_id'], additionalProperties: false },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('delete automations');+ const out = await api(() => deleteAutomation(auth.userId, args.automation_id));+ if (failed(out)) return out.__error;+ logAudit({ userId: auth.userId, action: 'automation_delete', resourceId: args.automation_id, meta: { source: out.source } });+ return toolResult({ status: 'deleted', ...out });+ },+ },+ {+ name: 'automation_trigger',+ title: 'Fire an automation now',+ annotations: { ...WRITE, destructiveHint: true, openWorldHint: true },+ description:+ 'Run an automation\'s action right now, outside its trigger, once per call. It still passes every guard a real fire does (the agent must be running, spend policy and caps apply). An agent_prompt automation starts a run (driven inline for wait_seconds). A swap or transfer shows the spend terms first and needs confirm_spend: true.',+ inputSchema: {+ type: 'object',+ properties: { automation_id: AUTOMATION_ID, confirm_spend: { type: 'boolean' }, wait_seconds: WAIT },+ required: ['automation_id'],+ additionalProperties: false,+ },+ scope: 'agents:write',+ async handler(args, auth) {+ if (!auth.userId) return signInRequired('fire automations');+ const current = await api(() => getAutomation(auth.userId, args.automation_id));+ if (failed(current)) return current.__error;+ if (current.source === 'automation' && SPEND_ACTIONS.has(current.action?.type)) {+ const refused = assertMaySpend(auth, 'automation_trigger');+ if (refused) return refused;+ if (args.confirm_spend !== true) {+ return spendConfirmation('automation_trigger', spendTerms(current.action, { type: 'manual', note: 'fires once, now' }, current.limits), { automation_id: args.automation_id });+ }+ }+ const out = await api(() => triggerAutomation({ userId: auth.userId, id: args.automation_id, confirm: args.confirm_spend === true }));+ if (failed(out)) return out.__error;+ logAudit({ userId: auth.userId, action: 'automation_trigger', resourceId: out.automation.agentId, meta: { automation_id: args.automation_id, status: out.result.status } });+ const payload = { status: out.result.status, result: out.result, automation: out.automation };+ if (out.result.runId) Object.assign(payload, runView(await driveFor(out.result.runId, auth.userId, args.wait_seconds)));+ return toolResult(payload);+ },+ },+];diff --git a/packages/mcp-policy/src/table.js b/packages/mcp-policy/src/table.jsindex 28970da11..262097ce0 100644--- a/packages/mcp-policy/src/table.js+++ b/packages/mcp-policy/src/table.js@@ -156,6 +156,27 @@ export const POLICY = {agent_card_withdraw: own('cards', 'confirm_withdraw', 'agent_card_balance'),agent_card_connect: r('cards'),agent_card_connect_link: w('cards'),+ // Agent lifecycle, runs and automations (api/_mcp/tools/agent-lifecycle.js).+ // Deletes are financial-tier because they cannot be undone. Swap and+ // transfer automations gate themselves: connector keys are refused, the+ // bearer needs wallet:write, and the call needs confirm_spend after the+ // terms are shown.+ get_agent: r('agents'),+ update_agent: w('agents'),+ delete_agent: f('agents', 'confirm_delete', 'get_agent', ['agent_id']),+ start_agent: w('agents'),+ stop_agent: w('agents'),+ upload_agent_avatar: w('agents'),+ create_agent_run: w('runs'),+ update_agent_run: w('runs'),+ cancel_agent_run: w('runs'),+ get_agent_run_steps: r('runs'),+ automation_list: r('runs'),+ automation_get: r('runs'),+ automation_create: w('runs'),+ automation_update: w('runs'),+ automation_delete: f('runs', 'confirm_delete', 'automation_get', ['automation_id']),+ automation_trigger: w('runs'),},// /api/mcp-agentdiff --git a/tests/mcp-agent-lifecycle.test.js b/tests/mcp-agent-lifecycle.test.jsnew file mode 100644index 000000000..ce05a2df3--- /dev/null+++ b/tests/mcp-agent-lifecycle.test.js@@ -0,0 +1,622 @@+// Agent lifecycle, run and automation tools over MCP (api/_mcp/tools/agent-lifecycle.js).+//+// Every call goes through the real /api/mcp dispatcher: the real policy gate+// (enablement, confirm flags, preview ids), the real scope check, Ajv on the+// real input schemas, and the real tool handlers. Agent edits run the real+// agents-v1 agents.js and automations run the real agents-v1 automations.js,+// so MCP is held to the exact validators the REST API uses. Only storage is+// replaced: an in-memory SQL fake for the tables these tools touch, the+// wallet-intent store, R2, and the run engine's model loop (runs are stepped+// with real chained receipts from run-receipts.js).++import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';++const USER = '0a1b2c3d-0000-4000-8000-0000000000a1';+const OTHER = '0a1b2c3d-0000-4000-8000-0000000000b2';+const AGENT = '7e57a9e1-0000-4000-8000-000000000001';+const FOREIGN_AGENT = '7e57a9e1-0000-4000-8000-000000000002';+const MINT = 'THREEsynthetic11111111111111111111111111111';+const DEST = 'THREEsyntheticDest1111111111111111111111111';++const db = vi.hoisted(() => ({ agents: new Map(), automations: new Map(), runs: new Map(), steps: new Map(), seq: 0 }));++vi.mock('../api/_lib/db.js', () => {+ const norm = (strings) => (Array.isArray(strings) ? strings.join('?') : String(strings)).replace(/\s+/g, ' ').trim();+ const uuid = () => `00000000-0000-4000-8000-${String(++db.seq).padStart(12, '0')}`;+ const json = (v) => (typeof v === 'string' ? JSON.parse(v) : v);+ function run(text, v) {+ if (/^SELECT \* FROM agent_identities WHERE id = \? AND deleted_at IS NULL/.test(text)) {+ const a = db.agents.get(v[0]);+ return a && !a.deleted_at ? [a] : [];+ }+ if (/^SELECT status, deleted_at FROM agent_identities WHERE id = \?/.test(text)) {+ const a = db.agents.get(v[0]);+ return a ? [{ status: a.status, deleted_at: a.deleted_at }] : [];+ }+ if (/^UPDATE agent_identities SET name = COALESCE/.test(text)) {+ const a = db.agents.get(v[9]);+ if (v[0] != null) a.name = v[0];+ if (v[1]) a.description = v[2];+ if (v[3]) a.persona_prompt = v[4];+ if (v[5] != null) a.skills = v[5];+ a.meta = { ...a.meta, ...JSON.parse(v[8]) };+ return [a];+ }+ if (/^UPDATE agent_identities SET status = \?/.test(text)) {+ const a = db.agents.get(v[1]);+ a.status = v[0];+ return [a];+ }+ if (/^UPDATE agent_identities SET deleted_at = now\(\)/.test(text)) {+ db.agents.get(v[0]).deleted_at = new Date().toISOString();+ return [];+ }+ if (/^UPDATE agent_identities SET avatar_id = \?/.test(text)) {+ db.agents.get(v[1]).avatar_id = v[0];+ return [];+ }+ if (/^UPDATE agent_identities SET profile_image_url = \?/.test(text)) {+ db.agents.get(v[1]).profile_image_url = v[0];+ return [];+ }+ if (/count\(\*\)::int FROM agent_runs WHERE agent_id = \? AND status IN/.test(text)) {+ return [{ open_runs: 1, enabled_automations: 2, automations: 3, memories: 14, actions: 9 }];+ }+ if (/^SELECT count\(\*\)::int AS n FROM agent_automations WHERE agent_id = \?/.test(text)) {+ return [{ n: [...db.automations.values()].filter((r) => r.agent_id === v[0]).length }];+ }+ if (/^INSERT INTO agent_automations/.test(text)) {+ const row = {+ id: uuid(), agent_id: v[0], user_id: v[1], title: v[2], trigger_type: v[3], trigger_config: json(v[4]),+ action_type: v[5], action_config: json(v[6]), trigger_once: v[7], intent_id: v[8], source: v[9],+ enabled: true, fire_count: 0, created_at: new Date().toISOString(), updated_at: null,+ };+ db.automations.set(row.id, row);+ return [row];+ }+ if (/^SELECT \* FROM agent_automations WHERE id = \? AND user_id = \?/.test(text)) {+ const r = db.automations.get(v[0]);+ return r && r.user_id === v[1] ? [r] : [];+ }+ if (/^SELECT \* FROM agent_automations WHERE id = \?$/.test(text)) {+ const r = db.automations.get(v[0]);+ return r ? [r] : [];+ }+ if (/^SELECT \* FROM agent_automations WHERE agent_id = \?/.test(text)) {+ return [...db.automations.values()].filter((r) => r.agent_id === v[0]);+ }+ if (/^SELECT \* FROM agent_automations WHERE user_id = \?/.test(text)) {+ return [...db.automations.values()].filter((r) => r.user_id === v[0]);+ }+ if (/^UPDATE agent_automations SET title = \?/.test(text)) {+ const r = db.automations.get(v[9]);+ Object.assign(r, {+ title: v[0], trigger_type: v[1], trigger_config: json(v[2]), action_type: v[3], action_config: json(v[4]),+ trigger_once: v[5], enabled: v[6], intent_id: v[7], updated_at: new Date().toISOString(),+ });+ return [r];+ }+ if (/^DELETE FROM agent_automations WHERE id = \? AND user_id = \?/.test(text)) {+ const r = db.automations.get(v[0]);+ if (!r || r.user_id !== v[1]) return [];+ db.automations.delete(v[0]);+ return [{ agent_id: r.agent_id, intent_id: r.intent_id }];+ }+ return [];+ }+ const sql = (strings, ...values) => Promise.resolve(run(norm(strings), values));+ sql.transaction = (queries) => Promise.all(queries);+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false, isStoragePressured: () => false };+});++vi.mock('../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++vi.mock('../api/_lib/webhook-dispatch.js', () => ({ dispatchWebhooks: vi.fn(async () => ({ queued: 0 })) }));++vi.mock('../api/_lib/wallet-intents.js', async (importOriginal) => ({+ ...(await importOriginal()),+ createIntent: vi.fn(async () => ({ id: '1e7e0000-0000-4000-8000-0000000000f1' })),+ getIntent: vi.fn(async () => ({ limits: { per_action_usd: 25, daily_usd: 50 } })),+ updateIntent: vi.fn(async () => ({ ok: true })),+ deleteIntent: vi.fn(async () => ({ ok: true })),+ listIntents: vi.fn(async () => []),+}));++vi.mock('../api/_lib/r2.js', async (importOriginal) => ({+ ...(await importOriginal()),+ putObject: vi.fn(async () => ({})),+ publicUrl: (key) => `https://cdn.three.ws/${key}`,+}));++vi.mock('../api/_lib/avatars.js', async (importOriginal) => ({+ ...(await importOriginal()),+ createAvatar: vi.fn(async ({ storageKey, input }) => ({+ id: 'a7a7a7a7-0000-4000-8000-000000000001',+ storage_key: storageKey,+ model_url: `https://cdn.three.ws/${storageKey}`,+ visibility: input.visibility,+ })),+ defaultAvatarVisibilityFor: vi.fn(async () => 'unlisted'),+}));++vi.mock('../api/_lib/auto-rig.js', async (importOriginal) => ({+ ...(await importOriginal()),+ maybeAutoRigAvatar: vi.fn(async () => ({ queued: true })),+}));++vi.mock('../api/_lib/agent-wallet.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getSolanaAddressBalances: vi.fn(async () => ({ sol: 0.5, usdc: 0 })),+}));++vi.mock('../api/_lib/ssrf-guard.js', async (importOriginal) => ({+ ...(await importOriginal()),+ fetchSafePublicUrl: vi.fn(),+}));++// The run engine: the real serializers and receipt chain, with the model loop+// replaced by a deterministic two-tool step sequence.+vi.mock('../api/_lib/agents-v1/runs.js', async (importOriginal) => {+ const real = await importOriginal();+ const { stepReceipt, summarizeRun } = await import('../api/_lib/agents-v1/run-receipts.js');+ const { apiError } = await import('../api/_lib/agents-v1/http.js');+ const now = () => new Date().toISOString();+ function addStep(runId, s) {+ const list = db.steps.get(runId) || [];+ const seq = list.length + 1;+ const prev = list.at(-1)?.receipt || null;+ const row = { seq, kind: s.kind, provider: null, model: null, tool_name: s.tool || null, input: s.input ?? null, output: s.output ?? null, latency_ms: 5, created_at: now() };+ row.receipt = stepReceipt({ prev, runId, seq, kind: row.kind, tool: row.tool_name, input: row.input, output: row.output });+ list.push(row);+ db.steps.set(runId, list);+ }+ const owned = (runId, userId) => {+ const r = db.runs.get(runId);+ if (!r || r.user_id !== userId) throw apiError(404, 'run_not_found', 'Run not found.');+ return r;+ };+ return {+ ...real,+ createRun: vi.fn(async (o) => {+ const a = db.agents.get(o.agentId);+ if (a.status === 'stopped') throw apiError(409, 'agent_stopped', 'This agent is stopped. Start it before creating a run.');+ const id = `00000000-0000-4000-8000-${String(++db.seq).padStart(12, '0')}`;+ const row = {+ id, agent_id: o.agentId, user_id: o.userId, goal: o.goal, status: o.scheduledFor ? 'scheduled' : 'queued',+ max_steps: o.maxSteps ?? 12, step_count: 0, budget_credits_usd: o.budgetCreditsUsd ?? 0, spent_credits_usd: 0,+ budget_usd: 0, spent_usd: 0, source: o.source, automation_id: o.automationId ?? null, created_at: now(),+ };+ db.runs.set(id, row);+ addStep(id, { kind: 'status', output: { status: row.status, note: 'run created' } });+ return row;+ }),+ getOwnedRun: vi.fn(async (runId, userId) => owned(runId, userId)),+ listRunSteps: vi.fn(async (runId, userId, { after = 0, limit = 200 } = {}) => {+ owned(runId, userId);+ return (db.steps.get(runId) || []).filter((s) => s.seq > after).slice(0, limit).map(real.serializeStep);+ }),+ driveRun: vi.fn(async (runId) => {+ const r = db.runs.get(runId);+ if (real.TERMINAL_RUN_STATUSES.has(r.status) || r.status === 'paused') return r;+ r.status = 'running';+ r.started_at = now();+ addStep(runId, { kind: 'model_call', output: { finish: 'tool_calls' } });+ addStep(runId, { kind: 'tool_call', tool: 'get_price', input: { mint: MINT } });+ addStep(runId, { kind: 'tool_result', tool: 'get_price', input: { mint: MINT }, output: { priceUsd: 0.0021 } });+ addStep(runId, { kind: 'tool_call', tool: 'get_holders', input: { mint: MINT } });+ addStep(runId, { kind: 'tool_result', tool: 'get_holders', input: { mint: MINT }, output: { error: 'upstream timeout' } });+ addStep(runId, { kind: 'model_call', output: { finish: 'stop' } });+ Object.assign(r, { status: 'completed', step_count: 2, result: 'Price is $0.0021.', finished_at: now() });+ r.summary = summarizeRun(r, [+ { kind: 'model_call', tool_name: null, n: 2, failed: 0 },+ { kind: 'tool_call', tool_name: 'get_price', n: 1, failed: 0 },+ { kind: 'tool_call', tool_name: 'get_holders', n: 1, failed: 0 },+ { kind: 'tool_result', tool_name: null, n: 2, failed: 1 },+ ]);+ return r;+ }),+ cancelRun: vi.fn(async (runId, userId) => {+ const r = owned(runId, userId);+ if (real.TERMINAL_RUN_STATUSES.has(r.status)) return r;+ r.cancel_requested_at = now();+ if (['queued', 'scheduled', 'paused'].includes(r.status)) Object.assign(r, { status: 'cancelled', finished_at: now(), summary: 'Cancelled after 0 model turns.' });+ return r;+ }),+ updateRun: vi.fn(async (runId, userId, { action, budgetCreditsUsd }) => {+ const r = owned(runId, userId);+ if (real.TERMINAL_RUN_STATUSES.has(r.status)) throw apiError(409, 'run_finished', `This run already ${r.status}.`);+ if (budgetCreditsUsd != null && budgetCreditsUsd < r.budget_credits_usd) throw apiError(400, 'budget_decrease', 'A budget can only be raised.');+ if (budgetCreditsUsd != null) r.budget_credits_usd = budgetCreditsUsd;+ if (action === 'pause') r.status = 'paused';+ if (action === 'resume' && r.status === 'paused') r.status = 'queued';+ return r;+ }),+ };+});++const FULL = 'agents:read agents:write avatars:write wallet:write';+const owner = (scope = FULL) => ({ userId: USER, scope, source: 'oauth', apiKeyId: null });+const ALL = { headers: { 'x-three-tools': 'all' }, url: '/api/mcp' };+const DEFAULT = { headers: {}, url: '/api/mcp' };++let dispatch;+async function call(name, args = {}, { auth = owner(), req = ALL } = {}) {+ if (!dispatch) ({ dispatch } = await import('../api/_mcp/dispatch.js'));+ const res = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth, req);+ return res;+}+const out = (res) => res.result?.structuredContent;++function seedAgent(id = AGENT, userId = USER, extra = {}) {+ db.agents.set(id, {+ id, user_id: userId, name: 'Scout', description: 'Watches launches', persona_prompt: null, skills: [],+ status: 'running', meta: { solana_address: 'THREEsyntheticWallet111111111111111111111111' }, wallet_address: null,+ avatar_id: null, is_public: true, created_at: new Date().toISOString(), deleted_at: null, ...extra,+ });+}++function glb() {+ const jsonText = JSON.stringify({ asset: { version: '2.0' }, scenes: [{ nodes: [] }] });+ const json = Buffer.from(jsonText.padEnd(Math.ceil(jsonText.length / 4) * 4, ' '));+ const header = Buffer.alloc(20);+ header.writeUInt32LE(0x46546c67, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(20 + json.length, 8);+ header.writeUInt32LE(json.length, 12);+ header.writeUInt32LE(0x4e4f534a, 16);+ return Buffer.concat([header, json]);+}++const PNG = Buffer.from('89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489', 'hex');++beforeEach(() => {+ db.agents.clear();+ db.automations.clear();+ db.runs.clear();+ db.steps.clear();+ seedAgent();+ seedAgent(FOREIGN_AGENT, OTHER);+});++describe('agent lifecycle tools', () => {+ it('lists all sixteen tools on the main server', async () => {+ if (!dispatch) ({ dispatch } = await import('../api/_mcp/dispatch.js'));+ const res = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }, owner(), ALL);+ const names = new Set(res.result.tools.map((t) => t.name));+ for (const n of [+ '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',+ ]) {+ expect(names.has(n), n).toBe(true);+ }+ });++ it('get_agent reports what a delete would destroy and mints a preview id', async () => {+ const res = await call('get_agent', { agent_id: AGENT });+ expect(out(res).agent).toMatchObject({ id: AGENT, name: 'Scout', status: 'running' });+ expect(out(res).counts).toMatchObject({ open_runs: 1, memories: 14 });+ expect(out(res).delete_impact).toContain('permanently erases 14 memories');+ expect(out(res).delete_impact).toContain('withdraw them first');+ expect(res.result._meta['three.ws/preview'].preview_id).toMatch(/^p_/);+ });++ it('refuses an agent on another account with the REST error code', async () => {+ const res = await call('get_agent', { agent_id: FOREIGN_AGENT });+ expect(res.result.isError).toBe(true);+ expect(out(res)).toMatchObject({ error: 'forbidden', http_status: 403 });+ });++ it('update_agent maps snake_case onto the REST body and validates with the REST code', async () => {+ const ok = await call('update_agent', { agent_id: AGENT, name: 'Scout Prime', system_prompt: 'Be terse.', temperature: 0.4 });+ expect(out(ok)).toMatchObject({ status: 'updated', agent: { name: 'Scout Prime', systemPrompt: 'Be terse.', temperature: 0.4 } });+ expect(db.agents.get(AGENT).persona_prompt).toBe('Be terse.');++ const bad = await call('update_agent', { agent_id: AGENT, model: 'not-a-real-model' });+ expect(bad.result.isError).toBe(true);+ expect(out(bad).error).toBe('unknown_model');++ const badStrategy = await call('update_agent', { agent_id: AGENT, strategy: 'no-such-strategy' });+ expect(out(badStrategy).error).toBe('unknown_strategy');++ const empty = await call('update_agent', { agent_id: AGENT });+ expect(out(empty).error).toBe('nothing_to_update');+ });++ it('stop_agent and start_agent flip the status', async () => {+ expect(out(await call('stop_agent', { agent_id: AGENT })).agent.status).toBe('stopped');+ expect(db.agents.get(AGENT).status).toBe('stopped');+ expect(out(await call('start_agent', { agent_id: AGENT })).agent.status).toBe('running');+ });++ it('delete_agent is off unless the session enables the financial tier', async () => {+ const res = await call('delete_agent', { agent_id: AGENT, confirm_delete: true }, { req: DEFAULT });+ expect(res.result.isError).toBe(true);+ expect(out(res).reason).toBe('tool_disabled');+ expect(db.agents.get(AGENT).deleted_at).toBeNull();+ });++ it('refuses delete_agent without confirm_delete', async () => {+ const preview = await call('get_agent', { agent_id: AGENT });+ const preview_id = preview.result._meta['three.ws/preview'].preview_id;+ const res = await call('delete_agent', { agent_id: AGENT, preview_id });+ expect(res.result.isError).toBe(true);+ expect(out(res)).toMatchObject({ reason: 'confirmation_required', confirm_flag: 'confirm_delete', preview_tool: 'get_agent' });+ expect(db.agents.get(AGENT).deleted_at).toBeNull();+ });++ it('refuses delete_agent without a preview, and with a preview of a different agent', async () => {+ const none = await call('delete_agent', { agent_id: AGENT, confirm_delete: true });+ expect(out(none).reason).toBe('preview_required');++ seedAgent('7e57a9e1-0000-4000-8000-000000000003');+ const other = await call('get_agent', { agent_id: '7e57a9e1-0000-4000-8000-000000000003' });+ const res = await call('delete_agent', { agent_id: AGENT, confirm_delete: true, preview_id: other.result._meta['three.ws/preview'].preview_id });+ expect(out(res).reason).toBe('preview_mismatch');+ expect(db.agents.get(AGENT).deleted_at).toBeNull();+ });++ it('deletes with confirm_delete and a fresh preview, and burns the preview', async () => {+ const preview = await call('get_agent', { agent_id: AGENT });+ const preview_id = preview.result._meta['three.ws/preview'].preview_id;+ const res = await call('delete_agent', { agent_id: AGENT, preview_id, confirm_delete: true });+ expect(out(res)).toEqual({ status: 'deleted', agent_id: AGENT });+ expect(db.agents.get(AGENT).deleted_at).not.toBeNull();+ seedAgent();+ const replay = await call('delete_agent', { agent_id: AGENT, preview_id, confirm_delete: true });+ expect(out(replay).reason).toBe('preview_unknown');+ });++ it('needs agents:write to edit', async () => {+ const res = await call('stop_agent', { agent_id: AGENT }, { auth: owner('agents:read') });+ expect(res.error.code).toBe(-32002);+ });++ it('asks an anonymous caller to sign in', async () => {+ const res = await call('get_agent', { agent_id: AGENT }, { auth: { userId: null, scope: FULL } });+ expect(out(res).error).toBe('sign_in_required');+ });+});++describe('upload_agent_avatar', () => {+ it('ingests an inline GLB, attaches it as the 3D body, and queues the auto-rig', async () => {+ const { maybeAutoRigAvatar } = await import('../api/_lib/auto-rig.js');+ const { putObject } = await import('../api/_lib/r2.js');+ const res = await call('upload_agent_avatar', { agent_id: AGENT, data: `data:model/gltf-binary;base64,${glb().toString('base64')}` });+ expect(out(res)).toMatchObject({ status: 'attached', kind: 'glb', avatar_id: 'a7a7a7a7-0000-4000-8000-000000000001', rigged: false });+ expect(db.agents.get(AGENT).avatar_id).toBe('a7a7a7a7-0000-4000-8000-000000000001');+ expect(putObject).toHaveBeenCalledWith(expect.objectContaining({ contentType: 'model/gltf-binary', key: expect.stringMatching(new RegExp(`^u/${USER}/agent-`)) }));+ await new Promise((r) => setTimeout(r, 0));+ expect(maybeAutoRigAvatar).toHaveBeenCalledWith(expect.objectContaining({ rigInfo: { is_rigged: false, skeleton_joint_count: expect.anything() } }));+ });++ it('fetches a GLB by url through the SSRF guard', async () => {+ const { fetchSafePublicUrl } = await import('../api/_lib/ssrf-guard.js');+ fetchSafePublicUrl.mockResolvedValueOnce(new Response(glb(), { status: 200 }));+ const res = await call('upload_agent_avatar', { agent_id: AGENT, url: 'https://example.com/body.glb' });+ expect(out(res).kind).toBe('glb');+ expect(fetchSafePublicUrl).toHaveBeenCalledWith('https://example.com/body.glb', {}, { allowHttp: false });+ });++ it('sets an image as the portrait', async () => {+ const res = await call('upload_agent_avatar', { agent_id: AGENT, data: PNG.toString('base64') });+ expect(out(res)).toMatchObject({ status: 'attached', kind: 'image' });+ expect(db.agents.get(AGENT).profile_image_url).toMatch(new RegExp(`^https://cdn\\.three\\.ws/u/${USER}/agent-images/${AGENT}/.+\\.png$`));+ });++ it('refuses an unknown file type and a call with both url and data', async () => {+ const junk = await call('upload_agent_avatar', { agent_id: AGENT, data: Buffer.from('hello world, not a model').toString('base64') });+ expect(out(junk).error).toBe('unsupported_file');+ const both = await call('upload_agent_avatar', { agent_id: AGENT, data: 'AAAA', url: 'https://example.com/a.glb' });+ expect(out(both).error).toBe('invalid_request');+ });++ it('needs avatars:write to save a GLB to the library', async () => {+ const res = await call('upload_agent_avatar', { agent_id: AGENT, data: glb().toString('base64') }, { auth: owner('agents:read agents:write') });+ expect(out(res).error).toBe('insufficient_scope');+ });+});++describe('run tools', () => {+ it('creates a run with a step and dollar budget, drives it, and returns its summary', async () => {+ const res = await call('create_agent_run', { agent_id: AGENT, goal: 'Price the coin', max_steps: 6, budget_usd: 0.5, wait_seconds: 5 });+ const body = out(res);+ expect(body.status).toBe('created');+ expect(body.run).toMatchObject({ status: 'completed', maxSteps: 6, budget: { creditsUsd: 0.5 } });+ expect(body.live).toBe(false);+ expect(body.run.summary).toContain('Made 2 tool calls');+ expect(body.next).toBe(body.run.summary);+ expect(body.replay_url).toBe(`https://three.ws/agents/${AGENT}?view=runs&run=${body.run.id}`);+ });++ it('refuses a run on a stopped agent', async () => {+ db.agents.get(AGENT).status = 'stopped';+ const res = await call('create_agent_run', { agent_id: AGENT, goal: 'x' });+ expect(out(res).error).toBe('agent_stopped');+ });++ it('returns each tool call paired with its result and a receipt chain that verifies', async () => {+ const created = out(await call('create_agent_run', { agent_id: AGENT, goal: 'Price the coin' }));+ const res = out(await call('get_agent_run_steps', { run_id: created.run.id }));+ expect(res.steps.length).toBe(7);+ expect(res.tool_traces).toEqual([+ expect.objectContaining({ tool: 'get_price', status: 'ok', input: { mint: MINT }, output: { priceUsd: 0.0021 }, receipt: expect.stringMatching(/^[0-9a-f]{64}$/) }),+ expect.objectContaining({ tool: 'get_holders', status: 'error', output: { error: 'upstream timeout' } }),+ ]);+ expect(res.receipt_chain).toEqual({ verified: true, checked: 7, brokenAt: null });+ expect(res.next_after).toBe(7);+ });++ it('detects a tampered step', async () => {+ const created = out(await call('create_agent_run', { agent_id: AGENT, goal: 'Price the coin' }));+ db.steps.get(created.run.id)[2].output = { priceUsd: 99 };+ const res = out(await call('get_agent_run_steps', { run_id: created.run.id }));+ expect(res.receipt_chain).toMatchObject({ verified: false, brokenAt: 3 });+ });++ it('pauses, raises the budget, resumes, and refuses a budget cut', async () => {+ const created = out(await call('create_agent_run', { agent_id: AGENT, goal: 'Watch', wait_seconds: 0, budget_usd: 1 }));+ const paused = out(await call('update_agent_run', { run_id: created.run.id, action: 'pause' }));+ expect(paused.run.status).toBe('paused');+ const raised = out(await call('update_agent_run', { run_id: created.run.id, budget_usd: 2 }));+ expect(raised.run.budget.creditsUsd).toBe(2);+ const cut = await call('update_agent_run', { run_id: created.run.id, budget_usd: 0.5 });+ expect(out(cut).error).toBe('budget_decrease');+ const resumed = out(await call('update_agent_run', { run_id: created.run.id, action: 'resume', wait_seconds: 3 }));+ expect(resumed.run.status).toBe('completed');+ });++ it('cancels a queued run at once and reports a running one as cancel_requested', async () => {+ const queued = out(await call('create_agent_run', { agent_id: AGENT, goal: 'Watch', wait_seconds: 0 }));+ expect(out(await call('cancel_agent_run', { run_id: queued.run.id })).status).toBe('cancelled');++ const live = out(await call('create_agent_run', { agent_id: AGENT, goal: 'Watch', wait_seconds: 0 }));+ db.runs.get(live.run.id).status = 'running';+ const res = out(await call('cancel_agent_run', { run_id: live.run.id }));+ expect(res).toMatchObject({ status: 'cancel_requested', note: 'The run stops before its next step.' });+ expect(res.run.cancelRequested).toBe(true);+ });++ it('hides another account\'s run', async () => {+ const created = out(await call('create_agent_run', { agent_id: AGENT, goal: 'x', wait_seconds: 0 }));+ const res = await call('get_agent_run_steps', { run_id: created.run.id }, { auth: { ...owner(), userId: OTHER } });+ expect(out(res).error).toBe('run_not_found');+ });+});++describe('automation tools', () => {+ const prompt = { agent_id: AGENT, trigger: { type: 'schedule', cron: '0 * * * *' }, action: { type: 'agent_prompt', prompt: 'Summarize new launches', maxSteps: 4 } };++ it('creates, lists, reads and edits an agent_prompt automation through the REST validator', async () => {+ const created = out(await call('automation_create', prompt));+ expect(created.automation).toMatchObject({ agentId: AGENT, trigger: { type: 'schedule', cron: '0 * * * *' }, action: { type: 'agent_prompt' }, enabled: true });+ const id = created.automation.id;++ const listed = out(await call('automation_list', { agent_id: AGENT }));+ expect(listed.items.map((i) => i.id)).toContain(id);+ expect(listed.trigger_types).toContain('whale_buy');++ const got = await call('automation_get', { automation_id: id });+ expect(out(got).automation).toMatchObject({ id, nextFireAt: expect.any(String), recentRuns: [] });++ const updated = out(await call('automation_update', { automation_id: id, trigger: { cron: '30 * * * *' }, title: 'Hourly digest' }));+ expect(updated.automation).toMatchObject({ title: 'Hourly digest', trigger: { type: 'schedule', cron: '30 * * * *' } });++ const off = out(await call('automation_update', { automation_id: id, enabled: false }));+ expect(off.automation.enabled).toBe(false);+ });++ it('refuses an invalid config with the shared validator', async () => {+ const res = await call('automation_create', { ...prompt, trigger: { type: 'price_threshold', mint: MINT, operator: 'sideways', priceUsd: 1 } });+ expect(res.result.isError).toBe(true);+ expect(out(res).error).toBe('invalid_parameter');+ expect(db.automations.size).toBe(0);+ });++ it('shows spend terms and refuses a swap automation without confirm_spend', async () => {+ const res = await call('automation_create', {+ agent_id: AGENT,+ trigger: { type: 'price_threshold', mint: MINT, operator: 'below', priceUsd: 0.001 },+ action: { type: 'swap', mint: MINT, amountSol: 0.25 },+ limits: { dailyUsd: 50 },+ });+ expect(res.result.isError).toBe(true);+ expect(out(res)).toMatchObject({+ status: 'confirmation_required',+ confirm_flag: 'confirm_spend',+ terms: { amount: '0.25 SOL per fire', asset: 'SOL', chain: 'Solana mainnet', recipient: expect.stringContaining(MINT), caps: 'dailyUsd $50' },+ });+ expect(res.result.content[0].text).toContain('Recipient:');+ expect(db.automations.size).toBe(0);+ });++ it('creates a transfer automation once confirm_spend is true', async () => {+ const res = await call('automation_create', {+ agent_id: AGENT,+ trigger: { type: 'balance_below', thresholdSol: 0.1 },+ action: { type: 'transfer', destination: DEST, amountSol: 0.05 },+ confirm_spend: true,+ });+ expect(out(res).status).toBe('created');+ expect(out(res).automation.action).toMatchObject({ type: 'transfer', destination: DEST, amountSol: 0.05 });+ });++ it('refuses a spending automation to a connector key and to a bearer without wallet:write', async () => {+ const spend = { agent_id: AGENT, trigger: { type: 'tip_received' }, action: { type: 'transfer', destination: DEST, amountSol: 0.01 }, confirm_spend: true };+ const connector = await call('automation_create', spend, { auth: { ...owner('agents:read agents:write'), connector: true, apiKeyId: 'k' } });+ expect(connector.error.code).toBe(-32003);+ const narrow = await call('automation_create', spend, { auth: owner('agents:read agents:write') });+ expect(out(narrow).error).toBe('insufficient_scope');+ expect(db.automations.size).toBe(0);+ });++ it('lets a connector key create a non-spending automation', async () => {+ const res = await call('automation_create', prompt, { auth: { ...owner('agents:read agents:write'), connector: true, apiKeyId: 'k' } });+ expect(out(res).status).toBe('created');+ });++ it('needs confirm_spend to edit a spend automation but not to switch it off', async () => {+ const created = out(await call('automation_create', {+ agent_id: AGENT,+ trigger: { type: 'balance_below', thresholdSol: 0.1 },+ action: { type: 'transfer', destination: DEST, amountSol: 0.05 },+ confirm_spend: true,+ }));+ const id = created.automation.id;+ const raise = await call('automation_update', { automation_id: id, action: { amountSol: 1 } });+ expect(out(raise)).toMatchObject({ status: 'confirmation_required', terms: { amount: '1 SOL per fire', recipient: DEST } });+ expect(db.automations.get(id).action_config.amountSol).toBe(0.05);+ const off = out(await call('automation_update', { automation_id: id, enabled: false }));+ expect(off.automation.enabled).toBe(false);+ const confirmed = out(await call('automation_update', { automation_id: id, action: { amountSol: 1 }, enabled: true, confirm_spend: true }));+ expect(confirmed.automation.action.amountSol).toBe(1);+ });++ it('fires an agent_prompt automation on demand and drives the run it starts', async () => {+ const id = out(await call('automation_create', prompt)).automation.id;+ const res = out(await call('automation_trigger', { automation_id: id, wait_seconds: 2 }));+ expect(res.status).toBe('run_started');+ expect(res.run).toMatchObject({ status: 'completed', automationId: id });+ expect(res.run.summary).toContain('Completed');+ });++ it('refuses to fire on a stopped agent and to fire a spend automation without confirm_spend', async () => {+ const id = out(await call('automation_create', prompt)).automation.id;+ db.agents.get(AGENT).status = 'stopped';+ expect(out(await call('automation_trigger', { automation_id: id })).error).toBe('agent_stopped');+ db.agents.get(AGENT).status = 'running';++ const spend = out(await call('automation_create', {+ agent_id: AGENT,+ trigger: { type: 'balance_below', thresholdSol: 0.1 },+ action: { type: 'transfer', destination: DEST, amountSol: 0.05 },+ confirm_spend: true,+ })).automation.id;+ const res = await call('automation_trigger', { automation_id: spend });+ expect(out(res)).toMatchObject({ status: 'confirmation_required', terms: { recipient: DEST, chain: 'Solana mainnet' } });+ });++ it('refuses automation_delete without confirm_delete, then deletes with a preview', async () => {+ const id = out(await call('automation_create', prompt)).automation.id;+ const refused = await call('automation_delete', { automation_id: id });+ expect(out(refused)).toMatchObject({ reason: 'confirmation_required', confirm_flag: 'confirm_delete' });+ expect(db.automations.has(id)).toBe(true);++ const preview = await call('automation_get', { automation_id: id });+ const preview_id = preview.result._meta['three.ws/preview'].preview_id;+ const res = out(await call('automation_delete', { automation_id: id, preview_id, confirm_delete: true }));+ expect(res).toMatchObject({ status: 'deleted', id, source: 'automation' });+ expect(db.automations.has(id)).toBe(false);+ });++ it('answers an unknown automation with not_found', async () => {+ const res = await call('automation_get', { automation_id: '00000000-0000-4000-8000-00000000dead' });+ expect(out(res).error).toBe('not_found');+ });+});diff --git a/tests/mcp-remote-annotations.test.js b/tests/mcp-remote-annotations.test.jsindex cba269900..24ff50f3d 100644--- a/tests/mcp-remote-annotations.test.js+++ b/tests/mcp-remote-annotations.test.js@@ -30,6 +30,10 @@ const CATALOGS = [// forget deletes a stored agent memory// delete_custom_skill permanently removes a skill an owner may have written// by hand; gated on confirm_delete+// delete_agent cancels an agent's runs and erases its memories and+// action log; gated on confirm_delete+// automation_delete removes an automation (or the wallet rule or alert+// rule behind it); gated on confirm_delete// Moving money (an irreversible transfer or an on-chain transaction):// pay_and_call spends the user's USDC on an x402 endpoint// persona_tip, persona_send spend a persona's own USDC@@ -39,6 +43,8 @@ const CATALOGS = [// paired_launch launches a coin and its opening buy on Robinhood Chain// paired_claim_fees signs and broadcasts the fee-collection transaction on// Robinhood Chain (marked destructive on 2026-10-09)+// automation_trigger fires an automation now, and a swap or transfer+// automation spends SOL from the agent wallet// create_marketplace_listing, delist_marketplace_listing, place_bid,// buy_now, accept_marketplace_bid, withdraw_marketplace_bid// commit an agent or move USDC through marketplace escrow@@ -57,10 +63,10 @@ const CATALOGS = [// future home tool is genuinely read-only it belongs outside this set; anything// that reaches an actuator belongs inside it.const DESTRUCTIVE_TOOLS = new Set([- 'delete_avatar', 'forget', 'delete_custom_skill',+ 'delete_avatar', 'forget', 'delete_custom_skill', 'delete_agent', 'automation_delete','pay_and_call', 'persona_tip', 'persona_send','agent_card_create', 'agent_card_reveal', 'agent_card_cancel', 'agent_card_withdraw',- 'paired_launch', 'paired_claim_fees',+ 'paired_launch', 'paired_claim_fees', 'automation_trigger','create_marketplace_listing', 'delist_marketplace_listing', 'place_bid', 'buy_now','accept_marketplace_bid', 'withdraw_marketplace_bid','predictions_open', 'predictions_close', 'predictions_redeem',@@ -69,10 +75,13 @@ const DESTRUCTIVE_TOOLS = new Set([// Destructive tools the policy deliberately leaves in the write tier (on by// default, no confirm flag). paired_claim_fees collects fees into the agent's-// own wallet, so nothing leaves the owner's control. Every other destructive-// tool must be financial tier: off until the session enables it, and refused-// without its confirm flag.-const DESTRUCTIVE_WRITE_TIER = new Set(['paired_claim_fees']);+// own wallet, so nothing leaves the owner's control. automation_trigger gates+// its own spend: an agent_prompt or notify fire moves nothing, and a swap or+// transfer fire refuses connector keys, needs wallet:write, and needs+// confirm_spend after the tool has shown recipient, amount, asset and chain.+// Every other destructive tool must be financial tier: off until the session+// enables it, and refused without its confirm flag.+const DESTRUCTIVE_WRITE_TIER = new Set(['paired_claim_fees', 'automation_trigger']);// Internal/spec-only fields that must never leak into the tools/list wire// payload.