@bitbaum/ai-kit 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -58,6 +58,95 @@ the same org-wide daily budget, so when the day runs dry every link in that
58
58
  via a text tool protocol, not native `tool_calls`. A native-only client would
59
59
  have silently lost most of the chain.
60
60
 
61
+ ### Make the call — `complete()` owns the fetch
62
+
63
+ ```ts
64
+ import { complete, freeChain, usableChain, createHealthTracker } from '@bitbaum/ai-kit';
65
+
66
+ export const llmHealth = createHealthTracker();
67
+ const chain = usableChain(freeChain('MYAPP'), process.env);
68
+
69
+ const { text, id } = await complete({
70
+ chain,
71
+ health: llmHealth,
72
+ maxTokens: 500,
73
+ messages: [{ role: 'user', content: 'Summarise this in one line.' }],
74
+ });
75
+ ```
76
+
77
+ For four releases this package shipped the *decisions* and told you to keep the
78
+ fetch. The rule read well and it was wrong: measured 2026-09-05, this fleet ran
79
+ **eight** hand-rolled clients, **two** of which told the three kinds of 429
80
+ apart — while `ai-forms`, which ships a working route factory, had more than
81
+ twice this package's adoption. A package that hands you a working call gets
82
+ installed; one that hands you advice about calls does not.
83
+
84
+ `complete()` is the chain walk plus the request, and it carries the parts that
85
+ kept getting left out of the hand-rolled ones:
86
+
87
+ - a **200 with empty content is a failure**, not an answer — reasoning models
88
+ and some vendors return exactly that, and every client that read
89
+ `choices[0].message.content || ''` shipped the empty string to a user;
90
+ - a **daily** 429 marks the whole vendor dead for the walk, instead of trying
91
+ its other models against the same exhausted org-wide budget;
92
+ - a **size** 429 ends the walk rather than demoting to a *smaller* ceiling,
93
+ which is strictly worse;
94
+ - the vendor's response body survives into the error, so an exhausted day is
95
+ distinguishable from a momentary burst in a log.
96
+
97
+ **`maxTokens` has a floor, and it is higher than you think.** The chain leads
98
+ with reasoning models, which spend the budget on hidden thinking before emitting
99
+ a visible token: `groq/openai/gpt-oss-20b` answered *empty* at 16 and correctly
100
+ at 256 for the same one-word question. A mean budget makes a healthy model look
101
+ dead.
102
+
103
+ `tryChain` stays for a caller with a genuinely unusual request to make.
104
+
105
+ ### Does it work RIGHT NOW? — a probe, not a guess
106
+
107
+ ```ts
108
+ // app/api/health/ai/route.ts — Next App Router, Hono, Deno and Bun all take
109
+ // this shape directly.
110
+ import { createAiHealthHandler, freeChain, usableChain } from '@bitbaum/ai-kit';
111
+ import { llmHealth } from '@/lib/llm-health';
112
+
113
+ const handler = createAiHealthHandler({
114
+ chain: usableChain(freeChain('MYAPP'), process.env),
115
+ health: llmHealth,
116
+ secret: process.env.AI_PROBE_SECRET,
117
+ });
118
+
119
+ export const GET = handler;
120
+ ```
121
+
122
+ ```
123
+ GET /api/health/ai free. What happened last time.
124
+ GET /api/health/ai?probe=1 + the secret makes a real call. 200 or 503.
125
+ ```
126
+
127
+ **Why a probe and not a passive read.** Absence of failure is not evidence of
128
+ success. A tracker that has recorded nothing looks identical whether the chain
129
+ is perfect or every key is missing — and straight after a deploy that is exactly
130
+ the state it is in. Observed converting the first app: the deploy was green, the
131
+ bundle provably held the new code, both keys were present, `/api/health`
132
+ returned 200, and `llm.status` was `"unknown"`. Every available signal said
133
+ "probably fine" and none said "works". The only paths that would have answered
134
+ were an admin-authenticated form and two cron jobs that **email real users** —
135
+ verifying a deploy must never require spamming somebody.
136
+
137
+ **Why it is gated and cached.** A probe spends real tokens from a daily budget
138
+ shared with the app's actual features, so an ungated one on a health route is a
139
+ self-inflicted outage: a monitor polling every 30s would drain the allowance and
140
+ take the AI features down with it. So a probe runs only on `?probe=1` **and**
141
+ with the secret, a *success* is cached for 10 minutes (returned with `cached`
142
+ and its age, because a nine-minute-old success is a different claim from a fresh
143
+ one), and a **failure is never cached** — the whole point is the truth about
144
+ right now.
145
+
146
+ With no secret configured the route answers **501**, not an open probe: an app
147
+ that forgets to set one gets a route that cannot spend money, rather than one
148
+ that can.
149
+
61
150
  ### Is it up? — walk the chain, and know when none of it worked
62
151
 
63
152
  A chain nobody walks is a list, not a fallback. This was found sitting unused
@@ -79,7 +168,7 @@ const { text } = await tryChain(chain, {
79
168
  });
80
169
  ```
81
170
 
82
- No HTTP client here either — `attempt` makes the real request; `tryChain` only
171
+ `attempt` makes the real request; `tryChain` only
83
172
  decides which link goes next and throws `ChainExhaustedError` (naming every
84
173
  link's failure, not just the last) when none of them work.
85
174
 
@@ -180,14 +269,11 @@ React lives on its own subpath and is an **optional** peer, so importing
180
269
 
181
270
  ## What it deliberately does not ship
182
271
 
183
- **An HTTP client.** Every app has its own calling conventions, retries and
184
- logging, and replacing those is a rewrite rather than an adoption. This supplies
185
- the decisions; you keep the fetch.
186
-
187
- That rule is under review, and honestly. `ai-forms` is the most-adopted package
188
- in this fleet and it is the one that broke the rule, by shipping a route factory
189
- and a React hook. A package that hands you a working route gets installed; one
190
- that hands you advice about routes does not.
272
+ **~~An HTTP client.~~** It ships one now see [`complete()`](#make-the-call--complete-owns-the-fetch).
273
+ The old rule ("every app has its own calling conventions, and replacing those is
274
+ a rewrite rather than an adoption") described this fleet's duplication
275
+ accurately and then protected it: the conventions differed because nothing had
276
+ ever offered to own them.
191
277
 
192
278
  **Model values.** Which ids are free, which are billed, and which your account
193
279
  may use are properties of *your* deployment. Centralise the rule, assert it
package/dist/index.d.ts CHANGED
@@ -54,5 +54,6 @@ export { type CatalogVerdict, type CheckCatalogOptions, checkCatalog, hasRot, de
54
54
  export { type ChainAttemptFailure, type TryChainOptions, ChainExhaustedError, tryChain, } from "./attempt.js";
55
55
  export { type ChatMessage, type ToolCall, type CompleteOptions, type CompleteResult, LinkFailure, complete, linkId, } from "./complete.js";
56
56
  export { type HealthStatus, type Health, type HealthTrackerOptions, type HealthTracker, createHealthTracker, } from "./health.js";
57
+ export { type LivenessResult, type LivenessOptions, type LivenessProbe, type AiHealthHandlerOptions, createLivenessProbe, createAiHealthHandler, } from "./liveness.js";
57
58
  export { type RateLimitKind, classifyRateLimit, retryAfterSeconds, humanizeWait, rateLimitMessage, } from "./limits.js";
58
59
  export { DAY_SECONDS, DEFAULT_BURST, type ShareInput, type ShareReason, type ShareDecision, fairShare, utcDayElapsed, utcDayKey, } from "./fair-share.js";
package/dist/index.js CHANGED
@@ -54,6 +54,7 @@ export { checkCatalog, hasRot, deadProviders, catalogReport, } from "./catalog.j
54
54
  export { ChainExhaustedError, tryChain, } from "./attempt.js";
55
55
  export { LinkFailure, complete, linkId, } from "./complete.js";
56
56
  export { createHealthTracker, } from "./health.js";
57
+ export { createLivenessProbe, createAiHealthHandler, } from "./liveness.js";
57
58
  export { classifyRateLimit, retryAfterSeconds, humanizeWait, rateLimitMessage, } from "./limits.js";
58
59
  export { DAY_SECONDS, DEFAULT_BURST, fairShare, utcDayElapsed, utcDayKey, } from "./fair-share.js";
59
60
  // Form filling lives at `ai-kit/forms`, NOT here.
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Can this deployment reach a model RIGHT NOW?
3
+ *
4
+ * ── The gap this closes ──────────────────────────────────────────────────────
5
+ * A health route that reports `createHealthTracker().getHealth()` reports what
6
+ * happened the last time the app happened to call a model. Straight after a
7
+ * deploy that is `"unknown"` — no calls yet — and "unknown" is what it stays
8
+ * until real traffic arrives. So the one question a deploy needs answered ("did
9
+ * I just ship a working AI path?") is exactly the one it cannot answer.
10
+ *
11
+ * Observed 2026-09-05, converting the first app to `complete()`: the deploy was
12
+ * green, the bundle provably contained the new code, both keys were present,
13
+ * `/api/health` returned 200 — and `llm.status` was `"unknown"`. Every signal
14
+ * available said "probably fine". The only paths that would have produced a
15
+ * real answer were an admin-authenticated form and two cron jobs that EMAIL
16
+ * REAL USERS. Verifying a deploy must never require spamming somebody.
17
+ *
18
+ * ── Why it is a probe and not a passive read ─────────────────────────────────
19
+ * Absence of failure is not evidence of success. A tracker that has recorded
20
+ * nothing looks identical whether the chain is perfect or every key is missing.
21
+ * The only thing that distinguishes them is making a call — so this makes one,
22
+ * deliberately, on demand.
23
+ *
24
+ * ── Why it must be gated and cached ──────────────────────────────────────────
25
+ * This spends real tokens from a free daily budget shared across the whole org.
26
+ * An ungated probe on a health route is a self-inflicted outage: a monitor
27
+ * polling every 30s would drain a 100k/day allowance and take the app's actual
28
+ * AI features down with it. So:
29
+ *
30
+ * - a probe runs ONLY when asked for explicitly (`?probe=1`) AND the caller
31
+ * proves it is allowed to (a secret), never on an ordinary health poll;
32
+ * - a successful probe is CACHED for `minIntervalMs` (default 10 minutes),
33
+ * so even an authorised caller in a retry loop cannot burn the budget. The
34
+ * cached answer is returned with `cached: true` and the age, because a
35
+ * nine-minute-old success is a different claim from a fresh one and the
36
+ * reader deserves to know which they got.
37
+ *
38
+ * The prompt is deliberately tiny — a handful of tokens — because the question
39
+ * is "does the pipe carry water", not "is the model any good".
40
+ */
41
+ import { type CompleteOptions } from "./complete.js";
42
+ import type { HealthTracker } from "./health.js";
43
+ export interface LivenessResult {
44
+ /** Did a model answer? */
45
+ ok: boolean;
46
+ /** `provider/model` that served it, when one did. */
47
+ servedBy?: string;
48
+ /** What the model actually said, trimmed — proof of a real generation, not a 200. */
49
+ answer?: string;
50
+ /** Round-trip milliseconds for a fresh probe. */
51
+ ms?: number;
52
+ /** True when this is a remembered result rather than a call made just now. */
53
+ cached: boolean;
54
+ /** Age of a cached result, in milliseconds. */
55
+ cachedAgeMs?: number;
56
+ /** Every link's failure, when the whole chain was exhausted. */
57
+ failures?: string[];
58
+ /** Why no call was attempted at all (no keys, no links). */
59
+ skipped?: string;
60
+ }
61
+ export interface LivenessOptions extends Omit<CompleteOptions, "messages" | "maxTokens" | "temperature"> {
62
+ /**
63
+ * Don't call again within this window; return the last successful result.
64
+ * Default 10 minutes. Set 0 to disable caching — only for a test.
65
+ */
66
+ minIntervalMs?: number;
67
+ /** Injected for tests. Defaults to `Date.now`. */
68
+ now?: () => number;
69
+ }
70
+ export interface LivenessProbe {
71
+ /** Make a call (or return a cached success). */
72
+ run(): Promise<LivenessResult>;
73
+ /** Forget any cached success — the next `run` will really call. */
74
+ reset(): void;
75
+ }
76
+ /**
77
+ * Build a probe with its own cache.
78
+ *
79
+ * The cache lives on the instance rather than in a module global so that two
80
+ * apps in one process, or a test, cannot silently share (and satisfy) each
81
+ * other's probe.
82
+ */
83
+ export declare function createLivenessProbe(options?: LivenessOptions): LivenessProbe;
84
+ export interface AiHealthHandlerOptions extends LivenessOptions {
85
+ /**
86
+ * Shared secret authorising a probe. Compared against the `x-probe-secret`
87
+ * header or a `secret` query parameter.
88
+ *
89
+ * When absent, the handler NEVER probes — it only reports passive health.
90
+ * That default is deliberate: an app that forgets to configure a secret gets
91
+ * a route that cannot spend money, rather than an open endpoint that can.
92
+ */
93
+ secret?: string;
94
+ /** Passive health to report alongside. Optional. */
95
+ health?: HealthTracker;
96
+ }
97
+ /**
98
+ * A framework-neutral `Request -> Response` handler for an AI health route.
99
+ *
100
+ * Web-standard on purpose: Next's App Router, Hono, Deno and Bun all accept
101
+ * this shape directly, so adopting it is an export line rather than a port.
102
+ *
103
+ * GET /api/health/ai passive — what happened last time. Free.
104
+ * GET /api/health/ai?probe=1 makes a real call. Requires the secret.
105
+ *
106
+ * A probe without a valid secret is 401 and does NOT fall back to probing.
107
+ *
108
+ * Status codes are chosen so an uptime monitor can watch this URL directly:
109
+ * 200 when the answer is good, 503 when a probe was attempted and the chain
110
+ * could not answer.
111
+ */
112
+ export declare function createAiHealthHandler(options?: AiHealthHandlerOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Can this deployment reach a model RIGHT NOW?
3
+ *
4
+ * ── The gap this closes ──────────────────────────────────────────────────────
5
+ * A health route that reports `createHealthTracker().getHealth()` reports what
6
+ * happened the last time the app happened to call a model. Straight after a
7
+ * deploy that is `"unknown"` — no calls yet — and "unknown" is what it stays
8
+ * until real traffic arrives. So the one question a deploy needs answered ("did
9
+ * I just ship a working AI path?") is exactly the one it cannot answer.
10
+ *
11
+ * Observed 2026-09-05, converting the first app to `complete()`: the deploy was
12
+ * green, the bundle provably contained the new code, both keys were present,
13
+ * `/api/health` returned 200 — and `llm.status` was `"unknown"`. Every signal
14
+ * available said "probably fine". The only paths that would have produced a
15
+ * real answer were an admin-authenticated form and two cron jobs that EMAIL
16
+ * REAL USERS. Verifying a deploy must never require spamming somebody.
17
+ *
18
+ * ── Why it is a probe and not a passive read ─────────────────────────────────
19
+ * Absence of failure is not evidence of success. A tracker that has recorded
20
+ * nothing looks identical whether the chain is perfect or every key is missing.
21
+ * The only thing that distinguishes them is making a call — so this makes one,
22
+ * deliberately, on demand.
23
+ *
24
+ * ── Why it must be gated and cached ──────────────────────────────────────────
25
+ * This spends real tokens from a free daily budget shared across the whole org.
26
+ * An ungated probe on a health route is a self-inflicted outage: a monitor
27
+ * polling every 30s would drain a 100k/day allowance and take the app's actual
28
+ * AI features down with it. So:
29
+ *
30
+ * - a probe runs ONLY when asked for explicitly (`?probe=1`) AND the caller
31
+ * proves it is allowed to (a secret), never on an ordinary health poll;
32
+ * - a successful probe is CACHED for `minIntervalMs` (default 10 minutes),
33
+ * so even an authorised caller in a retry loop cannot burn the budget. The
34
+ * cached answer is returned with `cached: true` and the age, because a
35
+ * nine-minute-old success is a different claim from a fresh one and the
36
+ * reader deserves to know which they got.
37
+ *
38
+ * The prompt is deliberately tiny — a handful of tokens — because the question
39
+ * is "does the pipe carry water", not "is the model any good".
40
+ */
41
+ import { complete } from "./complete.js";
42
+ import { ChainExhaustedError } from "./attempt.js";
43
+ const DEFAULT_MIN_INTERVAL_MS = 10 * 60 * 1000;
44
+ /**
45
+ * The budget the probe asks for.
46
+ *
47
+ * NOT small, despite the tiny prompt. The chain leads with REASONING models,
48
+ * which spend this on hidden thinking before emitting a visible token: measured
49
+ * 2026-09-05, groq/openai/gpt-oss-20b answered EMPTY at 16 and correctly at 256
50
+ * for the same one-word question. An empty completion is a failure here (see
51
+ * complete.ts), so a mean budget would make a perfectly healthy deployment
52
+ * report itself dead — the exact false alarm this module exists to prevent.
53
+ */
54
+ const PROBE_MAX_TOKENS = 256;
55
+ /** A question with one short right answer, cheap to ask and easy to sanity-check. */
56
+ const PROBE_MESSAGES = [
57
+ { role: "system", content: "Answer with a single word, no punctuation." },
58
+ { role: "user", content: "What colour is a clear midday sky? Answer in one word." },
59
+ ];
60
+ /**
61
+ * Build a probe with its own cache.
62
+ *
63
+ * The cache lives on the instance rather than in a module global so that two
64
+ * apps in one process, or a test, cannot silently share (and satisfy) each
65
+ * other's probe.
66
+ */
67
+ export function createLivenessProbe(options = {}) {
68
+ const minIntervalMs = options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
69
+ const now = options.now ?? Date.now;
70
+ let lastOk = null;
71
+ return {
72
+ reset() {
73
+ lastOk = null;
74
+ },
75
+ async run() {
76
+ if (lastOk && minIntervalMs > 0) {
77
+ const age = now() - lastOk.at;
78
+ if (age < minIntervalMs) {
79
+ return { ...lastOk.result, cached: true, cachedAgeMs: age };
80
+ }
81
+ }
82
+ const started = now();
83
+ try {
84
+ const result = await complete({
85
+ ...options,
86
+ messages: PROBE_MESSAGES,
87
+ maxTokens: PROBE_MAX_TOKENS,
88
+ temperature: 0,
89
+ });
90
+ const answer = result.text.trim();
91
+ const fresh = {
92
+ ok: true,
93
+ servedBy: result.id,
94
+ answer,
95
+ ms: now() - started,
96
+ cached: false,
97
+ };
98
+ lastOk = { at: now(), result: fresh };
99
+ return fresh;
100
+ }
101
+ catch (error) {
102
+ // A failure is deliberately NOT cached. Caching it would keep reporting
103
+ // an outage after the vendor recovered, and the whole point is to tell
104
+ // the truth about right now.
105
+ if (error instanceof ChainExhaustedError) {
106
+ return {
107
+ ok: false,
108
+ cached: false,
109
+ ms: now() - started,
110
+ failures: error.failures.map((f) => f.message),
111
+ ...(error.failures.length === 0
112
+ ? { skipped: "No usable link — every provider is missing its key or has no models." }
113
+ : {}),
114
+ };
115
+ }
116
+ return {
117
+ ok: false,
118
+ cached: false,
119
+ ms: now() - started,
120
+ failures: [error instanceof Error ? error.message : String(error)],
121
+ };
122
+ }
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * A framework-neutral `Request -> Response` handler for an AI health route.
128
+ *
129
+ * Web-standard on purpose: Next's App Router, Hono, Deno and Bun all accept
130
+ * this shape directly, so adopting it is an export line rather than a port.
131
+ *
132
+ * GET /api/health/ai passive — what happened last time. Free.
133
+ * GET /api/health/ai?probe=1 makes a real call. Requires the secret.
134
+ *
135
+ * A probe without a valid secret is 401 and does NOT fall back to probing.
136
+ *
137
+ * Status codes are chosen so an uptime monitor can watch this URL directly:
138
+ * 200 when the answer is good, 503 when a probe was attempted and the chain
139
+ * could not answer.
140
+ */
141
+ export function createAiHealthHandler(options = {}) {
142
+ const { secret, health, ...probeOptions } = options;
143
+ const probe = createLivenessProbe(probeOptions);
144
+ return async function handler(request) {
145
+ const url = new URL(request.url);
146
+ const wantsProbe = url.searchParams.get("probe") === "1";
147
+ const offered = request.headers.get("x-probe-secret") ?? url.searchParams.get("secret") ?? undefined;
148
+ const passive = health ? { health: health.getHealth() } : {};
149
+ if (!wantsProbe) {
150
+ return json(200, { probed: false, ...passive });
151
+ }
152
+ // No secret configured means probing is switched off, which is a different
153
+ // answer from "your secret is wrong" — say so, rather than implying the
154
+ // caller could retry with a better credential.
155
+ if (!secret) {
156
+ return json(501, {
157
+ probed: false,
158
+ error: "Probing is not configured on this deployment (no secret set).",
159
+ ...passive,
160
+ });
161
+ }
162
+ if (!offered || !timingSafeEqual(offered, secret)) {
163
+ return json(401, { probed: false, error: "Bad or missing probe secret.", ...passive });
164
+ }
165
+ const result = await probe.run();
166
+ // Record into passive health too, so one probe also answers the next
167
+ // ordinary health poll — otherwise the probe's knowledge dies with it.
168
+ if (health) {
169
+ if (result.ok)
170
+ health.recordSuccess();
171
+ else
172
+ health.recordFailure(new Error(result.failures?.join("; ") ?? "probe failed"));
173
+ }
174
+ return json(result.ok ? 200 : 503, {
175
+ probed: true,
176
+ ...result,
177
+ ...(health ? { health: health.getHealth() } : {}),
178
+ });
179
+ };
180
+ }
181
+ function json(status, body) {
182
+ return new Response(JSON.stringify(body), {
183
+ status,
184
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
185
+ });
186
+ }
187
+ /**
188
+ * Constant-time comparison, so a wrong secret cannot be discovered one
189
+ * character at a time by timing the 401.
190
+ */
191
+ function timingSafeEqual(a, b) {
192
+ if (a.length !== b.length)
193
+ return false;
194
+ let diff = 0;
195
+ for (let i = 0; i < a.length; i += 1)
196
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
197
+ return diff === 0;
198
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitbaum/ai-kit",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "One install for the AI layer of an app: which model to call, what to do when the vendor retires it, how to walk the fallback chain and know when none of it worked, how to read the three kinds of 429, a fair daily budget across users, headless AI form filling — and now the model registry (one SSOT for every callable id, with the paid/free boundary as a field) and the grounding harness (facts, contract, deterministic fabrication check).",
5
5
  "license": "MIT",
6
6
  "author": "Mao Nakamoto",
package/src/index.ts CHANGED
@@ -100,6 +100,15 @@ export {
100
100
  createHealthTracker,
101
101
  } from "./health.js";
102
102
 
103
+ export {
104
+ type LivenessResult,
105
+ type LivenessOptions,
106
+ type LivenessProbe,
107
+ type AiHealthHandlerOptions,
108
+ createLivenessProbe,
109
+ createAiHealthHandler,
110
+ } from "./liveness.js";
111
+
103
112
  export {
104
113
  type RateLimitKind,
105
114
  classifyRateLimit,
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Can this deployment reach a model RIGHT NOW?
3
+ *
4
+ * ── The gap this closes ──────────────────────────────────────────────────────
5
+ * A health route that reports `createHealthTracker().getHealth()` reports what
6
+ * happened the last time the app happened to call a model. Straight after a
7
+ * deploy that is `"unknown"` — no calls yet — and "unknown" is what it stays
8
+ * until real traffic arrives. So the one question a deploy needs answered ("did
9
+ * I just ship a working AI path?") is exactly the one it cannot answer.
10
+ *
11
+ * Observed 2026-09-05, converting the first app to `complete()`: the deploy was
12
+ * green, the bundle provably contained the new code, both keys were present,
13
+ * `/api/health` returned 200 — and `llm.status` was `"unknown"`. Every signal
14
+ * available said "probably fine". The only paths that would have produced a
15
+ * real answer were an admin-authenticated form and two cron jobs that EMAIL
16
+ * REAL USERS. Verifying a deploy must never require spamming somebody.
17
+ *
18
+ * ── Why it is a probe and not a passive read ─────────────────────────────────
19
+ * Absence of failure is not evidence of success. A tracker that has recorded
20
+ * nothing looks identical whether the chain is perfect or every key is missing.
21
+ * The only thing that distinguishes them is making a call — so this makes one,
22
+ * deliberately, on demand.
23
+ *
24
+ * ── Why it must be gated and cached ──────────────────────────────────────────
25
+ * This spends real tokens from a free daily budget shared across the whole org.
26
+ * An ungated probe on a health route is a self-inflicted outage: a monitor
27
+ * polling every 30s would drain a 100k/day allowance and take the app's actual
28
+ * AI features down with it. So:
29
+ *
30
+ * - a probe runs ONLY when asked for explicitly (`?probe=1`) AND the caller
31
+ * proves it is allowed to (a secret), never on an ordinary health poll;
32
+ * - a successful probe is CACHED for `minIntervalMs` (default 10 minutes),
33
+ * so even an authorised caller in a retry loop cannot burn the budget. The
34
+ * cached answer is returned with `cached: true` and the age, because a
35
+ * nine-minute-old success is a different claim from a fresh one and the
36
+ * reader deserves to know which they got.
37
+ *
38
+ * The prompt is deliberately tiny — a handful of tokens — because the question
39
+ * is "does the pipe carry water", not "is the model any good".
40
+ */
41
+
42
+ import { complete, type CompleteOptions } from "./complete.js";
43
+ import { ChainExhaustedError } from "./attempt.js";
44
+ import type { HealthTracker } from "./health.js";
45
+
46
+ export interface LivenessResult {
47
+ /** Did a model answer? */
48
+ ok: boolean;
49
+ /** `provider/model` that served it, when one did. */
50
+ servedBy?: string;
51
+ /** What the model actually said, trimmed — proof of a real generation, not a 200. */
52
+ answer?: string;
53
+ /** Round-trip milliseconds for a fresh probe. */
54
+ ms?: number;
55
+ /** True when this is a remembered result rather than a call made just now. */
56
+ cached: boolean;
57
+ /** Age of a cached result, in milliseconds. */
58
+ cachedAgeMs?: number;
59
+ /** Every link's failure, when the whole chain was exhausted. */
60
+ failures?: string[];
61
+ /** Why no call was attempted at all (no keys, no links). */
62
+ skipped?: string;
63
+ }
64
+
65
+ export interface LivenessOptions extends Omit<
66
+ CompleteOptions,
67
+ "messages" | "maxTokens" | "temperature"
68
+ > {
69
+ /**
70
+ * Don't call again within this window; return the last successful result.
71
+ * Default 10 minutes. Set 0 to disable caching — only for a test.
72
+ */
73
+ minIntervalMs?: number;
74
+ /** Injected for tests. Defaults to `Date.now`. */
75
+ now?: () => number;
76
+ }
77
+
78
+ const DEFAULT_MIN_INTERVAL_MS = 10 * 60 * 1000;
79
+
80
+ /**
81
+ * The budget the probe asks for.
82
+ *
83
+ * NOT small, despite the tiny prompt. The chain leads with REASONING models,
84
+ * which spend this on hidden thinking before emitting a visible token: measured
85
+ * 2026-09-05, groq/openai/gpt-oss-20b answered EMPTY at 16 and correctly at 256
86
+ * for the same one-word question. An empty completion is a failure here (see
87
+ * complete.ts), so a mean budget would make a perfectly healthy deployment
88
+ * report itself dead — the exact false alarm this module exists to prevent.
89
+ */
90
+ const PROBE_MAX_TOKENS = 256;
91
+
92
+ /** A question with one short right answer, cheap to ask and easy to sanity-check. */
93
+ const PROBE_MESSAGES = [
94
+ { role: "system" as const, content: "Answer with a single word, no punctuation." },
95
+ { role: "user" as const, content: "What colour is a clear midday sky? Answer in one word." },
96
+ ];
97
+
98
+ export interface LivenessProbe {
99
+ /** Make a call (or return a cached success). */
100
+ run(): Promise<LivenessResult>;
101
+ /** Forget any cached success — the next `run` will really call. */
102
+ reset(): void;
103
+ }
104
+
105
+ /**
106
+ * Build a probe with its own cache.
107
+ *
108
+ * The cache lives on the instance rather than in a module global so that two
109
+ * apps in one process, or a test, cannot silently share (and satisfy) each
110
+ * other's probe.
111
+ */
112
+ export function createLivenessProbe(options: LivenessOptions = {}): LivenessProbe {
113
+ const minIntervalMs = options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
114
+ const now = options.now ?? Date.now;
115
+
116
+ let lastOk: { at: number; result: LivenessResult } | null = null;
117
+
118
+ return {
119
+ reset() {
120
+ lastOk = null;
121
+ },
122
+
123
+ async run(): Promise<LivenessResult> {
124
+ if (lastOk && minIntervalMs > 0) {
125
+ const age = now() - lastOk.at;
126
+ if (age < minIntervalMs) {
127
+ return { ...lastOk.result, cached: true, cachedAgeMs: age };
128
+ }
129
+ }
130
+
131
+ const started = now();
132
+ try {
133
+ const result = await complete({
134
+ ...options,
135
+ messages: PROBE_MESSAGES,
136
+ maxTokens: PROBE_MAX_TOKENS,
137
+ temperature: 0,
138
+ });
139
+
140
+ const answer = result.text.trim();
141
+ const fresh: LivenessResult = {
142
+ ok: true,
143
+ servedBy: result.id,
144
+ answer,
145
+ ms: now() - started,
146
+ cached: false,
147
+ };
148
+ lastOk = { at: now(), result: fresh };
149
+ return fresh;
150
+ } catch (error) {
151
+ // A failure is deliberately NOT cached. Caching it would keep reporting
152
+ // an outage after the vendor recovered, and the whole point is to tell
153
+ // the truth about right now.
154
+ if (error instanceof ChainExhaustedError) {
155
+ return {
156
+ ok: false,
157
+ cached: false,
158
+ ms: now() - started,
159
+ failures: error.failures.map((f) => f.message),
160
+ ...(error.failures.length === 0
161
+ ? { skipped: "No usable link — every provider is missing its key or has no models." }
162
+ : {}),
163
+ };
164
+ }
165
+ return {
166
+ ok: false,
167
+ cached: false,
168
+ ms: now() - started,
169
+ failures: [error instanceof Error ? error.message : String(error)],
170
+ };
171
+ }
172
+ },
173
+ };
174
+ }
175
+
176
+ export interface AiHealthHandlerOptions extends LivenessOptions {
177
+ /**
178
+ * Shared secret authorising a probe. Compared against the `x-probe-secret`
179
+ * header or a `secret` query parameter.
180
+ *
181
+ * When absent, the handler NEVER probes — it only reports passive health.
182
+ * That default is deliberate: an app that forgets to configure a secret gets
183
+ * a route that cannot spend money, rather than an open endpoint that can.
184
+ */
185
+ secret?: string;
186
+ /** Passive health to report alongside. Optional. */
187
+ health?: HealthTracker;
188
+ }
189
+
190
+ /**
191
+ * A framework-neutral `Request -> Response` handler for an AI health route.
192
+ *
193
+ * Web-standard on purpose: Next's App Router, Hono, Deno and Bun all accept
194
+ * this shape directly, so adopting it is an export line rather than a port.
195
+ *
196
+ * GET /api/health/ai passive — what happened last time. Free.
197
+ * GET /api/health/ai?probe=1 makes a real call. Requires the secret.
198
+ *
199
+ * A probe without a valid secret is 401 and does NOT fall back to probing.
200
+ *
201
+ * Status codes are chosen so an uptime monitor can watch this URL directly:
202
+ * 200 when the answer is good, 503 when a probe was attempted and the chain
203
+ * could not answer.
204
+ */
205
+ export function createAiHealthHandler(
206
+ options: AiHealthHandlerOptions = {},
207
+ ): (request: Request) => Promise<Response> {
208
+ const { secret, health, ...probeOptions } = options;
209
+ const probe = createLivenessProbe(probeOptions);
210
+
211
+ return async function handler(request: Request): Promise<Response> {
212
+ const url = new URL(request.url);
213
+ const wantsProbe = url.searchParams.get("probe") === "1";
214
+ const offered =
215
+ request.headers.get("x-probe-secret") ?? url.searchParams.get("secret") ?? undefined;
216
+
217
+ const passive = health ? { health: health.getHealth() } : {};
218
+
219
+ if (!wantsProbe) {
220
+ return json(200, { probed: false, ...passive });
221
+ }
222
+
223
+ // No secret configured means probing is switched off, which is a different
224
+ // answer from "your secret is wrong" — say so, rather than implying the
225
+ // caller could retry with a better credential.
226
+ if (!secret) {
227
+ return json(501, {
228
+ probed: false,
229
+ error: "Probing is not configured on this deployment (no secret set).",
230
+ ...passive,
231
+ });
232
+ }
233
+ if (!offered || !timingSafeEqual(offered, secret)) {
234
+ return json(401, { probed: false, error: "Bad or missing probe secret.", ...passive });
235
+ }
236
+
237
+ const result = await probe.run();
238
+ // Record into passive health too, so one probe also answers the next
239
+ // ordinary health poll — otherwise the probe's knowledge dies with it.
240
+ if (health) {
241
+ if (result.ok) health.recordSuccess();
242
+ else health.recordFailure(new Error(result.failures?.join("; ") ?? "probe failed"));
243
+ }
244
+ return json(result.ok ? 200 : 503, {
245
+ probed: true,
246
+ ...result,
247
+ ...(health ? { health: health.getHealth() } : {}),
248
+ });
249
+ };
250
+ }
251
+
252
+ function json(status: number, body: unknown): Response {
253
+ return new Response(JSON.stringify(body), {
254
+ status,
255
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
256
+ });
257
+ }
258
+
259
+ /**
260
+ * Constant-time comparison, so a wrong secret cannot be discovered one
261
+ * character at a time by timing the 401.
262
+ */
263
+ function timingSafeEqual(a: string, b: string): boolean {
264
+ if (a.length !== b.length) return false;
265
+ let diff = 0;
266
+ for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
267
+ return diff === 0;
268
+ }