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(chat): ship a server-side agent loop as a built-in chat model

nirholasc97354721b27
diff --git a/api/_lib/agent-tools.js b/api/_lib/agent-tools.js
new file mode 100644
index 000000000..65da9d0a0
--- /dev/null
+++ b/api/_lib/agent-tools.js
@@ -0,0 +1,203 @@
+// api/_lib/agent-tools.js - the server-executable tool registry for the
+// general agent loop (/api/agent/run).
+//
+// Every tool here is READ-ONLY and runs entirely server-side over surfaces the
+// platform already operates: CoinGecko through the cached geckoFetch lane,
+// public Solana RPC through the failover connection, the trade firewall, the
+// smart-money index, and SNS resolution. Nothing signs, sends, or mutates;
+// fund-moving actions live client-side behind the wallet-approval modal and
+// the /api/agent/guard preflight, and are deliberately NOT represented here.
+//
+// Shape: `name` and OpenAI function-calling `parameters` feed the model;
+// `handler(args)` returns a JSON-serializable result. Handlers throw on bad
+// input; the loop feeds the error back to the model as a tool error result.
+
+import { geckoFetch } from './coingecko.js';
+import { solanaPublicConnection } from './agent-pumpfun.js';
+import { assessTradeSafety } from './trade-firewall.js';
+import { getSmartMoneyForMint } from './smart-money.js';
+import { resolveSnsName } from '../../src/solana/sns.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// The round-trip probe size the firewall simulates a buy+sell with when the
+// caller has no live quote: 0.1 SOL, small enough to be simulable and large
+// enough that a honeypot's sell trap shows.
+const SAFETY_PROBE_LAMPORTS = 100_000_000;
+
+function str(v, max = 200) {
+ return typeof v === 'string' ? v.trim().slice(0, max) : '';
+}
+
+export const AGENT_TOOLS = {
+ web_search: {
+ description:
+ 'Search the web (DuckDuckGo instant answers). Returns an abstract and related topics. Use for general knowledge and current context; use the token tools for anything crypto-specific.',
+ parameters: {
+ type: 'object',
+ properties: { query: { type: 'string', description: 'Search query' } },
+ required: ['query'],
+ },
+ async handler(args) {
+ const query = str(args?.query, 400);
+ if (!query) throw new Error('query is required');
+ const res = await fetch(
+ `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1`,
+ { signal: AbortSignal.timeout(8000) },
+ );
+ if (!res.ok) throw new Error(`search upstream ${res.status}`);
+ const d = await res.json();
+ return {
+ abstract: d.AbstractText || '',
+ source: d.AbstractURL || '',
+ topics: (d.RelatedTopics || [])
+ .map((t) => t.Text)
+ .filter(Boolean)
+ .slice(0, 5),
+ };
+ },
+ },
+
+ token_price: {
+ description:
+ 'Live USD price, 24h change, and market cap for a crypto asset by name, symbol, or CoinGecko id (e.g. "solana", "SOL", "bitcoin").',
+ parameters: {
+ type: 'object',
+ properties: { query: { type: 'string', description: 'Coin name, symbol, or CoinGecko id' } },
+ required: ['query'],
+ },
+ async handler(args) {
+ const query = str(args?.query, 100);
+ if (!query) throw new Error('query is required');
+ const search = await geckoFetch(`/search?query=${encodeURIComponent(query)}`);
+ const coin = search?.coins?.[0];
+ if (!coin?.id) return { found: false, query };
+ const prices = await geckoFetch(
+ `/simple/price?ids=${encodeURIComponent(coin.id)}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true`,
+ );
+ const row = prices?.[coin.id] || {};
+ return {
+ found: true,
+ id: coin.id,
+ name: coin.name,
+ symbol: coin.symbol,
+ priceUsd: row.usd ?? null,
+ change24hPct: row.usd_24h_change ?? null,
+ marketCapUsd: row.usd_market_cap ?? null,
+ };
+ },
+ },
+
+ trending_tokens: {
+ description: 'The crypto assets trending on CoinGecko right now (top searched, with rank and price in BTC).',
+ parameters: { type: 'object', properties: {} },
+ async handler() {
+ const data = await geckoFetch('/search/trending');
+ return {
+ trending: (data?.coins || []).slice(0, 10).map(({ item }) => ({
+ id: item?.id,
+ name: item?.name,
+ symbol: item?.symbol,
+ marketCapRank: item?.market_cap_rank ?? null,
+ priceBtc: item?.price_btc ?? null,
+ })),
+ };
+ },
+ },
+
+ sol_balance: {
+ description: 'Native SOL balance of a Solana wallet address (mainnet).',
+ parameters: {
+ type: 'object',
+ properties: { address: { type: 'string', description: 'Base58 Solana wallet address' } },
+ required: ['address'],
+ },
+ async handler(args) {
+ const address = str(args?.address, 60);
+ if (!BASE58_RE.test(address)) throw new Error('address must be a base58 Solana address');
+ const { PublicKey } = await import('@solana/web3.js');
+ const lamports = await solanaPublicConnection('mainnet').getBalance(
+ new PublicKey(address),
+ 'confirmed',
+ );
+ return { address, lamports, sol: lamports / LAMPORTS_PER_SOL };
+ },
+ },
+
+ token_safety: {
+ description:
+ 'Rug/honeypot safety verdict for a Solana token mint from the three.ws trade firewall: allow/warn/block with per-check reasons. Simulates a small buy+sell round trip where possible.',
+ parameters: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string', description: 'Base58 token mint address' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], description: 'Default: mainnet' },
+ },
+ required: ['mint'],
+ },
+ async handler(args) {
+ const mint = str(args?.mint, 60);
+ if (!BASE58_RE.test(mint)) throw new Error('mint must be a base58 Solana address');
+ const out = await assessTradeSafety({
+ mint,
+ network: args?.network === 'devnet' ? 'devnet' : 'mainnet',
+ side: 'buy',
+ quoteAmount: SAFETY_PROBE_LAMPORTS,
+ });
+ return {
+ mint,
+ verdict: out.verdict,
+ score: out.score,
+ simulated: out.simulated,
+ reasons: out.reasons,
+ };
+ },
+ },
+
+ smart_money: {
+ description:
+ 'Smart-money activity on a Solana token mint: how many tracked profitable wallets hold or recently traded it.',
+ parameters: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string', description: 'Base58 token mint address' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], description: 'Default: mainnet' },
+ },
+ required: ['mint'],
+ },
+ async handler(args) {
+ const mint = str(args?.mint, 60);
+ if (!BASE58_RE.test(mint)) throw new Error('mint must be a base58 Solana address');
+ return getSmartMoneyForMint(mint, args?.network === 'devnet' ? 'devnet' : 'mainnet');
+ },
+ },
+
+ resolve_sol_name: {
+ description: 'Resolve a .sol name (SNS) to its owner wallet address.',
+ parameters: {
+ type: 'object',
+ properties: { name: { type: 'string', description: 'SNS name, e.g. "toly.sol"' } },
+ required: ['name'],
+ },
+ async handler(args) {
+ const name = str(args?.name, 100);
+ if (!name) throw new Error('name is required');
+ const address = await resolveSnsName(name);
+ return { name, address: address || null, resolved: Boolean(address) };
+ },
+ },
+};
+
+/** OpenAI function-calling schema array for the whole registry. */
+export function agentToolSchemas() {
+ return Object.entries(AGENT_TOOLS).map(([name, t]) => ({
+ type: 'function',
+ function: { name, description: t.description, parameters: t.parameters },
+ }));
+}
+
+/** Handler map in the shape @three-ws/agent-runtime's call_tool executor expects. */
+export function agentToolHandlers() {
+ return Object.fromEntries(Object.entries(AGENT_TOOLS).map(([name, t]) => [name, t.handler]));
+}
diff --git a/api/_lib/llm-tool-chain.js b/api/_lib/llm-tool-chain.js
new file mode 100644
index 000000000..fe80c3288
--- /dev/null
+++ b/api/_lib/llm-tool-chain.js
@@ -0,0 +1,142 @@
+// api/_lib/llm-tool-chain.js: the OpenAI-wire tool-calling LLM chain.
+//
+// Extracted verbatim from api/agents/copilot.js (where it was proven in
+// production on the trading copilot) so every server-side tool loop: the
+// copilot, the general agent loop at /api/agent/run: runs on the same lanes
+// with the same failover semantics. Free platform keys lead, the paid OpenAI
+// key is a backstop, and the credits-funded Vertex Gemini anchor is ALWAYS the
+// final rung when the GCP project is set. Every provider speaks the OpenAI
+// chat-completions wire format (tools + streamed tool_calls), so one reader
+// handles them all.
+
+import { env } from './env.js';
+import {
+ vertexGeminiAvailable,
+ vertexGeminiModel,
+ vertexGeminiChatUrl,
+ vertexGeminiHeaders,
+} from './vertex-gemini.js';
+
+// ── provider chain (free-first, OpenAI-compatible tool-calling + streaming) ────
+// Mirrors the platform policy in api/_lib/llm.js: free platform keys lead, the
+// paid OpenAI key is appended last as a backstop. Every provider here speaks the
+// OpenAI chat-completions wire format (tools + streamed tool_calls), so one
+// reader handles them all. Anthropic is intentionally omitted from the tool loop
+//: the free OpenAI-compatible lanes are the primary path and OpenAI is the paid
+// tail; nothing here depends on a paid key existing. The credits-funded Vertex
+// Gemini anchor is ALWAYS the final rung when the GCP project is set (api/chat.js
+// semantics): the prod OPENAI_API_KEY is billing-dead, so without the anchor a
+// simultaneous free-lane throttle 5xx'd the copilot. Exported for the anchor
+// regression tests.
+export function providerChain() {
+ const chain = [];
+ if (env.GROQ_API_KEY) {
+ chain.push({ name: 'groq', url: 'https://api.groq.com/openai/v1/chat/completions', key: env.GROQ_API_KEY, model: 'llama-3.3-70b-versatile' });
+ }
+ const orKeys = [...new Set([env.OPENROUTER_API_KEY, ...(env.OPENROUTER_FALLBACK_KEYS || [])].filter(Boolean))];
+ orKeys.forEach((key, i) => {
+ chain.push({
+ name: i === 0 ? 'openrouter' : `openrouter#${i + 1}`,
+ url: 'https://openrouter.ai/api/v1/chat/completions',
+ key,
+ model: i === 0 ? 'meta-llama/llama-3.3-70b-instruct' : 'meta-llama/llama-3.3-70b-instruct:free',
+ extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws' },
+ });
+ });
+ if (env.NVIDIA_API_KEY) {
+ chain.push({ name: 'nvidia', url: 'https://integrate.api.nvidia.com/v1/chat/completions', key: env.NVIDIA_API_KEY, model: 'meta/llama-3.3-70b-instruct' });
+ }
+ // Three more free lanes, same OpenAI wire format including tools + streamed
+ // tool_calls: SambaNova (Llama 3.3 70B, own quota pool), Mistral (Experiment
+ // tier, about 1B free tokens/month), and Z.AI's free GLM Flash lane.
+ if (env.SAMBANOVA_API_KEY) {
+ chain.push({ name: 'sambanova', url: 'https://api.sambanova.ai/v1/chat/completions', key: env.SAMBANOVA_API_KEY, model: 'Meta-Llama-3.3-70B-Instruct' });
+ }
+ if (env.MISTRAL_API_KEY) {
+ chain.push({ name: 'mistral', url: 'https://api.mistral.ai/v1/chat/completions', key: env.MISTRAL_API_KEY, model: 'mistral-small-latest' });
+ }
+ if (env.ZAI_API_KEY) {
+ chain.push({ name: 'zai', url: 'https://api.z.ai/api/paas/v4/chat/completions', key: env.ZAI_API_KEY, model: 'glm-4.7-flash' });
+ }
+ if (env.OPENAI_API_KEY) {
+ chain.push({ name: 'openai', url: 'https://api.openai.com/v1/chat/completions', key: env.OPENAI_API_KEY, model: 'gpt-5.4-nano' });
+ }
+ // Vertex Gemini credits anchor: keyless (GCP OAuth token minted per request
+ // via getHeaders; see api/_lib/vertex-gemini.js), OpenAI-compatible including
+ // tools + streamed tool_calls, billed to platform credits. Appended at the
+ // tail unconditionally when available so no present provider key can evict it.
+ if (vertexGeminiAvailable()) {
+ chain.push({
+ name: 'vertex-gemini',
+ url: vertexGeminiChatUrl(),
+ key: null,
+ model: vertexGeminiModel(),
+ getHeaders: vertexGeminiHeaders,
+ });
+ }
+ return chain;
+}
+
+// Stream one chat-completion round. Emits assistant content deltas via
+// onContent; accumulates streamed tool_calls. Resolves { content, toolCalls }.
+// Throws on transport / non-2xx so the caller can fail over to the next provider.
+export async function streamRound(provider, { messages, tools, onContent }) {
+ const body = {
+ model: provider.model,
+ max_tokens: 1024,
+ temperature: 0.4,
+ stream: true,
+ messages,
+ };
+ if (Array.isArray(tools) && tools.length) { body.tools = tools; body.tool_choice = 'auto'; }
+ // Keyless lanes (the Vertex Gemini credits anchor) mint their auth per request
+ // via getHeaders; a token-exchange failure throws here and fails over to the
+ // next provider exactly like a transport error.
+ const headers = provider.getHeaders
+ ? { ...(await provider.getHeaders()), ...(provider.extraHeaders || {}) }
+ : { 'content-type': 'application/json', authorization: `Bearer ${provider.key}`, ...(provider.extraHeaders || {}) };
+ const resp = await fetch(provider.url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(45_000),
+ });
+ if (!resp.ok || !resp.body) {
+ const detail = await resp.text().catch(() => '');
+ throw Object.assign(new Error(`${provider.name} ${resp.status}: ${detail.slice(0, 180)}`), { status: 502 });
+ }
+ const reader = resp.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let content = '';
+ const toolCalls = []; // index → { id, name, args }
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let nl;
+ while ((nl = buf.indexOf('\n')) >= 0) {
+ const line = buf.slice(0, nl).trim();
+ buf = buf.slice(nl + 1);
+ if (!line.startsWith('data:')) continue;
+ const payload = line.slice(5).trim();
+ if (payload === '[DONE]') { buf = ''; break; }
+ let evt;
+ try { evt = JSON.parse(payload); } catch { continue; }
+ const delta = evt.choices?.[0]?.delta;
+ if (!delta) continue;
+ if (delta.content) { content += delta.content; onContent?.(delta.content); }
+ if (Array.isArray(delta.tool_calls)) {
+ for (const tc of delta.tool_calls) {
+ const idx = tc.index ?? 0;
+ if (!toolCalls[idx]) toolCalls[idx] = { id: tc.id || `call_${idx}`, name: '', args: '' };
+ if (tc.id) toolCalls[idx].id = tc.id;
+ if (tc.function?.name) toolCalls[idx].name = tc.function.name;
+ if (tc.function?.arguments) toolCalls[idx].args += tc.function.arguments;
+ }
+ }
+ }
+ }
+ return { content, toolCalls: toolCalls.filter(Boolean) };
+}
+
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 01250b457..f77d0bcbe 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -508,6 +508,12 @@ export const limits = {
// chat session stays far under 300 evaluations per 5 minutes.
agentGuardIp: (ip) =>
getLimiter('agent:guard:ip', { limit: 300, window: '5 m', local: true }).limit(ip),
+ // The server-side agent loop (/api/agent/run). One request can fan into
+ // several LLM rounds plus tool executions against shared free-lane quotas,
+ // so it gets a tighter ceiling than the plain chat proxy: 30 runs per 5
+ // minutes per IP is an active conversation, not a drain.
+ agentRunIp: (ip) =>
+ getLimiter('agent:run:ip', { limit: 30, window: '5 m', local: true }).limit(ip),
// Auth buckets gate credential guessing / account-creation spam. They are
// sensitive (critical) but use degradeToMemory: on a Redis outage they fall
// back to the per-instance memory limiter rather than failing closed. Failing
diff --git a/api/agent/run.js b/api/agent/run.js
new file mode 100644
index 000000000..9fbf5e5f5
--- /dev/null
+++ b/api/agent/run.js
@@ -0,0 +1,301 @@
+// POST /api/agent/run - the general server-side agent loop.
+//
+// Speaks the OpenAI chat-completions wire format both ways: the request body
+// is `{ messages, stream }` exactly as a chat client would send to any
+// OpenAI-compatible provider, and the response is either a standard
+// chat.completion JSON or an SSE stream of chat.completion.chunk deltas. That
+// makes the loop a drop-in "model" for the chat client's Built-in lane
+// (model id `three-ws/agent`), with zero client-side protocol work.
+//
+// Inside one request, @three-ws/agent-runtime's AgentRuntime drives the loop:
+// call the LLM over the shared tool-calling chain (api/_lib/llm-tool-chain.js,
+// free lanes first, Vertex credits anchor last), execute any requested tools
+// server-side from the READ-ONLY registry (api/_lib/agent-tools.js: web
+// search, token prices, trending, SOL balances, the trade-firewall safety
+// verdict, smart money, SNS), feed results back, repeat, then stream the
+// final answer. Every planned tool call is preflighted through the GuardChain
+// in headless mode first; a blacklisted call is returned to the model as a
+// blocked-tool error, never executed. No tool here can sign, send, or mutate;
+// fund-moving tools live client-side behind the wallet modal and
+// /api/agent/guard.
+//
+// Tool activity is surfaced as SSE comment lines (`: tool web_search …`),
+// which every OpenAI SSE parser ignores by spec, so observability rides along
+// without breaking any client.
+
+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { providerChain, streamRound } from '../_lib/llm-tool-chain.js';
+import { agentToolSchemas, agentToolHandlers } from '../_lib/agent-tools.js';
+import { AgentRuntime, GuardChain, TradeGuard } from '@three-ws/agent-runtime';
+
+export const AGENT_MODEL_ID = 'three-ws/agent';
+
+const MAX_TOOL_ROUNDS = 4;
+const MAX_MESSAGES = 40;
+const MAX_BODY_BYTES = 512_000;
+
+const guardChain = new GuardChain({ defiGuard: new TradeGuard() });
+
+const SYSTEM_NOTE = [
+ 'You have server-side tools: live token prices and trends, web search, Solana balances, a rug/honeypot safety verdict, smart-money activity, and .sol name resolution.',
+ 'Use them instead of guessing; never invent prices, balances, or safety verdicts. If a tool returns no data, say so plainly.',
+ 'You cannot move funds: no tool here transfers, swaps, or signs anything.',
+].join(' ');
+
+function sanitizeMessages(raw) {
+ if (!Array.isArray(raw)) return null;
+ const out = [];
+ for (const m of raw.slice(-MAX_MESSAGES)) {
+ if (!m || typeof m !== 'object') continue;
+ const role = ['system', 'user', 'assistant'].includes(m.role) ? m.role : null;
+ if (!role) continue;
+ const content =
+ typeof m.content === 'string'
+ ? m.content
+ : Array.isArray(m.content)
+ ? m.content
+ .map((p) => (typeof p?.text === 'string' ? p.text : ''))
+ .join('\n')
+ .trim()
+ : '';
+ out.push({ role, content });
+ }
+ return out.length ? out : null;
+}
+
+/** OpenAI chat.completion.chunk SSE frame. */
+function chunkFrame(id, delta, finishReason = null) {
+ return `data: ${JSON.stringify({
+ id,
+ object: 'chat.completion.chunk',
+ created: Math.floor(Date.now() / 1000),
+ model: AGENT_MODEL_ID,
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
+ })}\n\n`;
+}
+
+/**
+ * Run one full agent completion over `body.messages` and answer in OpenAI
+ * format (SSE when body.stream, JSON otherwise). Shared by POST /api/agent/run
+ * and the chat proxy's `three-ws/agent` model branch; `opts.rateLimited` skips
+ * the limiter when the caller already applied its own.
+ */
+export async function runAgentCompletion(req, res, body, opts = {}) {
+ if (!opts.rateLimited) {
+ const rl = await limits.agentRunIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ }
+
+ const chain = providerChain();
+ if (!chain.length) {
+ return error(res, 503, 'llm_unavailable', 'No LLM provider is configured for the agent loop.');
+ }
+
+ const messages = sanitizeMessages(body?.messages);
+ if (!messages) return error(res, 400, 'bad_messages', 'Provide `messages: [{ role, content }]`.');
+
+ // The server note rides as a second system message so a client-authored
+ // persona keeps the first slot.
+ const sysIdx = messages[0]?.role === 'system' ? 1 : 0;
+ messages.splice(sysIdx, 0, { role: 'system', content: SYSTEM_NOTE });
+
+ const stream = body?.stream !== false;
+ const completionId = `agentrun-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
+
+ let sseOpen = false;
+ const sse = (text) => {
+ if (!sseOpen) {
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('x-accel-buffering', 'no');
+ res.write(chunkFrame(completionId, { role: 'assistant' }));
+ sseOpen = true;
+ }
+ res.write(text);
+ };
+
+ const toolSchemas = agentToolSchemas();
+ const toolHandlers = agentToolHandlers();
+ let streamedAny = false;
+ let finalContent = '';
+
+ // The model runtime the loop's built-in call_llm executor consumes: one
+ // round over the provider chain, failing over BEFORE any byte streams and
+ // aborting (not retrying) after a mid-stream death so the client never sees
+ // the same sentence twice.
+ async function* modelRuntime(payload) {
+ let lastErr = null;
+ for (const provider of chain) {
+ let emittedHere = false;
+ try {
+ const out = await streamRound(provider, {
+ messages: payload.messages,
+ tools: toolSchemas,
+ onContent: (delta) => {
+ emittedHere = true;
+ streamedAny = true;
+ if (stream) sse(chunkFrame(completionId, { content: delta }));
+ },
+ });
+ yield {
+ content: out.content,
+ tool_calls: out.toolCalls.map((tc) => ({
+ id: tc.id,
+ type: 'function',
+ function: { name: tc.name, arguments: tc.args || '{}' },
+ })),
+ };
+ return;
+ } catch (err) {
+ lastErr = err;
+ if (emittedHere) throw err;
+ }
+ }
+ throw lastErr || new Error('No LLM provider available');
+ }
+
+ // The "brain": plan from the phase the runtime reports. Tool rounds are
+ // bounded; past the budget the model is asked to answer with what it has.
+ const runner = async (context, state) => {
+ switch (context.phase) {
+ case 'init':
+ case 'user_input':
+ return { type: 'call_llm', payload: { messages: state.messages } };
+
+ case 'llm_result': {
+ const { result, toolCalls } = context.payload || {};
+ const content = result?.content || '';
+ const roundsUsed = state.messages.filter((m) => m.role === 'assistant' && m.tool_calls).length;
+
+ if (Array.isArray(toolCalls) && toolCalls.length > 0 && roundsUsed < MAX_TOOL_ROUNDS) {
+ state.messages.push({ role: 'assistant', content: content || null, tool_calls: toolCalls });
+
+ const allowed = [];
+ for (const tc of toolCalls) {
+ const name = tc.function?.name || '';
+ let args = {};
+ try {
+ args = JSON.parse(tc.function?.arguments || '{}');
+ } catch {
+ args = {};
+ }
+ if (!toolHandlers[name]) {
+ state.messages.push({
+ role: 'tool',
+ tool_call_id: tc.id,
+ content: JSON.stringify({ error: `Unknown tool: ${name}` }),
+ });
+ continue;
+ }
+ const verdict = await guardChain.evaluate({
+ identifier: name,
+ apiName: name,
+ arguments: args,
+ approvalMode: 'headless',
+ });
+ if (verdict.decision === 'block') {
+ state.messages.push({
+ role: 'tool',
+ tool_call_id: tc.id,
+ content: JSON.stringify({ blocked: true, error: verdict.reason }),
+ });
+ continue;
+ }
+ if (stream) sse(`: tool ${name}\n\n`);
+ allowed.push(tc);
+ }
+
+ if (allowed.length > 0) return { type: 'call_tools_batch', payload: allowed };
+ // Everything was blocked or unknown: let the model read the errors.
+ return { type: 'call_llm', payload: { messages: state.messages } };
+ }
+
+ finalContent = content;
+ state.messages.push({ role: 'assistant', content });
+ return { type: 'finish', reason: 'completed' };
+ }
+
+ case 'tool_result':
+ case 'tools_batch_result':
+ return { type: 'call_llm', payload: { messages: state.messages } };
+
+ case 'error':
+ return { type: 'finish', reason: 'error_recovery' };
+
+ default:
+ return { type: 'finish', reason: 'agent_decision' };
+ }
+ };
+
+ const agent = { runner, modelRuntime, tools: toolHandlers };
+ const runtime = new AgentRuntime(agent);
+ let state = AgentRuntime.createInitialState({
+ operationId: completionId,
+ maxSteps: MAX_TOOL_ROUNDS * 2 + 3,
+ });
+ state.messages = messages;
+
+ let context;
+ try {
+ while (state.status !== 'done' && state.status !== 'error') {
+ const step = await runtime.step(state, context);
+ state = step.newState;
+ context = step.nextContext;
+ if (!context && state.status !== 'done' && state.status !== 'error') break;
+ }
+ } catch (err) {
+ if (sseOpen) {
+ sse(`: error ${String(err?.message || err).slice(0, 200)}\n\n`);
+ sse(chunkFrame(completionId, {}, 'stop'));
+ sse('data: [DONE]\n\n');
+ return res.end();
+ }
+ return error(res, 502, 'agent_loop_failed', String(err?.message || err).slice(0, 300));
+ }
+
+ if (state.status === 'error') {
+ const detail = String(state.error?.message || state.error || 'agent loop error').slice(0, 300);
+ if (sseOpen) {
+ sse(`: error ${detail}\n\n`);
+ sse(chunkFrame(completionId, {}, 'stop'));
+ sse('data: [DONE]\n\n');
+ return res.end();
+ }
+ return error(res, 502, 'agent_loop_failed', detail);
+ }
+
+ if (stream) {
+ // A run whose final round emitted no deltas (e.g. everything came from a
+ // non-streaming provider quirk) still owes the client the content.
+ if (!streamedAny && finalContent) sse(chunkFrame(completionId, { content: finalContent }));
+ sse(chunkFrame(completionId, {}, 'stop'));
+ sse('data: [DONE]\n\n');
+ return res.end();
+ }
+
+ return json(res, 200, {
+ id: completionId,
+ object: 'chat.completion',
+ created: Math.floor(Date.now() / 1000),
+ model: AGENT_MODEL_ID,
+ choices: [
+ { index: 0, message: { role: 'assistant', content: finalContent }, finish_reason: 'stop' },
+ ],
+ });
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'POST, OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ let body;
+ try {
+ body = await readJson(req, MAX_BODY_BYTES);
+ } catch (err) {
+ return error(res, err?.status || 400, 'bad_json', err?.message || 'Body must be JSON.');
+ }
+
+ return runAgentCompletion(req, res, body);
+});
diff --git a/api/agents/copilot.js b/api/agents/copilot.js
index f14bf711c..dfe6b9ab3 100644
--- a/api/agents/copilot.js
+++ b/api/agents/copilot.js
@@ -26,19 +26,14 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { sql } from '../_lib/db.js';
import { cors, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
-import { env } from '../_lib/env.js';
import { PublicKey } from '@solana/web3.js';
import { solanaPublicConnection } from '../_lib/agent-pumpfun.js';
import { quoteTrade } from './solana-trade.js';
import { assessTradeSafety } from '../_lib/trade-firewall.js';
import { getSmartMoneyForMint } from '../_lib/smart-money.js';
import { getTradeLimits } from '../_lib/agent-trade-guards.js';
-import {
- vertexGeminiAvailable,
- vertexGeminiModel,
- vertexGeminiChatUrl,
- vertexGeminiHeaders,
-} from '../_lib/vertex-gemini.js';
+import { providerChain, streamRound } from '../_lib/llm-tool-chain.js';
+export { providerChain };
const NETWORKS = new Set(['mainnet', 'devnet']);
const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');
@@ -56,129 +51,11 @@ async function resolveAuth(req) {
return null;
}
-// ── provider chain (free-first, OpenAI-compatible tool-calling + streaming) ────
-// Mirrors the platform policy in api/_lib/llm.js: free platform keys lead, the
-// paid OpenAI key is appended last as a backstop. Every provider here speaks the
-// OpenAI chat-completions wire format (tools + streamed tool_calls), so one
-// reader handles them all. Anthropic is intentionally omitted from the tool loop
-// — the free OpenAI-compatible lanes are the primary path and OpenAI is the paid
-// tail; nothing here depends on a paid key existing. The credits-funded Vertex
-// Gemini anchor is ALWAYS the final rung when the GCP project is set (api/chat.js
-// semantics): the prod OPENAI_API_KEY is billing-dead, so without the anchor a
-// simultaneous free-lane throttle 5xx'd the copilot. Exported for the anchor
-// regression tests.
-export function providerChain() {
- const chain = [];
- if (env.GROQ_API_KEY) {
- chain.push({ name: 'groq', url: 'https://api.groq.com/openai/v1/chat/completions', key: env.GROQ_API_KEY, model: 'llama-3.3-70b-versatile' });
- }
- const orKeys = [...new Set([env.OPENROUTER_API_KEY, ...(env.OPENROUTER_FALLBACK_KEYS || [])].filter(Boolean))];
- orKeys.forEach((key, i) => {
- chain.push({
- name: i === 0 ? 'openrouter' : `openrouter#${i + 1}`,
- url: 'https://openrouter.ai/api/v1/chat/completions',
- key,
- model: i === 0 ? 'meta-llama/llama-3.3-70b-instruct' : 'meta-llama/llama-3.3-70b-instruct:free',
- extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws copilot' },
- });
- });
- if (env.NVIDIA_API_KEY) {
- chain.push({ name: 'nvidia', url: 'https://integrate.api.nvidia.com/v1/chat/completions', key: env.NVIDIA_API_KEY, model: 'meta/llama-3.3-70b-instruct' });
- }
- // Three more free lanes, same OpenAI wire format including tools + streamed
- // tool_calls: SambaNova (Llama 3.3 70B, own quota pool), Mistral (Experiment
- // tier, about 1B free tokens/month), and Z.AI's free GLM Flash lane.
- if (env.SAMBANOVA_API_KEY) {
- chain.push({ name: 'sambanova', url: 'https://api.sambanova.ai/v1/chat/completions', key: env.SAMBANOVA_API_KEY, model: 'Meta-Llama-3.3-70B-Instruct' });
- }
- if (env.MISTRAL_API_KEY) {
- chain.push({ name: 'mistral', url: 'https://api.mistral.ai/v1/chat/completions', key: env.MISTRAL_API_KEY, model: 'mistral-small-latest' });
- }
- if (env.ZAI_API_KEY) {
- chain.push({ name: 'zai', url: 'https://api.z.ai/api/paas/v4/chat/completions', key: env.ZAI_API_KEY, model: 'glm-4.7-flash' });
- }
- if (env.OPENAI_API_KEY) {
- chain.push({ name: 'openai', url: 'https://api.openai.com/v1/chat/completions', key: env.OPENAI_API_KEY, model: 'gpt-5.4-nano' });
- }
- // Vertex Gemini credits anchor: keyless (GCP OAuth token minted per request
- // via getHeaders; see api/_lib/vertex-gemini.js), OpenAI-compatible including
- // tools + streamed tool_calls, billed to platform credits. Appended at the
- // tail unconditionally when available so no present provider key can evict it.
- if (vertexGeminiAvailable()) {
- chain.push({
- name: 'vertex-gemini',
- url: vertexGeminiChatUrl(),
- key: null,
- model: vertexGeminiModel(),
- getHeaders: vertexGeminiHeaders,
- });
- }
- return chain;
-}
-
-// Stream one chat-completion round. Emits assistant content deltas via
-// onContent; accumulates streamed tool_calls. Resolves { content, toolCalls }.
-// Throws on transport / non-2xx so the caller can fail over to the next provider.
-async function streamRound(provider, { messages, tools, onContent }) {
- const body = {
- model: provider.model,
- max_tokens: 1024,
- temperature: 0.4,
- stream: true,
- messages,
- };
- if (Array.isArray(tools) && tools.length) { body.tools = tools; body.tool_choice = 'auto'; }
- // Keyless lanes (the Vertex Gemini credits anchor) mint their auth per request
- // via getHeaders; a token-exchange failure throws here and fails over to the
- // next provider exactly like a transport error.
- const headers = provider.getHeaders
- ? { ...(await provider.getHeaders()), ...(provider.extraHeaders || {}) }
- : { 'content-type': 'application/json', authorization: `Bearer ${provider.key}`, ...(provider.extraHeaders || {}) };
- const resp = await fetch(provider.url, {
- method: 'POST',
- headers,
- body: JSON.stringify(body),
- signal: AbortSignal.timeout(45_000),
- });
- if (!resp.ok || !resp.body) {
- const detail = await resp.text().catch(() => '');
- throw Object.assign(new Error(`${provider.name} ${resp.status}: ${detail.slice(0, 180)}`), { status: 502 });
- }
- const reader = resp.body.getReader();
- const decoder = new TextDecoder();
- let buf = '';
- let content = '';
- const toolCalls = []; // index → { id, name, args }
- for (;;) {
- const { value, done } = await reader.read();
- if (done) break;
- buf += decoder.decode(value, { stream: true });
- let nl;
- while ((nl = buf.indexOf('\n')) >= 0) {
- const line = buf.slice(0, nl).trim();
- buf = buf.slice(nl + 1);
- if (!line.startsWith('data:')) continue;
- const payload = line.slice(5).trim();
- if (payload === '[DONE]') { buf = ''; break; }
- let evt;
- try { evt = JSON.parse(payload); } catch { continue; }
- const delta = evt.choices?.[0]?.delta;
- if (!delta) continue;
- if (delta.content) { content += delta.content; onContent?.(delta.content); }
- if (Array.isArray(delta.tool_calls)) {
- for (const tc of delta.tool_calls) {
- const idx = tc.index ?? 0;
- if (!toolCalls[idx]) toolCalls[idx] = { id: tc.id || `call_${idx}`, name: '', args: '' };
- if (tc.id) toolCalls[idx].id = tc.id;
- if (tc.function?.name) toolCalls[idx].name = tc.function.name;
- if (tc.function?.arguments) toolCalls[idx].args += tc.function.arguments;
- }
- }
- }
- }
- return { content, toolCalls: toolCalls.filter(Boolean) };
-}
-
+// ── LLM chain: shared tool-calling chain + stream reader ─────────────────────
+// providerChain() and streamRound() were born here and now live in
+// api/_lib/llm-tool-chain.js so the general agent loop (/api/agent/run) runs
+// on the same lanes. providerChain is re-exported unchanged for the anchor
+// regression tests and any existing importer.
// ── tool schema (OpenAI function-calling format) ───────────────────────────────
const TOOLS = [
{
diff --git a/api/chat/models.js b/api/chat/models.js
index 09fb3f12a..0f51e1bba 100644
--- a/api/chat/models.js
+++ b/api/chat/models.js
@@ -1,5 +1,6 @@
import { cors, json, method, wrap } from '../_lib/http.js';
import { listFreeModels } from '../_lib/openrouter-free.js';
+import { AGENT_MODEL_ID } from '../agent/run.js';
// The live free-model list (fetch, cache, ranking) lives in _lib/openrouter-free.js
// so this endpoint and the completion proxy agree on what is actually serving —
@@ -11,6 +12,13 @@ export default wrap(async (req, res) => {
// Ranked best-first, so a client can take data[0] as the default without
// knowing anything about which ids exist today.
const models = await listFreeModels();
+ // The server-side agent loop rides the same picker as a virtual model. It is
+ // appended, never first, so it can never become the silent default: it runs
+ // multiple LLM rounds per message and answers slower than a plain model.
+ models.push({
+ id: AGENT_MODEL_ID,
+ name: 'three.ws Agent · server tools',
+ });
res.setHeader('cache-control', 'public, max-age=60');
return json(res, 200, { data: models });
});
diff --git a/api/chat/proxy.js b/api/chat/proxy.js
index b6c89cd41..66b2b5369 100644
--- a/api/chat/proxy.js
+++ b/api/chat/proxy.js
@@ -2,6 +2,7 @@ import { env } from '../_lib/env.js';
import { cors, error, json, method, wrap, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { isFreeModelId, isLiveFreeModel, pickDefaultFreeModel } from '../_lib/openrouter-free.js';
+import { AGENT_MODEL_ID, runAgentCompletion } from '../agent/run.js';
const UPGRADE_URL = `${env.APP_ORIGIN}/pricing`;
@@ -23,9 +24,6 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
- if (!env.OPENROUTER_API_KEY && !env.OPENROUTER_FALLBACK_KEYS.length)
- return error(res, 503, 'not_configured', 'Built-in model not available');
-
// Anonymous proxy — only :free models pass the gate below, but the upstream
// free-tier quota is shared across our OpenRouter key. Cap per-IP to prevent
// a single client from draining the free quota and rate-limiting everyone.
@@ -43,6 +41,18 @@ export default wrap(async (req, res) => {
return error(res, err.status ?? 400, 'bad_request', err.message);
}
+ // The virtual agent-loop model: same wire format in and out, but answered by
+ // the server-side tool loop instead of OpenRouter. The chatIp limit above
+ // already counted this request, so the loop skips its own limiter. Branches
+ // before the OpenRouter key check on purpose: the loop runs on its own
+ // provider chain (Groq / Vertex / …) and does not need an OpenRouter key.
+ if (body?.model === AGENT_MODEL_ID) {
+ return runAgentCompletion(req, res, body, { rateLimited: true });
+ }
+
+ if (!env.OPENROUTER_API_KEY && !env.OPENROUTER_FALLBACK_KEYS.length)
+ return error(res, 503, 'not_configured', 'Built-in model not available');
+
const model = body?.model;
// Only allow free-tier OpenRouter models to prevent abuse.
if (!isFreeModelId(model))
diff --git a/tests/agent-run-endpoint.test.js b/tests/agent-run-endpoint.test.js
new file mode 100644
index 000000000..3311a1400
--- /dev/null
+++ b/tests/agent-run-endpoint.test.js
@@ -0,0 +1,210 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// The loop's impure edges are all mocked at module boundaries: the LLM chain
+// (scripted rounds), the tool registry (a spy handler), the rate limiter, and
+// env. What runs for real is the AgentRuntime loop, the GuardChain preflight,
+// and the OpenAI wire formatting.
+const agentRunIp = vi.fn();
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { agentRunIp: (...a) => agentRunIp(...a) },
+ clientIp: () => '1.2.3.4',
+}));
+vi.mock('../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' },
+}));
+
+const providerChain = vi.fn();
+const streamRound = vi.fn();
+vi.mock('../api/_lib/llm-tool-chain.js', () => ({
+ providerChain: (...a) => providerChain(...a),
+ streamRound: (...a) => streamRound(...a),
+}));
+
+const priceHandler = vi.fn();
+vi.mock('../api/_lib/agent-tools.js', () => ({
+ agentToolSchemas: () => [
+ {
+ type: 'function',
+ function: {
+ name: 'token_price',
+ description: 'test tool',
+ parameters: { type: 'object', properties: { query: { type: 'string' } } },
+ },
+ },
+ ],
+ agentToolHandlers: () => ({ token_price: (...a) => priceHandler(...a) }),
+}));
+
+const { default: runHandler } = await import('../api/agent/run.js');
+
+function mkReq({ method = 'POST', body = null } = {}) {
+ return {
+ method,
+ url: '/api/agent/run',
+ headers: body != null ? { 'content-type': 'application/json' } : {},
+ socket: { remoteAddress: '127.0.0.1' },
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ queueMicrotask(() => {
+ cb(Buffer.from(JSON.stringify(body)));
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ if (body == null) queueMicrotask(() => cb());
+ else this._endCb = cb;
+ }
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ chunks: [],
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ write(c) {
+ this.chunks.push(String(c));
+ },
+ end(c) {
+ if (c != null) this.chunks.push(String(c));
+ this.writableEnded = true;
+ },
+ };
+}
+const sseText = (res) => res.chunks.join('');
+
+beforeEach(() => {
+ agentRunIp.mockReset().mockResolvedValue({ success: true, limit: 30, remaining: 29, reset: Date.now() + 1000 });
+ providerChain.mockReset().mockReturnValue([{ name: 'scripted', url: 'http://test', key: 'k', model: 'm' }]);
+ streamRound.mockReset();
+ priceHandler.mockReset();
+});
+
+describe('POST /api/agent/run', () => {
+ it('runs a tool round then streams the final answer as OpenAI chunks', async () => {
+ streamRound
+ .mockImplementationOnce(async () => ({
+ content: '',
+ toolCalls: [{ id: 'c1', name: 'token_price', args: '{"query":"solana"}' }],
+ }))
+ .mockImplementationOnce(async (_provider, { onContent }) => {
+ onContent('SOL is ');
+ onContent('$200.');
+ return { content: 'SOL is $200.', toolCalls: [] };
+ });
+ priceHandler.mockResolvedValue({ found: true, symbol: 'sol', priceUsd: 200 });
+
+ const res = mkRes();
+ await runHandler(mkReq({ body: { messages: [{ role: 'user', content: 'price of sol?' }], stream: true } }), res);
+
+ const text = sseText(res);
+ expect(res.headers['content-type']).toContain('text/event-stream');
+ expect(text).toContain('"role":"assistant"');
+ expect(text).toContain(': tool token_price');
+ expect(text).toContain('"content":"SOL is "');
+ expect(text).toContain('"finish_reason":"stop"');
+ expect(text).toContain('data: [DONE]');
+
+ // The tool actually executed with the model's arguments…
+ expect(priceHandler).toHaveBeenCalledWith({ query: 'solana' });
+ // …and the second round saw the assistant tool_calls message plus the
+ // tool result fed back in OpenAI format.
+ const secondMessages = streamRound.mock.calls[1][1].messages;
+ const assistant = secondMessages.find((m) => m.role === 'assistant' && m.tool_calls);
+ expect(assistant.tool_calls[0].function.name).toBe('token_price');
+ const toolMsg = secondMessages.find((m) => m.role === 'tool' && m.tool_call_id === 'c1');
+ expect(JSON.parse(toolMsg.content)).toMatchObject({ priceUsd: 200 });
+ });
+
+ it('answers non-stream requests with a chat.completion JSON', async () => {
+ streamRound.mockImplementationOnce(async () => ({ content: 'Just an answer.', toolCalls: [] }));
+
+ const res = mkRes();
+ await runHandler(mkReq({ body: { messages: [{ role: 'user', content: 'hi' }], stream: false } }), res);
+
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(sseText(res));
+ expect(out.object).toBe('chat.completion');
+ expect(out.choices[0].message.content).toBe('Just an answer.');
+ expect(streamRound).toHaveBeenCalledTimes(1);
+ });
+
+ it('feeds an unknown tool back to the model as an error instead of crashing', async () => {
+ streamRound
+ .mockImplementationOnce(async () => ({
+ content: '',
+ toolCalls: [{ id: 'c9', name: 'not_a_tool', args: '{}' }],
+ }))
+ .mockImplementationOnce(async () => ({ content: 'That tool does not exist.', toolCalls: [] }));
+
+ const res = mkRes();
+ await runHandler(mkReq({ body: { messages: [{ role: 'user', content: 'x' }] } }), res);
+
+ const secondMessages = streamRound.mock.calls[1][1].messages;
+ const toolMsg = secondMessages.find((m) => m.role === 'tool' && m.tool_call_id === 'c9');
+ expect(JSON.parse(toolMsg.content).error).toContain('Unknown tool');
+ expect(priceHandler).not.toHaveBeenCalled();
+ });
+
+ it('injects the server system note without displacing a client persona', async () => {
+ streamRound.mockImplementationOnce(async () => ({ content: 'ok', toolCalls: [] }));
+
+ const res = mkRes();
+ await runHandler(
+ mkReq({
+ body: {
+ messages: [
+ { role: 'system', content: 'You are Blorbo.' },
+ { role: 'user', content: 'hi' },
+ ],
+ },
+ }),
+ res,
+ );
+
+ const messages = streamRound.mock.calls[0][1].messages;
+ expect(messages[0].content).toBe('You are Blorbo.');
+ expect(messages[1].role).toBe('system');
+ expect(messages[1].content).toContain('server-side tools');
+ });
+
+ it('fails over to the next provider before any byte is streamed', async () => {
+ providerChain.mockReturnValue([
+ { name: 'dead', url: 'http://dead', key: 'k', model: 'm' },
+ { name: 'live', url: 'http://live', key: 'k', model: 'm' },
+ ]);
+ streamRound
+ .mockImplementationOnce(async () => {
+ throw new Error('dead lane');
+ })
+ .mockImplementationOnce(async () => ({ content: 'from the live lane', toolCalls: [] }));
+
+ const res = mkRes();
+ await runHandler(mkReq({ body: { messages: [{ role: 'user', content: 'hi' }], stream: false } }), res);
+
+ const out = JSON.parse(sseText(res));
+ expect(out.choices[0].message.content).toBe('from the live lane');
+ });
+
+ it('400s on missing messages and 429s when rate-limited', async () => {
+ let res = mkRes();
+ await runHandler(mkReq({ body: {} }), res);
+ expect(res.statusCode).toBe(400);
+
+ agentRunIp.mockResolvedValue({ success: false, limit: 30, remaining: 0, reset: Date.now() + 1000 });
+ res = mkRes();
+ await runHandler(mkReq({ body: { messages: [{ role: 'user', content: 'hi' }] } }), res);
+ expect(res.statusCode).toBe(429);
+ });
+
+ it('503s when no LLM provider is configured', async () => {
+ providerChain.mockReturnValue([]);
+ const res = mkRes();
+ await runHandler(mkReq({ body: { messages: [{ role: 'user', content: 'hi' }] } }), res);
+ expect(res.statusCode).toBe(503);
+ });
+});
diff --git a/tests/agent-tools-registry.test.js b/tests/agent-tools-registry.test.js
new file mode 100644
index 000000000..4afa11f26
--- /dev/null
+++ b/tests/agent-tools-registry.test.js
@@ -0,0 +1,107 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// The registry's upstreams are the mocked boundary; what is under test is the
+// schema surface, argument validation, and result mapping.
+const geckoFetch = vi.fn();
+vi.mock('../api/_lib/coingecko.js', () => ({ geckoFetch: (...a) => geckoFetch(...a) }));
+
+const getBalance = vi.fn();
+vi.mock('../api/_lib/agent-pumpfun.js', () => ({
+ solanaPublicConnection: () => ({ getBalance: (...a) => getBalance(...a) }),
+}));
+
+const assessTradeSafety = vi.fn();
+vi.mock('../api/_lib/trade-firewall.js', () => ({
+ assessTradeSafety: (...a) => assessTradeSafety(...a),
+}));
+
+const getSmartMoneyForMint = vi.fn();
+vi.mock('../api/_lib/smart-money.js', () => ({
+ getSmartMoneyForMint: (...a) => getSmartMoneyForMint(...a),
+}));
+
+const resolveSnsName = vi.fn();
+vi.mock('../src/solana/sns.js', () => ({ resolveSnsName: (...a) => resolveSnsName(...a) }));
+
+const { AGENT_TOOLS, agentToolSchemas, agentToolHandlers } = await import(
+ '../api/_lib/agent-tools.js'
+);
+
+const SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+beforeEach(() => {
+ geckoFetch.mockReset();
+ getBalance.mockReset();
+ assessTradeSafety.mockReset();
+ getSmartMoneyForMint.mockReset();
+ resolveSnsName.mockReset();
+});
+
+describe('agent tool registry', () => {
+ it('exposes a valid OpenAI function schema for every tool', () => {
+ const schemas = agentToolSchemas();
+ expect(schemas.length).toBe(Object.keys(AGENT_TOOLS).length);
+ for (const s of schemas) {
+ expect(s.type).toBe('function');
+ expect(s.function.name).toBeTruthy();
+ expect(s.function.description.length).toBeGreaterThan(10);
+ expect(s.function.parameters.type).toBe('object');
+ expect(agentToolHandlers()[s.function.name]).toBeTypeOf('function');
+ }
+ });
+
+ it('token_price maps a CoinGecko search + price into one result', async () => {
+ geckoFetch
+ .mockResolvedValueOnce({ coins: [{ id: 'solana', name: 'Solana', symbol: 'SOL' }] })
+ .mockResolvedValueOnce({
+ solana: { usd: 200, usd_24h_change: 3.2, usd_market_cap: 9e10 },
+ });
+
+ const out = await AGENT_TOOLS.token_price.handler({ query: 'sol' });
+ expect(out).toMatchObject({ found: true, id: 'solana', priceUsd: 200, change24hPct: 3.2 });
+ });
+
+ it('token_price reports a miss instead of inventing a coin', async () => {
+ geckoFetch.mockResolvedValueOnce({ coins: [] });
+ const out = await AGENT_TOOLS.token_price.handler({ query: 'zzzznotacoin' });
+ expect(out).toEqual({ found: false, query: 'zzzznotacoin' });
+ });
+
+ it('sol_balance validates the address before touching RPC', async () => {
+ await expect(AGENT_TOOLS.sol_balance.handler({ address: 'not-base58!' })).rejects.toThrow(
+ /base58/,
+ );
+ expect(getBalance).not.toHaveBeenCalled();
+
+ getBalance.mockResolvedValue(2_500_000_000);
+ const out = await AGENT_TOOLS.sol_balance.handler({ address: SOL_MINT });
+ expect(out.sol).toBe(2.5);
+ });
+
+ it('token_safety forwards the firewall verdict fields verbatim', async () => {
+ assessTradeSafety.mockResolvedValue({
+ verdict: 'block',
+ score: 12,
+ simulated: true,
+ reasons: ['sell simulation failed'],
+ checks: [],
+ });
+ const out = await AGENT_TOOLS.token_safety.handler({ mint: SOL_MINT });
+ expect(out).toMatchObject({ verdict: 'block', score: 12, simulated: true });
+ expect(assessTradeSafety).toHaveBeenCalledWith(
+ expect.objectContaining({ mint: SOL_MINT, side: 'buy' }),
+ );
+ });
+
+ it('resolve_sol_name reports resolution honestly', async () => {
+ resolveSnsName.mockResolvedValue(null);
+ const out = await AGENT_TOOLS.resolve_sol_name.handler({ name: 'ghost.sol' });
+ expect(out).toEqual({ name: 'ghost.sol', address: null, resolved: false });
+ });
+
+ it('smart_money validates the mint and passes the network through', async () => {
+ getSmartMoneyForMint.mockResolvedValue({ mint: SOL_MINT, holders: 3 });
+ await AGENT_TOOLS.smart_money.handler({ mint: SOL_MINT, network: 'devnet' });
+ expect(getSmartMoneyForMint).toHaveBeenCalledWith(SOL_MINT, 'devnet');
+ });
+});