27 Commits
Author SHA1 Message Date
ce95a19b5b fix(grounding): a markdown table is not a fabrication (#54)
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>
2026-09-12 12:37:49 -07:00
CatoandClaude Opus 5 ae92496e90 feat(complete): content may be parts, not only a string (#52)
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>
2026-09-12 03:47:38 -07:00
CatoandClaude Opus 5 1bf0074f95 fix(capability): recognise the refusal in the form vendors actually write it (#51)
`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>
2026-09-12 03:36:48 -07:00
0bd6c38103 feat(tool-protocol): read the OTHER way models ask for a tool (#50)
`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>
2026-09-12 01:59:27 -07:00
CatoandClaude Opus 5 d7051a4c72 feat(capability): what a model can do, observed rather than declared (#48)
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>
2026-09-11 13:55:38 -07:00
97ac6cfa17 feat(policy): one statement of who may spend what, read by the gate AND the screen (#49)
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>
2026-09-11 12:59:21 -07:00
00b70757de feat(meter): read what is left at the vendor, off the call you already made (#47)
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>
2026-09-11 12:52:50 -07:00
CatoandClaude Opus 5 ac5027df4d feat(web): the agent can see the web, and cite what it saw (#45)
* 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>
2026-09-11 04:36:21 -07:00
CatoandClaude Opus 5 e7b80bc78c fix: read the probe secret per request — a captured one cannot be rotated, or tested (#41)
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>
2026-09-07 06:55:55 -07:00
CatoandClaude Opus 5 ca19d36b70 feat: ask — let an app probe its OWN path, not a chain this module assembles (#40)
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>
2026-09-07 13:33:30 +00:00
CatoandClaude Opus 5 2e178ae9b4 feat: a rejected key condemns the VENDOR, not just the model (#39)
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>
2026-09-06 21:28:00 -07:00
CatoandClaude Opus 5 7959bb16bd feat: resolveChain may carry the env — keys move with the chain, or the probe lies (#38)
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>
2026-09-06 16:04:51 -07:00
CatoandClaude Opus 5 c51d33b817 feat: resolveChain — a probe on a DB-configured chain must not read a frozen one (#37)
Found wiring the probe into evig, whose provider list lives in a
database: an admin screen with enabled/default rows and per-provider
keys. A chain fixed at construction is a chain frozen at process start,
so the probe would keep reporting on a configuration the operator
changed twenty minutes ago — the exact opposite of "the truth about
right now", which is the module's whole reason to exist.

resolveChain() is called only when a probe actually runs, never on a
cache hit, so a monitor polling the route does not also poll the
database. That second property is the one worth writing down: it is what
keeps the safety guarantee (a cached success costs nothing) true for an
app whose chain is not free to compute.

Both verified by mutation: ignoring resolveChain turns exactly those two
tests red.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 15:49:48 -07:00
CatoandClaude Opus 5 913b16c790 feat: extraHeaders — the attribution a caller silently loses on adoption (#36)
Found converting botsmann: its OpenRouter call sends HTTP-Referer and
X-Title, which OpenRouter reads for app attribution in its public
rankings. complete() had no way to send them, so adopting the engine
would have dropped botsmann off that list with no error anywhere —
exactly the kind of small, invisible regression that makes a shared
package feel worse than the hand-rolled client it replaced.

`authorization` is merged AFTER extraHeaders and cannot be overridden. A
typo in a caller's header map must not become someone else's credential
on the wire, or an auth failure blamed on the vendor.

Both properties verified by mutation: dropping the spread turns the
attribution test red, and moving it after `authorization` turns the
override test red.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 22:46:19 +00:00
CatoandClaude Opus 5 b31baa9f7f feat: give every link its own deadline — a chain that cannot time out is not a fallback (#35)
A vendor that accepts the connection and then never answers is the most
common partial outage there is, and it was the one this chain could not
survive: without a deadline `await fetch` never returns, link two is
never reached, and the fallback becomes the thing holding the request
open. Every one of the fleet's hand-rolled clients has the same hole.

`timeoutMs` (default 30s) is PER LINK, and that is the whole point. The
obvious alternative — passing a budget as `signal` — is actively worse
than nothing: link one spends all of it and links two onward inherit an
already-aborted signal, so the fallback fails instantly and reports every
vendor broken when only the first was slow. A deadline and a fallback can
both be true only if each link gets its own.

Also: when the CALLER's signal aborts, the walk now stops. Touring the
remaining vendors spends a daily budget on an answer nobody will read,
then reports "every vendor failed" about vendors never asked.

A timeout names itself in the failure. "This operation was aborted" in a
log is indistinguishable from a caller cancelling, and the two want
opposite reactions from whoever reads it.

The probe takes a tighter 10s: a monitor asking "is the AI up?" has given
up long before a chain of 30s links finishes being patient, and a health
route that takes a minute to say "down" has become a second outage.

Two test-quality fixes found by mutation, both worth more than the
feature:

  - the first "abandoned, next link serves" tests PASSED with the
    deadline deleted. Without a signal the helper threw instantly, the
    walk demoted, and the test proved demotion rather than the deadline
    it was named for. Asserting inside the fake fetch does not fix it
    either — `complete` catches everything a link throws, so a failed
    assertion becomes just another demotion. The deadline is now recorded
    and asserted outside the walk.
  - the probe's tighter deadline was "covered" by asserting a signal
    existed. complete's own 30s default supplies one, so that test stayed
    green with the tighter deadline removed. It now measures WHEN the
    abort lands, which costs ~10s of suite time and is the only shape
    that observes the thing it names.

Dropped an unref() on the timer that I had justified with a scenario
that does not hold: it is always cleared in dispose, so there is nothing
to save, and an unref'd timer stops firing when nothing else keeps the
loop alive — a deadline that sometimes does not happen.

109 tests. Each new guarantee verified by mutation.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 14:38:30 -07:00
CatoandClaude Opus 5 29b9241bc2 feat: prove the AI works right now, without emailing anybody (#34)
A health tracker that has recorded nothing looks identical whether the
chain is perfect or every key is missing. Straight after a deploy that is
exactly the state it is in, so the one question a deploy needs answered
("did I just ship a working AI path?") is the one it cannot answer.

Observed 2026-09-05 converting the first app: deploy green, bundle
provably held the new code, both keys present, /api/health 200 — and
llm.status "unknown". Every available signal said "probably fine" and
none said "works". The only paths that would have produced a real answer
were an admin-authenticated form and two crons that EMAIL REAL USERS.

createLivenessProbe / createAiHealthHandler make the call deliberately,
and the safety properties are the design:

- probes only on ?probe=1 AND with a secret, never on an ordinary poll;
- a SUCCESS is cached 10 min, so an authorised retry loop cannot drain a
  daily budget shared with the app's real features;
- a FAILURE is never cached — the point is the truth about right now;
- no secret configured => 501, not an open endpoint that can spend money;
- 200/503 so an uptime monitor can watch the URL directly;
- constant-time secret compare;
- 256-token budget, because reasoning models answer EMPTY at 16.

Each of those four safety properties verified by MUTATION: disabling the
success cache, caching failures, dropping the 501 guard and bypassing the
secret compare each turned exactly the test that names it red.

README also loses two stale claims: it still advertised the withheld HTTP
client that 0.7.0 shipped — the front door was telling every prospective
adopter the exact thing that made them hand-roll a client.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 20:33:12 +00:00
CatoandClaude Opus 5 d3cfbe096b feat: v0.7.0 — release the call, and prove the engine RUNS (#33)
Merging #32 gave this package an HTTP client but published nothing: the
version stayed at 0.6.2, so no consumer could reach it. This releases it.

It also closes the gap that a shared engine makes dangerous. Every check in
this repo was hermetic — `test/` drives an injected fetch, `check-catalog`
asks whether ids still EXIST — so all of them could be green while the
package could not complete one real turn. That was survivable while two repos
imported it. It stops being survivable when one engine sits behind every app,
because then its bugs arrive everywhere simultaneously.

scripts/smoke.mjs makes a real generation against the live free tier. It
earned its place on first run, finding two things no hermetic test could:

  - `maxTokens: 16` made groq/openai/gpt-oss-20b return 200 with EMPTY
    content. The chain leads with REASONING models, which spend the budget
    thinking before emitting a visible token — so a small budget makes a
    healthy model indistinguishable from a dead one, walks the entire chain,
    and reports every link broken. Documented on CompleteOptions.maxTokens
    where a consumer will actually hit it, and the smoke now asks for 256.
  - A single-quoted value in a .env inlines its QUOTES into the key, and
    OpenRouter answers that with "Missing Authentication header" — which
    reads as a missing key rather than a malformed one.

Scheduled, never a PR gate: it calls other people's servers, so as a required
check it would redden pull requests for a vendor's 500 and train everyone to
ignore red. The `|| status=$?` in the workflow is load-bearing — Actions runs
steps under `bash -e`, so a bare failing command aborts before its exit code
can be read, and the "no keys" branch would be unreachable.

Both scheduled jobs refuse to pass while blind: a probe that looked at nothing
has told us nothing, and green would be a lie.

Verified: catalog check run live — all 7 default pins present at their vendor,
confirmed both locally and in Actions ("7 id(s) confirmed present"). Smoke run
live — groq/openai/gpt-oss-120b answered "blue" in 878ms. verify green:
format + lint + typecheck + build + 91 tests.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 09:49:55 -07:00
CatoandClaude Opus 5 23aaee1503 feat: complete() — the package makes the call, and a schedule watches the pins (#32)
ai-kit's modules are each correct and each written against a real outage.
Almost none of it reached the apps that were failing. Measured 2026-09-05:

  ai-kit (ships decisions)                 imported by 2 repos
  ai-forms (ships a working handler)       installed by 5 repos
  hand-rolled LLM clients still in service 8, ~1400-1700 lines each

Not a quality gap, a shape gap. The stated rule — "every app has its own
calling conventions, replacing them is a rewrite rather than an adoption" —
described the duplication accurately and then protected it. The conventions
differed because nothing offered to own them. Of those 8 clients, 2 tell the
three kinds of 429 apart; the other 6 treat a spent daily budget as a busy
minute, which limits.ts has warned against since 2026-08-14 from inside a
module they do not import.

complete() owns the fetch, and makes the three judgements every hand-rolled
client here got wrong:

  - an HTTP 200 with empty content is a FAILURE, not a success. Two models in
    the default chain do this; a res.ok check hands "" to the user, reports
    success, and keeps health green through a total outage.
  - a DAILY 429 condemns the whole vendor. The budget is org-wide, so the
    remaining links there are already dead — skip them instead of buying a
    dead round trip each.
  - a SIZE 429 ends the walk. The next model down has a smaller ceiling
    (12000 TPM vs 6000), so demoting is strictly worse.

tryChain stays for callers with an unusual request to make.

Also: scripts/check-catalog.mjs has said since it was written that it is
"cheap enough to run on a schedule, which is the only kind of check that
catches rot without someone remembering". Nothing ran it, and the rot came
anyway — 2026-08-25, four of nine pins retired, both Groq models, eight days
of silent FleetCrown downtime. It now runs daily. The script exits 0 when it
could not check (right for an offline dev run, wrong for a scheduled probe),
so the workflow fails when zero ids were verified rather than passing blind.

All three walk behaviours proven by mutation against dist/: each disabled
individually, each caught by exactly the test that names it, then restored.
verify green: format + lint + typecheck + build + 91 tests.

NOTE: bitbaum/ai-kit has no Actions secrets, so the new workflow will fail
on its first scheduled run until GROQ_API_KEY / OPENROUTER_API_KEY are set.
That failure is the intended signal, not a regression.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 16:38:45 +00:00
d0fddb42b0 feat: the package is @bitbaum/ai-kit — npm's typosquat guard owns the bare name (#25)
First-publish attempt returned E403: 'Package name too similar to existing
package aikit' — the unscoped name is permanently unpublishable, no auth or
token changes that. Scoped to the org that owns the repos: @bitbaum/ai-kit.
Self-referencing imports in src/tests and the README install line follow.
77/77 tests green under the new name; consumers' import-path updates ride
the Wave-7 pin swap, which touches those exact files anyway.


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-03 07:27:48 -07:00
GandClaude Opus 5 9009d73d3f chore: add a formatter (#22)
* chore: add a formatter, matching the style this repo already writes

singleQuote=false was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format with prettier (27 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: teach git blame to skip the reformat

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(ci): ignore dist-cjs, which only exists on the runner

format:check passed locally and failed in CI on six files under dist-cjs/. The
ignore list covered 'dist' but not its siblings, and CI builds before verify —
so those files exist on the runner and never locally. A clean local check is no
evidence when a build precedes the gate.

Widened to dist-* so dist-esm and friends cannot repeat this.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 10:42:02 +02:00
4c7ededd8d feat: the model registry and the grounding harness move into the engine (#19)
Phases 1–2 of the fleet AI-engine plan: ai-kit stops being only the
transport layer and gains the two modules every adopter re-invented.

ai-kit/registry — one SSOT for every callable model id. Two incidents, two
invariants: a checker that does not enumerate its subjects cannot report the
id it never knew about (eight days of model_not_found, 2026-08-18), so
require() throws for anything unregistered and idsForVendor() IS the
enumeration a catalog check walks; and three apps silently billed on
fallback because a `:free` suffix was the whole paid/free boundary, so paid
is a required FIELD and the validator refuses an entry whose flag
contradicts its own price or id. freeOnly() is the platform-key guard
(unregistered ids are dropped too — an unknown price spends someone's money
only when a person decides it does); toolCapable() carries the probe
verdicts (native / text / none / unprobed — five of nine probed free models
only speak the text protocol).

ai-kit/grounding — facts, contract, and the deterministic fabrication check,
lifted from fleetcrown/src/lib/agent/core (the canonical copy of the
FleetCrown↔OrangeCat mirror). The mirror's README called the duplication
"deliberate and temporary" and named this extraction as the exit. Two
mechanical deltas from verbatim: `.js` extensions on relative imports (pure
ESM) and two null-guards under this package's noUncheckedIndexedAccess.
Adopting apps delete their copies and the SHA-256 drift check with them.

Both are subpath exports, not root re-exports — the v0.4.0 lesson (one
import path per concern) and zero collision with the root export surface.

verify green: lint, typecheck, build, 75/75 tests.


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 10:45:13 +02:00
de7319a29d feat: tryChain + createHealthTracker — walk the chain, know when it's down (#18)
The chain and catalog modules already answer WHICH model to call and
whether the vendor still lists it. What every hand-rolled adopter still
had to build itself, differently, was the loop that actually walks the
chain on failure, and a record of whether the whole thing came back
empty — the gap a real outage fell through on 2026-08-28: an app's only
key died, the chat routes caught it and answered a friendly 200, and
/health reported healthy because it only ever checked the database.

tryChain() tries each link in order and returns the first success,
throwing ChainExhaustedError (naming every link's failure, not just the
last) when none work. It ships no HTTP client, same as the rest of this
package — attempt() is supplied by the caller and makes the real
request; this only decides which link goes next.

createHealthTracker() is a factory rather than a module-level global, so
a consumer gets old-style shared-process state for free by creating
exactly one, and tests never fight over shared state. Health only
records once per whole chain walk: a success on link two is a success,
not a "degraded" report on the fallback working as designed.

Version 0.4.0 -> 0.5.0. Also fixes stale catomean/* org references in
README and package.json left over from the bitbaum rename.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 09:30:40 +02:00
GandClaude Opus 5 44f6bcaa69 fix(exports)!: form filling leaves the root, one install stays (#8)
The first app to adopt the merged package broke on it, which is the fastest
possible feedback and worth acting on rather than patching around.

`ai-forms` is ESM-only. Re-exporting it from this root meant that importing the
CHAIN pulled the forms package in behind it, so AOZ — which wanted `freeChain`
and nothing else — had its Jest run die on `Unexpected token 'export'` inside a
module it never asked for. Three suites, seven tests.

The available remedy was a `transformIgnorePatterns` entry in AOZ. Then the same
entry in the next adopter, and the one after: a single class of breakage, paid
once per repo, forever. That is precisely the shape this fleet has a rule
against, so the fix goes here instead.

One install was always the promise, and it is untouched. Same package, same
version, nothing new to install — only the import path moves:

    import { freeChain }    from "ai-kit";        // the chain
    import { defineFields } from "ai-kit/forms";  // form filling
    import { useAssist }    from "ai-kit/react";  // the React hook

Which is what the exports map was for. Collapsing it into the root threw away
the one thing it buys: a server that wants a provider chain no longer pays for
a form library, or for a UI peer behind it.

BREAKING for anyone importing form symbols from the root. Measured before
changing rather than assumed: across both consumers — FleetCrown (5 files) and
AOZ (2) — every root import is chain, limits or fair-share. Zero form symbols.
Nothing in the fleet has to change.

The absence is now a test, not a convention. `test/exports.test.js` asserts both
that `ai-kit/forms` resolves and that the root does NOT carry those symbols,
because a convenience re-export added back at the root would read as harmless in
review and break the next consumer in exactly this way.

verify: lint, typecheck, build, 48/48 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 23:38:28 +02:00
GandClaude Opus 5 0462b74365 feat!: become ai-kit — the AI layer in one install (#5)
The owner of this fleet read the name `ai-ration` and could not tell what the
package did. That is not a cosmetic complaint. An unreadable name is a cost paid
at every install decision, and this package had exactly ONE adopter while five
repos that skipped it — botsmann, evig, kivvi, orangecat, truthseeker — were all
taken down together on 2026-08-26 by a retired model id, which is precisely the
failure `chain` and `catalog` exist to prevent. "Ration" named one of five
modules and hid the other four.

Renamed, and widened to match how an app actually thinks about this. Adding an
AI feature looks like one decision and is really four — which model, is it still
there, what do the 429s mean, who gets the free tier — plus filling forms. Get
any one wrong and it fails identically from outside: the assistant is broken.
AOZ is the proof: it adopted the form half, hand-rolled the rest because that
was a second decision nobody made, and then reported "KI-Assistent nicht
konfiguriert" on a deployment whose key was valid.

So `ai-forms` is re-exported from the root and from ./forms, ./react and
./server. It is NOT absorbed: it works, four apps run it, and it is genuinely
useful outside this fleet. Swallowing it would break four repos to satisfy a
filing system. React stays on its own subpath as an optional peer so importing
ai-kit on a server never pulls in a UI library.

threadkit and limitkit are deliberately NOT merged. Neither has anything to do
with AI — an app throttling its login form should not install a model catalogue
to do it.

Four new tests cover the merge itself, because the merge IS the feature: without
them a broken re-export quietly turns this back into ai-ration under a friendlier
name and nothing else here would notice.

BREAKING CHANGE: the package is now `ai-kit`. Import from 'ai-kit'.
The GitHub repo is renamed; existing `github:maonakamoto/ai-ration` installs
continue to resolve through GitHub's redirect.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 14:33:08 +02:00
GandClaude Opus 5 07c492ce27 fix: four of the nine default pins were already retired (#4)
* fix: four of the nine default pins were already retired

Checked `freeChain()` against the live catalogues on 2026-08-25. Four of its
nine ids no longer exist:

    groq       llama-3.3-70b-versatile        GONE
    groq       llama-3.1-8b-instant           GONE   <- whole vendor dead
    openrouter openai/gpt-oss-20b:free        GONE   <- was FIRST in the list
    openrouter nvidia/nemotron-3-nano-30b...  GONE

The chain exists because a single pinned free model is a scheduled outage. That
reasoning has a hole this package fell into: the chain is ITSELF a list of pins,
so it rots too — and a chain whose first vendor is entirely dead is a slower
version of the failure it was built to prevent. Every caller paid two Groq 404s
and then a third on the preferred OpenRouter fallback before reaching a model
that could answer.

Consumers inherited it. FleetCrown used the same Groq id for direct, unchained
calls and was silently broken for eight days: its nightly frontier digest fell
back to a canned headline, and activity digests, calendar extraction, proposal
extraction and hosted-runner analysis all failed one at a time, quietly enough
that nothing looked broken.

Replacements probed, not guessed — the package's own rule. `openai/gpt-oss-120b`
and `openai/gpt-oss-20b` each returned a correct native tool_call with correct
arguments. The two retired OpenRouter ids are removed; the other five were
confirmed present in the 419-model catalogue.

── catalog: the check that can actually run on a timer ──────────────────────

New module, exported as `checkCatalog` / `hasRot` / `deadProviders` /
`catalogReport`. One GET /models per provider and ZERO tokens, which is the
entire point: a tool-call probe costs real money and therefore can never be
scheduled, so the only existing defence was a command someone had to remember
to type. Existence is cheap enough to check nightly. `npm run check:catalog`
runs it against this package's own defaults and exits 1 on confirmed rot.

It lives here rather than in each app because the check is the same everywhere,
and the first app to need it had already written its own, slightly differently.

Three states, not two. `live: null` means the catalogue could not be READ — no
key, network failure, non-200, or a body that parses but lists nothing. That is
not an empty catalogue. Reporting it as rot invents an outage; reporting it as
a pass hides one. `hasRot` counts only CONFIRMED absences, so an offline or
keyless run cannot fail a pipeline for something it never saw.

That distinction earned itself immediately: Node's global fetch is intermittently
broken on the laptop this was written on, and the checker correctly reported
7 UNCHECKED rather than "every model retired" — which would have sent me
"fixing" ids that were live.

`deadProviders` is separate from `hasRot` on purpose: a chain missing some
models is degraded, a chain missing an entire vendor is back to being a single
point of failure, and those deserve different words.

── modelCost is provider-dependent, and was silently wrong about it ─────────

The existing `paidModelsIn` guard caught the new Groq pins and called them PAID.
It was not a false alarm to suppress — it was the guard finding a real hole in
its own rule.

`modelCost` decides from the id: a slashed id without `:free` is paid. That is
right for OpenRouter, where `openai/gpt-oss-20b` genuinely bills. It is wrong
for Groq, where the same string is just that vendor's name for a model whose
cost is the account's tier. The rule was only ever safe because direct vendors
used bare ids (`llama-3.1-8b-instant` → "unknown"); Groq now ships
vendor-prefixed ids, so the shape stopped identifying the vendor.

So `Provider` gains `routed?: boolean` (true for OpenRouter), and `modelCostAt`
judges an id AT its provider. At a direct vendor the verdict is "unknown" —
never "free", which would reopen the hole this module was written to close.
`modelCost(id)` is unchanged for existing callers, with a docstring saying what
it assumes.

A false "paid" here is not harmless: it pressures someone into "fixing" a
working free model, and a guard that cries wolf gets disabled — taking the three
real cases it does catch with it. Pinned by a test that the routed vendor's
`anthropic/claude-sonnet-5` and `google/gemini-2.0-flash-001` are still flagged.

verify: 44/44 pass. Live catalogue check: all 7 pins present, no rot. Mutation:
restoring the retired pins turns it red (exit 1, deadProviders ["groq"]).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: 0.2.1 — retired pins replaced, catalog check added

Consumers pin this package by git TAG (FleetCrown:
github:maonakamoto/ai-ration#v0.2.0), so the retired-model fix only reaches
them once a new tag exists and their pin moves. Bumping here keeps
package.json and the tag in agreement — the previous release left an installed
copy reporting 0.1.0 under a #v0.2.0 pin, which makes 'which code is actually
running' unanswerable from the tree.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 15:11:04 +02:00
G 14a41b0c34 feat: modelCost — because the same paid fallback was found in three apps (#3)
One mistake, three codebases, one day. Each was a FALLBACK that began spending
the moment the free tier ran dry — the path nobody watches, because it only runs
when something else has already broken:

  botsmann   OPENROUTER_DEFAULT_MODEL = anthropic/claude-sonnet-5 (premium)
  kivvi      chain ended at Anthropic; OpenRouter default was
             google/gemini-2.0-flash-001, the paid twin of a :free id
  evig       meta-llama/llama-3.3-70b-instruct — reads free, bills at 1e-7/token,
             and its :free sibling has been retired from the catalogue

A fallback is a reliability mechanism; paying is a business decision. Wiring the
second to the first lets an outage make the decision, at the worst moment,
without anyone choosing it.

The rule is deliberately narrow and says so. A ROUTED id (vendor/model) is free
only with the :free suffix and paid without it — that suffix is the entire
difference between free routing and a per-call charge for identical weights. A
bare id (llama-3.1-8b-instant) returns "unknown": whether it costs depends on
the account tier at that vendor, which no string can answer. Guessing "free"
there is the direction that let all three through review, so it is not the
default.

paidModelsIn() applies it to a whole chain, returning offenders rather than
throwing — the caller knows whether a paid link is a bug or a deliberate,
opted-in upgrade, and a library that throws on the second case gets routed
around.

35 tests green, including the case that keeps this package honest: its own
shipped free chain must contain no paid model.
2026-08-16 14:57:42 +02:00
Mao NakamotoandClaude Opus 5 71b665e5b5 feat: ai-ration — free-tier chain, 429 classification, fair-share rationing
Three pure modules extracted from FleetCrown, where each was written after the
matching failure had already happened in production:

  chain      — a fallback list ACROSS VENDORS. A single pinned free model is a
               scheduled outage, and stepping down to a smaller model at the
               SAME vendor buys nothing: it draws on the same org-wide daily
               budget, so when the day runs dry every link is already dead.

  limits     — the three kinds of 429 share a status, a `type` and a `code`, and
               need OPPOSITE responses. Only the body separates them. Treating
               `size` as `capacity` broke a tool loop on every single turn;
               treating `daily` as `capacity` is the same mistake one level
               deeper.

  fair-share — divide a fixed daily pool across users active TODAY, paced through
               the day, with a one-turn floor so nobody's first question is
               refused. The goal is not throughput; it is that every active user
               gets a usable amount every day.

No HTTP client on purpose. Every consumer already has its own calling
conventions, retries and logging; replacing those is a rewrite rather than an
adoption. This package supplies the decisions and leaves the fetch alone.

Two things fixed in the extraction rather than carried over:

- `humanizeWait`'s singular hour was unreachable. With the boundary at 90
  minutes, anything reaching the hours branch divided to at least 1.5, which
  rounds to 2 — so "about 1 hour" could never print and an hour-long wait was
  announced as two. Boundary moved to 60 and the case is now tested.
- The fair-share header quoted a 10k turn cost. A measured turn was ~16k, so the
  worked example understated the squeeze by nearly half.

Tests import the package BY NAME rather than reaching into dist/, so a broken
`exports` map or a `files` list that forgets to ship dist/ fails here instead of
at the first consumer's install.

31 tests, all green via `npm run verify`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 11:49:17 +02:00