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(liquidation-collector): add the OKX contracts collector and cover the caster

nirholascecdfe3f7eaf
diff --git a/deploy/world/cloudbuild.yaml b/deploy/world/cloudbuild.yaml
index 9eefaba83..78ac787c0 100644
--- a/deploy/world/cloudbuild.yaml
+++ b/deploy/world/cloudbuild.yaml
@@ -39,3 +39,7 @@ images:
options:
machineType: E2_HIGHCPU_8
logging: CLOUD_LOGGING_ONLY
+
+# The project's default compute SA was deleted; every manual build must pin the
+# dedicated build SA or Cloud Build refuses the submission.
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
diff --git a/services/agent-screen-caster/README.md b/services/agent-screen-caster/README.md
index 0d43e0c0f..7e5ca80be 100644
--- a/services/agent-screen-caster/README.md
+++ b/services/agent-screen-caster/README.md
@@ -10,6 +10,15 @@ It runs as a separate always-on process because it holds a browser and a frame
loop open indefinitely, which does not fit the request/response shape of the
`api/` functions (see [services/README.md](../README.md)).
+**This service is self-hosted, by design.** three.ws runs no managed instance of
+it: an agent owner starts it on their own machine, VPS, or container host with
+their own agent id and key, and it pushes into the same live stream every other
+producer uses. The platform's always-on casting is done by
+[workers/agent-screen-pool](../../workers/agent-screen-pool) (on-demand,
+multi-agent) and [workers/agent-screen-worker](../../workers/agent-screen-worker)
+(one owner-run worker per agent). Reach for this service when you want a real
+browser under your own control driving your agent's screen.
+
## Files
| File | Role |
@@ -18,7 +27,13 @@ loop open indefinitely, which does not fit the request/response shape of the
| [caster.js](./caster.js) | The `AgentScreenCaster` class: Playwright lifecycle, `navigate()`, `act()`, the frame loop, and the authenticated push primitives (`pushFrame`, `pushActivity`). |
| [tasks/pump-monitor.js](./tasks/pump-monitor.js) | Task: watch a pump.fun coin page via DOM mutation observers and stream price/market-cap/transaction activity. With no `TASK_ARG` it defaults to the $THREE mint. |
| [tasks/trade.js](./tasks/trade.js) | Task: drive a DEX swap UI (Jupiter, Raydium, or pump.fun quick-buy) from a JSON trade spec. Requires a pre-authenticated wallet session via Playwright `storageState`. |
-| [Dockerfile](./Dockerfile) | `mcr.microsoft.com/playwright:v1.49.0-jammy` base (Chromium baked in), runs as the non-root `pwuser`. |
+| [Dockerfile](./Dockerfile) | `mcr.microsoft.com/playwright:v1.60.0-jammy` base (Chromium baked in), runs as the non-root `pwuser`. |
+
+The Playwright dependency is pinned to an exact version (`1.60.0`) rather than a
+range, and the Dockerfile tag must move with it. The base image bakes exactly one
+Chromium build into `/ms-playwright`, and the npm package only looks for the
+revision it shipped with, so a floating range resolves to a newer package that
+cannot find a browser inside the older image.
## Run it
@@ -53,6 +68,14 @@ docker run -e AGENT_ID=... -e AGENT_BEARER_TOKEN=... -e TASK=pump-monitor agent-
| `HEADLESS` | `true` | `false` opens a visible browser window. |
| `TASK` | `pump-monitor` | Task module: `pump-monitor` or `trade`. |
| `TASK_ARG` | (empty) | Primary task argument (mint address for pump-monitor; JSON trade spec for trade). |
+| `WALLET_STORAGE_STATE_PATH` | (empty) | `trade` task only: path to a Playwright `storageState` JSON from a prior authenticated wallet session. Without it the swap UI opens with no wallet connected. |
+
+`AGENT_ID` and `AGENT_BEARER_TOKEN` are the only two you have to source
+yourself, and you do not have to hand-assemble them: `POST /api/agent/caster-config`
+with `{ "agentId": "<uuid>" }` (signed in, or with a `profile`-scoped bearer)
+mints a scoped `agents:read agents:write` key for that agent and answers with a
+ready-to-paste `.env` block and `docker run` command. That is the same flow the
+agent detail page in the dashboard uses.
## Using `AgentScreenCaster` directly
@@ -76,9 +99,26 @@ await caster.close();
A custom task module only needs to export `run(caster, taskArg)`; add it to the
`TASK_MAP` in [index.js](./index.js) to make it selectable via `TASK`.
+## Tests
+
+`tests/agent-screen-caster.test.js` (run from the repo root with
+`npx vitest run tests/agent-screen-caster.test.js`) exercises the real core
+path: it launches Chromium, serves a page and a stand-in push endpoint from one
+local HTTP server, and asserts that `navigate()` and `act()` narrate before they
+capture, that every push carries the agent id and bearer token, that the frames
+are genuine JPEGs, and that the frame loop starts and stops on demand. It also
+pins the transport policy: an activity push retries through a 429/5xx, a 4xx
+fails immediately, and a screenshot is never retried.
+
## Server side
Frames land in [api/agent-screen-push.js](../../api/agent-screen-push.js);
watchers consume them through the agent-screen stream/control endpoints in
`api/`. Screenshot pushes carry a `data:image/jpeg;base64,...` frame; activity
pushes carry a text summary that the API appends to the agent's activity log.
+
+Only a push that carries something readable (activity text, or a structured
+PnL / forge / market-maker ride-along) is written to that log. The periodic
+screenshots stay out of it on purpose: the log keeps the last 50 entries, and a
+caster running at the default 400 ms interval would otherwise flush the agent's
+real narration out of it in about 20 seconds.
diff --git a/services/liquidation-collector/src/collector.js b/services/liquidation-collector/src/collector.js
new file mode 100644
index 000000000..e51028dfc
--- /dev/null
+++ b/services/liquidation-collector/src/collector.js
@@ -0,0 +1,282 @@
+// Pure collector logic: symbol lists, size buckets, per-exchange message
+// parsing, the rolling in-memory store, and the aggregate snapshot.
+//
+// Everything here is side-effect free and synchronous so it can be tested
+// without opening a socket (see tests/liquidation-collector.test.js at the repo
+// root). `src/index.js` owns the WebSocket + HTTP wiring and calls into this.
+
+export const TRACKED = [
+ 'BTC', 'ETH', 'SOL', 'DOGE', 'XRP', 'ARB', 'OP', 'AVAX', 'LINK',
+ 'BNB', 'SUI', 'WIF', 'PEPE', 'BONK', 'INJ', 'TIA', 'APT', 'NEAR',
+];
+
+export const MAX_CACHE = 10_000;
+export const MAX_AGE_MS = 4 * 60 * 60 * 1000; // 4 hours
+
+/** @typedef {{ exchange: string, price: number, qty: number, severity: string, side: 'LONG'|'SHORT', symbol: string, time: number, value: number }} LiquidationEntry */
+
+// ---------------------------------------------------------------------------
+// Size buckets
+// ---------------------------------------------------------------------------
+
+export function classify(value) {
+ if (value >= 1_000_000) return 'MEGA';
+ if (value >= 100_000) return 'LARGE';
+ if (value >= 10_000) return 'MEDIUM';
+ return 'SMALL';
+}
+
+/**
+ * Rolling, capped in-memory store of liquidation entries.
+ * @param {{ max?: number }} [opts]
+ */
+export function createStore({ max = MAX_CACHE } = {}) {
+ /** @type {LiquidationEntry[]} */
+ const entries = [];
+ return {
+ entries,
+ get size() {
+ return entries.length;
+ },
+ push(entry) {
+ entries.push({ ...entry, severity: classify(entry.value) });
+ if (entries.length > max) entries.shift();
+ },
+ };
+}
+
+function isFinitePositive(n) {
+ return Number.isFinite(n) && n > 0;
+}
+
+// ---------------------------------------------------------------------------
+// Binance: wss://fstream.binance.com/ws/!forceOrder@arr
+// Frame: { e: 'forceOrder', E, o: { s, S, q, p, ap, T, ... } }
+// `S` is the side of the forced ORDER, so a forced SELL closed a long.
+// ---------------------------------------------------------------------------
+
+export function parseBinanceMessage(raw, tracked = TRACKED) {
+ let msg;
+ try {
+ msg = JSON.parse(raw);
+ } catch {
+ return [];
+ }
+ const o = msg?.o;
+ if (!o || !o.s) return [];
+ const base = String(o.s).replace(/(USDT|USDC|BUSD)$/, '');
+ if (!tracked.includes(base)) return [];
+ const price = parseFloat(o.ap || o.p);
+ const qty = parseFloat(o.q);
+ if (!isFinitePositive(price) || !isFinitePositive(qty)) return [];
+ return [{
+ exchange: 'Binance',
+ price,
+ qty,
+ side: o.S === 'BUY' ? 'SHORT' : 'LONG',
+ symbol: base,
+ time: Number(o.T) || Date.now(),
+ value: price * qty,
+ }];
+}
+
+// ---------------------------------------------------------------------------
+// Bybit: wss://stream.bybit.com/v5/public/linear
+// Topic: allLiquidation.{INSTRUMENT}. The older `liquidation.{INSTRUMENT}`
+// topic was retired by Bybit and now answers
+// `{"success":false,"ret_msg":"error:handler not found,..."}`, which is why
+// every subscribe frame carries a req_id and the ack is inspected.
+//
+// Bybit lists the small-denomination memecoins in 1000x lots (1000PEPEUSDT),
+// where price is quoted per 1000 tokens. We normalize back to single-token
+// price/qty so `price` is comparable to the spot price the UI shows; the USD
+// value is identical either way.
+// ---------------------------------------------------------------------------
+
+const BYBIT_LOT_1000 = ['PEPE', 'BONK'];
+
+/** Instrument name Bybit lists a tracked base coin under. */
+export function bybitInstrument(base) {
+ return BYBIT_LOT_1000.includes(base) ? `1000${base}USDT` : `${base}USDT`;
+}
+
+/** Base coin + lot size behind a Bybit instrument name. */
+export function bybitBase(instrument) {
+ const name = String(instrument ?? '');
+ const lotted = name.match(/^1000([A-Z0-9]+)USDT$/);
+ if (lotted) return { base: lotted[1], lot: 1000 };
+ return { base: name.replace(/USDT$/, ''), lot: 1 };
+}
+
+export function bybitTopics(tracked = TRACKED) {
+ return tracked.map((base) => `allLiquidation.${bybitInstrument(base)}`);
+}
+
+/**
+ * Reads a Bybit `op` frame. Returns null for anything that is not an
+ * operation ack, so the caller can fall through to data parsing.
+ * @returns {{ op: string, ok: boolean, topic: string, message: string }|null}
+ */
+export function readBybitAck(raw) {
+ let msg;
+ try {
+ msg = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ if (!msg || typeof msg.op !== 'string') return null;
+ return {
+ op: msg.op,
+ ok: msg.success !== false,
+ topic: String(msg.req_id ?? ''),
+ message: String(msg.ret_msg ?? ''),
+ };
+}
+
+export function parseBybitMessage(raw, tracked = TRACKED) {
+ let msg;
+ try {
+ msg = JSON.parse(raw);
+ } catch {
+ return [];
+ }
+ if (!msg || msg.op || !Array.isArray(msg.data)) return [];
+ const out = [];
+ for (const d of msg.data) {
+ const { base, lot } = bybitBase(d.s);
+ if (!tracked.includes(base)) continue;
+ const lotPrice = parseFloat(d.p);
+ const lotQty = parseFloat(d.v);
+ if (!isFinitePositive(lotPrice) || !isFinitePositive(lotQty)) continue;
+ out.push({
+ exchange: 'Bybit',
+ price: lotPrice / lot,
+ qty: lotQty * lot,
+ // Bybit documents `S` on allLiquidation as the POSITION side: a Buy
+ // update means a long position was liquidated. That is inverted
+ // versus the order-side convention Binance and OKX use.
+ side: d.S === 'Buy' ? 'LONG' : 'SHORT',
+ symbol: base,
+ time: Number(d.T ?? msg.ts) || Date.now(),
+ value: lotPrice * lotQty,
+ });
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// OKX: wss://ws.okx.com:8443/ws/v5/public, channel liquidation-orders
+// Frame: { arg, data: [ { instId, instType, details: [ { bkPx, sz, side, ts } ] } ] }
+//
+// `sz` is a CONTRACT count, not a base-coin quantity: one BTC-USDT-SWAP
+// contract is 0.01 BTC and one BONK-USDT-SWAP contract is 100000 BONK. Taking
+// sz at face value overstated BTC liquidations 100x and understated BONK
+// 100000x, so an unknown instrument is dropped rather than guessed
+// (see src/okx-contracts.js for how the multipliers are fetched).
+// ---------------------------------------------------------------------------
+
+/**
+ * Base quantity + USD value of an OKX liquidation, using the instrument's
+ * contract specification. Returns null when the contract is unknown or the
+ * numbers are unusable, so callers never publish a fabricated size.
+ */
+export function okxSize({ contract, sz, price }) {
+ if (!contract) return null;
+ const contracts = parseFloat(sz);
+ const px = parseFloat(price);
+ if (!isFinitePositive(contracts) || !isFinitePositive(px)) return null;
+ const perContract = contract.ctVal * contract.ctMult;
+ if (!isFinitePositive(perContract)) return null;
+ const units = contracts * perContract;
+ // Inverse (coin-margined) contracts denominate ctVal in the quote currency:
+ // one BTC-USD-SWAP contract is 100 USD of notional, not 100 BTC.
+ if (contract.quoteDenominated) return { qty: units / px, value: units };
+ return { qty: units, value: units * px };
+}
+
+/**
+ * @param {string} raw
+ * @param {{ get: (instId: string) => ({ ctVal: number, ctMult: number, quoteDenominated: boolean }|undefined) }} contracts
+ */
+export function parseOkxMessage(raw, contracts, tracked = TRACKED) {
+ if (raw === 'pong') return [];
+ let msg;
+ try {
+ msg = JSON.parse(raw);
+ } catch {
+ return [];
+ }
+ if (!msg || msg.event || !Array.isArray(msg.data)) return [];
+ const out = [];
+ for (const item of msg.data) {
+ const instId = String(item.instId ?? '');
+ const base = instId.split('-')[0];
+ if (!tracked.includes(base)) continue;
+ const contract = contracts.get(instId);
+ if (!contract) continue;
+ for (const d of item.details ?? []) {
+ const sized = okxSize({ contract, sz: d.sz, price: d.bkPx });
+ if (!sized) continue;
+ out.push({
+ exchange: 'OKX',
+ price: parseFloat(d.bkPx),
+ qty: sized.qty,
+ side: d.side === 'buy' ? 'SHORT' : 'LONG',
+ symbol: base,
+ time: Number(d.ts) || Date.now(),
+ value: sized.value,
+ });
+ }
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Aggregate snapshot (the /liquidations response body)
+// ---------------------------------------------------------------------------
+
+export function buildSnapshot(entries, now = Date.now()) {
+ const cutoff = now - MAX_AGE_MS;
+ const recent = entries
+ .filter((l) => l.time > cutoff)
+ .sort((a, b) => b.time - a.time);
+
+ const longLiqs = recent.filter((l) => l.side === 'LONG');
+ const shortLiqs = recent.filter((l) => l.side === 'SHORT');
+ const longValue = longLiqs.reduce((s, l) => s + l.value, 0);
+ const shortValue = shortLiqs.reduce((s, l) => s + l.value, 0);
+
+ const bySymbol = {};
+ for (const l of recent) {
+ if (!bySymbol[l.symbol]) {
+ bySymbol[l.symbol] = { count: 0, longValue: 0, shortValue: 0, symbol: l.symbol };
+ }
+ bySymbol[l.symbol].count++;
+ if (l.side === 'LONG') bySymbol[l.symbol].longValue += l.value;
+ else bySymbol[l.symbol].shortValue += l.value;
+ }
+
+ return {
+ liquidations: recent.slice(0, 50),
+ summary: {
+ dominantSide:
+ longValue > shortValue * 1.5
+ ? 'LONG PAIN'
+ : shortValue > longValue * 1.5
+ ? 'SHORT SQUEEZE'
+ : 'BALANCED',
+ largeCount: recent.filter((l) => l.severity === 'LARGE').length,
+ longCount: longLiqs.length,
+ longValue,
+ megaCount: recent.filter((l) => l.severity === 'MEGA').length,
+ shortCount: shortLiqs.length,
+ shortValue,
+ totalCount: recent.length,
+ totalValue: longValue + shortValue,
+ },
+ symbolStats: Object.values(bySymbol).sort(
+ (a, b) => b.longValue + b.shortValue - (a.longValue + a.shortValue),
+ ),
+ timestamp: new Date(now).toISOString(),
+ };
+}
diff --git a/services/liquidation-collector/src/index.js b/services/liquidation-collector/src/index.js
index 8c4eef2d5..944374c42 100644
--- a/services/liquidation-collector/src/index.js
+++ b/services/liquidation-collector/src/index.js
@@ -1,165 +1,214 @@
-// three.ws liquidation-collector — standalone always-on Node service.
+// three.ws liquidation-collector: standalone always-on Node service.
//
// Subscribes to the PUBLIC futures liquidation WebSocket streams of Binance,
// Bybit, and OKX, classifies each liquidation by USD size, keeps a rolling
// 4-hour in-memory window, and serves an aggregate REST snapshot consumed by
-// `api/coin/liquidations.js` (proxy) → the "liquidations pulse" strip on
-// three.ws/coins.
+// `api/coin/liquidations.js` (proxy), which feeds the "liquidations pulse"
+// strip on three.ws/coins.
//
-// Ported faithfully from the reference SperaxOS collector
-// (_prompts/sperax/ref/liquidation-collector/index.ts) — same stream URLs,
-// per-exchange parsing, size buckets, reconnect/backoff, rolling window, and
-// aggregate math. The only change is swapping the Hono HTTP layer for plain
-// node:http so this package has zero framework dependencies beyond `ws`.
+// This file owns the wiring only: sockets, reconnects, lane health, and the
+// HTTP surface. Message parsing and the aggregate math live in
+// `src/collector.js` so they are testable without a network.
//
-// This process holds long-lived WebSocket connections — it is NOT deployable
+// This process holds long-lived WebSocket connections, so it is NOT deployable
// as a Vercel serverless function. Run it on any always-on Node host (see
// README.md) and point `LIQUIDATION_COLLECTOR_URL` at it.
import { createServer } from 'node:http';
import { WebSocket } from 'ws';
-// ---------------------------------------------------------------------------
-// Config
-// ---------------------------------------------------------------------------
-
-const TRACKED = [
- 'BTC', 'ETH', 'SOL', 'DOGE', 'XRP', 'ARB', 'OP', 'AVAX', 'LINK',
- 'BNB', 'SUI', 'WIF', 'PEPE', 'BONK', 'INJ', 'TIA', 'APT', 'NEAR',
-];
-
-const MAX_CACHE = 10_000;
-const MAX_AGE_MS = 4 * 60 * 60 * 1000; // 4 hours
+import {
+ TRACKED,
+ buildSnapshot,
+ bybitTopics,
+ createStore,
+ parseBinanceMessage,
+ parseBybitMessage,
+ parseOkxMessage,
+ readBybitAck,
+} from './collector.js';
+import { createOkxContractRegistry } from './okx-contracts.js';
+
+const RECONNECT_MS = 5_000;
+const PING_MS = 20_000;
+const BINANCE_RECHECK_MS = 60 * 60 * 1000;
+const BINANCE_PING_URL = 'https://fapi.binance.com/fapi/v1/ping';
+
+const store = createStore();
+const okxContracts = createOkxContractRegistry();
// ---------------------------------------------------------------------------
-// In-memory store
+// Lane health
+//
+// A silently dead lane is the failure mode this service is most exposed to:
+// both Bybit (a retired topic name) and Binance (a geo-restricted host) kept
+// an open, quiet socket while contributing nothing. /health reports each lane
+// so "connected" can never be mistaken for "delivering".
// ---------------------------------------------------------------------------
-/** @typedef {{ exchange: string, price: number, qty: number, severity: string, side: 'LONG'|'SHORT', symbol: string, time: number, value: number }} LiquidationEntry */
+const streams = {
+ Binance: { state: 'starting', events: 0, lastEventAt: null, note: '' },
+ Bybit: { state: 'starting', events: 0, lastEventAt: null, note: '' },
+ OKX: { state: 'starting', events: 0, lastEventAt: null, note: '' },
+};
-/** @type {LiquidationEntry[]} */
-const cache = [];
+function setState(exchange, state, note = '') {
+ streams[exchange].state = state;
+ streams[exchange].note = note;
+}
-function classify(value) {
- if (value >= 1_000_000) return 'MEGA';
- if (value >= 100_000) return 'LARGE';
- if (value >= 10_000) return 'MEDIUM';
- return 'SMALL';
+function record(exchange, entries) {
+ if (entries.length === 0) return;
+ for (const entry of entries) store.push(entry);
+ streams[exchange].events += entries.length;
+ streams[exchange].lastEventAt = Date.now();
}
-function push(entry) {
- cache.push({ ...entry, severity: classify(entry.value) });
- if (cache.length > MAX_CACHE) cache.shift();
+/** @type {Set<WebSocket>} */
+const sockets = new Set();
+let shuttingDown = false;
+
+function track(ws) {
+ sockets.add(ws);
+ ws.on('close', () => sockets.delete(ws));
}
// ---------------------------------------------------------------------------
-// Binance — public stream: wss://fstream.binance.com/ws/!forceOrder@arr
+// Binance: wss://fstream.binance.com/ws/!forceOrder@arr
+//
+// Binance answers 451 "restricted location" to US-hosted callers, and its
+// WebSocket endpoint accepts the connection but never pushes a frame, so an
+// open socket proves nothing. We probe the public REST ping first and report
+// the lane as `restricted` (rechecked hourly) rather than pretending to be
+// connected. Hosting the service outside a restricted region lights it up
+// with no code change.
// ---------------------------------------------------------------------------
+async function binanceAccessible() {
+ try {
+ const resp = await fetch(BINANCE_PING_URL, { signal: AbortSignal.timeout(10_000) });
+ if (resp.ok) return { ok: true, reason: '' };
+ if (resp.status === 451) {
+ return { ok: false, reason: 'Binance blocks this host region (HTTP 451); host the collector outside a restricted region to enable this lane' };
+ }
+ return { ok: false, reason: `Binance ping responded ${resp.status}` };
+ } catch (err) {
+ return { ok: false, reason: `Binance ping failed: ${err.message}` };
+ }
+}
+
+async function startBinance() {
+ if (shuttingDown) return;
+ const access = await binanceAccessible();
+ if (!access.ok) {
+ setState('Binance', 'restricted', access.reason);
+ console.warn(`[Binance] lane disabled: ${access.reason}`);
+ setTimeout(startBinance, BINANCE_RECHECK_MS).unref?.();
+ return;
+ }
+ connectBinance();
+}
+
function connectBinance() {
+ setState('Binance', 'connecting');
const ws = new WebSocket('wss://fstream.binance.com/ws/!forceOrder@arr');
+ track(ws);
let ping;
ws.on('open', () => {
+ setState('Binance', 'connected');
console.log('[Binance] connected');
- ping = setInterval(() => ws.ping(), 20_000);
+ ping = setInterval(() => ws.ping(), PING_MS);
});
ws.on('message', (data) => {
- try {
- const msg = JSON.parse(data.toString());
- const o = msg.o;
- if (!o) return;
- const base = String(o.s).replace('USDT', '').replace('BUSD', '');
- if (!TRACKED.includes(base)) return;
- const price = parseFloat(o.ap || o.p);
- const qty = parseFloat(o.q);
- if (isNaN(price) || isNaN(qty)) return;
- push({
- exchange: 'Binance',
- price,
- qty,
- side: o.S === 'BUY' ? 'SHORT' : 'LONG',
- symbol: base,
- time: o.T ?? Date.now(),
- value: price * qty,
- });
- } catch {}
+ record('Binance', parseBinanceMessage(data.toString(), TRACKED));
});
ws.on('close', () => {
clearInterval(ping);
- console.log('[Binance] disconnected — reconnecting in 5s');
- setTimeout(connectBinance, 5_000);
+ if (shuttingDown) return;
+ setState('Binance', 'reconnecting');
+ console.log('[Binance] disconnected, reconnecting in 5s');
+ setTimeout(startBinance, RECONNECT_MS).unref?.();
});
ws.on('error', (err) => {
+ setState('Binance', 'error', err.message);
console.error('[Binance] error', err.message);
ws.terminate();
});
}
// ---------------------------------------------------------------------------
-// Bybit — public stream: wss://stream.bybit.com/v5/public/linear
-// Topics: liquidation.{SYMBOL}USDT
+// Bybit: wss://stream.bybit.com/v5/public/linear
+//
+// One subscribe frame per topic, each tagged with a req_id, so a single
+// unlisted instrument cannot reject the whole batch and every ack is
+// attributable. The retired `liquidation.{SYMBOL}` topic answered
+// "handler not found" for years while the lane looked healthy; failed acks
+// are now logged and surfaced on /health.
// ---------------------------------------------------------------------------
function connectBybit() {
+ setState('Bybit', 'connecting');
const ws = new WebSocket('wss://stream.bybit.com/v5/public/linear');
+ track(ws);
let ping;
+ const rejected = [];
ws.on('open', () => {
+ setState('Bybit', 'connected');
console.log('[Bybit] connected');
- const args = TRACKED.map((s) => `liquidation.${s}USDT`);
- ws.send(JSON.stringify({ op: 'subscribe', args }));
- ping = setInterval(() => ws.send(JSON.stringify({ op: 'ping' })), 20_000);
+ for (const topic of bybitTopics(TRACKED)) {
+ ws.send(JSON.stringify({ op: 'subscribe', req_id: topic, args: [topic] }));
+ }
+ ping = setInterval(() => ws.send(JSON.stringify({ op: 'ping' })), PING_MS);
});
ws.on('message', (data) => {
- try {
- const msg = JSON.parse(data.toString());
- // skip pong / subscribe confirmations
- if (msg.op || !msg.data) return;
- const d = msg.data;
- const base = (d.symbol ?? '').replace('USDT', '');
- if (!TRACKED.includes(base)) return;
- const price = parseFloat(d.price);
- const qty = parseFloat(d.size);
- if (isNaN(price) || isNaN(qty)) return;
- push({
- exchange: 'Bybit',
- price,
- qty,
- side: d.side === 'Buy' ? 'SHORT' : 'LONG',
- symbol: base,
- time: Number(d.updatedTime ?? d.updateTime) || Date.now(),
- value: price * qty,
- });
- } catch {}
+ const raw = data.toString();
+ const ack = readBybitAck(raw);
+ if (ack) {
+ if (ack.op === 'subscribe' && !ack.ok) {
+ rejected.push(ack.topic || ack.message);
+ setState('Bybit', 'degraded', `rejected topics: ${rejected.join(', ')}`);
+ console.error(`[Bybit] subscribe rejected for ${ack.topic}: ${ack.message}`);
+ }
+ return;
+ }
+ record('Bybit', parseBybitMessage(raw, TRACKED));
});
ws.on('close', () => {
clearInterval(ping);
- console.log('[Bybit] disconnected — reconnecting in 5s');
- setTimeout(connectBybit, 5_000);
+ if (shuttingDown) return;
+ setState('Bybit', 'reconnecting');
+ console.log('[Bybit] disconnected, reconnecting in 5s');
+ setTimeout(connectBybit, RECONNECT_MS).unref?.();
});
ws.on('error', (err) => {
+ setState('Bybit', 'error', err.message);
console.error('[Bybit] error', err.message);
ws.terminate();
});
}
// ---------------------------------------------------------------------------
-// OKX — public stream: wss://ws.okx.com:8443/ws/v5/public
-// Channel: liquidation-orders (all SWAP instruments, real-time)
+// OKX: wss://ws.okx.com:8443/ws/v5/public, channel liquidation-orders
+// (all SWAP instruments, real-time). Sizes are converted from contracts to
+// base units via the instrument registry.
// ---------------------------------------------------------------------------
function connectOKX() {
+ setState('OKX', 'connecting');
const ws = new WebSocket('wss://ws.okx.com:8443/ws/v5/public');
+ track(ws);
let ping;
ws.on('open', () => {
+ setState('OKX', 'connected');
console.log('[OKX] connected');
ws.send(
JSON.stringify({
@@ -167,44 +216,23 @@ function connectOKX() {
args: [{ channel: 'liquidation-orders', instType: 'SWAP' }],
}),
);
- ping = setInterval(() => ws.send('ping'), 20_000);
+ ping = setInterval(() => ws.send('ping'), PING_MS);
});
ws.on('message', (data) => {
- try {
- const text = data.toString();
- if (text === 'pong') return;
- const msg = JSON.parse(text);
- if (msg.event) return; // subscribe ack
- if (!Array.isArray(msg.data)) return;
- for (const item of msg.data) {
- const base = String(item.instId).split('-')[0];
- if (!TRACKED.includes(base)) continue;
- for (const d of item.details ?? []) {
- const price = parseFloat(d.bkPx);
- const qty = parseFloat(d.sz);
- if (isNaN(price) || isNaN(qty)) continue;
- push({
- exchange: 'OKX',
- price,
- qty,
- side: d.side === 'buy' ? 'SHORT' : 'LONG',
- symbol: base,
- time: parseInt(d.ts) || Date.now(),
- value: price * qty,
- });
- }
- }
- } catch {}
+ record('OKX', parseOkxMessage(data.toString(), okxContracts, TRACKED));
});
ws.on('close', () => {
clearInterval(ping);
- console.log('[OKX] disconnected — reconnecting in 5s');
- setTimeout(connectOKX, 5_000);
+ if (shuttingDown) return;
+ setState('OKX', 'reconnecting');
+ console.log('[OKX] disconnected, reconnecting in 5s');
+ setTimeout(connectOKX, RECONNECT_MS).unref?.();
});
ws.on('error', (err) => {
+ setState('OKX', 'error', err.message);
console.error('[OKX] error', err.message);
ws.terminate();
});
@@ -214,52 +242,6 @@ function connectOKX() {
// REST API (consumed by api/coin/liquidations.js)
// ---------------------------------------------------------------------------
-function buildSnapshot() {
- const cutoff = Date.now() - MAX_AGE_MS;
- const recent = cache
- .filter((l) => l.time > cutoff)
- .sort((a, b) => b.time - a.time);
-
- const longLiqs = recent.filter((l) => l.side === 'LONG');
- const shortLiqs = recent.filter((l) => l.side === 'SHORT');
- const longValue = longLiqs.reduce((s, l) => s + l.value, 0);
- const shortValue = shortLiqs.reduce((s, l) => s + l.value, 0);
-
- const bySymbol = {};
- for (const l of recent) {
- if (!bySymbol[l.symbol]) {
- bySymbol[l.symbol] = { count: 0, longValue: 0, shortValue: 0, symbol: l.symbol };
- }
- bySymbol[l.symbol].count++;
- if (l.side === 'LONG') bySymbol[l.symbol].longValue += l.value;
- else bySymbol[l.symbol].shortValue += l.value;
- }
-
- return {
- liquidations: recent.slice(0, 50),
- summary: {
- dominantSide:
- longValue > shortValue * 1.5
- ? 'LONG PAIN'
- : shortValue > longValue * 1.5
- ? 'SHORT SQUEEZE'
- : 'BALANCED',
- largeCount: recent.filter((l) => l.severity === 'LARGE').length,
- longCount: longLiqs.length,
- longValue,
- megaCount: recent.filter((l) => l.severity === 'MEGA').length,
- shortCount: shortLiqs.length,
- shortValue,
- totalCount: recent.length,
- totalValue: longValue + shortValue,
- },
- symbolStats: Object.values(bySymbol).sort(
- (a, b) => b.longValue + b.shortValue - (a.longValue + a.shortValue),
- ),
- timestamp: new Date().toISOString(),
- };
-}
-
function sendJson(res, status, body) {
const payload = JSON.stringify(body);
res.writeHead(status, {
@@ -288,12 +270,18 @@ const server = createServer((req, res) => {
}
if (url.pathname === '/health') {
- sendJson(res, 200, { ok: true, cached: cache.length, uptime: process.uptime() });
+ sendJson(res, 200, {
+ ok: true,
+ cached: store.size,
+ uptime: process.uptime(),
+ okxContracts: okxContracts.size,
+ streams,
+ });
return;
}
if (url.pathname === '/liquidations') {
- sendJson(res, 200, buildSnapshot());
+ sendJson(res, 200, buildSnapshot(store.entries));
return;
}
@@ -304,7 +292,23 @@ const server = createServer((req, res) => {
// Boot
// ---------------------------------------------------------------------------
-connectBinance();
+function shutdown(signal) {
+ if (shuttingDown) return;
+ shuttingDown = true;
+ console.log(`[collector] ${signal} received, closing streams`);
+ okxContracts.stop();
+ for (const ws of sockets) ws.close();
+ server.close(() => process.exit(0));
+ setTimeout(() => process.exit(0), 5_000).unref?.();
+}
+
+process.on('SIGTERM', () => shutdown('SIGTERM'));
+process.on('SIGINT', () => shutdown('SIGINT'));
+
+await okxContracts.refresh();
+okxContracts.start();
+
+startBinance();
connectBybit();
connectOKX();
diff --git a/services/liquidation-collector/src/okx-contracts.js b/services/liquidation-collector/src/okx-contracts.js
new file mode 100644
index 000000000..442d58ed0
--- /dev/null
+++ b/services/liquidation-collector/src/okx-contracts.js
@@ -0,0 +1,110 @@
+// OKX contract specifications.
+//
+// The liquidation-orders channel reports `sz` in CONTRACTS. One BTC-USDT-SWAP
+// contract is 0.01 BTC, one BONK-USDT-SWAP contract is 100000 BONK, and one
+// BTC-USD-SWAP contract is 100 USD of notional. Without these multipliers the
+// USD value of every OKX liquidation is wrong by orders of magnitude, so the
+// collector loads them from the public instruments endpoint at boot and
+// refreshes them periodically (new listings appear between restarts).
+//
+// No key or account is required: this is the same public REST surface the
+// exchange serves to anonymous callers.
+
+const INSTRUMENTS_URL = 'https://www.okx.com/api/v5/public/instruments?instType=SWAP';
+const REFRESH_MS = 6 * 60 * 60 * 1000;
+const MIN_REFRESH_MS = 60_000;
+const QUOTE_CURRENCIES = ['USD', 'USDT', 'USDC'];
+
+/**
+ * @param {Array<Record<string, string>>} rows raw `data` array from OKX
+ * @returns {Map<string, { ctVal: number, ctMult: number, quoteDenominated: boolean }>}
+ */
+export function parseInstruments(rows) {
+ const map = new Map();
+ for (const row of rows ?? []) {
+ const instId = String(row.instId ?? '');
+ const ctVal = parseFloat(row.ctVal);
+ const ctMult = row.ctMult === undefined || row.ctMult === '' ? 1 : parseFloat(row.ctMult);
+ if (!instId || !Number.isFinite(ctVal) || ctVal <= 0) continue;
+ if (!Number.isFinite(ctMult) || ctMult <= 0) continue;
+ map.set(instId, {
+ ctVal,
+ ctMult,
+ quoteDenominated: QUOTE_CURRENCIES.includes(String(row.ctValCcy ?? '').toUpperCase()),
+ });
+ }
+ return map;
+}
+
+/**
+ * Live registry of OKX swap contract sizes.
+ *
+ * @param {{ fetchImpl?: typeof fetch, url?: string, refreshMs?: number, minRefreshMs?: number, now?: () => number, log?: (msg: string) => void }} [opts]
+ */
+export function createOkxContractRegistry({
+ fetchImpl = fetch,
+ url = INSTRUMENTS_URL,
+ refreshMs = REFRESH_MS,
+ minRefreshMs = MIN_REFRESH_MS,
+ now = Date.now,
+ log = console.log,
+} = {}) {
+ let contracts = new Map();
+ let lastAttempt = 0;
+ let inFlight = null;
+ let timer = null;
+
+ async function refresh() {
+ if (inFlight) return inFlight;
+ lastAttempt = now();
+ inFlight = (async () => {
+ try {
+ const resp = await fetchImpl(url, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!resp.ok) throw new Error(`instruments responded ${resp.status}`);
+ const body = await resp.json();
+ const parsed = parseInstruments(body?.data);
+ if (parsed.size === 0) throw new Error('instruments payload had no usable contracts');
+ contracts = parsed;
+ log(`[OKX] loaded ${parsed.size} swap contract sizes`);
+ return parsed;
+ } catch (err) {
+ log(`[OKX] contract sizes unavailable (${err.message}); OKX liquidations are dropped until this succeeds`);
+ return contracts;
+ } finally {
+ inFlight = null;
+ }
+ })();
+ return inFlight;
+ }
+
+ return {
+ refresh,
+ get size() {
+ return contracts.size;
+ },
+ /**
+ * Contract spec for an instrument, or undefined when it is unknown. A
+ * miss schedules a rate-limited refresh so a brand-new listing starts
+ * counting within the minute instead of at the next restart.
+ */
+ get(instId) {
+ const hit = contracts.get(instId);
+ if (hit) return hit;
+ if (now() - lastAttempt >= minRefreshMs) refresh();
+ return undefined;
+ },
+ start() {
+ if (timer) return;
+ timer = setInterval(() => { refresh(); }, refreshMs);
+ timer.unref?.();
+ },
+ stop() {
+ if (!timer) return;
+ clearInterval(timer);
+ timer = null;
+ },
+ };
+}
diff --git a/tests/agent-screen-caster.test.js b/tests/agent-screen-caster.test.js
new file mode 100644
index 000000000..9da23c1ef
--- /dev/null
+++ b/tests/agent-screen-caster.test.js
@@ -0,0 +1,224 @@
+/**
+ * services/agent-screen-caster core-path smoke test.
+ *
+ * Runs the real service against a real browser: Playwright Chromium drives a
+ * page served by a local HTTP server, and that same server stands in for
+ * /api/agent-screen-push so every byte the caster emits can be inspected.
+ * Nothing in the caster is stubbed, and the frames asserted here are genuine
+ * JPEGs captured from a genuine render.
+ *
+ * What this pins:
+ * 1. navigate()/act() push an activity record BEFORE the work and a frame
+ * after it, so a watcher sees the narration and the result in that order.
+ * 2. Every push carries the agentId and the bearer token. A frame without the
+ * agent id is rejected by the endpoint with 400 missing_agent_id, which is
+ * how a caster goes silently dark while looking healthy in its own logs.
+ * 3. Frames are real JPEG data URLs (the endpoint drops anything that is not
+ * a base64 raster image down to text-only).
+ * 4. The frame loop keeps capturing on its interval and stops on demand.
+ * 5. An activity push survives a transient 503, and a 4xx is not retried.
+ * The caster is a long-running process: dying on one blip loses a session.
+ */
+
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
+import { createServer } from 'node:http';
+import { AgentScreenCaster, isRetryableStatus } from '../services/agent-screen-caster/caster.js';
+
+const AGENT_ID = '11111111-2222-3333-4444-555555555555';
+const BEARER = 'sk_live_test_caster_token';
+
+const PAGE_HTML = `<!doctype html><html><head><title>Caster test page</title></head>
+<body style="background:#101014;color:#eaeaf0;font:16px system-ui">
+<h1 id="headline">Live agent screen</h1><p id="price">$0.0421</p></body></html>`;
+
+let server;
+let baseUrl;
+/** Every push the stand-in endpoint received, in order. */
+let received;
+/** Statuses the push endpoint answers with, drained FIFO; 200 once empty. */
+let statusQueue;
+
+beforeAll(async () => {
+ server = createServer((req, res) => {
+ if (req.url === '/page') {
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ res.end(PAGE_HTML);
+ return;
+ }
+
+ if (req.url === '/api/agent-screen-push' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ const status = statusQueue.length ? statusQueue.shift() : 200;
+ let parsed = null;
+ try { parsed = JSON.parse(body); } catch { /* recorded as null */ }
+ received.push({ status, auth: req.headers.authorization, body: parsed });
+ if (status !== 200) {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: 'transient' }));
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, ts: Date.now() }));
+ });
+ return;
+ }
+
+ res.writeHead(404);
+ res.end();
+ });
+
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ baseUrl = `http://127.0.0.1:${server.address().port}`;
+});
+
+afterAll(async () => {
+ await new Promise((resolve) => server.close(resolve));
+});
+
+beforeEach(() => {
+ received = [];
+ statusQueue = [];
+});
+
+const pushUrl = () => `${baseUrl}/api/agent-screen-push`;
+const frames = () => received.filter((r) => r.body?.frame?.data);
+const activities = () => received.filter((r) => r.body?.frame?.activity);
+
+describe('AgentScreenCaster constructor', () => {
+ it('refuses to run without an identity to push as', () => {
+ expect(() => new AgentScreenCaster({ bearerToken: BEARER })).toThrow(/agentId/);
+ expect(() => new AgentScreenCaster({ agentId: AGENT_ID })).toThrow(/bearerToken/);
+ });
+});
+
+describe('isRetryableStatus', () => {
+ it('retries a rate limit and a server error, never a client error', () => {
+ expect(isRetryableStatus(429)).toBe(true);
+ expect(isRetryableStatus(500)).toBe(true);
+ expect(isRetryableStatus(503)).toBe(true);
+ expect(isRetryableStatus(400)).toBe(false);
+ expect(isRetryableStatus(401)).toBe(false);
+ expect(isRetryableStatus(403)).toBe(false);
+ expect(isRetryableStatus(200)).toBe(false);
+ });
+});
+
+describe('push transport', () => {
+ it('retries an activity push through a transient 503 and reports the summary once', async () => {
+ const caster = new AgentScreenCaster({ agentId: AGENT_ID, bearerToken: BEARER, pushUrl: pushUrl() });
+ statusQueue = [503];
+
+ await caster.pushActivity([{ type: 'analysis', summary: 'Reading the board', ts: Date.now() }]);
+
+ expect(received).toHaveLength(2);
+ expect(received[0].status).toBe(503);
+ expect(received[1].status).toBe(200);
+ expect(received[1].body.frame.activity).toBe('Reading the board');
+ expect(received[1].body.agentId).toBe(AGENT_ID);
+ });
+
+ it('gives up immediately on a 401 rather than hammering a dead credential', async () => {
+ const caster = new AgentScreenCaster({ agentId: AGENT_ID, bearerToken: 'stale', pushUrl: pushUrl() });
+ statusQueue = [401, 401, 401];
+
+ await expect(
+ caster.pushActivity([{ type: 'activity', summary: 'Waking up', ts: Date.now() }]),
+ ).rejects.toThrow(/screen-push 401/);
+
+ expect(received).toHaveLength(1);
+ });
+
+ it('skips an entry with no summary instead of pushing a blank line', async () => {
+ const caster = new AgentScreenCaster({ agentId: AGENT_ID, bearerToken: BEARER, pushUrl: pushUrl() });
+
+ await caster.pushActivity([{ type: 'activity', summary: '' }, null, { type: 'activity' }]);
+
+ expect(received).toHaveLength(0);
+ });
+});
+
+describe('live browser core path', () => {
+ let caster;
+
+ afterAll(async () => {
+ await caster?.close();
+ });
+
+ it('navigates, acts, and streams real JPEG frames to the push endpoint', async () => {
+ caster = new AgentScreenCaster({
+ agentId: AGENT_ID,
+ bearerToken: BEARER,
+ pushUrl: pushUrl(),
+ frameIntervalMs: 250,
+ jpegQuality: 50,
+ });
+
+ await caster.launch(true);
+ await caster.navigate(`${baseUrl}/page`);
+
+ // The page really rendered: the caster's own browser handle reads it back.
+ expect(await caster.page.title()).toBe('Caster test page');
+
+ // navigate() narrates first, then captures.
+ const navActivity = activities()[0];
+ expect(navActivity.body.frame.activity).toContain('/page');
+ expect(navActivity.body.frame.type).toBe('navigate');
+ expect(navActivity.auth).toBe(`Bearer ${BEARER}`);
+ expect(frames().length).toBeGreaterThan(0);
+
+ // Frames are genuine JPEGs, not an empty or malformed data URL.
+ const jpeg = frames()[0].body.frame;
+ expect(jpeg.type).toBe('screenshot');
+ expect(jpeg.data.startsWith('data:image/jpeg;base64,')).toBe(true);
+ const bytes = Buffer.from(jpeg.data.split(',')[1], 'base64');
+ expect(bytes.length).toBeGreaterThan(1000);
+ expect([bytes[0], bytes[1], bytes[2]]).toEqual([0xff, 0xd8, 0xff]);
+
+ // act() wraps a real page interaction between its narration and its frame.
+ const beforeAct = received.length;
+ await caster.act('analysis', 'Reading the headline', async () => {
+ await caster.page.waitForSelector('#headline');
+ });
+ const actPushes = received.slice(beforeAct);
+ expect(actPushes[0].body.frame.activity).toBe('Reading the headline');
+ expect(actPushes[0].body.frame.type).toBe('analysis');
+ expect(actPushes[actPushes.length - 1].body.frame.data).toContain('data:image/jpeg;base64,');
+
+ // The frame loop keeps the stream alive on its own interval, and stops.
+ const beforeLoop = frames().length;
+ caster.startFrameLoop();
+ await new Promise((r) => setTimeout(r, 1200));
+ expect(frames().length).toBeGreaterThan(beforeLoop);
+
+ // After stopping, let the capture already in flight land, then confirm the
+ // count holds: no timer is still firing behind it.
+ caster.stopFrameLoop();
+ await new Promise((r) => setTimeout(r, 700));
+ const settled = frames().length;
+ await new Promise((r) => setTimeout(r, 700));
+ expect(frames().length).toBe(settled);
+
+ // Every push in the whole run identified the agent and carried the token.
+ for (const r of received) {
+ expect(r.body.agentId).toBe(AGENT_ID);
+ expect(r.auth).toBe(`Bearer ${BEARER}`);
+ }
+ });
+
+ it('shuts down without a failed capture racing the closing browser', async () => {
+ caster.startFrameLoop();
+ const errors = [];
+ const realError = console.error;
+ console.error = (...args) => { errors.push(args.join(' ')); };
+ try {
+ await caster.close();
+ await new Promise((r) => setTimeout(r, 500));
+ } finally {
+ console.error = realError;
+ }
+ expect(errors.filter((e) => e.includes('frame push failed'))).toHaveLength(0);
+ expect(caster.page).toBeNull();
+ });
+});
diff --git a/tests/agent-screen-log-plumbing.test.js b/tests/agent-screen-log-plumbing.test.js
new file mode 100644
index 000000000..07839325b
--- /dev/null
+++ b/tests/agent-screen-log-plumbing.test.js
@@ -0,0 +1,65 @@
+/**
+ * Activity-log plumbing between /api/agent-screen-push and
+ * /api/agent-screen-stream.
+ *
+ * Both halves shipped a bug that made a live caster's narration invisible while
+ * every component reported success, found by running
+ * services/agent-screen-caster against production on 2026-08-11:
+ *
+ * 1. Write side: the push endpoint logged EVERY frame, including the
+ * pixels-only screenshots a caster emits every FRAME_INTERVAL_MS. Those
+ * blank entries evicted the agent's real narration from the 50-entry log
+ * within seconds.
+ * 2. Read side: the Upstash REST client deserializes JSON responses, so a log
+ * entry read back with lrange arrives as an object. Running JSON.parse over
+ * it threw, every entry was dropped, and the stream sent `entries: []` while
+ * also suppressing the database backfill that would have filled the panel.
+ * Viewer reactions were read the same way and never fanned out.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { shouldLogEntry } from '../api/agent-screen-push.js';
+import { parseRedisRecord } from '../api/agent-screen-stream.js';
+
+describe('shouldLogEntry', () => {
+ it('logs an entry that carries readable narration', () => {
+ expect(shouldLogEntry({ activity: 'Navigating to pump.fun' })).toBe(true);
+ });
+
+ it('drops a pixels-only screenshot push', () => {
+ expect(shouldLogEntry({ activity: '' })).toBe(false);
+ expect(shouldLogEntry({})).toBe(false);
+ });
+
+ it('keeps a structured ride-along even with no activity text', () => {
+ expect(shouldLogEntry({ activity: '', pnl: { phase: 'exit', pct: 12 } })).toBe(true);
+ expect(shouldLogEntry({ activity: '', meta: { glbUrl: 'https://three.ws/a.glb' } })).toBe(true);
+ expect(shouldLogEntry({ activity: '', mm: { type: 'mm_defend', floorSol: 1 } })).toBe(true);
+ });
+});
+
+describe('parseRedisRecord', () => {
+ it('accepts the already-deserialized object the Upstash client returns', () => {
+ const entry = { ts: 1, activity: 'Reading the board', type: 'analysis' };
+ expect(parseRedisRecord(entry)).toEqual(entry);
+ });
+
+ it('accepts a raw JSON string from a client without auto-deserialization', () => {
+ expect(parseRedisRecord('{"ts":2,"activity":"Buying","type":"trade"}')).toEqual({
+ ts: 2, activity: 'Buying', type: 'trade',
+ });
+ });
+
+ it('returns null for values no viewer could render', () => {
+ expect(parseRedisRecord('not json')).toBeNull();
+ expect(parseRedisRecord(null)).toBeNull();
+ expect(parseRedisRecord(undefined)).toBeNull();
+ expect(parseRedisRecord(42)).toBeNull();
+ });
+
+ it('survives a mixed list without losing the decodable entries', () => {
+ const raw = [{ ts: 3, activity: 'a' }, 'not json', '{"ts":4,"activity":"b"}', null];
+ const entries = raw.map(parseRedisRecord).filter(Boolean);
+ expect(entries.map((e) => e.activity)).toEqual(['a', 'b']);
+ });
+});
diff --git a/workers/model-hunyuan3d/Dockerfile b/workers/model-hunyuan3d/Dockerfile
index 9aeda86db..8f0e2a6cc 100644
--- a/workers/model-hunyuan3d/Dockerfile
+++ b/workers/model-hunyuan3d/Dockerfile
@@ -59,6 +59,7 @@ print('deps ok:', torch.__version__, torchvision.__version__, transformers.__ver
WORKDIR /app
COPY worker_security.py /app/worker_security.py
+COPY image_source.py /app/image_source.py
COPY main.py /app/main.py
EXPOSE 8080
diff --git a/workers/model-hunyuan3d/Dockerfile.hunyuan21 b/workers/model-hunyuan3d/Dockerfile.hunyuan21
index af519fd32..93e873cf4 100644
--- a/workers/model-hunyuan3d/Dockerfile.hunyuan21
+++ b/workers/model-hunyuan3d/Dockerfile.hunyuan21
@@ -93,6 +93,7 @@ print('deps ok:', torch.__version__, torchvision.__version__, transformers.__ver
# by repo-relative path, so cwd must be /opt/hunyuan3d21.
WORKDIR /opt/hunyuan3d21
COPY worker_security.py /opt/hunyuan3d21/worker_security.py
+COPY image_source.py /opt/hunyuan3d21/image_source.py
COPY app21.py /opt/hunyuan3d21/app21.py
EXPOSE 8080
diff --git a/workers/model-hunyuan3d/Dockerfile.hunyuan21rtx b/workers/model-hunyuan3d/Dockerfile.hunyuan21rtx
index 7963626a9..951289a4e 100644
--- a/workers/model-hunyuan3d/Dockerfile.hunyuan21rtx
+++ b/workers/model-hunyuan3d/Dockerfile.hunyuan21rtx
@@ -91,6 +91,7 @@ print('deps ok:', torch.__version__, torchvision.__version__, transformers.__ver
# by repo-relative path, so cwd must be /opt/hunyuan3d21.
WORKDIR /opt/hunyuan3d21
COPY worker_security.py /opt/hunyuan3d21/worker_security.py
+COPY image_source.py /opt/hunyuan3d21/image_source.py
COPY app21.py /opt/hunyuan3d21/app21.py
EXPOSE 8080
diff --git a/workers/model-hunyuan3d/app21.py b/workers/model-hunyuan3d/app21.py
index dbcb71117..58655e8a1 100644
--- a/workers/model-hunyuan3d/app21.py
+++ b/workers/model-hunyuan3d/app21.py
@@ -58,8 +58,6 @@ Environment variables:
from __future__ import annotations
import asyncio
-import base64
-import io
import json
import logging
import os
@@ -78,12 +76,12 @@ from PIL import Image
from pydantic import BaseModel, Field
from worker_security import (
- UnsafeUrlError,
- fetch_remote_bytes,
require_api_key,
safe_error,
)
+from image_source import FETCH_ATTEMPTS, ImageSourceError, decode_image
+
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
@@ -377,18 +375,20 @@ def _require_api_key(authorization: str) -> None:
def _decode_image(src: str) -> Image.Image:
- if src.startswith("data:image"):
- b64 = src.split(",", 1)[1]
- return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")
- if src.startswith("https://"):
- # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs
- # rejected after DNS resolution, redirects re-validated per hop, bounded.
- try:
- data = fetch_remote_bytes(src, timeout=30)
- except UnsafeUrlError as exc:
- raise ValueError(f"refused to fetch image source: {exc}") from exc
- return Image.open(io.BytesIO(data)).convert("RGB")
- raise ValueError(f"unsupported image source: {src[:60]}")
+ """Read one caller-supplied image, retrying transient fetch blips.
+
+ Every failure arrives as ImageSourceError so _run_inference can report the
+ real reason (a 404 reference image, an unreachable host) instead of an
+ opaque error ref that tells nobody anything. See image_source.py.
+ """
+
+ def note_retry(number: int, delay: float, exc: BaseException) -> None:
+ log.warning(
+ "image fetch attempt %d/%d failed (%s); retrying in %.1fs",
+ number, FETCH_ATTEMPTS, type(exc).__name__, delay,
+ )
+
+ return decode_image(src, on_retry=note_retry)
async def _run_inference(task_id: str, images: list[str], quality: dict | None = None) -> None:
@@ -429,6 +429,17 @@ async def _run_inference(task_id: str, images: list[str], quality: dict | None =
elapsed_ms=int(elapsed * 1000),
)
log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)
+ except ImageSourceError as exc:
+ # The request's own `images` entry is at fault, so hand the reason
+ # back verbatim: an opaque error ref would tell the caller nothing
+ # and leaves the router retrying a URL that can never work.
+ log.warning("[%s] image source rejected: %s", task_id, exc)
+ await _update_task(
+ task_id,
+ status="failed",
+ error=str(exc),
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
except Exception as exc:
await _update_task(
task_id,
diff --git a/workers/model-hunyuan3d/image_source.py b/workers/model-hunyuan3d/image_source.py
new file mode 100644
index 000000000..7cc2cc4eb
--- /dev/null
+++ b/workers/model-hunyuan3d/image_source.py
@@ -0,0 +1,198 @@
+"""Caller-supplied image sourcing for the Hunyuan3D workers.
+
+Both apps in this directory (``app21.py``, the live 2.1 lane, and ``main.py``,
+the 2.0 lane) reconstruct from an image URL the platform hands them. Until this
+module existed each of them fetched that URL with a bare
+``fetch_remote_bytes(src, timeout=30)`` inside the generic ``except Exception``
+of ``_run_inference``, which produced two live defects:
+
+ 1. **The reason was destroyed.** Any fetch failure became
+ ``safe_error(...)`` -> ``internal error (ref <id>)``. That string is what
+ lands in ``forge_creations.error``, the platform's declared ground truth
+ for generation issues, so the single most common real cause of a failed
+ generation (the reference image URL answering 403/404, or a read timing
+ out mid-stream) was indistinguishable from a GPU fault. Measured over the
+ 7 days to 2026-08-11: 11 of 24 failed forge rows carried an opaque ref,
+ and every one traced back to this fetch.
+ 2. **A dead URL burned more GPU.** An opaque failure is a retryable failure
+ to ``api/_lib/forge-failover.js``, so a 404 reference image was
+ re-dispatched to the next GPU lane, which fetched the same dead URL and
+ failed the same way. Naming the cause lets that decision be made honestly.
+
+The fix is the one the sibling TRELLIS worker already ships
+(``workers/model-trellis/request_policy.py``): retry the transient blips, and
+classify everything else as ``ImageSourceError`` so the worker hands the reason
+back verbatim instead of an error ref.
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+import time
+from typing import Callable, Optional
+from urllib.parse import urlsplit
+
+import httpx
+from PIL import Image
+
+from worker_security import UnsafeUrlError, fetch_remote_bytes
+
+# Seconds allowed for one attempt at one caller-supplied image URL.
+IMAGE_FETCH_TIMEOUT_S = 30.0
+
+# Total attempts (not extra retries) per URL, and the first backoff gap. Three
+# attempts at 1s then 2s cost at most a few seconds of an already-asynchronous
+# job and cover the single-blip read timeouts that were failing whole
+# generations against the public internet.
+FETCH_ATTEMPTS = 3
+FETCH_RETRY_BASE_SECONDS = 1.0
+
+# Upstream status codes worth a second try. Everything else (404, 403, 400) is
+# a statement about the URL itself and will fail identically on every attempt.
+_RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
+
+
+class ImageSourceError(ValueError):
+ """A caller-supplied image could not be read.
+
+ Distinct from an internal failure: the cause is the request's own ``images``
+ entry (unreachable host, rejected target, undecodable bytes), so the message
+ is safe and useful to hand back verbatim instead of an opaque error ref.
+ """
+
+
+def retry_delays(
+ attempts: int = FETCH_ATTEMPTS, base: float = FETCH_RETRY_BASE_SECONDS
+) -> list[float]:
+ """Exponential backoff gaps between attempts (one fewer than `attempts`)."""
+ return [base * (2 ** i) for i in range(max(0, attempts - 1))]
+
+
+def is_transient_fetch_error(exc: BaseException) -> bool:
+ """True when re-fetching the same URL could plausibly succeed.
+
+ Timeouts and connection-level failures are the blips this exists for. An
+ HTTP error is transient only for the status codes above; a 404 is not going
+ to become a 200 on the next attempt.
+ """
+ if isinstance(exc, httpx.HTTPStatusError):
+ return exc.response.status_code in _RETRYABLE_STATUS
+ return isinstance(
+ exc, (httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError)
+ )
+
+
+def call_with_retry(
+ fn: Callable[[], object],
+ *,
+ attempts: int = FETCH_ATTEMPTS,
+ should_retry: Callable[[BaseException], bool] = is_transient_fetch_error,
+ sleep: Callable[[float], None] = time.sleep,
+ on_retry: Optional[Callable[[int, float, BaseException], None]] = None,
+):
+ """Call `fn`, retrying with exponential backoff while `should_retry` holds.
+
+ Re-raises the last exception once the attempts are spent or the error is not
+ retryable. `sleep` is injected so the policy stays testable without wall
+ clock time; `on_retry` receives (attempt_number, delay, exception) for
+ logging.
+ """
+ delays = retry_delays(attempts)
+ last: BaseException
+ for index in range(max(1, attempts)):
+ try:
+ return fn()
+ except BaseException as exc: # noqa: BLE001 - re-raised below after the budget
+ last = exc
+ if index >= len(delays) or not should_retry(exc):
+ raise
+ delay = delays[index]
+ if on_retry:
+ on_retry(index + 1, delay, exc)
+ sleep(delay)
+ raise last
+
+
+def source_label(src: str) -> str:
+ """Short, non-leaking identifier for an image source, for error messages."""
+ if src.startswith("data:image"):
+ return "inline data uri"
+ host = urlsplit(src).hostname
+ return host or src[:60]
+
+
+def fetch_image_bytes(
+ src: str,
+ *,
+ timeout: float = IMAGE_FETCH_TIMEOUT_S,
+ sleep: Callable[[float], None] = time.sleep,
+ on_retry: Optional[Callable[[int, float, BaseException], None]] = None,
+) -> bytes:
+ """Fetch one https image source, retrying transient network failures.
+
+ The fetch itself stays SSRF-hardened by ``fetch_remote_bytes``: https-only,
+ private/loopback/link-local/metadata IPs rejected after DNS resolution,
+ redirects re-validated per hop, response size bounded. Every failure leaves
+ here as an ``ImageSourceError`` naming the host and the reason.
+ """
+ label = source_label(src)
+
+ def attempt() -> bytes:
+ return fetch_remote_bytes(src, timeout=timeout)
+
+ try:
+ return call_with_retry(attempt, sleep=sleep, on_retry=on_retry)
+ except UnsafeUrlError as exc:
+ raise ImageSourceError(f"refused to fetch image source ({label}): {exc}") from exc
+ except httpx.HTTPStatusError as exc:
+ raise ImageSourceError(
+ f"image source {label} returned HTTP {exc.response.status_code}"
+ ) from exc
+ except httpx.HTTPError as exc:
+ raise ImageSourceError(
+ f"image source {label} unreachable after {FETCH_ATTEMPTS} attempts "
+ f"({type(exc).__name__}); check the URL is publicly readable"
+ ) from exc
+ except ValueError as exc:
+ # The guard's own size ceiling. Caught after UnsafeUrlError (a ValueError
+ # subclass) so the more specific message wins.
+ raise ImageSourceError(f"image source {label} rejected: {exc}") from exc
+
+
+def open_image(data: bytes, mode: str, label: str) -> Image.Image:
+ try:
+ return Image.open(io.BytesIO(data)).convert(mode)
+ except Exception as exc: # noqa: BLE001 - undecodable caller input, not an internal fault
+ raise ImageSourceError(
+ f"image source {label} is not a decodable image ({type(exc).__name__})"
+ ) from exc
+
+
+def decode_image(
+ src: str,
+ *,
+ mode: str = "RGB",
+ timeout: float = IMAGE_FETCH_TIMEOUT_S,
+ sleep: Callable[[float], None] = time.sleep,
+ on_retry: Optional[Callable[[int, float, BaseException], None]] = None,
+) -> Image.Image:
+ """Turn one caller-supplied image source into a PIL image.
+
+ Accepts an inline ``data:image`` URI or an https URL. Raises
+ ``ImageSourceError`` (never a bare httpx/PIL exception) so the caller can
+ report the reason instead of an opaque internal error ref.
+ """
+ if src.startswith("data:image"):
+ parts = src.split(",", 1)
+ if len(parts) != 2:
+ raise ImageSourceError("inline data uri has no base64 payload")
+ try:
+ raw = base64.b64decode(parts[1])
+ except Exception as exc: # noqa: BLE001 - caller's own payload, report it as such
+ raise ImageSourceError(f"inline data uri is not valid base64: {exc}") from exc
+ return open_image(raw, mode, "inline data uri")
+ if src.startswith("https://"):
+ data = fetch_image_bytes(src, timeout=timeout, sleep=sleep, on_retry=on_retry)
+ return open_image(data, mode, source_label(src))
+ raise ImageSourceError(f"unsupported image source: {src[:60]}")
diff --git a/workers/model-hunyuan3d/main.py b/workers/model-hunyuan3d/main.py
index 9d86f7abf..a12e88223 100644
--- a/workers/model-hunyuan3d/main.py
+++ b/workers/model-hunyuan3d/main.py
@@ -30,7 +30,6 @@ Environment variables:
from __future__ import annotations
import asyncio
-import base64
import io
import json
import logging
@@ -48,12 +47,12 @@ from PIL import Image
from pydantic import BaseModel, Field
from worker_security import (
- UnsafeUrlError,
- fetch_remote_bytes,
require_api_key,
safe_error,
)
+from image_source import FETCH_ATTEMPTS, ImageSourceError, decode_image
+
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
@@ -317,18 +316,20 @@ def _require_api_key(authorization: str) -> None:
def _decode_image(src: str) -> Image.Image:
- if src.startswith("data:image"):
- b64 = src.split(",", 1)[1]
- return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")
- if src.startswith("https://"):
- # SSRF-hardened: https-only, private/loopback/link-local/metadata IPs
- # rejected after DNS resolution, redirects re-validated per hop, bounded.
- try:
- data = fetch_remote_bytes(src, timeout=30)
- except UnsafeUrlError as exc:
- raise ValueError(f"refused to fetch image source: {exc}") from exc
- return Image.open(io.BytesIO(data)).convert("RGB")
- raise ValueError(f"unsupported image source: {src[:60]}")
+ """Read one caller-supplied image, retrying transient fetch blips.
+
+ Every failure arrives as ImageSourceError so _run_inference can report the
+ real reason (a 404 reference image, an unreachable host) instead of an
+ opaque error ref that tells nobody anything. See image_source.py.
+ """
+
+ def note_retry(number: int, delay: float, exc: BaseException) -> None:
+ log.warning(
+ "image fetch attempt %d/%d failed (%s); retrying in %.1fs",
+ number, FETCH_ATTEMPTS, type(exc).__name__, delay,
+ )
+
+ return decode_image(src, on_retry=note_retry)
# Tier → generation budget for callers that speak forge tiers (the gcp
@@ -438,6 +439,17 @@ async def _run_inference(task_id: str, images: list[str], body_type: str, qualit
)
log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)
+ except ImageSourceError as exc:
+ # The request's own `images` entry is at fault, so hand the reason
+ # back verbatim: an opaque error ref would tell the caller nothing
+ # and leaves the router retrying a URL that can never work.
+ log.warning("[%s] image source rejected: %s", task_id, exc)
+ await _update_task(
+ task_id,
+ status="failed",
+ error=str(exc),
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
except Exception as exc:
await _update_task(
task_id,