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(okx-chat-bot): keep a missing daemon binary from taking the whole host down

nirholase7f44ecbbbdb
diff --git a/tests/okx-chat-bot.test.js b/tests/okx-chat-bot.test.js
index fcd2a20c9..a4e7789f8 100644
--- a/tests/okx-chat-bot.test.js
+++ b/tests/okx-chat-bot.test.js
@@ -8,11 +8,19 @@
//
// Pure logic only: no daemon, no wallet, no network, no DB.
-import { describe, it, expect } from 'vitest';
+import http from 'node:http';
+import { existsSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterAll, describe, it, expect, vi } from 'vitest';
import { classify, loginInstructions } from '../workers/okx-chat-bot/session.js';
import { resolveProvider, loadConfig, paths } from '../workers/okx-chat-bot/config.js';
+import { createHealthHandler } from '../workers/okx-chat-bot/health-server.js';
+import { createSupervisor } from '../workers/okx-chat-bot/supervisor.js';
import { STATE_ROOTS, STATE_EXCLUDES } from '../workers/okx-chat-bot/state.js';
-import { SKILLS } from '../workers/okx-chat-bot/workspace.js';
+import { SKILLS, buildWorkspace } from '../workers/okx-chat-bot/workspace.js';
import { classifyOkxChatBotBeat } from '../api/_lib/ops/subsystem-health.js';
import { buildChatBriefing } from '../api/_lib/okx-chat-briefing.js';
import { OKX_CATALOG } from '../api/_lib/okx-catalog.js';
@@ -138,6 +146,23 @@ describe('okx-chat-bot state contract', () => {
expect(STATE_EXCLUDES).toContain('.okx-agent-task/logs');
});
+ // The heartbeat runs on its own timer, not at the end of a probe. A probe is
+ // bounded at 15s + 30s + 90s of CLI calls, which can outlast the freshness
+ // window classifyOkxChatBotBeat judges this host by, so a beat tied to the
+ // probe would let one slow CLI call read as "the host is gone".
+ it('beats well inside the window /api/healthz calls a host stale', () => {
+ const cfg = loadConfig({});
+ const now = Date.parse('2026-08-02T12:00:00Z');
+ const beat = {
+ mode: cfg.provider,
+ last_beat_at: new Date(now - cfg.heartbeatMs).toISOString(),
+ meta: { health: 'ok', activeClients: 1 },
+ };
+ expect(classifyOkxChatBotBeat(beat, now).status).toBe('ok');
+ // And a beat one full worst-case probe old must NOT be what keeps it green.
+ expect(cfg.heartbeatMs).toBeLessThan(135_000);
+ });
+
it('roots every CLI path at the configured HOME so a restore is what the daemon reads', () => {
const cfg = loadConfig({ OKX_BOT_HOME: '/state' });
const p = paths(cfg);
@@ -191,6 +216,145 @@ describe('okx-chat-bot chat briefing', () => {
});
});
+// Smoke tests: the core path end to end, over real HTTP and a real filesystem.
+// Still no daemon, wallet, or network, because neither of those two paths needs
+// one: the verdicts are produced by the real classifier and the workspace is
+// staged from the real repo.
+describe('okx-chat-bot health surface (smoke)', () => {
+ const cfg = loadConfig({ OKX_BOT_HOME: '/state', ANTHROPIC_API_KEY: 'sk-ant-smoke' });
+ const stats = () => ({ restarts: 0, pid: 4242, uptimeMs: 1000 });
+
+ /** Serve one `live` record on an ephemeral port and read a path off it. */
+ async function get(live, path) {
+ const server = http.createServer(createHealthHandler(cfg, live, stats, '2026-08-11T00:00:00.000Z'));
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const { port } = /** @type {import('node:net').AddressInfo} */ (server.address());
+ const resp = await fetch(`http://127.0.0.1:${port}${path}`);
+ return { status: resp.status, body: await resp.json() };
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+ }
+
+ const liveRecord = (probe, login = null) => ({
+ verdict: classify(probe),
+ checkedAt: Date.now(),
+ daemon: probe.daemon,
+ wallet: probe.wallet,
+ agents: probe.agents,
+ login,
+ workspace: { briefingBytes: 4096, skills: SKILLS.length },
+ stateRestore: 'restored',
+ });
+
+ it('answers /readyz 200 only when a buyer message can actually land', async () => {
+ const r = await get(liveRecord(ONLINE), '/readyz');
+ expect(r.status).toBe(200);
+ expect(r.body.health.ready).toBe(true);
+ expect(r.body.agents.activeClients).toBe(1);
+ });
+
+ // The defining false-green: process alive, session dead, chat silently lost.
+ it('answers /readyz 503 for a live host whose session expired', async () => {
+ const live = liveRecord(
+ { ...ONLINE, wallet: { loggedIn: false }, agents: { agentCount: 0, activeClients: 0 } },
+ { loginUrl: 'https://web3.okx.com/account/sociallogin?authSessionId=smoke', authSessionId: 'smoke' },
+ );
+ const r = await get(live, '/readyz');
+ expect(r.status).toBe(503);
+ expect(r.body.health.reason).toBe('session_logged_out');
+ // The remedy travels with the status, so the fix is not in a runbook.
+ expect(r.body.remedy.join('\n')).toContain('authSessionId=smoke');
+ expect(r.body.remedy.join('\n')).toContain('--session-id smoke');
+ });
+
+ // Cloud Run's startup probe reads /healthz. It must never restart the
+ // container for a logged-out session: a restart cannot renew an OTP, and the
+ // loop would destroy the state snapshot cadence.
+ it('keeps /healthz at 200 even while readiness is refused', async () => {
+ const live = liveRecord({ ...ONLINE, wallet: { loggedIn: false }, agents: { agentCount: 0, activeClients: 0 } });
+ const r = await get(live, '/healthz');
+ expect(r.status).toBe(200);
+ expect(r.body.ok).toBe(true);
+ expect(r.body.health.ready).toBe(false);
+ });
+
+ it('omits the remedy when no human is needed', async () => {
+ const r = await get(liveRecord(ONLINE), '/healthz');
+ expect(r.body.remedy).toBeUndefined();
+ });
+});
+
+describe('okx-chat-bot workspace staging (smoke)', () => {
+ const repoRoot = fileURLToPath(new URL('..', import.meta.url));
+ const homes = [];
+ afterAll(async () => {
+ for (const home of homes) await rm(home, { recursive: true, force: true });
+ });
+
+ it('stages the briefing and every skill the subsession answers from', async () => {
+ const home = await mkdtemp(join(tmpdir(), 'okx-bot-workspace-'));
+ homes.push(home);
+ const cfg = loadConfig({ OKX_BOT_HOME: home, OKX_BOT_REPO_ROOT: repoRoot });
+ const result = await buildWorkspace(cfg, paths(cfg));
+
+ expect(result.skills).toBe(SKILLS.length);
+ expect(result.briefingBytes).toBeGreaterThan(0);
+ // Both names, because which one the subsession reads depends on which AI
+ // CLI the adapter spawns.
+ for (const name of ['CLAUDE.md', 'AGENTS.md']) {
+ expect(existsSync(join(home, '.okx-agent-task', 'workspace', name))).toBe(true);
+ }
+ for (const dir of ['.claude', '.codex']) {
+ for (const skill of SKILLS) {
+ expect(existsSync(join(home, '.okx-agent-task', 'workspace', dir, 'skills', skill, 'SKILL.md'))).toBe(true);
+ }
+ }
+ });
+
+ // Skills are copied, not symlinked: a link into the image survives locally but
+ // points at a path the subsession may not be allowed to traverse.
+ it('rebuilds cleanly over an existing workspace, so a redeploy is idempotent', async () => {
+ const home = await mkdtemp(join(tmpdir(), 'okx-bot-workspace-'));
+ homes.push(home);
+ const cfg = loadConfig({ OKX_BOT_HOME: home, OKX_BOT_REPO_ROOT: repoRoot });
+ const p = paths(cfg);
+ const first = await buildWorkspace(cfg, p);
+ const second = await buildWorkspace(cfg, p);
+ expect(second).toEqual(first);
+ });
+});
+
+describe('okx-chat-bot daemon supervision (smoke)', () => {
+ // A daemon binary that is not on PATH raises 'error', not just 'exit'. With no
+ // listener that is an unhandled event: it throws and takes the whole worker
+ // down, so "the daemon is missing" would surface as "the host is gone" and the
+ // health verdict, heartbeat and alert that name the real problem never fire.
+ it('survives a daemon binary that cannot be spawned and keeps restarting it', async () => {
+ const home = await mkdtemp(join(tmpdir(), 'okx-bot-supervisor-'));
+ const cfg = loadConfig({
+ OKX_BOT_HOME: home,
+ OKX_BOT_DAEMON_BIN: 'okx-a2a-binary-that-does-not-exist',
+ OKX_BOT_RESTART_BASE_MS: '20',
+ OKX_BOT_RESTART_MAX_MS: '40',
+ });
+ const supervisor = createSupervisor(cfg, paths(cfg));
+ try {
+ supervisor.start();
+ await vi.waitFor(() => expect(supervisor.stats().restarts).toBeGreaterThanOrEqual(2), {
+ timeout: 5_000,
+ interval: 25,
+ });
+ // The process is still here to report it, which is the whole point.
+ expect(classify({ daemon: 'stopped', wallet: null, agents: { agentCount: 0, activeClients: 0 }, providerCredentialed: true }).reason).toBe('daemon_down');
+ } finally {
+ await supervisor.stop(1_000);
+ await rm(home, { recursive: true, force: true });
+ }
+ });
+});
+
describe('okx_chat_bot subsystem health', () => {
const now = Date.parse('2026-08-02T12:00:00Z');
const beat = (ageMs, meta = {}) => ({
diff --git a/workers/okx-chat-bot/README.md b/workers/okx-chat-bot/README.md
index 3b4470232..84e890c8c 100644
--- a/workers/okx-chat-bot/README.md
+++ b/workers/okx-chat-bot/README.md
@@ -43,16 +43,17 @@ testable without a daemon, a wallet, or a network.
| File | Role |
|------|------|
-| `index.js` | Entrypoint. Boot order, health server, session probe, heartbeat, ops alerts, graceful shutdown. |
+| `index.js` | Entrypoint. Boot order, session probe, heartbeat, ops alerts, graceful shutdown. |
| `config.js` | Env-driven config (`loadConfig`, `paths`) and AI-provider selection (`resolveProvider`). |
| `cli.js` | Timeout-bounded, non-throwing wrappers around the `okx-a2a` and `onchainos` binaries. |
| `session.js` | Pure health `classify()` plus `loginInstructions()`, the exact commands a human runs. |
+| `health-server.js` | The HTTP surface: strict `/readyz`, always-200 liveness, and the `remedy` payload. |
| `state.js` | Tar the wallet/XMTP identity to GCS and restore it on boot (`snapshotState`, `restoreState`). |
| `supervisor.js` | Owns the `okx-a2a run` child with capped exponential backoff restarts. |
| `workspace.js` | Rebuilds the AI subsession's briefing and skills from the image on every boot. |
| `log.js` | Structured JSON lines for Cloud Logging. |
-### Three things that are load-bearing
+### Four things that are load-bearing
**The daemon runs in the foreground, never via `daemon start`.** `okx-a2a daemon
start` delegates to an OS autostart unit (systemd/launchd). There is no systemd
@@ -69,6 +70,14 @@ is in-memory and dies with the revision, so `state.js` tars both trees to one
GCS object and restores it on boot. Without that, every deploy would log the bot
out and need a fresh human OTP.
+**A daemon that cannot be spawned must not take the host with it.** A missing or
+unrunnable `okx-a2a` binary raises `error` on the child, not just `exit`. Node
+throws on an unhandled `error` event, so without a listener the whole worker dies
+and "the daemon binary is missing" surfaces as "the host is gone": no health
+verdict, no heartbeat, no alert naming the real problem. `supervisor.js` handles
+both events through one restart path, and a spawn that raises both never
+schedules two restarts.
+
**The AI workspace is rebuilt from the image, not from the snapshot.** The
adapter spawns the AI CLI with cwd set to `~/.okx-agent-task/workspace`, and
whatever is in that directory **is** the subsession's world knowledge. A naive
@@ -91,7 +100,8 @@ locally with no code change. Defaults are the production posture.
| `OKX_BOT_STATE_OBJECT` | `okx-chat-bot/state.tar.gz` | Object name within that bucket. |
| `OKX_BOT_REPO_ROOT` | `/app` | Where the briefing and skills are read from. |
| `OKX_BOT_AI_PROVIDER` | auto | Pin the provider (`claude`, `codex`, `hermes`, `openclaw`). |
-| `OKX_BOT_HEARTBEAT_MS` | `30000` | Heartbeat cadence. |
+| `OKX_BOT_DAEMON_BIN` | `okx-a2a` | The XMTP daemon binary the supervisor owns. |
+| `OKX_BOT_HEARTBEAT_MS` | `30000` | How often the `bot_heartbeat` row is written. Its own timer, not the probe's. |
| `OKX_BOT_SESSION_PROBE_MS` | `60000` | How often health is re-probed. |
| `OKX_BOT_SNAPSHOT_MS` | `300000` | Periodic state snapshot cadence. |
| `OKX_BOT_ALERT_REPEAT_MS` | `21600000` | Re-alert ceiling while a bad state persists (6 h). |
@@ -149,12 +159,19 @@ someone has to go find.
## Deploying
+**Status: built and tested, not yet deployed.** There is no `okx-chat-bot`
+Cloud Run service in `aerial-vehicle-466722-p5` yet, and the one-time setup
+below has not been run: neither `gs://three-ws-okx-bot-state` nor the
+`okx-chat-bot-database-url` and `anthropic-api-key` secrets exist. Deploys are
+owner-gated, so the three setup commands and the build submit below are the
+whole remaining path. Until they run, the bot is hosted wherever it was last
+started by hand and `/api/healthz` reports `okx_chat_bot` as `unknown`.
+
The service must run `--min-instances=1 --max-instances=1`. This is not a
capacity choice: the GCS snapshot has exactly one writer, and concurrent
revisions would interleave snapshots and corrupt the identity.
-Production deploys are owner-gated, so everything is pre-staged and shipping is
-one command:
+Shipping is one command once the setup below exists:
```bash
gcloud builds submit --config workers/okx-chat-bot/cloudbuild.yaml \
@@ -170,14 +187,23 @@ required. The bucket and secret commands are at the top of
Cloud Run's startup probe is wired to `/healthz` and deliberately **not** to
`/readyz`, for the same reason liveness is always-200.
-One-time setup:
+One-time setup (none of it has run yet; the exact commands are at the top of
+[cloudbuild.yaml](cloudbuild.yaml)):
1. Create the state bucket and grant the runtime service account
`roles/storage.objectAdmin` on it.
-2. Set `OKX_BOT_STATE_BUCKET`, `DATABASE_URL`, and an AI-provider key
- (`ANTHROPIC_API_KEY` preferred) on the service.
+2. Create the `okx-chat-bot-database-url` and `anthropic-api-key` secrets and
+ grant the runtime service account `roles/secretmanager.secretAccessor` on
+ both. The deploy step wires them by name and **fails if either is missing**,
+ which is deliberate: a bot with no AI credential receives buyer chat and
+ never answers it. `OKX_BOT_STATE_BUCKET` needs no manual step, the deploy
+ sets it.
3. Confirm the image has both CLIs installed and the repo at `OKX_BOT_REPO_ROOT`.
+Never patch the AI key onto the service by hand. `--set-secrets` in the deploy
+step replaces the whole secret set, so a hand-added key survives exactly until
+the next deploy and then vanishes without a single error line.
+
The first boot logs `no state snapshot yet: first boot for this bucket` and
comes up logged out, which pages a human to complete the initial OTP as
`[email protected]`. Every boot after that restores the session.
@@ -201,7 +227,11 @@ curl -s https://three.ws/api/healthz \
```
A host that stops beating reads as `down` rather than silently vanishing, which
-is the whole point: a dead host cannot report that it is dead.
+is the whole point: a dead host cannot report that it is dead. The beat runs on
+its own timer (`OKX_BOT_HEARTBEAT_MS`) rather than at the end of a probe,
+because a probe is bounded at 15s + 30s + 90s of CLI calls and can outlast the
+two-minute freshness window `/api/healthz` judges the host by. One slow wallet
+call must not read as "the host is gone".
What a human has to do, read off the service itself:
diff --git a/workers/okx-chat-bot/cloudbuild.yaml b/workers/okx-chat-bot/cloudbuild.yaml
index 58788d944..d00e63301 100644
--- a/workers/okx-chat-bot/cloudbuild.yaml
+++ b/workers/okx-chat-bot/cloudbuild.yaml
@@ -93,7 +93,14 @@ steps:
- --no-allow-unauthenticated
- --service-account=three-ws@$PROJECT_ID.iam.gserviceaccount.com
- --set-env-vars=NODE_ENV=production,OKX_BOT_HOME=/state,OKX_BOT_REPO_ROOT=/app,OKX_BOT_AGENT_ID=2632,OKX_BOT_STATE_BUCKET=${_STATE_BUCKET}
- - --set-secrets=DATABASE_URL=okx-chat-bot-database-url:latest
+ # The AI-provider key belongs HERE, not patched on after the deploy:
+ # --set-secrets replaces the whole secret set, so a key added by hand would
+ # be silently stripped by the next deploy. The bot would then receive buyer
+ # chat and never answer it, which is the exact failure this worker exists to
+ # kill. A missing secret failing the deploy loudly is the better trade.
+ # Switching the provider to codex means swapping BOTH the variable name and
+ # the secret here (see workers/okx-chat-bot/config.js).
+ - --set-secrets=DATABASE_URL=okx-chat-bot-database-url:latest,ANTHROPIC_API_KEY=anthropic-api-key:latest
# Liveness only. Readiness is deliberately NOT wired to Cloud Run: a
# logged-out session fails /readyz and no restart can fix it, so probing it
# here would put the service in a crash loop instead of paging a human.
diff --git a/workers/okx-chat-bot/config.js b/workers/okx-chat-bot/config.js
index bdc95e1e2..21bce85a1 100644
--- a/workers/okx-chat-bot/config.js
+++ b/workers/okx-chat-bot/config.js
@@ -60,6 +60,11 @@ export function loadConfig(env = process.env) {
agentId: env.OKX_BOT_AGENT_ID || '2632',
+ // The XMTP daemon binary the supervisor owns. Overridable so a host that
+ // installed it under a different name (or a test that needs a spawn to
+ // fail) does not have to patch the supervisor.
+ daemonBin: env.OKX_BOT_DAEMON_BIN || 'okx-a2a',
+
// Durable state. Cloud Run's filesystem is in-memory and dies with the
// revision, so the tree above is tarred to GCS and restored on boot.
// Unset bucket = ephemeral mode (local dev, or a host with a real disk).
diff --git a/workers/okx-chat-bot/supervisor.js b/workers/okx-chat-bot/supervisor.js
index e33518568..0a1f01dc5 100644
--- a/workers/okx-chat-bot/supervisor.js
+++ b/workers/okx-chat-bot/supervisor.js
@@ -26,7 +26,7 @@ export function createSupervisor(cfg, p) {
function spawnDaemon() {
if (stopping) return;
rmSync(p.lock, { force: true, recursive: true });
- child = spawn('okx-a2a', ['run'], {
+ child = spawn(cfg.daemonBin, ['run'], {
env: cliEnv(cfg),
cwd: cfg.home,
stdio: ['ignore', 'pipe', 'pipe'],
@@ -42,10 +42,15 @@ export function createSupervisor(cfg, p) {
if (line.trim()) log[level]('daemon', { line: line.slice(0, 2000) });
}
};
- child.stdout.on('data', forward('info'));
- child.stderr.on('data', forward('warn'));
+ child.stdout?.on('data', forward('info'));
+ child.stderr?.on('data', forward('warn'));
- child.on('exit', (code, signal) => {
+ // One spawn can raise both 'error' and 'exit' (a binary missing from PATH
+ // does exactly that), and each must schedule at most one restart.
+ let settled = false;
+ const daemonDied = (detail) => {
+ if (settled) return;
+ settled = true;
const aliveMs = Date.now() - startedAt;
child = null;
if (stopping) return;
@@ -55,10 +60,17 @@ export function createSupervisor(cfg, p) {
// immediately is a config fault and must back off, or the restart loop
// buries the real error under thousands of log lines.
backoffMs = aliveMs > 60_000 ? cfg.restartBaseMs : Math.min(backoffMs * 2, cfg.restartMaxMs);
- log.error('daemon exited', { code, signal, aliveMs, restarts, restartInMs: backoffMs });
+ log.error('daemon exited', { ...detail, aliveMs, restarts, restartInMs: backoffMs });
timer = setTimeout(spawnDaemon, backoffMs);
if (typeof timer.unref === 'function') timer.unref();
- });
+ };
+
+ // Without this listener a spawn failure is an unhandled 'error' event, which
+ // throws and takes the whole worker down. That turns "the daemon binary is
+ // missing" into "the host is gone", losing the health verdict, the heartbeat
+ // and the alert that would have named the real problem.
+ child.on('error', (err) => daemonDied({ code: err?.code ?? null, signal: null, spawnError: err?.message }));
+ child.on('exit', (code, signal) => daemonDied({ code, signal }));
}
return {