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
fix(market-data): survive an exhausted CoinGecko demo key instead of 502ing
nirholascf2db15f03f6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64449c4a2..7f5001a15 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-07-28++- **Coin pages are back, and they can no longer be taken down by an expired market-data key** — Every coin profile page was returning an error. The market-data provider we read prices and coin details from gives us a monthly call allowance, and once it ran out, every request we sent with our key was refused. The awkward part: the exact same request sent without the key was still being answered. We were effectively locking ourselves out. The pages are live again, and the fix is permanent rather than a one-off: when the key gets refused, we now set it aside for a while and retry the same request without it, so the pages keep serving and recover on their own when the allowance resets. We also repaired a 3D model service that was crash-looping because it tried to download a small config file from a public model host on every start and kept getting throttled. That file now ships with our own model storage, so the service starts without depending on anyone else. (`/coins`) `[fix, infra]`+## 2026-07-27- **3D generations that run long now hand back a handle instead of an error** — A detailed model can take several minutes, longer than an assistant will wait inside a single tool call. Those generations used to look like failures even though the GPU finished the model minutes later. The ChatGPT 3D Studio now returns a live handle with a countdown of how much time is left, and a new check_job tool collects the finished model when it lands. Poll responses carry elapsed time and a remaining estimate that counts down, the assistant sees progress instead of identical waiting frames, and the inline viewer shows a real "still rendering" panel rather than an empty one. A generation whose GPU worker dies mid-job is now automatically retried on a healthy engine instead of being written off, including when nobody is watching the page. (`/docs/mcp-studio`) `[improvement, fix]`diff --git a/api/_lib/coingecko.js b/api/_lib/coingecko.jsindex c1bf4f1ee..5f4f17c41 100644--- a/api/_lib/coingecko.js+++ b/api/_lib/coingecko.js@@ -41,13 +41,55 @@ async function durableStale(path) {}}-function headers() {+// ── Demo-key health ──────────────────────────────────────────────────────────+// The demo tier caps at 10,000 calls per MONTH. Once that cap is reached every+// keyed request comes back 429 (error_code 10006) for the rest of the billing+// period — while the SAME request without the key is still served by the+// keyless public tier. So an exhausted key is strictly worse than no key: on+// 2026-07-28 it took every /api/coin/detail, /tickers and /exchange call to a+// 502 for hours because the key was attached to all of them.+//+// Treat the key as a resource that can go bad: when a keyed request is rejected+// for an auth/quota reason, retry the same URL keyless and, if that works, park+// the key for a cooldown so subsequent calls skip it entirely instead of paying+// a wasted round trip. The key is re-probed after the cooldown, so a monthly+// reset (or a key upgrade) heals on its own with no redeploy.+const KEY_COOLDOWN_MS = 15 * 60_000;+// 429 = quota exhausted or throttled; 401/403 = revoked or wrong-tier key.+const KEY_FAULT_STATUSES = new Set([401, 403, 429]);+let _keyBenchedUntil = 0;++/** True when the demo key is currently benched (recently rejected). */+export function isGeckoKeyBenched(now = Date.now()) {+ return _keyBenchedUntil > now;+}++/** Bench the demo key so the next calls go out keyless. Exported for tests. */+export function benchGeckoKey(now = Date.now()) {+ _keyBenchedUntil = now + KEY_COOLDOWN_MS;+}++/** Clear the bench. Test-only hook; production heals via the cooldown. */+export function resetGeckoKeyHealth() {+ _keyBenchedUntil = 0;+}++/**+ * Request headers for a CoinGecko call.+ * @param {boolean} [withKey=true] false forces the keyless public tier.+ */+export function geckoHeaders(withKey = true) {const h = { accept: 'application/json', 'user-agent': 'three.ws/1.0' };const key = (process.env.COINGECKO_API_KEY || '').trim();- if (key) h['x-cg-demo-api-key'] = key;+ if (key && withKey && !isGeckoKeyBenched()) h['x-cg-demo-api-key'] = key;return h;}+/** Did this response carry the demo key, and was it rejected for using it? */+function keyWasRejected(headersUsed, status) {+ return Boolean(headersUsed['x-cg-demo-api-key']) && KEY_FAULT_STATUSES.has(status);+}+/*** GET a CoinGecko path (must start with '/'), JSON-parsed, memory-cached.* Throws an Error with .status = upstream HTTP status on a non-OK response so@@ -60,12 +102,23 @@ export async function geckoFetch(path, { ttlMs = 60_000, timeoutMs = 8000 } = {}// A still-usable stale entry lets us ride out a throttled/failing upstream.const stale = hit && hit.staleUntil > now ? hit.value : null;+ const url = `${COINGECKO_BASE}${path}`;let resp;try {- resp = await fetch(`${COINGECKO_BASE}${path}`, {- headers: headers(),- signal: AbortSignal.timeout(timeoutMs),- });+ const sent = geckoHeaders();+ resp = await fetch(url, { headers: sent, signal: AbortSignal.timeout(timeoutMs) });+ // An exhausted/revoked demo key rejects requests the keyless tier would+ // still answer. Bench the key and retry once without it before falling+ // back to stale data — the live payload beats a cached one.+ if (keyWasRejected(sent, resp.status)) {+ benchGeckoKey();+ console.warn(`[coingecko] ${path} → ${resp.status} with demo key; benching key, retrying keyless`);+ const keyless = await fetch(url, {+ headers: geckoHeaders(false),+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (keyless.ok) resp = keyless;+ }} catch (netErr) {// Network failure or timeout — serve stale if we have it, else surface.if (stale !== null) {diff --git a/api/_lib/market-fallbacks.js b/api/_lib/market-fallbacks.jsindex fd30b9b7c..e2e98a3b7 100644--- a/api/_lib/market-fallbacks.js+++ b/api/_lib/market-fallbacks.js@@ -20,7 +20,7 @@// and api/_lib/sol-price.js for the SOL-spot failover.import { fetchFirst } from '../../src/shared/failover-fetch.js';-import { COINGECKO_BASE } from './coingecko.js';+import { COINGECKO_BASE, geckoHeaders } from './coingecko.js';import { downsample } from '../../src/shared/coin-format.js';const num = (v) => {@@ -28,14 +28,9 @@ const num = (v) => {return Number.isFinite(n) ? n : null;};-// CoinGecko demo key (optional) lifts the public rate limit — same header the-// shared geckoFetch uses. Absent key just means the stricter keyless tier.-function geckoHeaders() {- const h = { accept: 'application/json', 'user-agent': 'three.ws/1.0' };- const key = (process.env.COINGECKO_API_KEY || '').trim();- if (key) h['x-cg-demo-api-key'] = key;- return h;-}+// Headers come from the shared geckoFetch client (geckoHeaders) so the demo-key+// health state is process-wide: once geckoFetch benches an exhausted key, these+// failover rungs stop attaching it too, instead of each burning a 429 first.const asPrice = (v) => {const n = Number(v);diff --git a/data/changelog.json b/data/changelog.jsonindex 74dec2c34..a9031f9f9 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$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-28",+ "title": "Coin pages are back, and they can no longer be taken down by an expired market-data key",+ "summary": "Every coin profile page was returning an error. The market-data provider we read prices and coin details from gives us a monthly call allowance, and once it ran out, every request we sent with our key was refused. The awkward part: the exact same request sent without the key was still being answered. We were effectively locking ourselves out. The pages are live again, and the fix is permanent rather than a one-off: when the key gets refused, we now set it aside for a while and retry the same request without it, so the pages keep serving and recover on their own when the allowance resets. We also repaired a 3D model service that was crash-looping because it tried to download a small config file from a public model host on every start and kept getting throttled. That file now ships with our own model storage, so the service starts without depending on anyone else.",+ "tags": [+ "fix",+ "infra"+ ],+ "link": "/coins"+ },{"date": "2026-07-27","title": "A new dance joins the animation library, and two rig quirks that used to break imports are now handled",diff --git a/docs/ops/production-log-triage.md b/docs/ops/production-log-triage.mdindex b522c02d3..fba31b573 100644--- a/docs/ops/production-log-triage.md+++ b/docs/ops/production-log-triage.md@@ -167,6 +167,114 @@ HTTP 502/503 GET|POST /api/x402/*, /api/mcp ua: threews-x402-autonomous/1.0 orservice) so burn matches what the owner wants to spend.- **Monitor signature:** `x402-wallets-dry-5xx` in[scripts/gcp-triage.mjs](../../scripts/gcp-triage.mjs), classified `owner`.+ It matches **any** `threews-*` user agent, because the ring calls its own paid+ routes under several: `threews-x402-autonomous/1.0`, `threews-x402-seed`,+ `threews-ring-agent/<persona>` (persona agents), `threews-x402-wallet-monitor`+ and `threews-x402-thumbnail-regen`. Matching only the first two used to leak+ the rest into `investigate` on every sweep with the same root cause.++---++## 🟡 HTTP 502 on `/api/coin/*` — `coingecko-quota-exhausted-502`++```+HTTP 502 GET /api/coin/detail?id=<coin-id>+body: {"error":"upstream_error","error_description":"coin data is unavailable right now — retry shortly"}+```++- **Source:** [api/_lib/coingecko.js](../../api/_lib/coingecko.js) `geckoFetch()`+ exhausted every rung — live fetch, in-memory stale buffer (30 min) and the+ durable Upstash last-good copy (6 h) — so the handler surfaced its 502.+- **What it usually means: the demo KEY, not the upstream.** CoinGecko's demo+ tier caps at **10,000 calls per month**. Once the cap is hit, every request+ carrying `COINGECKO_API_KEY` gets a 429 (`error_code: 10006`) for the rest of+ the billing period — while the *identical request without the key* is still+ answered by the keyless public tier. An exhausted key is therefore strictly+ worse than no key. On **2026-07-28** it took `/api/coin/detail`, `/tickers`+ and `/exchange` to a hard 502 for hours; the pages that survived only did so+ off their durable last-good copies.+- **Confirm in one call** (`$KEY` from the Cloud Run env):++ ```sh+ curl -s -H "x-cg-demo-api-key: $KEY" https://api.coingecko.com/api/v3/key+ # {"status":{"error_code":10006,"error_message":"You've reached 10,000 calls limit. …"}}+ ```++- **Self-healing since 2026-07-28.** `geckoFetch` now treats the key as a+ resource that can go bad: a keyed 401/403/429 benches the key for 15 minutes+ and immediately retries the same URL keyless, and `geckoHeaders()` (shared+ with [api/\_lib/market-fallbacks.js](../../api/_lib/market-fallbacks.js)) stops+ attaching a benched key at all. A monthly quota reset or a key upgrade+ recovers on its own with no redeploy. Pinned by+ [tests/coingecko-key-health.test.js](../../tests/coingecko-key-health.test.js).+- **Resolve:** a *lingering* 502 after that means the keyless tier is throttled+ too (Cloud Run egress IPs are shared and CoinGecko rate-limits per IP). Stop+ paying the wasted round trip, config-only and pre-approved:++ ```sh+ gcloud run services update three-ws-api --region us-central1 \+ --remove-env-vars COINGECKO_API_KEY+ ```++ Then tell the owner the key needs a paid tier (or to wait for the monthly+ reset). Re-add with `--update-env-vars COINGECKO_API_KEY=<key>` once renewed.+- **Monitor signature:** `coingecko-quota-exhausted-502` in+ [scripts/gcp-triage.mjs](../../scripts/gcp-triage.mjs), classified `env-action`.++---++## 🟡 `429 Client Error … huggingface.co` → `LocalEntryNotFoundError` on a model worker — `hf-hub-rate-limited`++```+requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url:+ https://huggingface.co/facebook/dino-vitb16/resolve/main/config.json+We had to rate limit your IP (2600:1900:0:2d0e::2801).+huggingface_hub.utils._errors.LocalEntryNotFoundError: An error happened while trying to locate the file on the Hub …+ERROR: Application startup failed. Exiting.+Container called exit(3).+Default STARTUP TCP probe failed 1 time consecutively for container "server-1" on port 8080.+```++- **Source:** a model worker whose model construction pulls a file from+ huggingface.co **at startup**. 2026-07-28 case: `model-triposr`, whose+ TripoSR `DINOSingleImageTokenizer` calls `hf_hub_download("facebook/dino-vitb16",+ "config.json")` while building the graph — the TripoSR checkpoint itself was+ already local on the gcsfuse mount, but that one 454-byte config was not.+- **What it means:** anonymous HF pulls are rate-limited **per IP**, and Cloud+ Run egress IPs are shared with the rest of the region. When HF says no, the+ app never listens on `$PORT`, the startup probe fails, and Cloud Run kills the+ revision — a crash loop that scales to zero and 503s every request. **No boot+ path may depend on a live huggingface.co fetch.**+- **The token trap:** the pinned `huggingface_hub` reads the **legacy**+ `HUGGING_FACE_HUB_TOKEN` env var. Setting `HF_TOKEN` alone changes nothing+ (verified: the retry 429'd identically).+- **Resolve (config-only, pre-approved).** Stage the file into the HF cache+ layout inside the already-mounted weights bucket, then point the worker at it.+ `<sha>` is the repo's current commit from+ `https://huggingface.co/api/models/<org>/<repo>` (field `sha`):++ ```sh+ # 1. build the cache layout locally+ SHA=$(curl -s https://huggingface.co/api/models/facebook/dino-vitb16 | jq -r .sha)+ D=hub/models--facebook--dino-vitb16+ mkdir -p "$D/refs" "$D/snapshots/$SHA"+ printf '%s' "$SHA" > "$D/refs/main"+ curl -sL -o "$D/snapshots/$SHA/config.json" \+ "https://huggingface.co/facebook/dino-vitb16/resolve/$SHA/config.json"++ # 2. stage it (the bucket is gcsfuse-mounted at /weights on every model worker)+ gsutil -m cp -r hub gs://three-ws-model-weights/hf-cache/++ # 3. point the worker at it, offline+ gcloud run services update model-triposr --region us-central1 \+ --update-env-vars HF_HOME=/weights/hf-cache,HF_HUB_OFFLINE=1,HUGGING_FACE_HUB_TOKEN=<HF_TOKEN from .env>+ ```++ Plain files work — `hf_hub_download` only checks `refs/<revision>` for the+ commit hash and then `os.path.exists()` on the snapshot path, so the blob+ symlinks a real HF cache uses are not required.+- **Monitor signature:** `hf-hub-rate-limited` in+ [scripts/gcp-triage.mjs](../../scripts/gcp-triage.mjs), classified `env-action`.---diff --git a/public/changelog.json b/public/changelog.jsonindex b9dbec263..b3a82d24a 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-07-27T23:29:26.349Z",+ "generated_at": "2026-07-28T01:50:53.710Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-28",+ "type": "update",+ "title": "Coin pages are back, and they can no longer be taken down by an expired market-data key",+ "summary": "Every coin profile page was returning an error. The market-data provider we read prices and coin details from gives us a monthly call allowance, and once it ran out, every request we sent with our key was refused. The awkward part: the exact same request sent without the key was still being answered. We were effectively locking ourselves out. The pages are live again, and the fix is permanent rather than a one-off: when the key gets refused, we now set it aside for a while and retry the same request without it, so the pages keep serving and recover on their own when the allowance resets. We also repaired a 3D model service that was crash-looping because it tried to download a small config file from a public model host on every start and kept getting throttled. That file now ships with our own model storage, so the service starts without depending on anyone else.",+ "link": "/coins",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-27","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 3acb21b4e..c8b36c42a 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Coin pages are back, and they can no longer be taken down by an expired market-data key</title>+ <link>https://three.ws/coins</link>+ <guid isPermaLink="false">2026-07-28:Coin pages are back, and they can no longer be taken down by an expired market-data key</guid>+ <pubDate>Tue, 28 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every coin profile page was returning an error. The market-data provider we read prices and coin details from gives us a monthly call allowance, and once it ran out, every request we sent with our key was refused. The awkward part: the exact same request sent without the key was still being answered. We were effectively locking ourselves out. The pages are live again, and the fix is permanent rather than a one-off: when the key gets refused, we now set it aside for a while and retry the same request without it, so the pages keep serving and recover on their own when the allowance resets. We also repaired a 3D model service that was crash-looping because it tried to download a small config file from a public model host on every start and kept getting throttled. That file now ships with our own model storage, so the service starts without depending on anyone else.</description>+ </item><item><title>3D generations that run long now hand back a handle instead of an error</title><link>https://three.ws/docs/mcp-studio</link>diff --git a/public/features.json b/public/features.jsonindex 58422d407..f44fe53e6 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-27T23:29:26.333Z",+ "generated_at": "2026-07-28T01:50:53.698Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/gcp-triage.mjs b/scripts/gcp-triage.mjsindex 303e3f36f..72fc1b380 100644--- a/scripts/gcp-triage.mjs+++ b/scripts/gcp-triage.mjs@@ -97,6 +97,12 @@ const KNOWN_SIGNATURES = [class: 'self-healing',action: `Forge lane failover fired; generation keeps succeeding on the next rung. Tied to Replicate credit if you want the paid lane back. ${RUNBOOK} §forge.`,},+ {+ id: 'hf-hub-rate-limited',+ match: /We had to rate limit your IP|429 Client Error: Too Many Requests for url: https:\/\/huggingface\.co|LocalEntryNotFoundError/i,+ class: 'env-action',+ action: `A model worker fetched weights from huggingface.co at startup and HF rate-limited the Cloud Run egress IP, so the container never listened and Cloud Run killed the revision (crash loop). Anonymous HF pulls are per-IP capped and Cloud Run IPs are shared — never depend on a live HF fetch at boot. Fix (config-only, pre-approved): stage the needed files into the HF cache layout under gs://three-ws-model-weights/hf-cache/hub/models--<org>--<repo>/{refs/main,snapshots/<sha>/...} (the weights bucket is already gcsfuse-mounted at /weights), then gcloud run services update <service> --region us-central1 --update-env-vars HF_HOME=/weights/hf-cache,HF_HUB_OFFLINE=1,HUGGING_FACE_HUB_TOKEN=<HF_TOKEN from .env>. Note the token env var: the pinned huggingface_hub reads the LEGACY name HUGGING_FACE_HUB_TOKEN, so setting HF_TOKEN alone changes nothing. 2026-07-28 case: model-triposr, facebook/dino-vitb16 config.json. ${RUNBOOK} §hf-hub-rate-limited.`,+ },{id: 'sns-name-not-found',match: /Invalid name account provided/i,@@ -132,11 +138,24 @@ const KNOWN_HTTP_SIGNATURES = [},{id: 'x402-wallets-dry-5xx',+ // The ring calls its own paid routes under several user agents, not just+ // the autonomous/seed drivers: persona agents ride "threews-ring-agent/+ // <persona>" (api/_lib/x402/agents/persona-kit.js), plus the wallet+ // monitor and thumbnail regen pipelines. Matching only two of them left+ // the rest landing in `investigate` every sweep with the same root cause+ // (2026-07-28: /api/x402/club-cover from threews-ring-agent/agora-citizen).+ // Any "threews-*" agent is the platform paying itself — one signature.test: (g) => g.status >= 500 && (g.path.startsWith('/api/x402') || g.path === '/api/mcp')- && /threews-x402-(autonomous|seed)/.test(g.userAgent),+ && /^threews-/.test(g.userAgent),class: 'owner',action: `5xx on paid x402 routes from the platform's own agent traffic means the economy wallets are out of SOL for tx fees (symptom map: 502 = fee wallet below SOL floor, 503 = payer self-pay refused). The economy-rebalance keypair crash is FIXED and LIVE (commit bb02839f9); when it reports skipped: "insufficient_sol_surplus" there is genuinely nothing left to swap. At the 94-calls/min ring shape the burn is ~1-1.4 SOL/day. Owner action: send SOL (or USDC) to the economy master WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW; treasury-topup distributes to engines within minutes and economy-rebalance restores the payer's USDC float. Verify recovery: POST /api/cron/economy-rebalance (Bearer CRON_SECRET) returns results[].status "swapped", healthz x402_settle returns to ok, 5xx storm stops. Alternative to daily funding: throttle the ring to funded runway (X402_RING_TICK_CONCURRENCY and cadence knobs). ${RUNBOOK} §x402-wallets-dry.`,},+ {+ id: 'coingecko-quota-exhausted-502',+ test: (g) => g.status === 502 && g.path.startsWith('/api/coin/'),+ class: 'env-action',+ action: `502 on a /api/coin/* route means every CoinGecko rung failed and no cached last-good existed. The usual cause is the DEMO KEY, not the upstream: the demo tier caps at 10,000 calls per MONTH, and once exhausted every request carrying COINGECKO_API_KEY gets 429 while the identical keyless request is still served (2026-07-28: /coin/detail, /tickers and /exchange all 502'd for hours on an exhausted key). Confirm in one call: curl -s -H "x-cg-demo-api-key: $KEY" https://api.coingecko.com/api/v3/key — error_code 10006 is the cap. geckoFetch now benches a rejected key for 15 min and retries keyless on its own, so a lingering 502 means the keyless tier is ALSO throttled (the Cloud Run egress IP is shared). Fix: gcloud run services update three-ws-api --region us-central1 --remove-env-vars COINGECKO_API_KEY (config-only, pre-approved) to stop paying the round trip, and tell the owner the key needs a paid tier or a monthly reset. ${RUNBOOK} §coingecko-quota-exhausted.`,+ },{id: 'cc-unconfigured-503',// Every /api/community/* and /api/clash route wraps the same client anddiff --git a/tests/coingecko-key-health.test.js b/tests/coingecko-key-health.test.jsnew file mode 100644index 000000000..1cfe8d37e--- /dev/null+++ b/tests/coingecko-key-health.test.js@@ -0,0 +1,108 @@+/**+ * CoinGecko demo-key health — unit tests.+ *+ * The demo tier caps at 10,000 calls per MONTH. When that cap is hit every+ * request carrying the key comes back 429 for the rest of the billing period,+ * while the identical request WITHOUT the key is still served by the keyless+ * public tier. On 2026-07-28 that took every /api/coin/detail, /tickers and+ * /exchange call to a 502 for hours.+ *+ * These tests pin the recovery contract: a keyed rejection benches the key,+ * retries the same URL keyless, and later calls skip the key until the cooldown+ * expires — so a monthly reset heals with no redeploy and no human.+ */++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ geckoFetch,+ geckoHeaders,+ isGeckoKeyBenched,+ resetGeckoKeyHealth,+} from '../api/_lib/coingecko.js';++const KEY = 'CG-test-key';+const jsonResponse = (body, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });++// The demo-tier quota-exhausted reply, verbatim in shape.+const quotaExhausted = () =>+ jsonResponse({ status: { error_code: 10006, error_message: "You've reached 10,000 calls limit." } }, 429);++let calls;++beforeEach(() => {+ resetGeckoKeyHealth();+ process.env.COINGECKO_API_KEY = KEY;+ calls = [];+ vi.stubGlobal('fetch', vi.fn(async (url, init) => {+ calls.push({ url: String(url), key: init?.headers?.['x-cg-demo-api-key'] ?? null });+ return calls.at(-1).key ? quotaExhausted() : jsonResponse({ id: 'coin-a' });+ }));+});++afterEach(() => {+ vi.unstubAllGlobals();+ resetGeckoKeyHealth();+ delete process.env.COINGECKO_API_KEY;+});++describe('geckoHeaders', () => {+ it('attaches the demo key when one is configured and healthy', () => {+ expect(geckoHeaders()['x-cg-demo-api-key']).toBe(KEY);+ });++ it('omits the key when explicitly asked for the keyless tier', () => {+ expect(geckoHeaders(false)['x-cg-demo-api-key']).toBeUndefined();+ });++ it('omits the key when none is configured', () => {+ delete process.env.COINGECKO_API_KEY;+ expect(geckoHeaders()['x-cg-demo-api-key']).toBeUndefined();+ });++ it('always carries the accept + user-agent identity headers', () => {+ expect(geckoHeaders()).toMatchObject({ accept: 'application/json', 'user-agent': 'three.ws/1.0' });+ });+});++describe('geckoFetch demo-key failover', () => {+ it('retries keyless and serves the live payload when the keyed call is 429d', async () => {+ const value = await geckoFetch('/coins/kh-live', { ttlMs: 0 });+ expect(value).toEqual({ id: 'coin-a' });+ expect(calls.map((c) => c.key)).toEqual([KEY, null]);+ });++ it('benches the key so the next call goes out keyless on the first try', async () => {+ await geckoFetch('/coins/kh-bench-a', { ttlMs: 0 });+ expect(isGeckoKeyBenched()).toBe(true);+ calls.length = 0;+ await geckoFetch('/coins/kh-bench-b', { ttlMs: 0 });+ expect(calls.map((c) => c.key)).toEqual([null]);+ });++ it('benches on a revoked key (401/403), not only on quota exhaustion', async () => {+ vi.stubGlobal('fetch', vi.fn(async (url, init) => {+ calls.push({ url: String(url), key: init?.headers?.['x-cg-demo-api-key'] ?? null });+ return calls.at(-1).key ? jsonResponse({ error: 'unauthorized' }, 401) : jsonResponse({ id: 'coin-a' });+ }));+ await geckoFetch('/coins/kh-revoked', { ttlMs: 0 });+ expect(isGeckoKeyBenched()).toBe(true);+ });++ it('leaves the key alone when a keyed call succeeds', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ id: 'coin-a' })));+ await geckoFetch('/coins/kh-healthy', { ttlMs: 0 });+ expect(isGeckoKeyBenched()).toBe(false);+ });++ it('does not bench on a 404 — an unknown coin is not a key fault', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'coin not found' }, 404)));+ await expect(geckoFetch('/coins/kh-unknown', { ttlMs: 0 })).rejects.toMatchObject({ status: 404 });+ expect(isGeckoKeyBenched()).toBe(false);+ });++ it('surfaces the original status when the keyless retry also fails', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => quotaExhausted()));+ await expect(geckoFetch('/coins/kh-both-down', { ttlMs: 0 })).rejects.toMatchObject({ status: 429 });+ });+});