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(gateway): Telegram, Discord and Signal chat gateways sharing one agent thread and the copilot engine

nirholasf796d7fae0c4
diff --git a/api/_lib/agent-thread.js b/api/_lib/agent-thread.js
new file mode 100644
index 000000000..465571682
--- /dev/null
+++ b/api/_lib/agent-thread.js
@@ -0,0 +1,77 @@
+// One conversation per (agent, owner), shared by every surface that talks to
+// the agent: the web copilot, the v1 messages API, Telegram and Discord. Rows
+// live in agent_messages; `channel` says which surface a message came from so
+// each surface can label the others ("via Telegram") while the model sees one
+// continuous history.
+
+import { sql } from './db.js';
+
+export const THREAD_CHANNELS = ['web', 'api', 'telegram', 'discord'];
+const MAX_CONTENT = 8000;
+
+/**
+ * Append one message to the agent's thread.
+ * @returns {Promise<{ id:number, created_at:string }>}
+ */
+export async function appendThreadMessage({ agentId, userId, role, content, channel, toolCalls = [], signatures = [], model = null, provider = null }) {
+ const text = String(content || '').slice(0, MAX_CONTENT);
+ const [row] = await sql`
+ INSERT INTO agent_messages (agent_id, user_id, role, content, channel, tool_calls, signatures, model, provider)
+ VALUES (${agentId}, ${userId}, ${role}, ${text}, ${channel}, ${JSON.stringify(toolCalls || [])}::jsonb,
+ ${signatures || []}, ${model}, ${provider})
+ RETURNING id, created_at
+ `;
+ return row;
+}
+
+/**
+ * Page the thread newest first. `before` is a message id cursor.
+ * @returns {Promise<{ messages:object[], hasMore:boolean }>}
+ */
+export async function listThread({ agentId, userId, limit = 30, before = null }) {
+ const n = Math.max(1, Math.min(100, Number(limit) || 30));
+ const cursor = before != null && /^\d+$/.test(String(before)) ? String(before) : null;
+ const rows = cursor
+ ? await sql`
+ SELECT id, role, content, channel, tool_calls, signatures, created_at
+ FROM agent_messages
+ WHERE agent_id = ${agentId} AND user_id = ${userId} AND id < ${cursor}
+ ORDER BY id DESC LIMIT ${n + 1}`
+ : await sql`
+ SELECT id, role, content, channel, tool_calls, signatures, created_at
+ FROM agent_messages
+ WHERE agent_id = ${agentId} AND user_id = ${userId}
+ ORDER BY id DESC LIMIT ${n + 1}`;
+ const hasMore = rows.length > n;
+ return {
+ hasMore,
+ messages: rows.slice(0, n).map((r) => ({
+ id: Number(r.id),
+ role: r.role,
+ content: r.content,
+ channel: r.channel,
+ toolCalls: r.tool_calls || [],
+ signatures: r.signatures || [],
+ createdAt: r.created_at,
+ })),
+ };
+}
+
+/**
+ * The trailing turns a model should see, oldest first, optionally only those
+ * after `since` (a chat's /new reset point).
+ * @returns {Promise<Array<{ role:'user'|'assistant', content:string }>>}
+ */
+export async function threadHistoryForModel({ agentId, userId, since = null, limit = 24 }) {
+ const n = Math.max(1, Math.min(60, limit));
+ const rows = since
+ ? await sql`
+ SELECT role, content FROM agent_messages
+ WHERE agent_id = ${agentId} AND user_id = ${userId} AND created_at > ${since}
+ ORDER BY id DESC LIMIT ${n}`
+ : await sql`
+ SELECT role, content FROM agent_messages
+ WHERE agent_id = ${agentId} AND user_id = ${userId}
+ ORDER BY id DESC LIMIT ${n}`;
+ return rows.reverse().map((r) => ({ role: r.role, content: String(r.content || '').slice(0, 4000) }));
+}
diff --git a/api/_lib/copilot-engine.js b/api/_lib/copilot-engine.js
new file mode 100644
index 000000000..67104b9c6
--- /dev/null
+++ b/api/_lib/copilot-engine.js
@@ -0,0 +1,513 @@
+// The Conversational Trading Copilot engine: one owner turn against an agent's
+// self-custodied Solana wallet, shared by every surface that talks to it.
+//
+// Born inside api/agents/copilot.js (the web copilot, SSE) and extracted so the
+// chat gateways (api/_lib/gateway/, Telegram and Discord) run the exact same
+// tools, prompt and proposal rules. A surface supplies the agent row, the
+// conversation so far and an `emit(event, data)` sink; the engine runs the
+// read-only tools server-side and turns every state-changing intent into a
+// proposal the owner must confirm on a gated endpoint. It never signs.
+//
+// Events emitted: `status` {phase}, `tool_start` {name}, `tool` {name, summary,
+// data}, `proposal` (a confirm-before-execute card), `chunk` {text}.
+//
+// $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is the only coin three.ws
+// promotes. The copilot trades whatever mint the owner names at runtime (generic
+// coin-agnostic plumbing) and never names or recommends any other token.
+
+import { sql } from './db.js';
+import { PublicKey } from '@solana/web3.js';
+import { solanaPublicConnection } from './agent-pumpfun.js';
+import { quoteTrade } from '../agents/solana-trade.js';
+import { assessTradeSafety } from './trade-firewall.js';
+import { getSmartMoneyForMint } from './smart-money.js';
+import { getTradeLimits } from './agent-trade-guards.js';
+import { providerChain, streamRound } from './llm-tool-chain.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+export const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const MAX_ROUNDS = 4; // tool-loop rounds before we force a final answer
+export const COPILOT_MAX_MESSAGES = 24; // trailing turns we keep as context
+
+// ── tool schema (OpenAI function-calling format) ───────────────────────────────
+export const COPILOT_TOOLS = [
+ {
+ type: 'function',
+ function: {
+ name: 'get_portfolio',
+ description: "Read the agent wallet's live SOL balance, token holdings, and open sniper positions with unrealized PnL. Use to answer 'how's my position?' / 'what do I hold?'.",
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_coin_intel',
+ description: 'Live intelligence for one coin mint: quality score, bundle/organic/concentration signals, risk flags, dev-sold, narrative, and graduation/rug outcome. Use before discussing or proposing a buy.',
+ parameters: { type: 'object', properties: { mint: { type: 'string', description: 'base58 token mint address' } }, required: ['mint'], additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_smart_money',
+ description: 'Smart-money read for one coin: count of reputable wallets in it, a 0-100 smart-money score, and whether one funder cluster dominates (sybil). Use for "is smart money in this?".',
+ parameters: { type: 'object', properties: { mint: { type: 'string' } }, required: ['mint'], additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'assess_safety',
+ description: 'Run the rug/honeypot firewall on a prospective BUY: returns verdict (allow/warn/block), a 0-100 safety score, and plain-language reasons (mint authority, honeypot round-trip, concentration, price impact). Always run before proposing a buy.',
+ parameters: { type: 'object', properties: { mint: { type: 'string' }, sol_amount: { type: 'number', description: 'SOL the owner would spend' } }, required: ['mint'], additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_quote',
+ description: 'Non-binding live quote: expected output and price impact for a buy (sol_amount) or sell (token_amount in UI units). Cite these exact numbers; never invent a quote.',
+ parameters: {
+ type: 'object',
+ properties: {
+ side: { type: 'string', enum: ['buy', 'sell'] },
+ mint: { type: 'string' },
+ sol_amount: { type: 'number', description: 'for buy: SOL to spend' },
+ token_amount: { type: 'number', description: 'for sell: tokens to sell, in UI units' },
+ slippage_bps: { type: 'integer', description: 'default 300 (3%)' },
+ },
+ required: ['side', 'mint'],
+ additionalProperties: false,
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'get_trade_limits',
+ description: "Read the owner's discretionary trade guardrails: per-trade SOL cap, daily budget, max price impact, max slippage, and kill-switch state.",
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'propose_buy',
+ description: 'Surface a BUY proposal for the owner to confirm. Does NOT execute. It returns a confirm card grounded with a fresh quote + firewall verdict. Call this when the owner clearly wants to buy. Never claim a buy happened until the owner confirms it.',
+ parameters: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ sol_amount: { type: 'number', description: 'SOL to spend (> 0)' },
+ slippage_bps: { type: 'integer', description: 'default 300' },
+ rationale: { type: 'string', description: 'one short sentence on why, citing real signals' },
+ },
+ required: ['mint', 'sol_amount'],
+ additionalProperties: false,
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'propose_sell',
+ description: 'Surface a SELL proposal for the owner to confirm. Does NOT execute. Provide either token_pct (1-100 of the held balance) or token_amount (UI units).',
+ parameters: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ token_pct: { type: 'number', description: 'percent of holding to sell, 1-100' },
+ token_amount: { type: 'number', description: 'tokens to sell in UI units (alternative to token_pct)' },
+ slippage_bps: { type: 'integer', description: 'default 300' },
+ rationale: { type: 'string' },
+ },
+ required: ['mint'],
+ additionalProperties: false,
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'propose_set_limits',
+ description: "Surface a risk-control change for the owner to confirm (does NOT apply until confirmed): per-trade SOL cap, daily SOL budget, max price-impact %, or the kill switch (kill_switch:true halts all trading). Use for 'cap my trades at 0.5 SOL', 'pause trading', 'set a daily budget'.",
+ parameters: {
+ type: 'object',
+ properties: {
+ per_trade_sol: { type: 'number' },
+ daily_budget_sol: { type: 'number' },
+ max_price_impact_pct: { type: 'number' },
+ kill_switch: { type: 'boolean' },
+ rationale: { type: 'string' },
+ },
+ additionalProperties: false,
+ },
+ },
+ },
+];
+
+// ── server-side tool execution (read-only) ─────────────────────────────────────
+function num(v) { return v == null || !Number.isFinite(Number(v)) ? null : Number(v); }
+
+async function loadIntel(mint, network) {
+ const [row] = await sql`
+ SELECT i.mint, i.symbol, i.name, i.quality_score, i.bundle_score, i.organic_score,
+ i.snipe_ratio, i.concentration_top10, i.fresh_wallet_ratio, i.risk_flags,
+ i.category, i.narrative, i.dev_sold, i.unique_buyers, i.observation_seconds,
+ o.outcome, o.ath_multiple
+ FROM pump_coin_intel i
+ LEFT JOIN pump_coin_outcomes o ON o.mint = i.mint AND o.network = i.network
+ WHERE i.mint = ${mint} AND i.network = ${network}
+ LIMIT 1`.catch(() => []);
+ if (!row) return { mint, found: false, note: 'No intelligence on this mint yet. The engine only fingerprints pump.fun launches it has observed.' };
+ return {
+ mint, found: true, symbol: row.symbol, name: row.name,
+ quality_score: num(row.quality_score),
+ bundle_score: num(row.bundle_score), organic_score: num(row.organic_score),
+ snipe_ratio: num(row.snipe_ratio), concentration_top10: num(row.concentration_top10),
+ fresh_wallet_ratio: num(row.fresh_wallet_ratio), risk_flags: row.risk_flags || [],
+ category: row.category, narrative: row.narrative, dev_sold: row.dev_sold,
+ unique_buyers: row.unique_buyers, observation_seconds: row.observation_seconds,
+ outcome: row.outcome || null, ath_multiple: num(row.ath_multiple),
+ };
+}
+
+export async function loadPortfolio(agentId, address, network) {
+ const out = { network, wallet: address, sol_balance: null, holdings: [], open_positions: [] };
+ if (!address) return out;
+ const conn = solanaPublicConnection(network);
+ const ownerPk = new PublicKey(address);
+ try {
+ const lamports = await conn.getBalance(ownerPk);
+ out.sol_balance = Number(lamports) / LAMPORTS_PER_SOL;
+ } catch { /* RPC hiccup — report null, copilot says balance unavailable */ }
+ try {
+ const TOKEN = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
+ const TOKEN22 = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
+ const accounts = [];
+ for (const prog of [TOKEN, TOKEN22]) {
+ const r = await conn.getParsedTokenAccountsByOwner(ownerPk, { programId: prog }).catch(() => null);
+ if (r?.value) accounts.push(...r.value);
+ }
+ out.holdings = accounts
+ .map((a) => {
+ const info = a.account.data.parsed?.info;
+ const amt = info?.tokenAmount;
+ return amt && Number(amt.uiAmount) > 0
+ ? { mint: info.mint, ui_amount: Number(amt.uiAmount), decimals: amt.decimals }
+ : null;
+ })
+ .filter(Boolean)
+ .slice(0, 30);
+ } catch { /* token read failed — holdings stay empty */ }
+ try {
+ const rows = await sql`
+ SELECT mint, symbol, status, entry_quote_lamports, last_value_lamports,
+ realized_pnl_lamports, realized_pnl_pct, exit_reason
+ FROM agent_sniper_positions
+ WHERE agent_id = ${agentId} AND network = ${network} AND status = 'open'
+ ORDER BY opened_at DESC LIMIT 20`;
+ out.open_positions = rows.map((p) => ({
+ mint: p.mint, symbol: p.symbol,
+ entry_sol: num(p.entry_quote_lamports) != null ? num(p.entry_quote_lamports) / LAMPORTS_PER_SOL : null,
+ current_sol: num(p.last_value_lamports) != null ? num(p.last_value_lamports) / LAMPORTS_PER_SOL : null,
+ unrealized_pnl_pct: num(p.realized_pnl_pct),
+ }));
+ } catch { /* positions table read failed — leave empty */ }
+ return out;
+}
+
+export async function runQuote({ side, mint, solAmount, tokenAmount, slippageBps, network }) {
+ const conn = solanaPublicConnection(network);
+ const mintPk = new PublicKey(mint);
+ let tokenAmountRaw;
+ if (side === 'sell') {
+ // Convert UI tokens → raw using on-chain decimals.
+ let decimals = 6;
+ try {
+ const info = await conn.getParsedAccountInfo(mintPk);
+ const d = info?.value?.data?.parsed?.info?.decimals;
+ if (Number.isInteger(d)) decimals = d;
+ } catch { /* default 6 */ }
+ tokenAmountRaw = BigInt(Math.floor(Number(tokenAmount || 0) * 10 ** decimals)).toString();
+ }
+ const q = await quoteTrade({ conn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps });
+ return {
+ side, mint, venue: q.venue, price_impact_pct: num(q.priceImpactPct),
+ in_asset: q.inAsset, in_amount: num(q.inAmount),
+ out_asset: q.outAsset, expected_out: num(q.outUi),
+ min_received: num(q.minOutUi),
+ };
+}
+
+// Best-effort coin label (symbol/name) for proposal cards.
+async function coinLabel(mint, network) {
+ const intel = await loadIntel(mint, network).catch(() => null);
+ if (intel?.found && (intel.symbol || intel.name)) return { symbol: intel.symbol || null, name: intel.name || null };
+ return { symbol: null, name: null };
+}
+
+// ── system prompt ──────────────────────────────────────────────────────────────
+export function buildSystemPrompt({ agentName, persona, network }) {
+ const base = (persona || '').trim();
+ return [
+ base ? `You speak in character as ${agentName}. Persona:\n${base}\n` : `You are ${agentName}, a trading copilot.`,
+ `You are the in-world CONVERSATIONAL TRADING COPILOT for the three.ws agent "${agentName}" and its self-custodied Solana wallet (network: ${network}).`,
+ `Your job: help the owner snipe, trade, and manage risk by talking. You have real tools, so use them; never invent numbers, prices, balances, safety verdicts, or smart-money counts. If a tool returns no data, say so plainly.`,
+ `RULES:`,
+ `• ACT, don't ask. The read-only tools (get_portfolio, get_coin_intel, get_smart_money, assess_safety, get_quote, get_trade_limits) are free and instant, so CALL them immediately to answer. NEVER ask the owner for permission to read their own wallet or check a coin ("would you like me to check…?" is forbidden). If they ask "how's my portfolio?", call get_portfolio right away and answer with the real numbers. Only the propose_* actions need confirmation.`,
+ `• You NEVER execute or sign anything. To buy, sell, or change risk limits you MUST call the matching propose_* tool, which surfaces a confirm card. The owner confirms; a guarded server endpoint then enforces spend caps, the firewall, and the kill switch and signs. Never say a trade is done. Say you've prepared it for confirmation.`,
+ `• Before proposing OR recommending a buy, ground it: call assess_safety (firewall) and get_quote, and mention the safety verdict and price impact. If the firewall verdict is "block", refuse the buy and explain why.`,
+ `• Keep answers tight and conversational (2-5 sentences), because this may be read aloud. Light markdown is fine (bold, short bullet lists) but no tables or code blocks. The UI already shows the raw numbers as cards, so narrate the takeaway and don't re-list every figure.`,
+ `• The only coin three.ws promotes is $THREE. You may trade any mint the owner explicitly names (that is their call), but never suggest, shill, or name a specific other token on your own initiative.`,
+ `• When the owner is vague ("buy the safe one"), ask one brief clarifying question or have them paste a mint. Do not guess a mint address.`,
+ ].join('\n');
+}
+
+
+/**
+ * Run one copilot turn.
+ *
+ * @param {object} opts
+ * @param {{ id:string, name?:string, persona_prompt?:string, meta?:object }} opts.agent the owned agent row
+ * @param {Array<{role:'user'|'assistant', content:string}>} opts.history trailing turns, last one the user's
+ * @param {'mainnet'|'devnet'} opts.network
+ * @param {(event:string, data:object) => void} [opts.emit] event sink (see header)
+ * @param {() => boolean} [opts.isActive] false once the caller has gone away
+ * @param {string} [opts.surfaceNote] extra system guidance for the delivering surface
+ * @param {Array} [opts.chain] provider chain override (defaults to providerChain())
+ * @returns {Promise<{ reply:string, proposals:object[], citations:object[], toolCalls:{name:string, summary:string}[] }>}
+ */
+export async function runCopilotTurn({ agent, history, network, emit = () => {}, isActive = () => true, surfaceNote = '', chain = providerChain() }) {
+ if (!chain.length) {
+ throw Object.assign(new Error('No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY (or GOOGLE_CLOUD_PROJECT for the Vertex credits anchor).'), { code: 'llm_unavailable' });
+ }
+ const id = agent.id;
+ const meta = agent.meta || {};
+ const address = meta.solana_address || null;
+ const send = (event, data) => { if (isActive()) emit(event, data); };
+ const system = buildSystemPrompt({ agentName: agent.name || 'Agent', persona: agent.persona_prompt, network });
+ const messages = [{ role: 'system', content: surfaceNote ? `${system}\n${surfaceNote}` : system }, ...history];
+ const proposals = [];
+ const citations = [];
+ const toolCalls = [];
+ let finalText = '';
+ const active = () => isActive();
+
+ // Read-only tools are pure within a turn — the wallet/intel/quote a round sees
+ // won't change between the model's rounds. Memoize by (name, args) so when the
+ // model re-issues an identical read (a common small-model tic that otherwise
+ // burns a whole tool-loop round and paints a duplicate "Portfolio: …" line in
+ // the UI) we serve it from cache: no second RPC, no duplicate `tool` event, and
+ // the loop can tell the round made no new progress and cut to a final answer.
+ const readCache = new Map();
+
+ // One read-only tool execution → returns a compact result for the model + a UI summary.
+ async function execReadTool(name, args) {
+ if (name === 'get_portfolio') {
+ const p = await loadPortfolio(id, address, network);
+ citations.push({ kind: 'portfolio', sol: p.sol_balance, holdings: p.holdings.length, positions: p.open_positions.length });
+ return {
+ result: p,
+ summary: address ? `Portfolio: ${p.sol_balance != null ? p.sol_balance.toFixed(4) + ' SOL' : 'balance unavailable'}, ${p.holdings.length} token(s), ${p.open_positions.length} open position(s)` : 'No wallet provisioned yet',
+ card: { kind: 'portfolio', wallet: p.wallet, sol_balance: p.sol_balance, holdings: p.holdings, open_positions: p.open_positions, network },
+ };
+ }
+ if (name === 'get_coin_intel') {
+ const intel = await loadIntel(args.mint, network);
+ citations.push({ kind: 'intel', mint: args.mint, quality: intel.quality_score ?? null });
+ return {
+ result: intel,
+ summary: intel.found ? `Intel ${intel.symbol || ''}: quality ${intel.quality_score ?? 'n/a'}/100, ${(intel.risk_flags || []).length} risk flag(s)${intel.outcome ? `, outcome ${intel.outcome}` : ''}` : 'No intel on this mint',
+ card: { kind: 'intel', ...intel },
+ };
+ }
+ if (name === 'get_smart_money') {
+ const sm = await getSmartMoneyForMint(args.mint, network);
+ citations.push({ kind: 'smart_money', mint: args.mint, score: sm.smart_money_score, count: sm.count });
+ return {
+ result: sm,
+ summary: `Smart money: ${sm.count} reputable wallet(s), score ${sm.smart_money_score}/100${sm.sybil_flag ? ' (sybil-dominated)' : ''}`,
+ card: { kind: 'smart_money', mint: args.mint, count: sm.count, score: sm.smart_money_score, sybil: !!sm.sybil_flag },
+ };
+ }
+ if (name === 'assess_safety') {
+ const conn = solanaPublicConnection(network);
+ const quoteLamports = args.sol_amount > 0 ? BigInt(Math.floor(Number(args.sol_amount) * LAMPORTS_PER_SOL)) : null;
+ const a = await assessTradeSafety({ network, mint: args.mint, side: 'buy', payer: address, quoteAmount: quoteLamports, connection: conn });
+ citations.push({ kind: 'safety', mint: args.mint, verdict: a.verdict, score: a.score });
+ return {
+ result: { verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated },
+ summary: `Firewall: ${a.verdict.toUpperCase()} (${a.score}/100)${a.reasons?.[0] ? ': ' + a.reasons[0] : ''}`,
+ card: { kind: 'safety', mint: args.mint, verdict: a.verdict, score: a.score, reasons: a.reasons || [], simulated: !!a.simulated },
+ };
+ }
+ if (name === 'get_quote') {
+ const q = await runQuote({ side: args.side, mint: args.mint, solAmount: args.sol_amount, tokenAmount: args.token_amount, slippageBps: args.slippage_bps || 300, network });
+ citations.push({ kind: 'quote', mint: args.mint, side: args.side, impact: q.price_impact_pct });
+ return {
+ result: q,
+ summary: `Quote ${args.side}: ${q.expected_out != null ? q.expected_out.toLocaleString(undefined, { maximumFractionDigits: 4 }) : 'n/a'} ${q.out_asset}, ${q.price_impact_pct != null ? q.price_impact_pct.toFixed(2) + '% impact' : 'impact n/a'}`,
+ card: { kind: 'quote', mint: args.mint, side: q.side, in_asset: q.in_asset, in_amount: q.in_amount, out_asset: q.out_asset, expected_out: q.expected_out, price_impact_pct: q.price_impact_pct, min_received: q.min_received },
+ };
+ }
+ if (name === 'get_trade_limits') {
+ const lim = getTradeLimits(meta);
+ return {
+ result: lim,
+ summary: `Limits: per-trade ${lim.per_trade_sol ?? '∞'} SOL, daily ${lim.daily_budget_sol ?? '∞'} SOL, kill switch ${lim.kill_switch ? 'ON' : 'off'}`,
+ card: { kind: 'limits', ...lim },
+ };
+ }
+ return { result: { error: 'unknown_tool' }, summary: 'unknown tool' };
+ }
+
+ // A propose_* tool → grounded proposal card, never executed here.
+ async function execProposeTool(name, args) {
+ if (name === 'propose_buy') {
+ if (!BASE58_RE.test(args.mint || '')) return { result: { error: 'invalid_mint' }, summary: 'invalid mint' };
+ const slippageBps = Math.max(0, Math.min(5000, Math.round(args.slippage_bps || 300)));
+ const [quote, safety, label] = await Promise.all([
+ runQuote({ side: 'buy', mint: args.mint, solAmount: args.sol_amount, slippageBps, network }).catch((e) => ({ error: e?.message || 'quote_failed' })),
+ assessTradeSafety({ network, mint: args.mint, side: 'buy', payer: address, quoteAmount: BigInt(Math.floor(Number(args.sol_amount) * LAMPORTS_PER_SOL)), connection: solanaPublicConnection(network) })
+ .then((a) => ({ verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated }))
+ .catch(() => null),
+ coinLabel(args.mint, network),
+ ]);
+ const proposal = { id: `p${proposals.length + 1}`, kind: 'buy', mint: args.mint, coin: label, sol_amount: Number(args.sol_amount), slippage_bps: slippageBps, network, quote, safety, rationale: args.rationale || null };
+ proposals.push(proposal);
+ send('proposal', proposal);
+ const blocked = safety?.verdict === 'block';
+ return { result: { surfaced: true, blocked, safety_verdict: safety?.verdict, price_impact_pct: quote?.price_impact_pct }, summary: `Buy proposal surfaced (awaiting confirmation). Firewall ${safety?.verdict || 'n/a'}.${blocked ? ' BLOCKED, do not encourage this trade.' : ''}` };
+ }
+ if (name === 'propose_sell') {
+ if (!BASE58_RE.test(args.mint || '')) return { result: { error: 'invalid_mint' }, summary: 'invalid mint' };
+ const slippageBps = Math.max(0, Math.min(5000, Math.round(args.slippage_bps || 300)));
+ // Resolve the held balance so a percent maps to a concrete UI amount.
+ const port = await loadPortfolio(id, address, network).catch(() => null);
+ const held = port?.holdings?.find((h) => h.mint === args.mint) || null;
+ let tokenAmount = num(args.token_amount);
+ let tokenPct = num(args.token_pct);
+ if (tokenAmount == null && tokenPct != null && held) tokenAmount = (held.ui_amount * Math.max(1, Math.min(100, tokenPct))) / 100;
+ if (tokenAmount == null && held) tokenAmount = held.ui_amount; // default: sell all
+ if (!(tokenAmount > 0)) return { result: { error: 'no_holding' }, summary: 'owner does not hold this coin' };
+ const [quote, label] = await Promise.all([
+ runQuote({ side: 'sell', mint: args.mint, tokenAmount, slippageBps, network }).catch((e) => ({ error: e?.message || 'quote_failed' })),
+ coinLabel(args.mint, network),
+ ]);
+ const proposal = { id: `p${proposals.length + 1}`, kind: 'sell', mint: args.mint, coin: label, token_amount: tokenAmount, token_pct: tokenPct ?? null, decimals: held?.decimals ?? 6, slippage_bps: slippageBps, network, quote, rationale: args.rationale || null };
+ proposals.push(proposal);
+ send('proposal', proposal);
+ return { result: { surfaced: true, expected_sol: quote?.expected_out }, summary: `Sell proposal surfaced (awaiting confirmation): ~${quote?.expected_out != null ? Number(quote.expected_out).toFixed(4) : 'n/a'} SOL.` };
+ }
+ if (name === 'propose_set_limits') {
+ const cur = getTradeLimits(meta);
+ const changes = {};
+ for (const k of ['per_trade_sol', 'daily_budget_sol', 'max_price_impact_pct']) {
+ if (num(args[k]) != null) changes[k] = Number(args[k]);
+ }
+ if (typeof args.kill_switch === 'boolean') changes.kill_switch = args.kill_switch;
+ if (!Object.keys(changes).length) return { result: { error: 'no_change' }, summary: 'no limit change specified' };
+ const proposal = { id: `p${proposals.length + 1}`, kind: 'limits', network, current: cur, changes, rationale: args.rationale || null };
+ proposals.push(proposal);
+ send('proposal', proposal);
+ return { result: { surfaced: true }, summary: 'Risk-limit change surfaced (awaiting confirmation).' };
+ }
+ return { result: { error: 'unknown_tool' }, summary: 'unknown tool' };
+ }
+
+ // ── tool loop ──────────────────────────────────────────────────────────────
+ let answered = false;
+ for (let round = 0; round < MAX_ROUNDS && active() && !answered; round++) {
+ send('status', { phase: round === 0 ? 'thinking' : 'continuing' });
+ // Pick the first provider that yields a round; once content has been
+ // streamed to the client we can't fail over, so stream-failover only
+ // applies before any byte for THIS round was emitted.
+ let roundOut = null;
+ let lastErr = null;
+ for (const provider of chain) {
+ let emitted = false;
+ try {
+ roundOut = await streamRound(provider, {
+ messages,
+ tools: COPILOT_TOOLS,
+ onContent: (t) => { emitted = true; finalText += t; send('chunk', { text: t }); },
+ });
+ break;
+ } catch (e) {
+ lastErr = e;
+ if (emitted) { roundOut = { content: '', toolCalls: [] }; break; } // mid-stream failure; stop
+ }
+ }
+ if (!roundOut) throw lastErr || new Error('all providers failed');
+
+ if (!roundOut.toolCalls.length) { answered = true; break; }
+
+ // Record the assistant's tool-call turn, then resolve each call.
+ messages.push({
+ role: 'assistant',
+ content: roundOut.content || null,
+ tool_calls: roundOut.toolCalls.map((tc) => ({ id: tc.id, type: 'function', function: { name: tc.name, arguments: tc.args || '{}' } })),
+ });
+ // A round is only "progress" if at least one call surfaced something new —
+ // a fresh read, or a proposal. If every call this round is a repeat of a
+ // read the model already ran this turn, it's spinning: feed the cached
+ // results back (OpenAI requires a tool result per tool_call) but break out
+ // afterward so the finalize step turns what we have into a real answer
+ // instead of stalling the owner behind more identical "Analyzing…" rounds.
+ let progressed = false;
+ for (const tc of roundOut.toolCalls) {
+ let args = {};
+ try { args = tc.args ? JSON.parse(tc.args) : {}; } catch { args = {}; }
+ const isPropose = tc.name.startsWith('propose_');
+ send('tool_start', { name: tc.name });
+ let outcome;
+ let cached = false;
+ try {
+ if (isPropose) {
+ outcome = await execProposeTool(tc.name, args);
+ progressed = true;
+ } else {
+ const key = `${tc.name}:${JSON.stringify(args)}`;
+ if (readCache.has(key)) {
+ outcome = readCache.get(key);
+ cached = true;
+ } else {
+ outcome = await execReadTool(tc.name, args);
+ readCache.set(key, outcome);
+ progressed = true;
+ }
+ }
+ } catch (e) {
+ outcome = { result: { error: e?.message || 'tool_failed' }, summary: `Tool ${tc.name} failed: ${e?.message || 'error'}` };
+ progressed = true; // a genuine failure is new information, not a spin
+ }
+ // Surface read activity once per distinct read — never re-paint a cached repeat.
+ if (!isPropose && !cached) send('tool', { name: tc.name, summary: outcome.summary, data: outcome.card || null });
+ if (!cached) toolCalls.push({ name: tc.name, summary: outcome.summary });
+ messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(outcome.result).slice(0, 6000) });
+ }
+ if (!progressed) break; // model looped on data it already has — go answer.
+ }
+
+ // If the loop hit its round cap mid-tool without a natural answer, ask for a
+ // final plain-language wrap-up (no tools) so the user always gets a reply.
+ if (!finalText.trim() && active()) {
+ send('status', { phase: 'finalizing' });
+ for (const provider of chain) {
+ try {
+ const out = await streamRound(provider, {
+ messages: [...messages, { role: 'user', content: 'Briefly summarize what you found and what I should do next. Plain language, 2-4 sentences.' }],
+ tools: [],
+ onContent: (t) => { finalText += t; send('chunk', { text: t }); },
+ });
+ if (out) break;
+ } catch { /* try next provider */ }
+ }
+ }
+
+ return { reply: finalText.trim(), proposals, citations, toolCalls };
+}
diff --git a/api/_lib/gateway/agents.js b/api/_lib/gateway/agents.js
new file mode 100644
index 000000000..a672cd4a0
--- /dev/null
+++ b/api/_lib/gateway/agents.js
@@ -0,0 +1,49 @@
+// Which agent a paired chat talks to. A chat has a default agent; an account
+// with exactly one agent never has to choose.
+
+import { sql } from '../db.js';
+import { setLinkDefaultAgent } from './store.js';
+
+export async function listAccountAgents(userId) {
+ return sql`
+ SELECT id, name, meta, created_at FROM agent_identities
+ WHERE user_id = ${userId} AND deleted_at IS NULL
+ ORDER BY created_at ASC
+ LIMIT 50`;
+}
+
+/**
+ * The chat's agent: its default when that agent is still owned and live, the
+ * account's only agent otherwise (remembered as the default), or null when the
+ * owner has to pick one with /use.
+ */
+export async function resolveChatAgent(link) {
+ if (link.default_agent_id) {
+ const [row] = await sql`
+ SELECT id, user_id, name, persona_prompt, meta FROM agent_identities
+ WHERE id = ${link.default_agent_id} AND user_id = ${link.user_id} AND deleted_at IS NULL`;
+ if (row) return row;
+ }
+ const agents = await listAccountAgents(link.user_id);
+ if (agents.length !== 1) return null;
+ await setLinkDefaultAgent(link.id, agents[0].id);
+ const [row] = await sql`
+ SELECT id, user_id, name, persona_prompt, meta FROM agent_identities WHERE id = ${agents[0].id}`;
+ return row || null;
+}
+
+/** Match `/use <arg>`: a list number, a full or prefix id, or a name. */
+export function pickAgent(agents, arg) {
+ const a = String(arg || '').trim();
+ if (!a) return null;
+ if (/^\d+$/.test(a)) {
+ const i = Number(a) - 1;
+ if (i >= 0 && i < agents.length) return agents[i];
+ }
+ const lower = a.toLowerCase();
+ return agents.find((x) => x.id === a)
+ || agents.find((x) => x.id.startsWith(lower) && lower.length >= 6)
+ || agents.find((x) => String(x.name || '').toLowerCase() === lower)
+ || agents.filter((x) => String(x.name || '').toLowerCase().includes(lower)).at(0)
+ || null;
+}
diff --git a/api/_lib/gateway/approvals.js b/api/_lib/gateway/approvals.js
new file mode 100644
index 000000000..c124bf6dd
--- /dev/null
+++ b/api/_lib/gateway/approvals.js
@@ -0,0 +1,171 @@
+// Approve and Cancel for chat previews. The confirm flag behind a trade is set
+// in exactly one place: a button press carrying the preview's id, from the
+// platform user the chat is paired to, while the preview is still live. Text
+// can never reach here, and an expired, cancelled or already-used preview can
+// never execute.
+//
+// Execution runs through the same engine as the web wallet's Trade tab
+// (executeAgentTrade: quote, kill switch, per-trade cap, daily budget, spend
+// policy, firewall, custody ledger, idempotency) and the same limits writer.
+
+import { sql } from '../db.js';
+import { currentSignatureFor, agreementRequirement } from '../real-funds-agreement.js';
+import { getTradeLimits, setTradeLimits } from '../agent-trade-guards.js';
+import { executeAgentTrade, parseTradeInput } from '../../agents/agent-trade.js';
+import { appendThreadMessage } from '../agent-thread.js';
+import { limits } from '../rate-limit.js';
+import { getPreview, claimPreview, cancelPreview, expirePreview, finishPreview } from './store.js';
+import { previewText, APPROVE, CANCEL } from './conversation.js';
+import { explorerTx, fmtNum } from './format.js';
+
+/** Parse a button id into { verb, previewId }, or null. */
+export function parseActionId(id) {
+ const s = String(id || '');
+ if (s.startsWith(APPROVE)) return { verb: 'approve', previewId: s.slice(APPROVE.length) };
+ if (s.startsWith(CANCEL)) return { verb: 'cancel', previewId: s.slice(CANCEL.length) };
+ return null;
+}
+
+const fail = (code, message, detail = null) => ({ ok: false, code, message, detail });
+
+const LIMIT_KEYS = ['per_trade_sol', 'daily_budget_sol', 'max_price_impact_pct', 'kill_switch'];
+function validLimitChanges(changes) {
+ const out = {};
+ for (const k of LIMIT_KEYS) {
+ if (!(k in (changes || {}))) continue;
+ const v = changes[k];
+ if (k === 'kill_switch') {
+ if (typeof v !== 'boolean') return null;
+ } else if (!(typeof v === 'number' && Number.isFinite(v) && v >= 0 && (k !== 'max_price_impact_pct' || v <= 100))) {
+ return null;
+ }
+ out[k] = v;
+ }
+ return Object.keys(out).length ? out : null;
+}
+
+/**
+ * Execute a claimed preview. `confirm` must be the literal true the button path
+ * passes; any other caller gets a refusal.
+ * @returns {Promise<{ ok:true, data:object } | { ok:false, code:string, message:string, detail?:object }>}
+ */
+export async function executePreview(preview, { confirm } = {}) {
+ if (confirm !== true) return fail('confirm_required', 'This action needs the Approve button on its preview.');
+ const p = preview.proposal || {};
+ const [agent] = await sql`
+ SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${preview.agent_id} AND deleted_at IS NULL`;
+ if (!agent) return fail('not_found', 'That agent no longer exists.');
+ if (agent.user_id !== preview.user_id) return fail('forbidden', 'That agent is no longer owned by this account.');
+
+ if (preview.kind === 'limits') {
+ const changes = validLimitChanges(p.changes);
+ if (!changes) return fail('validation_error', 'That limit change is not valid. Ask again with the exact numbers.');
+ const next = await setTradeLimits(agent.id, agent.user_id, changes);
+ return { ok: true, data: { limits: next } };
+ }
+
+ const network = p.network === 'devnet' ? 'devnet' : 'mainnet';
+ if (network !== 'devnet') {
+ let signed;
+ try {
+ signed = await currentSignatureFor(agent.user_id);
+ } catch {
+ return fail('agreement_check_unavailable', 'Could not verify your signed real-funds agreements, so nothing was sent. Try again in a moment.');
+ }
+ if (!signed) {
+ const req = agreementRequirement();
+ return fail('risk_ack_required', `Sign the real-funds agreements before trading real funds. Nothing was sent. Sign here: ${req.sign_url}`);
+ }
+ }
+
+ const sell = preview.kind === 'sell';
+ const amount = sell ? (Number(p.token_pct) >= 100 ? 'max' : p.token_amount) : p.sol_amount;
+ let input;
+ try {
+ input = parseTradeInput({
+ side: sell ? 'sell' : 'buy',
+ mint: p.mint,
+ amount,
+ slippageBps: p.slippage_bps,
+ network,
+ idempotency_key: `gateway:${preview.id}`,
+ }, getTradeLimits(agent.meta));
+ } catch (e) {
+ return fail(e?.code || 'validation_error', e?.message || 'That trade is not valid.');
+ }
+ const r = await executeAgentTrade({ id: agent.id, userId: agent.user_id, meta: agent.meta || {}, input, source: 'discretionary' });
+ if (!r.ok) return fail(r.code, r.message, r.detail);
+ return { ok: true, data: r.data };
+}
+
+function outcomeText(preview, result) {
+ if (!result.ok) {
+ const sig = result.detail?.signature;
+ return `Not executed: ${result.message}${sig ? `\nSignature: ${explorerTx(sig, preview.proposal?.network)}` : ''}`;
+ }
+ if (preview.kind === 'limits') return 'Done. Your risk limits are updated.';
+ const d = result.data;
+ const what = preview.kind === 'buy'
+ ? `Bought with ${fmtNum(d.sol_spent)} SOL`
+ : `Sold for about ${fmtNum(d.sol_received)} SOL`;
+ return `${what}.\nSignature: ${explorerTx(d.signature, d.network)}${d.new_balance_sol != null ? `\nWallet now holds ${fmtNum(d.new_balance_sol)} SOL.` : ''}`;
+}
+
+/**
+ * Handle one Approve or Cancel press.
+ * @param {{ gw:object, event:object, link:object|null }} ctx
+ */
+export async function handleAction({ gw, event, link }) {
+ const { verb, previewId } = event.action;
+ const preview = await getPreview(previewId);
+ if (!preview || !link || preview.link_id !== link.id) {
+ return gw.ackAction(event, 'This preview is no longer valid.');
+ }
+ if (String(event.userId) !== String(link.platform_user_id)) {
+ return gw.ackAction(event, 'Only the account owner paired to this chat can use these buttons.');
+ }
+ const ref = preview.message_ref || event.messageRef || null;
+ const base = previewText(preview.proposal);
+ const settle = async (line) => { if (ref) await gw.editMessage(ref, `${base}\n\n${line}`, { choices: [] }).catch(() => {}); };
+
+ if (verb === 'cancel') {
+ const done = await cancelPreview(preview.id);
+ await gw.ackAction(event, done ? 'Cancelled' : `Already ${preview.status}`);
+ if (done) {
+ await settle('Cancelled. Nothing was sent.');
+ await appendThreadMessage({ agentId: preview.agent_id, userId: preview.user_id, role: 'assistant', content: `Cancelled the ${preview.kind} preview. Nothing was sent.`, channel: event.platform }).catch(() => {});
+ }
+ return;
+ }
+
+ if (preview.status !== 'pending') return gw.ackAction(event, `Already ${preview.status}.`);
+ if (new Date(preview.expires_at) <= new Date()) {
+ await expirePreview(preview.id);
+ await gw.ackAction(event, 'This preview expired.');
+ return settle('Expired. Ask your agent again for a fresh quote.');
+ }
+ const rl = await limits.gatewayMessage(link.id);
+ if (!rl.success) return gw.ackAction(event, 'Too many actions. Wait a minute and press again.');
+
+ const claimed = await claimPreview(preview.id);
+ if (!claimed) return gw.ackAction(event, 'This preview was already handled.');
+ await gw.ackAction(event, 'Approved. Executing...');
+ await settle('Approved. Executing...');
+
+ let result;
+ try {
+ result = await executePreview(claimed, { confirm: true });
+ } catch (e) {
+ console.error('[gateway] preview execution crashed', e?.message);
+ result = fail('internal_error', 'Something went wrong before anything was sent. Try again.');
+ }
+ await finishPreview(preview.id, result.ok ? 'executed' : 'failed', result.ok ? result.data : { code: result.code, message: result.message, detail: result.detail });
+ const text = outcomeText(claimed, result);
+ await settle(text);
+ const signature = result.ok ? result.data?.signature : result.detail?.signature;
+ await appendThreadMessage({
+ agentId: preview.agent_id, userId: preview.user_id, role: 'assistant', content: text, channel: event.platform,
+ signatures: signature ? [signature] : [],
+ }).catch(() => {});
+ return result;
+}
diff --git a/api/_lib/gateway/codes.js b/api/_lib/gateway/codes.js
new file mode 100644
index 000000000..9b7bdc504
--- /dev/null
+++ b/api/_lib/gateway/codes.js
@@ -0,0 +1,31 @@
+// Pairing codes for the chat gateways: eight characters from an alphabet with
+// no look-alikes (no 0/O, 1/I/L, 5/S, 2/Z), shown as XXXX-XXXX. Only the sha256
+// is stored, so a read of gateway_pair_codes cannot pair anything.
+
+import { randomInt, createHash } from 'node:crypto';
+
+export const CODE_ALPHABET = 'ABCDEFGHJKMNPQRTUVWXY346789';
+export const CODE_LENGTH = 8;
+export const CODE_TTL_MINUTES = 10;
+
+export function generatePairCode() {
+ let out = '';
+ for (let i = 0; i < CODE_LENGTH; i++) out += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
+ return out;
+}
+
+/** Uppercase, strip spaces and dashes. Returns null unless it can be a code. */
+export function normalizePairCode(input) {
+ const s = String(input || '').toUpperCase().replace(/[\s-]/g, '');
+ if (s.length !== CODE_LENGTH) return null;
+ for (const ch of s) if (!CODE_ALPHABET.includes(ch)) return null;
+ return s;
+}
+
+export function formatPairCode(code) {
+ return `${code.slice(0, 4)}-${code.slice(4)}`;
+}
+
+export function hashPairCode(code) {
+ return createHash('sha256').update(`gateway-pair:${code}`).digest('hex');
+}
diff --git a/api/_lib/gateway/commands.js b/api/_lib/gateway/commands.js
new file mode 100644
index 000000000..9b140d123
--- /dev/null
+++ b/api/_lib/gateway/commands.js
@@ -0,0 +1,175 @@
+// Slash commands shared by Telegram (/balance) and Discord (/balance and
+// /three balance). Each reads the same data the web shows: the wallet card's
+// balance, the Portfolio tab, the agent's runs and its launch history.
+
+import { sql } from '../db.js';
+import { readAgentSolBalance } from '../../agents/solana-wallet.js';
+import { lamportsToUsd, listCustodyEvents } from '../agent-trade-guards.js';
+import { getPortfolio } from '../portfolio.js';
+import { queryAgentLaunches } from '../pump-agent-launches.js';
+import { listAccountAgents, pickAgent, resolveChatAgent } from './agents.js';
+import { revokeLink, resetLinkContext, setLinkDefaultAgent } from './store.js';
+import { appOrigin, agentWalletUrl, explorerTx, fmtNum, fmtUsd, short } from './format.js';
+
+export const COMMANDS = [
+ { name: 'balance', description: "Your agent wallet's SOL balance" },
+ { name: 'portfolio', description: 'Net worth and top holdings' },
+ { name: 'runs', description: 'Recent agent runs and trades' },
+ { name: 'launches', description: 'Coins your agent launched' },
+ { name: 'agents', description: 'List your agents' },
+ { name: 'use', description: 'Pick the agent this chat talks to', arg: 'agent' },
+ { name: 'new', description: 'Start a fresh conversation thread' },
+ { name: 'unlink', description: 'Disconnect this chat from your account' },
+ { name: 'link', description: 'Pair this chat with your three.ws account', arg: 'code' },
+ { name: 'help', description: 'What this bot can do' },
+];
+
+export function helpText() {
+ return [
+ 'Talk to your three.ws agent here. Just write, send a voice note, or send a photo.',
+ '',
+ ...COMMANDS.filter((c) => c.name !== 'link').map((c) => `/${c.name}${c.arg ? ` <${c.arg}>` : ''}: ${c.description}`),
+ '',
+ 'Trades never run from text alone. When your agent prepares one you get a preview with Approve and Cancel buttons; only Approve executes it, and a preview expires after ten minutes.',
+ `Manage paired chats: ${appOrigin()}/settings/connections`,
+ ].join('\n');
+}
+
+async function needAgent(link, gw, chatId) {
+ const agent = await resolveChatAgent(link);
+ if (agent) return agent;
+ const agents = await listAccountAgents(link.user_id);
+ if (!agents.length) {
+ await gw.sendText(chatId, `Your account has no agents yet. Create one at ${appOrigin()}/create, then come back and say hi.`);
+ } else {
+ await gw.sendText(chatId, `Pick which agent this chat talks to:\n${agentList(agents, null)}\n\nSend /use <number or name>.`);
+ }
+ return null;
+}
+
+function agentList(agents, currentId) {
+ return agents.map((a, i) => `${i + 1}. ${a.name || 'Untitled agent'}${a.id === currentId ? ' (current)' : ''}`).join('\n');
+}
+
+export async function cmdAgents({ gw, event, link }) {
+ const agents = await listAccountAgents(link.user_id);
+ if (!agents.length) return gw.sendText(event.chatId, `Your account has no agents yet. Create one at ${appOrigin()}/create.`);
+ const current = await resolveChatAgent(link);
+ return gw.sendText(event.chatId, `Your agents:\n${agentList(agents, current?.id)}\n\nSend /use <number or name> to switch.`);
+}
+
+export async function cmdUse({ gw, event, link }) {
+ const agents = await listAccountAgents(link.user_id);
+ if (!agents.length) return gw.sendText(event.chatId, `Your account has no agents yet. Create one at ${appOrigin()}/create.`);
+ const pick = pickAgent(agents, event.args);
+ if (!pick) return gw.sendText(event.chatId, `No agent matches "${String(event.args || '').slice(0, 60)}". Your agents:\n${agentList(agents, link.default_agent_id)}`);
+ await setLinkDefaultAgent(link.id, pick.id);
+ return gw.sendText(event.chatId, `This chat now talks to ${pick.name || 'your agent'}.`);
+}
+
+export async function cmdUnlink({ gw, event, link }) {
+ await revokeLink(link.id, link.user_id);
+ return gw.sendText(event.chatId, 'Unlinked. This chat no longer talks to your three.ws account, and any open trade previews were cancelled. Send /start to pair again.');
+}
+
+export async function cmdNew({ gw, event, link }) {
+ await resetLinkContext(link.id);
+ return gw.sendText(event.chatId, 'Started a fresh thread. Your agent will not see earlier messages here; the full history stays on the web.');
+}
+
+export async function cmdBalance({ gw, event, link }) {
+ const agent = await needAgent(link, gw, event.chatId);
+ if (!agent) return;
+ const address = agent.meta?.solana_address;
+ if (!address) return gw.sendText(event.chatId, `${agent.name} has no wallet yet. Open ${agentWalletUrl(agent.id)} to create it.`);
+ const { lamports, error } = await readAgentSolBalance(address, 'mainnet');
+ if (lamports == null) {
+ const why = error === 'rpc_rate_limited' ? 'the Solana RPC is rate limiting right now' : 'the Solana RPC did not answer';
+ return gw.sendText(event.chatId, `Balance unavailable: ${why}. Try again in a minute.`);
+ }
+ const usd = await lamportsToUsd(lamports).catch(() => null);
+ return gw.sendText(event.chatId, [
+ `${agent.name} wallet (Solana mainnet)`,
+ `${fmtNum(lamports / 1e9, 6)} SOL${usd != null ? ` (about ${fmtUsd(usd)})` : ''}`,
+ `Address: ${address}`,
+ agentWalletUrl(agent.id),
+ ].join('\n'));
+}
+
+export async function cmdPortfolio({ gw, event, link }) {
+ const agent = await needAgent(link, gw, event.chatId);
+ if (!agent) return;
+ if (!agent.meta?.solana_address) return gw.sendText(event.chatId, `${agent.name} has no wallet yet. Open ${agentWalletUrl(agent.id)} to create it.`);
+ const p = await getPortfolio({ agentId: agent.id, network: 'mainnet' });
+ if (!p) return gw.sendText(event.chatId, 'Portfolio unavailable right now. Try again in a minute.');
+ const top = (p.holdings || []).slice(0, 6).map((h) => {
+ const label = h.isNative ? 'SOL' : (h.symbol || short(h.mint));
+ const value = h.usd_value != null ? ` (${fmtUsd(h.usd_value)})` : '';
+ const pnl = h.unrealized_pct != null ? `, ${h.unrealized_pct >= 0 ? '+' : ''}${fmtNum(h.unrealized_pct, 1)}%` : '';
+ return `- ${label}: ${fmtNum(h.amount, 4)}${value}${pnl}`;
+ });
+ return gw.sendText(event.chatId, [
+ `${agent.name} portfolio`,
+ `Net worth: ${fmtNum(p.net_worth?.sol, 4)} SOL${p.net_worth?.usd != null ? ` (${fmtUsd(p.net_worth.usd)})` : ''}`,
+ top.length ? top.join('\n') : 'No holdings yet.',
+ (p.risk_flags || []).length ? `Flags: ${p.risk_flags.map((f) => f.label || f.code || f).join(', ')}` : null,
+ agentWalletUrl(agent.id, 'portfolio'),
+ ].filter(Boolean).join('\n'));
+}
+
+async function recentRuns(agentId) {
+ // agent_runs arrives with the v1 Agents API; until that migration is applied
+ // the section is simply absent rather than an error.
+ const [t] = await sql`SELECT to_regclass('public.agent_runs') AS t`;
+ if (!t?.t) return [];
+ return sql`
+ SELECT id, goal, status, step_count, created_at FROM agent_runs
+ WHERE agent_id = ${agentId} ORDER BY created_at DESC LIMIT 5`;
+}
+
+export async function cmdRuns({ gw, event, link }) {
+ const agent = await needAgent(link, gw, event.chatId);
+ if (!agent) return;
+ const [runs, trades] = await Promise.all([
+ recentRuns(agent.id),
+ listCustodyEvents(agent.id, { limit: 5, category: 'trade', network: 'mainnet' }).catch(() => []),
+ ]);
+ const lines = [`${agent.name}: recent activity`];
+ if (runs.length) {
+ lines.push('', 'Runs:');
+ for (const r of runs) lines.push(`- ${r.status}: ${String(r.goal).slice(0, 80)} (${r.step_count} steps)`);
+ }
+ const tradeRows = trades;
+ if (tradeRows.length) {
+ lines.push('', 'Trades:');
+ for (const e of tradeRows) {
+ const side = e.meta?.side || e.reason || 'trade';
+ const sig = e.signature ? ` ${explorerTx(e.signature, e.network)}` : '';
+ lines.push(`- ${side} ${e.meta?.mint ? short(e.meta.mint) : e.asset}: ${e.status}${sig}`);
+ }
+ }
+ if (!runs.length && !tradeRows.length) lines.push('No runs or trades yet. Ask your agent to do something, or start a run from the web.');
+ lines.push('', agentWalletUrl(agent.id, 'trade'));
+ return gw.sendText(event.chatId, lines.join('\n'));
+}
+
+export async function cmdLaunches({ gw, event, link }) {
+ const agent = await needAgent(link, gw, event.chatId);
+ if (!agent) return;
+ const { launches } = await queryAgentLaunches({ agentId: agent.id, limit: 5 });
+ if (!launches?.length) return gw.sendText(event.chatId, `${agent.name} has not launched a coin yet.`);
+ const lines = [`${agent.name}: launches`];
+ for (const l of launches) lines.push(`- ${l.name || 'Untitled'}${l.symbol ? ` (${l.symbol})` : ''}: ${appOrigin()}/launches/${l.mint}`);
+ return gw.sendText(event.chatId, lines.join('\n'));
+}
+
+export const COMMAND_HANDLERS = {
+ agents: cmdAgents,
+ use: cmdUse,
+ unlink: cmdUnlink,
+ new: cmdNew,
+ balance: cmdBalance,
+ portfolio: cmdPortfolio,
+ runs: cmdRuns,
+ launches: cmdLaunches,
+};
diff --git a/api/_lib/gateway/conversation.js b/api/_lib/gateway/conversation.js
new file mode 100644
index 000000000..42a59eda4
--- /dev/null
+++ b/api/_lib/gateway/conversation.js
@@ -0,0 +1,144 @@
+// One chat message -> one copilot turn, delivered back to the chat.
+//
+// The turn is the same one the web copilot runs (api/_lib/copilot-engine.js)
+// over the agent's cross-channel thread (api/_lib/agent-thread.js), so a
+// conversation started on the web continues here and the other way round. While
+// the agent works, the chat shows a typing indicator and one compact status
+// line ("working: get_quote") edited in place. Every trade or limit change the
+// agent proposes becomes a preview with Approve and Cancel buttons; nothing in
+// the reply text can execute one.
+
+import { runCopilotTurn } from '../copilot-engine.js';
+import { appendThreadMessage, threadHistoryForModel } from '../agent-thread.js';
+import { resolveChatAgent, listAccountAgents } from './agents.js';
+import { createPreview, setPreviewMessageRef, PREVIEW_TTL_MINUTES } from './store.js';
+import { chunkText, describeProposal, plainText, MAX_TEXT, PLATFORM_LABEL, appOrigin } from './format.js';
+
+export const APPROVE = 'gw:ap:';
+export const CANCEL = 'gw:cx:';
+const TYPING_EVERY_MS = 4500;
+
+function surfaceNote(platform) {
+ const where = PLATFORM_LABEL[platform] || platform;
+ return [
+ `SURFACE: you are replying in a ${where} chat with your owner. Write plain text: no tables, no headings, no code blocks. Keep it short.`,
+ 'Every propose_* card you surface reaches the owner as a preview message with Approve and Cancel buttons. Tell them to press Approve to execute it or Cancel to discard it, and that it expires in ten minutes. Never claim a trade happened.',
+ ].join('\n');
+}
+
+/** Keep the platform's typing indicator alive until stop() is called. */
+function keepTyping(gw, chatId) {
+ let stopped = false;
+ const tick = () => { if (!stopped) Promise.resolve(gw.typing(chatId)).catch(() => {}); };
+ tick();
+ const timer = setInterval(tick, TYPING_EVERY_MS);
+ return () => { stopped = true; clearInterval(timer); };
+}
+
+/**
+ * The status line: sent on the first tool call, edited on every one after, and
+ * left behind as a compact record of what the agent looked at.
+ */
+function statusLine(gw, chatId) {
+ let ref = null;
+ let chain = Promise.resolve();
+ const used = [];
+ const put = (text) => {
+ chain = chain.then(async () => {
+ if (ref) await gw.editMessage(ref, text);
+ else ref = await gw.sendText(chatId, text);
+ }).catch(() => {});
+ };
+ return {
+ working(name) {
+ if (!used.includes(name)) used.push(name);
+ put(`working: ${name}`);
+ },
+ async finish() {
+ if (used.length) put(`used: ${used.join(', ')}`);
+ await chain;
+ },
+ };
+}
+
+function choicesFor(preview, proposal) {
+ const blocked = proposal.kind === 'buy' && proposal.safety?.verdict === 'block';
+ const unpriced = (proposal.kind === 'buy' || proposal.kind === 'sell') && (!proposal.quote || proposal.quote.error);
+ if (blocked || unpriced) return [{ id: `${CANCEL}${preview.id}`, label: 'Dismiss', style: 'secondary' }];
+ return [
+ { id: `${APPROVE}${preview.id}`, label: 'Approve', style: 'primary' },
+ { id: `${CANCEL}${preview.id}`, label: 'Cancel', style: 'danger' },
+ ];
+}
+
+export function previewText(proposal) {
+ const blocked = proposal.kind === 'buy' && proposal.safety?.verdict === 'block';
+ const tail = blocked
+ ? 'The safety firewall blocked this buy, so it cannot be approved.'
+ : `Approve to execute, Cancel to discard. Expires in ${PREVIEW_TTL_MINUTES} minutes.`;
+ return `${describeProposal(proposal)}\n\n${tail}`;
+}
+
+async function sendPreviews({ gw, event, link, agent, proposals }) {
+ for (const p of proposals) {
+ const preview = await createPreview({ linkId: link.id, userId: link.user_id, agentId: agent.id, kind: p.kind, proposal: p });
+ const ref = await gw.sendChoice(event.chatId, previewText(p), choicesFor(preview, p));
+ if (ref) await setPreviewMessageRef(preview.id, ref);
+ }
+}
+
+async function sendReply(gw, chatId, text) {
+ for (const part of chunkText(text, MAX_TEXT[gw.platform] || 1900)) await gw.sendText(chatId, part);
+}
+
+/**
+ * Run one turn for `text` in a paired chat.
+ * @param {{ gw:object, event:object, link:object, text:string }} ctx
+ */
+export async function converse({ gw, event, link, text }) {
+ const agent = await resolveChatAgent(link);
+ if (!agent) {
+ const agents = await listAccountAgents(link.user_id);
+ return gw.sendText(event.chatId, agents.length
+ ? 'Pick which agent this chat talks to first: send /agents, then /use <number>.'
+ : `Your account has no agents yet. Create one at ${appOrigin()}/create, then come back and say hi.`);
+ }
+
+ const channel = event.platform;
+ const history = await threadHistoryForModel({ agentId: agent.id, userId: link.user_id, since: link.context_reset_at, limit: 23 });
+ history.push({ role: 'user', content: text.slice(0, 4000) });
+ await appendThreadMessage({ agentId: agent.id, userId: link.user_id, role: 'user', content: text, channel });
+
+ const stopTyping = keepTyping(gw, event.chatId);
+ const status = statusLine(gw, event.chatId);
+ let turn;
+ try {
+ turn = await runCopilotTurn({
+ agent,
+ history,
+ network: 'mainnet',
+ surfaceNote: surfaceNote(event.platform),
+ emit: (name, data) => { if (name === 'tool_start') status.working(data.name); },
+ });
+ } catch (e) {
+ stopTyping();
+ await status.finish();
+ const msg = e?.code === 'llm_unavailable'
+ ? 'Your agent cannot think right now: no language model is reachable. Try again shortly.'
+ : 'Your agent hit an error answering that. Try again in a moment.';
+ console.error('[gateway] turn failed', e?.message);
+ return gw.sendText(event.chatId, msg);
+ }
+ stopTyping();
+ await status.finish();
+
+ const reply = plainText(turn.reply) || (turn.proposals.length ? 'Here is what I prepared:' : 'I have nothing to add to that.');
+ await sendReply(gw, event.chatId, reply);
+ if (turn.proposals.length) await sendPreviews({ gw, event, link, agent, proposals: turn.proposals });
+
+ await appendThreadMessage({
+ agentId: agent.id, userId: link.user_id, role: 'assistant', content: turn.reply || reply, channel,
+ toolCalls: turn.toolCalls,
+ });
+ return turn;
+}
diff --git a/api/_lib/gateway/core.js b/api/_lib/gateway/core.js
new file mode 100644
index 000000000..e19617e6f
--- /dev/null
+++ b/api/_lib/gateway/core.js
@@ -0,0 +1,140 @@
+// The chat gateway core: one platform-neutral handler for every inbound chat
+// event, driven by a platform adapter (workers/agent-gateway/src/telegram.js,
+// workers/agent-gateway/src/discord.js).
+//
+// An adapter turns platform updates into events and implements the Gateway
+// interface below; everything else (pairing, commands, conversation, previews,
+// approvals) lives here, so Telegram and Discord behave identically.
+//
+// @typedef {object} GatewayEvent
+// @property {'telegram'|'discord'} platform
+// @property {string} chatId the chat, DM channel or guild channel
+// @property {string} [chatType] private | group | supergroup | dm | guild
+// @property {string} [chatTitle]
+// @property {string} userId the platform user who sent it
+// @property {string} [username]
+// @property {string} [text] a plain message
+// @property {string} [command] a slash command, lowercased, without the slash
+// @property {string} [args] everything after the command
+// @property {{ verb:'approve'|'cancel', previewId:string }} [action] a button press
+// @property {{ fetch:() => Promise<{buffer:Buffer, mimeType:string}> }} [voice]
+// @property {{ fetch:() => Promise<{buffer:Buffer, mimeType:string}>, caption?:string }} [photo]
+// @property {object} [messageRef] the pressed message, for button events
+//
+// @typedef {object} Gateway
+// @property {'telegram'|'discord'} platform
+// @property {(chatId:string, text:string) => Promise<object>} sendText returns a message ref
+// @property {(chatId:string, text:string, choices:{id:string,label:string,style?:string}[]) => Promise<object>} sendChoice
+// @property {(ref:object, text:string, opts?:{choices?:object[]}) => Promise<void>} editMessage choices [] removes buttons
+// @property {(chatId:string, media:{url:string, caption?:string}) => Promise<object>} sendMedia
+// @property {(chatId:string) => Promise<void>} typing
+// @property {(event:GatewayEvent, text?:string) => Promise<void>} ackAction answer a button press
+
+import { limits } from '../rate-limit.js';
+import { getLiveLink, touchLink, issueChatCode, redeemSiteCode, GatewayError } from './store.js';
+import { normalizePairCode, formatPairCode } from './codes.js';
+import { COMMAND_HANDLERS, helpText } from './commands.js';
+import { converse } from './conversation.js';
+import { handleAction } from './approvals.js';
+import { transcribeVoice, describePhoto, MediaError } from './media.js';
+import { appOrigin } from './format.js';
+
+function identityOf(event) {
+ return {
+ platform: event.platform,
+ platformUserId: String(event.userId),
+ platformUsername: event.username || null,
+ chatId: String(event.chatId),
+ chatType: event.chatType || null,
+ chatTitle: event.chatTitle || null,
+ };
+}
+
+async function pairingPrompt(gw, event) {
+ const rl = await limits.gatewayPair(`${event.platform}:${event.chatId}`);
+ if (!rl.success) return gw.sendText(event.chatId, 'Too many pairing codes for this chat. Wait an hour, or generate a code on the site and send /link <code> here.');
+ const { code, expiresInMinutes } = await issueChatCode(identityOf(event));
+ const pretty = formatPairCode(code);
+ return gw.sendText(event.chatId, [
+ 'Connect this chat to your three.ws agent.',
+ '',
+ `Your pairing code: ${pretty}`,
+ `Open ${appOrigin()}/settings/connections?code=${code}`,
+ `sign in, and confirm. The code expires in ${expiresInMinutes} minutes.`,
+ '',
+ `Already on the site? Generate a code there and send /link <code> here instead.`,
+ ].join('\n'));
+}
+
+async function cmdLink({ gw, event, link }) {
+ const code = normalizePairCode(event.args);
+ if (!code) {
+ if (link) return gw.sendText(event.chatId, `This chat is already paired. Send /help to see what you can do, or /unlink to disconnect.`);
+ return pairingPrompt(gw, event);
+ }
+ try {
+ await redeemSiteCode({ code, identity: identityOf(event) });
+ } catch (e) {
+ if (e instanceof GatewayError) return gw.sendText(event.chatId, e.message);
+ throw e;
+ }
+ return gw.sendText(event.chatId, `Paired. This chat now talks to your three.ws account.\n\n${helpText()}`);
+}
+
+async function textFromMedia(gw, event) {
+ try {
+ if (event.voice) {
+ const { buffer, mimeType } = await event.voice.fetch();
+ const heard = await transcribeVoice({ buffer, mimeType });
+ await gw.sendText(event.chatId, `Heard: "${heard}"`);
+ return heard;
+ }
+ const { buffer, mimeType } = await event.photo.fetch();
+ return await describePhoto({ buffer, mimeType, caption: event.photo.caption || '' });
+ } catch (e) {
+ if (e instanceof MediaError) {
+ await gw.sendText(event.chatId, e.message);
+ return null;
+ }
+ console.error('[gateway] media failed', e?.code || e?.message);
+ await gw.sendText(event.chatId, event.voice
+ ? 'I could not transcribe that voice note. Try again, or type it.'
+ : 'I could not read that photo. Try again, or describe it in text.');
+ return null;
+ }
+}
+
+/**
+ * Handle one inbound chat event end to end.
+ * @param {GatewayEvent} event
+ * @param {Gateway} gw
+ */
+export async function handleEvent(event, gw) {
+ const link = await getLiveLink(event.platform, event.chatId);
+
+ if (event.action) return handleAction({ gw, event, link });
+ if (event.command === 'start' || event.command === 'link') return cmdLink({ gw, event, link });
+ if (event.command === 'help') return gw.sendText(event.chatId, link ? helpText() : `${helpText()}\n\nThis chat is not paired yet: send /start to get a pairing code.`);
+
+ if (!link) return pairingPrompt(gw, event);
+
+ // A paired group chat still belongs to one person: everyone else is told so,
+ // and never reaches the owner's agent or wallet.
+ if (String(event.userId) !== String(link.platform_user_id)) {
+ return gw.sendText(event.chatId, 'This chat is paired to another person\'s three.ws account. Only they can talk to the agent here.');
+ }
+
+ const rl = await limits.gatewayMessage(link.id);
+ if (!rl.success) return gw.sendText(event.chatId, 'You are sending messages faster than your agent can answer. Wait a minute and try again.');
+ await touchLink(link.id);
+
+ if (event.command) {
+ const run = COMMAND_HANDLERS[event.command];
+ if (run) return run({ gw, event, link });
+ return gw.sendText(event.chatId, `Unknown command /${event.command}. Send /help for the list.`);
+ }
+
+ const text = event.voice || event.photo ? await textFromMedia(gw, event) : String(event.text || '').trim();
+ if (!text) return;
+ return converse({ gw, event, link, text });
+}
diff --git a/api/_lib/gateway/format.js b/api/_lib/gateway/format.js
new file mode 100644
index 000000000..bc822cc57
--- /dev/null
+++ b/api/_lib/gateway/format.js
@@ -0,0 +1,106 @@
+// Plain-text rendering for chat replies. Both platforms get the same text:
+// Telegram is sent without a parse mode (nothing to escape, links auto-link)
+// and Discord renders it as-is, so one formatter serves both.
+
+import { env } from '../env.js';
+
+export const PLATFORM_LABEL = { telegram: 'Telegram', discord: 'Discord', web: 'the web', api: 'the API' };
+export const MAX_TEXT = { telegram: 4000, discord: 1900 };
+
+export function appOrigin() {
+ return env.APP_ORIGIN || 'https://three.ws';
+}
+
+export function short(s, head = 4, tail = 4) {
+ const v = String(s || '');
+ return v.length <= head + tail + 1 ? v : `${v.slice(0, head)}...${v.slice(-tail)}`;
+}
+
+export function fmtNum(n, max = 4) {
+ if (n == null || !Number.isFinite(Number(n))) return 'n/a';
+ return Number(n).toLocaleString('en-US', { maximumFractionDigits: max });
+}
+
+export function fmtUsd(n) {
+ if (n == null || !Number.isFinite(Number(n))) return null;
+ return `$${Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+}
+
+export function explorerTx(signature, network = 'mainnet') {
+ return network === 'devnet'
+ ? `https://explorer.solana.com/tx/${signature}?cluster=devnet`
+ : `https://solscan.io/tx/${signature}`;
+}
+
+export function agentWalletUrl(agentId, tab = '') {
+ return `${appOrigin()}/agents/${agentId}/wallet${tab ? `#${tab}` : ''}`;
+}
+
+/**
+ * Split text into platform-sized chunks on paragraph, then line, then word
+ * boundaries, so a long reply arrives as several readable messages.
+ */
+export function chunkText(text, limit) {
+ const out = [];
+ let rest = String(text || '').trim();
+ while (rest.length > limit) {
+ let cut = rest.lastIndexOf('\n\n', limit);
+ if (cut < limit * 0.5) cut = rest.lastIndexOf('\n', limit);
+ if (cut < limit * 0.5) cut = rest.lastIndexOf(' ', limit);
+ if (cut < limit * 0.5) cut = limit;
+ out.push(rest.slice(0, cut).trim());
+ rest = rest.slice(cut).trim();
+ }
+ if (rest) out.push(rest);
+ return out;
+}
+
+/** The agent's markdown, flattened for a chat that renders plain text. */
+export function plainText(md) {
+ return String(md || '')
+ .replace(/\*\*(.+?)\*\*/g, '$1')
+ .replace(/__(.+?)__/g, '$1')
+ .replace(/`([^`]+)`/g, '$1')
+ .replace(/^#{1,6}\s+/gm, '')
+ .replace(/\[([^\]]+)\]\((https?:[^)]+)\)/g, '$1: $2');
+}
+
+/** A proposal card as chat text. */
+export function describeProposal(p) {
+ const coin = p.coin?.symbol ? `${p.coin.symbol} (${short(p.mint)})` : short(p.mint, 6, 6);
+ const lines = [];
+ if (p.kind === 'buy') {
+ lines.push(`Buy preview on ${p.network}`);
+ lines.push(`Spend: ${fmtNum(p.sol_amount)} SOL`);
+ lines.push(`Token: ${coin}`);
+ if (p.quote && !p.quote.error) {
+ lines.push(`Expected: ${fmtNum(p.quote.expected_out, 2)} tokens (at least ${fmtNum(p.quote.min_received, 2)})`);
+ lines.push(`Price impact: ${p.quote.price_impact_pct != null ? `${fmtNum(p.quote.price_impact_pct, 2)}%` : 'n/a'}`);
+ } else {
+ lines.push(`Quote: unavailable (${p.quote?.error || 'no market'})`);
+ }
+ if (p.safety) lines.push(`Firewall: ${String(p.safety.verdict).toUpperCase()} ${p.safety.score}/100${p.safety.reasons?.[0] ? `, ${p.safety.reasons[0]}` : ''}`);
+ lines.push(`Slippage: ${fmtNum(p.slippage_bps / 100, 2)}%`);
+ } else if (p.kind === 'sell') {
+ lines.push(`Sell preview on ${p.network}`);
+ lines.push(`Sell: ${fmtNum(p.token_amount, 4)} tokens${p.token_pct ? ` (${fmtNum(p.token_pct, 2)}% of holding)` : ''}`);
+ lines.push(`Token: ${coin}`);
+ if (p.quote && !p.quote.error) {
+ lines.push(`Expected: ${fmtNum(p.quote.expected_out)} SOL (at least ${fmtNum(p.quote.min_received)})`);
+ lines.push(`Price impact: ${p.quote.price_impact_pct != null ? `${fmtNum(p.quote.price_impact_pct, 2)}%` : 'n/a'}`);
+ } else {
+ lines.push(`Quote: unavailable (${p.quote?.error || 'no market'})`);
+ }
+ lines.push(`Slippage: ${fmtNum(p.slippage_bps / 100, 2)}%`);
+ } else if (p.kind === 'limits') {
+ lines.push('Risk limit change');
+ for (const [k, v] of Object.entries(p.changes || {})) {
+ const label = { per_trade_sol: 'Per-trade cap', daily_budget_sol: 'Daily budget', max_price_impact_pct: 'Max price impact', kill_switch: 'Kill switch' }[k] || k;
+ const unit = k.endsWith('_sol') ? ' SOL' : k.endsWith('_pct') ? '%' : '';
+ const shown = typeof v === 'boolean' ? (v ? 'ON (trading paused)' : 'off') : `${fmtNum(v)}${unit}`;
+ lines.push(`${label}: ${shown}`);
+ }
+ }
+ if (p.rationale) lines.push(`Why: ${p.rationale}`);
+ return lines.join('\n');
+}
diff --git a/api/_lib/gateway/media.js b/api/_lib/gateway/media.js
new file mode 100644
index 000000000..8aeda8c1a
--- /dev/null
+++ b/api/_lib/gateway/media.js
@@ -0,0 +1,51 @@
+// Voice notes and photos sent to a chat gateway become text the agent can read.
+// Voice runs through the same NVIDIA Riva speech path as POST /api/asr; photos
+// run through the same vision chain as POST /api/vision.
+
+import { transcribeNvidiaAsr, nvidiaAsrConfigured } from '../asr-nvidia.js';
+import { describeImage, visionConfigured } from '../vision.js';
+
+export const MAX_VOICE_BYTES = 8 * 1024 * 1024;
+export const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
+
+export class MediaError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+/**
+ * Transcribe a chat voice note. Telegram and Discord both deliver Ogg/Opus at
+ * 48 kHz, which Riva accepts directly (no transcode).
+ * @returns {Promise<string>}
+ */
+export async function transcribeVoice({ buffer, mimeType = 'audio/ogg', language = 'en-US' }) {
+ if (!nvidiaAsrConfigured()) throw new MediaError('asr_unavailable', 'Voice notes are not available right now. Type your message instead.');
+ if (!buffer?.length) throw new MediaError('empty_audio', 'That voice note was empty.');
+ if (buffer.length > MAX_VOICE_BYTES) throw new MediaError('audio_too_large', 'That voice note is too long. Keep it under about five minutes.');
+ const encoding = /ogg|opus/i.test(mimeType) ? 'OGGOPUS' : /flac/i.test(mimeType) ? 'FLAC' : 'OGGOPUS';
+ const out = await transcribeNvidiaAsr({ audio: buffer, encoding, sampleRateHz: 48000, language });
+ const text = String(out?.text || '').trim();
+ if (!text) throw new MediaError('no_speech', 'I could not make out any words in that voice note.');
+ return text;
+}
+
+/**
+ * Describe a photo so the agent can reason about it. The caption, when the
+ * owner sent one, is what they asked; the description is what the image shows.
+ * @returns {Promise<string>} a message for the agent
+ */
+export async function describePhoto({ buffer, mimeType = 'image/jpeg', caption = '' }) {
+ if (!visionConfigured()) throw new MediaError('vision_unavailable', 'Photos are not available right now. Describe it in text instead.');
+ if (!buffer?.length) throw new MediaError('empty_image', 'That photo was empty.');
+ if (buffer.length > MAX_IMAGE_BYTES) throw new MediaError('image_too_large', 'That photo is too large. Send one under 8 MB.');
+ const prompt = caption
+ ? `The user sent this image with the message: "${caption.slice(0, 500)}". Describe what the image shows that is relevant to that message. Transcribe any visible text, numbers, token names or addresses exactly.`
+ : 'Describe this image in a few sentences. Transcribe any visible text, numbers, token names or addresses exactly.';
+ const out = await describeImage({ prompt, imageBase64: buffer.toString('base64'), mimeType, maxTokens: 400 });
+ const description = String(out?.text || '').trim();
+ return caption
+ ? `${caption}\n\n[Attached image: ${description}]`
+ : `[The user sent an image: ${description}]`;
+}
diff --git a/api/_lib/gateway/store.js b/api/_lib/gateway/store.js
new file mode 100644
index 000000000..605fd8fbc
--- /dev/null
+++ b/api/_lib/gateway/store.js
@@ -0,0 +1,285 @@
+// Persistence for the chat gateways: paired chats, pairing codes, the webhook
+// inbox and financial previews. Tables: 20260922180000_chat_gateways.sql.
+
+import { sql } from '../db.js';
+import { generatePairCode, hashPairCode, CODE_TTL_MINUTES } from './codes.js';
+
+export const PREVIEW_TTL_MINUTES = 10;
+
+export class GatewayError extends Error {
+ constructor(code, message, status = 400) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+
+// ── links ────────────────────────────────────────────────────────────────────
+
+export async function getLiveLink(platform, chatId) {
+ const [row] = await sql`
+ SELECT * FROM gateway_links
+ WHERE platform = ${platform} AND chat_id = ${String(chatId)} AND revoked_at IS NULL
+ LIMIT 1`;
+ return row || null;
+}
+
+export async function getLinkById(id) {
+ const [row] = await sql`SELECT * FROM gateway_links WHERE id = ${id} LIMIT 1`;
+ return row || null;
+}
+
+export async function listLinksForUser(userId) {
+ return sql`
+ SELECT l.id, l.platform, l.platform_username, l.chat_id, l.chat_type, l.chat_title,
+ l.default_agent_id, a.name AS default_agent_name, l.notify, l.created_at, l.last_seen_at
+ FROM gateway_links l
+ LEFT JOIN agent_identities a ON a.id = l.default_agent_id AND a.deleted_at IS NULL
+ WHERE l.user_id = ${userId} AND l.revoked_at IS NULL
+ ORDER BY l.created_at DESC`;
+}
+
+export async function listNotifyLinks(userId) {
+ return sql`
+ SELECT id, platform, chat_id FROM gateway_links
+ WHERE user_id = ${userId} AND revoked_at IS NULL AND notify = true`;
+}
+
+/**
+ * Pair a chat to an account. A chat already paired to the same account returns
+ * that link unchanged; a chat paired to another account is refused, so one chat
+ * can never drive two accounts.
+ */
+export async function createLink({ platform, platformUserId, platformUsername = null, chatId, chatType = null, chatTitle = null, userId }) {
+ const existing = await getLiveLink(platform, chatId);
+ if (existing) {
+ if (existing.user_id !== userId) throw new GatewayError('chat_taken', 'This chat is already paired to a different three.ws account. Send /unlink from that account first.', 409);
+ return existing;
+ }
+ try {
+ const [row] = await sql`
+ INSERT INTO gateway_links (platform, platform_user_id, platform_username, chat_id, chat_type, chat_title, user_id, last_seen_at)
+ VALUES (${platform}, ${String(platformUserId)}, ${platformUsername}, ${String(chatId)}, ${chatType}, ${chatTitle}, ${userId}, now())
+ RETURNING *`;
+ return row;
+ } catch (e) {
+ // Two redemptions raced for the same chat: the unique live-link index lets
+ // exactly one win. Re-read to report the winner honestly.
+ if (e?.code === '23505') {
+ const won = await getLiveLink(platform, chatId);
+ if (won && won.user_id === userId) return won;
+ throw new GatewayError('chat_taken', 'This chat is already paired to a different three.ws account.', 409);
+ }
+ throw e;
+ }
+}
+
+export async function revokeLink(linkId, userId) {
+ const [row] = await sql`
+ UPDATE gateway_links SET revoked_at = now()
+ WHERE id = ${linkId} AND user_id = ${userId} AND revoked_at IS NULL
+ RETURNING id, platform, chat_id`;
+ if (row) {
+ await sql`
+ UPDATE gateway_previews SET status = 'cancelled', decided_at = now()
+ WHERE link_id = ${linkId} AND status = 'pending'`;
+ }
+ return row || null;
+}
+
+export async function setLinkDefaultAgent(linkId, agentId) {
+ await sql`UPDATE gateway_links SET default_agent_id = ${agentId} WHERE id = ${linkId}`;
+}
+
+export async function setLinkNotify(linkId, userId, notify) {
+ const [row] = await sql`
+ UPDATE gateway_links SET notify = ${!!notify}
+ WHERE id = ${linkId} AND user_id = ${userId} AND revoked_at IS NULL
+ RETURNING id, notify`;
+ return row || null;
+}
+
+export async function resetLinkContext(linkId) {
+ await sql`UPDATE gateway_links SET context_reset_at = now() WHERE id = ${linkId}`;
+}
+
+export async function touchLink(linkId) {
+ await sql`UPDATE gateway_links SET last_seen_at = now() WHERE id = ${linkId}`;
+}
+
+// ── pairing codes ────────────────────────────────────────────────────────────
+
+/** The bot printed a code in a chat; the owner redeems it on the site. */
+export async function issueChatCode({ platform, platformUserId, platformUsername = null, chatId, chatType = null, chatTitle = null }) {
+ // One live code per chat: a fresh /start supersedes the last one.
+ await sql`
+ DELETE FROM gateway_pair_codes
+ WHERE origin = 'chat' AND platform = ${platform} AND chat_id = ${String(chatId)} AND redeemed_at IS NULL`;
+ const code = generatePairCode();
+ await sql`
+ INSERT INTO gateway_pair_codes (code_hash, origin, platform, platform_user_id, platform_username, chat_id, chat_type, chat_title, expires_at)
+ VALUES (${hashPairCode(code)}, 'chat', ${platform}, ${String(platformUserId)}, ${platformUsername}, ${String(chatId)}, ${chatType}, ${chatTitle},
+ now() + make_interval(mins => ${CODE_TTL_MINUTES}))`;
+ return { code, expiresInMinutes: CODE_TTL_MINUTES };
+}
+
+/** The site generated a code for a signed-in owner to paste into a chat. */
+export async function issueSiteCode(userId) {
+ await sql`
+ DELETE FROM gateway_pair_codes
+ WHERE origin = 'site' AND user_id = ${userId} AND redeemed_at IS NULL`;
+ const code = generatePairCode();
+ const [row] = await sql`
+ INSERT INTO gateway_pair_codes (code_hash, origin, user_id, expires_at)
+ VALUES (${hashPairCode(code)}, 'site', ${userId}, now() + make_interval(mins => ${CODE_TTL_MINUTES}))
+ RETURNING expires_at`;
+ return { code, expiresAt: row.expires_at, expiresInMinutes: CODE_TTL_MINUTES };
+}
+
+async function loadLiveCode(code, origin) {
+ const [row] = await sql`
+ SELECT * FROM gateway_pair_codes WHERE code_hash = ${hashPairCode(code)} AND origin = ${origin} LIMIT 1`;
+ if (!row) throw new GatewayError('code_invalid', 'That code was not recognised. Codes are eight characters, like ABCD-EFGH.', 404);
+ if (row.redeemed_at) throw new GatewayError('code_used', 'That code was already used. Ask for a new one.', 410);
+ if (new Date(row.expires_at) <= new Date()) throw new GatewayError('code_expired', 'That code expired. Codes last ten minutes; ask for a new one.', 410);
+ return row;
+}
+
+async function consumeCode(id, { userId, linkId }) {
+ const [row] = await sql`
+ UPDATE gateway_pair_codes SET redeemed_at = now(), user_id = COALESCE(user_id, ${userId}), link_id = ${linkId}
+ WHERE id = ${id} AND redeemed_at IS NULL AND expires_at > now()
+ RETURNING id`;
+ if (!row) throw new GatewayError('code_used', 'That code was just used. Ask for a new one.', 410);
+}
+
+/** Site side: a signed-in owner redeems a code the bot printed. */
+export async function redeemChatCode({ code, userId }) {
+ const row = await loadLiveCode(code, 'chat');
+ const existing = await getLiveLink(row.platform, row.chat_id);
+ if (existing && existing.user_id !== userId) {
+ throw new GatewayError('chat_taken', 'That chat is already paired to a different three.ws account. Send /unlink in the chat from that account first.', 409);
+ }
+ const link = existing || await createLink({
+ platform: row.platform, platformUserId: row.platform_user_id, platformUsername: row.platform_username,
+ chatId: row.chat_id, chatType: row.chat_type, chatTitle: row.chat_title, userId,
+ });
+ await consumeCode(row.id, { userId, linkId: link.id });
+ return link;
+}
+
+/** Chat side: the bot receives a code the owner generated on the site. */
+export async function redeemSiteCode({ code, identity }) {
+ const row = await loadLiveCode(code, 'site');
+ const link = await createLink({ ...identity, userId: row.user_id });
+ await consumeCode(row.id, { userId: row.user_id, linkId: link.id });
+ return link;
+}
+
+// ── webhook inbox ────────────────────────────────────────────────────────────
+
+/** @returns {Promise<boolean>} false when this delivery was already queued (a platform retry). */
+export async function enqueueInbox({ platform, dedupeKey, chatKey, payload }) {
+ const rows = await sql`
+ INSERT INTO gateway_inbox (platform, dedupe_key, chat_key, payload)
+ VALUES (${platform}, ${String(dedupeKey)}, ${String(chatKey)}, ${JSON.stringify(payload)}::jsonb)
+ ON CONFLICT (platform, dedupe_key) DO NOTHING
+ RETURNING id`;
+ return rows.length > 0;
+}
+
+/**
+ * Claim up to `limit` deliveries, at most one per chat, and only the oldest open
+ * delivery of a chat whose previous delivery is not still being processed, so a
+ * chat's replies always come back in the order its messages were sent.
+ */
+export async function claimInbox({ limit = 8, leaseSeconds = 120 } = {}) {
+ return sql`
+ WITH heads AS (
+ SELECT DISTINCT ON (chat_key) id, status, locked_until
+ FROM gateway_inbox
+ WHERE status IN ('queued', 'processing')
+ ORDER BY chat_key, id
+ ), ready AS (
+ SELECT id FROM heads
+ WHERE status = 'queued' OR locked_until < now()
+ ORDER BY id
+ LIMIT ${limit}
+ )
+ UPDATE gateway_inbox g
+ SET status = 'processing', attempts = g.attempts + 1, locked_until = now() + make_interval(secs => ${leaseSeconds})
+ FROM ready
+ WHERE g.id = ready.id AND (g.status = 'queued' OR g.locked_until < now())
+ RETURNING g.id, g.platform, g.chat_key, g.payload, g.attempts`;
+}
+
+export async function completeInbox(id) {
+ await sql`UPDATE gateway_inbox SET status = 'done', finished_at = now(), locked_until = NULL WHERE id = ${id}`;
+}
+
+/** Requeue for another attempt, or park as failed after `maxAttempts`. */
+export async function failInbox(id, message, { attempts, maxAttempts = 3 } = {}) {
+ const giveUp = attempts >= maxAttempts;
+ await sql`
+ UPDATE gateway_inbox
+ SET status = ${giveUp ? 'failed' : 'queued'}, last_error = ${String(message || '').slice(0, 500)},
+ locked_until = NULL, finished_at = ${giveUp ? new Date().toISOString() : null}
+ WHERE id = ${id}`;
+ return giveUp;
+}
+
+export async function pruneInbox({ keepDays = 7 } = {}) {
+ await sql`
+ DELETE FROM gateway_inbox
+ WHERE status IN ('done', 'failed') AND created_at < now() - make_interval(days => ${keepDays})`;
+}
+
+// ── previews ─────────────────────────────────────────────────────────────────
+
+export async function createPreview({ linkId, userId, agentId, kind, proposal }) {
+ const [row] = await sql`
+ INSERT INTO gateway_previews (link_id, user_id, agent_id, kind, proposal, expires_at)
+ VALUES (${linkId}, ${userId}, ${agentId}, ${kind}, ${JSON.stringify(proposal)}::jsonb,
+ now() + make_interval(mins => ${PREVIEW_TTL_MINUTES}))
+ RETURNING *`;
+ return row;
+}
+
+export async function setPreviewMessageRef(id, ref) {
+ await sql`UPDATE gateway_previews SET message_ref = ${JSON.stringify(ref)}::jsonb WHERE id = ${id}`;
+}
+
+export async function getPreview(id) {
+ if (!/^[0-9a-f-]{36}$/i.test(String(id || ''))) return null;
+ const [row] = await sql`SELECT * FROM gateway_previews WHERE id = ${id} LIMIT 1`;
+ return row || null;
+}
+
+/** pending -> executing, only while it is still live. Exactly one press wins. */
+export async function claimPreview(id) {
+ const [row] = await sql`
+ UPDATE gateway_previews SET status = 'executing', decided_at = now()
+ WHERE id = ${id} AND status = 'pending' AND expires_at > now()
+ RETURNING *`;
+ return row || null;
+}
+
+export async function cancelPreview(id) {
+ const [row] = await sql`
+ UPDATE gateway_previews SET status = 'cancelled', decided_at = now()
+ WHERE id = ${id} AND status = 'pending'
+ RETURNING *`;
+ return row || null;
+}
+
+export async function expirePreview(id) {
+ await sql`
+ UPDATE gateway_previews SET status = 'expired', decided_at = now()
+ WHERE id = ${id} AND status = 'pending'`;
+}
+
+export async function finishPreview(id, status, result) {
+ await sql`
+ UPDATE gateway_previews SET status = ${status}, result = ${JSON.stringify(result || {})}::jsonb
+ WHERE id = ${id}`;
+}
diff --git a/api/_lib/migrations/20260922180000_chat_gateways.sql b/api/_lib/migrations/20260922180000_chat_gateways.sql
new file mode 100644
index 000000000..cddb3304e
--- /dev/null
+++ b/api/_lib/migrations/20260922180000_chat_gateways.sql
@@ -0,0 +1,104 @@
+-- Chat gateways: talk to your agent from Telegram and Discord.
+--
+-- The gateway worker (workers/agent-gateway) and the webhook receivers
+-- (api/gateway/telegram.js, api/gateway/discord.js) share these tables through
+-- api/_lib/gateway/. docs/chat-gateways.md is the user-facing guide.
+--
+-- agent_messages.channel which surface a thread message came from (web, api,
+-- telegram, discord). The thread itself is created by
+-- 20260922130000_agents_v1_api.sql; one thread per
+-- (agent, owner) spans every surface.
+-- gateway_links a paired chat: which platform identity and chat talk
+-- to which account, and the chat's default agent. One
+-- live link per chat, so a chat can never be paired to
+-- two accounts at once.
+-- gateway_pair_codes eight-character pairing codes, either printed by the
+-- bot (/start, /three link) and redeemed on
+-- /settings/connections, or generated on the site and
+-- pasted into the chat. Only the sha256 is stored.
+-- gateway_inbox webhook deliveries waiting for the worker. The
+-- receivers verify the platform signature, insert a row
+-- and answer at once; the worker claims rows one chat
+-- at a time so replies never overtake each other.
+-- gateway_previews a financial proposal rendered with Approve and Cancel
+-- buttons. Only a button press carrying this id, from
+-- the linked platform user, inside its ten-minute life,
+-- can execute it.
+
+ALTER TABLE agent_messages ADD COLUMN IF NOT EXISTS channel text NOT NULL DEFAULT 'api';
+DO $$ BEGIN
+ ALTER TABLE agent_messages ADD CONSTRAINT agent_messages_channel_check CHECK (channel ~ '^[a-z0-9_-]{1,24}$');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+CREATE TABLE IF NOT EXISTS gateway_links (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ platform text NOT NULL CHECK (platform IN ('telegram', 'discord')),
+ platform_user_id text NOT NULL,
+ platform_username text,
+ chat_id text NOT NULL,
+ chat_type text,
+ chat_title text,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ default_agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,
+ context_reset_at timestamptz,
+ notify boolean NOT NULL DEFAULT true,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ last_seen_at timestamptz,
+ revoked_at timestamptz
+);
+CREATE UNIQUE INDEX IF NOT EXISTS gateway_links_chat_live_uidx
+ ON gateway_links (platform, chat_id) WHERE revoked_at IS NULL;
+CREATE INDEX IF NOT EXISTS gateway_links_user_idx
+ ON gateway_links (user_id, created_at DESC) WHERE revoked_at IS NULL;
+
+CREATE TABLE IF NOT EXISTS gateway_pair_codes (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ code_hash text NOT NULL UNIQUE,
+ origin text NOT NULL CHECK (origin IN ('chat', 'site')),
+ platform text CHECK (platform IN ('telegram', 'discord')),
+ platform_user_id text,
+ platform_username text,
+ chat_id text,
+ chat_type text,
+ chat_title text,
+ user_id uuid REFERENCES users(id) ON DELETE CASCADE,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ expires_at timestamptz NOT NULL,
+ redeemed_at timestamptz,
+ link_id uuid REFERENCES gateway_links(id) ON DELETE SET NULL
+);
+CREATE INDEX IF NOT EXISTS gateway_pair_codes_user_idx ON gateway_pair_codes (user_id, created_at DESC);
+
+CREATE TABLE IF NOT EXISTS gateway_inbox (
+ id bigserial PRIMARY KEY,
+ platform text NOT NULL CHECK (platform IN ('telegram', 'discord')),
+ dedupe_key text NOT NULL,
+ chat_key text NOT NULL,
+ payload jsonb NOT NULL,
+ status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'done', 'failed')),
+ attempts int NOT NULL DEFAULT 0,
+ locked_until timestamptz,
+ last_error text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ finished_at timestamptz,
+ UNIQUE (platform, dedupe_key)
+);
+CREATE INDEX IF NOT EXISTS gateway_inbox_open_idx ON gateway_inbox (id) WHERE status IN ('queued', 'processing');
+CREATE INDEX IF NOT EXISTS gateway_inbox_chat_idx ON gateway_inbox (chat_key, id) WHERE status IN ('queued', 'processing');
+
+CREATE TABLE IF NOT EXISTS gateway_previews (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ link_id uuid NOT NULL REFERENCES gateway_links(id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ kind text NOT NULL CHECK (kind IN ('buy', 'sell', 'limits')),
+ proposal jsonb NOT NULL,
+ message_ref jsonb,
+ status text NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'executing', 'executed', 'failed', 'cancelled', 'expired')),
+ result jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ expires_at timestamptz NOT NULL,
+ decided_at timestamptz
+);
+CREATE INDEX IF NOT EXISTS gateway_previews_link_idx ON gateway_previews (link_id, created_at DESC);
diff --git a/api/agents/copilot.js b/api/agents/copilot.js
index f35c14c86..7277478d2 100644
--- a/api/agents/copilot.js
+++ b/api/agents/copilot.js
@@ -18,6 +18,11 @@
// (a confirm-before-execute trade/limits card), `chunk` (streamed narration
// tokens), `done` (final reply + proposals + citations), `error`.
//
+// The tools, prompt and loop live in api/_lib/copilot-engine.js, shared with the
+// Telegram and Discord gateways (api/_lib/gateway/). Each finished web turn is
+// appended to the agent's cross-channel thread (api/_lib/agent-thread.js) with
+// channel `web`, so a conversation started here continues in chat and back.
+//
// $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) is the only coin three.ws
// promotes. The copilot trades whatever mint the owner names at runtime — generic
// coin-agnostic plumbing — and never names or recommends any other token.
@@ -26,22 +31,11 @@ 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 { 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 { providerChain, streamRound } from '../_lib/llm-tool-chain.js';
+import { providerChain } from '../_lib/llm-tool-chain.js';
+import { runCopilotTurn, netOf, COPILOT_MAX_MESSAGES } from '../_lib/copilot-engine.js';
+import { appendThreadMessage } from '../_lib/agent-thread.js';
export { providerChain };
-const NETWORKS = new Set(['mainnet', 'devnet']);
-const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');
-const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
-const LAMPORTS_PER_SOL = 1_000_000_000;
-const MAX_ROUNDS = 4; // tool-loop rounds before we force a final answer
-const MAX_MESSAGES = 24; // trailing turns we keep as context
-
// ── auth / ownership ──────────────────────────────────────────────────────────
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -51,247 +45,6 @@ async function resolveAuth(req) {
return null;
}
-// ── 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 = [
- {
- type: 'function',
- function: {
- name: 'get_portfolio',
- description: "Read the agent wallet's live SOL balance, token holdings, and open sniper positions with unrealized PnL. Use to answer 'how's my position?' / 'what do I hold?'.",
- parameters: { type: 'object', properties: {}, additionalProperties: false },
- },
- },
- {
- type: 'function',
- function: {
- name: 'get_coin_intel',
- description: 'Live intelligence for one coin mint: quality score, bundle/organic/concentration signals, risk flags, dev-sold, narrative, and graduation/rug outcome. Use before discussing or proposing a buy.',
- parameters: { type: 'object', properties: { mint: { type: 'string', description: 'base58 token mint address' } }, required: ['mint'], additionalProperties: false },
- },
- },
- {
- type: 'function',
- function: {
- name: 'get_smart_money',
- description: 'Smart-money read for one coin: count of reputable wallets in it, a 0-100 smart-money score, and whether one funder cluster dominates (sybil). Use for "is smart money in this?".',
- parameters: { type: 'object', properties: { mint: { type: 'string' } }, required: ['mint'], additionalProperties: false },
- },
- },
- {
- type: 'function',
- function: {
- name: 'assess_safety',
- description: 'Run the rug/honeypot firewall on a prospective BUY: returns verdict (allow/warn/block), a 0-100 safety score, and plain-language reasons (mint authority, honeypot round-trip, concentration, price impact). Always run before proposing a buy.',
- parameters: { type: 'object', properties: { mint: { type: 'string' }, sol_amount: { type: 'number', description: 'SOL the owner would spend' } }, required: ['mint'], additionalProperties: false },
- },
- },
- {
- type: 'function',
- function: {
- name: 'get_quote',
- description: 'Non-binding live quote: expected output and price impact for a buy (sol_amount) or sell (token_amount in UI units). Cite these exact numbers; never invent a quote.',
- parameters: {
- type: 'object',
- properties: {
- side: { type: 'string', enum: ['buy', 'sell'] },
- mint: { type: 'string' },
- sol_amount: { type: 'number', description: 'for buy: SOL to spend' },
- token_amount: { type: 'number', description: 'for sell: tokens to sell, in UI units' },
- slippage_bps: { type: 'integer', description: 'default 300 (3%)' },
- },
- required: ['side', 'mint'],
- additionalProperties: false,
- },
- },
- },
- {
- type: 'function',
- function: {
- name: 'get_trade_limits',
- description: "Read the owner's discretionary trade guardrails: per-trade SOL cap, daily budget, max price impact, max slippage, and kill-switch state.",
- parameters: { type: 'object', properties: {}, additionalProperties: false },
- },
- },
- {
- type: 'function',
- function: {
- name: 'propose_buy',
- description: 'Surface a BUY proposal for the owner to confirm. Does NOT execute. It returns a confirm card grounded with a fresh quote + firewall verdict. Call this when the owner clearly wants to buy. Never claim a buy happened until the owner confirms it.',
- parameters: {
- type: 'object',
- properties: {
- mint: { type: 'string' },
- sol_amount: { type: 'number', description: 'SOL to spend (> 0)' },
- slippage_bps: { type: 'integer', description: 'default 300' },
- rationale: { type: 'string', description: 'one short sentence on why, citing real signals' },
- },
- required: ['mint', 'sol_amount'],
- additionalProperties: false,
- },
- },
- },
- {
- type: 'function',
- function: {
- name: 'propose_sell',
- description: 'Surface a SELL proposal for the owner to confirm. Does NOT execute. Provide either token_pct (1-100 of the held balance) or token_amount (UI units).',
- parameters: {
- type: 'object',
- properties: {
- mint: { type: 'string' },
- token_pct: { type: 'number', description: 'percent of holding to sell, 1-100' },
- token_amount: { type: 'number', description: 'tokens to sell in UI units (alternative to token_pct)' },
- slippage_bps: { type: 'integer', description: 'default 300' },
- rationale: { type: 'string' },
- },
- required: ['mint'],
- additionalProperties: false,
- },
- },
- },
- {
- type: 'function',
- function: {
- name: 'propose_set_limits',
- description: "Surface a risk-control change for the owner to confirm (does NOT apply until confirmed): per-trade SOL cap, daily SOL budget, max price-impact %, or the kill switch (kill_switch:true halts all trading). Use for 'cap my trades at 0.5 SOL', 'pause trading', 'set a daily budget'.",
- parameters: {
- type: 'object',
- properties: {
- per_trade_sol: { type: 'number' },
- daily_budget_sol: { type: 'number' },
- max_price_impact_pct: { type: 'number' },
- kill_switch: { type: 'boolean' },
- rationale: { type: 'string' },
- },
- additionalProperties: false,
- },
- },
- },
-];
-
-// ── server-side tool execution (read-only) ─────────────────────────────────────
-function num(v) { return v == null || !Number.isFinite(Number(v)) ? null : Number(v); }
-
-async function loadIntel(mint, network) {
- const [row] = await sql`
- SELECT i.mint, i.symbol, i.name, i.quality_score, i.bundle_score, i.organic_score,
- i.snipe_ratio, i.concentration_top10, i.fresh_wallet_ratio, i.risk_flags,
- i.category, i.narrative, i.dev_sold, i.unique_buyers, i.observation_seconds,
- o.outcome, o.ath_multiple
- FROM pump_coin_intel i
- LEFT JOIN pump_coin_outcomes o ON o.mint = i.mint AND o.network = i.network
- WHERE i.mint = ${mint} AND i.network = ${network}
- LIMIT 1`.catch(() => []);
- if (!row) return { mint, found: false, note: 'No intelligence on this mint yet. The engine only fingerprints pump.fun launches it has observed.' };
- return {
- mint, found: true, symbol: row.symbol, name: row.name,
- quality_score: num(row.quality_score),
- bundle_score: num(row.bundle_score), organic_score: num(row.organic_score),
- snipe_ratio: num(row.snipe_ratio), concentration_top10: num(row.concentration_top10),
- fresh_wallet_ratio: num(row.fresh_wallet_ratio), risk_flags: row.risk_flags || [],
- category: row.category, narrative: row.narrative, dev_sold: row.dev_sold,
- unique_buyers: row.unique_buyers, observation_seconds: row.observation_seconds,
- outcome: row.outcome || null, ath_multiple: num(row.ath_multiple),
- };
-}
-
-async function loadPortfolio(agentId, address, network) {
- const out = { network, wallet: address, sol_balance: null, holdings: [], open_positions: [] };
- if (!address) return out;
- const conn = solanaPublicConnection(network);
- const ownerPk = new PublicKey(address);
- try {
- const lamports = await conn.getBalance(ownerPk);
- out.sol_balance = Number(lamports) / LAMPORTS_PER_SOL;
- } catch { /* RPC hiccup — report null, copilot says balance unavailable */ }
- try {
- const TOKEN = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
- const TOKEN22 = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
- const accounts = [];
- for (const prog of [TOKEN, TOKEN22]) {
- const r = await conn.getParsedTokenAccountsByOwner(ownerPk, { programId: prog }).catch(() => null);
- if (r?.value) accounts.push(...r.value);
- }
- out.holdings = accounts
- .map((a) => {
- const info = a.account.data.parsed?.info;
- const amt = info?.tokenAmount;
- return amt && Number(amt.uiAmount) > 0
- ? { mint: info.mint, ui_amount: Number(amt.uiAmount), decimals: amt.decimals }
- : null;
- })
- .filter(Boolean)
- .slice(0, 30);
- } catch { /* token read failed — holdings stay empty */ }
- try {
- const rows = await sql`
- SELECT mint, symbol, status, entry_quote_lamports, last_value_lamports,
- realized_pnl_lamports, realized_pnl_pct, exit_reason
- FROM agent_sniper_positions
- WHERE agent_id = ${agentId} AND network = ${network} AND status = 'open'
- ORDER BY opened_at DESC LIMIT 20`;
- out.open_positions = rows.map((p) => ({
- mint: p.mint, symbol: p.symbol,
- entry_sol: num(p.entry_quote_lamports) != null ? num(p.entry_quote_lamports) / LAMPORTS_PER_SOL : null,
- current_sol: num(p.last_value_lamports) != null ? num(p.last_value_lamports) / LAMPORTS_PER_SOL : null,
- unrealized_pnl_pct: num(p.realized_pnl_pct),
- }));
- } catch { /* positions table read failed — leave empty */ }
- return out;
-}
-
-async function runQuote({ side, mint, solAmount, tokenAmount, slippageBps, network }) {
- const conn = solanaPublicConnection(network);
- const mintPk = new PublicKey(mint);
- let tokenAmountRaw;
- if (side === 'sell') {
- // Convert UI tokens → raw using on-chain decimals.
- let decimals = 6;
- try {
- const info = await conn.getParsedAccountInfo(mintPk);
- const d = info?.value?.data?.parsed?.info?.decimals;
- if (Number.isInteger(d)) decimals = d;
- } catch { /* default 6 */ }
- tokenAmountRaw = BigInt(Math.floor(Number(tokenAmount || 0) * 10 ** decimals)).toString();
- }
- const q = await quoteTrade({ conn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps });
- return {
- side, mint, venue: q.venue, price_impact_pct: num(q.priceImpactPct),
- in_asset: q.inAsset, in_amount: num(q.inAmount),
- out_asset: q.outAsset, expected_out: num(q.outUi),
- min_received: num(q.minOutUi),
- };
-}
-
-// Best-effort coin label (symbol/name) for proposal cards.
-async function coinLabel(mint, network) {
- const intel = await loadIntel(mint, network).catch(() => null);
- if (intel?.found && (intel.symbol || intel.name)) return { symbol: intel.symbol || null, name: intel.name || null };
- return { symbol: null, name: null };
-}
-
-// ── system prompt ──────────────────────────────────────────────────────────────
-function buildSystemPrompt({ agentName, persona, network }) {
- const base = (persona || '').trim();
- return [
- base ? `You speak in character as ${agentName}. Persona:\n${base}\n` : `You are ${agentName}, a trading copilot.`,
- `You are the in-world CONVERSATIONAL TRADING COPILOT for the three.ws agent "${agentName}" and its self-custodied Solana wallet (network: ${network}).`,
- `Your job: help the owner snipe, trade, and manage risk by talking. You have real tools, so use them; never invent numbers, prices, balances, safety verdicts, or smart-money counts. If a tool returns no data, say so plainly.`,
- `RULES:`,
- `• ACT, don't ask. The read-only tools (get_portfolio, get_coin_intel, get_smart_money, assess_safety, get_quote, get_trade_limits) are free and instant, so CALL them immediately to answer. NEVER ask the owner for permission to read their own wallet or check a coin ("would you like me to check…?" is forbidden). If they ask "how's my portfolio?", call get_portfolio right away and answer with the real numbers. Only the propose_* actions need confirmation.`,
- `• You NEVER execute or sign anything. To buy, sell, or change risk limits you MUST call the matching propose_* tool, which surfaces a confirm card. The owner confirms; a guarded server endpoint then enforces spend caps, the firewall, and the kill switch and signs. Never say a trade is done. Say you've prepared it for confirmation.`,
- `• Before proposing OR recommending a buy, ground it: call assess_safety (firewall) and get_quote, and mention the safety verdict and price impact. If the firewall verdict is "block", refuse the buy and explain why.`,
- `• Keep answers tight and conversational (2-5 sentences), because this may be read aloud. Light markdown is fine (bold, short bullet lists) but no tables or code blocks. The UI already shows the raw numbers as cards, so narrate the takeaway and don't re-list every figure.`,
- `• The only coin three.ws promotes is $THREE. You may trade any mint the owner explicitly names (that is their call), but never suggest, shill, or name a specific other token on your own initiative.`,
- `• When the owner is vague ("buy the safe one"), ask one brief clarifying question or have them paste a mint. Do not guess a mint address.`,
- ].join('\n');
-}
-
// ── handler ─────────────────────────────────────────────────────────────────────
export default async function handler(req, res, id) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
@@ -307,14 +60,12 @@ export default async function handler(req, res, id) {
if (!row) return error(res, 404, 'not_found', 'agent not found');
if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'only the owner can use this copilot');
- const meta = row.meta || {};
- const address = meta.solana_address || null;
const body = await readJson(req).catch(() => null);
const network = netOf(body?.network);
const rawMessages = Array.isArray(body?.messages) ? body.messages : [];
const history = rawMessages
.filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim())
- .slice(-MAX_MESSAGES)
+ .slice(-COPILOT_MAX_MESSAGES)
.map((m) => ({ role: m.role, content: m.content.slice(0, 4000) }));
if (!history.length || history[history.length - 1].role !== 'user') {
return error(res, 422, 'no_message', 'send at least one user message');
@@ -340,223 +91,19 @@ export default async function handler(req, res, id) {
// genuinely dead connection, never on a model that's just thinking.
const heartbeat = setInterval(() => { if (active) res.write(': ping\n\n'); }, 15_000);
- const messages = [{ role: 'system', content: buildSystemPrompt({ agentName: row.name || 'Agent', persona: row.persona_prompt, network }) }, ...history];
- const proposals = [];
- const citations = [];
- let finalText = '';
-
- // Read-only tools are pure within a turn — the wallet/intel/quote a round sees
- // won't change between the model's rounds. Memoize by (name, args) so when the
- // model re-issues an identical read (a common small-model tic that otherwise
- // burns a whole tool-loop round and paints a duplicate "Portfolio: …" line in
- // the UI) we serve it from cache: no second RPC, no duplicate `tool` event, and
- // the loop can tell the round made no new progress and cut to a final answer.
- const readCache = new Map();
-
- // One read-only tool execution → returns a compact result for the model + a UI summary.
- async function execReadTool(name, args) {
- if (name === 'get_portfolio') {
- const p = await loadPortfolio(id, address, network);
- citations.push({ kind: 'portfolio', sol: p.sol_balance, holdings: p.holdings.length, positions: p.open_positions.length });
- return {
- result: p,
- summary: address ? `Portfolio: ${p.sol_balance != null ? p.sol_balance.toFixed(4) + ' SOL' : 'balance unavailable'}, ${p.holdings.length} token(s), ${p.open_positions.length} open position(s)` : 'No wallet provisioned yet',
- card: { kind: 'portfolio', wallet: p.wallet, sol_balance: p.sol_balance, holdings: p.holdings, open_positions: p.open_positions, network },
- };
- }
- if (name === 'get_coin_intel') {
- const intel = await loadIntel(args.mint, network);
- citations.push({ kind: 'intel', mint: args.mint, quality: intel.quality_score ?? null });
- return {
- result: intel,
- summary: intel.found ? `Intel ${intel.symbol || ''}: quality ${intel.quality_score ?? 'n/a'}/100, ${(intel.risk_flags || []).length} risk flag(s)${intel.outcome ? `, outcome ${intel.outcome}` : ''}` : 'No intel on this mint',
- card: { kind: 'intel', ...intel },
- };
- }
- if (name === 'get_smart_money') {
- const sm = await getSmartMoneyForMint(args.mint, network);
- citations.push({ kind: 'smart_money', mint: args.mint, score: sm.smart_money_score, count: sm.count });
- return {
- result: sm,
- summary: `Smart money: ${sm.count} reputable wallet(s), score ${sm.smart_money_score}/100${sm.sybil_flag ? ' (sybil-dominated)' : ''}`,
- card: { kind: 'smart_money', mint: args.mint, count: sm.count, score: sm.smart_money_score, sybil: !!sm.sybil_flag },
- };
- }
- if (name === 'assess_safety') {
- const conn = solanaPublicConnection(network);
- const quoteLamports = args.sol_amount > 0 ? BigInt(Math.floor(Number(args.sol_amount) * LAMPORTS_PER_SOL)) : null;
- const a = await assessTradeSafety({ network, mint: args.mint, side: 'buy', payer: address, quoteAmount: quoteLamports, connection: conn });
- citations.push({ kind: 'safety', mint: args.mint, verdict: a.verdict, score: a.score });
- return {
- result: { verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated },
- summary: `Firewall: ${a.verdict.toUpperCase()} (${a.score}/100)${a.reasons?.[0] ? ': ' + a.reasons[0] : ''}`,
- card: { kind: 'safety', mint: args.mint, verdict: a.verdict, score: a.score, reasons: a.reasons || [], simulated: !!a.simulated },
- };
- }
- if (name === 'get_quote') {
- const q = await runQuote({ side: args.side, mint: args.mint, solAmount: args.sol_amount, tokenAmount: args.token_amount, slippageBps: args.slippage_bps || 300, network });
- citations.push({ kind: 'quote', mint: args.mint, side: args.side, impact: q.price_impact_pct });
- return {
- result: q,
- summary: `Quote ${args.side}: ${q.expected_out != null ? q.expected_out.toLocaleString(undefined, { maximumFractionDigits: 4 }) : 'n/a'} ${q.out_asset}, ${q.price_impact_pct != null ? q.price_impact_pct.toFixed(2) + '% impact' : 'impact n/a'}`,
- card: { kind: 'quote', mint: args.mint, side: q.side, in_asset: q.in_asset, in_amount: q.in_amount, out_asset: q.out_asset, expected_out: q.expected_out, price_impact_pct: q.price_impact_pct, min_received: q.min_received },
- };
- }
- if (name === 'get_trade_limits') {
- const lim = getTradeLimits(meta);
- return {
- result: lim,
- summary: `Limits: per-trade ${lim.per_trade_sol ?? '∞'} SOL, daily ${lim.daily_budget_sol ?? '∞'} SOL, kill switch ${lim.kill_switch ? 'ON' : 'off'}`,
- card: { kind: 'limits', ...lim },
- };
- }
- return { result: { error: 'unknown_tool' }, summary: 'unknown tool' };
- }
-
- // A propose_* tool → grounded proposal card, never executed here.
- async function execProposeTool(name, args) {
- if (name === 'propose_buy') {
- if (!BASE58_RE.test(args.mint || '')) return { result: { error: 'invalid_mint' }, summary: 'invalid mint' };
- const slippageBps = Math.max(0, Math.min(5000, Math.round(args.slippage_bps || 300)));
- const [quote, safety, label] = await Promise.all([
- runQuote({ side: 'buy', mint: args.mint, solAmount: args.sol_amount, slippageBps, network }).catch((e) => ({ error: e?.message || 'quote_failed' })),
- assessTradeSafety({ network, mint: args.mint, side: 'buy', payer: address, quoteAmount: BigInt(Math.floor(Number(args.sol_amount) * LAMPORTS_PER_SOL)), connection: solanaPublicConnection(network) })
- .then((a) => ({ verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated }))
- .catch(() => null),
- coinLabel(args.mint, network),
- ]);
- const proposal = { id: `p${proposals.length + 1}`, kind: 'buy', mint: args.mint, coin: label, sol_amount: Number(args.sol_amount), slippage_bps: slippageBps, network, quote, safety, rationale: args.rationale || null };
- proposals.push(proposal);
- send('proposal', proposal);
- const blocked = safety?.verdict === 'block';
- return { result: { surfaced: true, blocked, safety_verdict: safety?.verdict, price_impact_pct: quote?.price_impact_pct }, summary: `Buy proposal surfaced (awaiting confirmation). Firewall ${safety?.verdict || 'n/a'}.${blocked ? ' BLOCKED, do not encourage this trade.' : ''}` };
- }
- if (name === 'propose_sell') {
- if (!BASE58_RE.test(args.mint || '')) return { result: { error: 'invalid_mint' }, summary: 'invalid mint' };
- const slippageBps = Math.max(0, Math.min(5000, Math.round(args.slippage_bps || 300)));
- // Resolve the held balance so a percent maps to a concrete UI amount.
- const port = await loadPortfolio(id, address, network).catch(() => null);
- const held = port?.holdings?.find((h) => h.mint === args.mint) || null;
- let tokenAmount = num(args.token_amount);
- let tokenPct = num(args.token_pct);
- if (tokenAmount == null && tokenPct != null && held) tokenAmount = (held.ui_amount * Math.max(1, Math.min(100, tokenPct))) / 100;
- if (tokenAmount == null && held) tokenAmount = held.ui_amount; // default: sell all
- if (!(tokenAmount > 0)) return { result: { error: 'no_holding' }, summary: 'owner does not hold this coin' };
- const [quote, label] = await Promise.all([
- runQuote({ side: 'sell', mint: args.mint, tokenAmount, slippageBps, network }).catch((e) => ({ error: e?.message || 'quote_failed' })),
- coinLabel(args.mint, network),
- ]);
- const proposal = { id: `p${proposals.length + 1}`, kind: 'sell', mint: args.mint, coin: label, token_amount: tokenAmount, token_pct: tokenPct ?? null, decimals: held?.decimals ?? 6, slippage_bps: slippageBps, network, quote, rationale: args.rationale || null };
- proposals.push(proposal);
- send('proposal', proposal);
- return { result: { surfaced: true, expected_sol: quote?.expected_out }, summary: `Sell proposal surfaced (awaiting confirmation): ~${quote?.expected_out != null ? Number(quote.expected_out).toFixed(4) : 'n/a'} SOL.` };
- }
- if (name === 'propose_set_limits') {
- const cur = getTradeLimits(meta);
- const changes = {};
- for (const k of ['per_trade_sol', 'daily_budget_sol', 'max_price_impact_pct']) {
- if (num(args[k]) != null) changes[k] = Number(args[k]);
- }
- if (typeof args.kill_switch === 'boolean') changes.kill_switch = args.kill_switch;
- if (!Object.keys(changes).length) return { result: { error: 'no_change' }, summary: 'no limit change specified' };
- const proposal = { id: `p${proposals.length + 1}`, kind: 'limits', network, current: cur, changes, rationale: args.rationale || null };
- proposals.push(proposal);
- send('proposal', proposal);
- return { result: { surfaced: true }, summary: 'Risk-limit change surfaced (awaiting confirmation).' };
- }
- return { result: { error: 'unknown_tool' }, summary: 'unknown tool' };
- }
-
- // ── tool loop ───────────────────────────────────────────────────────────────
try {
- let answered = false;
- for (let round = 0; round < MAX_ROUNDS && active && !answered; round++) {
- send('status', { phase: round === 0 ? 'thinking' : 'continuing' });
- // Pick the first provider that yields a round; once content has been
- // streamed to the client we can't fail over, so stream-failover only
- // applies before any byte for THIS round was emitted.
- let roundOut = null;
- let lastErr = null;
- for (const provider of chain) {
- let emitted = false;
- try {
- roundOut = await streamRound(provider, {
- messages,
- tools: TOOLS,
- onContent: (t) => { emitted = true; finalText += t; send('chunk', { text: t }); },
- });
- break;
- } catch (e) {
- lastErr = e;
- if (emitted) { roundOut = { content: '', toolCalls: [] }; break; } // mid-stream failure; stop
- }
- }
- if (!roundOut) throw lastErr || new Error('all providers failed');
-
- if (!roundOut.toolCalls.length) { answered = true; break; }
-
- // Record the assistant's tool-call turn, then resolve each call.
- messages.push({
- role: 'assistant',
- content: roundOut.content || null,
- tool_calls: roundOut.toolCalls.map((tc) => ({ id: tc.id, type: 'function', function: { name: tc.name, arguments: tc.args || '{}' } })),
- });
- // A round is only "progress" if at least one call surfaced something new —
- // a fresh read, or a proposal. If every call this round is a repeat of a
- // read the model already ran this turn, it's spinning: feed the cached
- // results back (OpenAI requires a tool result per tool_call) but break out
- // afterward so the finalize step turns what we have into a real answer
- // instead of stalling the owner behind more identical "Analyzing…" rounds.
- let progressed = false;
- for (const tc of roundOut.toolCalls) {
- let args = {};
- try { args = tc.args ? JSON.parse(tc.args) : {}; } catch { args = {}; }
- const isPropose = tc.name.startsWith('propose_');
- let outcome;
- let cached = false;
- try {
- if (isPropose) {
- outcome = await execProposeTool(tc.name, args);
- progressed = true;
- } else {
- const key = `${tc.name}:${JSON.stringify(args)}`;
- if (readCache.has(key)) {
- outcome = readCache.get(key);
- cached = true;
- } else {
- outcome = await execReadTool(tc.name, args);
- readCache.set(key, outcome);
- progressed = true;
- }
- }
- } catch (e) {
- outcome = { result: { error: e?.message || 'tool_failed' }, summary: `Tool ${tc.name} failed: ${e?.message || 'error'}` };
- progressed = true; // a genuine failure is new information, not a spin
- }
- // Surface read activity once per distinct read — never re-paint a cached repeat.
- if (!isPropose && !cached) send('tool', { name: tc.name, summary: outcome.summary, data: outcome.card || null });
- messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(outcome.result).slice(0, 6000) });
- }
- if (!progressed) break; // model looped on data it already has — go answer.
- }
-
- // If the loop hit its round cap mid-tool without a natural answer, ask for a
- // final plain-language wrap-up (no tools) so the user always gets a reply.
- if (!finalText.trim() && active) {
- send('status', { phase: 'finalizing' });
- for (const provider of chain) {
- try {
- const out = await streamRound(provider, {
- messages: [...messages, { role: 'user', content: 'Briefly summarize what you found and what I should do next. Plain language, 2-4 sentences.' }],
- tools: [],
- onContent: (t) => { finalText += t; send('chunk', { text: t }); },
- });
- if (out) break;
- } catch { /* try next provider */ }
- }
- }
-
- send('done', { reply: finalText.trim(), proposals, citations });
+ const turn = await runCopilotTurn({
+ agent: row,
+ history,
+ network,
+ chain,
+ isActive: () => active,
+ // tool_start is for surfaces that paint a live status line (the chat
+ // gateways); the web UI already paints each finished read as a card.
+ emit: (event, data) => { if (event !== 'tool_start') send(event, data); },
+ });
+ send('done', { reply: turn.reply, proposals: turn.proposals, citations: turn.citations });
+ await persistWebTurn({ agentId: id, userId: auth.userId, userText: history[history.length - 1].content, turn });
} catch (e) {
send('error', { code: e?.code || 'copilot_error', message: e?.message || 'The copilot hit an error. Try again.' });
} finally {
@@ -564,3 +111,16 @@ export default async function handler(req, res, id) {
if (active) res.end();
}
}
+
+// Append the finished web turn to the agent's cross-channel thread, so Telegram
+// and Discord continue the same conversation. Best-effort: the owner already has
+// the reply, and a thread write must never turn a good answer into an error.
+async function persistWebTurn({ agentId, userId, userText, turn }) {
+ if (!turn.reply) return;
+ try {
+ await appendThreadMessage({ agentId, userId, role: 'user', content: userText, channel: 'web' });
+ await appendThreadMessage({ agentId, userId, role: 'assistant', content: turn.reply, channel: 'web', toolCalls: turn.toolCalls });
+ } catch (e) {
+ console.warn('[copilot] thread append failed', e?.message);
+ }
+}
diff --git a/workers/signal-bridge/Dockerfile b/workers/signal-bridge/Dockerfile
new file mode 100644
index 000000000..c393b4931
--- /dev/null
+++ b/workers/signal-bridge/Dockerfile
@@ -0,0 +1,28 @@
+# signal-bridge: the Signal leg of the agent gateway (workers/agent-gateway).
+#
+# A thin layer over the maintained signal-cli REST bridge
+# (github.com/bbernhard/signal-cli-rest-api). The upstream image already does the
+# hard part (signal-cli, the REST surface, the live receive websocket); this layer
+# only adds persistence, because Cloud Run disks are ephemeral and the registered
+# number's identity keys must survive a restart. persist.sh restores the state
+# tree from the mounted bucket on boot and snapshots it back on a timer.
+#
+# docker build -t signal-bridge workers/signal-bridge
+# docker run -p 8080:8080 -v "$PWD/.signal-state:/state" signal-bridge
+
+FROM bbernhard/signal-cli-rest-api:0.100
+
+# json-rpc keeps one signal-cli process resident, so sends are milliseconds
+# instead of a JVM start each, and it is the mode that serves the receive
+# websocket the gateway subscribes to.
+ENV MODE=json-rpc \
+ PORT=8080 \
+ JSON_RPC_TRUST_NEW_IDENTITIES=on-first-use \
+ JSON_RPC_IGNORE_STORIES=true \
+ JSON_RPC_IGNORE_STICKERS=true \
+ SIGNAL_STATE_DIR=/state \
+ SIGNAL_SNAPSHOT_SECONDS=120
+
+COPY --chmod=755 persist.sh /usr/local/bin/signal-bridge-persist
+
+ENTRYPOINT ["/usr/local/bin/signal-bridge-persist"]
diff --git a/workers/signal-bridge/cloudbuild.yaml b/workers/signal-bridge/cloudbuild.yaml
new file mode 100644
index 000000000..f6494598d
--- /dev/null
+++ b/workers/signal-bridge/cloudbuild.yaml
@@ -0,0 +1,103 @@
+# Cloud Build -> Cloud Run for the Signal bridge (workers/signal-bridge), the
+# Signal leg of the agent gateway. Build context is THIS directory.
+#
+# gcloud builds submit workers/signal-bridge --config workers/signal-bridge/cloudbuild.yaml \
+# --region us-central1 --project aerial-vehicle-466722-p5 \
+# --substitutions=SHORT_SHA=manual$(date +%s)
+#
+# Why the flags below are load-bearing:
+# --max-instances=1 signal-cli owns one registered number's key material.
+# Two instances would each advance the ratchets and
+# corrupt the other's sessions.
+# --min-instances=1 and the gateway holds the receive websocket open; an idle
+# --no-cpu-throttling scale-to-zero would drop inbound Signal messages.
+# --no-allow-unauthenticated
+# the upstream REST bridge has no auth of its own. Only
+# the runtime service account (the gateway) may invoke
+# it, with a Google ID token.
+# state volume the bucket keeps the snapshot persist.sh writes, so a
+# new revision restores the registration instead of
+# needing the number re-verified.
+
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
+
+substitutions:
+ _REGION: us-central1
+ _SERVICE: signal-bridge
+ _REPO: signal-bridge
+ _STATE_BUCKET: three-ws-signal-bridge-state
+
+steps:
+ - id: ensure-repo-and-bucket
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: bash
+ args:
+ - -c
+ - |
+ set -e
+ gcloud artifacts repositories describe ${_REPO} --location=${_REGION} >/dev/null 2>&1 \
+ || gcloud artifacts repositories create ${_REPO} --repository-format=docker --location=${_REGION}
+ if ! gcloud storage buckets describe gs://${_STATE_BUCKET} >/dev/null 2>&1; then
+ gcloud storage buckets create gs://${_STATE_BUCKET} --location=${_REGION} --uniform-bucket-level-access
+ gcloud storage buckets update gs://${_STATE_BUCKET} --versioning
+ fi
+ gcloud storage buckets add-iam-policy-binding gs://${_STATE_BUCKET} \
+ --member=serviceAccount:${_RUN_SA} --role=roles/storage.objectAdmin >/dev/null
+
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ args:
+ - build
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args: [push, --all-tags, '${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}']
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:$SHORT_SHA
+ - --region=${_REGION}
+ - --service-account=${_RUN_SA}
+ - --execution-environment=gen2
+ - --port=8080
+ - --cpu=1
+ - --memory=1Gi
+ - --min-instances=1
+ - --max-instances=1
+ - --no-cpu-throttling
+ - --timeout=3600
+ - --no-allow-unauthenticated
+ - --add-volume=name=state,type=cloud-storage,bucket=${_STATE_BUCKET},mount-options=uid=1000;gid=1000
+ - --add-volume-mount=volume=state,mount-path=/state
+ - --startup-probe=httpGet.path=/v1/health,initialDelaySeconds=10,periodSeconds=10,failureThreshold=30
+
+ - id: grant-invoker
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - services
+ - add-iam-policy-binding
+ - ${_SERVICE}
+ - --region=${_REGION}
+ - --member=serviceAccount:${_RUN_SA}
+ - --role=roles/run.invoker
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:latest
+
+options:
+ logging: CLOUD_LOGGING_ONLY
+timeout: 1800s
diff --git a/workers/signal-bridge/persist.sh b/workers/signal-bridge/persist.sh
new file mode 100755
index 000000000..4119bcbbd
--- /dev/null
+++ b/workers/signal-bridge/persist.sh
@@ -0,0 +1,46 @@
+#!/bin/sh
+# Restore the signal-cli state tree from the mounted state volume, keep it
+# snapshotted there, then hand PID 1 to the upstream s6 init.
+#
+# The snapshot is written to a temp name and renamed, so a restart mid-write
+# restores the previous complete tarball rather than a torn one. The loop only
+# writes when the tree changed since the last snapshot, which keeps an idle
+# bridge from rewriting the same object every interval.
+set -eu
+
+CONFIG_DIR="${SIGNAL_CLI_CONFIG_DIR:-/home/.local/share/signal-cli}"
+STATE_DIR="${SIGNAL_STATE_DIR:-/state}"
+INTERVAL="${SIGNAL_SNAPSHOT_SECONDS:-120}"
+SNAPSHOT="$STATE_DIR/signal-cli.tgz"
+
+mkdir -p "$CONFIG_DIR"
+
+if [ -d "$STATE_DIR" ] && [ -s "$SNAPSHOT" ]; then
+ echo "signal-bridge: restoring state from $SNAPSHOT"
+ tar -xzf "$SNAPSHOT" -C "$CONFIG_DIR"
+else
+ echo "signal-bridge: no snapshot at $SNAPSHOT, starting unregistered"
+fi
+
+snapshot() {
+ [ -d "$STATE_DIR" ] || return 0
+ tar -czf "$STATE_DIR/.signal-cli.tgz.tmp" -C "$CONFIG_DIR" . \
+ && mv -f "$STATE_DIR/.signal-cli.tgz.tmp" "$SNAPSHOT"
+}
+
+(
+ last=""
+ while sleep "$INTERVAL"; do
+ stamp="$(find "$CONFIG_DIR" -type f -newer "$SNAPSHOT" 2>/dev/null | head -1)"
+ if [ ! -s "$SNAPSHOT" ] || [ -n "$stamp" ]; then
+ if snapshot; then
+ last="$(date -u +%FT%TZ)"
+ echo "signal-bridge: snapshot written $last"
+ else
+ echo "signal-bridge: snapshot failed" >&2
+ fi
+ fi
+ done
+) &
+
+exec /init