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.

fix(sniper): surface fleet solvency instead of trusting process liveness

nirholasf24e2a95312c
diff --git a/api/_lib/pricing/catalog.js b/api/_lib/pricing/catalog.js
index 01351a3a4..66f0a1129 100644
--- a/api/_lib/pricing/catalog.js
+++ b/api/_lib/pricing/catalog.js
@@ -46,6 +46,13 @@ const FORGE_GAMEREADY_USD = Number(priceUsdcForOutput('gameready')); // 0.10
// BYOK requests bypass the charge entirely (api/tts/eleven.js).
export const TTS_ELEVEN_USD_PER_1K = 0.3;
+// OpenAI TTS (gpt-4o-mini-tts / tts-1): retail USD per 1,000 synthesized
+// characters on the platform key. Upstream is ~$0.015/1k chars; $0.03 retail
+// keeps the same margin shape as the ElevenLabs rung. Same policy applies —
+// a vendor-billed lane never has a free tier (owner policy 2026-08-06), so
+// every platform-key OpenAI synthesis is metered to the caller's credits.
+export const TTS_OPENAI_USD_PER_1K = 0.03;
+
// ── The catalog ─────────────────────────────────────────────────────────────────
// id → { label, category, policy, usd }. `usd: null` ⇒ price set per-call.
export const CATALOG = Object.freeze({
@@ -110,6 +117,12 @@ export const CATALOG = Object.freeze({
policy: POLICY.CONSUMPTION,
usd: null, // per-call: characters * TTS_ELEVEN_USD_PER_1K / 1000
},
+ 'tts.openai': {
+ label: 'Voice: OpenAI TTS synthesis (per 1k characters)',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: null, // per-call: characters * TTS_OPENAI_USD_PER_1K / 1000
+ },
'selfie.reconstruct': {
label: 'Selfie → Avatar reconstruction',
category: 'generation',
diff --git a/api/_lib/sniper-solvency.js b/api/_lib/sniper-solvency.js
new file mode 100644
index 000000000..c49323257
--- /dev/null
+++ b/api/_lib/sniper-solvency.js
@@ -0,0 +1,183 @@
+// @ts-check
+/**
+ * Agent Sniper — fleet solvency.
+ *
+ * The failure this module exists to make visible: between 2026-07-29 and
+ * 2026-08-08 the sniper fleet booked over a thousand consecutive failed entries
+ * and closed zero trades, while `/api/sniper/status` reported `state: "live"`
+ * the entire time. Everything the status endpoint measured was true — the
+ * process was up, the feed was connected, strategies were armed — and none of
+ * it was the thing that mattered. The wallets were too poor to place a single
+ * buy, and the funding master they refill from was itself down to dust, so the
+ * auto-funder could not fix it either.
+ *
+ * Liveness is not solvency. A trading worker has two ways to be dead and the
+ * loud one (process down, feed silent) was already covered. This covers the
+ * quiet one: financially unable to trade, indistinguishable from healthy to
+ * every check that only looks at the process.
+ *
+ * The rule that keeps this honest: a wallet's trade state is decided by
+ * `resolveEntrySize` — the SAME function the executor calls to size or skip a
+ * real entry (api/_lib/agent-trade-guards.js, used at workers/agent-sniper/
+ * executor.js step 4). Duplicating its thresholds here is how this surface
+ * would drift into claiming "tradeable" for a wallet the executor skips, which
+ * is the exact class of bug it was written to catch. Ask the decider, don't
+ * re-derive the decision.
+ *
+ * Pure over its inputs: no DB, no RPC. The worker's auto-funder already reads
+ * every armed wallet's balance on its 5-minute tick and feeds the result here,
+ * so the public status path stays DB-only and pays no RPC hop.
+ */
+
+import { resolveEntrySize } from './agent-trade-guards.js';
+import { fundTargetSol } from './agent-funding-policy.js';
+
+/** Smallest entry worth placing, matching the worker's SNIPER_MIN_TRADE_LAMPORTS default. */
+export const DEFAULT_MIN_TRADE_LAMPORTS = 10_000n;
+
+/**
+ * A master wallet at exactly the deficit can't actually cover it: the transfers
+ * themselves cost fees, and `fundAgentForLaunch` enforces its own balance buffer
+ * underneath. This is the margin above the raw deficit at which we are willing
+ * to say "the master can fix this on its own".
+ */
+export const MASTER_COVER_BUFFER_SOL = 0.01;
+
+function toLamports(sol) {
+ const n = Number(sol);
+ if (!Number.isFinite(n) || n <= 0) return 0n;
+ return BigInt(Math.round(n * 1e9));
+}
+
+/**
+ * What one wallet can do with its next entry, per the executor's own sizing rule.
+ *
+ * 'funded' — can place the arm's configured size
+ * 'shrunk' — can still trade, but only below the configured size (the
+ * executor shrinks rather than skips: learning > profit)
+ * 'starved' — cannot place any entry; the executor sits this wallet out
+ *
+ * @param {number} balanceSol current wallet balance
+ * @param {number} perTradeSol the arm's configured per-trade size
+ * @param {bigint} [minTradeLamports] smallest size worth placing
+ * @returns {'funded'|'shrunk'|'starved'}
+ */
+export function walletTradeState(balanceSol, perTradeSol, minTradeLamports = DEFAULT_MIN_TRADE_LAMPORTS) {
+ const wallet = toLamports(balanceSol);
+ const want = toLamports(perTradeSol);
+ // An arm with no configured size can't be sized against; treat the wallet as
+ // starved only if it couldn't even cover the minimum trade.
+ const target = want > 0n ? want : BigInt(minTradeLamports);
+ const sized = resolveEntrySize(wallet, target, minTradeLamports);
+ if (sized.skip) return 'starved';
+ return sized.sizeLamports < target ? 'shrunk' : 'funded';
+}
+
+/**
+ * Roll per-wallet balances up into one fleet verdict.
+ *
+ * `state` is the headline, and it is deliberately about capability rather than
+ * count: a fleet where every wallet is starved is `starved` no matter how many
+ * strategies are armed, because the honest answer to "is the sniper working" is
+ * no. One tradeable wallet among starved ones is `degraded` — it still trades,
+ * just not at fleet strength.
+ *
+ * 'unknown' — nothing measured yet (no armed wallets, or balances unread)
+ * 'funded' — every wallet can place its configured size
+ * 'degraded' — at least one wallet can still trade, at least one cannot
+ * 'starved' — no wallet can place any entry; the fleet is financially dead
+ *
+ * `deficitSol` is what it would cost to lift every starved wallet back to its
+ * own refill target — i.e. the number to hand an operator who asks "how much
+ * SOL does this need?". `masterCanCover` answers whether the auto-funder can
+ * close that gap by itself, which is the difference between "it will heal in
+ * five minutes" and "a human has to move money".
+ *
+ * @param {object} p
+ * @param {Array<{agentId?: string, address?: string, balanceSol?: number|null, perTradeSol?: number}>} p.wallets
+ * @param {number|null} [p.masterSol] funding master balance, null when unread/unconfigured
+ * @param {bigint} [p.minTradeLamports]
+ * @returns {{
+ * state: 'unknown'|'funded'|'degraded'|'starved',
+ * agents: number, funded: number, shrunk: number, starved: number,
+ * tradeable: number, deficitSol: number,
+ * masterSol: number|null, masterCanCover: boolean|null,
+ * wallets: Array<{agentId: string|null, address: string|null, balanceSol: number, state: string}>,
+ * }}
+ */
+export function summarizeFleetSolvency({ wallets, masterSol = null, minTradeLamports = DEFAULT_MIN_TRADE_LAMPORTS } = {}) {
+ const measured = [];
+ for (const w of wallets || []) {
+ // A balance we failed to read is not a balance of zero. Excluding it keeps
+ // an RPC blip from reporting a healthy fleet as starved and paging someone.
+ if (w?.balanceSol == null || !Number.isFinite(Number(w.balanceSol))) continue;
+ const balanceSol = Number(w.balanceSol);
+ const perTradeSol = Number(w.perTradeSol) || 0;
+ measured.push({
+ agentId: w.agentId ?? null,
+ address: w.address ?? null,
+ balanceSol,
+ perTradeSol,
+ state: walletTradeState(balanceSol, perTradeSol, minTradeLamports),
+ });
+ }
+
+ const counts = { funded: 0, shrunk: 0, starved: 0 };
+ let deficitSol = 0;
+ for (const w of measured) {
+ counts[w.state] += 1;
+ if (w.state === 'starved') {
+ deficitSol += Math.max(0, fundTargetSol({ perTradeSol: w.perTradeSol }) - w.balanceSol);
+ }
+ }
+
+ const agents = measured.length;
+ const tradeable = counts.funded + counts.shrunk;
+ const state = agents === 0
+ ? 'unknown'
+ : tradeable === 0
+ ? 'starved'
+ : counts.starved > 0 || counts.shrunk > 0
+ ? 'degraded'
+ : 'funded';
+
+ deficitSol = Math.round(deficitSol * 1e9) / 1e9;
+ const master = masterSol == null || !Number.isFinite(Number(masterSol)) ? null : Number(masterSol);
+
+ return {
+ state,
+ agents,
+ funded: counts.funded,
+ shrunk: counts.shrunk,
+ starved: counts.starved,
+ tradeable,
+ deficitSol,
+ masterSol: master,
+ masterCanCover: master == null ? null : master >= deficitSol + MASTER_COVER_BUFFER_SOL,
+ wallets: measured.map(({ agentId, address, balanceSol, state: s }) => ({
+ agentId, address, balanceSol, state: s,
+ })),
+ };
+}
+
+/**
+ * One-line operator summary of a solvency snapshot. Shared by the worker's alert
+ * body and the status page so both describe the same condition the same way.
+ *
+ * @param {ReturnType<typeof summarizeFleetSolvency>} s
+ * @returns {string}
+ */
+export function describeSolvency(s) {
+ if (!s || s.state === 'unknown') return 'No armed wallet balances measured yet.';
+ if (s.state === 'funded') return `All ${s.agents} armed wallets can place their configured size.`;
+ const head = s.state === 'starved'
+ ? `No armed wallet can place an entry (${s.starved}/${s.agents} starved).`
+ : `${s.tradeable}/${s.agents} armed wallets can still trade (${s.starved} starved, ${s.shrunk} shrunk).`;
+ if (s.deficitSol <= 0) return head;
+ const fix = s.masterCanCover === true
+ ? `The funding master holds ${s.masterSol?.toFixed(4)} SOL and will refill them automatically.`
+ : s.masterCanCover === false
+ ? `The funding master holds only ${s.masterSol?.toFixed(4)} SOL, so it CANNOT refill them: a human must move SOL in.`
+ : 'The funding master balance is unknown.';
+ return `${head} Refilling them needs ${s.deficitSol.toFixed(4)} SOL. ${fix}`;
+}
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index 0ef1d239b..859cd809d 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -225,20 +225,24 @@ const PUBLIC_DEVNET = 'https://api.devnet.solana.com';
// for the methods it serves without ever blinding a balance/signature caller.
// The free public-RPC pool has thinned (most providers now 401/403/429
// keyless), so this set is curated to ones that actually respond; re-verify any
-// that start cooling persistently in the failover logs. (solana.therpc.io was
-// pruned 2026-07-17 after going fully unreachable, DNS fetch failures on every
-// probe of both getLatestBlockhash and getBalance.)
+// that start cooling persistently in the failover logs. Two pruned so far:
+// solana.therpc.io on 2026-07-17 after going fully unreachable (DNS fetch
+// failures on every probe of both getLatestBlockhash and getBalance), and
+// rpc.magicblock.app on 2026-08-07 after it began answering EVERY method on
+// EVERY call with HTTP 403 "Your IP or provider is blocked from this endpoint".
+// A lane blocked at the caller level is worse than absent: the breadth guard
+// parks it for 30m, then the next rotation spends another real request
+// rediscovering the same block, which is capacity burned to learn nothing.
//
-// MagicBlock + Tatum's gateway host were verified live (getLatestBlockhash +
-// sendTransaction enabled) on 2026-07-04 when the free pool was re-probed after
-// a Helius plan lapsed mid-cycle. They deepen the keyless chain precisely for
-// the "every paid key is exhausted" case; the classifyRpcBody guard still fails
-// them over if either returns garbage.
+// Tatum's gateway host was verified live (getLatestBlockhash + sendTransaction
+// enabled) on 2026-07-04 when the free pool was re-probed after a Helius plan
+// lapsed mid-cycle. It deepens the keyless chain precisely for the "every paid
+// key is exhausted" case; the classifyRpcBody guard still fails it over if it
+// returns garbage.
const FREE_KEYLESS_MAINNET = [
'https://solana-rpc.publicnode.com',
'https://solana.leorpc.com/?api_key=FREE',
'https://api.tatum.io/v3/blockchain/node/solana-mainnet',
- 'https://rpc.magicblock.app/mainnet',
'https://solana-mainnet.gateway.tatum.io',
PUBLIC_MAINNET,
];
diff --git a/workers/agent-sniper/alerts.js b/workers/agent-sniper/alerts.js
index 8d23da507..efd5f8acd 100644
--- a/workers/agent-sniper/alerts.js
+++ b/workers/agent-sniper/alerts.js
@@ -45,6 +45,33 @@ export function alertFeedDown({ network, mode }) {
);
}
+/**
+ * The fleet cannot place a single entry — every armed wallet is below the size
+ * its own executor would accept. This is the alert the 2026-07-29 outage did not
+ * have: the worker stayed green for ten days while booking a thousand failed
+ * buys, because nothing watched the money.
+ */
+export function alertFleetStarved({ summary, network, mode }) {
+ alert(
+ 'fleet starved — no wallet can trade',
+ `${summary} Network ${network} (${mode}). Nothing will fill until SOL reaches these wallets.`,
+ 'sniper:fleet-starved',
+ );
+}
+
+/**
+ * The auto-funder has wallets to refill and not enough SOL to do it. Distinct
+ * from the starved alert on purpose: this one cannot self-heal, so it names the
+ * human action rather than describing a condition that may pass on its own.
+ */
+export function alertFundingMasterDry({ summary, network, mode }) {
+ alert(
+ 'funding master cannot cover refills',
+ `${summary} Network ${network} (${mode}). Auto-funding is a no-op until the master wallet is topped up.`,
+ 'sniper:funding-master-dry',
+ );
+}
+
/** Executor / RPC errors crossed the run-window threshold. */
export function alertErrorSpike({ count, windowMs, lastError, network, mode }) {
alert(
diff --git a/workers/agent-sniper/auto-funder.js b/workers/agent-sniper/auto-funder.js
index 1de83ba4a..cd41912e0 100644
--- a/workers/agent-sniper/auto-funder.js
+++ b/workers/agent-sniper/auto-funder.js
@@ -31,6 +31,8 @@ import { screenPush } from './screen-push.js';
import { cachedStrategies, getRealizedNetLamports, effectiveDailyLossLimitLamports } from './strategy-store.js';
import { checkDailyLoss } from '../../api/_lib/agent-trade-guards.js';
import { autoFundMinSol, autoFundTargetSol, fundTriggerSol, fundTargetSol } from '../../api/_lib/agent-funding-policy.js';
+import { summarizeFleetSolvency, describeSolvency } from '../../api/_lib/sniper-solvency.js';
+import { alertFleetStarved, alertFundingMasterDry } from './alerts.js';
const POLL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
@@ -89,6 +91,26 @@ function activeAgentIds(network) {
return optedInAgentIds(cachedStrategies(), network);
}
+/**
+ * Unique agent ids with an ARMED strategy on this network, opted into funding or
+ * not. Solvency is reported over this set rather than the opted-in one: an agent
+ * that never consented to auto-funding still trades and still starves, and a
+ * fleet report that quietly omitted it would be the same blind spot one level up.
+ *
+ * Pure over its `strategies` arg so it can be unit-tested without the cache.
+ *
+ * @param {Array<{agent_id?: string, network?: string}>} strategies
+ * @param {string} network
+ * @returns {string[]}
+ */
+export function armedAgentIds(strategies, network) {
+ const ids = new Set();
+ for (const s of strategies || []) {
+ if (s.agent_id && s.network === network) ids.add(s.agent_id);
+ }
+ return [...ids];
+}
+
/**
* Largest configured trade size among an agent's opted-in strategies, in SOL.
* The funding levels are sized off this: a wallet that cannot cover the arm's own
@@ -102,10 +124,11 @@ function activeAgentIds(network) {
* @param {string} network
* @returns {number} SOL, 0 when unknown
*/
-export function agentPerTradeSol(strategies, agentId, network) {
+export function agentPerTradeSol(strategies, agentId, network, { optedInOnly = true } = {}) {
let max = 0;
for (const s of strategies || []) {
- if (s.agent_id !== agentId || s.network !== network || s.auto_fund_enabled !== true) continue;
+ if (s.agent_id !== agentId || s.network !== network) continue;
+ if (optedInOnly && s.auto_fund_enabled !== true) continue;
const sol = Number(s.per_trade_lamports) / 1e9;
if (Number.isFinite(sol) && sol > max) max = sol;
}
@@ -170,33 +193,114 @@ async function agentAddresses(agentIds) {
return m;
}
+// Latest fleet solvency snapshot, published on every tick and read by the
+// heartbeat. Null until the first tick completes, which the status endpoint
+// renders as 'unknown' rather than inventing a healthy default.
+let _solvency = null;
+
+/** The most recent fleet solvency snapshot, or null before the first tick. */
+export function latestSolvency() {
+ return _solvency;
+}
+
+/**
+ * Measure every armed wallet and publish the fleet's solvency. Runs before any
+ * funding decision so the snapshot reflects what the executor is up against
+ * right now, not what the funder left behind.
+ *
+ * Balance reads are per-wallet and independent: one failed read is recorded as
+ * unmeasured (null) rather than zero, so an RPC blip degrades coverage instead
+ * of faking a starved fleet.
+ *
+ * Returns the balances it read so the funding loop below spends them rather than
+ * re-reading. Beyond halving the RPC calls, this is what guarantees the fleet
+ * report and the funding decision are made from the same numbers.
+ */
+async function publishSolvency(cfg, addresses, conn) {
+ const wallets = [];
+ const balances = new Map();
+ for (const [agentId, address] of addresses) {
+ let balanceSol = null;
+ try {
+ ({ sol: balanceSol } = await getSolBalance(conn, address));
+ balances.set(agentId, balanceSol);
+ } catch (err) {
+ log.warn('solvency balance read failed', { agentId, err: err?.message });
+ }
+ wallets.push({
+ agentId, address, balanceSol,
+ perTradeSol: agentPerTradeSol(cachedStrategies(), agentId, cfg.network, { optedInOnly: false }),
+ });
+ }
+
+ let masterSol = null;
+ try {
+ masterSol = await masterBalanceSol(cfg.network);
+ } catch (err) {
+ log.warn('solvency master balance read failed', { err: err?.message });
+ }
+
+ const snapshot = summarizeFleetSolvency({ wallets, masterSol });
+ _solvency = { ...snapshot, at: new Date().toISOString() };
+
+ const summary = describeSolvency(snapshot);
+ if (snapshot.state === 'starved') {
+ log.error('fleet starved — no armed wallet can place an entry', {
+ network: cfg.network, agents: snapshot.agents, deficit_sol: snapshot.deficitSol, master_sol: snapshot.masterSol,
+ });
+ screenPush('Sniper fleet is out of SOL — no wallet can trade', 'guard');
+ // Live money only: a simulate-mode fleet is starved by design (it never
+ // funds anything), and paging on that would train operators to ignore this.
+ if (cfg.mode === 'live') alertFleetStarved({ summary, network: cfg.network, mode: cfg.mode });
+ } else if (snapshot.state === 'degraded') {
+ log.warn('fleet partially starved', {
+ network: cfg.network, tradeable: snapshot.tradeable, agents: snapshot.agents, deficit_sol: snapshot.deficitSol,
+ });
+ }
+ // A master that cannot cover the deficit is its own condition: the fleet may
+ // still be limping along on one funded wallet, and the refills that would fix
+ // it are silently no-ops. Alerted separately so it can't hide behind 'degraded'.
+ if (cfg.mode === 'live' && snapshot.deficitSol > 0 && snapshot.masterCanCover === false) {
+ log.error('funding master cannot cover refills', {
+ network: cfg.network, master_sol: snapshot.masterSol, deficit_sol: snapshot.deficitSol,
+ });
+ alertFundingMasterDry({ summary, network: cfg.network, mode: cfg.mode });
+ }
+
+ return { snapshot, balances };
+}
+
async function tick(cfg) {
- const agentIds = activeAgentIds(cfg.network);
- if (!agentIds.length) return;
+ const conn = solanaConnection(cfg.network);
- const addresses = await agentAddresses(agentIds);
+ // Solvency is measured over every ARMED agent; funding still only ever touches
+ // the opted-in subset. Reading the wider set costs one balance call per armed
+ // wallet per 5 minutes and is what makes a starved non-consenting agent visible.
+ const armed = armedAgentIds(cachedStrategies(), cfg.network);
+ const addresses = await agentAddresses(armed);
if (!addresses.size) return;
+ const { balances } = await publishSolvency(cfg, addresses, conn);
+
+ const optedIn = new Set(activeAgentIds(cfg.network));
+ if (!optedIn.size) return;
// One daily-spend read per tick; decremented locally as we fund so several
// agents in the same tick can't collectively blow past the cap.
let dailyRemaining = DAILY_CAP_SOL > 0 ? Math.max(0, DAILY_CAP_SOL - (await dailyFundedSol(cfg.network))) : Infinity;
// Per-agent funded-today, so one wallet can't consume the whole fleet budget.
const perAgentFunded = PER_AGENT_DAILY_CAP_SOL > 0 ? await perAgentFundedSol(cfg.network) : new Map();
- const conn = solanaConnection(cfg.network);
for (const [agentId, address] of addresses) {
+ if (!optedIn.has(agentId)) continue; // measured for solvency, never funded
if (DAILY_CAP_SOL > 0 && dailyRemaining <= 0) {
log.warn('auto-fund daily cap reached — skipping remaining agents', { network: cfg.network, dailyCapSol: DAILY_CAP_SOL });
break;
}
- let balanceSol;
- try {
- ({ sol: balanceSol } = await getSolBalance(conn, address));
- } catch (err) {
- log.warn('auto-fund balance read failed', { agentId, err: err?.message });
- continue;
- }
+ // From the solvency pass above — an unreadable balance is absent, and a
+ // wallet we could not measure is never funded on a guess.
+ const balanceSol = balances.get(agentId);
+ if (balanceSol == null) continue;
// "Healthy" is per-arm, not a flat number: a wallet that cannot cover this
// arm's own trade size plus the entry's fixed overhead is not healthy, however