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(desktop): add the local agent runtime for the desktop app (keystore, launch feed, bonding-curve math, strategy schema, run log)

nirholas19e40fe538bd
diff --git a/apps/desktop/src/runtime/curve.js b/apps/desktop/src/runtime/curve.js
new file mode 100644
index 000000000..1704298df
--- /dev/null
+++ b/apps/desktop/src/runtime/curve.js
@@ -0,0 +1,29 @@
+// Constant-product maths for a pump.fun bonding curve, from the coin's own
+// reported virtual reserves. Paper fills use real, live reserves, so a paper
+// trade shows the price and impact the same order would get on chain, less
+// the venue fee.
+
+const FEE = 0.01;
+const LAMPORTS = 1e9;
+
+function reserves(coin) {
+ const s = Number(coin?.virtual_sol_reserves);
+ const t = Number(coin?.virtual_token_reserves);
+ if (!(s > 0) || !(t > 0)) throw new Error('coin has no usable reserves');
+ return { s, t };
+}
+
+export function quoteBuy(coin, sol) {
+ const { s, t } = reserves(coin);
+ const inLamports = sol * LAMPORTS * (1 - FEE);
+ const tokens = t - (s * t) / (s + inLamports);
+ const spot = s / t;
+ const exec = (sol * LAMPORTS) / tokens;
+ return { tokens: Math.floor(tokens), impact_pct: Math.max(0, (exec / spot - 1) * 100) };
+}
+
+export function quoteSell(coin, tokens) {
+ const { s, t } = reserves(coin);
+ const out = s - (s * t) / (t + tokens);
+ return { lamports: Math.floor(out * (1 - FEE)) };
+}
diff --git a/apps/desktop/src/runtime/feed.js b/apps/desktop/src/runtime/feed.js
new file mode 100644
index 000000000..df6dc946c
--- /dev/null
+++ b/apps/desktop/src/runtime/feed.js
@@ -0,0 +1,60 @@
+// Real pump.fun launch feed, fetched directly from this machine so a strategy
+// keeps evaluating while three.ws is unreachable. Mainnet only: the venue has
+// no public devnet feed, so devnet agents see no entries (open positions still
+// exit). Mirrors api/_lib/pump-launch-feed.js normalizeLaunch.
+
+const BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
+const UA = 'three.ws-desktop-runtime/1';
+
+async function getJson(fetchImpl, url, ms = 8000) {
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), ms);
+ try {
+ const r = await fetchImpl(url, { signal: ctrl.signal, headers: { accept: 'application/json', 'user-agent': UA } });
+ return r.ok ? await r.json() : null;
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+export function normalizeLaunch(c, solUsd = 0) {
+ if (!c?.mint) return null;
+ const real = Number(c.real_sol_reserves);
+ const virt = Number(c.virtual_sol_reserves);
+ return {
+ mint: c.mint, name: c.name || null, symbol: c.symbol || null,
+ created_at: c.created_timestamp ? Number(c.created_timestamp) : null,
+ market_cap_usd: typeof c.usd_market_cap === 'number' ? c.usd_market_cap : typeof c.market_cap === 'number' && solUsd > 0 ? c.market_cap * solUsd : null,
+ liquidity_sol: real > 0 ? real / 1e9 : virt > 0 ? virt / 1e9 : null,
+ creator: c.creator || null, creator_launches: null, creator_graduated: null,
+ twitter: c.twitter || null, telegram: c.telegram || null, website: c.website || null,
+ is_usdc_pair: false, graduated: c.complete === true || !!c.raydium_pool || !!c.pump_swap_pool,
+ };
+}
+
+export function createPumpFeed({ fetchImpl = fetch, base = BASE, now = Date.now } = {}) {
+ let sol = { at: 0, usd: 0 };
+ // SOL/USD from Coinbase's public spot endpoint, cached a minute, so the
+ // launch market cap (reported in SOL) can be gated in dollars.
+ async function solUsd() {
+ if (now() - sol.at < 60_000 && sol.usd > 0) return sol.usd;
+ const d = await getJson(fetchImpl, 'https://api.coinbase.com/v2/prices/SOL-USD/spot');
+ const usd = Number(d?.data?.amount);
+ if (usd > 0) sol = { at: now(), usd };
+ return sol.usd;
+ }
+ return {
+ async launches({ network = 'mainnet', limit = 50 } = {}) {
+ if (network !== 'mainnet') return [];
+ const data = await getJson(fetchImpl, `${base}/coins?offset=0&limit=${limit}&sort=created_timestamp&order=DESC&includeNsfw=false`);
+ const list = Array.isArray(data) ? data : Array.isArray(data?.coins) ? data.coins : [];
+ const usd = await solUsd();
+ return list.map((c) => normalizeLaunch(c, usd)).filter((l) => l && !l.graduated);
+ },
+ async coin(mint) {
+ return getJson(fetchImpl, `${base}/coins/${encodeURIComponent(mint)}`);
+ },
+ };
+}
diff --git a/apps/desktop/src/runtime/hash.js b/apps/desktop/src/runtime/hash.js
new file mode 100644
index 000000000..1f2b414de
--- /dev/null
+++ b/apps/desktop/src/runtime/hash.js
@@ -0,0 +1,48 @@
+// Payload-hash confirmation for locally filed approvals. Byte-for-byte the same
+// canonical JSON + sha256 the cloud uses (api/_lib/approvals.js), so a hash
+// shown on the desktop equals the hash the web flow would show for the same
+// payload. tests/desktop-runtime.test.js proves the parity against the cloud
+// module's own vectors.
+
+import { createHash } from 'node:crypto';
+
+export function canonicalJson(value) {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
+ if (Array.isArray(value)) return `[${value.map((v) => canonicalJson(v === undefined ? null : v)).join(',')}]`;
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
+}
+
+export function payloadHash(payload) {
+ return createHash('sha256').update(canonicalJson(payload)).digest('hex');
+}
+
+const shortAddr = (a) => {
+ const s = String(a || '');
+ return s.length > 12 ? `${s.slice(0, 4)}...${s.slice(-4)}` : s;
+};
+
+function fmtAmount(amount, asset) {
+ const n = Number(amount);
+ if (!Number.isFinite(n)) return '';
+ const digits = n >= 1 ? 4 : 6;
+ return `${n.toLocaleString('en-US', { maximumFractionDigits: digits })}${asset ? ` ${asset}` : ''}`;
+}
+
+export function chainLabel(chain, network) {
+ const c = String(chain || 'solana');
+ const name = c.charAt(0).toUpperCase() + c.slice(1);
+ return network && network !== 'mainnet' ? `${name} ${network}` : name;
+}
+
+/** The CLAUDE.md spend-gate table: recipient, amount, asset, chain. */
+export function confirmationTable(row) {
+ return [
+ { key: 'recipient', label: 'Recipient', value: row.recipient_label ? `${row.recipient_label} (${shortAddr(row.recipient)})` : row.recipient || 'n/a', full: row.recipient || null },
+ { key: 'amount', label: 'Amount', value: fmtAmount(row.amount, row.asset) },
+ { key: 'asset', label: 'Asset', value: row.asset || 'n/a' },
+ { key: 'chain', label: 'Chain', value: chainLabel(row.chain, row.network) },
+ ];
+}
+
+export const confirmationText = (row) => confirmationTable(row).map((r) => `${r.label}: ${r.value}`).join('\n');
diff --git a/apps/desktop/src/runtime/index.js b/apps/desktop/src/runtime/index.js
new file mode 100644
index 000000000..66c30fede
--- /dev/null
+++ b/apps/desktop/src/runtime/index.js
@@ -0,0 +1,22 @@
+// Runtime bootstrap for the desktop app: wires the keychain-backed keystore,
+// the state file and the redacted log under one directory and returns the
+// runtime plus the IPC-facing facade. Electron-free so the smoke test can run
+// it headless.
+
+import { join } from 'node:path';
+import { createSecureStore } from '../main/secure-store.js';
+import { createKeystore } from './keystore.js';
+import { createLogger } from './log.js';
+import { createRuntime } from './runtime.js';
+import { createLiveExecutor } from './live.js';
+import { createPumpFeed } from './feed.js';
+
+export function createLocalRuntime({ dir, safeStorage, apiBase, token = () => null, onEvent, feed = createPumpFeed(), fetchImpl, now }) {
+ const log = createLogger({ file: join(dir, 'runtime.log') });
+ const keys = createSecureStore({ file: join(dir, 'keys.bin'), safeStorage });
+ const stateFile = createSecureStore({ file: join(dir, 'state.bin'), safeStorage: null });
+ const keystore = createKeystore({ store: keys });
+ const live = createLiveExecutor({ keystore, apiBase, token, fetchImpl });
+ const runtime = createRuntime({ stateStore: stateFile, keystore, log, feed, live, onEvent, now });
+ return { runtime, keystore, log, keysEncrypted: () => keystore.encrypted() };
+}
diff --git a/apps/desktop/src/runtime/keystore.js b/apps/desktop/src/runtime/keystore.js
new file mode 100644
index 000000000..d02d40414
--- /dev/null
+++ b/apps/desktop/src/runtime/keystore.js
@@ -0,0 +1,47 @@
+// Signing keys for local agents. Generated on this machine, stored only inside
+// the OS keychain through the secure store (Electron safeStorage), never
+// written to a log, never sent to the cloud. The renderer and the cloud only
+// ever see the public address; signing happens in-process via sign().
+
+import { Keypair, VersionedTransaction } from '@solana/web3.js';
+
+export function createKeystore({ store }) {
+ const load = () => store.read() || { wallets: {} };
+
+ function create(agentId) {
+ const data = load();
+ if (data.wallets[agentId]) return { address: data.wallets[agentId].address, created: false };
+ const kp = Keypair.generate();
+ data.wallets[agentId] = { address: kp.publicKey.toBase58(), secret: Array.from(kp.secretKey) };
+ store.write(data);
+ return { address: data.wallets[agentId].address, created: true };
+ }
+
+ function address(agentId) {
+ return load().wallets[agentId]?.address || null;
+ }
+
+ function remove(agentId) {
+ const data = load();
+ if (!data.wallets[agentId]) return false;
+ delete data.wallets[agentId];
+ store.write(data);
+ return true;
+ }
+
+ /** Sign a base64 VersionedTransaction. Returns the signed transaction, base64. */
+ function signTransaction(agentId, txBase64) {
+ const w = load().wallets[agentId];
+ if (!w) throw new Error(`no signing key for agent ${agentId}`);
+ const kp = Keypair.fromSecretKey(Uint8Array.from(w.secret));
+ const tx = VersionedTransaction.deserialize(Buffer.from(txBase64, 'base64'));
+ tx.sign([kp]);
+ return Buffer.from(tx.serialize()).toString('base64');
+ }
+
+ function list() {
+ return Object.entries(load().wallets).map(([agentId, w]) => ({ agentId, address: w.address }));
+ }
+
+ return { create, address, remove, signTransaction, list, encrypted: () => Boolean(store.encrypted?.()) };
+}
diff --git a/apps/desktop/src/runtime/live.js b/apps/desktop/src/runtime/live.js
new file mode 100644
index 000000000..49dad63de
--- /dev/null
+++ b/apps/desktop/src/runtime/live.js
@@ -0,0 +1,47 @@
+// Live executor. The unsigned transaction comes from three.ws's buy-prep and
+// sell-prep routes (bearer-authenticated), is signed here with the agent's
+// keychain key, and is broadcast straight to a Solana RPC from this machine.
+// The key never leaves the keystore. A successful trade is then reported to
+// buy-confirm / sell-confirm so the cloud account's ledger matches.
+//
+// This path only runs after the approval gate (or an explicitly 'auto'
+// strategy) has passed in runtime.js. It needs the cloud for the unsigned
+// transaction and a Solana RPC to send it; paper mode needs neither.
+
+import { Connection } from '@solana/web3.js';
+
+const DEFAULT_RPC = { mainnet: 'https://api.mainnet-beta.solana.com', devnet: 'https://api.devnet.solana.com' };
+
+export function createLiveExecutor({ keystore, apiBase = 'https://three.ws', token, rpc = DEFAULT_RPC, fetchImpl = fetch, makeConnection = (url) => new Connection(url, 'confirmed') }) {
+ async function call(path, body) {
+ const bearer = token();
+ if (!bearer) throw Object.assign(new Error('Sign in to three.ws to trade live.'), { code: 'not_signed_in', status: 401 });
+ const r = await fetchImpl(`${apiBase}${path}`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${bearer}` }, body: JSON.stringify(body) });
+ const json = await r.json().catch(() => ({}));
+ if (!r.ok) throw Object.assign(new Error(json.error_description || json.message || `three.ws answered ${r.status}`), { code: json.error || 'cloud_error', status: r.status });
+ return json.data || json;
+ }
+
+ async function signAndSend(agent, txBase64, network) {
+ const signed = keystore.signTransaction(agent.id, txBase64);
+ const conn = makeConnection(rpc[network]);
+ const sig = await conn.sendRawTransaction(Buffer.from(signed, 'base64'), { skipPreflight: false, preflightCommitment: 'confirmed', maxRetries: 3 });
+ await conn.confirmTransaction(sig, 'confirmed');
+ return sig;
+ }
+
+ return {
+ async buy({ agent, payload }) {
+ const prep = await call('/api/pump/buy-prep', { mint: payload.mint, network: agent.network, sol: payload.amount_sol, slippage_bps: payload.slippage_bps, wallet_address: agent.address });
+ const sig = await signAndSend(agent, prep.tx_base64, agent.network);
+ await call('/api/pump/buy-confirm', { mint: payload.mint, network: agent.network, tx_signature: sig, wallet_address: agent.address, sol: payload.amount_sol, route: prep.route, slippage_bps: payload.slippage_bps }).catch(() => null);
+ return sig;
+ },
+ async sell({ agent, payload, position }) {
+ const prep = await call('/api/pump/sell-prep', { mint: position.mint, network: agent.network, tokens: String(position.tokens), slippage_bps: agent.strategy.sizing.max_slippage_bps, wallet_address: agent.address });
+ const sig = await signAndSend(agent, prep.tx_base64, agent.network);
+ await call('/api/pump/sell-confirm', { mint: position.mint, network: agent.network, tx_signature: sig, wallet_address: agent.address, tokens: String(position.tokens), route: prep.route, slippage_bps: agent.strategy.sizing.max_slippage_bps }).catch(() => null);
+ return sig;
+ },
+ };
+}
diff --git a/apps/desktop/src/runtime/log.js b/apps/desktop/src/runtime/log.js
new file mode 100644
index 000000000..7dea216df
--- /dev/null
+++ b/apps/desktop/src/runtime/log.js
@@ -0,0 +1,55 @@
+// Structured runtime log with secret redaction. Nothing that reaches a file, the
+// console or a crash report may carry key material, so every value passes
+// through redact() on the way out: known secret field names are masked, and
+// anything shaped like a Solana secret key (a 64-byte array, an 87 or 88
+// character base58 string) or a bearer token is replaced.
+
+import { appendFileSync, mkdirSync, statSync, renameSync } from 'node:fs';
+import { dirname } from 'node:path';
+
+const SECRET_KEYS = /^(secret|secretkey|secret_key|privatekey|private_key|seed|mnemonic|password|token|access_token|refresh_token|authorization|bearer|keypair)$/i;
+const BASE58_SECRET = /\b[1-9A-HJ-NP-Za-km-z]{86,90}\b/g;
+const BEARER = /\b(Bearer\s+)[A-Za-z0-9._~+/=-]{12,}/gi;
+const MAX_BYTES = 2 * 1024 * 1024;
+
+export function redact(value, depth = 0) {
+ if (depth > 6) return '[deep]';
+ if (typeof value === 'string') return value.replace(BASE58_SECRET, '[redacted-key]').replace(BEARER, '$1[redacted]');
+ if (value instanceof Error) return { name: value.name, message: redact(value.message, depth + 1) };
+ if (Array.isArray(value)) {
+ if (value.length >= 32 && value.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) return '[redacted-bytes]';
+ return value.map((v) => redact(v, depth + 1));
+ }
+ if (value && typeof value === 'object') {
+ if (ArrayBuffer.isView(value)) return '[redacted-bytes]';
+ const out = {};
+ for (const [k, v] of Object.entries(value)) out[k] = SECRET_KEYS.test(k) ? '[redacted]' : redact(v, depth + 1);
+ return out;
+ }
+ return value;
+}
+
+export function createLogger({ file = null, sink = null, now = Date.now } = {}) {
+ function write(level, event, data) {
+ const line = { t: new Date(now()).toISOString(), level, event, ...(data ? { data: redact(data) } : {}) };
+ const text = JSON.stringify(line);
+ if (sink) sink(line);
+ if (!file) return;
+ try {
+ mkdirSync(dirname(file), { recursive: true });
+ try {
+ if (statSync(file).size > MAX_BYTES) renameSync(file, `${file}.1`);
+ } catch {
+ // first write: nothing to rotate
+ }
+ appendFileSync(file, `${text}\n`, { mode: 0o600 });
+ } catch {
+ // Logging must never take the runtime down.
+ }
+ }
+ return {
+ info: (event, data) => write('info', event, data),
+ warn: (event, data) => write('warn', event, data),
+ error: (event, data) => write('error', event, data),
+ };
+}
diff --git a/apps/desktop/src/runtime/runtime.js b/apps/desktop/src/runtime/runtime.js
new file mode 100644
index 000000000..5f4112b24
--- /dev/null
+++ b/apps/desktop/src/runtime/runtime.js
@@ -0,0 +1,483 @@
+// The local agent runtime. Runs agents, strategies, orders and automations on
+// this machine. Signing keys live in the keystore (OS keychain), state lives in
+// a plain JSON file with no key material, and every action that signs or moves
+// funds in live mode waits for an explicit yes carrying the payload hash the
+// owner was shown (the same canonical-JSON sha256 the web flow uses).
+//
+// Pure of Electron: main.js injects the keystore, the store and the callbacks,
+// the smoke test injects the same real pieces with a temp directory.
+
+import { randomUUID } from 'node:crypto';
+import { canonicalJson, payloadHash, confirmationTable, confirmationText } from './hash.js';
+import { validateStrategyConfig, matchesEntry, shouldExit, effectivePriceImpactPct } from './strategy-schema.js';
+import { createPumpFeed } from './feed.js';
+import { quoteBuy, quoteSell } from './curve.js';
+
+export const APPROVAL_TTL_MS = 15 * 60 * 1000;
+export const AGENT_STATES = ['idle', 'working', 'waiting_approval', 'paused', 'error', 'killed'];
+const MAX_RECEIPTS = 500;
+
+export class RuntimeError extends Error {
+ constructor(code, message, status = 400) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+
+const emptyState = () => ({ version: 1, agents: {}, positions: [], approvals: {}, receipts: [], seen: {} });
+
+export function createRuntime({ stateStore, keystore, log, feed = createPumpFeed(), live = null, onEvent = () => {}, now = Date.now }) {
+ const state = { ...emptyState(), ...(stateStore.read() || {}) };
+ const persist = () => stateStore.write(state);
+ const emit = (type, data) => {
+ try {
+ onEvent({ type, ...data });
+ } catch (err) {
+ log.warn('event_handler_failed', { type, err });
+ }
+ };
+
+ const agentOf = (id) => {
+ const a = state.agents[id];
+ if (!a) throw new RuntimeError('agent_not_found', `No agent ${id}.`, 404);
+ return a;
+ };
+
+ function setStatus(agent, status, detail = null) {
+ if (agent.status === status && agent.detail === detail) return;
+ agent.status = status;
+ agent.detail = detail;
+ persist();
+ emit('status', { agent: publicAgent(agent), face: face() });
+ }
+
+ // ── agents ───────────────────────────────────────────────────────────────
+ function createAgent({ name, mode = 'paper', network = 'mainnet', strategy = {} }) {
+ const cleanName = String(name || '').trim().slice(0, 60);
+ if (!cleanName) throw new RuntimeError('invalid_name', 'An agent needs a name.');
+ if (!['paper', 'live'].includes(mode)) throw new RuntimeError('invalid_mode', 'Mode must be paper or live.');
+ if (!['mainnet', 'devnet'].includes(network)) throw new RuntimeError('invalid_network', 'Network must be mainnet or devnet.');
+ const v = validateStrategyConfig({ ...strategy, network });
+ if (!v.valid) throw new RuntimeError('invalid_strategy', v.errors.map((e) => `${e.field}: ${e.message}`).join(' '));
+ const id = `ag_${randomUUID().slice(0, 12)}`;
+ const wallet = keystore.create(id);
+ state.agents[id] = {
+ id, name: cleanName, mode, network, strategy: v.config, address: wallet.address,
+ status: 'idle', detail: null, orders: [], automations: [], created_at: now(), last_sweep_at: null, last_cooldown_at: 0,
+ };
+ persist();
+ log.info('agent_created', { id, mode, network });
+ emit('status', { agent: publicAgent(state.agents[id]), face: face() });
+ return publicAgent(state.agents[id]);
+ }
+
+ function pause(id) {
+ const a = agentOf(id);
+ if (a.status === 'killed') throw new RuntimeError('agent_killed', 'A killed agent cannot be paused.', 409);
+ setStatus(a, 'paused');
+ return publicAgent(a);
+ }
+
+ function resume(id) {
+ const a = agentOf(id);
+ if (a.status === 'killed') throw new RuntimeError('agent_killed', 'A killed agent cannot be resumed.', 409);
+ setStatus(a, 'idle');
+ return publicAgent(a);
+ }
+
+ /** Stop the agent for good: denies its pending approvals and disables orders and automations. Receipts and positions stay. */
+ function kill(id) {
+ const a = agentOf(id);
+ for (const ap of Object.values(state.approvals)) {
+ if (ap.agent_id === id && ap.status === 'pending') decideLocal(ap, 'denied', 'kill');
+ }
+ a.orders = [];
+ a.automations = [];
+ setStatus(a, 'killed');
+ log.info('agent_killed', { id });
+ return publicAgent(a);
+ }
+
+ function remove(id) {
+ const a = agentOf(id);
+ if (a.status !== 'killed') throw new RuntimeError('agent_active', 'Kill the agent before removing it.', 409);
+ if (state.positions.some((p) => p.agent_id === id && p.status === 'open')) {
+ throw new RuntimeError('open_positions', 'Close the open positions before removing the agent.', 409);
+ }
+ keystore.remove(id);
+ delete state.agents[id];
+ persist();
+ return { removed: id };
+ }
+
+ function addOrder(id, order) {
+ const a = agentOf(id);
+ if (a.status === 'killed') throw new RuntimeError('agent_killed', 'The agent is killed.', 409);
+ const side = order.side === 'sell' ? 'sell' : 'buy';
+ if (!order.mint || typeof order.mint !== 'string') throw new RuntimeError('invalid_order', 'An order needs a mint.');
+ const below = Number(order.trigger?.price_sol_below);
+ const above = Number(order.trigger?.price_sol_above);
+ const hasBelow = Number.isFinite(below) && below > 0;
+ const hasAbove = Number.isFinite(above) && above > 0;
+ if (!hasBelow && !hasAbove) throw new RuntimeError('invalid_order', 'An order needs price_sol_below or price_sol_above.');
+ const amount = Number(order.amount_sol);
+ if (side === 'buy' && !(amount > 0 && amount <= a.strategy.sizing.amount_sol * 10)) {
+ throw new RuntimeError('invalid_order', 'Buy size must be positive and within ten times the strategy size.');
+ }
+ const o = { id: `or_${randomUUID().slice(0, 10)}`, mint: order.mint, side, amount_sol: side === 'buy' ? amount : null, trigger: { ...(hasBelow && { price_sol_below: below }), ...(hasAbove && { price_sol_above: above }) }, created_at: now() };
+ a.orders.push(o);
+ persist();
+ return o;
+ }
+
+ function removeOrder(id, orderId) {
+ const a = agentOf(id);
+ a.orders = a.orders.filter((o) => o.id !== orderId);
+ persist();
+ }
+
+ function addAutomation(id, auto) {
+ const a = agentOf(id);
+ if (a.status === 'killed') throw new RuntimeError('agent_killed', 'The agent is killed.', 409);
+ const every = Number(auto.every_minutes);
+ if (!(every >= 1 && every <= 10080)) throw new RuntimeError('invalid_automation', 'every_minutes must be between 1 and 10080.');
+ if (!['sweep', 'expire_sweep'].includes(auto.action)) throw new RuntimeError('invalid_automation', 'action must be sweep or expire_sweep.');
+ const x = { id: `au_${randomUUID().slice(0, 10)}`, action: auto.action, every_minutes: every, last_run_at: 0 };
+ a.automations.push(x);
+ persist();
+ return x;
+ }
+
+ // ── approvals ────────────────────────────────────────────────────────────
+ function decideLocal(ap, status, via) {
+ ap.status = status;
+ ap.decided_at = now();
+ ap.via = via;
+ emit('approval', { approval: publicApproval(ap) });
+ }
+
+ /** The exact action that will run, plus the table and hash the owner is shown. */
+ function fileApproval(agent, payload, row) {
+ const dupe = Object.values(state.approvals).find((ap) => ap.agent_id === agent.id && ap.status === 'pending' && ap.payload.idempotency_key === payload.idempotency_key);
+ if (dupe) return dupe;
+ const ap = {
+ id: `ap_${randomUUID().slice(0, 12)}`, agent_id: agent.id, status: 'pending', payload,
+ hash: payloadHash(payload), row, created_at: now(), expires_at: now() + APPROVAL_TTL_MS,
+ };
+ state.approvals[ap.id] = ap;
+ persist();
+ setStatus(agent, 'waiting_approval', `${row.amount} ${row.asset} to ${row.recipient_label || row.recipient}`);
+ emit('approval', { approval: publicApproval(ap), notify: true });
+ return ap;
+ }
+
+ function publicApproval(ap) {
+ return {
+ id: ap.id, agent_id: ap.agent_id, status: effectiveStatus(ap), hash: ap.hash, payload: ap.payload,
+ table: confirmationTable(ap.row), text: confirmationText(ap.row), created_at: ap.created_at, expires_at: ap.expires_at, decided_at: ap.decided_at || null,
+ };
+ }
+
+ const effectiveStatus = (ap) => (ap.status === 'pending' && ap.expires_at <= now() ? 'expired' : ap.status);
+
+ function listApprovals({ status = null, agentId = null } = {}) {
+ return Object.values(state.approvals)
+ .filter((ap) => (!agentId || ap.agent_id === agentId) && (!status || effectiveStatus(ap) === status))
+ .sort((a, b) => b.created_at - a.created_at)
+ .map(publicApproval);
+ }
+
+ function refreshWaiting(agent) {
+ const waiting = Object.values(state.approvals).some((ap) => ap.agent_id === agent.id && effectiveStatus(ap) === 'pending');
+ if (agent.status === 'waiting_approval' && !waiting) setStatus(agent, 'idle');
+ }
+
+ /**
+ * Approve or deny. An approval must present the hash it was shown; the stored
+ * payload is re-hashed here so neither a stale view nor an edited state file
+ * can run an action that differs from what the owner saw.
+ */
+ async function decide(approvalId, { decision, hash, via = 'desktop' }) {
+ const ap = state.approvals[approvalId];
+ if (!ap) throw new RuntimeError('approval_not_found', 'No such approval.', 404);
+ if (!['approve', 'deny'].includes(decision)) throw new RuntimeError('invalid_decision', 'Decision must be approve or deny.');
+ if (effectiveStatus(ap) === 'expired' && ap.status === 'pending') {
+ decideLocal(ap, 'expired', 'timeout');
+ persist();
+ throw new RuntimeError('approval_expired', 'This approval expired. Nothing was run.', 410);
+ }
+ if (ap.status !== 'pending') throw new RuntimeError('approval_not_pending', `This approval is already ${ap.status}.`, 409);
+ const agent = agentOf(ap.agent_id);
+ if (decision === 'deny') {
+ decideLocal(ap, 'denied', via);
+ persist();
+ refreshWaiting(agent);
+ return publicApproval(ap);
+ }
+ if (agent.status === 'killed') throw new RuntimeError('agent_killed', 'The agent was killed. Nothing was run.', 409);
+ if (typeof hash !== 'string' || hash.toLowerCase() !== ap.hash) {
+ throw new RuntimeError('hash_mismatch', 'The hash does not match the action on file. Nothing was run.', 409);
+ }
+ if (payloadHash(ap.payload) !== ap.hash) {
+ throw new RuntimeError('payload_changed', 'The stored action changed after it was filed. Nothing was run.', 409);
+ }
+ ap.status = 'executing';
+ persist();
+ try {
+ const receipt = await execute(agent, ap.payload, { approval: ap });
+ ap.status = 'executed';
+ ap.decided_at = now();
+ ap.via = via;
+ ap.receipt_id = receipt.id;
+ } catch (err) {
+ ap.status = 'failed';
+ ap.decided_at = now();
+ ap.error = String(err.message || err).slice(0, 300);
+ setStatus(agent, 'error', ap.error);
+ log.error('approval_execute_failed', { id: ap.id, err });
+ }
+ persist();
+ emit('approval', { approval: publicApproval(ap) });
+ refreshWaiting(agent);
+ return publicApproval(ap);
+ }
+
+ // ── execution ────────────────────────────────────────────────────────────
+ function recordReceipt(r) {
+ const receipt = { id: `rc_${randomUUID().slice(0, 12)}`, at: now(), ...r };
+ state.receipts.unshift(receipt);
+ if (state.receipts.length > MAX_RECEIPTS) state.receipts.length = MAX_RECEIPTS;
+ persist();
+ emit('receipt', { receipt });
+ return receipt;
+ }
+
+ async function execute(agent, payload, { approval = null } = {}) {
+ if (payload.side === 'buy') return executeBuy(agent, payload, approval);
+ return executeSell(agent, payload, approval);
+ }
+
+ async function executeBuy(agent, p, approval) {
+ const coin = await feed.coin(p.mint);
+ if (!coin) throw new RuntimeError('quote_unavailable', 'The launch feed has no data for this coin right now.', 502);
+ const q = quoteBuy(coin, p.amount_sol);
+ if (p.max_price_impact_pct != null && q.impact_pct > p.max_price_impact_pct) {
+ throw new RuntimeError('price_impact', `Price impact ${q.impact_pct.toFixed(2)}% exceeds the ${p.max_price_impact_pct}% cap.`, 409);
+ }
+ let signature = null;
+ if (agent.mode === 'live') {
+ if (!live) throw new RuntimeError('live_unavailable', 'Live execution is not configured on this install.', 409);
+ signature = await live.buy({ agent, payload: p, quote: q });
+ }
+ state.positions.push({
+ id: `po_${randomUUID().slice(0, 10)}`, agent_id: agent.id, mint: p.mint, symbol: coin.symbol || null, status: 'open',
+ entry_lamports: Math.round(p.amount_sol * 1e9), tokens: q.tokens, peak_value_lamports: Math.round(p.amount_sol * 1e9),
+ opened_at: now(), network: agent.network, mode: agent.mode,
+ });
+ agent.last_cooldown_at = now();
+ return recordReceipt({ agent_id: agent.id, kind: 'buy', mode: agent.mode, network: agent.network, mint: p.mint, symbol: coin.symbol || null, sol: p.amount_sol, tokens: q.tokens, impact_pct: q.impact_pct, signature, approval_id: approval?.id || null, payload_hash: approval?.hash || null });
+ }
+
+ async function executeSell(agent, p, approval) {
+ const pos = state.positions.find((x) => x.id === p.position_id && x.status === 'open');
+ if (!pos) throw new RuntimeError('position_not_found', 'That position is not open.', 404);
+ const coin = await feed.coin(pos.mint);
+ if (!coin) throw new RuntimeError('quote_unavailable', 'The launch feed has no data for this coin right now.', 502);
+ const q = quoteSell(coin, pos.tokens);
+ let signature = null;
+ if (agent.mode === 'live') {
+ if (!live) throw new RuntimeError('live_unavailable', 'Live execution is not configured on this install.', 409);
+ signature = await live.sell({ agent, payload: p, position: pos, quote: q });
+ }
+ pos.status = 'closed';
+ pos.closed_at = now();
+ pos.exit_lamports = q.lamports;
+ pos.exit_reason = p.reason || 'manual';
+ return recordReceipt({ agent_id: agent.id, kind: 'sell', mode: agent.mode, network: agent.network, mint: pos.mint, symbol: pos.symbol, sol: q.lamports / 1e9, tokens: pos.tokens, pnl_pct: ((q.lamports - pos.entry_lamports) / pos.entry_lamports) * 100, reason: pos.exit_reason, signature, approval_id: approval?.id || null, payload_hash: approval?.hash || null });
+ }
+
+ /** Paper never needs a yes (nothing signs). Live needs one unless the strategy is explicitly 'auto'. */
+ const needsApproval = (agent) => agent.mode === 'live' && agent.strategy.mode !== 'auto';
+
+ async function act(agent, payload, row) {
+ if (needsApproval(agent)) return fileApproval(agent, payload, row);
+ return execute(agent, payload);
+ }
+
+ const buyRow = (agent, p, symbol) => ({
+ recipient: p.mint, recipient_label: symbol ? `$${symbol}` : null, amount: p.amount_sol, asset: 'SOL', chain: 'solana', network: agent.network, side: 'buy',
+ });
+
+ // ── scheduler ────────────────────────────────────────────────────────────
+ function buyPayload(agent, mint) {
+ const c = agent.strategy;
+ return {
+ kind: 'local_strategy_buy', agent_id: agent.id, strategy: c.name || 'local', network: agent.network, mint, side: 'buy',
+ amount_sol: c.sizing.amount_sol, slippage_bps: c.sizing.max_slippage_bps,
+ max_price_impact_pct: effectivePriceImpactPct(c, null), idempotency_key: `${agent.id}:${mint}`,
+ };
+ }
+
+ async function sweepEntries(agent) {
+ const c = agent.strategy;
+ const launches = await feed.launches({ network: agent.network });
+ const open = state.positions.filter((p) => p.agent_id === agent.id && p.status === 'open');
+ const pending = Object.values(state.approvals).filter((ap) => ap.agent_id === agent.id && effectiveStatus(ap) === 'pending').length;
+ let slots = c.risk.max_concurrent_positions - open.length - pending;
+ const seen = new Set(state.seen[agent.id] || []);
+ const decisions = [];
+ for (const launch of launches) {
+ if (slots <= 0) break;
+ if (seen.has(launch.mint)) continue;
+ if (c.risk.cooldown_minutes > 0 && now() - agent.last_cooldown_at < c.risk.cooldown_minutes * 60000) break;
+ const verdict = matchesEntry(c, launch, now());
+ seen.add(launch.mint);
+ decisions.push({ mint: launch.mint, pass: verdict.pass, reasons: verdict.reasons });
+ if (!verdict.pass) continue;
+ const payload = buyPayload(agent, launch.mint);
+ try {
+ await act(agent, payload, buyRow(agent, payload, launch.symbol));
+ slots -= 1;
+ } catch (err) {
+ log.warn('entry_failed', { agent: agent.id, mint: launch.mint, err });
+ }
+ }
+ state.seen[agent.id] = [...seen].slice(-500);
+ return decisions;
+ }
+
+ async function sweepExits(agent) {
+ const open = state.positions.filter((p) => p.agent_id === agent.id && p.status === 'open');
+ for (const pos of open) {
+ const coin = await feed.coin(pos.mint);
+ if (!coin) continue;
+ const q = quoteSell(coin, pos.tokens);
+ pos.peak_value_lamports = Math.max(pos.peak_value_lamports, q.lamports);
+ const verdict = shouldExit(agent.strategy, pos, q.lamports, now());
+ if (!verdict.exit) continue;
+ const payload = { kind: 'local_strategy_sell', agent_id: agent.id, network: agent.network, mint: pos.mint, side: 'sell', position_id: pos.id, reason: verdict.reason, idempotency_key: `${agent.id}:${pos.id}:sell` };
+ try {
+ await act(agent, payload, { recipient: pos.mint, recipient_label: pos.symbol ? `$${pos.symbol}` : null, amount: q.lamports / 1e9, asset: 'SOL', chain: 'solana', network: agent.network, side: 'sell' });
+ } catch (err) {
+ log.warn('exit_failed', { agent: agent.id, mint: pos.mint, err });
+ }
+ }
+ persist();
+ }
+
+ async function runOrders(agent) {
+ for (const order of [...agent.orders]) {
+ const coin = await feed.coin(order.mint);
+ if (!coin || !(Number(coin.virtual_token_reserves) > 0)) continue;
+ const price = Number(coin.virtual_sol_reserves) / 1e9 / (Number(coin.virtual_token_reserves) / 1e6);
+ const hit = (order.trigger.price_sol_below && price <= order.trigger.price_sol_below) || (order.trigger.price_sol_above && price >= order.trigger.price_sol_above);
+ if (!hit) continue;
+ agent.orders = agent.orders.filter((o) => o.id !== order.id);
+ persist();
+ if (order.side === 'buy') {
+ const payload = { ...buyPayload(agent, order.mint), amount_sol: order.amount_sol, kind: 'local_order_buy', idempotency_key: `${agent.id}:${order.id}` };
+ await act(agent, payload, buyRow(agent, payload, coin.symbol));
+ } else {
+ const pos = state.positions.find((x) => x.agent_id === agent.id && x.mint === order.mint && x.status === 'open');
+ if (!pos) continue;
+ const q = quoteSell(coin, pos.tokens);
+ const payload = { kind: 'local_order_sell', agent_id: agent.id, network: agent.network, mint: pos.mint, side: 'sell', position_id: pos.id, reason: 'order', idempotency_key: `${agent.id}:${order.id}` };
+ await act(agent, payload, { recipient: pos.mint, recipient_label: pos.symbol ? `$${pos.symbol}` : null, amount: q.lamports / 1e9, asset: 'SOL', chain: 'solana', network: agent.network, side: 'sell' });
+ }
+ }
+ }
+
+ function expireSweep() {
+ for (const ap of Object.values(state.approvals)) {
+ if (ap.status === 'pending' && ap.expires_at <= now()) decideLocal(ap, 'expired', 'timeout');
+ }
+ persist();
+ for (const a of Object.values(state.agents)) refreshWaiting(a);
+ }
+
+ /** One scheduler pass for one agent. Returns what it decided, for logs and tests. */
+ async function tickAgent(agent) {
+ if (agent.status === 'paused' || agent.status === 'killed') return { skipped: agent.status };
+ const wasWaiting = agent.status === 'waiting_approval';
+ setStatus(agent, 'working');
+ try {
+ expireSweep();
+ await sweepExits(agent);
+ await runOrders(agent);
+ const decisions = await sweepEntries(agent);
+ for (const au of agent.automations) {
+ if (now() - au.last_run_at >= au.every_minutes * 60000) {
+ au.last_run_at = now();
+ if (au.action === 'expire_sweep') expireSweep();
+ }
+ }
+ agent.last_sweep_at = now();
+ const waiting = Object.values(state.approvals).some((ap) => ap.agent_id === agent.id && effectiveStatus(ap) === 'pending');
+ setStatus(agent, waiting ? 'waiting_approval' : 'idle', waiting ? agent.detail : null);
+ persist();
+ return { decisions };
+ } catch (err) {
+ log.error('tick_failed', { agent: agent.id, err });
+ setStatus(agent, 'error', String(err.message || err).slice(0, 200));
+ return { error: err.message, wasWaiting };
+ }
+ }
+
+ let timer = null;
+ let ticking = false;
+ async function tick() {
+ if (ticking) return;
+ ticking = true;
+ try {
+ for (const agent of Object.values(state.agents)) {
+ if (agent.status === 'error') setStatus(agent, 'idle');
+ await tickAgent(agent);
+ }
+ } finally {
+ ticking = false;
+ }
+ }
+
+ function start({ intervalMs = 30_000 } = {}) {
+ if (timer) return;
+ timer = setInterval(() => void tick(), intervalMs);
+ timer.unref?.();
+ void tick();
+ }
+
+ function stop() {
+ if (timer) clearInterval(timer);
+ timer = null;
+ }
+
+ // ── views ────────────────────────────────────────────────────────────────
+ function publicAgent(a) {
+ const open = state.positions.filter((p) => p.agent_id === a.id && p.status === 'open').length;
+ const pending = Object.values(state.approvals).filter((ap) => ap.agent_id === a.id && effectiveStatus(ap) === 'pending').length;
+ return {
+ id: a.id, name: a.name, mode: a.mode, network: a.network, address: a.address, status: a.status, detail: a.detail,
+ strategy: a.strategy, orders: a.orders, automations: a.automations, open_positions: open, pending_approvals: pending,
+ last_sweep_at: a.last_sweep_at, created_at: a.created_at,
+ };
+ }
+
+ /** What the mascot shows: the most urgent state across all agents. */
+ function face() {
+ const statuses = Object.values(state.agents).map((a) => a.status);
+ const order = ['error', 'waiting_approval', 'working', 'idle', 'paused', 'killed'];
+ const top = order.find((s) => statuses.includes(s)) || 'none';
+ return { state: top, agents: statuses.length };
+ }
+
+ return {
+ createAgent, pause, resume, kill, remove, addOrder, removeOrder, addAutomation,
+ listAgents: () => Object.values(state.agents).map(publicAgent),
+ getAgent: (id) => publicAgent(agentOf(id)),
+ listApprovals, decide, tick, tickAgent, start, stop, face,
+ positions: ({ agentId = null } = {}) => state.positions.filter((p) => !agentId || p.agent_id === agentId),
+ receipts: ({ agentId = null, limit = 100 } = {}) => state.receipts.filter((r) => !agentId || r.agent_id === agentId).slice(0, limit),
+ exportConfig: () => ({ agents: Object.values(state.agents).map((a) => ({ id: a.id, name: a.name, mode: a.mode, network: a.network, address: a.address, strategy: a.strategy, status: a.status })) }),
+ canonicalJson,
+ };
+}
diff --git a/apps/desktop/src/runtime/strategy-schema.js b/apps/desktop/src/runtime/strategy-schema.js
new file mode 100644
index 000000000..aad7193bb
--- /dev/null
+++ b/apps/desktop/src/runtime/strategy-schema.js
@@ -0,0 +1,512 @@
+// Strategy Object config — the validated, versioned rule set behind a Strategy.
+//
+// A strategy is NOT free text: it is a structured plan with a real schema. This
+// module is the single source of truth for that schema. It normalizes arbitrary
+// owner input into a clean, bounded config; validates it (so a malformed rule
+// set can never be saved); and evaluates a real pump.fun launch against the
+// entry conditions (pure + synchronous, so it is trivially testable and the same
+// logic runs in the runtime and in a backtest).
+//
+// Critically, the strategy's own caps (per-trade size, slippage, concurrency)
+// are ADDITIONAL constraints layered on top of the agent's server-side spend
+// policy — never a way around it. The runtime sizes a buy from `sizing.amount_sol`
+// but the trade still passes through the full guard + custody path, so a strategy
+// can never exceed the spend leash. Ever.
+//
+// Version 2 adds the strategy settings an owner tunes in the Strategy Lab:
+// entry.sources which launch venues a candidate may come from
+// sizing.max_price_impact_bps a per-strategy price-impact ceiling, applied
+// as min(this, the agent's own breaker)
+// research pre-buy research gates evaluated against a real
+// gate report (holders, top holder, liquidity,
+// firewall security score, authorities, dev history)
+// mode 'auto' buys within caps; 'ask' files an approval
+// request and waits for the owner's explicit yes
+// A v1 config normalizes to v2 losslessly; a config with no mode becomes 'ask',
+// the conservative default (the migration backfills stored rows the same way).
+
+const ENTRY_TRIGGERS = ['new_launch'];
+const NETWORKS = ['mainnet', 'devnet'];
+const STRATEGY_MODES = ['auto', 'ask'];
+// Where a candidate can come from. `pump_curve` is any live pump.fun bonding-curve
+// launch; `three_ws_launch` is a coin an agent launched through three.ws
+// (pump_agent_mints), which is also on the curve. An empty list means every
+// source; ['three_ws_launch'] means platform launches only.
+const ENTRY_SOURCES = ['pump_curve', 'three_ws_launch'];
+export const STRATEGY_CONFIG_VERSION = 2;
+
+export const STRATEGY_CONFIG_DEFAULTS = Object.freeze({
+ version: STRATEGY_CONFIG_VERSION,
+ mode: 'ask',
+ network: 'mainnet',
+ entry: {
+ trigger: 'new_launch',
+ sources: [],
+ max_age_minutes: 60,
+ min_market_cap_usd: null,
+ max_market_cap_usd: null,
+ min_liquidity_sol: null,
+ require_socials: false,
+ max_creator_launches: null,
+ min_creator_graduated: null,
+ require_sol_quote: true,
+ },
+ sizing: {
+ amount_sol: 0.1,
+ max_slippage_bps: 500,
+ max_price_impact_bps: null,
+ },
+ exits: {
+ take_profit_pct: 100, // +100% = 2x
+ stop_loss_pct: 40, // -40%
+ trailing_stop_pct: null,
+ max_hold_minutes: null,
+ },
+ risk: {
+ max_concurrent_positions: 3,
+ cooldown_minutes: 0,
+ },
+ research: {
+ min_holders: null,
+ max_top_holder_pct: null,
+ min_liquidity_sol: null,
+ security_min_score: null,
+ require_no_mint_authority: false,
+ require_no_freeze_authority: false,
+ dev_history: {
+ max_launches: null,
+ min_graduated: null,
+ block_dev_sold: false,
+ },
+ },
+});
+
+// Hard ceilings the schema enforces regardless of input — defensive bounds so a
+// stored config can never carry a nonsense number into the runtime.
+const BOUNDS = Object.freeze({
+ amount_sol: { min: 0.0001, max: 100 },
+ max_slippage_bps: { min: 0, max: 10000 },
+ max_age_minutes: { min: 1, max: 10080 }, // up to 7 days
+ take_profit_pct: { min: 1, max: 100000 },
+ stop_loss_pct: { min: 1, max: 99 },
+ trailing_stop_pct: { min: 1, max: 99 },
+ max_hold_minutes: { min: 1, max: 525600 }, // up to 1 year
+ max_concurrent_positions: { min: 1, max: 50 },
+ cooldown_minutes: { min: 0, max: 10080 },
+ market_cap_usd: { min: 0, max: 1e12 },
+ liquidity_sol: { min: 0, max: 1e9 },
+ creator_count: { min: 0, max: 100000 },
+ price_impact_bps: { min: 1, max: 10000 },
+ holders: { min: 0, max: 10000000 },
+ pct: { min: 0, max: 100 },
+ score: { min: 0, max: 100 },
+});
+
+// Owners and the natural-language compiler may write camelCase; the stored
+// shape is snake_case like every other config key. First present key wins.
+function pick(obj, ...keys) {
+ for (const k of keys) if (obj && obj[k] !== undefined) return obj[k];
+ return undefined;
+}
+
+function normalizeSources(v) {
+ if (!Array.isArray(v)) return [];
+ const out = [];
+ for (const raw of v) {
+ const s = String(raw || '').trim().toLowerCase();
+ if (ENTRY_SOURCES.includes(s) && !out.includes(s)) out.push(s);
+ }
+ return out.length === ENTRY_SOURCES.length ? [] : out;
+}
+
+function numOrNull(v, { min = -Infinity, max = Infinity } = {}) {
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ if (!Number.isFinite(n)) return null;
+ return Math.min(max, Math.max(min, n));
+}
+
+function intOrNull(v, bounds) {
+ const n = numOrNull(v, bounds);
+ return n === null ? null : Math.round(n);
+}
+
+function clampNum(v, def, { min = 0, max = Infinity, round = false } = {}) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return def;
+ const c = Math.min(max, Math.max(min, n));
+ return round ? Math.round(c) : c;
+}
+
+/** Turn a strategy name into a URL-safe, stable slug. */
+export function slugifyStrategy(name) {
+ const base = String(name || '')
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 48);
+ return base || 'strategy';
+}
+
+/**
+ * Coerce arbitrary input into a clean, bounded, complete strategy config.
+ * Always returns a fully-populated object (missing keys fall back to defaults).
+ */
+export function normalizeStrategyConfig(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const e = r.entry && typeof r.entry === 'object' ? r.entry : {};
+ const s = r.sizing && typeof r.sizing === 'object' ? r.sizing : {};
+ const x = r.exits && typeof r.exits === 'object' ? r.exits : {};
+ const k = r.risk && typeof r.risk === 'object' ? r.risk : {};
+ const q = r.research && typeof r.research === 'object' ? r.research : {};
+ const dvRaw = pick(q, 'dev_history', 'devHistory');
+ const dv = dvRaw && typeof dvRaw === 'object' ? dvRaw : {};
+ const d = STRATEGY_CONFIG_DEFAULTS;
+
+ const trigger = ENTRY_TRIGGERS.includes(e.trigger) ? e.trigger : d.entry.trigger;
+ const network = NETWORKS.includes(r.network) ? r.network : d.network;
+ const mode = STRATEGY_MODES.includes(r.mode) ? r.mode : d.mode;
+
+ // Creator history and liquidity exist both as cheap entry pre-filters (v1)
+ // and as research gates (v2). They are one setting: the research value wins
+ // when present, the legacy entry value fills it otherwise, and both halves are
+ // written back identical so the two evaluators can never disagree.
+ const maxLaunches = intOrNull(pick(dv, 'max_launches', 'maxLaunches') ?? e.max_creator_launches, BOUNDS.creator_count);
+ const minGraduated = intOrNull(pick(dv, 'min_graduated', 'minGraduated') ?? e.min_creator_graduated, BOUNDS.creator_count);
+ const minLiq = numOrNull(pick(q, 'min_liquidity_sol', 'minLiquiditySol') ?? e.min_liquidity_sol, BOUNDS.liquidity_sol);
+
+ return {
+ version: STRATEGY_CONFIG_VERSION,
+ mode,
+ network,
+ entry: {
+ trigger,
+ sources: normalizeSources(e.sources),
+ max_age_minutes: clampNum(e.max_age_minutes, d.entry.max_age_minutes, { ...BOUNDS.max_age_minutes, round: true }),
+ min_market_cap_usd: numOrNull(e.min_market_cap_usd, BOUNDS.market_cap_usd),
+ max_market_cap_usd: numOrNull(e.max_market_cap_usd, BOUNDS.market_cap_usd),
+ min_liquidity_sol: minLiq,
+ require_socials: e.require_socials === true,
+ max_creator_launches: maxLaunches,
+ min_creator_graduated: minGraduated,
+ require_sol_quote: e.require_sol_quote !== false,
+ },
+ sizing: {
+ amount_sol: clampNum(s.amount_sol, d.sizing.amount_sol, BOUNDS.amount_sol),
+ max_slippage_bps: clampNum(s.max_slippage_bps, d.sizing.max_slippage_bps, { ...BOUNDS.max_slippage_bps, round: true }),
+ max_price_impact_bps: intOrNull(pick(s, 'max_price_impact_bps', 'maxPriceImpactBps'), BOUNDS.price_impact_bps),
+ },
+ exits: {
+ take_profit_pct: numOrNull(x.take_profit_pct, BOUNDS.take_profit_pct),
+ // stop_loss is mandatory and always present — default applied if absent/invalid.
+ stop_loss_pct: clampNum(x.stop_loss_pct, d.exits.stop_loss_pct, BOUNDS.stop_loss_pct),
+ trailing_stop_pct: numOrNull(x.trailing_stop_pct, BOUNDS.trailing_stop_pct),
+ max_hold_minutes: intOrNull(x.max_hold_minutes, BOUNDS.max_hold_minutes),
+ },
+ risk: {
+ max_concurrent_positions: clampNum(k.max_concurrent_positions, d.risk.max_concurrent_positions, { ...BOUNDS.max_concurrent_positions, round: true }),
+ cooldown_minutes: clampNum(k.cooldown_minutes, d.risk.cooldown_minutes, { ...BOUNDS.cooldown_minutes, round: true }),
+ },
+ research: {
+ min_holders: intOrNull(pick(q, 'min_holders', 'minHolders'), BOUNDS.holders),
+ max_top_holder_pct: numOrNull(pick(q, 'max_top_holder_pct', 'maxTopHolderPct'), BOUNDS.pct),
+ min_liquidity_sol: minLiq,
+ security_min_score: intOrNull(pick(q, 'security_min_score', 'securityMinScore'), BOUNDS.score),
+ require_no_mint_authority: pick(q, 'require_no_mint_authority', 'requireNoMintAuthority') === true,
+ require_no_freeze_authority: pick(q, 'require_no_freeze_authority', 'requireNoFreezeAuthority') === true,
+ dev_history: {
+ max_launches: maxLaunches,
+ min_graduated: minGraduated,
+ block_dev_sold: pick(dv, 'block_dev_sold', 'blockDevSold') === true,
+ },
+ },
+ };
+}
+
+/** True when any research gate is switched on (the runtime skips the report otherwise). */
+export function researchGatesActive(config) {
+ const g = config?.research;
+ if (!g) return false;
+ const dv = g.dev_history || {};
+ return g.min_holders != null || g.max_top_holder_pct != null || g.min_liquidity_sol != null
+ || g.security_min_score != null || g.require_no_mint_authority || g.require_no_freeze_authority
+ || dv.max_launches != null || dv.min_graduated != null || dv.block_dev_sold === true;
+}
+
+/**
+ * The effective price-impact ceiling in percent for one strategy trade: the
+ * tighter of the agent's breaker and the strategy's own max_price_impact_bps.
+ * A strategy can only tighten the agent's limit, never loosen it.
+ */
+export function effectivePriceImpactPct(config, agentMaxPct) {
+ const own = config?.sizing?.max_price_impact_bps;
+ const ownPct = own == null ? null : own / 100;
+ const agent = agentMaxPct == null || !Number.isFinite(Number(agentMaxPct)) ? null : Number(agentMaxPct);
+ if (ownPct == null) return agent;
+ if (agent == null) return ownPct;
+ return Math.min(ownPct, agent);
+}
+
+/**
+ * The sources one launch belongs to, for the entry.sources filter. The live feed
+ * only carries bonding-curve coins (graduated ones are dropped upstream), so
+ * every candidate is `pump_curve`; a three.ws agent launch is also tagged.
+ */
+export function launchSources(launch) {
+ const out = ['pump_curve'];
+ if (launch?.three_ws_launch === true) out.push('three_ws_launch');
+ return out;
+}
+
+/**
+ * Validate a strategy config. Returns { valid, errors:[{field,message}], config }.
+ * `config` is the normalized form (safe to persist). Errors are human-readable
+ * and field-tagged so the UI can show them inline.
+ */
+export function validateStrategyConfig(raw) {
+ const errors = [];
+ const config = normalizeStrategyConfig(raw);
+
+ if (!(config.sizing.amount_sol > 0)) {
+ errors.push({ field: 'sizing.amount_sol', message: 'Per-trade size must be greater than 0 SOL.' });
+ }
+ if (!(config.exits.stop_loss_pct > 0)) {
+ errors.push({ field: 'exits.stop_loss_pct', message: 'A stop-loss is required — every strategy must define its downside.' });
+ }
+ if (
+ config.entry.min_market_cap_usd != null &&
+ config.entry.max_market_cap_usd != null &&
+ config.entry.min_market_cap_usd > config.entry.max_market_cap_usd
+ ) {
+ errors.push({ field: 'entry.max_market_cap_usd', message: 'Max market cap must be greater than min market cap.' });
+ }
+ if (config.exits.take_profit_pct == null && config.exits.trailing_stop_pct == null && config.exits.max_hold_minutes == null) {
+ errors.push({ field: 'exits', message: 'Define at least one upside exit: take-profit, trailing stop, or max hold.' });
+ }
+ const rawMode = raw && typeof raw === 'object' ? raw.mode : undefined;
+ if (rawMode !== undefined && rawMode !== null && !STRATEGY_MODES.includes(rawMode)) {
+ errors.push({ field: 'mode', message: 'Mode must be "auto" (buy within caps) or "ask" (request approval for each buy).' });
+ }
+ const rawSources = raw?.entry?.sources;
+ if (Array.isArray(rawSources)) {
+ const bad = rawSources.filter((x) => !ENTRY_SOURCES.includes(String(x || '').trim().toLowerCase()));
+ if (bad.length) errors.push({ field: 'entry.sources', message: `Unknown source: ${bad.map(String).join(', ')}. Use ${ENTRY_SOURCES.join(', ')}.` });
+ }
+
+ return { valid: errors.length === 0, errors, config };
+}
+
+/**
+ * Evaluate one real launch against a strategy's entry conditions. Pure +
+ * synchronous. Returns { pass, reasons } — reasons always explains the verdict
+ * (kept on rejections too, for the runtime's evaluation log).
+ *
+ * @param {object} config normalized strategy config
+ * @param {object} launch normalized launch: { mint, created_at(ms), market_cap_usd,
+ * liquidity_sol, creator_launches, creator_graduated,
+ * twitter, telegram, website, is_usdc_pair }
+ * @param {number} nowMs current epoch ms
+ */
+export function matchesEntry(config, launch, nowMs) {
+ const e = config.entry;
+ const reasons = [];
+
+ if (!launch || !launch.mint) return { pass: false, reasons: ['no_mint'] };
+
+ // Age gate — only act on genuinely recent launches.
+ if (e.max_age_minutes != null && launch.created_at) {
+ const ageMin = (nowMs - Number(launch.created_at)) / 60000;
+ if (!Number.isFinite(ageMin) || ageMin < 0) {
+ // Clock skew / bad timestamp — treat as fresh, don't reject.
+ } else if (ageMin > e.max_age_minutes) {
+ return { pass: false, reasons: [`too_old:${Math.round(ageMin)}m`] };
+ } else {
+ reasons.push(`age:${Math.round(ageMin)}m`);
+ }
+ }
+
+ // SOL-quote requirement — the agent wallet trades in SOL on this path.
+ if (e.require_sol_quote && launch.is_usdc_pair === true) {
+ return { pass: false, reasons: ['quote_not_sol'] };
+ }
+
+ // Source filter: the candidate must come from at least one allowed venue.
+ if (Array.isArray(e.sources) && e.sources.length) {
+ const have = launchSources(launch);
+ if (!have.some((src) => e.sources.includes(src))) {
+ return { pass: false, reasons: [`source_excluded:${have.join('+')}`] };
+ }
+ }
+
+ const mc = numOrNull(launch.market_cap_usd);
+ if (e.min_market_cap_usd != null) {
+ if (mc == null || mc < e.min_market_cap_usd) return { pass: false, reasons: [`mc_below_min:${mc ?? 'n/a'}`] };
+ }
+ if (e.max_market_cap_usd != null && mc != null && mc > e.max_market_cap_usd) {
+ return { pass: false, reasons: [`mc_above_max:${Math.round(mc)}`] };
+ }
+ if (mc != null) reasons.push(`mc:${Math.round(mc)}`);
+
+ const liq = numOrNull(launch.liquidity_sol);
+ if (e.min_liquidity_sol != null) {
+ if (liq == null || liq < e.min_liquidity_sol) return { pass: false, reasons: [`liq_below_min:${liq ?? 'n/a'}`] };
+ reasons.push(`liq:${liq.toFixed(2)}sol`);
+ }
+
+ const launches = numOrNull(launch.creator_launches);
+ if (e.max_creator_launches != null && launches != null && launches > e.max_creator_launches) {
+ return { pass: false, reasons: [`creator_launches:${launches}`] };
+ }
+ const graduated = numOrNull(launch.creator_graduated);
+ if (e.min_creator_graduated != null) {
+ if (graduated == null || graduated < e.min_creator_graduated) return { pass: false, reasons: [`creator_graduated_below:${graduated ?? 'n/a'}`] };
+ reasons.push(`creator_graduated:${graduated}`);
+ }
+
+ const hasSocials = !!(launch.twitter || launch.telegram || launch.website);
+ if (e.require_socials && !hasSocials) {
+ return { pass: false, reasons: ['no_socials'] };
+ }
+ if (hasSocials) reasons.push('has_socials');
+
+ return { pass: true, reasons };
+}
+
+// Plain-language labels for each research check, shared by the runtime's
+// decision log, the Lab's block breakdown, and the compiler's explanations.
+export const RESEARCH_CHECK_LABELS = Object.freeze({
+ min_holders: 'Minimum holders',
+ max_top_holder_pct: 'Largest holder share',
+ min_liquidity_sol: 'Minimum liquidity',
+ security_min_score: 'Firewall security score',
+ require_no_mint_authority: 'Mint authority renounced',
+ require_no_freeze_authority: 'Freeze authority renounced',
+ dev_max_launches: 'Creator launch count',
+ dev_min_graduated: 'Creator graduations',
+ dev_block_sold: 'Creator has not sold',
+});
+
+const NUMBER_FORMATS = new Map();
+function fmt(v, digits = 2) {
+ if (v == null) return 'unknown';
+ let f = NUMBER_FORMATS.get(digits);
+ if (!f) NUMBER_FORMATS.set(digits, (f = new Intl.NumberFormat('en-US', { maximumFractionDigits: digits })));
+ return f.format(Number(v));
+}
+
+/**
+ * Evaluate a strategy's research gates against a gate report. Pure + sync.
+ *
+ * Fail closed: a gate the owner switched on whose data the report could not
+ * establish blocks the buy with an "unknown" reason. A research gate exists to
+ * prove something about a coin before money moves, so "could not check" is
+ * never treated as "passed". Gates left off are reported with status 'off'.
+ *
+ * @param {object} config normalized strategy config
+ * @param {object} report gate report (api/_lib/strategy-research.js#buildGateReport):
+ * { holders:{count, top_holder_pct}, liquidity:{sol}, security:{score},
+ * authority:{known, mint_authority, freeze_authority},
+ * dev:{launches, graduated, sold} }
+ * @returns {{ pass:boolean, blocked_by:Array, checks:Array }}
+ * each check: { check, label, status:'pass'|'fail'|'unknown'|'off', actual, required, reason }
+ */
+export function evaluateResearchGates(config, report) {
+ const g = config?.research || STRATEGY_CONFIG_DEFAULTS.research;
+ const dv = g.dev_history || {};
+ const r = report || {};
+ const checks = [];
+
+ const add = (check, required, actual, ok, reason) => {
+ let status;
+ if (required == null || required === false) status = 'off';
+ else if (actual == null) status = 'unknown';
+ else status = ok ? 'pass' : 'fail';
+ // Reasons are built only for checks that ran: the match preview replays tens
+ // of thousands of coins through this function, and number formatting is slow.
+ let why = null;
+ if (status === 'unknown') why = `${RESEARCH_CHECK_LABELS[check]} could not be verified, so the buy is held back.`;
+ else if (status !== 'off') why = reason();
+ checks.push({ check, label: RESEARCH_CHECK_LABELS[check], status, actual: actual ?? null, required: required === false ? null : required, reason: why });
+ };
+
+ const holders = numOrNull(r.holders?.count);
+ add('min_holders', g.min_holders, holders, holders != null && holders >= g.min_holders,
+ () => `${fmt(holders, 0)} holders against a minimum of ${fmt(g.min_holders, 0)}.`);
+
+ const top = numOrNull(r.holders?.top_holder_pct);
+ add('max_top_holder_pct', g.max_top_holder_pct, top, top != null && top <= g.max_top_holder_pct,
+ () => `The largest holder owns ${fmt(top, 1)}% against a ceiling of ${fmt(g.max_top_holder_pct, 1)}%.`);
+
+ const liq = numOrNull(r.liquidity?.sol);
+ add('min_liquidity_sol', g.min_liquidity_sol, liq, liq != null && liq >= g.min_liquidity_sol,
+ () => `${fmt(liq)} SOL of liquidity against a minimum of ${fmt(g.min_liquidity_sol)} SOL.`);
+
+ const score = numOrNull(r.security?.score);
+ add('security_min_score', g.security_min_score, score, score != null && score >= g.security_min_score,
+ () => `Firewall score ${fmt(score, 0)}/100 against a minimum of ${fmt(g.security_min_score, 0)}.`);
+
+ const authKnown = r.authority?.known === true;
+ const mintAuth = authKnown ? (r.authority.mint_authority ? 'active' : 'renounced') : null;
+ add('require_no_mint_authority', g.require_no_mint_authority || null, mintAuth, mintAuth === 'renounced',
+ () => mintAuth === 'active' ? 'The creator can still mint new supply.' : 'Mint authority is renounced.');
+ const freezeAuth = authKnown ? (r.authority.freeze_authority ? 'active' : 'renounced') : null;
+ add('require_no_freeze_authority', g.require_no_freeze_authority || null, freezeAuth, freezeAuth === 'renounced',
+ () => freezeAuth === 'active' ? 'The creator can freeze holder accounts, so a buy might never sell.' : 'Freeze authority is renounced.');
+
+ const launches = numOrNull(r.dev?.launches);
+ add('dev_max_launches', dv.max_launches, launches, launches != null && launches <= dv.max_launches,
+ () => `The creator has launched ${fmt(launches, 0)} coins against a ceiling of ${fmt(dv.max_launches, 0)}.`);
+ const grads = numOrNull(r.dev?.graduated);
+ add('dev_min_graduated', dv.min_graduated, grads, grads != null && grads >= dv.min_graduated,
+ () => `The creator has graduated ${fmt(grads, 0)} coins against a minimum of ${fmt(dv.min_graduated, 0)}.`);
+ const sold = typeof r.dev?.sold === 'boolean' ? (r.dev.sold ? 'sold' : 'holding') : null;
+ add('dev_block_sold', dv.block_dev_sold || null, sold, sold === 'holding',
+ () => sold === 'sold' ? 'The creator has already sold their own allocation.' : 'The creator has not sold.');
+
+ const blocked_by = checks
+ .filter((c) => c.status === 'fail' || c.status === 'unknown')
+ .map(({ check, label, status, actual, required, reason }) => ({ check, label, status, actual, required, reason }));
+ return { pass: blocked_by.length === 0, blocked_by, checks };
+}
+
+/**
+ * Decide whether an open position should exit, given a live re-quote. Pure.
+ * Returns { exit, reason } — reason ∈ take_profit|stop_loss|trailing_stop|timeout.
+ *
+ * @param {object} config normalized config
+ * @param {object} pos { entry_lamports, peak_value_lamports, opened_at(ms) }
+ * @param {bigint|number|string} currentValueLamports live quoteForSell value
+ * @param {number} nowMs
+ */
+export function shouldExit(config, pos, currentValueLamports, nowMs) {
+ const x = config.exits;
+ const entry = Number(pos.entry_lamports || 0);
+ const cur = Number(currentValueLamports || 0);
+
+ // Time-based exit is independent of price — check it even with no entry basis.
+ if (x.max_hold_minutes != null && pos.opened_at) {
+ const heldMin = (nowMs - Number(pos.opened_at)) / 60000;
+ if (heldMin >= x.max_hold_minutes) return { exit: true, reason: 'timeout' };
+ }
+
+ if (!(entry > 0) || !(cur >= 0)) return { exit: false, reason: null };
+ const pnlPct = ((cur - entry) / entry) * 100;
+
+ if (x.take_profit_pct != null && pnlPct >= x.take_profit_pct) {
+ return { exit: true, reason: 'take_profit' };
+ }
+ if (x.stop_loss_pct != null && pnlPct <= -x.stop_loss_pct) {
+ return { exit: true, reason: 'stop_loss' };
+ }
+ if (x.trailing_stop_pct != null) {
+ const peak = Math.max(Number(pos.peak_value_lamports || 0), cur, entry);
+ if (peak > 0) {
+ const dropFromPeakPct = ((peak - cur) / peak) * 100;
+ if (dropFromPeakPct >= x.trailing_stop_pct) return { exit: true, reason: 'trailing_stop' };
+ }
+ }
+ return { exit: false, reason: null };
+}
+
+export { ENTRY_TRIGGERS, NETWORKS, STRATEGY_MODES, ENTRY_SOURCES };