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(fact-check): degraded checks return sources instead of timing out

nirholas03dabea4d120
diff --git a/api/x402/fact-check.js b/api/x402/fact-check.js
index e3a45c908..345e77c0a 100644
--- a/api/x402/fact-check.js
+++ b/api/x402/fact-check.js
@@ -339,6 +339,11 @@ async function runFactCheck(claim, strictness, imageUrl = null) {
.digest('hex');
const result = { verdict, confidence, claim, strictness, sources, costBreakdown, attestation };
+ // A degraded check still returns real sources, but it did not get the full
+ // chain — say so on the response rather than letting an `insufficient`
+ // verdict read as "we checked and the evidence was thin". checkClaim() also
+ // reads this to keep the result out of the 7-day cache.
+ if (degradations.length) result.degraded = degradations;
// Surface the image analysis separately so a caller sees what the vision lane
// read from the attachment (description, transcribed text, stance) without
// digging it out of the weighted source list.
@@ -365,7 +370,12 @@ async function checkClaim(claim, strictness, imageUrl) {
return { ...cached, cachedAt: cached.cachedAt || new Date().toISOString() };
}
const result = await runFactCheck(claim, strictness, imageUrl);
- await redisSet(key, result, CACHE_TTL_SECONDS);
+ // Never cache a degraded check. It is a snapshot of a provider outage, not of
+ // the claim: caching it would pin an `insufficient` verdict on a perfectly
+ // checkable claim for seven days and serve that to every later caller,
+ // including the paid lane. Skipping the write costs one re-run and keeps the
+ // cache holding only full-chain answers.
+ if (!result.degraded) await redisSet(key, result, CACHE_TTL_SECONDS);
return result;
}
diff --git a/docs/api-reference.md b/docs/api-reference.md
index f2975c924..b8b90f8b5 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -609,6 +609,20 @@ POST /api/llm/anthropic?agent=<agent_id>
Older single-provider proxy. Request/response shape matches the [Anthropic Messages API](https://docs.anthropic.com/en/api/messages) exactly. New integrations should use `/api/brain/chat` instead — it supports more providers and emits richer events.
+**Request normalisation.** Model generations disagree about which request fields they accept, and sending the wrong one returns a hard `400` from the upstream. Rather than surface that to an embed, the proxy adapts the body to the model it is about to call:
+
+| Field you send | What happens |
+|---|---|
+| `temperature` | Dropped for Opus 4.7 and the Claude 5 family, which reject sampling parameters. Passed through unchanged for every other model. |
+| `thinking: {type:"enabled", budget_tokens:N}` | Rewritten to `{type:"adaptive"}` — the token-budget form was removed in the current generation. |
+| `thinking: {type:"disabled"}` | Dropped for Fable/Mythos 5, where thinking is always on and an explicit config is rejected. |
+| `max_tokens` below 4096 | Raised to 4096 on models that think by default. Their `max_tokens` covers reasoning *and* visible text, so a tight cap can be spent entirely on reasoning and return an empty reply. A budget already above the floor is never lowered. |
+| `system` (long, plain string) | Given a prompt-cache breakpoint, so repeat turns re-read the prefix at roughly a tenth of the input price. The length required to qualify differs per model; below it the prompt is sent unchanged. Pass `system` as a block array yourself to control placement, and the proxy leaves it alone. |
+
+Your original body is never mutated, and none of this changes the response shape.
+
+**Usage accounting.** When a response is served from the prompt cache, Anthropic reports `usage.input_tokens` as the *uncached remainder only*, with the rest split across `cache_read_input_tokens` and `cache_creation_input_tokens`. The `input_tokens` figure recorded against your agent's monthly budget is the sum of all three, so a cached turn still counts the full prompt it sent.
+
---
## TTS API
@@ -1564,6 +1578,28 @@ exhausted, or immediately if the request carries an `X-PAYMENT` header. Marked
identical `{ claim, strictness, imageUrl }` within 7 days replays the cached
verdict on either lane (adds `cachedAt`) rather than re-running the chain.
+**`degraded` — when the check ran on less than the full chain.** Every live
+check has a wall-clock budget (45s by default, `FACT_CHECK_BUDGET_MS`) and each
+stage gets what is left of it. If query generation or stance extraction cannot
+reach a language-model provider inside that budget, the stage falls back rather
+than failing the request: query generation searches the claim text itself, and
+stance extraction marks every source `neutral`, which scores as `insufficient`.
+You still get the real sources and their excerpts. When that happens the
+response carries a `degraded` array naming each stage that fell back:
+
+```json
+{
+ "verdict": "insufficient",
+ "confidence": 0.3,
+ "sources": [ "…real sources, real excerpts…" ],
+ "degraded": ["stance extraction unavailable: all providers exhausted"]
+}
+```
+
+Treat `degraded` as "re-run this later", not as a judgement about the claim: a
+degraded result is deliberately **not** written to the 7-day cache, so the next
+request re-runs the full chain. Absence of the field means the full chain ran.
+
**Example**
```bash
diff --git a/tests/fact-check-degradation.test.js b/tests/fact-check-degradation.test.js
new file mode 100644
index 000000000..00d62ce94
--- /dev/null
+++ b/tests/fact-check-degradation.test.js
@@ -0,0 +1,154 @@
+// The fact-checker's degradation contract.
+//
+// Both LLM stages ship a designed fallback (search the claim itself; mark every
+// stance neutral). Those fallbacks used to be reachable ONLY when a provider
+// returned unparseable text — when the provider chain itself failed or ran out
+// of budget, the error propagated out of the stage and killed the whole check,
+// so the request that most needed the fallback was the one that never got it.
+// Production saw that as 40-60s hangs ending in a 502 carrying nothing, on
+// claims the pipeline already had real sources for.
+//
+// These tests pin the repaired behaviour: a stage that cannot reach a provider
+// degrades, reports that it degraded, and lets the check finish.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const llmComplete = vi.fn();
+vi.mock('../api/_lib/llm.js', () => ({ llmComplete: (...a) => llmComplete(...a) }));
+
+const { generateSearchQueries, analyzeResults } = await import(
+ '../agents/fact-checker/src/llm-verdict.js'
+);
+const { searchAll } = await import('../agents/fact-checker/src/search-sources.js');
+
+const RESULTS = [
+ { url: 'https://en.wikipedia.org/wiki/Eiffel_Tower', title: 'Eiffel Tower', snippet: 'A tower in Paris.' },
+ { url: 'https://www.britannica.com/topic/Eiffel-Tower', title: 'Eiffel Tower', snippet: 'Paris landmark.' },
+];
+
+beforeEach(() => {
+ llmComplete.mockReset();
+});
+
+describe('generateSearchQueries degradation', () => {
+ it('falls back to the claim itself when every provider fails', async () => {
+ llmComplete.mockRejectedValue(
+ Object.assign(new Error('openai 429: billing_not_active'), { status: 502 }),
+ );
+ const claim = 'The Eiffel Tower is located in Paris, France.';
+
+ const out = await generateSearchQueries(claim);
+
+ expect(out.queries).toEqual([claim]);
+ expect(out.tokens).toBe(0);
+ expect(out.degraded).toMatch(/query generation unavailable/i);
+ });
+
+ it('does not start a provider turn it has no budget to finish', async () => {
+ llmComplete.mockResolvedValue({ text: '["a","b","c"]', usage: { input: 1, output: 1 } });
+
+ const out = await generateSearchQueries('A claim about something', { budgetMs: 200 });
+
+ expect(llmComplete).not.toHaveBeenCalled();
+ expect(out.degraded).toMatch(/no budget/i);
+ expect(out.queries).toEqual(['A claim about something']);
+ });
+
+ it('passes the caller budget through as the chain timeout', async () => {
+ llmComplete.mockResolvedValue({ text: '["one","two","three"]', usage: { input: 5, output: 5 } });
+
+ const out = await generateSearchQueries('A claim', { budgetMs: 9_000 });
+
+ expect(llmComplete).toHaveBeenCalledWith(expect.objectContaining({ timeoutMs: 9_000 }));
+ expect(out.queries).toEqual(['one', 'two', 'three']);
+ expect(out.degraded).toBeUndefined();
+ });
+});
+
+describe('analyzeResults degradation', () => {
+ it('marks every stance neutral when every provider fails', async () => {
+ llmComplete.mockRejectedValue(new Error('all providers exhausted'));
+
+ const out = await analyzeResults('some claim', RESULTS);
+
+ expect(out.analyses).toHaveLength(RESULTS.length);
+ expect(out.analyses.every((a) => a.stance === 'neutral')).toBe(true);
+ expect(out.tokens).toBe(0);
+ expect(out.degraded).toMatch(/stance extraction unavailable/i);
+ });
+
+ it('still parses a healthy provider response without flagging degradation', async () => {
+ llmComplete.mockResolvedValue({
+ text: '[{"excerpt":"A tower in Paris","stance":"supports"},{"excerpt":"Paris landmark","stance":"supports"}]',
+ usage: { input: 100, output: 20 },
+ });
+
+ const out = await analyzeResults('some claim', RESULTS);
+
+ expect(out.analyses.map((a) => a.stance)).toEqual(['supports', 'supports']);
+ expect(out.degraded).toBeUndefined();
+ expect(out.tokens).toBe(120);
+ });
+});
+
+// The search chain is driven entirely through fetch, so stubbing fetch controls
+// every rung (Wikipedia and DuckDuckGo are the keyless fallbacks that run when
+// no provider key and no Vertex project are configured, which is the shape these
+// tests pin).
+describe('searchAll deadline', () => {
+ const realFetch = globalThis.fetch;
+ const realEnv = { ...process.env };
+
+ beforeEach(() => {
+ for (const k of ['BRAVE_API_KEY', 'TAVILY_API_KEY', 'EXA_API_KEY', 'SERPER_API_KEY', 'GOOGLE_CLOUD_PROJECT']) {
+ delete process.env[k];
+ }
+ });
+
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ process.env = { ...realEnv };
+ });
+
+ const wikiPayload = (title) => ({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ query: { pages: { 1: { index: 1, title, extract: `${title} is a real thing described here.` } } },
+ }),
+ });
+
+ it('gives up on a stalled query instead of holding the sweep open', async () => {
+ // Every rung hangs. Before the budget existed this sat until the edge cut
+ // the request off at 60s and the caller got a 502 carrying nothing.
+ globalThis.fetch = vi.fn(() => new Promise(() => {}));
+
+ const started = Date.now();
+ const out = await searchAll(['q1', 'q2'], { budgetMs: 150 });
+ const elapsed = Date.now() - started;
+
+ expect(out).toEqual([]);
+ expect(elapsed).toBeLessThan(3_000);
+ });
+
+ it('keeps evidence from the queries that did answer in time', async () => {
+ globalThis.fetch = vi.fn((url) =>
+ String(url).includes('fast')
+ ? Promise.resolve(wikiPayload('Fast Result'))
+ : new Promise(() => {}),
+ );
+
+ const out = await searchAll(['fast', 'slow'], { budgetMs: 200 });
+
+ expect(out).toHaveLength(1);
+ expect(out[0].title).toBe('Fast Result');
+ });
+
+ it('returns full results when the sweep finishes inside the budget', async () => {
+ globalThis.fetch = vi.fn(() => Promise.resolve(wikiPayload('Prompt Result')));
+
+ const out = await searchAll(['q1'], { budgetMs: 5_000 });
+
+ expect(out).toHaveLength(1);
+ expect(out[0].title).toBe('Prompt Result');
+ });
+});