Skip to content

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

feat(agents-api): v1 Agents API with shared creation path, strategies, swap and wallet routes, plus the TS SDK transport

nirholasa1b705dbb63e
diff --git a/api/_lib/agent-create.js b/api/_lib/agent-create.js
new file mode 100644
index 000000000..17d3708b8
--- /dev/null
+++ b/api/_lib/agent-create.js
@@ -0,0 +1,140 @@
+// Create an agent identity: the one path every creation surface shares.
+//
+// POST /api/agents (api/agents.js) and the create_agent MCP tool both call
+// createAgentIdentity, so an agent made from a browser and one made by a model
+// through MCP get the same integrity screening, the same custodial wallets and
+// the same announcements. Transport concerns (auth, CSRF, rate limits, scope)
+// stay with the caller.
+
+import { sql } from './db.js';
+import { env } from './env.js';
+import { generateAgentWallet, generateSolanaAgentWallet } from './agent-wallet.js';
+import { checkIdentityIntegrity } from './identity-integrity.js';
+import { pingIndexNow } from './indexnow.js';
+import { publishFeedEvent } from './feed.js';
+
+export const DEFAULT_AGENT_SKILLS = Object.freeze(['greet', 'present-model', 'validate-model', 'remember', 'think']);
+
+// Wallet minting encrypts keys under the secret box, which can fail when that
+// key is misconfigured (for example under the JWT_SECRET fallback, see
+// api/_lib/secret-box.js). That must never brick creating an agent. The
+// platform mints wallets lazily and idempotently on first use (ensureAgentWallet
+// / getOrCreateAgentEvmWallet), so a walletless identity self-heals the next
+// time it touches a wallet once the key is configured, which is exactly how
+// the avatar-agent path degrades. On failure the agent is created with a null
+// wallet_address and no encrypted keys, and a warning is logged (never the
+// secret-box internals). Returns { walletAddress, meta } for the INSERT.
+export async function mintAgentWalletMeta() {
+ try {
+ const [wallet, sol] = await Promise.all([generateAgentWallet(), generateSolanaAgentWallet()]);
+ return {
+ walletAddress: wallet.address,
+ meta: {
+ encrypted_wallet_key: wallet.encrypted_key,
+ solana_address: sol.address,
+ encrypted_solana_secret: sol.encrypted_secret,
+ },
+ };
+ } catch (err) {
+ console.warn(
+ '[agents] wallet provisioning deferred: minting failed at create time, ' +
+ 'agent will be provisioned lazily on first wallet use:',
+ err?.message,
+ );
+ return { walletAddress: null, meta: {} };
+ }
+}
+
+/**
+ * Create an agent owned by `userId`.
+ *
+ * @param {object} p
+ * @param {string} p.userId
+ * @param {string} p.name already trimmed, 1-100 chars
+ * @param {string} [p.description]
+ * @param {string[]} [p.personaToneTags] fed to the identity-integrity screen
+ * @param {string|null} [p.avatarId] an avatar the caller owns (checked by caller)
+ * @param {string[]} [p.skills]
+ * @param {object} [p.meta] extra meta merged under the wallet keys
+ * @param {string|null} [p.personaPrompt] the brain's persona (persona_prompt column)
+ * @returns {Promise<{ agent: object } | { blocked: { message: string, integrity: object } }>}
+ */
+export async function createAgentIdentity({
+ userId,
+ name,
+ description = null,
+ personaToneTags,
+ avatarId = null,
+ skills = null,
+ meta: extraMeta = {},
+ personaPrompt = null,
+}) {
+ // Granite identity-integrity gate: refuse an identity that impersonates an
+ // existing public agent (embedding look-alike) or fails content screening.
+ // Best-effort: any failure, or watsonx being unconfigured, lets creation
+ // proceed rather than failing closed.
+ let integrity = null;
+ try {
+ integrity = await checkIdentityIntegrity(
+ { name, description, persona_tone_tags: personaToneTags },
+ { userId },
+ );
+ if (integrity.status === 'block') {
+ return {
+ blocked: {
+ message: integrity.reasons[0] || 'this identity conflicts with an existing agent',
+ integrity,
+ },
+ };
+ }
+ } catch (err) {
+ console.error('[agents] identity_integrity_check_failed', err);
+ integrity = null;
+ }
+
+ const { walletAddress, meta: walletMeta } = await mintAgentWalletMeta();
+ const meta = { ...(extraMeta || {}), ...walletMeta };
+ // Stamp the integrity verdict onto the identity so the profile/editor can show
+ // a "distinct identity" signal and reviewers can see what was checked at birth.
+ if (integrity && integrity.configured) {
+ meta.identity_integrity = {
+ status: integrity.status,
+ uniqueness: integrity.uniqueness,
+ guardian: integrity.guardian ? integrity.guardian.decision : null,
+ closest: integrity.similar[0]
+ ? { name: integrity.similar[0].name, score: integrity.similar[0].score }
+ : null,
+ checked_at: new Date().toISOString(),
+ };
+ }
+
+ const [agent] = await sql`
+ INSERT INTO agent_identities (user_id, name, description, skills, wallet_address, meta, avatar_id, persona_prompt)
+ VALUES (
+ ${userId},
+ ${name},
+ ${description ? String(description).slice(0, 500) : null},
+ ${skills || [...DEFAULT_AGENT_SKILLS]},
+ ${walletAddress},
+ ${JSON.stringify(meta)}::jsonb,
+ ${avatarId},
+ ${personaPrompt ? String(personaPrompt).slice(0, 8000) : null}
+ )
+ RETURNING *
+ `;
+
+ // Push the new agent's URL to IndexNow so Bing / Yandex discover it within
+ // minutes instead of waiting for the next crawl. Fire-and-forget.
+ pingIndexNow(`${env.APP_ORIGIN}/agents/${agent.id}`).catch(() => {});
+
+ // Announce the new agent on the site-wide live activity ticker. Fire-and-forget.
+ publishFeedEvent({
+ type: 'agent-deploy',
+ ts: Date.now(),
+ actor: name,
+ agentId: agent.id,
+ name,
+ }).catch(() => {});
+
+ return { agent };
+}
diff --git a/api/_lib/agents-v1/agents.js b/api/_lib/agents-v1/agents.js
new file mode 100644
index 000000000..ae6f1acdc
--- /dev/null
+++ b/api/_lib/agents-v1/agents.js
@@ -0,0 +1,191 @@
+// v1 agents: create, read, update, delete, and the running/stopped lifecycle.
+//
+// Agents are the same agent_identities rows every other surface reads; creation
+// goes through createAgentIdentity (api/_lib/agent-create.js) so a v1 agent gets
+// the identical custodial wallets, identity-integrity check and discovery pings
+// as one made in the Studio. v1-only settings (model, temperature, strategy)
+// live under meta.runtime.
+
+import { sql } from '../db.js';
+import { createAgentIdentity } from '../agent-create.js';
+import { MODEL_CATALOG } from '../chat-models.js';
+import { env } from '../env.js';
+import { apiError, strParam, numParam } from './http.js';
+import { getStrategy } from './strategies.js';
+import { createAutomation } from './automations.js';
+
+const MAX_SKILLS = 30;
+
+/** Public-safe v1 projection of an agent row, for its owner. */
+export function serializeAgent(row) {
+ const meta = row.meta || {};
+ const runtime = meta.runtime || {};
+ return {
+ id: row.id,
+ name: row.name,
+ persona: row.description || null,
+ systemPrompt: row.persona_prompt || null,
+ model: runtime.model || null,
+ temperature: runtime.temperature ?? null,
+ strategy: runtime.strategy || null,
+ skills: row.skills || [],
+ status: row.status || 'running',
+ statusChangedAt: row.status_changed_at || null,
+ wallet: {
+ solana: meta.solana_address || null,
+ evm: row.wallet_address || null,
+ },
+ avatarId: row.avatar_id || null,
+ isPublic: row.is_public !== false,
+ url: `${env.APP_ORIGIN}/agents/${row.id}`,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at || null,
+ };
+}
+
+/**
+ * Load an agent the caller owns, or throw 404 / 403.
+ * @returns {Promise<object>} the agent_identities row
+ */
+export async function loadOwnedAgent(id, userId) {
+ const [row] = await sql`SELECT * FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) throw apiError(404, 'not_found', 'No agent with that id.');
+ if (row.user_id !== userId) throw apiError(403, 'forbidden', 'This agent belongs to another account.');
+ return row;
+}
+
+function validateModel(model) {
+ if (model == null) return null;
+ if (typeof model !== 'string' || !MODEL_CATALOG[model]) {
+ throw apiError(400, 'unknown_model', 'model must be an id from GET /api/v1/models.', { parameter: 'model' });
+ }
+ if (!MODEL_CATALOG[model].tools) {
+ throw apiError(400, 'model_lacks_tools', 'That model has no tool-calling endpoint, so it cannot run an agent.', { parameter: 'model' });
+ }
+ return model;
+}
+
+function validateSkills(skills) {
+ if (skills == null) return null;
+ if (!Array.isArray(skills) || skills.length > MAX_SKILLS || skills.some((s) => typeof s !== 'string' || !/^[a-z0-9][a-z0-9-_]{0,39}$/i.test(s))) {
+ throw apiError(400, 'invalid_parameter', `skills must be an array of up to ${MAX_SKILLS} skill ids.`, { parameter: 'skills' });
+ }
+ return [...new Set(skills)];
+}
+
+function readSettings(body, { partial }) {
+ const out = {};
+ if (!partial || 'name' in body) out.name = strParam(body.name, { name: 'name', max: 80, required: !partial });
+ if ('persona' in body) out.persona = strParam(body.persona, { name: 'persona', max: 500 });
+ if ('systemPrompt' in body) out.systemPrompt = strParam(body.systemPrompt, { name: 'systemPrompt', max: 8000 });
+ if ('model' in body) out.model = validateModel(body.model);
+ if ('temperature' in body) out.temperature = numParam(body.temperature, { name: 'temperature', min: 0, max: 2 });
+ if ('skills' in body) out.skills = validateSkills(body.skills);
+ if ('strategy' in body && body.strategy != null) {
+ const s = getStrategy(body.strategy);
+ if (!s) throw apiError(400, 'unknown_strategy', 'strategy must be an id from GET /api/v1/strategies.', { parameter: 'strategy' });
+ out.strategy = s;
+ }
+ return out;
+}
+
+/** List the caller's agents, newest first, keyset-paginated. */
+export async function listAgents(userId, { limit, cursor }) {
+ let anchor = null;
+ if (cursor) {
+ [anchor] = await sql`SELECT created_at, id FROM agent_identities WHERE id = ${cursor} AND user_id = ${userId}`;
+ }
+ const rows = await sql`
+ SELECT * FROM agent_identities
+ WHERE user_id = ${userId} AND deleted_at IS NULL
+ AND (${anchor?.created_at ?? null}::timestamptz IS NULL
+ OR (created_at, id) < (${anchor?.created_at ?? null}::timestamptz, ${anchor?.id ?? null}::uuid))
+ ORDER BY created_at DESC, id DESC
+ LIMIT ${limit + 1}
+ `;
+ const hasMore = rows.length > limit;
+ const items = rows.slice(0, limit);
+ return { items: items.map(serializeAgent), hasMore, nextCursor: hasMore ? items.at(-1).id : null };
+}
+
+/**
+ * Create an agent. A strategy preset fills skills, persona text and
+ * temperature the caller left out, and installs its default automations
+ * (which never spend). Returns `{ agent, automations }`.
+ */
+export async function createAgent(userId, body) {
+ const s = readSettings(body, { partial: false });
+ const strategy = s.strategy || null;
+ const runtime = {
+ model: s.model ?? null,
+ temperature: s.temperature ?? strategy?.temperature ?? null,
+ strategy: strategy?.id ?? null,
+ };
+ const created = await createAgentIdentity({
+ userId,
+ name: s.name,
+ description: s.persona ?? null,
+ skills: s.skills ?? strategy?.skills ?? null,
+ personaPrompt: s.systemPrompt ?? strategy?.persona ?? null,
+ meta: { runtime },
+ });
+ if (created.blocked) {
+ throw apiError(409, 'identity_conflict', created.blocked.message, { integrity: created.blocked.integrity });
+ }
+ const agent = created.agent;
+ const automations = [];
+ for (const preset of strategy?.automations || []) {
+ automations.push(await createAutomation({ agent, userId, body: preset, source: `strategy:${strategy.id}` }));
+ }
+ return { agent: serializeAgent(agent), automations };
+}
+
+/** Patch an agent's settings. Unknown fields are ignored; meta is merged. */
+export async function updateAgent(agent, body) {
+ const s = readSettings(body, { partial: true });
+ const runtime = { ...(agent.meta?.runtime || {}) };
+ if ('model' in s) runtime.model = s.model;
+ if ('temperature' in s) runtime.temperature = s.temperature;
+ if (s.strategy) runtime.strategy = s.strategy.id;
+ if ('strategy' in body && body.strategy == null) runtime.strategy = null;
+ const [row] = await sql`
+ UPDATE agent_identities SET
+ name = COALESCE(${s.name ?? null}, name),
+ description = CASE WHEN ${'persona' in s} THEN ${s.persona ?? null} ELSE description END,
+ persona_prompt = CASE WHEN ${'systemPrompt' in s} THEN ${s.systemPrompt ?? null} ELSE persona_prompt END,
+ skills = COALESCE(${s.skills ?? null}::text[], skills),
+ meta = meta || ${JSON.stringify({ runtime })}::jsonb,
+ updated_at = now()
+ WHERE id = ${agent.id} AND deleted_at IS NULL
+ RETURNING *
+ `;
+ return serializeAgent(row);
+}
+
+/** Soft-delete an agent; its automations stop and its open runs are cancelled. */
+export async function deleteAgent(agent) {
+ await sql.transaction([
+ sql`UPDATE agent_identities SET deleted_at = now() WHERE id = ${agent.id}`,
+ sql`UPDATE agent_automations SET enabled = false, updated_at = now() WHERE agent_id = ${agent.id}`,
+ sql`
+ UPDATE agent_runs SET status = 'cancelled', error = 'agent deleted', finished_at = now(), updated_at = now()
+ WHERE agent_id = ${agent.id} AND status IN ('scheduled', 'queued', 'running', 'paused')
+ `,
+ sql`DELETE FROM agent_actions WHERE agent_id = ${agent.id}`,
+ sql`DELETE FROM agent_memories WHERE agent_id = ${agent.id}`,
+ ]);
+ return { id: agent.id, deleted: true };
+}
+
+/**
+ * Move an agent between running and stopped. Stopping pauses its automations,
+ * wallet intents and runs where they stand; starting resumes all of them.
+ */
+export async function setAgentStatus(agent, status) {
+ const [row] = await sql`
+ UPDATE agent_identities SET status = ${status}, status_changed_at = now(), updated_at = now()
+ WHERE id = ${agent.id} AND deleted_at IS NULL
+ RETURNING *
+ `;
+ return serializeAgent(row);
+}
diff --git a/api/_lib/agents-v1/automations.js b/api/_lib/agents-v1/automations.js
new file mode 100644
index 000000000..f7083b7c4
--- /dev/null
+++ b/api/_lib/agents-v1/automations.js
@@ -0,0 +1,676 @@
+// The v1 automation object: one trigger, one action, one guarded execution path.
+//
+// An automation is a row in agent_automations. Its trigger is evaluated here,
+// by the per-minute sweep (api/cron/agent-automations.js) or, for tips, inline
+// from the tip-recording path. Its action runs through the platform engine that
+// already owns that kind of work:
+//
+// agent_prompt → a v1 run (api/_lib/agents-v1/runs.js), driven by the run cron
+// swap | transfer → a backing wallet intent (trigger 'on_automation') executed by
+// notify fireIntentForAutomation, so spending inherits the intent
+// engine's freeze check, spend policy, per-intent caps and the
+// idempotent custody claim exactly as the wallet UI's rules do
+//
+// Existing wallet intents and pump alert rules are listed alongside as the same
+// object (source 'wallet_intent' / 'alert_rule') and can be deleted through it.
+// A stopped agent (agent_identities.status) never fires.
+
+import { CronExpressionParser } from 'cron-parser';
+import { sql } from '../db.js';
+import { apiError } from './http.js';
+import {
+ createIntent,
+ deleteIntent,
+ fireIntentForAutomation,
+ listIntents,
+ normalizeIntent,
+} from '../wallet-intents.js';
+import { fetchTokenPriceUsd } from '../market/token-market.js';
+import { getSolanaAddressBalances } from '../agent-wallet.js';
+import { recentPumpLaunches } from '../pump-launch-feed.js';
+import { fetchRecentTrades } from '../pump-alert-runner.js';
+import { solPriceUsd } from '../sol-price.js';
+import { resolveSolanaRecipient } from '../../../src/solana/sns.js';
+
+export const TRIGGER_TYPES = Object.freeze([
+ 'price_threshold',
+ 'schedule',
+ 'balance_below',
+ 'tip_received',
+ 'launch_matching',
+ 'graduation',
+ 'whale_buy',
+]);
+export const ACTION_TYPES = Object.freeze(['agent_prompt', 'swap', 'transfer', 'notify']);
+const SPEND_ACTIONS = new Set(['swap', 'transfer']);
+// Event triggers default to a cooldown so a busy market cannot start a run per
+// event; schedule/price/balance are already edge- or period-bounded.
+const DEFAULT_COOLDOWN_MIN = { launch_matching: 15, graduation: 15, whale_buy: 15, tip_received: 0 };
+const MIN_SCHEDULE_GAP_MS = 5 * 60 * 1000;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const MAX_PER_AGENT = 50;
+
+function bad(code, message, details = null) {
+ return apiError(400, code, message, details);
+}
+
+function posNumber(v, name, { min = 0, exclusive = true, max = Number.MAX_SAFE_INTEGER } = {}) {
+ const n = Number(v);
+ if (!Number.isFinite(n) || (exclusive ? n <= min : n < min) || n > max) {
+ throw bad('invalid_parameter', `${name} must be a number ${exclusive ? 'greater than' : 'of at least'} ${min}.`, { parameter: name });
+ }
+ return n;
+}
+
+function mintParam(v, name) {
+ if (typeof v !== 'string' || !BASE58_RE.test(v.trim())) {
+ throw bad('invalid_parameter', `${name} must be a Solana mint address.`, { parameter: name });
+ }
+ return v.trim();
+}
+
+/** Validate a 5-field cron expression and refuse cadences tighter than five minutes. */
+export function validateCron(expr) {
+ if (typeof expr !== 'string' || expr.trim().split(/\s+/).length !== 5) {
+ throw bad('invalid_cron', 'schedule.cron must be a 5-field cron expression in UTC, e.g. "0 13 * * *".');
+ }
+ let it;
+ try {
+ it = CronExpressionParser.parse(expr.trim(), { currentDate: new Date(), tz: 'UTC' });
+ } catch (err) {
+ throw bad('invalid_cron', `schedule.cron is not valid: ${err.message}`);
+ }
+ const a = it.next().toDate().getTime();
+ const b = it.next().toDate().getTime();
+ if (b - a < MIN_SCHEDULE_GAP_MS) throw bad('invalid_cron', 'schedule.cron may fire at most once every 5 minutes.');
+ return expr.trim();
+}
+
+function normalizeTrigger(t) {
+ if (!t || typeof t !== 'object') throw bad('missing_parameter', 'trigger is required.', { parameter: 'trigger' });
+ const type = String(t.type || '');
+ if (!TRIGGER_TYPES.includes(type)) {
+ throw bad('invalid_trigger', `trigger.type must be one of: ${TRIGGER_TYPES.join(', ')}.`);
+ }
+ const out = { type };
+ switch (type) {
+ case 'price_threshold':
+ out.mint = mintParam(t.mint, 'trigger.mint');
+ if (!['above', 'below'].includes(t.operator)) throw bad('invalid_parameter', 'trigger.operator must be "above" or "below".');
+ out.operator = t.operator;
+ out.priceUsd = posNumber(t.priceUsd, 'trigger.priceUsd');
+ break;
+ case 'schedule':
+ out.cron = validateCron(t.cron);
+ break;
+ case 'balance_below':
+ out.thresholdSol = posNumber(t.thresholdSol, 'trigger.thresholdSol');
+ break;
+ case 'tip_received':
+ out.minSol = t.minSol == null ? 0 : posNumber(t.minSol, 'trigger.minSol', { exclusive: false });
+ break;
+ case 'launch_matching':
+ if (t.creator != null) out.creator = mintParam(t.creator, 'trigger.creator');
+ if (t.maxMcapUsd != null) out.maxMcapUsd = posNumber(t.maxMcapUsd, 'trigger.maxMcapUsd');
+ if (t.minMcapUsd != null) out.minMcapUsd = posNumber(t.minMcapUsd, 'trigger.minMcapUsd');
+ if (!out.creator && out.maxMcapUsd == null) {
+ throw bad('invalid_trigger', 'launch_matching needs a creator address, a maxMcapUsd, or both.');
+ }
+ break;
+ case 'graduation':
+ if (t.mint != null) out.mint = mintParam(t.mint, 'trigger.mint');
+ break;
+ case 'whale_buy':
+ out.mint = mintParam(t.mint, 'trigger.mint');
+ out.minSol = posNumber(t.minSol, 'trigger.minSol');
+ break;
+ }
+ const cd = t.cooldownMinutes ?? DEFAULT_COOLDOWN_MIN[type] ?? 0;
+ out.cooldownMinutes = posNumber(cd, 'trigger.cooldownMinutes', { exclusive: false, max: 10_080 });
+ return out;
+}
+
+function normalizeAction(a, trigger) {
+ if (!a || typeof a !== 'object') throw bad('missing_parameter', 'action is required.', { parameter: 'action' });
+ const type = String(a.type || '');
+ if (!ACTION_TYPES.includes(type)) throw bad('invalid_action', `action.type must be one of: ${ACTION_TYPES.join(', ')}.`);
+ const out = { type };
+ switch (type) {
+ case 'agent_prompt': {
+ const prompt = typeof a.prompt === 'string' ? a.prompt.trim() : '';
+ if (!prompt) throw bad('missing_parameter', 'action.prompt is required.', { parameter: 'action.prompt' });
+ if (prompt.length > 2000) throw bad('invalid_parameter', 'action.prompt must be at most 2000 characters.');
+ out.prompt = prompt;
+ if (a.maxSteps != null) {
+ const n = Number(a.maxSteps);
+ if (!Number.isInteger(n) || n < 1 || n > 30) throw bad('invalid_parameter', 'action.maxSteps must be an integer from 1 to 30.');
+ out.maxSteps = n;
+ }
+ if (a.budgetCreditsUsd != null) out.budgetCreditsUsd = posNumber(a.budgetCreditsUsd, 'action.budgetCreditsUsd', { exclusive: false, max: 100 });
+ break;
+ }
+ case 'swap': {
+ const fromEvent = trigger.type === 'launch_matching' || trigger.type === 'graduation';
+ if (a.mint != null) out.mint = mintParam(a.mint, 'action.mint');
+ else if (!fromEvent) throw bad('missing_parameter', 'action.mint is required for a swap.', { parameter: 'action.mint' });
+ else out.mintFromEvent = true;
+ out.amountSol = posNumber(a.amountSol, 'action.amountSol', { max: 1000 });
+ out.slippagePct = a.slippagePct == null ? 5 : posNumber(a.slippagePct, 'action.slippagePct', { max: 50 });
+ break;
+ }
+ case 'transfer':
+ if (typeof a.destination !== 'string' || !a.destination.trim()) {
+ throw bad('missing_parameter', 'action.destination is required for a transfer.', { parameter: 'action.destination' });
+ }
+ out.destination = a.destination.trim();
+ out.amountSol = posNumber(a.amountSol, 'action.amountSol', { max: 1000 });
+ break;
+ case 'notify':
+ out.message = typeof a.message === 'string' && a.message.trim() ? a.message.trim().slice(0, 280) : null;
+ break;
+ }
+ return out;
+}
+
+/**
+ * Validate a create payload into `{ title, trigger, action, triggerOnce, limits }`.
+ * Throws an ApiError with a stable code on bad input.
+ */
+export function normalizeAutomation(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const trigger = normalizeTrigger(r.trigger);
+ const action = normalizeAction(r.action, trigger);
+ const title = typeof r.title === 'string' && r.title.trim() ? r.title.trim().slice(0, 80) : defaultTitle(trigger, action);
+ const limits = {};
+ if (r.limits && typeof r.limits === 'object') {
+ for (const k of ['perActionUsd', 'dailyUsd', 'totalUsd']) {
+ if (r.limits[k] != null) limits[k] = posNumber(r.limits[k], `limits.${k}`);
+ }
+ }
+ return { title, trigger, action, triggerOnce: r.triggerOnce === true, limits };
+}
+
+function defaultTitle(trigger, action) {
+ const what = { agent_prompt: 'run the agent', swap: 'buy', transfer: 'send SOL', notify: 'notify me' }[action.type];
+ const when = {
+ price_threshold: `price ${trigger.operator} $${trigger.priceUsd}`,
+ schedule: `on schedule ${trigger.cron}`,
+ balance_below: `balance below ${trigger.thresholdSol} SOL`,
+ tip_received: 'on a tip',
+ launch_matching: 'on a matching launch',
+ graduation: 'on a graduation',
+ whale_buy: `on a whale buy over ${trigger.minSol} SOL`,
+ }[trigger.type];
+ return `When ${when}, ${what}`.slice(0, 80);
+}
+
+/** The wallet-intent payload that executes a spend/notify action. */
+function backingIntentPayload(a, title) {
+ const limits = {
+ per_action_usd: a.limits.perActionUsd ?? null,
+ daily_usd: a.limits.dailyUsd ?? null,
+ total_usd: a.limits.totalUsd ?? null,
+ };
+ const base = { title, trigger_type: 'on_automation', trigger_config: {}, limits };
+ if (a.action.type === 'swap') {
+ return {
+ ...base,
+ action_type: 'buy',
+ action_config: {
+ mint: a.action.mint || null,
+ mint_from_event: a.action.mintFromEvent === true,
+ amount_sol: a.action.amountSol,
+ slippage_pct: a.action.slippagePct,
+ },
+ };
+ }
+ if (a.action.type === 'transfer') {
+ return { ...base, action_type: 'transfer', action_config: { destination: a.action.destination, amount_sol: a.action.amountSol } };
+ }
+ return { ...base, action_type: 'notify', action_config: { message: a.action.message, channel: 'email' } };
+}
+
+// ── serialization ────────────────────────────────────────────────────────────
+
+export function serializeAutomation(row) {
+ return {
+ id: row.id,
+ agentId: row.agent_id,
+ source: 'automation',
+ title: row.title,
+ trigger: row.trigger_config,
+ action: row.action_config,
+ triggerOnce: row.trigger_once,
+ enabled: row.enabled,
+ intentId: row.intent_id || null,
+ stats: {
+ fireCount: row.fire_count,
+ lastFiredAt: row.last_fired_at,
+ lastCheckedAt: row.last_checked_at,
+ lastStatus: row.last_status,
+ lastNote: row.last_note,
+ },
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+}
+
+const INTENT_TRIGGER_NAMES = {
+ on_schedule: 'schedule',
+ on_balance_below: 'balance_below',
+ on_tip_received: 'tip_received',
+ on_launch_matching: 'launch_matching',
+};
+const INTENT_ACTION_NAMES = { buy: 'swap', snipe: 'swap', transfer: 'transfer', notify: 'notify' };
+
+function serializeIntent(intent) {
+ const { type: tType, ...tCfg } = intent.trigger;
+ const { type: aType, ...aCfg } = intent.action;
+ return {
+ id: intent.id,
+ agentId: intent.agent_id,
+ source: 'wallet_intent',
+ title: intent.title,
+ trigger: { type: INTENT_TRIGGER_NAMES[tType] || tType, ...tCfg },
+ action: { type: INTENT_ACTION_NAMES[aType] || aType, ...aCfg },
+ triggerOnce: false,
+ enabled: intent.enabled,
+ intentId: intent.id,
+ stats: {
+ fireCount: intent.stats.fire_count,
+ lastFiredAt: intent.stats.last_fired_at,
+ lastCheckedAt: null,
+ lastStatus: intent.stats.last_status,
+ lastNote: intent.stats.last_note,
+ },
+ createdAt: intent.created_at,
+ updatedAt: intent.updated_at,
+ };
+}
+
+function serializeAlertRule(r) {
+ const trigger =
+ r.kind === 'graduation'
+ ? { type: 'graduation', mint: r.target_mint || undefined, agentId: r.target_agent || undefined }
+ : r.kind === 'whale_buy'
+ ? { type: 'whale_buy', mint: r.target_mint, minSol: Number(r.threshold) }
+ : r.kind === 'new_mint'
+ ? { type: 'new_mint', agentId: r.target_agent }
+ : { type: 'market_cap_threshold', mint: r.target_mint, operator: r.kind === 'price_above' ? 'above' : 'below', marketCapUsd: Number(r.threshold) };
+ const channels = [r.deliver_in_app && 'in_app', r.webhook_url && 'webhook', r.telegram_chat && 'telegram'].filter(Boolean);
+ return {
+ id: r.id,
+ agentId: null,
+ source: 'alert_rule',
+ title: r.label,
+ trigger: { ...trigger, cooldownMinutes: Math.round((r.cooldown_seconds || 0) / 60) },
+ action: { type: 'notify', channels },
+ triggerOnce: false,
+ enabled: r.enabled,
+ intentId: null,
+ stats: { fireCount: null, lastFiredAt: r.last_fired_at || null, lastCheckedAt: null, lastStatus: null, lastNote: null },
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ };
+}
+
+// ── CRUD ─────────────────────────────────────────────────────────────────────
+
+/**
+ * Create an automation on an agent the caller owns. Spend actions need
+ * `confirm: true`: the owner is authorizing future autonomous spending.
+ */
+export async function createAutomation({ agent, userId, body, source = 'api' }) {
+ const a = normalizeAutomation(body);
+ if (SPEND_ACTIONS.has(a.action.type) && body.confirm !== true) {
+ throw apiError(400, 'confirmation_required', `A ${a.action.type} automation spends from the agent wallet on its own. Resend with "confirm": true to authorize it.`, {
+ action: a.action,
+ trigger: a.trigger,
+ });
+ }
+ const [{ n }] = await sql`SELECT count(*)::int AS n FROM agent_automations WHERE agent_id = ${agent.id}`;
+ if (n >= MAX_PER_AGENT) throw apiError(409, 'automation_limit', `An agent can hold at most ${MAX_PER_AGENT} automations.`);
+
+ if (a.action.type === 'transfer') {
+ const dest = await resolveSolanaRecipient(a.action.destination).catch(() => null);
+ const address = dest?.address || (BASE58_RE.test(a.action.destination) ? a.action.destination : null);
+ if (!address) throw bad('invalid_parameter', 'action.destination must be a Solana address or .sol name.', { parameter: 'action.destination' });
+ a.action.destination = address;
+ }
+
+ let intentId = null;
+ if (a.action.type !== 'agent_prompt') {
+ const norm = normalizeIntent(backingIntentPayload(a, a.title));
+ if (!norm.ok) throw bad(norm.error, norm.message);
+ const intent = await createIntent(agent.id, userId, norm.intent, { sourceText: `v1 automation: ${a.title}` });
+ intentId = intent.id;
+ }
+ const [row] = await sql`
+ INSERT INTO agent_automations
+ (agent_id, user_id, title, trigger_type, trigger_config, action_type, action_config, trigger_once, intent_id, source, last_checked_at)
+ VALUES (
+ ${agent.id}, ${userId}, ${a.title}, ${a.trigger.type}, ${JSON.stringify(a.trigger)}::jsonb,
+ ${a.action.type}, ${JSON.stringify(a.action)}::jsonb, ${a.triggerOnce}, ${intentId}, ${source}, now()
+ )
+ RETURNING *
+ `;
+ return serializeAutomation(row);
+}
+
+/** Every automation on one agent: native rows plus the wallet intents not backing one. */
+export async function listAgentAutomations(agentId) {
+ const [rows, intents] = await Promise.all([
+ sql`SELECT * FROM agent_automations WHERE agent_id = ${agentId} ORDER BY created_at DESC`,
+ listIntents(agentId),
+ ]);
+ const backing = new Set(rows.map((r) => r.intent_id).filter(Boolean));
+ return [
+ ...rows.map(serializeAutomation),
+ ...intents.filter((i) => !backing.has(i.id)).map(serializeIntent),
+ ];
+}
+
+/** Every automation across the caller's agents, plus their account-level alert rules. */
+export async function listUserAutomations(userId) {
+ const [rows, intentRows, rules] = await Promise.all([
+ sql`SELECT * FROM agent_automations WHERE user_id = ${userId} ORDER BY created_at DESC LIMIT 500`,
+ sql`
+ SELECT w.* FROM agent_wallet_intents w
+ JOIN agent_identities i ON i.id = w.agent_id AND i.deleted_at IS NULL
+ WHERE i.user_id = ${userId}
+ ORDER BY w.created_at DESC LIMIT 500
+ `,
+ sql`
+ SELECT r.*, f.last_fired_at FROM pump_alert_rules r
+ LEFT JOIN pump_alert_rule_fires f ON f.rule_id = r.id
+ WHERE r.user_id = ${userId}
+ ORDER BY r.created_at DESC LIMIT 500
+ `,
+ ]);
+ const backing = new Set(rows.map((r) => r.intent_id).filter(Boolean));
+ const standalone = new Set(intentRows.filter((w) => !backing.has(w.id)).map((w) => w.id));
+ const agentIds = [...new Set(intentRows.filter((w) => standalone.has(w.id)).map((w) => w.agent_id))];
+ const intents = (await Promise.all(agentIds.map((id) => listIntents(id)))).flat().filter((i) => standalone.has(i.id));
+ return [
+ ...rows.map(serializeAutomation),
+ ...intents.map(serializeIntent),
+ ...rules.map(serializeAlertRule),
+ ];
+}
+
+/** Delete any automation-shaped object the caller owns, whatever its source. */
+export async function deleteAutomation(userId, id) {
+ const [row] = await sql`DELETE FROM agent_automations WHERE id = ${id} AND user_id = ${userId} RETURNING agent_id, intent_id`;
+ if (row) {
+ if (row.intent_id) await deleteIntent(row.agent_id, userId, row.intent_id);
+ return { id, source: 'automation', deleted: true };
+ }
+ const [intent] = await sql`
+ SELECT w.id, w.agent_id FROM agent_wallet_intents w
+ JOIN agent_identities i ON i.id = w.agent_id
+ WHERE w.id = ${id} AND i.user_id = ${userId}
+ `;
+ if (intent) {
+ await deleteIntent(intent.agent_id, userId, id);
+ return { id, source: 'wallet_intent', deleted: true };
+ }
+ const [rule] = await sql`DELETE FROM pump_alert_rules WHERE id = ${id} AND user_id = ${userId} RETURNING id`;
+ if (rule) return { id, source: 'alert_rule', deleted: true };
+ throw apiError(404, 'not_found', 'No automation with that id.');
+}
+
+// ── evaluation ───────────────────────────────────────────────────────────────
+
+function cooledDown(row, now) {
+ const mins = Number(row.trigger_config?.cooldownMinutes || 0);
+ if (!mins || !row.last_fired_at) return true;
+ return now.getTime() - new Date(row.last_fired_at).getTime() >= mins * 60_000;
+}
+
+/** When a schedule automation is next due, from its last fire (or creation). */
+export function nextScheduledAt(row) {
+ const from = row.last_fired_at || row.created_at;
+ const it = CronExpressionParser.parse(row.trigger_config.cron, { currentDate: new Date(from), tz: 'UTC' });
+ return it.next().toDate();
+}
+
+/** Edge-triggered price check: fire when the price moves onto the target side. */
+export function evaluatePriceThreshold(trigger, priceUsd, state = {}) {
+ const side = priceUsd > trigger.priceUsd ? 'above' : priceUsd < trigger.priceUsd ? 'below' : state.side || null;
+ const fire = side === trigger.operator && state.side !== trigger.operator;
+ return { fire, state: { side, priceUsd } };
+}
+
+async function stamp(row, { fired, status, note, state }) {
+ await sql`
+ UPDATE agent_automations SET
+ fire_count = fire_count + ${fired ? 1 : 0},
+ last_fired_at = CASE WHEN ${fired} THEN now() ELSE last_fired_at END,
+ last_checked_at = now(),
+ last_status = COALESCE(${status}, last_status),
+ last_note = COALESCE(${note ? String(note).slice(0, 280) : null}, last_note),
+ state = COALESCE(${state ? JSON.stringify(state) : null}::jsonb, state),
+ enabled = CASE WHEN ${fired} AND trigger_once THEN false ELSE enabled END,
+ updated_at = now()
+ WHERE id = ${row.id}
+ `;
+}
+
+function eventSummary(event) {
+ const parts = [];
+ if (event.mint) parts.push(`mint ${event.mint}`);
+ if (event.symbol) parts.push(`symbol ${event.symbol}`);
+ if (event.priceUsd != null) parts.push(`price $${event.priceUsd}`);
+ if (event.marketCapUsd != null) parts.push(`market cap $${Math.round(event.marketCapUsd)}`);
+ if (event.amount_sol != null) parts.push(`${event.amount_sol} SOL`);
+ if (event.balance_sol != null) parts.push(`balance ${event.balance_sol} SOL`);
+ if (event.from) parts.push(`from ${event.from}`);
+ if (event.signature) parts.push(`tx ${event.signature}`);
+ return parts.join(', ');
+}
+
+/**
+ * Fire one automation's action for an event. `key` makes the fire idempotent:
+ * the same (automation, key) never executes twice.
+ */
+export async function fireAutomation(row, event, key) {
+ const discriminator = `auto:${row.id}:${key}`;
+ if (row.action_type === 'agent_prompt') {
+ const { createRun } = await import('./runs.js');
+ const context = eventSummary(event);
+ const run = await createRun({
+ agentId: row.agent_id,
+ userId: row.user_id,
+ goal: context ? `${row.action_config.prompt}\n\nTrigger: ${row.trigger_type} (${context}).` : row.action_config.prompt,
+ maxSteps: row.action_config.maxSteps,
+ budgetCreditsUsd: row.action_config.budgetCreditsUsd || 0,
+ source: 'automation',
+ automationId: row.id,
+ triggerKey: key.slice(0, 200),
+ });
+ if (!run) return { fired: false, status: 'skipped', note: 'already ran for this event' };
+ await stamp(row, { fired: true, status: 'run_started', note: `run ${run.id}` });
+ return { fired: true, status: 'run_started', runId: run.id };
+ }
+ const res = await fireIntentForAutomation({
+ agentId: row.agent_id,
+ intentId: row.intent_id,
+ discriminator,
+ event,
+ });
+ const fired = res.status === 'ok' || res.status === 'notified';
+ await stamp(row, { fired, status: res.status, note: res.note || res.signature || null });
+ return { fired, status: res.status, note: res.note || null, signature: res.signature || null };
+}
+
+async function liveRows(types) {
+ return sql`
+ SELECT a.*, i.meta AS agent_meta
+ FROM agent_automations a
+ JOIN agent_identities i ON i.id = a.agent_id AND i.deleted_at IS NULL AND i.status = 'running'
+ WHERE a.enabled = true AND a.trigger_type = ANY(${types})
+ ORDER BY a.last_checked_at ASC NULLS FIRST
+ LIMIT 500
+ `;
+}
+
+/**
+ * One sweep over every live automation with a polled trigger. Returns a tally
+ * the cron logs. Errors in one automation never stop the rest.
+ */
+export async function runAutomationSweep({ now = new Date() } = {}) {
+ const rows = await liveRows(['schedule', 'price_threshold', 'balance_below', 'launch_matching', 'graduation', 'whale_buy']);
+ const summary = { scanned: rows.length, fired: 0, errors: 0, by_trigger: {} };
+ if (!rows.length) return summary;
+
+ const byType = (t) => rows.filter((r) => r.trigger_type === t);
+ const tally = (t, r) => {
+ summary.by_trigger[t] = (summary.by_trigger[t] || 0) + 1;
+ if (r?.fired) summary.fired++;
+ };
+ const guard = async (row, fn) => {
+ try {
+ const r = await fn();
+ tally(row.trigger_type, r);
+ } catch (err) {
+ summary.errors++;
+ console.warn(`[automations] ${row.id} failed:`, err?.message || err);
+ await stamp(row, { fired: false, status: 'error', note: err?.message || 'failed' }).catch(() => {});
+ }
+ };
+
+ // schedule
+ for (const row of byType('schedule')) {
+ await guard(row, async () => {
+ const due = nextScheduledAt(row);
+ if (due > now) return null;
+ return fireAutomation(row, {}, `sched:${due.toISOString()}`);
+ });
+ }
+
+ // price_threshold: one price read per distinct mint
+ const priceRows = byType('price_threshold');
+ const prices = new Map();
+ for (const mint of [...new Set(priceRows.map((r) => r.trigger_config.mint))].slice(0, 60)) {
+ prices.set(mint, await fetchTokenPriceUsd(mint).catch(() => null));
+ }
+ for (const row of priceRows) {
+ await guard(row, async () => {
+ const price = prices.get(row.trigger_config.mint);
+ if (price == null) return stamp(row, { fired: false, status: 'no_price', note: 'no live price for this mint' }).then(() => null);
+ const verdict = evaluatePriceThreshold(row.trigger_config, price, row.state || {});
+ if (!verdict.fire || !cooledDown(row, now)) {
+ await stamp(row, { fired: false, status: null, note: null, state: verdict.state });
+ return null;
+ }
+ await sql`UPDATE agent_automations SET state = ${JSON.stringify(verdict.state)}::jsonb WHERE id = ${row.id}`;
+ return fireAutomation(row, { mint: row.trigger_config.mint, priceUsd: price }, `price:${now.toISOString().slice(0, 16)}`);
+ });
+ }
+
+ // balance_below: once per UTC day while below the floor
+ for (const row of byType('balance_below')) {
+ await guard(row, async () => {
+ const address = row.agent_meta?.solana_address;
+ if (!address) return stamp(row, { fired: false, status: 'no_wallet', note: 'agent has no Solana wallet yet' }).then(() => null);
+ const sol = Number((await getSolanaAddressBalances(address, 'mainnet'))?.sol);
+ if (!Number.isFinite(sol) || sol >= row.trigger_config.thresholdSol) {
+ await stamp(row, { fired: false, status: null, note: null, state: { balanceSol: sol } });
+ return null;
+ }
+ if (!cooledDown(row, now)) return null;
+ return fireAutomation(row, { balance_sol: sol }, `bal:${now.toISOString().slice(0, 10)}`);
+ });
+ }
+
+ // launch_matching: one shared pull of recent launches
+ const launchRows = byType('launch_matching');
+ if (launchRows.length) {
+ const launches = await recentPumpLaunches({ network: 'mainnet', limit: 60 }).catch(() => []);
+ for (const row of launchRows) {
+ await guard(row, async () => {
+ const t = row.trigger_config;
+ const since = row.state?.lastSeenAt || new Date(row.last_checked_at || row.created_at).getTime();
+ const match = launches.find(
+ (l) =>
+ l.created_at != null &&
+ l.created_at > since &&
+ (!t.creator || l.creator === t.creator) &&
+ (t.maxMcapUsd == null || (l.market_cap_usd != null && l.market_cap_usd <= t.maxMcapUsd)) &&
+ (t.minMcapUsd == null || (l.market_cap_usd != null && l.market_cap_usd >= t.minMcapUsd)),
+ );
+ const newest = Math.max(since, ...launches.map((l) => l.created_at || 0));
+ await stamp(row, { fired: false, status: null, note: null, state: { lastSeenAt: newest } });
+ if (!match || !cooledDown(row, now)) return null;
+ return fireAutomation(row, { mint: match.mint, symbol: match.symbol, marketCapUsd: match.market_cap_usd }, `launch:${match.mint}`);
+ });
+ }
+ }
+
+ // graduation: the persisted graduation feed
+ const gradRows = byType('graduation');
+ if (gradRows.length) {
+ const grads = await sql`
+ SELECT tx_signature, mint, symbol, market_cap_usd, seen_at FROM pumpfun_graduations
+ WHERE seen_at > now() - interval '30 minutes' ORDER BY seen_at DESC LIMIT 200
+ `;
+ for (const row of gradRows) {
+ await guard(row, async () => {
+ const since = new Date(row.last_checked_at || row.created_at);
+ const match = grads.find((g) => new Date(g.seen_at) > since && (!row.trigger_config.mint || g.mint === row.trigger_config.mint));
+ await stamp(row, { fired: false, status: null, note: null });
+ if (!match || !cooledDown(row, now)) return null;
+ return fireAutomation(row, { mint: match.mint, symbol: match.symbol, marketCapUsd: match.market_cap_usd != null ? Number(match.market_cap_usd) : null, signature: match.tx_signature }, `grad:${match.mint}`);
+ });
+ }
+ }
+
+ // whale_buy: recent trades per distinct mint
+ const whaleRows = byType('whale_buy');
+ if (whaleRows.length) {
+ const solPrice = await solPriceUsd().catch(() => 0);
+ const trades = new Map();
+ for (const mint of [...new Set(whaleRows.map((r) => r.trigger_config.mint))].slice(0, 60)) {
+ trades.set(mint, await fetchRecentTrades(mint, solPrice).catch(() => []));
+ }
+ for (const row of whaleRows) {
+ await guard(row, async () => {
+ const since = new Date(row.last_checked_at || row.created_at);
+ const hit = (trades.get(row.trigger_config.mint) || []).find(
+ (t) => t.is_buy && t.sol_amount >= row.trigger_config.minSol && t.ts && t.ts > since,
+ );
+ await stamp(row, { fired: false, status: null, note: null });
+ if (!hit || !cooledDown(row, now)) return null;
+ return fireAutomation(row, { mint: row.trigger_config.mint, amount_sol: hit.sol_amount, from: hit.buyer, signature: hit.signature }, `whale:${hit.signature || hit.ts.toISOString()}`);
+ });
+ }
+ }
+
+ return summary;
+}
+
+/**
+ * Fired from the tip-recording path with a freshly recorded, real tip.
+ * @param {string} agentId
+ * @param {{ signature?: string, amount_sol?: number|null, from?: string|null, network?: string }} tip
+ */
+export async function onAutomationTip(agentId, tip) {
+ if (tip.network === 'devnet') return { fired: 0 };
+ const rows = await sql`
+ SELECT a.* FROM agent_automations a
+ JOIN agent_identities i ON i.id = a.agent_id AND i.deleted_at IS NULL AND i.status = 'running'
+ WHERE a.agent_id = ${agentId} AND a.enabled = true AND a.trigger_type = 'tip_received'
+ `;
+ let fired = 0;
+ const now = new Date();
+ for (const row of rows) {
+ if ((tip.amount_sol ?? 0) < (row.trigger_config.minSol || 0) || !cooledDown(row, now)) continue;
+ try {
+ const r = await fireAutomation(row, { amount_sol: tip.amount_sol ?? null, from: tip.from || null, signature: tip.signature || null }, `tip:${tip.signature || now.toISOString()}`);
+ if (r.fired) fired++;
+ } catch (err) {
+ console.warn(`[automations] tip fire ${row.id} failed:`, err?.message || err);
+ }
+ }
+ return { fired };
+}
diff --git a/api/_lib/agents-v1/forward.js b/api/_lib/agents-v1/forward.js
new file mode 100644
index 000000000..45b356a67
--- /dev/null
+++ b/api/_lib/agents-v1/forward.js
@@ -0,0 +1,119 @@
+// Call an existing /api handler in-process from a v1 route and turn its
+// response into a v1 result, so a v1 route reuses the handler's whole guard
+// chain (ownership, spend policy, real-funds agreement, CSRF, rate limits,
+// custody ledger) instead of re-implementing it.
+//
+// The forwarded request keeps the caller's headers (so the handler resolves the
+// same principal from the same bearer or session cookie) and carries the new
+// body as `rawBody`, which api/_lib/http.js readBody prefers over the already
+// drained stream. The legacy envelope `{ error, error_description, ...extra }`
+// becomes an ApiError with the same status and code, extra as details.
+
+import { apiError } from './http.js';
+
+/**
+ * @param {(req: object, res: object) => Promise<void>} handler
+ * @param {object} ctx the v1 route ctx (uses ctx.req)
+ * @param {object} o
+ * @param {'GET'|'POST'|'PUT'|'PATCH'|'DELETE'} o.method
+ * @param {string} o.url path + query the handler sees, e.g. '/api/agents/<id>/solana?network=mainnet'
+ * @param {object} [o.body] JSON body for writes
+ * @returns {Promise<{ status: number, body: any, headers: Record<string, string> }>}
+ */
+export async function forward(handler, ctx, { method, url, body }) {
+ const headers = { ...ctx.req.headers };
+ delete headers['content-length'];
+ delete headers['transfer-encoding'];
+ let rawBody;
+ if (body !== undefined) {
+ rawBody = Buffer.from(JSON.stringify(body));
+ headers['content-type'] = 'application/json';
+ headers['content-length'] = String(rawBody.length);
+ }
+ // Inherit socket and connection info from the real request; override what
+ // the target handler reads.
+ const req = Object.create(ctx.req, {
+ method: { value: method, writable: true },
+ url: { value: url, writable: true },
+ headers: { value: headers, writable: true },
+ rawBody: { value: rawBody, writable: true },
+ body: { value: body, writable: true },
+ query: { value: Object.fromEntries(new URL(url, 'http://internal').searchParams), writable: true },
+ });
+
+ const res = new CapturedResponse();
+ await handler(req, res);
+ return { status: res.statusCode, body: res.json(), headers: res.headers };
+}
+
+/**
+ * Forward and unwrap: a 2xx returns the handler's `data` (or the whole body
+ * when it has no `data` key); anything else throws an ApiError.
+ */
+export async function forwardData(handler, ctx, opts) {
+ const out = await forward(handler, ctx, opts);
+ if (out.status >= 200 && out.status < 300) {
+ const b = out.body;
+ return b && typeof b === 'object' && 'data' in b ? b.data : b;
+ }
+ throw toApiError(out);
+}
+
+/** Convert a captured non-2xx legacy response into an ApiError. */
+export function toApiError({ status, body }) {
+ if (body && typeof body === 'object') {
+ if (body.error && typeof body.error === 'object') {
+ return apiError(status, body.error.code || 'error', body.error.message || 'Request failed.', body.error.details ?? null);
+ }
+ const { error: code, error_description: message, ...extra } = body;
+ if (typeof code === 'string') {
+ return apiError(status, code, message || code, Object.keys(extra).length ? extra : null);
+ }
+ }
+ return apiError(status >= 400 ? status : 502, 'upstream_error', 'The request failed.');
+}
+
+class CapturedResponse {
+ constructor() {
+ this.statusCode = 200;
+ this.headers = {};
+ this.headersSent = false;
+ this.writableEnded = false;
+ this.chunks = [];
+ }
+ setHeader(k, v) {
+ this.headers[String(k).toLowerCase()] = Array.isArray(v) ? v.join(', ') : String(v);
+ }
+ getHeader(k) {
+ return this.headers[String(k).toLowerCase()];
+ }
+ removeHeader(k) {
+ delete this.headers[String(k).toLowerCase()];
+ }
+ writeHead(status, headers) {
+ this.statusCode = status;
+ if (headers) for (const [k, v] of Object.entries(headers)) this.setHeader(k, v);
+ this.headersSent = true;
+ return this;
+ }
+ write(chunk) {
+ this.headersSent = true;
+ if (chunk != null) this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
+ return true;
+ }
+ end(chunk) {
+ if (chunk != null) this.write(chunk);
+ this.headersSent = true;
+ this.writableEnded = true;
+ return this;
+ }
+ json() {
+ const text = Buffer.concat(this.chunks).toString('utf8');
+ if (!text) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+ }
+}
diff --git a/api/_lib/agents-v1/http.js b/api/_lib/agents-v1/http.js
new file mode 100644
index 000000000..b2b70e1bd
--- /dev/null
+++ b/api/_lib/agents-v1/http.js
@@ -0,0 +1,341 @@
+// The v1 agents API contract: one router, one envelope, one error shape.
+//
+// Every route under /api/v1/{agents,runs,automations,models,me,intel,strategies}
+// is declared in api/v1/rest.js as a row of `defineRouter`. This module gives
+// each row the same behavior:
+//
+// • Auth three.ws API key (`Authorization: Bearer sk_live_…`), OAuth
+// access token, or a signed-in browser session.
+// • Scopes declared per route, enforced for key and OAuth callers.
+// • CSRF cookie-authenticated writes must carry X-CSRF-Token.
+// • Limits per principal (key › user › ip) via limits.apiV1.
+// • Metering every call lands in usage_events as kind 'api'.
+// • Envelope success → { data, meta: { requestId, timestamp, … } }
+// failure → { error: { code, message, details }, meta }
+// • Replay an authenticated write carrying `Idempotency-Key` runs once;
+// a retry with the same key and body gets the stored response
+// back (header `Idempotent-Replayed: true`) for 24 hours.
+//
+// A handler returns its payload, or `created(payload)` for a 201, or writes
+// the response itself (the SSE stream) and returns nothing. To fail, throw
+// `apiError(status, code, message, details)`. Anything else that throws is a
+// 500 with a sanitized message; the stable error codes are listed in
+// docs/api-reference.md.
+
+import { createHash, randomUUID } from 'node:crypto';
+import { cors, readJson, setRateLimitHeaders } from '../http.js';
+import { authenticateBearer, extractBearer, getSessionUser, hasScope } from '../auth.js';
+import { checkCsrf } from '../csrf.js';
+import { limits, clientIp } from '../rate-limit.js';
+import { recordEvent } from '../usage.js';
+import { acquireLock, cacheGet, cacheSet, releaseLock } from '../cache.js';
+
+export class ApiError extends Error {
+ /**
+ * @param {number} status
+ * @param {string} code
+ * @param {string} message
+ * @param {object|null} [details]
+ */
+ constructor(status, code, message, details = null) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ this.details = details;
+ }
+}
+
+/** Build an ApiError to throw. */
+export function apiError(status, code, message, details = null) {
+ return new ApiError(status, code, message, details);
+}
+
+const CREATED = Symbol('created');
+
+/** Mark a handler result as a 201 Created. */
+export function created(data) {
+ return { [CREATED]: true, data };
+}
+
+/** Attach pagination to a list result: `{ items, hasMore, nextCursor }`. */
+export function page(items, { hasMore, nextCursor = null }) {
+ return { __page: true, items, hasMore: Boolean(hasMore), nextCursor };
+}
+
+function meta(ctx, extra = {}) {
+ return { requestId: ctx.requestId, timestamp: new Date().toISOString(), ...extra };
+}
+
+function send(res, status, body) {
+ if (res.headersSent || res.writableEnded) return;
+ res.statusCode = status;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.end(JSON.stringify(body));
+}
+
+/** Write an error envelope. */
+export function sendError(res, ctx, status, code, message, details = null) {
+ send(res, status, { error: { code, message, details }, meta: meta(ctx) });
+}
+
+/** Compile '/agents/:id/runs' into a matcher returning params or null. */
+export function compilePath(pattern) {
+ const parts = pattern.split('/').filter(Boolean);
+ return (segments) => {
+ if (segments.length !== parts.length) return null;
+ const params = {};
+ for (let i = 0; i < parts.length; i++) {
+ const p = parts[i];
+ if (p.startsWith(':')) params[p.slice(1)] = segments[i];
+ else if (p !== segments[i]) return null;
+ }
+ return params;
+ };
+}
+
+async function resolvePrincipal(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session', scope: 'all' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ return {
+ userId: bearer.userId,
+ source: bearer.source,
+ scope: bearer.scope || '',
+ apiKeyId: bearer.apiKeyId,
+ clientId: bearer.clientId,
+ };
+}
+
+/**
+ * Build the single request handler for a table of routes.
+ *
+ * @param {object} o
+ * @param {string} o.base URL prefix stripped before matching, e.g. '/api/v1'
+ * @param {Array<{ method: string, path: string, name: string, auth: 'public'|'optional'|'required',
+ * scope?: string, csrf?: boolean, handler: (ctx: object) => any }>} o.routes
+ */
+export function defineRouter({ base, routes }) {
+ const compiled = routes.map((r) => ({ ...r, match: compilePath(r.path) }));
+ const allMethods = [...new Set(routes.map((r) => r.method))];
+
+ return async function handler(req, res) {
+ const ctx = { requestId: randomUUID(), req, res };
+ res.setHeader('x-request-id', ctx.requestId);
+ if (cors(req, res, { methods: [...allMethods, 'OPTIONS'].join(','), origins: '*' })) return;
+
+ const url = new URL(req.url, 'http://internal');
+ let rel = url.pathname;
+ if (rel.startsWith(base)) rel = rel.slice(base.length);
+ let segments;
+ try {
+ segments = rel.split('/').filter(Boolean).map(decodeURIComponent);
+ } catch {
+ return sendError(res, ctx, 400, 'bad_request', 'Malformed URL encoding.');
+ }
+
+ let route = null;
+ let params = null;
+ let pathMatched = false;
+ for (const r of compiled) {
+ const p = r.match(segments);
+ if (!p) continue;
+ pathMatched = true;
+ if (r.method === req.method) {
+ route = r;
+ params = p;
+ break;
+ }
+ }
+ if (!route) {
+ return pathMatched
+ ? sendError(res, ctx, 405, 'method_not_allowed', `${req.method} is not supported on ${url.pathname}.`)
+ : sendError(res, ctx, 404, 'not_found', `No route matches ${req.method} ${url.pathname}.`);
+ }
+
+ const started = Date.now();
+ let principal = null;
+ try {
+ if (route.auth !== 'public') {
+ principal = await resolvePrincipal(req);
+ if (route.auth === 'required' && !principal) {
+ throw apiError(
+ 401,
+ 'unauthorized',
+ 'Authenticate with a three.ws API key (`Authorization: Bearer sk_live_…`) or sign in. Create a key at /dashboard/developers.',
+ );
+ }
+ if (principal && principal.source !== 'session' && route.scope && !hasScope(principal.scope, route.scope)) {
+ throw apiError(403, 'insufficient_scope', `This route requires the "${route.scope}" scope.`, {
+ required: route.scope,
+ });
+ }
+ }
+
+ const rlKey = principal?.apiKeyId
+ ? `key:${principal.apiKeyId}`
+ : principal?.userId
+ ? `user:${principal.userId}`
+ : `ip:${clientIp(req)}`;
+ const rl = await limits.apiV1(rlKey);
+ const retryAfter = Math.max(1, setRateLimitHeaders(res, rl) || 1);
+ if (!rl.success) {
+ res.setHeader('retry-after', String(retryAfter));
+ throw apiError(429, 'rate_limited', 'Too many requests. Slow down and retry.', { retryAfterSeconds: retryAfter });
+ }
+
+ const writes = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method);
+ let body = {};
+ if (writes && req.method !== 'DELETE' && hasBody(req)) {
+ try {
+ body = (await readJson(req)) || {};
+ } catch (err) {
+ throw apiError(400, 'bad_json', err?.message || 'The request body must be JSON.');
+ }
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ throw apiError(400, 'bad_json', 'The request body must be a JSON object.');
+ }
+ }
+ if (writes && principal?.source === 'session' && route.csrf !== false) {
+ const verdict = await checkCsrf({ headers: req.headers, body }, principal.userId);
+ if (!verdict.ok) throw apiError(403, verdict.code, verdict.message);
+ }
+
+ const idem = writes && principal ? idempotencyKey(req, principal, route, body) : null;
+ if (idem) {
+ const stored = await cacheGet(idem.key).catch(() => null);
+ if (stored) {
+ if (stored.bodyHash !== idem.bodyHash) {
+ throw apiError(422, 'idempotency_key_reused', 'This Idempotency-Key was already used with a different request body.');
+ }
+ res.setHeader('idempotent-replayed', 'true');
+ meter(route, principal, 'ok', started);
+ return send(res, stored.status, stored.body);
+ }
+ if (!(await acquireLock(`${idem.key}:lock`, 120))) {
+ throw apiError(409, 'idempotency_in_progress', 'A request with this Idempotency-Key is still running. Retry shortly.');
+ }
+ ctx.idem = idem;
+ }
+
+ const query = Object.fromEntries(url.searchParams);
+ let result;
+ try {
+ result = await route.handler({ ...ctx, principal, params, query, body, ip: clientIp(req) });
+ } finally {
+ if (ctx.idem) releaseLock(`${ctx.idem.key}:lock`);
+ }
+ meter(route, principal, 'ok', started);
+ if (res.headersSent || res.writableEnded) return;
+ const out = shape(ctx, result);
+ if (ctx.idem) {
+ await cacheSet(ctx.idem.key, { ...out, bodyHash: ctx.idem.bodyHash }, IDEMPOTENCY_TTL_S).catch(() => {});
+ }
+ return send(res, out.status, out.body);
+ } catch (err) {
+ meter(route, principal, 'error', started);
+ if (res.headersSent) {
+ if (!res.writableEnded) res.end();
+ return;
+ }
+ if (err instanceof ApiError) return sendError(res, ctx, err.status, err.code, err.message, err.details);
+ // A 4xx thrown by a shared helper (a SpendLimitError, an insufficient-
+ // credits 402) keeps its code and message; everything else is redacted.
+ const status = Number(err?.status);
+ if (status >= 400 && status < 500 && err?.code) {
+ return sendError(res, ctx, status, String(err.code), String(err.message || err.code), err.detail || null);
+ }
+ console.error(`[v1] ${req.method} ${url.pathname} failed (${ctx.requestId}):`, err);
+ return sendError(res, ctx, 500, 'internal_error', 'The request failed unexpectedly. Quote the requestId if you report it.');
+ }
+ };
+}
+
+const IDEMPOTENCY_TTL_S = 24 * 60 * 60;
+
+function shape(ctx, result) {
+ if (result && result[CREATED]) return { status: 201, body: { data: result.data, meta: meta(ctx) } };
+ if (result && result.__page) {
+ return {
+ status: 200,
+ body: { data: result.items, meta: meta(ctx, { hasMore: result.hasMore, nextCursor: result.nextCursor }) },
+ };
+ }
+ return { status: 200, body: { data: result ?? null, meta: meta(ctx) } };
+}
+
+function idempotencyKey(req, principal, route, body) {
+ const raw = req.headers['idempotency-key'];
+ if (typeof raw !== 'string' || !raw.trim()) return null;
+ if (raw.length > 200) throw apiError(400, 'invalid_idempotency_key', 'Idempotency-Key must be at most 200 characters.');
+ const digest = (v) => createHash('sha256').update(v).digest('hex');
+ return {
+ key: `v1:idem:${principal.userId}:${route.name}:${digest(raw.trim())}`,
+ bodyHash: digest(`${req.url}\n${JSON.stringify(body)}`),
+ };
+}
+
+// A write with no payload (POST /agents/:id/start) is valid; only a declared
+// or non-empty body is parsed.
+function hasBody(req) {
+ if (req.body !== undefined && req.body !== null && !(typeof req.body === 'object' && Object.keys(req.body).length === 0)) return true;
+ if (req.headers['content-type']) return true;
+ const len = Number(req.headers['content-length'] || 0);
+ return len > 0 || Boolean(req.headers['transfer-encoding']);
+}
+
+function meter(route, principal, status, started) {
+ recordEvent({
+ kind: 'api',
+ tool: route.name,
+ userId: principal?.userId,
+ apiKeyId: principal?.apiKeyId,
+ clientId: principal?.clientId,
+ status,
+ latencyMs: Date.now() - started,
+ });
+}
+
+// ── input helpers shared by the service modules ──────────────────────────────
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** Throw 404 unless `id` is a UUID (every v1 resource id is one). */
+export function requireUuid(id, what = 'resource') {
+ if (typeof id !== 'string' || !UUID_RE.test(id)) throw apiError(404, 'not_found', `No ${what} with that id.`);
+ return id.toLowerCase();
+}
+
+/** Parse an optional bounded integer query/body value. */
+export function intParam(value, { name, min, max, fallback }) {
+ if (value === undefined || value === null || value === '') return fallback;
+ const n = Number(value);
+ if (!Number.isInteger(n) || n < min || n > max) {
+ throw apiError(400, 'invalid_parameter', `${name} must be an integer from ${min} to ${max}.`, { parameter: name });
+ }
+ return n;
+}
+
+/** Parse an optional non-negative number. */
+export function numParam(value, { name, min = 0, max = Number.MAX_SAFE_INTEGER, fallback = null }) {
+ if (value === undefined || value === null || value === '') return fallback;
+ const n = Number(value);
+ if (!Number.isFinite(n) || n < min || n > max) {
+ throw apiError(400, 'invalid_parameter', `${name} must be a number from ${min} to ${max}.`, { parameter: name });
+ }
+ return n;
+}
+
+/** Parse an optional trimmed string with a max length. */
+export function strParam(value, { name, max, required = false }) {
+ if (value === undefined || value === null || value === '') {
+ if (required) throw apiError(400, 'missing_parameter', `${name} is required.`, { parameter: name });
+ return null;
+ }
+ if (typeof value !== 'string') throw apiError(400, 'invalid_parameter', `${name} must be a string.`, { parameter: name });
+ const s = value.trim();
+ if (required && !s) throw apiError(400, 'missing_parameter', `${name} is required.`, { parameter: name });
+ if (s.length > max) throw apiError(400, 'invalid_parameter', `${name} must be at most ${max} characters.`, { parameter: name });
+ return s || null;
+}
diff --git a/api/_lib/agents-v1/quote-token.js b/api/_lib/agents-v1/quote-token.js
new file mode 100644
index 000000000..8de382a4e
--- /dev/null
+++ b/api/_lib/agents-v1/quote-token.js
@@ -0,0 +1,79 @@
+// Signed, short-lived quote ids for the v1 fund-moving routes.
+//
+// A fund-moving call (wallet transfer, custodial swap) is two steps: a quote
+// route previews the action and returns a `quoteId`, and the execute route
+// takes `{ quoteId, confirm: true }`. The quote id is an HMAC-signed token that
+// pins every parameter the owner saw (agent, user, destination, amount, asset,
+// network), so execute can never act on anything other than what was
+// previewed. It carries a random nonce that the execute route uses as the
+// underlying handler's idempotency key, which makes each quote single-use: a
+// second execute of the same quote replays the first result instead of moving
+// funds again.
+
+import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
+import { env } from '../env.js';
+import { apiError } from './http.js';
+
+export const QUOTE_TTL_MS = 5 * 60 * 1000;
+
+const b64url = (buf) => Buffer.from(buf).toString('base64url');
+
+function sign(payload) {
+ return createHmac('sha256', `v1-quote:${env.JWT_SECRET}`).update(payload).digest();
+}
+
+/**
+ * @param {string} kind 'transfer' | 'swap'
+ * @param {object} claims the pinned parameters
+ * @returns {{ quoteId: string, expiresAt: string, nonce: string }}
+ */
+export function issueQuote(kind, claims) {
+ const nonce = randomUUID();
+ const exp = Date.now() + QUOTE_TTL_MS;
+ const payload = b64url(JSON.stringify({ k: kind, n: nonce, exp, c: claims }));
+ return { quoteId: `q_${payload}.${b64url(sign(payload))}`, expiresAt: new Date(exp).toISOString(), nonce };
+}
+
+/**
+ * Verify a quote id and return its claims. Throws a 400 `invalid_quote` for a
+ * malformed or tampered id, 410 `quote_expired` once it has lapsed, and 400
+ * `quote_mismatch` when it was issued for a different kind or owner.
+ */
+export function verifyQuote(quoteId, kind, { userId, agentId = null }) {
+ if (typeof quoteId !== 'string' || !quoteId.startsWith('q_')) {
+ throw apiError(400, 'invalid_quote', 'quoteId is missing or malformed. Request a new quote first.', { parameter: 'quoteId' });
+ }
+ const [payload, sig] = quoteId.slice(2).split('.');
+ if (!payload || !sig) throw apiError(400, 'invalid_quote', 'quoteId is malformed.', { parameter: 'quoteId' });
+ const expected = sign(payload);
+ const given = Buffer.from(sig, 'base64url');
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
+ throw apiError(400, 'invalid_quote', 'quoteId failed verification. Request a new quote.', { parameter: 'quoteId' });
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
+ } catch {
+ throw apiError(400, 'invalid_quote', 'quoteId is malformed.', { parameter: 'quoteId' });
+ }
+ if (parsed.k !== kind || parsed.c?.userId !== userId || (agentId && parsed.c?.agentId !== agentId)) {
+ throw apiError(400, 'quote_mismatch', 'This quote was issued for a different action, account or agent.', { parameter: 'quoteId' });
+ }
+ if (!Number.isFinite(parsed.exp) || parsed.exp < Date.now()) {
+ throw apiError(410, 'quote_expired', 'This quote has expired. Request a new one and confirm it within five minutes.', {
+ parameter: 'quoteId',
+ });
+ }
+ return { claims: parsed.c, nonce: parsed.n, expiresAt: new Date(parsed.exp).toISOString() };
+}
+
+/** Throw the shared 400 every fund-moving route returns when `confirm` is not literally true. */
+export function requireConfirm(body, previewMethod, previewRoute) {
+ if (body?.confirm === true) return;
+ throw apiError(
+ 400,
+ 'confirmation_required',
+ `This action moves funds. Call ${previewRoute} first, review the quote, then send { quoteId, confirm: true }.`,
+ { confirmFlag: 'confirm', previewMethod, previewRoute },
+ );
+}
diff --git a/api/_lib/agents-v1/routes/skills.js b/api/_lib/agents-v1/routes/skills.js
new file mode 100644
index 000000000..c5105b9e9
--- /dev/null
+++ b/api/_lib/agents-v1/routes/skills.js
@@ -0,0 +1,293 @@
+// v1 skills routes: the built-in skill catalog, the community registry, and an
+// agent's custom skills (prompt-level instructions injected into its system
+// prompt under a token budget).
+//
+// GET /skills built-in skill ids for agent.skills[]
+// GET /skills/community public community registry search
+// GET /skills/community/:slug one registry skill with its SKILL.md
+// GET /agents/:id/skills/custom the agent's custom skills + budget
+// POST /agents/:id/skills/custom write a new custom skill
+// POST /agents/:id/skills/custom/import install a community skill by slug
+// GET /agents/:id/skills/custom/:skillId one custom skill
+// PATCH /agents/:id/skills/custom/:skillId edit, enable/disable, or { resync: true }
+// DELETE /agents/:id/skills/custom/:skillId remove it
+//
+// Custom skills live in agent_custom_skills and are owned by
+// api/_lib/agent-custom-skills.js; these routes are a v1 face over that store,
+// the same one /api/agents/:id/custom-skills and the MCP tools use.
+
+import { apiError, created, requireUuid, strParam, intParam } from '../http.js';
+import { CORE_SKILLS, OPTIONAL_SKILLS } from '../../../../src/studio/skills/skills-catalog.js';
+import { searchCommunitySkills, getCommunitySkill } from '../../community-skills.js';
+import {
+ CustomSkillError,
+ createSchema,
+ patchSchema,
+ requireOwnedAgent,
+ listSkills,
+ getSkill,
+ createSkill,
+ importCommunitySkill,
+ updateSkill,
+ deleteSkill,
+ presentSkill,
+} from '../../agent-custom-skills.js';
+
+/** Map the store's errors (and zod failures) onto the v1 envelope. */
+async function guard(fn) {
+ try {
+ return await fn();
+ } catch (err) {
+ if (err instanceof CustomSkillError) {
+ throw apiError(err.status, err.code === 'validation_error' ? 'invalid_parameter' : err.code, err.message, Object.keys(err.extra || {}).length ? err.extra : null);
+ }
+ throw err;
+ }
+}
+
+function parse(schema, body) {
+ const r = schema.safeParse(body);
+ if (!r.success) {
+ const issues = r.error.issues.map((i) => ({ path: i.path, message: i.message }));
+ throw apiError(400, 'invalid_parameter', issues[0]?.message || 'Invalid request body.', {
+ parameter: issues[0]?.path?.join('.') || null,
+ fields: issues,
+ });
+ }
+ return r.data;
+}
+
+function shapeSkill(s) {
+ return {
+ id: s.id,
+ agentId: s.agent_id,
+ slug: s.slug,
+ name: s.name,
+ description: s.description,
+ author: s.author ?? null,
+ tags: s.tags || [],
+ version: s.version,
+ content: s.content,
+ source: s.source,
+ sourceSlug: s.source_slug ?? null,
+ sourceVersion: s.source_version ?? null,
+ enabled: s.enabled,
+ tokens: s.tokens ?? null,
+ injected: s.injected ?? null,
+ skipReason: s.skip_reason ?? null,
+ registry: s.registry
+ ? {
+ slug: s.registry.slug,
+ latestVersion: s.registry.latest_version ?? null,
+ updateAvailable: Boolean(s.registry.update_available),
+ removed: Boolean(s.registry.removed),
+ }
+ : null,
+ installedAt: s.installed_at,
+ updatedAt: s.updated_at,
+ };
+}
+
+function shapeBudget(b) {
+ return {
+ capTokens: b.cap_tokens,
+ usedTokens: b.used_tokens,
+ enabledTokens: b.enabled_tokens,
+ remainingTokens: b.remaining_tokens,
+ injectedCount: b.injected_count,
+ skippedOverBudget: b.skipped_over_budget,
+ };
+}
+
+/** The agent's custom skills with the injection plan applied. */
+async function listing(agentId) {
+ const { skills, budget } = await listSkills(agentId);
+ return { skills: skills.map(shapeSkill), budget: shapeBudget(budget) };
+}
+
+/** One skill as planned against the budget, after a write. */
+async function planned(agentId, row) {
+ const { skills, budget } = await listSkills(agentId);
+ const s = skills.find((x) => x.id === row.id) || presentSkill(row);
+ return { skill: shapeSkill(s), budget: shapeBudget(budget) };
+}
+
+function shapeCommunity(s, { full = false } = {}) {
+ const out = {
+ slug: s.slug,
+ name: s.name,
+ description: s.description,
+ author: s.author ?? null,
+ tags: s.tags || [],
+ version: s.version,
+ sha256: s.sha256 ?? null,
+ page: `/skills/community?skill=${s.slug}`,
+ };
+ if (full) out.content = s.body;
+ return out;
+}
+
+export const ROUTES = [
+ {
+ method: 'GET',
+ path: '/skills',
+ name: 'v1.skills.list',
+ auth: 'public',
+ summary: "Built-in skill ids an agent's skills[] accepts. Core skills are always on; optional ones are toggled per agent.",
+ handler: () => ({
+ skills: [
+ ...CORE_SKILLS.map((s) => ({ id: s.id, name: s.name, description: s.desc, kind: 'core', sellable: false })),
+ ...OPTIONAL_SKILLS.map((s) => ({
+ id: s.id,
+ name: s.name,
+ description: s.desc,
+ kind: 'optional',
+ sellable: s.sellable !== false,
+ })),
+ ],
+ }),
+ },
+ {
+ method: 'GET',
+ path: '/skills/community',
+ name: 'v1.skills.community.list',
+ auth: 'public',
+ summary: 'Search the public community skills registry.',
+ params: { q: 'free-text search', tag: 'filter by tag', author: 'filter by author', limit: '1-100, default 50' },
+ handler: ({ query }) => {
+ const limit = intParam(query.limit, { name: 'limit', min: 1, max: 100, fallback: 50 });
+ const result = searchCommunitySkills({
+ q: strParam(query.q, { name: 'q', max: 120 }) || '',
+ tag: strParam(query.tag, { name: 'tag', max: 32 }) || '',
+ author: strParam(query.author, { name: 'author', max: 64 }) || '',
+ limit,
+ });
+ return {
+ skills: result.skills.map((s) => shapeCommunity(s)),
+ count: result.count,
+ total: result.total,
+ tags: result.tags,
+ };
+ },
+ },
+ {
+ method: 'GET',
+ path: '/skills/community/:slug',
+ name: 'v1.skills.community.get',
+ auth: 'public',
+ summary: 'One community registry skill, including its SKILL.md body.',
+ handler: ({ params }) => {
+ const s = getCommunitySkill(params.slug);
+ if (!s) throw apiError(404, 'not_found', `No community skill "${params.slug}".`);
+ return { skill: shapeCommunity(s, { full: true }) };
+ },
+ },
+ {
+ method: 'GET',
+ path: '/agents/:id/skills/custom',
+ name: 'v1.agents.skills.custom.list',
+ auth: 'required',
+ scope: 'agents:read',
+ summary: "The agent's custom skills and how much of the prompt budget they use.",
+ handler: ({ params, principal }) =>
+ guard(async () => {
+ const id = requireUuid(params.id, 'agent');
+ await requireOwnedAgent(id, principal.userId);
+ return listing(id);
+ }),
+ },
+ {
+ method: 'POST',
+ path: '/agents/:id/skills/custom',
+ name: 'v1.agents.skills.custom.create',
+ auth: 'required',
+ scope: 'agents:write',
+ summary: 'Write a custom skill: instructions injected into the agent\'s system prompt.',
+ params: {
+ name: '2-80 chars (required)',
+ content: 'the instructions, markdown (required)',
+ description: 'up to 400 chars',
+ slug: 'kebab-case id, derived from name when omitted',
+ tags: 'up to 8 kebab-case tags',
+ version: 'semver, default 1.0.0',
+ enabled: 'default true',
+ },
+ handler: ({ params, principal, body }) =>
+ guard(async () => {
+ const id = requireUuid(params.id, 'agent');
+ await requireOwnedAgent(id, principal.userId);
+ const input = parse(createSchema, body);
+ const row = await createSkill(id, principal.userId, input);
+ return created(await planned(id, row));
+ }),
+ },
+ {
+ method: 'POST',
+ path: '/agents/:id/skills/custom/import',
+ name: 'v1.agents.skills.custom.import',
+ auth: 'required',
+ scope: 'agents:write',
+ summary: 'Install a community registry skill on the agent as an editable custom skill.',
+ params: { slug: 'registry slug (required)', enabled: 'default true' },
+ handler: ({ params, principal, body }) =>
+ guard(async () => {
+ const id = requireUuid(params.id, 'agent');
+ await requireOwnedAgent(id, principal.userId);
+ const slug = strParam(body.slug, { name: 'slug', max: 64, required: true });
+ if (body.enabled !== undefined && typeof body.enabled !== 'boolean') {
+ throw apiError(400, 'invalid_parameter', 'enabled must be a boolean.', { parameter: 'enabled' });
+ }
+ const row = await importCommunitySkill(id, principal.userId, { slug, enabled: body.enabled ?? true });
+ return created(await planned(id, row));
+ }),
+ },
+ {
+ method: 'GET',
+ path: '/agents/:id/skills/custom/:skillId',
+ name: 'v1.agents.skills.custom.get',
+ auth: 'required',
+ scope: 'agents:read',
+ summary: 'One custom skill and where it lands in the prompt budget.',
+ handler: ({ params, principal }) =>
+ guard(async () => {
+ const id = requireUuid(params.id, 'agent');
+ const skillId = requireUuid(params.skillId, 'custom skill');
+ await requireOwnedAgent(id, principal.userId);
+ const { skill, budget } = await getSkill(id, skillId);
+ return { skill: shapeSkill(skill), budget: shapeBudget(budget) };
+ }),
+ },
+ {
+ method: 'PATCH',
+ path: '/agents/:id/skills/custom/:skillId',
+ name: 'v1.agents.skills.custom.update',
+ auth: 'required',
+ scope: 'agents:write',
+ summary: 'Edit a custom skill, toggle it, or { resync: true } to pull the latest registry version of an import.',
+ handler: ({ params, principal, body }) =>
+ guard(async () => {
+ const id = requireUuid(params.id, 'agent');
+ const skillId = requireUuid(params.skillId, 'custom skill');
+ await requireOwnedAgent(id, principal.userId);
+ const patch = parse(patchSchema, body);
+ const row = await updateSkill(id, skillId, patch);
+ return planned(id, row);
+ }),
+ },
+ {
+ method: 'DELETE',
+ path: '/agents/:id/skills/custom/:skillId',
+ name: 'v1.agents.skills.custom.delete',
+ auth: 'required',
+ scope: 'agents:write',
+ summary: 'Permanently remove a custom skill from the agent.',
+ handler: ({ params, principal }) =>
+ guard(async () => {
+ const id = requireUuid(params.id, 'agent');
+ const skillId = requireUuid(params.skillId, 'custom skill');
+ await requireOwnedAgent(id, principal.userId);
+ const row = await deleteSkill(id, skillId);
+ return { deleted: true, id: row.id, slug: row.slug, ...(await listing(id)) };
+ }),
+ },
+];
diff --git a/api/_lib/agents-v1/routes/swap.js b/api/_lib/agents-v1/routes/swap.js
new file mode 100644
index 000000000..eb4efffe2
--- /dev/null
+++ b/api/_lib/agents-v1/routes/swap.js
@@ -0,0 +1,263 @@
+// v1 swap routes, quote-then-execute, in two custody modes.
+//
+// POST /swap/quote price a swap and return a quoteId valid for five minutes
+// POST /swap/execute act on a quoteId
+//
+// Non-custodial (no agentId): priced and built by the Jupiter aggregator for
+// any SPL pair. Execute returns an UNSIGNED base64 VersionedTransaction for the
+// caller's own wallet to sign and send; nothing moves until they do, and the
+// platform never holds their key.
+//
+// Custodial (agentId given): the agent's own wallet trades through the guarded
+// executor in api/agents/solana-trade.js (pump.fun bonding curve and AMM), so
+// the kill switch, per-trade cap, daily budget, price-impact breaker, trade
+// firewall, real-funds agreement and custody ledger all apply unchanged. One
+// side must be SOL. Execute needs `confirm: true` and the wallet:write scope.
+
+import { apiError, requireUuid, strParam, intParam } from '../http.js';
+import { forward, forwardData, toApiError } from '../forward.js';
+import { issueQuote, verifyQuote, requireConfirm } from '../quote-token.js';
+import { hasScope } from '../../auth.js';
+import { jupiterQuote, jupiterSwapTx } from '../../token/jupiter.js';
+
+export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const LAMPORTS_PER_SOL = 1_000_000_000n;
+
+function mintParam(v, name) {
+ const s = strParam(v, { name, max: 64, required: true });
+ if (s.toUpperCase() === 'SOL') return WSOL_MINT;
+ if (!BASE58_RE.test(s)) throw apiError(400, 'invalid_parameter', `${name} must be a base58 mint address or "SOL".`, { parameter: name });
+ return s;
+}
+
+function atomicParam(v) {
+ const s = typeof v === 'number' && Number.isSafeInteger(v) ? String(v) : v;
+ if (typeof s !== 'string' || !/^\d{1,30}$/.test(s) || BigInt(s) <= 0n) {
+ throw apiError(400, 'invalid_parameter', 'amount must be a positive integer in the input mint\'s smallest unit (lamports for SOL).', {
+ parameter: 'amount',
+ });
+ }
+ return s;
+}
+
+function pubkeyParam(v, name) {
+ const s = strParam(v, { name, max: 64 });
+ if (s && !BASE58_RE.test(s)) throw apiError(400, 'invalid_parameter', `${name} must be a base58 Solana address.`, { parameter: name });
+ return s;
+}
+
+async function tradeHandler(agentId) {
+ const mod = await import('../../../agents/solana-trade.js');
+ return (req, res) => mod.handleTrade(req, res, agentId);
+}
+
+/** Custodial swaps map onto the trade executor's buy (SOL in) or sell (SOL out). */
+function custodialSide(inputMint, outputMint) {
+ if (inputMint === WSOL_MINT && outputMint !== WSOL_MINT) return { side: 'buy', mint: outputMint };
+ if (outputMint === WSOL_MINT && inputMint !== WSOL_MINT) return { side: 'sell', mint: inputMint };
+ throw apiError(
+ 422,
+ 'unsupported_pair',
+ 'Agent-wallet swaps need SOL on one side. For any other pair, quote without agentId and sign the returned transaction yourself.',
+ { parameter: 'inputMint' },
+ );
+}
+
+function tradeBody(pinned) {
+ const body = { side: pinned.side, mint: pinned.mint, network: 'mainnet', slippage_bps: pinned.slippageBps };
+ if (pinned.side === 'buy') {
+ // The executor takes whole SOL for a buy; the quote pinned lamports.
+ const lamports = BigInt(pinned.amount);
+ body.sol_amount = Number(lamports / LAMPORTS_PER_SOL) + Number(lamports % LAMPORTS_PER_SOL) / 1e9;
+ } else {
+ body.token_amount_raw = pinned.amount;
+ }
+ return body;
+}
+
+function shapeCustodialQuote(d, pinned) {
+ return {
+ inputMint: pinned.inputMint,
+ outputMint: pinned.outputMint,
+ inAmount: d.in?.atomics ?? pinned.amount,
+ outAmount: d.out?.atomics ?? null,
+ minOutAmount: d.min_received?.atomics ?? null,
+ priceImpactPct: d.price_impact_pct ?? null,
+ slippageBps: d.slippage_bps ?? pinned.slippageBps,
+ venue: d.venue ?? null,
+ route: [d.venue].filter(Boolean),
+ usd: d.usd ?? null,
+ platformFeeBps: d.platform_fee_bps ?? null,
+ warnings: [d.guard, d.funds].filter(Boolean).map((w) => ({ code: w.code, message: w.message })),
+ firewall: d.firewall ?? null,
+ };
+}
+
+function shapeJupiterQuote(q, pinned) {
+ return {
+ inputMint: pinned.inputMint,
+ outputMint: pinned.outputMint,
+ inAmount: String(q.inAmount),
+ outAmount: String(q.outAmount),
+ minOutAmount: String(q.otherAmountThreshold),
+ priceImpactPct: q.priceImpactPct != null ? Number(q.priceImpactPct) * 100 : null,
+ slippageBps: q.slippageBps ?? pinned.slippageBps,
+ venue: 'jupiter',
+ route: (q.routePlan || []).map((r) => r?.swapInfo?.label).filter(Boolean),
+ usd: q.swapUsdValue != null ? Number(q.swapUsdValue) : null,
+ platformFeeBps: null,
+ warnings: [],
+ firewall: null,
+ };
+}
+
+async function quoteJupiter(pinned) {
+ try {
+ return await jupiterQuote({
+ inputMint: pinned.inputMint,
+ outputMint: pinned.outputMint,
+ amount: pinned.amount,
+ slippageBps: pinned.slippageBps,
+ });
+ } catch (err) {
+ if (Number(err?.status) === 400 || Number(err?.status) === 404) {
+ throw apiError(422, 'no_route', 'No swap route exists for this pair and amount.', { inputMint: pinned.inputMint, outputMint: pinned.outputMint });
+ }
+ throw apiError(502, 'swap_failed', 'The swap could not be priced right now. Retry shortly.', {
+ inputMint: pinned.inputMint,
+ outputMint: pinned.outputMint,
+ });
+ }
+}
+
+export const ROUTES = [
+ {
+ method: 'POST',
+ path: '/swap/quote',
+ name: 'v1.swap.quote',
+ auth: 'required',
+ scope: 'agents:read',
+ // Quoting moves nothing, so a signed-in browser needs no CSRF token.
+ csrf: false,
+ summary: 'Price a Solana swap. Pass agentId to trade from the agent wallet; omit it to get a transaction for your own wallet.',
+ params: {
+ inputMint: 'mint to sell, or "SOL" (required)',
+ outputMint: 'mint to buy, or "SOL" (required)',
+ amount: 'input amount in the smallest unit, as an integer string (required)',
+ slippageBps: '0-5000; default 50 (non-custodial) or 300 (agent wallet)',
+ agentId: 'swap from this agent\'s custodial wallet',
+ userPublicKey: 'your wallet, for a non-custodial swap (can also be passed at execute)',
+ },
+ handler: async (ctx) => {
+ const b = ctx.body;
+ const inputMint = mintParam(b.inputMint, 'inputMint');
+ const outputMint = mintParam(b.outputMint, 'outputMint');
+ if (inputMint === outputMint) throw apiError(400, 'invalid_parameter', 'inputMint and outputMint must differ.', { parameter: 'outputMint' });
+ const amount = atomicParam(b.amount);
+ const agentId = b.agentId ? requireUuid(b.agentId, 'agent') : null;
+ const slippageBps = intParam(b.slippageBps, { name: 'slippageBps', min: 0, max: 5000, fallback: agentId ? 300 : 50 });
+ const userPublicKey = pubkeyParam(b.userPublicKey, 'userPublicKey');
+ const userId = ctx.principal.userId;
+
+ if (agentId) {
+ const { side, mint } = custodialSide(inputMint, outputMint);
+ const pinned = { mode: 'custodial', agentId, userId, inputMint, outputMint, amount, slippageBps, side, mint };
+ const d = await forwardData(await tradeHandler(agentId), ctx, {
+ method: 'POST',
+ url: `/api/agents/${agentId}/solana/trade`,
+ body: { ...tradeBody(pinned), preview: true },
+ });
+ const quote = shapeCustodialQuote(d, pinned);
+ const { quoteId, expiresAt } = issueQuote('swap', { ...pinned, minOutAmount: quote.minOutAmount });
+ return { quoteId, expiresAt, mode: 'custodial', agentId, ...quote };
+ }
+
+ const pinned = { mode: 'non_custodial', userId, inputMint, outputMint, amount, slippageBps, userPublicKey };
+ const q = await quoteJupiter(pinned);
+ const quote = shapeJupiterQuote(q, pinned);
+ const { quoteId, expiresAt } = issueQuote('swap', { ...pinned, minOutAmount: quote.minOutAmount });
+ return { quoteId, expiresAt, mode: 'non_custodial', agentId: null, ...quote };
+ },
+ },
+ {
+ method: 'POST',
+ path: '/swap/execute',
+ name: 'v1.swap.execute',
+ auth: 'required',
+ scope: 'agents:read',
+ // The custodial path forwards to the trade executor, which enforces CSRF
+ // for session callers itself; checking here would burn the token first.
+ csrf: false,
+ summary:
+ 'Act on a swap quote. Non-custodial returns an unsigned base64 transaction to sign; agent-wallet swaps need { confirm: true } and sign server-side.',
+ params: {
+ quoteId: 'from POST /swap/quote (required)',
+ confirm: 'must be true for an agent-wallet swap',
+ userPublicKey: 'your wallet, if it was not given at quote time (non-custodial)',
+ },
+ handler: async (ctx) => {
+ const { claims: pinned, nonce } = verifyQuote(ctx.body.quoteId, 'swap', { userId: ctx.principal.userId });
+
+ if (pinned.mode === 'custodial') {
+ const p = ctx.principal;
+ if (p.source !== 'session' && !hasScope(p.scope, 'wallet:write')) {
+ throw apiError(403, 'insufficient_scope', 'Swapping from an agent wallet requires the "wallet:write" scope.', {
+ required: 'wallet:write',
+ });
+ }
+ requireConfirm(ctx.body, 'swapQuote', 'POST /api/v1/swap/quote');
+ const out = await forward(await tradeHandler(pinned.agentId), ctx, {
+ method: 'POST',
+ url: `/api/agents/${pinned.agentId}/solana/trade`,
+ // The quote nonce is the executor's idempotency key, so a quote
+ // executes at most once and a repeat replays the first fill.
+ body: { ...tradeBody(pinned), idempotency_key: `v1q:${nonce}` },
+ });
+ if (out.status < 200 || out.status >= 300) throw toApiError(out);
+ const d = out.body?.data ?? {};
+ return {
+ mode: 'custodial',
+ agentId: pinned.agentId,
+ status: 'confirmed',
+ replayed: Boolean(d.replayed),
+ signature: d.signature ?? null,
+ explorer: d.explorer ?? null,
+ ...shapeCustodialQuote(d, pinned),
+ newBalanceSol: d.new_balance_sol ?? null,
+ };
+ }
+
+ const userPublicKey = pubkeyParam(ctx.body.userPublicKey, 'userPublicKey') || pinned.userPublicKey;
+ if (!userPublicKey) {
+ throw apiError(400, 'missing_parameter', 'userPublicKey is required: the wallet that will sign this swap.', { parameter: 'userPublicKey' });
+ }
+ // Re-price, and refuse if the market moved below what the caller saw.
+ const q = await quoteJupiter(pinned);
+ if (pinned.minOutAmount && BigInt(q.outAmount) < BigInt(pinned.minOutAmount)) {
+ throw apiError(409, 'quote_moved', 'The price moved past your slippage since the quote. Request a new quote.', {
+ quotedMinOut: pinned.minOutAmount,
+ currentOut: String(q.outAmount),
+ });
+ }
+ let transaction;
+ try {
+ transaction = await jupiterSwapTx({ quote: q, userPublicKey, wrapAndUnwrapSol: true });
+ } catch {
+ throw apiError(502, 'swap_failed', 'The swap transaction could not be built right now. Retry shortly.', {
+ inputMint: pinned.inputMint,
+ outputMint: pinned.outputMint,
+ });
+ }
+ return {
+ mode: 'non_custodial',
+ agentId: null,
+ status: 'unsigned',
+ transaction,
+ encoding: 'base64',
+ signer: userPublicKey,
+ ...shapeJupiterQuote(q, pinned),
+ };
+ },
+ },
+];
diff --git a/api/_lib/agents-v1/routes/wallet.js b/api/_lib/agents-v1/routes/wallet.js
new file mode 100644
index 000000000..f5bb4241b
--- /dev/null
+++ b/api/_lib/agents-v1/routes/wallet.js
@@ -0,0 +1,249 @@
+// v1 agent wallet routes: read the custodial Solana wallet, page its custody
+// ledger, and move funds out of it through quote-then-confirm.
+//
+// Every route forwards to the existing owner-gated handler in
+// api/agents/solana-wallet.js so the ownership check, spend policy
+// (enforceSpendLimit), withdraw allowlist, real-funds agreement, CSRF, rate
+// limits and custody ledger all apply exactly as they do for the dashboard.
+//
+// GET /agents/:id/wallet balance and address
+// GET /agents/:id/wallet/history custody ledger, newest first, paged
+// POST /agents/:id/wallet/transfer/quote simulate a transfer, return a quoteId
+// POST /agents/:id/wallet/transfer { quoteId, confirm: true } sends it
+
+import { apiError, page, requireUuid, intParam, strParam } from '../http.js';
+import { forward, forwardData, toApiError } from '../forward.js';
+import { issueQuote, verifyQuote, requireConfirm } from '../quote-token.js';
+
+/** Bind the solana-wallet dispatcher to one agent and action. */
+async function walletAction(id, action) {
+ const mod = await import('../../../agents/solana-wallet.js');
+ return (req, res) => mod.default(req, res, id, action);
+}
+
+export function networkParam(v) {
+ if (v === undefined || v === null || v === '' || v === 'mainnet') return 'mainnet';
+ if (v === 'devnet') return 'devnet';
+ throw apiError(400, 'invalid_parameter', 'network must be "mainnet" or "devnet".', { parameter: 'network' });
+}
+
+function amountParam(v) {
+ if (v === 'max') return 'max';
+ const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
+ if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0) {
+ throw apiError(400, 'invalid_parameter', 'amount must be a positive number or "max".', { parameter: 'amount' });
+ }
+ return n;
+}
+
+function shapeWallet(d, agentId) {
+ return {
+ agentId,
+ chain: 'solana',
+ network: d?.network ?? 'mainnet',
+ address: d?.address ?? null,
+ lamports: d?.lamports != null ? String(d.lamports) : null,
+ sol: d?.sol ?? null,
+ signable: d?.signable ?? null,
+ depositsEnabled: d?.deposits_enabled ?? null,
+ snsDomain: d?.sns_domain ?? null,
+ };
+}
+
+function shapeLedgerItem(e) {
+ return {
+ id: e.id,
+ type: e.event_type,
+ category: e.category,
+ network: e.network,
+ asset: e.asset,
+ amountLamports: e.amount_lamports,
+ amountRaw: e.amount_raw,
+ usd: e.usd,
+ destination: e.destination,
+ signature: e.signature,
+ explorer: e.explorer,
+ status: e.status,
+ reason: e.reason ?? null,
+ createdAt: e.created_at,
+ };
+}
+
+function shapePreview(d) {
+ return {
+ asset: d.asset,
+ network: d.network,
+ destination: d.destination,
+ amount: d.amount,
+ lamports: d.lamports ?? null,
+ amountRaw: d.amount_raw ?? null,
+ usd: d.usd ?? null,
+ note: d.note ?? null,
+ simulation: { ok: d.err == null, error: d.err ?? null, unitsConsumed: d.units_consumed ?? null },
+ };
+}
+
+export const ROUTES = [
+ {
+ method: 'GET',
+ path: '/agents/:id/wallet',
+ name: 'v1.agents.wallet.get',
+ auth: 'required',
+ scope: 'wallet:read',
+ summary: "The agent's custodial Solana wallet: address, SOL balance and whether it can sign.",
+ params: { network: 'mainnet (default) or devnet' },
+ handler: async (ctx) => {
+ const id = requireUuid(ctx.params.id, 'agent');
+ const network = networkParam(ctx.query.network);
+ const d = await forwardData(await walletAction(id, ''), ctx, {
+ method: 'GET',
+ url: `/api/agents/${id}/solana?network=${network}`,
+ });
+ return shapeWallet(d, id);
+ },
+ },
+ {
+ method: 'GET',
+ path: '/agents/:id/wallet/history',
+ name: 'v1.agents.wallet.history',
+ auth: 'required',
+ scope: 'wallet:read',
+ summary: "The agent wallet's custody ledger (every spend, receipt and withdrawal the platform signed), newest first.",
+ params: {
+ limit: '1-200, default 50',
+ before: 'cursor from meta.nextCursor',
+ network: 'mainnet or devnet (default both)',
+ category: 'filter to one spend category, e.g. withdraw, trade, x402',
+ },
+ handler: async (ctx) => {
+ const id = requireUuid(ctx.params.id, 'agent');
+ const limit = intParam(ctx.query.limit, { name: 'limit', min: 1, max: 200, fallback: 50 });
+ const before = strParam(ctx.query.before, { name: 'before', max: 32 });
+ if (before && !/^\d+$/.test(before)) {
+ throw apiError(400, 'invalid_parameter', 'before must be a cursor returned in meta.nextCursor.', { parameter: 'before' });
+ }
+ const category = strParam(ctx.query.category, { name: 'category', max: 32 });
+ const qs = new URLSearchParams({ limit: String(limit) });
+ if (before) qs.set('before', before);
+ if (ctx.query.network) qs.set('network', networkParam(ctx.query.network));
+ if (category) qs.set('category', category);
+ const d = await forwardData(await walletAction(id, 'custody'), ctx, {
+ method: 'GET',
+ url: `/api/agents/${id}/solana/custody?${qs}`,
+ });
+ const items = (d?.items || []).map(shapeLedgerItem);
+ return page(items, { hasMore: Boolean(d?.next_cursor), nextCursor: d?.next_cursor ?? null });
+ },
+ },
+ {
+ method: 'POST',
+ path: '/agents/:id/wallet/transfer/quote',
+ name: 'v1.agents.wallet.transfer_quote',
+ auth: 'required',
+ scope: 'wallet:read',
+ // A quote is a simulation: it moves nothing and never touches the key,
+ // which is why the withdraw handler also exempts it from CSRF.
+ csrf: false,
+ summary: 'Simulate a transfer out of the agent wallet and return a quoteId valid for five minutes.',
+ params: {
+ destination: 'Solana address to receive the funds (required)',
+ amount: 'positive number in whole units, or "max" (required)',
+ asset: '"SOL" (default) or an SPL mint address',
+ network: 'mainnet (default) or devnet',
+ },
+ handler: async (ctx) => {
+ const id = requireUuid(ctx.params.id, 'agent');
+ const destination = strParam(ctx.body.destination, { name: 'destination', max: 64, required: true });
+ const amount = amountParam(ctx.body.amount);
+ const asset = strParam(ctx.body.asset, { name: 'asset', max: 64 }) || 'SOL';
+ const network = networkParam(ctx.body.network);
+ const d = await forwardData(await walletAction(id, 'withdraw'), ctx, {
+ method: 'POST',
+ url: `/api/agents/${id}/solana/withdraw`,
+ body: { destination, amount, asset, network, simulate: true },
+ });
+ if (d?.err != null) {
+ throw apiError(422, 'simulation_failed', 'The transfer failed simulation, so it would fail on chain. Nothing was sent.', {
+ simulation: d.err,
+ logs: Array.isArray(d.logs) ? d.logs.slice(-12) : null,
+ });
+ }
+ // Pin the resolved amount, not "max": the owner confirms the number
+ // they saw, even if the balance moves before they confirm.
+ const pinned = Number(d.amount);
+ const { quoteId, expiresAt } = issueQuote('transfer', {
+ userId: ctx.principal.userId,
+ agentId: id,
+ destination,
+ amount: pinned,
+ asset,
+ network,
+ });
+ return { quoteId, expiresAt, preview: shapePreview(d) };
+ },
+ },
+ {
+ method: 'POST',
+ path: '/agents/:id/wallet/transfer',
+ name: 'v1.agents.wallet.transfer',
+ auth: 'required',
+ scope: 'wallet:write',
+ // The withdraw handler enforces CSRF for session callers itself; checking
+ // here too would burn the single-use token before it gets there.
+ csrf: false,
+ summary: 'Send a previously quoted transfer. Requires { quoteId, confirm: true }.',
+ params: { quoteId: 'from POST /agents/:id/wallet/transfer/quote (required)', confirm: 'must be true (required)' },
+ handler: async (ctx) => {
+ const id = requireUuid(ctx.params.id, 'agent');
+ requireConfirm(ctx.body, 'transferQuote', `POST /api/v1/agents/${id}/wallet/transfer/quote`);
+ const { claims, nonce } = verifyQuote(ctx.body.quoteId, 'transfer', { userId: ctx.principal.userId, agentId: id });
+ const out = await forward(await walletAction(id, 'withdraw'), ctx, {
+ method: 'POST',
+ url: `/api/agents/${id}/solana/withdraw`,
+ body: {
+ destination: claims.destination,
+ amount: claims.amount,
+ asset: claims.asset,
+ network: claims.network,
+ // The quote nonce makes the quote single-use: a repeat
+ // replays the first result instead of sending again.
+ idempotency_key: `v1q:${nonce}`,
+ },
+ });
+ // 202: submitted on chain but not yet confirmed. Not a failure, and
+ // not safe to resend; report the signature so the caller can watch it.
+ if (out.status === 202) {
+ return {
+ status: 'submitted',
+ confirmed: false,
+ replayed: false,
+ signature: out.body?.signature ?? null,
+ explorer: out.body?.explorer ?? null,
+ asset: claims.asset,
+ network: claims.network,
+ destination: claims.destination,
+ amount: claims.amount,
+ usd: null,
+ newBalanceSol: null,
+ newTokenBalance: null,
+ };
+ }
+ if (out.status < 200 || out.status >= 300) throw toApiError(out);
+ const d = out.body?.data ?? {};
+ return {
+ status: 'confirmed',
+ confirmed: true,
+ replayed: Boolean(d.replayed),
+ signature: d.signature ?? null,
+ explorer: d.explorer ?? null,
+ asset: d.asset ?? claims.asset,
+ network: d.network ?? claims.network,
+ destination: d.destination ?? claims.destination,
+ amount: d.amount ?? claims.amount,
+ usd: d.usd ?? null,
+ newBalanceSol: d.new_balance_sol ?? null,
+ newTokenBalance: d.new_token_balance ?? null,
+ };
+ },
+ },
+];
diff --git a/api/_lib/agents-v1/strategies.js b/api/_lib/agents-v1/strategies.js
new file mode 100644
index 000000000..e846f431c
--- /dev/null
+++ b/api/_lib/agents-v1/strategies.js
@@ -0,0 +1,75 @@
+// Strategy presets (data/agent-strategies.json): named bundles of skills,
+// persona text, a default tool allowlist for runs, and default automations.
+//
+// The file is validated when this module loads, so a malformed preset fails the
+// server boot, `npm run check:api-imports` in the deploy gate, and the test
+// suite, instead of failing the first user who picks it.
+
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { ALL_SKILLS } from '../../../src/studio/skills/skills-catalog.js';
+import { AGENT_TOOLS } from '../agent-tools.js';
+import { normalizeAutomation } from './automations.js';
+
+const STRATEGIES_PATH = fileURLToPath(new URL('../../../data/agent-strategies.json', import.meta.url));
+const SKILL_IDS = new Set(ALL_SKILLS.map((s) => s.id));
+const NON_SPENDING_ACTIONS = new Set(['notify', 'agent_prompt']);
+
+/**
+ * Validate a parsed strategies document. Returns the list of problems; an
+ * empty list means it is valid.
+ * @param {any} doc
+ * @returns {string[]}
+ */
+export function validateStrategies(doc) {
+ const problems = [];
+ if (!doc || doc.version !== 1 || !Array.isArray(doc.strategies)) return ['document must be { version: 1, strategies: [...] }'];
+ const seen = new Set();
+ for (const [i, s] of doc.strategies.entries()) {
+ const at = `strategies[${i}]${s?.id ? ` (${s.id})` : ''}`;
+ if (!s || typeof s.id !== 'string' || !/^[a-z][a-z0-9-]{1,31}$/.test(s.id)) problems.push(`${at}: id must be a lowercase slug`);
+ else if (seen.has(s.id)) problems.push(`${at}: duplicate id`);
+ else seen.add(s.id);
+ for (const k of ['name', 'summary', 'persona']) {
+ if (typeof s?.[k] !== 'string' || !s[k].trim()) problems.push(`${at}: ${k} is required`);
+ }
+ if (typeof s?.persona === 'string' && s.persona.length > 8000) problems.push(`${at}: persona exceeds 8000 characters`);
+ if (!Array.isArray(s?.skills) || !s.skills.length) problems.push(`${at}: skills must be a non-empty array`);
+ else for (const id of s.skills) if (!SKILL_IDS.has(id)) problems.push(`${at}: unknown skill "${id}"`);
+ if (!Array.isArray(s?.toolsAllowed) || !s.toolsAllowed.length) problems.push(`${at}: toolsAllowed must be a non-empty array`);
+ else for (const t of s.toolsAllowed) if (!AGENT_TOOLS[t]) problems.push(`${at}: unknown tool "${t}"`);
+ if (typeof s?.temperature !== 'number' || s.temperature < 0 || s.temperature > 2) problems.push(`${at}: temperature must be 0..2`);
+ if (!Array.isArray(s?.automations)) problems.push(`${at}: automations must be an array`);
+ else {
+ for (const [j, a] of s.automations.entries()) {
+ try {
+ const norm = normalizeAutomation(a);
+ if (!NON_SPENDING_ACTIONS.has(norm.action.type)) problems.push(`${at}.automations[${j}]: default automations may only notify or prompt the agent`);
+ } catch (err) {
+ problems.push(`${at}.automations[${j}]: ${err.message}`);
+ }
+ }
+ }
+ }
+ return problems;
+}
+
+function load() {
+ const doc = JSON.parse(readFileSync(STRATEGIES_PATH, 'utf8'));
+ const problems = validateStrategies(doc);
+ if (problems.length) throw new Error(`data/agent-strategies.json is invalid:\n ${problems.join('\n ')}`);
+ return doc.strategies;
+}
+
+const STRATEGIES = load();
+const BY_ID = new Map(STRATEGIES.map((s) => [s.id, s]));
+
+/** Every preset, in file order. */
+export function listStrategies() {
+ return STRATEGIES;
+}
+
+/** One preset by id, or null. */
+export function getStrategy(id) {
+ return typeof id === 'string' ? BY_ID.get(id) || null : null;
+}
diff --git a/api/_lib/migrations/20260922130000_agents_v1_api.sql b/api/_lib/migrations/20260922130000_agents_v1_api.sql
new file mode 100644
index 000000000..e4f6f8c49
--- /dev/null
+++ b/api/_lib/migrations/20260922130000_agents_v1_api.sql
@@ -0,0 +1,167 @@
+-- Agents v1 REST API: lifecycle status, runs and their steps, chat history,
+-- the unified automation object, and short link codes.
+--
+-- Every table here backs a route family under /api/v1 (api/v1/rest.js). The
+-- service layer lives in api/_lib/agents-v1/.
+
+-- ── lifecycle ────────────────────────────────────────────────────────────────
+-- `running` lets scheduled automations, wallet intents and runs execute.
+-- `stopped` pauses all of them without deleting anything. The wallet-intent
+-- execution context (api/_lib/wallet-intents.js buildExecContext), the
+-- automation engine and the run driver all read this column.
+ALTER TABLE agent_identities ADD COLUMN IF NOT EXISTS status text NOT NULL DEFAULT 'running';
+ALTER TABLE agent_identities ADD COLUMN IF NOT EXISTS status_changed_at timestamptz;
+DO $$ BEGIN
+ ALTER TABLE agent_identities ADD CONSTRAINT agent_identities_status_check CHECK (status IN ('running', 'stopped'));
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+-- ── runs ─────────────────────────────────────────────────────────────────────
+-- A run is a goal the agent pursues through the server-side tool loop, one
+-- checkpointed step at a time. `checkpoint` holds the AgentRuntime state and
+-- next context between steps so any instance can resume it; `lease_until`
+-- keeps two drivers (the SSE stream and the cron) from stepping it at once.
+CREATE TABLE IF NOT EXISTS agent_runs (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ goal text NOT NULL,
+ status text NOT NULL DEFAULT 'queued'
+ CHECK (status IN ('scheduled', 'queued', 'running', 'paused', 'completed', 'failed', 'cancelled', 'budget_exhausted')),
+ model text,
+ temperature real,
+ tools_allowed text[],
+ max_steps int NOT NULL DEFAULT 12 CHECK (max_steps BETWEEN 1 AND 60),
+ step_count int NOT NULL DEFAULT 0,
+ budget_credits_usd numeric(20, 6) NOT NULL DEFAULT 0,
+ budget_usd numeric(20, 6) NOT NULL DEFAULT 0,
+ spent_credits_usd numeric(20, 6) NOT NULL DEFAULT 0,
+ spent_usd numeric(20, 6) NOT NULL DEFAULT 0,
+ schedule_cron text,
+ scheduled_for timestamptz,
+ checkpoint jsonb,
+ result text,
+ error text,
+ source text NOT NULL DEFAULT 'api',
+ automation_id uuid,
+ trigger_key text,
+ lease_owner text,
+ lease_until timestamptz,
+ cancel_requested_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ started_at timestamptz,
+ finished_at timestamptz
+);
+CREATE INDEX IF NOT EXISTS agent_runs_agent_idx ON agent_runs (agent_id, created_at DESC, id DESC);
+CREATE INDEX IF NOT EXISTS agent_runs_user_idx ON agent_runs (user_id, created_at DESC);
+-- One run per automation fire: a retried sweep can never start the same run twice.
+CREATE UNIQUE INDEX IF NOT EXISTS agent_runs_trigger_uidx ON agent_runs (automation_id, trigger_key)
+ WHERE automation_id IS NOT NULL AND trigger_key IS NOT NULL;
+CREATE INDEX IF NOT EXISTS agent_runs_due_idx ON agent_runs (status, scheduled_for)
+ WHERE status IN ('scheduled', 'queued', 'running');
+
+CREATE TABLE IF NOT EXISTS agent_run_steps (
+ id bigserial PRIMARY KEY,
+ run_id uuid NOT NULL REFERENCES agent_runs(id) ON DELETE CASCADE,
+ seq int NOT NULL,
+ kind text NOT NULL
+ CHECK (kind IN ('status', 'model_call', 'tool_call', 'tool_result', 'tool_blocked', 'final', 'error')),
+ provider text,
+ model text,
+ tool_name text,
+ input jsonb,
+ output jsonb,
+ input_tokens int,
+ output_tokens int,
+ cost_micro_usd bigint,
+ latency_ms int,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (run_id, seq)
+);
+
+-- ── chat history ─────────────────────────────────────────────────────────────
+CREATE TABLE IF NOT EXISTS agent_messages (
+ id bigserial PRIMARY KEY,
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ role text NOT NULL CHECK (role IN ('user', 'assistant')),
+ content text NOT NULL,
+ model text,
+ provider text,
+ input_tokens int,
+ output_tokens int,
+ cost_micro_usd bigint,
+ charged_usd numeric(20, 6) NOT NULL DEFAULT 0,
+ free_tier boolean NOT NULL DEFAULT false,
+ tool_calls jsonb NOT NULL DEFAULT '[]'::jsonb,
+ signatures text[] NOT NULL DEFAULT '{}',
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS agent_messages_thread_idx ON agent_messages (agent_id, user_id, id DESC);
+CREATE INDEX IF NOT EXISTS agent_messages_user_day_idx ON agent_messages (user_id, created_at) WHERE role = 'user';
+
+-- ── automations ──────────────────────────────────────────────────────────────
+-- One trigger, one action. Spend and notify actions execute through a backing
+-- wallet intent (trigger_type 'on_automation', never swept on its own) so they
+-- inherit the intent engine's caps, spend policy and custody ledger. The
+-- `agent_prompt` action starts an agent run.
+CREATE TABLE IF NOT EXISTS agent_automations (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ title text,
+ trigger_type text NOT NULL
+ CHECK (trigger_type IN ('price_threshold', 'schedule', 'balance_below', 'tip_received', 'launch_matching', 'graduation', 'whale_buy')),
+ trigger_config jsonb NOT NULL DEFAULT '{}'::jsonb,
+ action_type text NOT NULL CHECK (action_type IN ('agent_prompt', 'swap', 'transfer', 'notify')),
+ action_config jsonb NOT NULL DEFAULT '{}'::jsonb,
+ trigger_once boolean NOT NULL DEFAULT false,
+ enabled boolean NOT NULL DEFAULT true,
+ intent_id uuid,
+ state jsonb NOT NULL DEFAULT '{}'::jsonb,
+ fire_count int NOT NULL DEFAULT 0,
+ last_fired_at timestamptz,
+ last_checked_at timestamptz,
+ last_status text,
+ last_note text,
+ source text NOT NULL DEFAULT 'api',
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS agent_automations_agent_idx ON agent_automations (agent_id, created_at DESC);
+CREATE INDEX IF NOT EXISTS agent_automations_live_idx ON agent_automations (trigger_type) WHERE enabled = true;
+
+-- ── link codes ───────────────────────────────────────────────────────────────
+-- An eight-character code pairs a device or chat gateway to an account for ten
+-- minutes. Only the sha256 of the code is stored; redemption is single use.
+CREATE TABLE IF NOT EXISTS account_link_codes (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ code_hash text NOT NULL UNIQUE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,
+ label text,
+ scopes text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ expires_at timestamptz NOT NULL,
+ redeemed_at timestamptz,
+ link_id uuid
+);
+CREATE INDEX IF NOT EXISTS account_link_codes_user_idx ON account_link_codes (user_id, created_at DESC);
+
+-- A redeemed code becomes a link: which device or gateway identity is paired,
+-- and the API key it was issued (revoking the link revokes the key).
+CREATE TABLE IF NOT EXISTS account_links (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,
+ kind text NOT NULL,
+ external_id text,
+ label text,
+ api_key_id uuid REFERENCES api_keys(id) ON DELETE SET NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ last_seen_at timestamptz,
+ revoked_at timestamptz
+);
+CREATE INDEX IF NOT EXISTS account_links_user_idx ON account_links (user_id) WHERE revoked_at IS NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS account_links_external_uidx ON account_links (kind, external_id)
+ WHERE revoked_at IS NULL AND external_id IS NOT NULL;
diff --git a/api/agents.js b/api/agents.js
index ceacfae1f..7cc069f44 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -17,12 +17,9 @@ import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error, serverError, rateLimited } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { generateAgentWallet, generateSolanaAgentWallet } from './_lib/agent-wallet.js';
-import { checkIdentityIntegrity } from './_lib/identity-integrity.js';
+import { createAgentIdentity, mintAgentWalletMeta } from './_lib/agent-create.js';
import { publicUrl, thumbnailUrl } from './_lib/r2.js';
import { pedigreeScore } from './_lib/genome.js';
-import { pingIndexNow } from './_lib/indexnow.js';
-import { publishFeedEvent } from './_lib/feed.js';
import { getSkillPrices, skillPriceMap } from './_lib/skill-price-cache.js';
import { cacheWrap } from './_lib/cache.js';
import { trackAgentOwnerVisit } from './_lib/retention.js';
@@ -194,41 +191,6 @@ async function handleList(req, res) {
return json(res, 200, { agents: rows.map((row) => decorate(row)) });
}
-// Mint the agent's custodial EVM + Solana wallets for the initial INSERT.
-//
-// Minting can fail when the at-rest encryption key is unavailable — in
-// production secret-box.js fails CLOSED rather than encrypt custodial secrets
-// under the JWT_SECRET fallback (see api/_lib/secret-box.js). That must never
-// brick the core product action of creating an agent. The platform already mints
-// wallets lazily and idempotently on first use (ensureAgentWallet /
-// getOrCreateAgentEvmWallet), so a walletless identity self-heals the next time
-// it touches a wallet once the key is configured — exactly how the avatar-agent
-// path degrades. On failure we create the agent with a null wallet_address and
-// no encrypted keys, and log a warning (never the secret-box internals as an
-// unhandled 500). Returns { walletAddress, meta } for the INSERT.
-async function mintAgentWalletMeta() {
- try {
- const [wallet, sol] = await Promise.all([
- generateAgentWallet(),
- generateSolanaAgentWallet(),
- ]);
- return {
- walletAddress: wallet.address,
- meta: {
- encrypted_wallet_key: wallet.encrypted_key,
- solana_address: sol.address,
- encrypted_solana_secret: sol.encrypted_secret,
- },
- };
- } catch (err) {
- console.warn(
- '[agents] wallet provisioning deferred — minting failed at create time, ' +
- 'agent will be provisioned lazily on first wallet use:',
- err?.message,
- );
- return { walletAddress: null, meta: {} };
- }
-}
// ── Get-or-create default agent ───────────────────────────────────────────
@@ -327,77 +289,21 @@ async function handleCreate(req, res) {
avatarId = av.id;
}
- // Granite identity-integrity gate. Refuse to mint an identity that impersonates
- // an existing public agent (Granite embedding look-alike) or fails Granite
- // Guardian content screening. Best-effort: any failure — or watsonx being
- // unconfigured — lets creation proceed rather than failing closed.
- let integrity = null;
- try {
- integrity = await checkIdentityIntegrity(
- { name, description: body.description, persona_tone_tags: body.persona_tone_tags },
- { userId: auth.userId },
- );
- if (integrity.status === 'block') {
- return error(
- res,
- 409,
- 'identity_conflict',
- integrity.reasons[0] || 'this identity conflicts with an existing agent',
- { integrity },
- );
- }
- } catch (err) {
- console.error('[agents] identity_integrity_check_failed', err);
- integrity = null;
- }
-
- const { walletAddress, meta: walletMeta } = await mintAgentWalletMeta();
- const meta = {
- ...(body.meta || {}),
- ...walletMeta,
- };
- // Stamp the integrity verdict onto the identity so the profile/editor can show
- // a "distinct identity" signal and reviewers can see what was checked at birth.
- if (integrity && integrity.configured) {
- meta.identity_integrity = {
- status: integrity.status,
- uniqueness: integrity.uniqueness,
- guardian: integrity.guardian ? integrity.guardian.decision : null,
- closest: integrity.similar[0]
- ? { name: integrity.similar[0].name, score: integrity.similar[0].score }
- : null,
- checked_at: new Date().toISOString(),
- };
- }
-
- const [agent] = await sql`
- INSERT INTO agent_identities (user_id, name, description, skills, wallet_address, meta, avatar_id)
- VALUES (
- ${auth.userId},
- ${name},
- ${body.description ? String(body.description).slice(0, 500) : null},
- ${body.skills || ['greet', 'present-model', 'validate-model', 'remember', 'think']},
- ${walletAddress},
- ${JSON.stringify(meta)}::jsonb,
- ${avatarId}
- )
- RETURNING *
- `;
-
- // Push the new agent's URL to IndexNow so Bing / Yandex discover it within
- // minutes instead of waiting for the next crawl. Fire-and-forget — IndexNow
- // failures must never block agent creation.
- pingIndexNow(`${env.APP_ORIGIN}/agents/${agent.id}`).catch(() => {});
-
- // Announce the new agent on the site-wide live activity ticker — discovery +
- // social proof. Fire-and-forget; never block or fail creation on the feed.
- publishFeedEvent({
- type: 'agent-deploy',
- ts: Date.now(),
- actor: name,
- agentId: agent.id,
+ const created = await createAgentIdentity({
+ userId: auth.userId,
name,
- }).catch(() => {});
+ description: body.description,
+ personaToneTags: body.persona_tone_tags,
+ avatarId,
+ skills: body.skills,
+ meta: body.meta,
+ });
+ if (created.blocked) {
+ return error(res, 409, 'identity_conflict', created.blocked.message, {
+ integrity: created.blocked.integrity,
+ });
+ }
+ const { agent } = created;
return json(res, 201, { agent: decorate(agent) });
}
diff --git a/data/agent-strategies.json b/data/agent-strategies.json
new file mode 100644
index 000000000..29832b30d
--- /dev/null
+++ b/data/agent-strategies.json
@@ -0,0 +1,122 @@
+{
+ "$comment": "Strategy presets for POST /api/v1/agents { strategy }. Each preset is a bundle of skills (ids from src/studio/skills/skills-catalog.js), persona text that becomes the agent's system prompt when none is given, the server tools a run may use by default (names from api/_lib/agent-tools.js), and default automations created with the agent. Default automations never spend: their actions are notify or agent_prompt only. Validated by api/_lib/agents-v1/strategies.js on load and by tests/agents-v1-strategies.test.js.",
+ "version": 1,
+ "strategies": [
+ {
+ "id": "momentum",
+ "name": "Momentum",
+ "summary": "Watches Solana tokens with accelerating price and volume, checks safety before anything else, and reports the strongest movers with the evidence.",
+ "skills": ["greet", "remember", "think", "pump-fun", "web-search"],
+ "temperature": 0.4,
+ "persona": "You are a momentum analyst for Solana tokens. You look for tokens whose price and volume are accelerating together, and you never recommend one without first checking its safety verdict and liquidity. You state numbers with their source and timeframe, you say plainly when data is missing, and you separate evidence from opinion. You never promise returns.",
+ "toolsAllowed": ["trending_tokens", "token_price", "token_safety", "smart_money", "web_search"],
+ "automations": [
+ {
+ "title": "Momentum scan every 4 hours",
+ "trigger": { "type": "schedule", "cron": "0 */4 * * *" },
+ "action": {
+ "type": "agent_prompt",
+ "prompt": "Scan the trending Solana tokens for the last few hours. Pick the three with the strongest combined price and volume acceleration, run a safety check on each, and report symbol, mint, 1h change, liquidity and the safety verdict. Flag anything that fails safety instead of ranking it."
+ }
+ }
+ ]
+ },
+ {
+ "id": "sniper",
+ "name": "Sniper",
+ "summary": "Watches brand-new launches under a market-cap ceiling and screens each one for rug risk the moment it appears.",
+ "skills": ["greet", "remember", "think", "pump-fun"],
+ "temperature": 0.3,
+ "persona": "You are a launch screener. You evaluate new Solana token launches in their first minutes: creator history, holder concentration, liquidity and the rug and honeypot safety verdict. You are skeptical by default and say so when a launch looks unsafe. You report facts first and keep verdicts short.",
+ "toolsAllowed": ["token_safety", "token_price", "smart_money", "sol_balance"],
+ "automations": [
+ {
+ "title": "Screen small launches",
+ "trigger": { "type": "launch_matching", "maxMcapUsd": 20000, "cooldownMinutes": 30 },
+ "action": {
+ "type": "agent_prompt",
+ "prompt": "A new launch matched your filter. Run the safety check on its mint, look at smart-money activity, and give a one-paragraph verdict: pass, watch, or avoid, with the reasons."
+ }
+ }
+ ]
+ },
+ {
+ "id": "defi-yield",
+ "name": "DeFi yield",
+ "summary": "Tracks the wallet's idle SOL and reports on it, and warns when the balance runs low.",
+ "skills": ["greet", "remember", "think", "web-search"],
+ "temperature": 0.3,
+ "persona": "You are a conservative yield researcher. You explain where idle funds could earn yield, what the risks are (smart-contract, depeg, liquidity, lockups), and what the realistic net return is after fees. You never recommend a position you cannot source, and you always mention the downside.",
+ "toolsAllowed": ["sol_balance", "token_price", "web_search"],
+ "automations": [
+ {
+ "title": "Low balance warning",
+ "trigger": { "type": "balance_below", "thresholdSol": 0.05 },
+ "action": { "type": "notify", "message": "Your agent's wallet dropped below 0.05 SOL. Top it up to keep automations running." }
+ },
+ {
+ "title": "Weekly yield review",
+ "trigger": { "type": "schedule", "cron": "0 14 * * 1" },
+ "action": {
+ "type": "agent_prompt",
+ "prompt": "Check the agent wallet's SOL balance and current SOL price, then research the current realistic yield options for idle SOL. Summarize the top options with net APY, the main risk of each, and how liquid it is."
+ }
+ }
+ ]
+ },
+ {
+ "id": "macro-hedge",
+ "name": "Macro hedge",
+ "summary": "Reads the broader market every morning and flags regime changes that should change how much risk the agent takes.",
+ "skills": ["greet", "remember", "think", "web-search"],
+ "temperature": 0.5,
+ "persona": "You are a macro-aware risk manager for a crypto portfolio. You read the broad market (total market cap, dominance, SOL trend, major news) and translate it into plain risk guidance: risk on, neutral, or risk off, with the evidence. You keep it short and you never trade on headlines alone.",
+ "toolsAllowed": ["token_price", "trending_tokens", "web_search"],
+ "automations": [
+ {
+ "title": "Morning macro brief",
+ "trigger": { "type": "schedule", "cron": "0 13 * * *" },
+ "action": {
+ "type": "agent_prompt",
+ "prompt": "Write the morning macro brief: SOL price and 24h change, what is trending, and any major market news. End with one line: risk on, neutral, or risk off, and why."
+ }
+ }
+ ]
+ },
+ {
+ "id": "monitor-exit",
+ "name": "Monitor and exit",
+ "summary": "Watches graduations and big buys and tells you when a position's conditions change, so you can decide whether to exit.",
+ "skills": ["greet", "remember", "think", "pump-fun"],
+ "temperature": 0.3,
+ "persona": "You are a position monitor. Your job is to notice when conditions on a token change: graduation to the open market, whale activity, a safety verdict that worsens, a sharp reversal. You report the change, what it usually means, and the options, without deciding for the owner.",
+ "toolsAllowed": ["token_price", "token_safety", "smart_money"],
+ "automations": [
+ {
+ "title": "Graduation watch",
+ "trigger": { "type": "graduation", "cooldownMinutes": 60 },
+ "action": {
+ "type": "agent_prompt",
+ "prompt": "A token just graduated from its bonding curve. Check its price, safety verdict and smart-money flow, and summarize whether post-graduation conditions look healthy."
+ }
+ }
+ ]
+ },
+ {
+ "id": "conservative",
+ "name": "Conservative",
+ "summary": "A careful assistant that answers questions with sourced data, checks safety first, and only notifies you. No trading automations.",
+ "skills": ["greet", "present-model", "validate-model", "remember", "think"],
+ "temperature": 0.2,
+ "persona": "You are a careful, plain-spoken assistant. You answer with sourced, current data, you check the safety of any token before discussing it, and you say clearly when you do not know. You never encourage risky trades and you never move funds.",
+ "toolsAllowed": ["token_price", "token_safety", "sol_balance", "resolve_sol_name", "web_search"],
+ "automations": [
+ {
+ "title": "Low balance warning",
+ "trigger": { "type": "balance_below", "thresholdSol": 0.02 },
+ "action": { "type": "notify", "message": "Your agent's wallet is below 0.02 SOL." }
+ }
+ ]
+ }
+ ]
+}
diff --git a/packages/agents-sdk/src/errors.ts b/packages/agents-sdk/src/errors.ts
new file mode 100644
index 000000000..ee3e53298
--- /dev/null
+++ b/packages/agents-sdk/src/errors.ts
@@ -0,0 +1,277 @@
+// Typed errors for @three-ws/agents.
+//
+// Every HTTP failure surfaces as a subclass of ThreeAgentsError carrying the
+// HTTP status, the stable error code from the v1 envelope, the request id (quote
+// it to support), the envelope's `details`, and the rate-limit headers the
+// server sent. On-chain failures reuse the error classes of
+// @three-ws/solana-agent (bundled from its source at build time, so this
+// package still has zero runtime dependencies) and carry the same fields.
+
+import {
+ SolanaAgentError,
+ SwapError,
+ SimulationError,
+ ConfirmationTimeoutError,
+ TransactionRejectedError,
+} from "../../../solana-agent-sdk/src/errors";
+
+export {
+ SolanaAgentError,
+ SwapError,
+ SimulationError,
+ ConfirmationTimeoutError,
+ TransactionRejectedError,
+ WalletNotConnectedError,
+ WalletCapabilityError,
+ MissingTokenAccountError,
+} from "../../../solana-agent-sdk/src/errors";
+
+/** Rate-limit state read from the RateLimit-* headers of the failing response. */
+export interface RateLimitInfo {
+ limit: number | null;
+ remaining: number | null;
+ /** Seconds until the window resets. */
+ reset: number | null;
+}
+
+/** Fields every error from this SDK carries, including the on-chain classes. */
+export interface ErrorContext {
+ status?: number;
+ code?: string;
+ requestId?: string | null;
+ details?: unknown;
+ rateLimit?: RateLimitInfo | null;
+ method?: string;
+ path?: string;
+}
+
+/** Base class for every HTTP, validation and transport error thrown by the client. */
+export class ThreeAgentsError extends Error {
+ /** HTTP status, or undefined when the request never got a response. */
+ readonly status: number | undefined;
+ /** Stable machine-readable code from the error envelope, e.g. `not_found`. */
+ readonly code: string;
+ /** Server request id (X-Request-Id). Include it in support requests. */
+ readonly requestId: string | null;
+ /** The envelope's `details` value, verbatim. */
+ readonly details: unknown;
+ /** RateLimit-* headers from the failing response, when the server sent them. */
+ readonly rateLimit: RateLimitInfo | null;
+ readonly method: string | undefined;
+ readonly path: string | undefined;
+
+ constructor(message: string, ctx: ErrorContext = {}) {
+ super(message);
+ this.name = new.target.name;
+ this.status = ctx.status;
+ this.code = ctx.code ?? "error";
+ this.requestId = ctx.requestId ?? null;
+ this.details = ctx.details;
+ this.rateLimit = ctx.rateLimit ?? null;
+ this.method = ctx.method;
+ this.path = ctx.path;
+ }
+}
+
+/** 401: the API key is missing, malformed, revoked or expired. */
+export class AuthenticationError extends ThreeAgentsError {}
+
+/** 403: the key is valid but lacks a scope, or the resource belongs to someone else. */
+export class PermissionError extends ThreeAgentsError {
+ /** The OAuth scope the route requires, when the failure was a missing scope. */
+ readonly scope: string | null;
+ constructor(message: string, ctx: ErrorContext & { scope?: string | null } = {}) {
+ super(message, ctx);
+ this.scope = ctx.scope ?? null;
+ }
+}
+
+/** 404: the agent, run, automation or skill does not exist or is not yours. */
+export class NotFoundError extends ThreeAgentsError {}
+
+/** One invalid field reported by a 400 / 422 response. */
+export interface FieldError {
+ field: string;
+ message: string;
+}
+
+/** 400 / 422: the request body or query failed validation. */
+export class ValidationError extends ThreeAgentsError {
+ readonly fields: FieldError[];
+ constructor(message: string, ctx: ErrorContext & { fields?: FieldError[] } = {}) {
+ super(message, ctx);
+ this.fields = ctx.fields ?? [];
+ }
+}
+
+/** 429: too many requests. Wait `retryAfter` seconds before trying again. */
+export class RateLimitError extends ThreeAgentsError {
+ readonly retryAfter: number | null;
+ constructor(message: string, ctx: ErrorContext & { retryAfter?: number | null } = {}) {
+ super(message, ctx);
+ this.retryAfter = ctx.retryAfter ?? null;
+ }
+}
+
+/** 402 or an insufficient-balance code: credits or wallet funds do not cover the call. */
+export class InsufficientFundsError extends ThreeAgentsError {}
+
+/**
+ * A fund-moving call was made without its explicit confirm flag. Thrown by the
+ * client before any request is sent, and mapped from the server's
+ * `confirmation_required` code.
+ */
+export class ConfirmationRequiredError extends ThreeAgentsError {
+ /** The flag that must be set to `true`, e.g. `confirm`. */
+ readonly confirmFlag: string;
+ /** The client method that previews the action and returns the quote to confirm. */
+ readonly previewMethod: string;
+ constructor(
+ message: string,
+ ctx: ErrorContext & { confirmFlag: string; previewMethod: string },
+ ) {
+ super(message, { code: "confirmation_required", ...ctx });
+ this.confirmFlag = ctx.confirmFlag;
+ this.previewMethod = ctx.previewMethod;
+ }
+}
+
+/** 5xx after every retry was spent. */
+export class ServerError extends ThreeAgentsError {}
+
+/** The request did not finish within `timeout` ms, after every retry was spent. */
+export class TimeoutError extends ThreeAgentsError {
+ readonly timeoutMs: number;
+ constructor(message: string, ctx: ErrorContext & { timeoutMs: number }) {
+ super(message, { code: "timeout", ...ctx });
+ this.timeoutMs = ctx.timeoutMs;
+ }
+}
+
+/** The server could not be reached (DNS, TLS, connection reset), after every retry. */
+export class ConnectionError extends ThreeAgentsError {}
+
+/** The on-chain classes, decorated with the same request context as HTTP errors. */
+export type OnChainError = SolanaAgentError & ErrorContext;
+
+function decorate<T extends SolanaAgentError>(err: T, ctx: ErrorContext): T & ErrorContext {
+ return Object.assign(err, {
+ status: ctx.status,
+ code: ctx.code,
+ requestId: ctx.requestId ?? null,
+ details: ctx.details,
+ rateLimit: ctx.rateLimit ?? null,
+ method: ctx.method,
+ path: ctx.path,
+ });
+}
+
+function detailString(details: unknown, key: string): string | undefined {
+ if (details && typeof details === "object" && key in details) {
+ const v = (details as Record<string, unknown>)[key];
+ if (typeof v === "string") return v;
+ }
+ return undefined;
+}
+
+function detailNumber(details: unknown, key: string): number | undefined {
+ if (details && typeof details === "object" && key in details) {
+ const v = Number((details as Record<string, unknown>)[key]);
+ if (Number.isFinite(v)) return v;
+ }
+ return undefined;
+}
+
+/** Normalise the many shapes a validation `details` value takes into field errors. */
+export function fieldErrorsFrom(details: unknown, message = "invalid"): FieldError[] {
+ if (!details || typeof details !== "object") return [];
+ const d = details as Record<string, unknown>;
+ // The v1 router's input helpers report one field as { parameter: name }.
+ if (typeof d.parameter === "string") return [{ field: d.parameter, message }];
+ const list = Array.isArray(details)
+ ? details
+ : Array.isArray(d.fields)
+ ? d.fields
+ : Array.isArray(d.issues)
+ ? d.issues
+ : null;
+ if (list) {
+ return list
+ .filter((x): x is Record<string, unknown> => !!x && typeof x === "object")
+ .map((x) => ({
+ field: Array.isArray(x.path) ? x.path.join(".") : String(x.field ?? x.path ?? ""),
+ message: String(x.message ?? "invalid"),
+ }));
+ }
+ if (d.fieldErrors && typeof d.fieldErrors === "object") {
+ return Object.entries(d.fieldErrors as Record<string, unknown>).flatMap(([field, msgs]) =>
+ (Array.isArray(msgs) ? msgs : [msgs]).map((m) => ({ field, message: String(m) })),
+ );
+ }
+ return [];
+}
+
+const INSUFFICIENT_CODES = new Set([
+ "insufficient_funds",
+ "insufficient_credits",
+ "insufficient_balance",
+ "payment_required",
+ "budget_exhausted",
+]);
+
+/**
+ * Build the right error for a non-2xx response. `retryAfter` is the parsed
+ * Retry-After value in seconds.
+ */
+export function errorFromResponse(
+ message: string,
+ ctx: ErrorContext & { status: number; retryAfter?: number | null },
+): ThreeAgentsError | OnChainError {
+ const { status, code = "error", details } = ctx;
+
+ switch (code) {
+ case "swap_failed":
+ return decorate(
+ new SwapError(message, detailString(details, "inputMint"), detailString(details, "outputMint")),
+ ctx,
+ );
+ case "simulation_failed":
+ return decorate(new SimulationError(details ?? message), ctx);
+ case "confirmation_timeout":
+ case "withdrawal_unconfirmed":
+ return decorate(
+ new ConfirmationTimeoutError(
+ detailString(details, "signature") ?? "",
+ detailNumber(details, "timeoutMs") ?? 0,
+ ),
+ ctx,
+ );
+ case "transaction_rejected":
+ return decorate(new TransactionRejectedError(message), ctx);
+ case "confirmation_required":
+ return new ConfirmationRequiredError(message, {
+ ...ctx,
+ confirmFlag: detailString(details, "confirmFlag") ?? "confirm",
+ previewMethod: detailString(details, "previewMethod") ?? "",
+ });
+ }
+
+ if (INSUFFICIENT_CODES.has(code) || status === 402) return new InsufficientFundsError(message, ctx);
+ if (status === 401) return new AuthenticationError(message, ctx);
+ if (status === 403) {
+ const scope =
+ detailString(details, "required") ??
+ detailString(details, "scope") ??
+ detailString(details, "requiredScope") ??
+ /"([a-z]+:[a-z_]+)"/.exec(message)?.[1] ??
+ null;
+ return new PermissionError(message, { ...ctx, scope });
+ }
+ if (status === 404) return new NotFoundError(message, ctx);
+ if (status === 400 || status === 422) {
+ return new ValidationError(message, { ...ctx, fields: fieldErrorsFrom(details, message) });
+ }
+ if (status === 429) return new RateLimitError(message, { ...ctx, retryAfter: ctx.retryAfter ?? null });
+ if (status >= 500) return new ServerError(message, ctx);
+ return new ThreeAgentsError(message, ctx);
+}
diff --git a/packages/agents-sdk/src/sse.ts b/packages/agents-sdk/src/sse.ts
new file mode 100644
index 000000000..4b0d22f60
--- /dev/null
+++ b/packages/agents-sdk/src/sse.ts
@@ -0,0 +1,87 @@
+// Minimal, spec-conformant Server-Sent Events parser over a fetch body.
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
+
+export interface SseMessage {
+ /** The `event:` field, `message` when the server sent none. */
+ event: string;
+ /** Concatenated `data:` lines. */
+ data: string;
+ /** The `id:` field of this message, or the last one seen. */
+ id: string | null;
+ /** The `retry:` hint in ms, when present. */
+ retry: number | null;
+}
+
+/** Yield one SseMessage per dispatched event from a byte stream. */
+export async function* parseSse(body: ReadableStream<Uint8Array>): AsyncGenerator<SseMessage> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ let event = "";
+ let data: string[] = [];
+ let lastId: string | null = null;
+ let retry: number | null = null;
+
+ const dispatch = (): SseMessage | null => {
+ if (data.length === 0) {
+ event = "";
+ return null;
+ }
+ const msg = { event: event || "message", data: data.join("\n"), id: lastId, retry };
+ event = "";
+ data = [];
+ retry = null;
+ return msg;
+ };
+
+ const handleLine = (line: string): SseMessage | null => {
+ if (line === "") return dispatch();
+ if (line.startsWith(":")) return null;
+ const colon = line.indexOf(":");
+ const field = colon === -1 ? line : line.slice(0, colon);
+ let value = colon === -1 ? "" : line.slice(colon + 1);
+ if (value.startsWith(" ")) value = value.slice(1);
+ switch (field) {
+ case "event":
+ event = value;
+ break;
+ case "data":
+ data.push(value);
+ break;
+ case "id":
+ if (!value.includes("\0")) lastId = value;
+ break;
+ case "retry":
+ if (/^\d+$/.test(value)) retry = Number(value);
+ break;
+ }
+ return null;
+ };
+
+ try {
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let idx: number;
+ while ((idx = buffer.search(/\r\n|\r|\n/)) !== -1) {
+ // A trailing CR may be the first half of a CRLF split across chunks.
+ if (buffer[idx] === "\r" && idx === buffer.length - 1) break;
+ const line = buffer.slice(0, idx);
+ const sepLen = buffer.startsWith("\r\n", idx) ? 2 : 1;
+ buffer = buffer.slice(idx + sepLen);
+ const msg = handleLine(line);
+ if (msg) yield msg;
+ }
+ }
+ buffer += decoder.decode();
+ if (buffer) {
+ const msg = handleLine(buffer);
+ if (msg) yield msg;
+ }
+ const tail = dispatch();
+ if (tail) yield tail;
+ } finally {
+ reader.releaseLock();
+ }
+}
diff --git a/packages/agents-sdk/src/transport.ts b/packages/agents-sdk/src/transport.ts
new file mode 100644
index 000000000..a5476bb98
--- /dev/null
+++ b/packages/agents-sdk/src/transport.ts
@@ -0,0 +1,311 @@
+// HTTP transport: auth header, timeout, retries with exponential backoff,
+// idempotency keys, envelope unwrapping and error mapping. Uses the global
+// `fetch` (Node 20+, Deno, Bun, browsers) or one passed in the options.
+
+import {
+ ConnectionError,
+ ServerError,
+ ThreeAgentsError,
+ TimeoutError,
+ errorFromResponse,
+ type RateLimitInfo,
+} from "./errors";
+
+export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
+
+export interface TransportOptions {
+ apiKey: string;
+ baseUrl: string;
+ timeout: number;
+ retries: number;
+ retryDelay: number;
+ fetch: FetchLike;
+ userAgent: string;
+ defaultHeaders: Record<string, string>;
+}
+
+/** Response metadata the v1 API attaches to every reply. */
+export interface ResponseMeta {
+ requestId: string | null;
+ timestamp: string | null;
+ hasMore?: boolean;
+ nextCursor?: string | null;
+ rateLimit: RateLimitInfo | null;
+}
+
+export interface RequestSpec {
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
+ path: string;
+ query?: Record<string, string | number | boolean | undefined | null | string[]>;
+ body?: unknown;
+ /**
+ * Send an Idempotency-Key. `true` generates one; a string uses it verbatim.
+ * The same key is reused across retries so a retried POST never acts twice.
+ */
+ idempotencyKey?: string | boolean;
+ /** Per-call overrides of the client defaults. */
+ timeout?: number;
+ retries?: number;
+ signal?: AbortSignal;
+}
+
+export interface RawResult<T> {
+ data: T;
+ meta: ResponseMeta;
+}
+
+const RETRYABLE_STATUS = (s: number) => s >= 500 && s <= 599;
+
+export function newIdempotencyKey(): string {
+ const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
+ if (c?.randomUUID) return c.randomUUID();
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`;
+}
+
+function headerNumber(h: Headers, name: string): number | null {
+ const raw = h.get(name);
+ if (raw == null || raw === "") return null;
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : null;
+}
+
+export function readRateLimit(h: Headers): RateLimitInfo | null {
+ const limit = headerNumber(h, "ratelimit-limit") ?? headerNumber(h, "x-ratelimit-limit");
+ const remaining = headerNumber(h, "ratelimit-remaining") ?? headerNumber(h, "x-ratelimit-remaining");
+ const reset = headerNumber(h, "ratelimit-reset") ?? headerNumber(h, "x-ratelimit-reset");
+ if (limit == null && remaining == null && reset == null) return null;
+ return { limit, remaining, reset };
+}
+
+/** Retry-After in seconds, from either the delta-seconds or the HTTP-date form. */
+export function readRetryAfter(h: Headers): number | null {
+ const raw = h.get("retry-after");
+ if (!raw) return null;
+ const n = Number(raw);
+ if (Number.isFinite(n)) return Math.max(0, n);
+ const at = Date.parse(raw);
+ return Number.isFinite(at) ? Math.max(0, Math.ceil((at - Date.now()) / 1000)) : null;
+}
+
+function buildUrl(baseUrl: string, path: string, query?: RequestSpec["query"]): string {
+ const url = new URL(baseUrl.replace(/\/+$/, "") + path);
+ if (query) {
+ for (const [k, v] of Object.entries(query)) {
+ if (v === undefined || v === null) continue;
+ url.searchParams.set(k, Array.isArray(v) ? v.join(",") : String(v));
+ }
+ }
+ return url.toString();
+}
+
+async function readBody(res: Response): Promise<unknown> {
+ const text = await res.text();
+ if (!text) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+interface ParsedError {
+ code: string;
+ message: string;
+ details: unknown;
+}
+
+/**
+ * Read either envelope: the v1 `{ error: { code, message, details } }` or the
+ * legacy `{ error: "code", error_description: "…" }` older routes still use.
+ */
+function parseError(body: unknown, status: number): ParsedError {
+ if (body && typeof body === "object") {
+ const b = body as Record<string, unknown>;
+ const e = b.error;
+ if (e && typeof e === "object") {
+ const eo = e as Record<string, unknown>;
+ return {
+ code: String(eo.code ?? "error"),
+ message: String(eo.message ?? `HTTP ${status}`),
+ details: eo.details,
+ };
+ }
+ if (typeof e === "string") {
+ const { error: _e, error_description, ...rest } = b;
+ return {
+ code: e,
+ message: String(error_description ?? e),
+ details: Object.keys(rest).length ? rest : undefined,
+ };
+ }
+ }
+ return { code: `http_${status}`, message: typeof body === "string" && body ? body.slice(0, 300) : `HTTP ${status}` };
+}
+
+function metaFrom(body: unknown, res: Response): ResponseMeta {
+ const m =
+ body && typeof body === "object" && (body as Record<string, unknown>).meta && typeof (body as Record<string, unknown>).meta === "object"
+ ? ((body as Record<string, unknown>).meta as Record<string, unknown>)
+ : {};
+ return {
+ requestId: (m.requestId as string | undefined) ?? res.headers.get("x-request-id"),
+ timestamp: (m.timestamp as string | undefined) ?? null,
+ hasMore: typeof m.hasMore === "boolean" ? m.hasMore : undefined,
+ nextCursor: (m.nextCursor as string | null | undefined) ?? undefined,
+ rateLimit: readRateLimit(res.headers),
+ };
+}
+
+function unwrapData(body: unknown): unknown {
+ if (body && typeof body === "object" && "data" in (body as Record<string, unknown>)) {
+ return (body as Record<string, unknown>).data;
+ }
+ return body;
+}
+
+const sleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (signal?.aborted) return reject(signal.reason);
+ const t = setTimeout(resolve, ms);
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(t);
+ reject(signal.reason);
+ },
+ { once: true },
+ );
+ });
+
+/** Backoff for attempt n (0-based): retryDelay * 2^n, with up to 20% jitter. */
+export function backoffMs(retryDelay: number, attempt: number): number {
+ const base = retryDelay * 2 ** attempt;
+ return Math.round(base + base * 0.2 * Math.random());
+}
+
+export class Transport {
+ constructor(readonly opts: TransportOptions) {}
+
+ private headers(spec: RequestSpec, idemKey: string | null, stream: boolean): Record<string, string> {
+ const h: Record<string, string> = {
+ ...this.opts.defaultHeaders,
+ authorization: `Bearer ${this.opts.apiKey}`,
+ accept: stream ? "text/event-stream" : "application/json",
+ };
+ if (typeof process === "undefined" || !process.versions?.node) {
+ // Browsers forbid setting User-Agent; send our identifier separately.
+ h["x-three-ws-client"] = this.opts.userAgent;
+ } else {
+ h["user-agent"] = this.opts.userAgent;
+ }
+ if (spec.body !== undefined) h["content-type"] = "application/json";
+ if (idemKey) h["idempotency-key"] = idemKey;
+ return h;
+ }
+
+ /**
+ * Open a request and return the Response once headers arrive, applying the
+ * retry policy to connection failures, timeouts and 5xx. Used directly by the
+ * SSE stream and by `request` for JSON calls.
+ */
+ async open(spec: RequestSpec, stream = false): Promise<{ res: Response; clear: () => void }> {
+ const url = buildUrl(this.opts.baseUrl, spec.path, spec.query);
+ const retries = spec.retries ?? this.opts.retries;
+ const timeoutMs = spec.timeout ?? this.opts.timeout;
+ const idemKey =
+ typeof spec.idempotencyKey === "string"
+ ? spec.idempotencyKey
+ : spec.idempotencyKey
+ ? newIdempotencyKey()
+ : null;
+ const ctxBase = { method: spec.method, path: spec.path };
+
+ let lastErr: ThreeAgentsError | Error | null = null;
+ for (let attempt = 0; attempt <= retries; attempt++) {
+ if (attempt > 0) await sleep(backoffMs(this.opts.retryDelay, attempt - 1), spec.signal);
+
+ const ctrl = new AbortController();
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ ctrl.abort();
+ }, timeoutMs);
+ const onAbort = () => ctrl.abort(spec.signal?.reason);
+ spec.signal?.addEventListener("abort", onAbort, { once: true });
+ const clear = () => {
+ clearTimeout(timer);
+ spec.signal?.removeEventListener("abort", onAbort);
+ };
+
+ let res: Response;
+ try {
+ res = await this.opts.fetch(url, {
+ method: spec.method,
+ headers: this.headers(spec, idemKey, stream),
+ body: spec.body === undefined ? undefined : JSON.stringify(spec.body),
+ signal: ctrl.signal,
+ });
+ } catch (err) {
+ clear();
+ if (spec.signal?.aborted) throw spec.signal.reason ?? err;
+ lastErr = timedOut
+ ? new TimeoutError(`${spec.method} ${spec.path} timed out after ${timeoutMs}ms`, {
+ ...ctxBase,
+ timeoutMs,
+ })
+ : new ConnectionError(
+ `${spec.method} ${spec.path} failed: ${(err as Error)?.message ?? String(err)}`,
+ { ...ctxBase, code: "connection_error" },
+ );
+ continue;
+ }
+
+ if (res.ok) {
+ // Streams keep the timer cleared only once the caller finishes; JSON
+ // calls clear it after the body is read (see request()).
+ if (stream) clearTimeout(timer);
+ return { res, clear };
+ }
+
+ const body = await readBody(res).catch(() => null);
+ clear();
+ const parsed = parseError(body, res.status);
+ const meta = metaFrom(body, res);
+ const err = errorFromResponse(parsed.message, {
+ ...ctxBase,
+ status: res.status,
+ code: parsed.code,
+ details: parsed.details,
+ requestId: meta.requestId,
+ rateLimit: meta.rateLimit,
+ retryAfter: readRetryAfter(res.headers),
+ });
+ // 409 idempotency_in_progress: the first attempt with this key is still
+ // running server-side; waiting and retrying returns its stored result.
+ const retryable = RETRYABLE_STATUS(res.status) || parsed.code === "idempotency_in_progress";
+ if (retryable && attempt < retries) {
+ lastErr = err;
+ continue;
+ }
+ throw err;
+ }
+
+ if (lastErr instanceof ThreeAgentsError) throw lastErr;
+ throw new ServerError(`${spec.method} ${spec.path} failed after ${retries + 1} attempts`, ctxBase);
+ }
+
+ async request<T>(spec: RequestSpec): Promise<RawResult<T>> {
+ const { res, clear } = await this.open(spec);
+ try {
+ const body = await readBody(res);
+ return { data: unwrapData(body) as T, meta: metaFrom(body, res) };
+ } catch (err) {
+ throw new ConnectionError(
+ `${spec.method} ${spec.path} response could not be read: ${(err as Error)?.message ?? String(err)}`,
+ { method: spec.method, path: spec.path, status: res.status, code: "connection_error", requestId: res.headers.get("x-request-id") },
+ );
+ } finally {
+ clear();
+ }
+ }
+}
diff --git a/packages/agents-sdk/src/types.ts b/packages/agents-sdk/src/types.ts
new file mode 100644
index 000000000..dc53be434
--- /dev/null
+++ b/packages/agents-sdk/src/types.ts
@@ -0,0 +1,546 @@
+// Public resource and request types for the three.ws v1 agents API.
+//
+// Field names match the JSON the server returns (camelCase throughout). The
+// path table in ./generated/openapi.ts is generated from the server's route
+// table, and the client is type-checked against it, so a method can never point
+// at a route that does not exist.
+
+// ── shared ──────────────────────────────────────────────────────────────────
+
+/** A page of results. Pass `nextCursor` back as `cursor` / `before` for the next page. */
+export interface Page<T> {
+ data: T[];
+ hasMore: boolean;
+ nextCursor: string | null;
+ requestId: string | null;
+}
+
+export interface PageParams {
+ /** Items per page. */
+ limit?: number;
+ /** `nextCursor` from the previous page. */
+ cursor?: string;
+}
+
+/** Per-call options every method accepts as its last argument. */
+export interface RequestOptions {
+ /** Override the client timeout for this call, in ms. */
+ timeout?: number;
+ /** Override the client retry count for this call. */
+ retries?: number;
+ /** Supply your own Idempotency-Key for a POST instead of a generated one. */
+ idempotencyKey?: string;
+ /** Abort the call. */
+ signal?: AbortSignal;
+}
+
+export type Network = "mainnet" | "devnet";
+
+// ── agents ──────────────────────────────────────────────────────────────────
+
+export type StrategyPreset = "momentum" | "sniper" | "defi-yield" | "macro-hedge" | "monitor-exit" | "conservative";
+
+export type AgentStatus = "running" | "stopped";
+
+export interface Agent {
+ id: string;
+ name: string;
+ persona: string | null;
+ systemPrompt: string | null;
+ model: string | null;
+ temperature: number | null;
+ strategy: StrategyPreset | string | null;
+ skills: string[];
+ /** `running` lets automations, intents and runs execute; `stopped` pauses them all. */
+ status: AgentStatus;
+ statusChangedAt: string | null;
+ wallet: { solana: string | null; evm: string | null };
+ avatarId: string | null;
+ isPublic: boolean;
+ /** The agent's public page. */
+ url: string;
+ createdAt: string;
+ updatedAt: string | null;
+}
+
+/** createAgent returns the agent plus the default automations its strategy preset installed. */
+export interface CreatedAgent extends Agent {
+ automations: Automation[];
+}
+
+export interface CreateAgentParams {
+ name: string;
+ /** Short public description of the agent. */
+ persona?: string;
+ /** Full system prompt. A strategy preset supplies one when omitted. */
+ systemPrompt?: string;
+ /** Model id from getModels(). Must support tool calling. */
+ model?: string;
+ temperature?: number;
+ /** Built-in skill ids from listSkills(). */
+ skills?: string[];
+ /** A preset bundle of skills, persona and default automations. */
+ strategy?: StrategyPreset;
+}
+
+export type UpdateAgentParams = Partial<CreateAgentParams> & { strategy?: StrategyPreset | null };
+
+export interface DeletedResource {
+ id: string;
+ deleted: true;
+}
+
+// ── chat ────────────────────────────────────────────────────────────────────
+
+export interface SendMessageParams {
+ message: string;
+ /** Override the agent's model for this message. */
+ model?: string;
+ /** Override the agent's temperature for this message. */
+ temperature?: number;
+}
+
+export interface ToolCallRecord {
+ name: string;
+ arguments?: unknown;
+ result?: unknown;
+ ok?: boolean;
+ [key: string]: unknown;
+}
+
+export interface MessageUsage {
+ inputTokens: number | null;
+ outputTokens: number | null;
+ [key: string]: unknown;
+}
+
+export interface MessageReply {
+ id?: string | number;
+ /** The agent's reply text. */
+ content: string;
+ model: string | null;
+ provider?: string | null;
+ usage: MessageUsage | null;
+ /** Credits charged in USD. Zero when the message was covered by the free tier. */
+ costCredits: number | null;
+ freeTier?: boolean;
+ toolCalls: ToolCallRecord[];
+ /** Signatures of any on-chain transactions the agent made while answering. */
+ signatures: string[];
+ createdAt?: string;
+ [key: string]: unknown;
+}
+
+export interface ChatMessage {
+ id: string | number;
+ role: "user" | "assistant";
+ content: string;
+ model: string | null;
+ createdAt: string;
+ toolCalls?: ToolCallRecord[];
+ signatures?: string[];
+ [key: string]: unknown;
+}
+
+export interface GetMessagesParams {
+ limit?: number;
+ /** `nextCursor` from the previous page: returns older messages. */
+ before?: string;
+}
+
+// ── runs ────────────────────────────────────────────────────────────────────
+
+export type RunStatus =
+ | "scheduled"
+ | "queued"
+ | "running"
+ | "paused"
+ | "completed"
+ | "failed"
+ | "cancelled"
+ | "budget_exhausted";
+
+export interface CreateRunParams {
+ /** What the agent should accomplish. */
+ goal: string;
+ /** Ceiling on model spend from your credits, in USD. */
+ budgetCreditsUsd?: number;
+ /** Ceiling on on-chain spend from the agent wallet, in USD. */
+ budgetUsd?: number;
+ /** 1 to 60 model/tool steps. */
+ maxSteps?: number;
+ /** Restrict the run to these tool names. */
+ toolsAllowed?: string[];
+ model?: string;
+ temperature?: number;
+ /** 5-field UTC cron to repeat the run, or omit to start immediately. */
+ schedule?: string;
+ /** ISO time to start a one-off run later. */
+ scheduledFor?: string;
+}
+
+export interface Run {
+ id: string;
+ agentId: string;
+ goal: string;
+ status: RunStatus;
+ [key: string]: unknown;
+}
+
+export interface UpdateRunParams {
+ /** Pause or resume a run. */
+ action?: "pause" | "resume";
+ budgetCreditsUsd?: number;
+ budgetUsd?: number;
+ maxSteps?: number;
+}
+
+export type RunStepKind = "status" | "model_call" | "tool_call" | "tool_result" | "tool_blocked" | "final" | "error";
+
+export interface RunStep {
+ seq: number;
+ kind: RunStepKind;
+ [key: string]: unknown;
+}
+
+/** One server-sent event from streamRun(). `data` is the parsed JSON payload. */
+export interface RunEvent<T = unknown> {
+ event: string;
+ data: T;
+ id: string | null;
+}
+
+// ── automations ─────────────────────────────────────────────────────────────
+
+export type AutomationTrigger =
+ | { type: "price_threshold"; mint: string; operator: "above" | "below"; priceUsd: number; cooldownMinutes?: number }
+ | { type: "schedule"; cron: string; cooldownMinutes?: number }
+ | { type: "balance_below"; thresholdSol: number; cooldownMinutes?: number }
+ | { type: "tip_received"; minSol?: number; cooldownMinutes?: number }
+ | { type: "launch_matching"; creator?: string; maxMcapUsd?: number; minMcapUsd?: number; cooldownMinutes?: number }
+ | { type: "graduation"; mint?: string; cooldownMinutes?: number }
+ | { type: "whale_buy"; mint: string; minSol: number; cooldownMinutes?: number };
+
+export type AutomationAction =
+ | { type: "agent_prompt"; prompt: string; maxSteps?: number; budgetCreditsUsd?: number }
+ | { type: "swap"; mint?: string; amountSol: number; slippagePct?: number }
+ | { type: "transfer"; destination: string; amountSol: number }
+ | { type: "notify"; message?: string };
+
+export interface CreateAutomationParams {
+ agentId: string;
+ title?: string;
+ trigger: AutomationTrigger;
+ action: AutomationAction;
+ /** Fire once, then disable. */
+ triggerOnce?: boolean;
+ /** Spend ceilings for swap and transfer actions, in USD. */
+ limits?: { perActionUsd?: number; dailyUsd?: number; totalUsd?: number };
+}
+
+export interface Automation {
+ id: string;
+ agentId: string | null;
+ /** `automation` rows are native; wallet intents and alert rules are listed as the same object. */
+ source: "automation" | "wallet_intent" | "alert_rule";
+ title: string | null;
+ trigger: Record<string, unknown> & { type: string };
+ action: Record<string, unknown> & { type: string };
+ triggerOnce: boolean;
+ enabled: boolean;
+ intentId: string | null;
+ stats: {
+ fireCount: number | null;
+ lastFiredAt: string | null;
+ lastCheckedAt: string | null;
+ lastStatus: string | null;
+ lastNote: string | null;
+ };
+ createdAt: string;
+ updatedAt: string | null;
+}
+
+export interface DeletedAutomation {
+ id: string;
+ source: Automation["source"];
+ deleted: true;
+}
+
+// ── skills ──────────────────────────────────────────────────────────────────
+
+export interface BuiltinSkill {
+ id: string;
+ name: string;
+ description: string;
+ /** Core skills are always on; optional skills are toggled per agent. */
+ kind: "core" | "optional";
+ sellable: boolean;
+}
+
+export interface CommunitySkill {
+ slug: string;
+ name: string;
+ description: string;
+ author: string | null;
+ tags: string[];
+ version: string;
+ sha256: string | null;
+ page: string;
+ /** The SKILL.md instructions (getCommunitySkill only). */
+ content?: string;
+}
+
+export interface CommunitySkillSearch {
+ skills: CommunitySkill[];
+ count: number;
+ total: number;
+ tags: string[];
+}
+
+export interface CustomSkill {
+ id: string;
+ agentId: string;
+ slug: string;
+ name: string;
+ description: string;
+ author: string | null;
+ tags: string[];
+ version: string;
+ content: string;
+ source: "custom" | "community";
+ sourceSlug: string | null;
+ sourceVersion: string | null;
+ enabled: boolean;
+ /** Estimated prompt tokens. */
+ tokens: number | null;
+ /** Whether it fits in the prompt budget and is injected. */
+ injected: boolean | null;
+ skipReason: string | null;
+ registry: { slug: string; latestVersion: string | null; updateAvailable: boolean; removed: boolean } | null;
+ installedAt: string;
+ updatedAt: string;
+}
+
+export interface SkillBudget {
+ capTokens: number;
+ usedTokens: number;
+ enabledTokens: number;
+ remainingTokens: number;
+ injectedCount: number;
+ skippedOverBudget: number;
+}
+
+export interface CustomSkillList {
+ skills: CustomSkill[];
+ budget: SkillBudget;
+}
+
+export interface CustomSkillResult {
+ skill: CustomSkill;
+ budget: SkillBudget;
+}
+
+export interface CreateCustomSkillParams {
+ name: string;
+ /** The instructions, as markdown. */
+ content: string;
+ description?: string;
+ slug?: string;
+ tags?: string[];
+ version?: string;
+ enabled?: boolean;
+}
+
+export type UpdateCustomSkillParams = Partial<Omit<CreateCustomSkillParams, "slug">> & {
+ /** Pull the latest registry version of an imported skill. */
+ resync?: true;
+};
+
+// ── wallet ──────────────────────────────────────────────────────────────────
+
+export interface Wallet {
+ agentId: string;
+ chain: "solana";
+ network: Network;
+ address: string | null;
+ lamports: string | null;
+ sol: number | null;
+ /** Whether the platform can sign for this wallet. */
+ signable: boolean | null;
+ depositsEnabled: boolean | null;
+ snsDomain: string | null;
+}
+
+export interface WalletLedgerEntry {
+ id: string;
+ type: string;
+ category: string | null;
+ network: Network;
+ asset: string | null;
+ amountLamports: string | null;
+ amountRaw: string | null;
+ usd: number | null;
+ destination: string | null;
+ signature: string | null;
+ explorer: string | null;
+ status: string;
+ reason: string | null;
+ createdAt: string;
+}
+
+export interface WalletHistoryParams {
+ limit?: number;
+ cursor?: string;
+ network?: Network;
+ /** One spend category, e.g. `withdraw`, `trade`, `x402`. */
+ category?: string;
+}
+
+export interface TransferQuoteParams {
+ destination: string;
+ /** Whole units (SOL, or the token's UI amount), or `"max"`. */
+ amount: number | "max";
+ /** `"SOL"` (default) or an SPL mint. */
+ asset?: string;
+ network?: Network;
+}
+
+export interface TransferQuote {
+ quoteId: string;
+ expiresAt: string;
+ preview: {
+ asset: string;
+ network: Network;
+ destination: string;
+ amount: number;
+ lamports: string | null;
+ amountRaw: string | null;
+ usd: number | null;
+ note: string | null;
+ simulation: { ok: boolean; error: unknown; unitsConsumed: number | null };
+ };
+}
+
+export interface TransferParams {
+ quoteId: string;
+ /** Must be `true`. The client refuses to send without it. */
+ confirm: true;
+}
+
+export interface TransferResult {
+ status: "confirmed" | "submitted";
+ confirmed: boolean;
+ replayed: boolean;
+ signature: string | null;
+ explorer: string | null;
+ asset: string;
+ network: Network;
+ destination: string;
+ amount: number;
+ usd: number | null;
+ newBalanceSol: number | null;
+ newTokenBalance: number | null;
+}
+
+// ── swap ────────────────────────────────────────────────────────────────────
+
+export interface SwapQuoteParams {
+ /** Mint to sell, or `"SOL"`. */
+ inputMint: string;
+ /** Mint to buy, or `"SOL"`. */
+ outputMint: string;
+ /** Input amount in the smallest unit (lamports for SOL), as an integer string. */
+ amount: string;
+ slippageBps?: number;
+ /** Swap from this agent's custodial wallet. Omit for a non-custodial swap. */
+ agentId?: string;
+ /** Your wallet for a non-custodial swap (can also be given to swapExecute). */
+ userPublicKey?: string;
+}
+
+export interface SwapQuote {
+ quoteId: string;
+ expiresAt: string;
+ mode: "custodial" | "non_custodial";
+ agentId: string | null;
+ inputMint: string;
+ outputMint: string;
+ inAmount: string;
+ outAmount: string | null;
+ minOutAmount: string | null;
+ priceImpactPct: number | null;
+ slippageBps: number;
+ venue: string | null;
+ route: string[];
+ usd: number | null;
+ platformFeeBps: number | null;
+ warnings: Array<{ code: string; message: string }>;
+ firewall: unknown;
+}
+
+export interface SwapExecuteParams {
+ quoteId: string;
+ /** Required (`true`) for an agent-wallet swap. */
+ confirm?: boolean;
+ /** Signer for a non-custodial swap, when not given at quote time. */
+ userPublicKey?: string;
+}
+
+export interface UnsignedSwap extends Omit<SwapQuote, "quoteId" | "expiresAt"> {
+ mode: "non_custodial";
+ status: "unsigned";
+ /** Base64 VersionedTransaction. Deserialize, sign with `signer`, send. */
+ transaction: string;
+ encoding: "base64";
+ signer: string;
+}
+
+export interface CustodialSwap extends Omit<SwapQuote, "quoteId" | "expiresAt"> {
+ mode: "custodial";
+ status: "confirmed";
+ replayed: boolean;
+ signature: string | null;
+ explorer: string | null;
+ newBalanceSol: number | null;
+}
+
+export type SwapResult = UnsignedSwap | CustodialSwap;
+
+// ── catalog, intel and account ──────────────────────────────────────────────
+
+/** Loosely typed server objects whose full shape is documented in docs/api-reference.md. */
+export type Json = Record<string, unknown>;
+
+export interface TopMoversParams {
+ timeframe?: string;
+ sortBy?: string;
+ minLiquidity?: number;
+ limit?: number;
+}
+
+export interface IndicatorsParams {
+ mint: string;
+ /** Any of `rsi`, `ema`, `sma`, `macd`. */
+ indicators?: Array<"rsi" | "ema" | "sma" | "macd"> | string;
+ interval?: string;
+}
+
+export interface IntegrationParams {
+ [key: string]: unknown;
+}
+
+export interface LinkCodeParams {
+ /** Pair the code to one agent. */
+ agentId?: string;
+ /** A label for the device or gateway, shown in your account. */
+ label?: string;
+ /** Space-separated scopes the paired device receives. */
+ scopes?: string;
+}
+
+export interface ExternalWalletParams {
+ /** Solana address withdrawals may be sent to. */
+ address: string;
+ /** Must be `true`: this changes where funds can leave to. */
+ confirm: true;
+}