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
chore: sync working tree
nirholasa5ae36bb9c9a
diff --git a/api/_lib/bundle-pricing.js b/api/_lib/bundle-pricing.jsindex b1f659147..4435132b8 100644--- a/api/_lib/bundle-pricing.js+++ b/api/_lib/bundle-pricing.js@@ -18,24 +18,67 @@* Amounts are ATOMIC integers throughout (the currency's smallest unit). Mixing* atomic and whole-token numbers is the classic way to publish a price 10^6 off,* so nothing here ever divides by decimals; formatting is the caller's job.+ *+ * Every amount is carried as a BigInt, and every amount that leaves this module+ * leaves as a decimal string. A 9-decimal mint puts real balances past+ * Number.MAX_SAFE_INTEGER (9007199254740991 atomic units is about 9,007,199+ * whole tokens), and the sums here are larger than the individual amounts. Doing+ * the arithmetic in Number and stringifying the result afterwards looks safe and+ * is not: the rounding has already happened by then. The database agrees, which+ * is why api/agents/[id]/bundles.js casts every SUM to ::text.*//** Discount below this reads as a rounding artifact rather than an offer. */export const MIN_MEANINGFUL_DISCOUNT_PERCENT = 1;+/**+ * Fallback discount when there is no history to learn from, as an exact ratio.+ * The float below is derived from these two so the two spellings cannot drift.+ */+export const DEFAULT_DISCOUNT_NUMERATOR = 8n;+export const DEFAULT_DISCOUNT_DENOMINATOR = 10n;+/** Fallback discount when there is no history to learn from. */-export const DEFAULT_DISCOUNT = 0.8;+export const DEFAULT_DISCOUNT = Number(DEFAULT_DISCOUNT_NUMERATOR) / Number(DEFAULT_DISCOUNT_DENOMINATOR);++/**+ * Coerce one atomic amount to a BigInt.+ *+ * Accepts a BigInt, a decimal string, or a Number that is an exact integer. A+ * Number past Number.MAX_SAFE_INTEGER THROWS rather than converting, because by+ * the time such a value reaches here it has already been rounded and no+ * downstream string can recover the lost digits. Callers reading money out of+ * the database pass the ::text column, not Number(column).+ *+ * @param {bigint|number|string} v+ * @returns {bigint}+ */+export function toAtomic(v) {+ if (typeof v === 'bigint') return v;+ if (typeof v === 'number') {+ if (!Number.isSafeInteger(v))+ throw new TypeError(`atomic amount ${v} is not an exact integer; pass a string or a BigInt`);+ return BigInt(v);+ }+ if (typeof v === 'string' && /^-?\d+$/.test(v.trim())) return BigInt(v.trim());+ throw new TypeError(`atomic amount ${JSON.stringify(v)} is not an integer`);+}++/** Half-up division that stays exact: no float ever touches the amount. */+function divRoundHalfUp(numerator, denominator) {+ return (numerator + denominator / 2n) / denominator;+}/*** Median of an integer list, rounded to an integer so it stays a spendable price.- * @param {number[]} sorted ascending- * @returns {number|null} null for an empty list+ * @param {(bigint|number|string)[]} sorted ascending+ * @returns {bigint|null} null for an empty list*/export function median(sorted) {const n = sorted.length;if (!n) return null;- if (n % 2) return sorted[(n - 1) / 2];- return Math.round((sorted[n / 2 - 1] + sorted[n / 2]) / 2);+ if (n % 2) return toAtomic(sorted[(n - 1) / 2]);+ return divRoundHalfUp(toAtomic(sorted[n / 2 - 1]) + toAtomic(sorted[n / 2]), 2n);}/**diff --git a/api/_lib/secret-box.js b/api/_lib/secret-box.jsindex 8a78ae878..599f7e41d 100644--- a/api/_lib/secret-box.js+++ b/api/_lib/secret-box.js@@ -66,6 +66,47 @@ function walletMasterSecret() {return env.JWT_SECRET;}+// Retired encryption keys, newest first, from WALLET_ENCRYPTION_KEY_PREVIOUS+// (comma or whitespace separated so several rotations can stack).+//+// Why this exists: a WALLET_ENCRYPTION_KEY rotation used to be a one-way door.+// The Vercel to Cloud Run migration (2026-07) changed the key with no read path+// back to the old one, and every ciphertext written under the retired key became+// permanently unopenable. That is not a degraded mode, it is destroyed custody:+// the wallet's SOL stays visible on chain and can never be signed for again.+// Measured 2026-08-01 by scripts/audit-custodial-key-health.mjs: 8 of 565+// custodial wallets, holding 0.49 SOL, of which 0.35 SOL belongs to CUSTOMERS+// who can no longer withdraw it.+//+// Decrypt therefore accepts retired keys; encrypt never does (see encryptSecret),+// so a rotation upgrades records as they are rewritten and old keys can be+// dropped from the list once nothing opens with them.+function retiredSecrets() {+ return String(env.WALLET_ENCRYPTION_KEY_PREVIOUS || '')+ .split(/[\s,]+/)+ .map((s) => s.trim())+ .filter((s) => s.length >= 16);+}++/**+ * Every secret a decrypt may try, in priority order: the current dedicated key,+ * then retired keys newest-first, then JWT_SECRET (v2 records written before a+ * dedicated key existed used it, and v1 records always did).+ *+ * Exported so a key-health audit can report WHICH key opened a record without+ * re-deriving this precedence and drifting from it.+ *+ * @returns {string[]} deduped, non-empty candidates+ */+export function secretBoxKeyCandidates() {+ const candidates = [];+ try { candidates.push(walletMasterSecret()); } catch { /* prod w/o dedicated key: retired + JWT below */ }+ candidates.push(...retiredSecrets());+ const jwt = env.JWT_SECRET;+ if (jwt) candidates.push(jwt);+ return [...new Set(candidates.filter(Boolean))];+}+// Derive an AES-256 key from a secret + salt via HKDF-SHA256.async function deriveKey(secret, salt) {const raw = new TextEncoder().encode(secret);@@ -109,10 +150,7 @@ export async function decryptSecret(ciphertext) {// real dedicated key in production, so NEW writes stay independent of JWT_SECRET.// Retire the fallback after a re-encryption migration lifts every record to the// dedicated key.- const candidates = [];- try { candidates.push(walletMasterSecret()); } catch { /* prod w/o dedicated key — JWT_SECRET below */ }- const jwt = env.JWT_SECRET;- if (jwt && !candidates.includes(jwt)) candidates.push(jwt);+ const candidates = secretBoxKeyCandidates();let lastErr;for (const secret of candidates) {try {@@ -123,13 +161,21 @@ export async function decryptSecret(ciphertext) {}throw lastErr || new Error('[secret-box] v2 decrypt failed: no candidate key available');}- // Legacy v1: JWT_SECRET + constant salt, no version tag.+ // Legacy v1: constant salt, no version tag. v1 always derived from JWT_SECRET,+ // but a retired JWT_SECRET strands v1 records exactly the way a retired+ // WALLET_ENCRYPTION_KEY strands v2 ones, so the same candidate list applies.const raw = Buffer.from(ciphertext, 'base64');const iv = raw.subarray(0, 12);const ct = raw.subarray(12);- const key = await deriveKey(env.JWT_SECRET, LEGACY_SALT);- const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);- return new TextDecoder().decode(plain);+ let lastErr;+ for (const secret of secretBoxKeyCandidates()) {+ try {+ const key = await deriveKey(secret, LEGACY_SALT);+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);+ return new TextDecoder().decode(plain);+ } catch (e) { lastErr = e; }+ }+ throw lastErr || new Error('[secret-box] v1 decrypt failed: no candidate key available');}/** True if a stored value is a v2 ciphertext (vs a legacy plaintext/base64 blob). */diff --git a/api/_lib/trade-card.js b/api/_lib/trade-card.jsindex c72322dc2..04fe38367 100644--- a/api/_lib/trade-card.js+++ b/api/_lib/trade-card.js@@ -156,7 +156,7 @@ export function shapeTradeCard(row, { origin = 'https://three.ws' } = {}) {const symbol = String(row.symbol || row.name || 'coin').replace(/^\$+/, '') || 'coin';const agentName = String(row.agent_name || 'Agent').trim() || 'Agent';- const pnlSolStr = pnlSol != null ? fmtSol(pnlSol) : null;+ const pnlSolStr = solStr(pnlSol);const holdLabel = secs != null ? holdTime(secs) : null;const model = {diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 37f7bc5ee..d0c5b2d79 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -481,6 +481,8 @@ async function submitGeometryJob({engine: engineIdFor(backendId),prompt: prompt || null,source_image_url: isImageMode ? primaryImage : null,+ cold_start: cold,+ cold_start_seconds: cold ? coldStartSecondsFor(backendId) : undefined,eta_seconds: etaSeconds,estimated_credits: estimateCredits({ backendId, path, tier }),},diff --git a/api/forge-enhance.js b/api/forge-enhance.jsindex 13417fa75..7585ec66b 100644--- a/api/forge-enhance.js+++ b/api/forge-enhance.js@@ -134,6 +134,31 @@ export function classifySubject(text) {return 'object';}+/**+ * classifySubject plus WHERE in the prompt the subject word was found.+ *+ * The position matters to any caller that has to weigh the subject against+ * another signal read from the same sentence. api/_lib/glb-pbr-derive.js weighs+ * it against material words: "a stainless steel chef knife" is a metal object+ * that happens to contain an occupation word, while "a chef in a wool apron" is+ * a person who happens to be wearing one, and only the ORDER of the two matches+ * tells them apart. classifySubject alone returns 'person' for both.+ *+ * `index` is the character offset of the matched subject word, or -1 when the+ * subject is the 'object' fallback (no word matched anything).+ *+ * @param {string} text+ * @returns {{ subject: 'person'|'animal'|'vehicle'|'food'|'object', index: number }}+ */+export function classifySubjectAt(text) {+ const t = String(text || '');+ for (const [re, subject] of [[PERSON_RE, 'person'], [ANIMAL_RE, 'animal'], [VEHICLE_RE, 'vehicle'], [FOOD_RE, 'food']]) {+ const m = re.exec(t);+ if (m) return { subject, index: m.index };+ }+ return { subject: 'object', index: -1 };+}+// The complete negative-prompt string for a prompt: the universal reconstruction// failures, the photoreal failures (only when the result should look real), and// the failures specific to the detected subject. This is the one place negativesdiff --git a/prompts/gcp-credits/05-catalog-animation-seeding.md b/prompts/gcp-credits/05-catalog-animation-seeding.mdindex f346dd88b..d76be094a 100644--- a/prompts/gcp-credits/05-catalog-animation-seeding.md+++ b/prompts/gcp-credits/05-catalog-animation-seeding.md@@ -27,14 +27,36 @@ gcloud run services describe three-ws-api --region us-central1 \--project aerial-vehicle-466722-p5 --format=yaml | grep -E "GCP_TEXT2MOTION_URL|MODEL_TRELLIS_URL|FORGE_SELFHOST_PRIMARY|SEED_CRON_BATCH"sed -n '1,40p' api/cron/forge-seed-cron.jsnode -e "const d=require('./data/motion-prompts.json');console.log(Object.keys(d), d.prompts?.length)"-curl -s "https://three.ws/api/animations/library?limit=1" | head -20-psql "$DATABASE_URL" -c "select count(*) from avatars" 2>/dev/null || echo "use api/_lib/db helpers instead"++# clip library: total, and how many are NOT the Mixamo import+curl -s "https://three.ws/api/animations/library" | python3 -c \+ "import sys,json;d=json.load(sys.stdin);n=[c['name'] for c in d['clips']];print('clips',d.get('total'),'non-mixamo',sum(1 for x in n if not x.startswith('mx-')))"++# catalog size, through the repo's own db helper (psql is not installed here)+cat > /tmp/catalog-count.mjs <<'EOF'+import fs from 'node:fs';+if (!process.env.DATABASE_URL) {+ const m = fs.readFileSync('/workspaces/three.ws/.env', 'utf8').match(/^DATABASE_URL=(.*)$/m);+ if (m) process.env.DATABASE_URL = m[1].replace(/^["']|["']$/g, '');+}+const { sql } = await import('/workspaces/three.ws/api/_lib/db.js');+console.log('avatars', (await sql`select count(*)::int as n from avatars`)[0].n);+console.log('last 7d', (await sql`select count(*)::int as n from avatars where created_at > now() - interval '7 days'`)[0].n);+EOF+node /tmp/catalog-count.mjs```-Known as of 2026-08-01: `data/motion-prompts.json` exists (the task-6 prompt library),+**Measured 2026-08-01, re-measure before trusting it:** 18,622 avatars in the catalog with 104+added in the previous 7 days, so the seed cron runs but at roughly 15 a day. The clip library+serves 2,874 clips and **every one is the `mx-` Mixamo import: zero generated clips exist**, so+section B below is entirely open. `data/motion-prompts.json` (the section B prompt library),`api/cron/forge-seed-cron.js`, `api/_lib/seed-prompts.js`, `api/marketplace/animations.js`,`api/x402/animation-download.js` and `api/animations/library.js` all exist;-`scripts/gcp/seed-avatars.mjs` does not. Verify each before deciding what is left.+`scripts/gcp/seed-avatars.mjs` does not.++That shape sets the priorities: the cron is alive but slow and unproven on quality, and the+generated-motion half has never run. Do not spend the session re-confirming that the cron+exists.## Tasksdiff --git a/prompts/quality-bar/03-gpu-fleet-scaleout.md b/prompts/quality-bar/03-gpu-fleet-scaleout.mdindex 188b787fe..788ebfd83 100644--- a/prompts/quality-bar/03-gpu-fleet-scaleout.md+++ b/prompts/quality-bar/03-gpu-fleet-scaleout.md@@ -23,7 +23,7 @@ This file's claims rot. Measure before you plan:```bashgcloud run services list --region us-central1 --project aerial-vehicle-466722-p5 \--format="table(metadata.name, status.conditions[0].status)"-gcloud alpha quotas preferences list --project=aerial-vehicle-466722-p5 2>&1 | head -40+timeout 120 gcloud alpha quotas preferences list --project=aerial-vehicle-466722-p5 2>&1 | head -40gcloud run services describe three-ws-api --region us-central1 \--project aerial-vehicle-466722-p5 --format=yaml \| grep -E "GCP_(TRIPOSG|TEXT2MOTION|HUNYUAN3D)_URL|MODEL_TRELLIS_URL"@@ -35,6 +35,11 @@ As of 2026-08-01, `model-triposg`, `model-text2motion`, `model-trellis`, `model-and "deploy text2motion" tasks are shipped. Confirm that yourself, record the evidence, andspend the session on what is still open.+The quota listing is slow and has returned empty in this workspace. Do not let it stall you:+`docs/ops/gcp-credits-plan.md` records the fleet position and the pre-approved scaling, and an+update that exceeds the grant fails with an explicit quota error, which is itself a measurement.+Attempt the scale change, read the error if there is one, and report the real ceiling.+## Tasks1. **Scale ceilings.** Read the granted L4 quotadiff --git a/src/animation-retarget.js b/src/animation-retarget.jsindex 30d8c9b18..32ac62387 100644--- a/src/animation-retarget.js+++ b/src/animation-retarget.js@@ -143,6 +143,34 @@ export function canonicalNodeMapFromObject(root) {return map;}+/**+ * Same walk as {@link canonicalNodeMapFromObject}, but keyed to the live nodes+ * rather than their names. Callers that need to *write* to the skeleton (the+ * skeleton-space proportion editor in src/avatar-proportions.js) need the node+ * itself; resolving by name afterwards would break on the duplicate bone names+ * a merged accessory or garment can introduce.+ *+ * @param {import('three').Object3D} root+ * @returns {Map<string,import('three').Object3D>}+ */+export function canonicalBoneNodesFromObject(root) {+ const map = new Map();+ const consider = (node) => {+ if (!node?.name) return;+ const canonical = canonicalizeBoneName(node.name);+ if (canonical && !map.has(canonical)) map.set(canonical, node);+ };+ const skinned = [];+ root?.traverse?.((node) => {+ if (node.isSkinnedMesh) skinned.push(node);+ if (node.isBone) consider(node);+ });+ for (const sm of skinned) {+ for (const bone of sm.skeleton?.bones || []) consider(bone);+ }+ return map;+}+/*** Build the same map from a GltfRig/MannequinRig (src/pose-rig.js), which has* already resolved canonical → node. We read each node's live `.name` so thediff --git a/src/avatar-sculpt.js b/src/avatar-sculpt.jsindex 3a70ead86..778a8af9f 100644--- a/src/avatar-sculpt.js+++ b/src/avatar-sculpt.js@@ -29,7 +29,7 @@ import {proportionsGroupHtml,wireProportionsGroup,} from './avatar-proportions.js';-import { canonicalizeBoneName } from './glb-canonicalize.js';+import { canonicalBoneNodesFromObject } from './animation-retarget.js';import { log } from './shared/log.js';/* ────────────────────────────────────────────────────────────────────────── *@@ -263,30 +263,6 @@ export function applyMorphsToRoot(root, morphs) {});}-/**- * Canonical bone → node map for the loaded rig, using the full name-variant- * coverage of glb-canonicalize (Mixamo, VRM, Unreal, Daz, Blender, …) rather- * than the lightweight fallback avatar-proportions ships for callers that- * can't afford the import. First bone wins, matching the retargeter's order.- */-function boneNodeMap(root) {- const map = new Map();- const consider = (node) => {- if (!node?.name) return;- const canonical = canonicalizeBoneName(node.name);- if (canonical && !map.has(canonical)) map.set(canonical, node);- };- const skinned = [];- root?.traverse?.((node) => {- if (node.isSkinnedMesh) skinned.push(node);- if (node.isBone) consider(node);- });- for (const sm of skinned) {- for (const bone of sm.skeleton?.bones || []) consider(bone);- }- return map;-}-/*** Render the sculpt panel into the supplied container. Idempotent — calling* twice rebuilds. The opts wire to avatar-edit.js's state machinery so wediff --git a/src/fact-check.js b/src/fact-check.jsindex 99cae3235..fd219869f 100644--- a/src/fact-check.js+++ b/src/fact-check.js@@ -34,17 +34,31 @@ function renderStats(bench) {}const r = bench.report;const cls = r.accuracy_pct >= 80 ? 'fc-good' : r.accuracy_pct >= 60 ? 'fc-warn' : '';- const byClass = Object.entries(r.by_class || {})- .map(([k, v]) => `<div class="fc-stat"><div class="fc-stat-label">${esc(k)}</div><div class="fc-stat-value">${pct(v.accuracy_pct)}</div></div>`)- .join('');+ // Only render a breakdown cell for a bucket that actually had claims: a 0-claim+ // bucket scores null, and showing it as a dash next to real numbers reads like+ // a failure rather than an absence.+ const cells = (table) =>+ Object.entries(table || {})+ .filter(([, v]) => v && v.total > 0)+ .map(+ ([k, v]) =>+ `<div class="fc-stat"><div class="fc-stat-label">${esc(k)}</div><div class="fc-stat-value">${pct(v.accuracy_pct)}</div><div class="fc-stat-sub">${v.correct}/${v.total}</div></div>`,+ )+ .join('');+ const byClass = cells(r.by_class);+ const byDifficulty = cells(r.by_difficulty);+ const ran = r.generated_at ? new Date(r.generated_at) : null;return `<div class="fc-stats-grid">- <div class="fc-stat"><div class="fc-stat-label">Overall accuracy</div><div class="fc-stat-value ${cls}">${pct(r.accuracy_pct)}</div></div>- <div class="fc-stat"><div class="fc-stat-label">Claims run</div><div class="fc-stat-value">${r.total ?? '—'}</div></div>- <div class="fc-stat"><div class="fc-stat-label">Errors</div><div class="fc-stat-value">${r.errors ?? 0}</div></div>+ <div class="fc-stat"><div class="fc-stat-label">Overall accuracy</div><div class="fc-stat-value ${cls}">${pct(r.accuracy_pct)}</div><div class="fc-stat-sub">${r.correct ?? 0}/${r.total ?? 0} claims</div></div>+ <div class="fc-stat"><div class="fc-stat-label">Claims run</div><div class="fc-stat-value">${r.total ?? 0}</div><div class="fc-stat-sub">${esc(String(r.fixture_version || '1.0.0'))} suite</div></div>+ <div class="fc-stat"><div class="fc-stat-label">Errors</div><div class="fc-stat-value">${r.errors ?? 0}</div><div class="fc-stat-sub">unreachable checks</div></div></div>- <div class="fc-stats-grid">${byClass}</div>- <p class="fc-hint" style="margin-top:12px">Last run: ${r.generated_at ? new Date(r.generated_at).toLocaleString() : 'unknown'}</p>`;+ ${byClass ? `<h3 class="fc-stats-heading">By expected verdict</h3><div class="fc-stats-grid">${byClass}</div>` : ''}+ ${byDifficulty ? `<h3 class="fc-stats-heading">By difficulty</h3><div class="fc-stats-grid">${byDifficulty}</div>` : ''}+ <p class="fc-hint" style="margin-top:12px">+ Last run: ${ran ? `<time datetime="${esc(ran.toISOString())}">${esc(ran.toLocaleString())}</time>` : 'unknown'}+ </p>`;}async function loadBenchmark() {diff --git a/tests/api/openrouter-usage.test.js b/tests/api/openrouter-usage.test.jsnew file mode 100644index 000000000..3515df5f2--- /dev/null+++ b/tests/api/openrouter-usage.test.js@@ -0,0 +1,118 @@+// The OpenRouter usage-accounting fetch: it must ask for the cost, read the+// cost, and never damage the response the AI SDK is about to stream.+//+// Both halves matter. Without the opt-in OpenRouter omits `usage.cost` entirely,+// so /brain metered paid Claude mirrors at nothing. And a metering wrapper that+// consumes or reorders the body would break streaming, which is a far worse+// outcome than missing telemetry: the rule here is that the completion always+// wins and metering is best-effort.++import { describe, it, expect, vi } from 'vitest';+import {+ withUsageAccounting,+ readReportedCost,+ openrouterUsageFetch,+} from '../../api/_lib/openrouter-usage.js';++const SSE = [+ 'data: {"choices":[{"delta":{"content":"hel"}}]}',+ 'data: {"choices":[{"delta":{"content":"lo"}}]}',+ // OpenRouter's final frame carries usage, including the charged amount and a+ // cost_details block whose keys also end in "cost" (a naive scan reads the+ // wrong number here).+ 'data: {"choices":[],"usage":{"prompt_tokens":69,"completion_tokens":16,"cost":0.0004312,"cost_details":{"upstream_inference_cost":0.0000021}}}',+ 'data: [DONE]',+ '',+].join('\n\n');++function streamOf(text) {+ const encoder = new TextEncoder();+ return new ReadableStream({+ start(controller) {+ // Deliberately chunked mid-frame: the reader must reassemble.+ const bytes = encoder.encode(text);+ controller.enqueue(bytes.slice(0, 40));+ controller.enqueue(bytes.slice(40));+ controller.close();+ },+ });+}++describe('withUsageAccounting', () => {+ it('adds the usage opt-in to a JSON body', () => {+ const out = withUsageAccounting({ body: JSON.stringify({ model: 'anthropic/claude-opus-5', messages: [] }) });+ expect(JSON.parse(out.body).usage).toEqual({ include: true });+ expect(JSON.parse(out.body).model).toBe('anthropic/claude-opus-5');+ });++ it('leaves a caller-supplied usage block alone', () => {+ const body = JSON.stringify({ model: 'm', usage: { include: false } });+ expect(withUsageAccounting({ body }).body).toBe(body);+ });++ it('passes through a non-JSON body untouched', () => {+ expect(withUsageAccounting({ body: 'not json' }).body).toBe('not json');+ expect(withUsageAccounting({}).body).toBeUndefined();+ });+});++describe('readReportedCost', () => {+ it('reads the cost from the final SSE usage frame, not from cost_details', () => {+ return expect(readReportedCost(SSE)).resolves.toBe(0.0004312);+ });++ it('reads the cost from a plain JSON completion', () => {+ return expect(readReportedCost(JSON.stringify({ usage: { prompt_tokens: 1, cost: 0.25 } }))).resolves.toBe(0.25);+ });++ it('returns a reported zero as zero (a free route really did cost nothing)', () => {+ return expect(readReportedCost(JSON.stringify({ usage: { cost: 0 } }))).resolves.toBe(0);+ });++ it('returns null when nothing reported a cost', () => {+ return expect(readReportedCost(JSON.stringify({ usage: { prompt_tokens: 3 } }))).resolves.toBeNull();+ });++ it('survives a truncated stream without throwing', () => {+ return expect(readReportedCost('data: {"choices":[{"delta":{"conte')).resolves.toBeNull();+ });+});++describe('openrouterUsageFetch', () => {+ it('reports the cost while handing the stream through intact', async () => {+ let seen = null;+ const base = vi.fn(async () => new Response(streamOf(SSE), { status: 200, headers: { 'content-type': 'text/event-stream' } }));+ const f = openrouterUsageFetch((usd) => { seen = usd; }, base);++ const res = await f('https://openrouter.ai/api/v1/chat/completions', {+ method: 'POST',+ body: JSON.stringify({ model: 'anthropic/claude-opus-5', messages: [] }),+ });+ // The consumer gets every byte, in order.+ const body = await res.text();+ expect(body).toBe(SSE);+ expect(res.status).toBe(200);+ // The opt-in went out on the wire.+ expect(JSON.parse(base.mock.calls[0][1].body).usage).toEqual({ include: true });+ // The cost arrives out-of-band once the copied stream drains.+ await vi.waitFor(() => expect(seen).toBe(0.0004312));+ });++ it('does not call back when the upstream failed', async () => {+ const onCost = vi.fn();+ const base = async () => new Response('{"error":{"message":"nope"}}', { status: 402 });+ const res = await openrouterUsageFetch(onCost, base)('https://openrouter.ai/x', { body: '{}' });+ expect(res.status).toBe(402);+ expect(onCost).not.toHaveBeenCalled();+ });++ it('returns the original response when the body cannot be teed', async () => {+ const onCost = vi.fn();+ // A response-like object whose body has no tee(): metering must degrade,+ // not throw into the request path.+ const fake = { ok: true, status: 200, body: {} };+ const res = await openrouterUsageFetch(onCost, async () => fake)('https://openrouter.ai/x', { body: '{}' });+ expect(res).toBe(fake);+ expect(onCost).not.toHaveBeenCalled();+ });+});diff --git a/tests/x402-ring-agents.test.js b/tests/x402-ring-agents.test.jsindex d101b8cc4..b1ab28383 100644--- a/tests/x402-ring-agents.test.js+++ b/tests/x402-ring-agents.test.js@@ -265,3 +265,111 @@ describe('ring on-chain step — cadence gate', () => {}});});++// ── Buyer float pre-flight ─────────────────────────────────────────────────────+// The 2026-08-01 defect: the roster kept shopping from empty custodial wallets.+// Every one of those purchases probed the endpoint, signed a USDC transfer and+// paid for a facilitator `verify` that simulates against an RPC node, only to+// come back InstructionError:[2,{Custom:1}] (SPL insufficient funds) and be+// recorded as `http_402`: which the settle sensor counts as a payment-RAIL+// fault. 180 of them in one 3h window, ~9% of the settle rate, all of it an+// empty wallet wearing a broken-rail costume.+describe('assessAgentBuyingPower: a dry wallet is back-pressure, not a rail fault', () => {+ it('refuses when the buyer cannot cover the price, and says by how much', () => {+ const v = assessAgentBuyingPower({ usdcAtomic: 48_000, priceAtomic: 100_000 });+ expect(v.ok).toBe(false);+ // The SAME token the shared ring payer reports, so the settle sensor's+ // existing benign-guard exclusion covers it with no sensor change.+ expect(v.reason).toBe('insufficient_payer_usdc');+ expect(v.detail).toBe('48000<100000');+ });++ it('admits when the balance covers the price exactly', () => {+ expect(assessAgentBuyingPower({ usdcAtomic: 10_000, priceAtomic: 10_000 }).ok).toBe(true);+ });++ it('an UNREADABLE balance admits: null is unknown, not zero', () => {+ // Number(null) is 0, so a nullish balance would otherwise read as "broke"+ // and freeze every funded agent behind one RPC lane outage.+ for (const unknown of [null, undefined, NaN, 'not-a-number']) {+ expect(assessAgentBuyingPower({ usdcAtomic: unknown, priceAtomic: 10_000 }).ok).toBe(true);+ }+ });++ it('a free endpoint (price 0) is always admitted', () => {+ expect(assessAgentBuyingPower({ usdcAtomic: 0, priceAtomic: 0 }).ok).toBe(true);+ });++ it('a genuine zero balance refuses: a missing ATA is knowably broke', () => {+ expect(assessAgentBuyingPower({ usdcAtomic: 0, priceAtomic: 1 }).ok).toBe(false);+ });+});++describe('readAgentUsdcAtomic: knowable zero vs unknown', () => {+ const BUYER = 'AGENTwa11et1111111111111111111111111111111';+ const connWith = (impl) => ({ getTokenAccountBalance: impl });++ it('reads the atomic amount and caches it within the tick', async () => {+ resetAgentUsdcCache();+ let calls = 0;+ const conn = connWith(async () => { calls += 1; return { value: { amount: '250000' } }; });+ expect(await readAgentUsdcAtomic(conn, BUYER)).toBe(250_000);+ expect(await readAgentUsdcAtomic(conn, BUYER)).toBe(250_000);+ expect(calls).toBe(1); // one read per wallet per tick, not per purchase+ });++ it('a missing ATA is 0 (knowably broke), an RPC fault is null (unknown)', async () => {+ resetAgentUsdcCache();+ const missing = connWith(async () => { throw new Error('could not find account'); });+ expect(await readAgentUsdcAtomic(missing, BUYER)).toBe(0);++ resetAgentUsdcCache();+ const laneDown = connWith(async () => { throw new Error('429 Too Many Requests'); });+ expect(await readAgentUsdcAtomic(laneDown, BUYER)).toBeNull();+ });++ it('never throws on a missing connection or address', async () => {+ resetAgentUsdcCache();+ expect(await readAgentUsdcAtomic(null, BUYER)).toBeNull();+ expect(await readAgentUsdcAtomic(connWith(async () => ({})), '')).toBeNull();+ });+});++describe('executePurchase: the dry buyer never reaches the payment path', () => {+ const TREASURY_SET = new Set([TREASURY]);+ const purchase = {+ slug: 'three-intel', url: 'https://three.ws/api/x402/three-intel',+ method: 'GET', body: null, priceAtomic: 10_000, kind: 'intel',+ };++ it('refuses without probing, signing or simulating', async () => {+ resetAgentUsdcCache();+ let paid = 0;+ const out = await executePurchase({+ agent: permissiveAgent(),+ purchase,+ solana: { conn: { getTokenAccountBalance: async () => ({ value: { amount: '0' } }) }, blockhash: 'hash', mintInfo: { decimals: 6 } },+ allowed: TREASURY_SET,+ persona: 'endpoint-shopper',+ payImpl: async () => { paid += 1; return { success: true, paid: true, amountAtomic: 10_000, txSig: 'nope' }; },+ });+ expect(out.status).toBe('refused');+ expect(out.reason).toBe('insufficient_payer_usdc:0<10000');+ expect(out.txSig).toBeNull();+ expect(paid).toBe(0); // the whole point: zero handshakes, zero simulations+ });++ it('still pays when the buyer is funded', async () => {+ resetAgentUsdcCache();+ const out = await executePurchase({+ agent: permissiveAgent(),+ purchase,+ solana: { conn: { getTokenAccountBalance: async () => ({ value: { amount: '2000000' } }) }, blockhash: 'hash', mintInfo: { decimals: 6 } },+ allowed: TREASURY_SET,+ persona: 'endpoint-shopper',+ payImpl: fakePay(TREASURY, 10_000),+ });+ expect(out.status).toBe('paid');+ expect(out.txSig).toBe('settle-sig-1');+ });+});diff --git a/tests/x402-wallet-fee-governor.test.js b/tests/x402-wallet-fee-governor.test.jsindex 550838ecd..266452b19 100644--- a/tests/x402-wallet-fee-governor.test.js+++ b/tests/x402-wallet-fee-governor.test.js@@ -23,6 +23,18 @@ describe('walletFeeGovernorConfig', () => {expect(cfg.runwayDays).toBe(3);expect(cfg.minBudgetLamports).toBe(10_000_000);expect(cfg.spentCacheMs).toBe(20_000);+ // Intraday pacing is opt-in: it moves which gate refuses a starved wallet+ // first, so it must never switch on by accident.+ expect(cfg.paceDay).toBe(false);+ expect(cfg.paceMinSliceLamports).toBe(200_000);+ });++ it('only an explicit "true" enables intraday pacing', () => {+ expect(walletFeeGovernorConfig({ X402_WALLET_FEE_PACE_DAY: 'true' }).paceDay).toBe(true);+ expect(walletFeeGovernorConfig({ X402_WALLET_FEE_PACE_DAY: 'TRUE' }).paceDay).toBe(true);+ expect(walletFeeGovernorConfig({ X402_WALLET_FEE_PACE_DAY: '1' }).paceDay).toBe(false);+ expect(walletFeeGovernorConfig({ X402_WALLET_FEE_PACE_DAY: 'yes' }).paceDay).toBe(false);+ expect(walletFeeGovernorConfig({}).paceDay).toBe(false);});it('only an explicit "false" disables it', () => {diff --git a/workers/okx-chat-bot/cloudbuild.yaml b/workers/okx-chat-bot/cloudbuild.yamlnew file mode 100644index 000000000..58788d944--- /dev/null+++ b/workers/okx-chat-bot/cloudbuild.yaml@@ -0,0 +1,110 @@+# Cloud Build → Cloud Run for the OKX.AI marketplace chat bot host+# (workers/okx-chat-bot). Build context is the REPO ROOT.+#+# gcloud builds submit --config workers/okx-chat-bot/cloudbuild.yaml \+# --region us-central1 --project aerial-vehicle-466722-p5 \+# --substitutions=SHORT_SHA=manual$(date +%s) .+#+# ── WHY --max-instances=1 IS LOAD-BEARING ────────────────────────────────────+# The bot's wallet/XMTP identity is a single GCS state object that this service+# reads on boot and overwrites on a timer. Two concurrent instances would+# interleave those writes and corrupt the identity, which costs a human OTP to+# recover. min=1 keeps the XMTP connection held open between requests (this is a+# daemon, not a request handler), and --no-cpu-throttling keeps it ticking when+# no HTTP request is in flight.+#+# ── ONE-TIME SETUP (run once per project, never commit secret values) ─────────+# # 1. State bucket. Versioning is the undo button for a torn snapshot.+# gcloud storage buckets create gs://three-ws-okx-bot-state \+# --location=us-central1 --uniform-bucket-level-access --project aerial-vehicle-466722-p5+# gcloud storage buckets update gs://three-ws-okx-bot-state --versioning+# gcloud storage buckets add-iam-policy-binding gs://three-ws-okx-bot-state \+# --member=serviceAccount:[email protected] \+# --role=roles/storage.objectAdmin+#+# # 2. Secrets. DATABASE_URL feeds the heartbeat that /api/healthz reads.+# printf '%s' "$DATABASE_URL" | gcloud secrets create okx-chat-bot-database-url --data-file=-+# # AI-provider credential (OWNER ACTION, see the README): one of+# printf '%s' "$ANTHROPIC_API_KEY" | gcloud secrets create anthropic-api-key --data-file=-+# printf '%s' "$OPENAI_API_KEY" | gcloud secrets create openai-api-key --data-file=-+# for s in okx-chat-bot-database-url anthropic-api-key openai-api-key; do \+# gcloud secrets add-iam-policy-binding "$s" \+# --member=serviceAccount:[email protected] \+# --role=roles/secretmanager.secretAccessor; done+#+# # 3. Optional Telegram push for the session-expired alert (it always lands on+# # /admin/ops regardless). Reuse the existing alert secrets if present.+#+# ── AFTER THE FIRST DEPLOY ────────────────────────────────────────────────────+# The bot boots logged out (there is no snapshot yet) and pages for a human OTP.+# Read the exact commands off the service itself:+# curl -s -H "Authorization: Bearer $(gcloud auth print-identity-token)" \+# "$(gcloud run services describe okx-chat-bot --region us-central1 \+# --format='value(status.url)')/readyz" | jq .remedy++substitutions:+ _REGION: us-central1+ _SERVICE: okx-chat-bot+ _REPO: workers+ # Deliberately not parameterised: see the max-instances note above.+ _STATE_BUCKET: three-ws-okx-bot-state++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ args:+ - build+ - --file+ - workers/okx-chat-bot/Dockerfile+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:latest+ - .+ timeout: 1800s++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:$SHORT_SHA+ - --region=${_REGION}+ - --platform=managed+ - --no-cpu-throttling+ - --cpu=2+ - --memory=4Gi+ # The state tree lives on the in-memory filesystem and the AI subsession+ # is a whole CLI process; 4Gi leaves headroom for both.+ - --min-instances=1+ - --max-instances=1+ - --timeout=3600+ - --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+ # 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.+ - --startup-probe=httpGet.path=/healthz,initialDelaySeconds=20,periodSeconds=10,failureThreshold=30++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_SERVICE}:latest++serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]+options:+ machineType: E2_HIGHCPU_8+ logging: CLOUD_LOGGING_ONLY+timeout: 2400s