A pasted chat in OrangeCat's article brief returned "Invalid request": the
route capped the topic at 300 characters and answered with a bare phrase.
- fitPromptText: keeps a brief whole up to PROMPT_TEXT_MAX_CHARS (12k),
otherwise keeps start and end around a "characters left out" marker.
- explainInputIssues: turns zod-shaped issues into sentences that name the
field, its length, the limit and the fix; never a bare "Invalid request".
Claude-Session: https://claude.ai/code/session_019MDtmsN9mz8QfGDCrNhY9p
Co-authored-by: Claude <noreply@anthropic.com>
PRICE_LIST names each paid model's USD per 1M tokens and the page it was read
from (2026-11-15). summariseUsage tallies gain costUSD for the server's paid
answered calls and unpriced for those it cannot price, never counted as zero.
Claude-Session: https://claude.ai/code/session_019MDtmtUQb9BM11ycpApwGq
Co-authored-by: Claude <noreply@anthropic.com>
WalkOptions.feature / CompleteOptions.feature is written beside the app; the
summary groups each app's calls by it. Solon spent Groq's whole free day
before 09:10 UTC on 14 Nov with nobody using any app, and the log could say
which app but not what for. CompleteOptions.app is now typed as well.
Claude-Session: https://claude.ai/code/session_019MDtmtUQb9BM11ycpApwGq
Co-authored-by: Claude <noreply@anthropic.com>
1.27.0 wrote only where AI_USAGE_DIR was exported; apps whose launch script
predates it wrote nothing. usageDir() falls back to /opt/fleet/ai-usage when
it exists; AI_USAGE_DIR=off writes nowhere. Release 1.28.0.
Claude-Session: https://claude.ai/code/session_019MDtmtUQb9BM11ycpApwGq
Co-authored-by: Claude <noreply@anthropic.com>
About $567 went to Google on 10-11 Nov 2026 and nobody could say which app
spent it, on what, or when: each app counted its own calls in its own
process, or not at all.
The chain walk now reports every link it touches (app, vendor, model;
served, failed with status and kind, or refused with the spend rule; tokens
and time when known; never content). With AI_USAGE_DIR set the event is
appended to <dir>/<UTC day>.jsonl through process.getBuiltinModule, so the
package root stays importable in a browser bundle. readUsageDay and
summariseUsage give the per-vendor and per-app picture.
test/usage-log.test.js: the three outcomes from a real walk, the file sink,
null for could-not-look, torn lines, a throwing sink, the summary.
Claude-Session: https://claude.ai/code/session_019MDtmtUQb9BM11ycpApwGq
Co-authored-by: Claude <noreply@anthropic.com>
freeChain() put Google's Gemini API second, on a fleet-wide GEMINI_API_KEY
described as a free per-project tier. The project had billing; every app on
the box fell through to it whenever Groq's pool was spent, about $567 on
10-11 Nov 2026. Google is not in the chain any more; it bills.
- freeChain(): Groq, then OpenRouter :free. visionProviders() loses the
Google seat; the free vision left is OpenRouter's :free Gemma id.
- spend: a provider is paid when marked so or when it is Google's Gemini
API, xAI, Anthropic or OpenAI (by host or key name, also prefixed). A
reader's own key is never paid by us.
- AI_PAID_DISABLED is on when unset; AI_PAID_OK / {PREFIX}_AI_PAID_OK opts an
app in. usableChain() drops paid providers unless allowed.
- Daily caps (UTC): fleet 90 calls / 120,000 in / 60,000 out; per-app rows
(about 60% of the fleet named), aliases, unknown apps 1 / 800 / 400, no-AI
apps 0; xAI 0 until opted in, then 2 / 2,000 / 1,000; a 5,000-call free
loop guard. Env overrides per prefix. A reached cap throws SpendLimitError
("limit reached") and never walks onto another paid vendor.
- images: every paid transport, the gemini one included, is gated the same
way; ownKey for a person's own key.
- README, docs/providers.md and CHANGELOG say plainly that Google bills.
Tests: test/spend.test.js (kill switch on/off/missing, no xAI or Google
link without opt-in, caps and headroom, aliases, unknown app, env
overrides, cap hit without walking to another paid vendor, fleet cap,
token cap, BYOK past spent caps, free loop guard); chain, images and vision
tests updated. 425 pass.
* feat(web): keyless fallback backends for when every configured one is down
A self-hosted SearXNG is refused by upstream engines from time to time;
without a paid key the chain then has nothing left, and every app on the
box says it could not look (seen on Substrata, 2026-11-11 to -12).
- gdeltProvider: GDELT DOC 2.0 news search, keyless. Paced to one request
every five seconds per process (GDELT's own ask); a call that cannot wait
its turn fails as rate_limited without being sent. Its plain-text refusals
are typed failures, never empty results.
- wikipediaProvider: one Wikipedia edition's search, keyless, no invented
date (the API's timestamp is the last edit).
- keylessProviders() and withKeylessFallback(env): one call to opt in.
defaultProviders is unchanged.
- A provider may declare coverage: "partial"; a partial index answering
empty never turns a search into "nothing".
Version 1.25.0.
Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8
* fix(web): keyless providers, from review
- GDELT query: OR and the parentheses grouping it are kept; a short
acronym ("AI", "EU") is joined to its neighbour as a phrase instead of
dropped; lower-case function words go; CJK words are quoted; unbalanced
quotes are removed.
- GDELT: a non-object body or row is bad_response, not "unreachable"; a
non-finite or negative interval falls back to 5 s instead of corrupting
the shared pacing; a call left with under a second is not sent.
- Wikipedia: a site naming an edition searches that edition; edition codes
such as "simple" and "zh-yue" are honoured and an unknown hint falls back
to the configured edition; a MediaWiki error in a 200 body is a failure,
never an empty search.
Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8
---------
Co-authored-by: Claude <noreply@anthropic.com>
The fleet's products already serve MCP (OrangeCat's and Loki's /api/mcp),
and the next thing every one of them wants is to call one: a bot on
OrangeCat asking Loki as the person, a product reaching a vendor's server
with the person's token. Each would write the same forty lines of JSON-RPC
over Streamable HTTP, and each would get one of the two response shapes
wrong (a server may answer a POST with JSON or with an SSE stream, per
request). So the client lives here, once.
@bitbaum/ai-kit/mcp: McpClient (initialize once with the session id carried,
tools/list, tools/call, both response shapes read the same way, a tool
error as data and a JSON-RPC error as McpError), toolDefinitionsFrom (the
server's tools in the shape complete() takes). No OAuth flow, no stdio, no
resources or prompts until a caller needs them. Tests against a fake server
in both answer shapes, plus the failed-handshake path.
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et
Co-authored-by: Claude <noreply@anthropic.com>
* feat(usage): what the budget numbers mean, defined once (1.21.0)
Loki's Settings → AI and OrangeCat's /settings/usage each grew the half a
meter leaves out — does today's pace last, the week, when it refills, what
the assistant still reads, levers with their consequence — separately, in
October 2026, with the same rules and slightly different sentences. The
product-neutral half moves here so the next app starts with it:
- paceForecast / paceLine: lasts the day, or runs out at "12:00 UTC"; silent
before there is a rate (PACE_MIN_USED, PACE_MIN_DAY_FRACTION, or minUsed).
- weekSummary: total, active days, days the cap was reached; null for an
empty or unreadable week, never "0".
- refillsIn: "in 4 hours", "in under a minute", "now", or null — never a
guessed time.
- admissionsLeft: answers a remainder buys, counted the way a gate admits
(one at the estimate, then per measured answer), not a bare division.
- historyWindowLine: what the assistant still reads of a conversation.
- countOf, clockAt, nextUtcMidnight; UsageAction / UsageExplanation types;
UTC_RESET_EXPLANATION.
Numbers go through the caller's formatter so a page never groups digits two
ways. Plan names, prices and which levers are open stay in each app.
Additive: minor release.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015QRNwA4BorkdoSCd8j5Xvu
* fix(usage): the reset sentence claims only what the counter does
UTC_RESET_EXPLANATION gave a reason — "that is when the model providers'
free allowances refill" — which is false of Groq, whose limits refill on a
rolling clock. OrangeCat's usage page had shipped the same reason and took
it back in bitbaum/orangecat#1318; a shared sentence that is wrong is wrong
in every app at once, so it now states only that the count is kept per UTC
day. weekSummary and the README also say the other #1318 lesson: seven rows
ending today are "last 7 days", not "this week".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015QRNwA4BorkdoSCd8j5Xvu
* refactor(usage): utcResetExplanation(unit) instead of a fixed sentence
OrangeCat counts messages and Loki a share; "Unused allowance does not roll
over" was right for neither. The reset is now utcResetExplanation("messages")
→ "Unused messages don't roll over.", defaulting to "allowance". Still claims
only what the counter does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015QRNwA4BorkdoSCd8j5Xvu
* test(usage): countOf's formatter test no longer depends on ICU data
CI (Node 24) groups de-CH with ' and this sandbox (Node 22) with ’, so the
test asserted a runtime's locale data rather than that countOf uses the
formatter it is given. It now passes a formatter with no locale behind it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015QRNwA4BorkdoSCd8j5Xvu
---------
Co-authored-by: Claude <noreply@anthropic.com>
Probed 2026-10-02: on gemini-flash-latest the default spends ~500 hidden
reasoning tokens out of max_tokens (Substrata answers cut mid-word at ~550
visible tokens of 2400) and 4.1 s vs 2.5 s per answer turn. reasoning_effort
low removes them. Not sent to flash-lite (low turns its thinking ON) or
gemma (refused).
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Heidi defined its Groq Whisper chain and its silence denylist in its own
lib; Loki has copies; Substrata had none, so its microphone had no server
leg. ai-kit owns the chains: this is the dictation one, beside freeChain,
with the guard against Whisper's silence artefacts ('Untertitelung des
ZDF', 'Amen.') typing words nobody said.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Gemini's OpenAI-compatible stream sends parallel tool calls with no
'index' and their own ids. Keyed on index alone they were glued into one
call whose arguments ({"query":"Russia"}{"kind":"country"}) parsed to
nothing, so every call ran with empty arguments — seen live in
Substrata's Ask. A new id on a slot that already holds a named call now
starts a new call, and glued argument objects are split back as a last
line of defence. Two tests, both failing on the old assembly.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
heidi's Swiss German pages passed their locale, gsw, as the language hint.
Groq answered 400 'unsupported language: gsw' on every link, and the
microphone said dictation did not work in this browser. Romansh (rm) failed
the same way. whisperLanguage() maps a tag or locale to a hint Whisper
accepts: gsw -> de, de-CH -> de, unknown -> none (auto-detect).
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
byokChain links share their provider id with the deployment's link to the same
vendor (groq is groq), and every shared ledger in this package keys on it. So:
- Provider.byok marks an own-key link (set by byokChain).
- dayCapacityTokens never counts it, even with a *_DAILY_TOKENS override.
- createLinkCooldown never cools a link because of it — one reader's
exhausted personal quota used to cool groq/<model> for everybody.
- tryChain / walkChain / completeStream record no health for it: one reader's
bad key says nothing about whether the site's AI works.
- Quota readings about it carry byok: true, so an app's store can skip them.
- dailyTokens is 0, not Infinity: a caller summing it by hand adds nothing.
- New exports: isOwnKeyLink(link), healthFor(chain, health).
No live app was exposed (checked loki, substrata, heidi, orangecat, evig,
petvity: none fed an own-key chain into capacity); this closes the trap for
the next one. Each guard mutation-checked.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The moment a reader pastes a key, a settings screen needs two answers: does
it work, and which models can it reach — so it can preselect the best one
instead of showing a text box and failing in the chat later. OrangeCat
answered the first and threw the second away; Loki had neither.
probeByokKey checks a key the way each vendor checks keys, verified against
the live endpoints on 2026-09-25:
- OpenRouter's /models is a public catalogue that answers 200 to a FAKE key,
so its key is checked at /key.
- Anthropic's model list wants x-api-key plus a version header.
- Google and xAI reject a bad key with 400, not 401 — any non-2xx fails,
in the vendor's own words, with the key masked if the vendor echoes it.
- An unreachable vendor is "couldn't check", never "your key is wrong".
The suggestion names no model (the newest ids that day were
claude-opus-5.5, gpt-6-luna-pro, grok-4.7 — none of which this package had
seen). It is the newest model in the strongest tier the key can use: tier
from the name, age from the vendor's dates or, where there are none
(Google), from the version in the name, with a vendor's -latest alias as
newest; speed variants never on top; a router's frontier-lab namespaces
first. Run live against real Groq, Gemini and OpenRouter keys it suggests
gpt-oss-120b, gemini-pro-latest and anthropic/claude-opus-5.5.
readCatalog is the one GET behind fetchCatalog, keeping the status and the
vendor's message that fetchCatalog deliberately collapses; ModelRecord gains
`created`. Additive: no existing export changes behaviour.
Claude-Session: https://claude.ai/code/session_016YJVAanfj8keVSXyZnTemh
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`transcribe({ words: true })` asks for `verbose_json` with word granularity
and returns normalised `words: [{ word, start, end }]`.
Why: Heidi measures HOW somebody spoke — speech rate, pauses between words,
length of run — and the text alone says which words, never when. The call
belongs here, not in Heidi: ai-kit owns every vendor request, and a second
hand-rolled Whisper call is the drift transcribe() was written to end.
The contract is absent-is-not-empty. `words` is omitted when timings were not
asked for or the vendor ignored the granularity ("not measured"), and is `[]`
only for a recording that was measured and contained nothing. A caller reading
absence as zero words would report a fluent speaker as silent. Missing timings
never fail the link — walking the chain would re-upload the audio to every
vendor for a nice-to-have. Impossible timings (end before start, NaN, empty
word) are dropped, not trusted.
Opt-in because dictation, the common caller, needs only the text and the
verbose body is several times larger. Proven by mutation: removing the
granularity request fails the request-shape test.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
timeoutMs bounds the whole stream, so it must allow for a long answer, and a
link that thinks silently or hangs was waited on for all of it. Measured on
substrata's Ask 2026-09-25: 38 s to first text behind OpenRouter links that
never produced a token. firstTokenMs aborts only the opening; once a token is
out, timeoutMs alone bounds the stream.
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
qwen/qwen3.6-27b left Groq's catalogue (listed 2026-09-25: gpt-oss-120b,
gpt-oss-20b, qwen3.8-27b) and 404'd on every Ask turn that reached it in
substrata's timing log. A 404 now also cools its link for an hour, so the next
rotted id costs one round trip per process-hour rather than one per turn.
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Measured on the box 2026-09-25 while substrata's Ask took 9-33s to its first
word:
- Groq meters its day PER MODEL: gpt-oss-20b refused "for model
`openai/gpt-oss-20b` ... TPD" while gpt-oss-120b served on the same key.
walkChain now condemns the vendor only for a daily refusal naming no model.
- Groq's "per day" is a rolling window: 20b refused at 00:14 and served at
00:17. The cooldown now honours the wait the refusal names, daily ones too;
UTC midnight is only the fallback. Before, one refusal kept the fastest link
out of a process for most of a day.
- reasoning: "light" sends reasoning_effort=low to Groq gpt-oss (first content
649ms -> 205ms on a 3k-token prompt). Only probed settings are listed.
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
classBudget + BACKGROUND_POLICY (max 25% of the day, never below a 50% floor)
+ estimateTokens. 1.13.0.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- ai-kit/byok: closed OpenAI-shaped vendor list (OpenRouter, OpenAI, Anthropic,
Gemini, Groq, Mistral, DeepSeek, xAI, Together, Cerebras), isByokConfig,
byokChain -> a one-link chain with a call-scoped env
- ai-kit/seal: AES-256-GCM sealSecret/openSecret (OrangeCat's scheme) for keys at rest
- createLinkCooldown: skip a link until its 429 resets (daily -> UTC midnight)
- 1.12.0
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`complete()` has forwarded `image_url` parts since the first release. What it
never did was CHOOSE a link for them — and `freeChain()` is ordered for text,
so a screenshot meets four Groq links that cannot read it before reaching one
that can. A blind model handed a picture does not fail usefully: it answers the
words around the image, fluently, about nothing.
Three products paid for that absence separately, in three repositories:
heidi had the users and REFUSED them — /api/chat returns 400 "Reading a
picture needs your own model", and byok.ts states as fact that "the
free chain has no model that can read a picture". Never true of
free models; true of a chain with no vision routing.
loki built a SECOND chain beside this one (config/vision-models.ts) and
it drifted immediately — never learned about Google, still carries
a dead Groq seat.
orangecat built the decision rule and had nobody to call it with. Its own
capability-gate reason string reads 'no caller sends images'.
The rule, the verified model list and the users existed; none could reach the
other two.
What lands:
- `Provider.visionModels` — which ids accept an image, populated from evidence
with the provenance stated beside each entry. Groq's empty list is a claim
(live-probed 2026-08-13: no vision model on this account); OpenRouter's
`google/gemma-4-26b-a4b-it:free` is the strong kind (probed live, answered
"Red" correctly); Google's three are declared-not-probed and say so.
- `src/vision.ts` — three verdicts, never two. A model in `models` but not in
`visionModels` is "no"; a model in NEITHER (env override, private
deployment, an id a user brought) is "unknown", and unknown is TRIED. Reading
silence as a denial is the inversion OrangeCat's ADR-0008 named, where the
stronger the model a user brings, the less the agent can do.
- `complete()` and `completeStream()` route on it through one shared helper, so
the two paths cannot disagree about which model can see — the same reason
they already share `walkChain`.
- `NoVisionLinkError`, thrown BEFORE any request when the whole chain is blind,
naming what it skipped. "No model here can see" and "every vendor failed"
need different answers and are indistinguishable once both arrive as
ChainExhaustedError; the first is knowable without spending a token.
- `scripts/probe-vision.mjs` (`pnpm run check:vision`) — a claim in a list is
worth what the last check was. Sends a real image, asks one word, and treats
HTTP 200 with EMPTY content as a failure: that is the shape loki found in
nemotron-nano-12b-v2-vl, and it reads as a successful analysis of a picture
nobody looked at.
`walkChain`'s chain resolution is extracted as `walkLinks` so the filter and
the walk resolve the same defaults once. Named `walkLinks`, not `resolveChain`
— that name is taken by resolve.ts, which answers a different question.
Inert for text: a plain turn returns the caller's own options object untouched
and costs one typeof per message. Pinned by a test, because breaking that would
break every text caller in the fleet.
301 tests pass, both directions pinned: a declared-blind model must never be
sent a picture, and an unclassified one must never be refused one.
Claude-Session: https://claude.ai/code/session_014RpRyAd15YvFmQ1c1p1Rsk
Co-authored-by: Claude <noreply@anthropic.com>
The registry has declared `kind: "transcribe"` since it was written, with
nothing behind it. This is the thing that was supposed to be behind it.
The fleet has three hand-rolled transcription clients — one in heidi, two in
loki — and not one of them has a chain, a fallback, a health tracker or
rate-limit classification. Each is a single vendor and a single key, so one
Groq blip takes dictation down in every app that has it, separately, with a
different error message each time. That is the exact shape this package exists
to stop being written a fourth time.
**The routing is not reimplemented.** `walkChain` already owns what a dead
vendor is, when a rejected key condemns a whole provider, and when to stop
walking — and there must be ONE answer to those questions or the fleet ends up
with two that disagree. `transcribe()` is a one-liner over it; only the request
differs, which is why the file is short.
To borrow the walk, `walkChain` now takes a named subset of what it actually
reads rather than `CompleteOptions`. `CompleteOptions` satisfies `WalkOptions`
structurally and did not change, so `complete()` and `completeStream()` are
untouched — the alternative was `transcribe()` faking a `messages` field to get
at the routing, or copying thirty lines of vendor-liveness logic.
Decisions the tests pin, each one a judgement a hand-rolled client got wrong:
- A DAILY 429 condemns the vendor and a capacity 429 does not — made by the
same `classifyRateLimit` the text path uses, not a second copy.
- An EMPTY transcript is an ANSWER. Silence genuinely transcribes to nothing,
and demoting it would re-upload the same audio to every vendor in the chain
to be told the same true thing, slowly and at the caller's expense.
- A 200 carrying no `text` field IS a failure — a success code over a body
that is not a transcript, which is the same call `complete` makes about
empty content.
- No `content-type` header is set by hand. `fetch` writes it from the
FormData including the multipart boundary; setting it manually omits the
boundary and every vendor answers 400 on a body it cannot split.
- Each link gets its own deadline rather than sharing the caller's signal,
for the reason `complete` documents: a vendor that accepts the connection
and never answers is the outage a fallback is least able to survive.
The MODELS stay the caller's. A chain of chat models is not a chain of
transcription models, and guessing one from the other is how an app ends up
POSTing audio at a text endpoint; `kind` in the registry is what an app builds
its chain from.
289 tests, 11 of them new.
Claude-Session: https://claude.ai/code/session_01FzYBD3sZroCAYeRgTYrpfT
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This package could not stream. `complete()` is request/response only, so every
app that wanted tokens to appear as they arrived used ai-kit to pick the model,
classify the 429 and track health — and then threw all of it away for the one
call that matters. Measured across the fleet on 2026-09-15: six hand-rolled
provider clients, four SSE readers, four emitters with divergent headers, under
~20,800 lines of chat UI in nine apps.
The duplication was real and it was in the wrong place. The apps were not
reinventing streaming because streaming is hard; they were reinventing it
because the package that owned the chain had no door for it.
ONE WALK, NOT TWO
`complete()` and `completeStream()` now share `walkChain`, extracted from
complete() unchanged. They must agree about what a dead vendor is, or the fleet
gets two answers to "is this provider out of budget" and the streaming path —
the one every chat surface uses — is the one that gets it wrong. complete()'s
existing suite is what proves the extraction was faithful; all 278 tests pass.
WHERE FALLBACK STOPS, AND WHY
A non-streaming walk can try every link because nothing has been shown yet. A
streaming walk cannot: once the first token is out, falling back would replay
the answer from the beginning into somebody already reading it. So the boundary
is explicit. Fails before the first delta -> LinkFailure, the walk continues.
Fails after -> StreamInterrupted, carrying the partial text, no silent recovery,
because there is no honest one.
That is also why a link is "served" only once a first token is really out. A 200
that then says nothing demotes, which is the same judgement complete() already
makes about an empty completion.
THE BUG THIS ENDS
ai-kit/sse carries both ends of the wire, lifted from loki, which had them
right. The reader KEEPS THE REMAINDER between chunks. A ReadableStream chunk is
a TCP-sized slice ending wherever the network put the boundary — routinely
mid-frame. Two apps split each chunk on newlines and dropped whatever straddled
it: a word vanishes from a long answer under load, nobody reports it, nobody can
reproduce it, and every short test passes.
12 new tests, choosing their own chunk boundaries because the boundaries ARE the
bug — including a frame cut mid-JSON and a chunk cut inside a two-byte "ü".
Proven by mutation: reintroducing the shipped `split` with no remainder turns
the suite red.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The free chain had two vendors and both are shared. Groq's daily TOKEN pool is
org-wide and OpenRouter's 50 requests a day are account-wide, so on a box where
several apps hold the same key they share the exhaustion too. A Google project
is per-app, which is the property being bought here — not the model.
Nothing below rests on an inference. Verified with a real key 2026-09-15:
GET /v1beta/openai/models -> 200, 56 models
POST /v1beta/openai/chat/completions
models/gemini-flash-latest -> NATIVE tool_call {"city":"Zurich"}
models/gemini-flash-lite-latest -> NATIVE tool_call
models/gemma-4-31b-it -> NATIVE tool_call
plain completion -> non-empty, finish=stop
THE 404 WAS AUTH, NOT ABSENCE. A consumer wrote this vendor off on the reasoning
that "the compat layer likely serves /chat/completions without a catalogue, so
its ids could never be rot-checked". That came from an UNKEYED 404 on
/v1beta/openai/models; with a key the same path answers 200. An unkeyed probe
cannot separate "absent" from "hidden behind auth" in either direction — the
same blind spot that let a paid vendor in elsewhere on a 403.
THE `models/` PREFIX IS LOAD-BEARING. The catalogue lists all 56 ids prefixed,
with no bare form anywhere, while /chat/completions accepts both (checked across
max_tokens 64/256/1024 — identical answers). A bare id therefore serves
perfectly AND is reported missing by checkCatalog on every run: a permanent
false rot alarm about a working model, which is worse than no alarm because it
teaches the reader to ignore the one that matters. Pinned by a test.
ALIASES, NOT VERSIONS. `-latest` is repointed by Google as the model behind it
retires — the property that makes `openrouter/free` the most durable entry in
the list. Not theoretical: `gemini-2.5-flash`, the id reached for from memory
while writing this, is already refused for new accounts with "no longer
available to new users, please update your code to use models/gemini-3.6-flash".
`gemma-4-31b-it` sits last and earns its place differently: Google's pricing
gives it a free column and no paid one, so it is the single id here that cannot
be quietly reclassified as billable.
ORDERING IS CAPACITY, NOT PREFERENCE. Google sits before OpenRouter for the same
reason Groq does: OpenRouter's unpaid tier is the scarcest pool in the chain, so
it is drained last. Now pinned by a test, since it was previously only a comment.
`dailyTokens: 50_000` is a deliberate under-estimate, not a figure. Google
publishes no fixed free-tier table — limits are per project, shown in AI Studio
— and no rate-limit headers come back on a completion either. Per this field's
contract, estimating high is what produces the wall the rationing exists to
prevent.
Also fixes a test that only worked while the chain had exactly two vendors: it
hard-coded two key names and compared against the sum over EVERY provider. It
now derives keys from the chain, and gains the assertion that only became
possible with a third vendor — that a keyed SUBSET contributes exactly its own
capacity.
The free-tier trade, for consumers to weigh: Google's free tier states content
is used to improve its products; the paid tier states the opposite. This is the
second-to-last link, reached only when the pools above it are spent.
266 tests pass, verify clean.
Claude-Session: https://claude.ai/code/session_01HJRuvHJEBd8t7iRA9Sb1iw
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The unknown-citation rule is described in this file as catching "the strongest
possible signal of fabrication — it invents its own proof". It matched
/\[[FD]\d+\]/ — ASCII brackets only — and models do not reliably write those.
Observed 2026-09-13, two models on Groq, both unprompted, from a prompt whose
every example used [F1]:
openai/gpt-oss-120b The most recent feedback was on project Heidi【F3】.
groq/compound-mini ...concerned project **Heidi**【F3】.
An ASCII-only match does not flag those as bad citations. It does not SEE them.
So `【F9】` on a turn holding three records sails straight past the rule, while
`[F9]` is caught — a hole opened by a character variant, in the one check whose
whole job is invented proof.
Nothing else covers it. A false citation hung on an otherwise attested claim
trips neither the proper-noun rule nor the number rule: every name and number in
the sentence really is in the records. Only the proof is invented, and that is
exactly the shape a reader is least able to check.
Brackets are normalised before matching — fullwidth 【】, lenticular 〔〕 and
fullwidth square []. Every substitution is one character for one character, so
offsets into the normalised copy still address the original, and the violation
reports the citation VERBATIM. Telling an author their `[F9]` is wrong when they
wrote `【F9】` sends them looking for a string that is not in their answer.
Proved by mutation: dropping the normalisation fails the new fullwidth test and
nothing else, which is the point — the rest of the suite could not see this.
263 tests pass, verify green.
Claude-Session: https://claude.ai/code/session_01Nm2REqtdsVsvjukBU2maCz
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Headers do not describe every limit a vendor enforces.
Groq publishes its per-minute token window and its per-day REQUEST count as
headers, and meters a third limit — tokens per DAY — that appears in no header
at all. It is stated once, in prose, inside the body of the 429 enforcing it:
on tokens per day (TPD): Limit 200000, Used 199773, Requested 571.
Observed on production 2026-09-13, and the surrounding numbers are the point:
every header on that same response looked healthy — 2,672 of 8,000 tokens left
this minute, 999 of 1,000 requests left today — while the account was locked out
of the model for the rest of the day. A dashboard fed only by headers reported a
working provider throughout an outage.
That is exactly the failure the top of this file exists to prevent ("reports a
full tank during an outage"), arriving through a door it left open. The module
refused to poll a usage endpoint because the endpoint lies; it then trusted
headers to be complete, and they are not.
readingFromRefusalBody() takes the body and returns the counter the vendor named
there — scope, window, limit, and remaining computed from the stated Used.
STILL NEVER INVENTS ONE
Returns null unless the body states numbers. OpenRouter's daily refusal names no
counter, so it yields nothing and the caller falls back to readingFromRefusal(),
which records the one fact any 429 carries: spent, now. Inventing a reading here
would be the same bug with the sign flipped — an invented outage.
Two details that cost a measurement each: the window comes from the vendor's own
sentence, so unlike a header name it is not overridden by the provider profile
(TPD read as a minute understates it 1440x); and remaining is clamped at zero,
because a vendor counting the rejected request against the total would otherwise
render a negative tank.
4 new tests, proved by mutation: breaking the arithmetic fails 3 of them.
261 tests pass, verify green.
Claude-Session: https://claude.ai/code/session_01Nm2REqtdsVsvjukBU2maCz
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The chain replaced one pinned model with a list of pinned models. catalog.ts
then noticed the list rots too and added a check. But a check only produces a
SENTENCE — somebody still has to read it, edit a file, open a PR, wait for CI
and deploy, and until they do the app hands users a model that answers 404.
That round trip is this module's origin. On 2026-09-13 a health check scheduled
minutes earlier alerted that two ids in a consumer's registry were gone from
OpenRouter. The alert was correct and fast and completely dependent on a human
being awake. The vendor had published the truth the whole time.
So resolveChain() treats the declared list as a PREFERENCE and asks each vendor
what it actually serves. A retirement stops being an incident and becomes a
no-op.
Three rules, each paid for by a real failure:
1. NEVER SHRINK ON IGNORANCE. An unreadable catalogue keeps the declared list
verbatim and sets `unverified`. While building this, a checkout without
GROQ_API_KEY got a 401 and the first draft printed GONE for both Groq
models — both live. Resolution that trusted that would let an expired key
empty the chain. Tested against 401, 500, 404 and a missing key.
2. DISCOVERY EXTENDS THE TAIL, NEVER THE HEAD. Declared ids were probed with a
real tool call; five of nine free models turned out to emit tool calls only
as text. A discovered id has no such evidence, so it is a last resort and
never a first choice.
3. DISCOVER ONLY WHAT THE VENDOR CALLS FREE AND USABLE — read, not guessed.
Price, not the `:free` suffix: OpenRouter lists 19 ids ending `:free` and 22
priced at zero, and the zero-priced ids WITHOUT the suffix include
`openrouter/free`, the auto-router that is the most rot-resistant entry in
the whole chain. Groq publishes prices too and none are zero, so discovery
there correctly finds nothing and that vendor stays curated.
Then suitability: of the 19 free ids one was `nemotron-3.5-content-safety`,
a classifier and the only one declaring tools:false, and two more
zero-priced ids were `lyria-3-*`, which emit AUDIO. Adding every zero-priced
model would have put a safety classifier and a music generator in front of a
user asking a question. Requiring text-out and declared tools removes
exactly those three and nothing else.
Silence is refused rather than assumed throughout: a model that publishes no
price is never discovered. Guessing wrong in that direction spends money, so
the default declines.
Measured against the live catalogues, replaying Groq's real body so no secret
moved: the declared chain is 7 models, resolution yields 17 — and it flagged
`dots-3-note-preview:free` as ending 2026-09-30, seventeen days of warning,
because vendors sometimes publish an expiration_date and honouring it turns rot
from detected-afterwards into avoided-in-advance.
catalog.ts's own GET now reads the shared fetch in catalog-fetch.ts rather than
keeping a second, slightly different copy — the failure its header objects to.
Both vendor schemas are normalised there, because they do NOT agree: OpenRouter
puts modalities under `architecture` and tools in `supported_parameters`, Groq
puts modalities at the top level and uses `supported_features`. A reader that
knows only one shape silently drops a working vendor.
What this does NOT fix, stated plainly: presence in a catalogue is not proof a
model works. This package already records an id that answered "Provider
returned error" and one that returned HTTP 200 with EMPTY content. Resolution
fixes "the id does not exist"; demoting an id that exists and misbehaves needs
observed outcomes, and is not in this change.
Verified: 257 tests pass (18 new), format, lint, typecheck and both builds
clean.
Claude-Session: https://claude.ai/code/session_01HJRuvHJEBd8t7iRA9Sb1iw
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
A live answer laid its findings out as a table and was reported as fabricating.
Every claim in it was cited and correct; the flagged "novel proper nouns" were:
Item
Item Status Notes Pending
Those are the header cells of `| Category | Item | Status | Notes |`. A pipe is
not a word character, so it was not a boundary — the header tokenised as one
capitalised run, and the run then continued past the row break into the FIRST
CELL OF THE NEXT ROW to produce a phrase that appears nowhere on screen.
This is the worst direction for this check to fail in. FleetCrown now renders a
prominent "some of this is not backed by your records" warning on a flagged
answer, so a false positive does not merely add noise — it teaches the operator
to dismiss the warning, which costs more than the fabrication the check exists
to catch. A grounding check that cries wolf is worse than one that is absent,
because absence is at least legible.
Fix: pipes become line breaks alongside the existing code-fence stripping. A
cell is its own utterance and a run must not span two of them.
Recall is barely touched, and the test says so. Splitting per cell makes each
header word cell-initial, and sentence-initial single words were ALREADY skipped
for exactly this reason ("Rotate the key" must not flag "Rotate"). A fabrication
inside a cell still trips its remaining tokens — pinned by a test asserting that
"Program Manager at Impact Hub Zurich" in a table cell is caught as both the
composite run and its individual tokens. If that test ever goes quiet, this
boundary has become a blindfold.
Found by reading the grounding verdict on a real production answer rather than
by testing the parser, which is the only way this shape shows up: it needs a
model that chose a table, and every unit fixture used prose.
239 tests, up from 236.
Co-authored-by: Cato <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The implementation always carried them. `callLink` forwards `messages`
into the request body untouched, so a multimodal message has worked at
runtime since the first release while `ChatMessage.content` said it
could not.
The cost of that gap is not theoretical. A consumer that needs to send
a screenshot — heidi, today — has to cast around this package's own
type, and a cast written to work around a library is the kind of thing
the next consumer copies without asking why it is there. This is the
fleet's AI layer; sending a picture should not require getting past it.
Backward compatible by construction: `string | ContentPart[]`, every
existing caller passes a string, and a string is still assignable.
`ContentPart` is OpenAI's shape, which is the shape every provider in
the default chain already speaks — `image_url.url` takes a `data:` URL
or an `https:` one.
Two tests, both asserting the wire rather than the type: parts arrive
intact, and a plain string still leaves as exactly a string.
Claude-Session: https://claude.ai/code/session_01FzYBD3sZroCAYeRgTYrpfT
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
`tools are not supported by this model` matched nothing. Eleven patterns, and
every one of them assumed a singular subject with `is` — so the plural-and-
`are` form, which is what vendors actually send, fell straight through.
The header said a false negative "costs one request". That was the reasoning
error underneath the gap, and it is wrong. The caller that sends tool
definitions also DROPS its prose action catalogue, because definitions are
meant to replace it. So an unrecognised refusal leaves the model unable to
call a tool AND no longer told how to act without one — and because nothing
is recorded, it happens again on the next turn, and every turn after. A missed
phrasing is not a wasted request; it is a permanently mute model.
The bar is unchanged and still conservative: NAME tools or functions, and
NEGATE support, both halves explicitly. What changes is that the boring
grammatical variants now clear it — plural, `are`, `cannot use`, `no tool
support`.
Both directions are pinned. Seventeen real refusal phrasings must match;
thirteen real 400s that say nothing about tools must not — including the near
misses that make widening risky, `streaming is not supported for this model`
and `vision is not supported by this model`.
Claude-Session: https://claude.ai/code/session_01HJRuvHJEBd8t7iRA9Sb1iw
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
`chain.ts` carries a probe table from nine free models called with a real tool.
Four answered with native `tool_calls`. Five answered only in TEXT. Three of the
seven models in the chain this package ships TODAY are in that second group:
google/gemma-4-26b-a4b-it:free text
cohere/north-mini-code:free text
openrouter/free text
`complete()` read only `message.tool_calls`. So on nearly half its own chain it
returned ZERO tool calls — and handed the model's narration of the call back as
ordinary content. A turn that should have looked up a record instead returns a
confident sentence describing the lookup it never performed, and every layer
downstream treats that as an answer.
That is not a missing feature. It is a fabrication path, and the package's own
evidence said it was open.
The old comment called text parsing "the caller's business, because its
convention differs per app". True of the convention; false of the consequence.
An app that declines to parse does not get less capability, it gets invented
answers — and the one app in this fleet that does parse had to keep its whole
HTTP client to do it, which is why "put every app on one caller" was blocked.
WHAT CHANGES
`complete()` now reads both protocols and merges them, native winning ties so a
model emitting the real call plus a prose echo runs the tool once. Parsed lines
are stripped from `text`, because a narrated call must never reach a user as
prose.
Inert unless you use tools: parsing is skipped when no `tools` are supplied — a
model does not narrate a call it was never offered. No consumer passes `tools`
to complete() today, so this changes behaviour for nobody and unblocks the one
that needs it. `toolProtocol: "native"` opts out for a caller that parses the
lines itself and would otherwise execute each call twice.
Ordering matters: after stripping, a reply that was ONLY a narrated call has
empty text. `complete()` treats an empty 200 as a link failure, so tool calls
are counted first or a working model gets demoted off the chain.
DETAILS WORTH THE TESTS
- The closed set comes from the `tools` array the caller already passed. Two
lists that must agree are one list that cannot disagree, and the split version
fails silently — a missing name makes the parser ignore a real call.
- The JSON walker is string-aware. Naive brace counting closes at the `}` inside
`{"q": "a } b"}` and the arguments vanish.
- Unparseable stays null, distinct from `{}`. Returning `{}` satisfies a
caller's `?? {}` and silently drops arguments the model put on the next line —
exactly what a ```json fence after ARGS: produces.
- Every tolerated shape (markdown bolding, list bullets, `=`, copied parens,
fenced or multi-line ARGS, a missing ARGS line) is one a small model actually
emitted. Rejecting any is a turn failed over formatting.
- `TEXT_TOOL_PROTOCOL_HINT` ships the prompt wording beside the parser that has
to read it back. A prompt and its parser are one contract.
232 tests, up from 211.
Co-authored-by: Cato <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Replaces the line every app in this fleet writes and every app gets
wrong:
const TOOL_CAPABLE_PROVIDERS = ['groq', 'openrouter'];
That list is wrong the moment a user brings a model nobody has heard of,
which is every day — and OrangeCat measured the consequence: a user on
their own frontier key is handed NO tools at all, so the person paying
most gets the least capable assistant. It is also wrong in the other
direction, because it cannot express that five of nine free models
probed here answer tools only in prose; a native-only client loses most
of its chain while believing it is fine.
The replacement is not a better list. It is three rules.
THE FIRST REAL CALL IS THE PROBE. Send the tools, read what comes back,
write down what it proved. Every model a user brings classifies itself
on its first message, at no extra cost and with no release from us.
Nothing here spends a separate request, which matters most when the key
belongs to the user.
A POSITIVE IS CHEAP, A NEGATIVE IS EXPENSIVE AND STICKY. One tool_calls
response proves capability outright. A 400 proves nothing unless the
vendor SAYS it is about tools — a context-length overflow, a content
filter or a bad parameter must be recorded as nothing at all, because
writing one down as "no tools" cripples a capable model until the record
expires and nothing in the product explains why. That asymmetry is what
`record: false` is for: the right response to an uninformative failure
is to learn nothing, not to guess. Most of the test file defends it.
"NEVER ASKED" IS ITS OWN ANSWER, READ TWO WAYS. planToolAttempt is
optimistic about it, because asking is the only way to learn.
claimableVerdict is pessimistic about it, because announcing a
capability a model has never demonstrated is a promise it may not keep,
and the user meets that as a broken feature rather than a missing one. A
single boolean cannot hold both directions at once.
Records expire, negatives sooner than positives: a model that gained
tool support and is still marked incapable is invisibly crippled, while
one that lost it says so loudly on the next call. Observations are keyed
by a HASH of the credential, never the credential, because capability
genuinely differs per key and observations must not leak across them.
A real call always overrules a registry claim, even an older one.
Storage stays with the app. This owns the shape and the rules, which is
the part everyone gets wrong; it does not own where rows live, which is
the part where apps legitimately differ.
21 new tests, 183 total green.
Claude-Session: https://claude.ai/code/session_014nayuDvAPd5BYkSfsVPHHA
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Across this fleet the same feature exists twice, half each. One app enforces a
daily AI budget with no interface at all: the user is refused, and never learns
why or what their share was. Another draws a quota meter with its own separate
notion of tier, which the enforcement path does not read. Both are correct in
isolation and they cannot agree, because there was no single statement of the
policy for them to agree ABOUT.
`decide(policy, state)` is that statement. The gate asks it whether to allow;
the settings page asks it what to draw. A number on screen the gate does not use
is decoration, and a gate whose reasoning cannot be rendered is a wall.
Pure, by the same rule as fair-share: no database, no clock, no provider.
WHY A REFUSAL CARRIES A LADDER
Shared free capacity is a fixed cost carried on behalf of strangers, and its
only job is to be good enough, once, that someone wants more of it. The moment
it runs out is the only moment anybody changes anything — which makes the
refusal the most important screen in the product, not an error state.
So `decide` returns a `Wall`, not a boolean. The default order offers the exits
that cost the user NOTHING before the one that costs money: asking someone to
make a free account elsewhere converts better than asking them to pay, and it
takes them off the shared pool just as completely.
FOUR PROPERTIES WORTH THE TESTS THEY COST
- `wait` is always the floor, and a config cannot remove it. A refusal with no
way forward reads as a broken product; "it refills at 01:00" is a path.
- An unknown tier fails CLOSED. A typo in a config should cost nothing, not
hand out the shared pool.
- Uncapped is `null`, never 0. Rendering null as a gauge at zero would tell a
user on their own key that they are out — the opposite of true.
- A rung the user cannot take is marked unavailable rather than dropped.
Dropping it makes the list differ per user for reasons nobody can see.
`shouldSurface()` keeps the indicator quiet until it matters: a permanent gauge
at 96% trains people to ignore the one at 4%.
190 tests, up from 179.
Claude-Session: https://claude.ai/code/session_01CAfKwM1oUSA9tU9fgdhfdf
Co-authored-by: Cato <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The obvious way to build a quota dashboard is to ask each provider how much is
left. That design is wrong, and it fails in the direction that hurts: it reports
a full tank during an outage.
Measured on one live key, within the same second:
GET /api/v1/key → limit_remaining: null, usage_daily: 0
POST /chat/completions → 429, x-ratelimit-remaining: 0 of 50,
"Rate limit exceeded: free-models-per-day"
Both answers are OpenRouter's, about the same account, and the account was
locked out. The usage endpoint tracks money, free models cost nothing, and the
limit that actually binds is a REQUEST count that endpoint never reports.
So `complete()` now reads the rate-limit headers off every response and hands
them to `onQuota`. No extra request, no quota spent to discover how much quota
is left, and the number comes from the same exchange that either worked or did
not. It fires on 429s too, and those are the most valuable readings there are:
a refusal is the vendor correcting a local counter that had drifted optimistic.
Three refusals to guess, each a bug avoided rather than a feature declined:
- A vendor that sends no headers produces NO reading. Absent is a third state
beside known and empty. Gemini sends nothing at all; inventing a zero there
would invent an outage, and inventing a full tank repeats the bug above.
- The window is never guessed. `x-ratelimit-remaining-requests` counts a DAY at
Groq and a MINUTE elsewhere, so it comes from a verified per-provider profile
or from the header's own name, and is otherwise reported as unknown. A
confident wrong window turns "900 requests left today" into "…this minute".
- A `size` 429 records nothing. That refusal means one prompt did not fit, not
that the allowance is gone; recording it as empty would take a working vendor
out of service for a day over a single oversized prompt.
Reset times arrive in three incompatible encodings and no vendor says which:
epoch milliseconds (OpenRouter), compound durations (Groq's "56m26.88s"), and
sub-second ones ("547ms"). They are told apart by magnitude, and anything
unparseable is null rather than a guess — a wrong reset tells the operator to
come back at the wrong hour.
`answersRemaining()` translates a token count into the unit a person thinks in.
The package still has no database: persisting is the app's job, which is why
this is a callback. A throwing sink cannot fail a good answer.
179 tests, up from 162.
Claude-Session: https://claude.ai/code/session_01CAfKwM1oUSA9tU9fgdhfdf
Co-authored-by: Cato <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* ci(auto-merge): correct the reason this repo passes a PAT
The comment added a few hours ago says GITHUB_TOKEN cannot merge a PR that
touches .github/workflows. That is contradicted by this fleet's own history:
github-actions[bot] merged datacat#253 and ai-kit#42 today, and both change a
workflow file. I asserted it from the reusable workflow's docstring without
checking, then found the counter-evidence while looking for something else.
Two stalled PRs were offered as proof and neither survives either. ai-kit#11
opened 2026-08-29 and this repo's sweep was not added until 2026-09-04, so for
most of that PR's life nothing was sweeping at all. aoz-housing#122 is still
unexplained — I merged it before diagnosing it, which destroyed the evidence.
The THROUGHPUT reason is unaffected and is why the line stays. A dispatch made
with GITHUB_TOKEN triggers no workflows — the same rule the deploy reconciler
exists for — so after a merge the re-armed CI run's completion fires no
workflow_run and nothing wakes the sweep for the next PR. It waits for the
cron, which GitHub throttles: fleetcrown's sweeps land 50-65 minutes apart
against a */10 schedule. A PAT-created dispatch does emit workflow_run.
The wrong claim is recorded in the file rather than quietly deleted, so the
next reader does not re-derive it from the same docstring I did.
No behaviour change: an undefined secret still resolves to empty and the
reusable workflow still falls back to github.token.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvjGNAS9CMfEGNW26tUR4P
* feat(web): the agent can see the web, and cite what it saw
Adds `@bitbaum/ai-kit/web`: search over a provider chain, a page reader
safe to point at an agent-chosen URL, and a mapping of both onto the
`Fact` type the grounding harness already verifies.
Every AI product in this fleet is about to need this, and each one is a
distinct way to be wrong:
- WHICH backend. Same fallback-chain problem `chain.ts` solved for
models, for the same reason — a single pinned backend is a scheduled
outage. searxng (self-hosted, no key, nobody told what users search
for) -> brave (an independent index, so the fallback is not the same
index asked twice) -> tavily. Only the ones the env configures.
- WHETHER it answered. The result is three-valued: found / nothing /
could_not_look. "Found nothing" and "could not look" are different
answers and collapsing them into [] is how an expired API key becomes
a confident sentence about what does not exist on the internet. A
backend answering 200 with zero results is walked past rather than
believed — that is what a metasearch instance does when its upstreams
refuse it, and stopping there would report an outage as a fact.
- FETCHING a page the MODEL chose, which is a different security problem
from fetching one a user typed. There is no human to blame for the
address, and any page the agent reads can hand it a link to the
metadata service. So: http(s) only, ports 80/443, no credentials,
every resolved address checked (not the first — a hostname with one
public and one private record is rebinding with the work done), and
`redirect: "manual"` with the full check re-run on every hop.
Validating the first URL and then letting fetch follow the 302 is not
a check, and it passes every test that only feeds it URLs.
- CITATIONS. Search without citation binding makes hallucination worse,
not better: the invented sentence is now surrounded by real ones. So
results become Facts with an id and a url, page text becomes evidence
labelled with the id that licenses it, and `verifyAnswer` checks the
binding mechanically. Web content and database rows now go through one
verifier instead of two.
`published` and the rest are declared in FACT_KINDS precisely because
engines omit them: a rendered `published: <not recorded>` is what stops
a model putting a year on an undated page.
39 new tests, written against the contract rather than the
implementation — the repo has already shipped a regression test that
asserted the buggy behaviour and went green. The reader's title path had
a real bug (tag-stripping left double spaces); the test found it and the
implementation was fixed, not the test.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nayuDvAPd5BYkSfsVPHHA
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Found immediately, wiring the probe into the second app.
A handler is built once and reused, because its cache has to live
somewhere. So a plain `secret` string is whatever the environment held on
the FIRST request that reached it. Two consequences, one operational and
one that blocks the work:
- rotating AI_PROBE_SECRET needs a process restart, which is not what
anyone expects of an env var read at request time;
- the route is untestable. The first test that runs before a secret is
configured pins every later one to 501, because the handler it built
captured `undefined`. That is exactly what happened: six of eight new
tests in the consuming app failed on "expected 501".
`secret` now also accepts a function, read per request. A plain string
still works and still behaves as before.
Verified by mutation: capturing instead of calling turns exactly the test
that names it red.
Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Found while trying to answer "does the AI work?" for every app in the
fleet. Two apps could answer; seven could not, because every AI route in
them is behind a login and only two had the probe wired.
Wiring the rest hit a wall: `createAiHealthHandler` needs a `Link[]`, and
four of them cannot produce one. kivvi builds its chain from its own
provider CLASSES; orangecat from a registry it deliberately owns (its
BYOK list includes paid ids); vitareba talks to ONE operator-configured
endpoint chosen for data residency; aoz-housing keeps a provider layer
that predates this package. Requiring a chain meant rewriting those or
leaving them unprobeable — and unprobeable is the state that made this
whole question unanswerable.
`ask` takes a function instead. The gating, the caching, the
never-cache-a-failure rule, the 200/503 contract: all unchanged.
The better reason is not the four awkward apps. A probe built from a
chain THIS module assembles tests A path; `ask` tests THE path — the same
function the app's real features call — so the probe cannot drift away
from the code it vouches for.
An empty or whitespace-only result is a FAILURE, for the same reason
complete() treats it as one, and it matters more here: several of these
apps return "" or null on failure BY DESIGN so callers can degrade.
Accepting that would make the probe report health on exactly the outage
it exists to catch. Verified by mutation — dropping the check turns that
test red and nothing else.
Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Learned from truthseeker's hand-rolled client while converting it — the
engine did not have this and should, so it is going in BEFORE the
conversion rather than being deleted by it.
401/403 says "not you". Every remaining link at that provider presents
the identical credential, so walking them spends a request each to be
told the same thing — and then reports "all 5 links failed", which reads
as an outage at someone else's shop and sends the reader looking for
one. The fact worth surfacing is that a key this app holds was refused.
Crossing to the NEXT vendor still happens: that is a different key, and
the whole reason the chain spans vendors.
Deliberately narrow, and the narrowness is the point. A 404 is a retired
id, a 5xx is a vendor being unwell, a capacity 429 is a busy minute —
all three are answered by asking a DIFFERENT model, and widening this
skip to cover them would quietly turn the chain back into the pin it
replaced. There is a test for the 404 case specifically.
Verified in both directions by mutation: removing the skip turns both
new tests red, and widening it to include 404 turns the one that names
that boundary red.
Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
0.11.0 let a probe resolve its CHAIN per call, for an app whose provider
list lives in a database. It left the KEYS behind, and that is half a
feature: an admin screen that stores a per-provider api_key next to the
model is the ordinary case, not an exotic one. Resolving links from the
database while reading credentials from a process.env captured at
construction makes the probe report "no key" for a provider that is
configured and working — a false alarm from the module whose entire
purpose is to prevent false alarms.
resolveChain may now return { chain, env }. A bare Link[] keeps whatever
env the probe was built with, so 0.11.0's shape is unchanged.
Found immediately, wiring evig — the same app that motivated
resolveChain. Worth noting that the first version was shipped and
published before the gap showed up: the use case was understood and the
implementation still only covered half of it.
Both shapes verified by mutation: ignoring the resolved env turns exactly
the test that names it red, and the bare-array test proves the old
behaviour is intact.
Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>