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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(ops): economy watchdog — the platform now pages itself when the agent economy stalls
fudjia1149f518a49d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f79145b3..e26d7d4a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-05- **@three-ws/retarget — the animation engine behind every avatar, now a standalone package** — The rig-agnostic animation system that powers all three.ws avatars is now on npm as @three-ws/retarget. It maps bone names from Mixamo, VRM/VRoid, Avaturn, Daz, MakeHuman, Unreal, and Blender rigs onto one canonical skeleton, retargets any clip onto any humanoid with rest-pose and hip-axis correction, and ships the crossfading runtime that keeps characters from ever freezing in a T-pose. Only dependency: your own copy of Three.js. Same engine, same tests (2,800 lines of them) — now usable in any Three.js project. `[sdk, feature]`+- **The agent economy now watches itself and pages the team** — After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began. `[improvement, infra]`## 2026-07-04diff --git a/api/cron/uptime-check.js b/api/cron/uptime-check.jsindex 8bb9f06c3..43f0d8e79 100644--- a/api/cron/uptime-check.js+++ b/api/cron/uptime-check.js@@ -56,6 +56,25 @@ const DEGRADE_STREAK_TTL_S = 6 * 60 * 60;// Re-page a still-degraded subsystem every this many ticks (5-min cadence → ~1h).const RE_ESCALATE_EVERY_TICKS = 12;+// ── Agent-economy watchdog state ─────────────────────────────────────────────+// The July 2026 stall went undetected for ~9 hours because nothing watched the+// economy AS a system: the heartbeat can be dead, an engine can fail or skip on+// a fixable reason, or the public money feed can flat-line — each invisible from+// the surface probes above. This watchdog reads the heartbeat snapshot parked by+// api/cron/economy-tick.js plus the public pulse feed, and escalates through the+// same streak machinery as subsystems (page on first sight, re-page hourly while+// it persists, announce recovery).+const ECONOMY_TICK_KEY = 'economy:last-tick';+const ECONOMY_STREAK_KEY = 'uptime:economy:streak';+const ECONOMY_HISTORY_KEY = 'economy:history';+const ECONOMY_HISTORY_WINDOW = 288; // 24h at 5-min cadence+const ECONOMY_HEARTBEAT_DEAD_MS = 10 * 60_000; // heartbeat fires every minute; 10 min silent = scheduler dead+const PULSE_SILENT_MS = 90 * 60_000; // the money feed should never be quiet this long+// Skip reasons that mean "an operator must act", as opposed to benign cadence+// skips ("not due this minute"). Matched against each engine's own reason string.+const ACTIONABLE_REASON =+ /disabled|not_configured|not configured|unset|base58|undecodable|db_at_storage_cap|insufficient|sol_floor|settle_unaffordable|treasury|invalid|schema_failed|redis_unavailable|rpc_|escrow/i;+async function probe(target, origin) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);@@ -162,15 +181,116 @@ export default wrapCron(async (req, res) => {console.warn('[uptime-check] subsystem health gather failed:', err?.message || err);}+ // ── Agent-economy watchdog ────────────────────────────────────────────────+ let economy = null;+ try {+ economy = await watchEconomy(origin);+ } catch (err) {+ console.warn('[uptime-check] economy watchdog failed:', err?.message || err);+ }+const downCount = Object.values(results).filter((r) => !r.ok).length;return json(res, 200, {ok: downCount === 0 && (subsystems ? subsystems.status !== 'down' : true),down: downCount,results,subsystems: subsystems ? { status: subsystems.status, degraded: subsystems.degraded } : null,+ economy,});});+// ── Agent-economy watchdog ──────────────────────────────────────────────────+// Classify one heartbeat engine result as a problem string, or null if healthy.+// Exported for tests.+export function classifyEngine(e) {+ if (!e || typeof e !== 'object' || !e.label) return null;+ if (e.ok !== true) return `${e.label}: ${e.error || `HTTP ${e.status}`}`;+ const reason = typeof e.reason === 'string' ? e.reason : '';+ if (reason && ACTIONABLE_REASON.test(reason)) return `${e.label}: ${reason}`;+ return null;+}++// Watch the economy AS a system: heartbeat freshness, per-engine actionable+// failures, and public money-feed silence. Streak-gated escalation (page on+// first sight, re-page every RE_ESCALATE_EVERY_TICKS while it persists, one+// recovery note when clear) so a weeks-long stall can't hide behind a single+// deduped alert — and a 5-minute blip can't page all night.+async function watchEconomy(origin) {+ const problems = [];++ // 1. Heartbeat freshness — economy-tick fires every minute; silence means the+ // scheduler itself is broken and EVERY engine below is untrustworthy/stale.+ const tick = await cacheGet(ECONOMY_TICK_KEY);+ const tickAgeMs = tick?.t ? Date.now() - tick.t : Number.POSITIVE_INFINITY;+ const heartbeatDead = tickAgeMs > ECONOMY_HEARTBEAT_DEAD_MS;+ if (heartbeatDead) {+ problems.push(+ `heartbeat: last economy-tick ${Number.isFinite(tickAgeMs) ? `${Math.round(tickAgeMs / 60_000)} min ago` : 'never'} — scheduler not firing (see docs/economy-heartbeat.md)`,+ );+ }++ // 2. Per-engine actionable problems from the last heartbeat fan-out.+ if (!heartbeatDead && Array.isArray(tick?.engines)) {+ for (const e of tick.engines) {+ const problem = classifyEngine(e);+ if (problem) problems.push(problem);+ }+ }++ // 3. Money-feed silence — the end-to-end signal. Engines can all report+ // "ran" while producing nothing on-chain; the public feed is the truth.+ let lastEventAgeMs = null;+ try {+ const r = await fetch(`${origin}/api/pulse?limit=1`, {+ headers: { 'user-agent': 'threews-uptime/1.0' },+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ const body = await r.json();+ const ts = body?.data?.events?.[0]?.ts;+ if (ts) lastEventAgeMs = Date.now() - new Date(ts).getTime();+ } catch { /* feed probe failure is covered by the surface probes above */ }+ if (lastEventAgeMs != null && lastEventAgeMs > PULSE_SILENT_MS) {+ problems.push(`money-feed: no on-chain agent activity for ${Math.round(lastEventAgeMs / 3_600_000 * 10) / 10}h`);+ }++ // Streak-gated digest: one alert naming every current problem, not a page per+ // engine. Fingerprint on the problem KEYS (label part) so a reason's wording+ // changing doesn't re-page, but a new engine joining does.+ const keys = problems.map((p) => p.split(':')[0].trim()).sort();+ const prev = (await cacheGet(ECONOMY_STREAK_KEY)) || { keys: [], streak: 0 };+ const same = JSON.stringify(keys) === JSON.stringify(prev.keys);+ const streak = problems.length ? (same ? prev.streak + 1 : 1) : 0;++ if (problems.length && (streak === 1 || streak % RE_ESCALATE_EVERY_TICKS === 0)) {+ const ageNote = streak === 1 ? 'new' : `ongoing ~${Math.round((streak * 5) / 60 * 10) / 10}h`;+ sendOpsAlert(+ `ECONOMY: ${problems.length} engine problem${problems.length === 1 ? '' : 's'}`,+ `${problems.join('\n')}\n(${ageNote}) → https://three.ws/status`,+ { signature: `economy:digest:${keys.join(',')}:${Math.floor(streak / RE_ESCALATE_EVERY_TICKS)}` },+ );+ }+ if (!problems.length && prev.keys.length) {+ sendOpsAlert('RESOLVED: agent economy healthy', 'all engines running, money feed live', {+ signature: `economy:resolved:${Date.now()}`,+ });+ }+ await cacheSet(ECONOMY_STREAK_KEY, { keys, streak }, DEGRADE_STREAK_TTL_S);++ // 24h problem history so /status (and a debugging agent) can see WHEN a+ // stall started, not just that one exists now.+ const history = (await cacheGet(ECONOMY_HISTORY_KEY)) || [];+ history.push({+ t: Date.now(),+ problems: problems.length,+ heartbeatAgeS: Number.isFinite(tickAgeMs) ? Math.round(tickAgeMs / 1000) : null,+ lastEventAgeS: lastEventAgeMs != null ? Math.round(lastEventAgeMs / 1000) : null,+ });+ while (history.length > ECONOMY_HISTORY_WINDOW) history.shift();+ await cacheSet(ECONOMY_HISTORY_KEY, history, SNAPSHOTS_TTL_S);++ return { problems, streak, heartbeatDead, lastEventAgeMs };+}+// Config-drift + escalation digest. A subsystem that is degraded/down for the// first time pages immediately (deduped 1h by sendOpsAlert). One that *stays*// unhealthy re-pages every RE_ESCALATE_EVERY_TICKS so a half-armed ring or andiff --git a/api/status.js b/api/status.jsindex 42aac7a8e..139f3ca66 100644--- a/api/status.js+++ b/api/status.js@@ -54,7 +54,7 @@ export default wrap(async (req, res) => {const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const [snapshots, daily, subsystemsSnap, economySnap] = await Promise.all([+ const [snapshots, daily, subsystemsSnap, economySnap, economyHistory] = await Promise.all([cacheGet('uptime:snapshots'),cacheGet('uptime:daily'),// Parked by api/cron/uptime-check.js every 5 min. We read the cron's@@ -65,6 +65,9 @@ export default wrap(async (req, res) => {// heartbeat's last fan-out, per-engine ok/skip reason. null until the first// tick — and a STALE `t` here is itself the diagnosis (scheduler dead).cacheGet('economy:last-tick'),+ // Parked by the uptime-check economy watchdog every 5 min: 24h of problem+ // counts + heartbeat/feed ages, so a stall's START time is visible.+ cacheGet('economy:history'),]);const snaps = Array.isArray(snapshots) ? snapshots : [];const days = Array.isArray(daily) ? daily : [];@@ -214,6 +217,10 @@ export default wrap(async (req, res) => {...(e.reason ? { reason: e.reason } : {}),...(e.error ? { error: e.error } : {}),})),+ // 24h of watchdog samples (5-min cadence) — problem counts plus+ // heartbeat/feed ages, so a stall's onset is visible, not just+ // its present state. Written by the uptime-check watchdog.+ history: Array.isArray(economyHistory) ? economyHistory : [],}: null,},diff --git a/data/changelog.json b/data/changelog.jsonindex b1185c7bb..ffdb24504 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-05",+ "title": "The agent economy now watches itself and pages the team",+ "summary": "After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began.",+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-07-05","title": "@three-ws/retarget — the animation engine behind every avatar, now a standalone package",diff --git a/docs/economy-heartbeat.md b/docs/economy-heartbeat.mdindex c648af728..346643512 100644--- a/docs/economy-heartbeat.md+++ b/docs/economy-heartbeat.md@@ -95,6 +95,29 @@ curl -s https://three.ws/api/status | jq .economyThe same data renders as the **Agent economy heartbeat** section on[/status](https://three.ws/status).+### The watchdog — you get paged, not surprised++The uptime cron ([api/cron/uptime-check.js](../api/cron/uptime-check.js), every+5 minutes) watches the economy as a system and escalates to the ops Telegram+channel (`TELEGRAM_BOT_TOKEN` + `TELEGRAM_ALERTS_CHAT_ID` — alerts silently+no-op if unset, so set them):++- **Heartbeat dead** — no economy-tick for 10+ minutes (the scheduler itself is+ broken; this was invisible for ~9 hours in the July 2026 stall).+- **Engine problems** — any engine failing (404/5xx/timeout) or skipping on an+ actionable reason (`disabled`, key parse failures, `db_at_storage_cap`,+ funding floors, `settle_unaffordable`, treasury-low, invalid config).+- **Money-feed silence** — no on-chain agent activity on `/api/pulse` for 90++ minutes, the end-to-end signal that catches anything the per-engine checks+ miss.++Escalation is streak-gated like the subsystem digest: page on first sight,+re-page hourly while the problem persists (so a stall can't hide behind one+deduped alert), and a single "RESOLVED" note when the economy is healthy again.+The watchdog also parks 24 hours of samples in `economy:history` — surfaced as+`economy.history` in `/api/status` — so you can see **when** a stall started,+not just that one exists.+## Manual / one-off```bashdiff --git a/public/changelog.json b/public/changelog.jsonindex b75351df0..26a6a0088 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-05T04:26:17.161Z",+ "generated_at": "2026-07-05T04:31:12.739Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -17,6 +17,17 @@"feature"]},+ {+ "date": "2026-07-05",+ "type": "update",+ "title": "The agent economy now watches itself and pages the team",+ "summary": "After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began.",+ "link": null,+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-07-04","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 0a92c7163..9b36c887e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>sdk</category><description>The rig-agnostic animation system that powers all three.ws avatars is now on npm as @three-ws/retarget. It maps bone names from Mixamo, VRM/VRoid, Avaturn, Daz, MakeHuman, Unreal, and Blender rigs onto one canonical skeleton, retargets any clip onto any humanoid with rest-pose and hip-axis correction, and ships the crossfading runtime that keeps characters from ever freezing in a T-pose. Only dependency: your own copy of Three.js. Same engine, same tests (2,800 lines of them) — now usable in any Three.js project.</description></item>+ <item>+ <title>The agent economy now watches itself and pages the team</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-05:The agent economy now watches itself and pages the team</guid>+ <pubDate>Sun, 05 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began.</description>+ </item><item><title>Markets — Live Crypto Prices</title><link>https://three.ws/coins</link>diff --git a/public/features.json b/public/features.jsonindex ba8f71722..8f33be789 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-05T04:26:17.149Z",+ "generated_at": "2026-07-05T04:31:12.727Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/economy-watchdog.test.js b/tests/economy-watchdog.test.jsnew file mode 100644index 000000000..2f8b2afb5--- /dev/null+++ b/tests/economy-watchdog.test.js@@ -0,0 +1,44 @@+import { describe, it, expect } from 'vitest';++import { classifyEngine } from '../api/cron/uptime-check.js';++// The economy watchdog's judgment call: which heartbeat engine results page an+// operator, and which are benign cadence skips. Getting this wrong either+// hides a weeks-long stall (July 2026) or pages all night for nothing.++describe('economy watchdog — classifyEngine', () => {+ it('a hard failure always pages (404 route gap, timeout, 5xx)', () => {+ expect(classifyEngine({ label: 'buyback', ok: false, status: 404 })).toBe('buyback: HTTP 404');+ expect(classifyEngine({ label: 'dca', ok: false, status: 0, error: 'timeout' })).toBe('dca: timeout');+ expect(classifyEngine({ label: 'launcher', ok: false, status: 500 })).toBe('launcher: HTTP 500');+ });++ it('actionable skip reasons page: misconfig, funding, storage, key parsing', () => {+ for (const reason of [+ 'disabled',+ 'Non-base58 character',+ 'x402 pay: seed keypair undecodable — X402_SEED_SOLANA_SECRET_BASE58 must be 64 bytes as base58, base64, or a JSON array of 64 ints',+ 'db_at_storage_cap',+ 'insufficient_payer_usdc',+ 'sponsor_sol_floor',+ 'settle_unaffordable',+ 'treasury balance 0.0100 SOL too low to fund 0.0300 SOL',+ 'ring_config_invalid',+ 'redis_unavailable: connect ETIMEDOUT',+ ]) {+ expect(classifyEngine({ label: 'ring-tick', ok: true, skipped: true, reason }), reason).toBeTruthy();+ }+ });++ it('benign cadence skips stay quiet', () => {+ expect(classifyEngine({ label: 'buyback', ok: true, skipped: true, reason: 'not_due' })).toBeNull();+ expect(classifyEngine({ label: 'buyback', ok: true, skipped: true, reason: 'already_ran_today' })).toBeNull();+ expect(classifyEngine({ label: 'pulse', ok: true, skipped: true })).toBeNull();+ expect(classifyEngine({ label: 'ring-tick', ok: true, status: 200 })).toBeNull();+ });++ it('tolerates malformed entries', () => {+ expect(classifyEngine(null)).toBeNull();+ expect(classifyEngine({})).toBeNull();+ });+});