@ultimat3/ai 31.25.0 → 31.27.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/CLAUDE.md CHANGED
@@ -22,7 +22,7 @@ Keep `policy` dev-only: tests and `*-fixture.ts` harnesses import `allow`. The
22
22
  | `model-fixture.ts` | the rows this package's own suites register (`useFixtureModels()`). Not shipped |
23
23
  | `provider.ts` | `Provider` interface, the request half; re-exports the Anthropic names |
24
24
  | `anthropic-provider.ts` | `anthropicProvider()`, its stream-only rule (`requiresStreaming`) and message parse |
25
- | `echo-provider.ts` | `echoProvider()`, the deterministic double — split from `provider.ts` at its line ceiling. A fixture that needs a tool call uses `scriptedProvider`, never a hand-rolled `Provider` |
25
+ | `echo-provider.ts` | `echoProvider()`, the deterministic double. A fixture that needs a tool call uses `scriptedProvider`, never a hand-rolled `Provider` |
26
26
  | `scripted-provider.ts` | `scriptedProvider()`, the scripted double that calls tools, and `X_AI_SCRIPT_EXHAUSTED`: one call past the script is refused, never answered with the last turn again |
27
27
  | `content-blocks.ts` | the `image` / `document` block shapes, the screen every request runs them through, their token estimate |
28
28
  | `content-errors.ts` | the `X_AI_CONTENT_UNSUPPORTED` class; its code and title belong in `error-codes.ts` |
@@ -33,7 +33,8 @@ Keep `policy` dev-only: tests and `*-fixture.ts` harnesses import `allow`. The
33
33
  | `openai-messages.ts` | the format mapping's request half: `AiMessage` blocks → OpenAI messages, `LlmTool` → functions, `tool_choice` |
34
34
  | `openai-body.ts` | one chat-completions body, and the per-model reasoning mapping |
35
35
  | `openai-wire.ts` / `openai-wire-stream.ts` | its response half: one completion and the field readers; `ChatCompletionStream` (fragmented tool calls, trailing usage, `[DONE]`) |
36
- | `gateway.ts` | routing, cache, budget wiring |
36
+ | `gateway.ts` / `gateway-settle.ts` | routing, cache, budget wiring; a failed settle, the cache key |
37
+ | `model-fallback.ts` / `provider-options.ts` | `MODEL_FALLBACK_ON`, the chain walk; the `providerOptions` screen |
37
38
  | `gateway-providers.ts` | the retry loop across providers, `backoffMs`, `isRetryable`, the breakers |
38
39
  | `budget.ts` / `budget-store.ts` | token ledgers per request/actor/org, ALS carrier; the `BudgetStore` contract and `memoryBudgetStore()` |
39
40
  | `prompt.ts` | `definePrompt`, `promptHash`, version registry |
@@ -142,9 +143,9 @@ Why each is shaped this way: [`docs/history/ai.md`](../../docs/history/ai.md#llm
142
143
  (`chunksRead()` false: JSON, MCP, `.job()`) it is the ordinary call, repair turn included.
143
144
  - **`configureAi({ redact })` is the one seam between `vars()` and the provider**; a `Secret` in
144
145
  `vars()` is `X_AI_PROMPT_SECRET` regardless.
145
- - **Fallback is across PROVIDERS serving one model, never across models**; `GenerateResult.provider`
146
- is stamped by the gateway. Server-side `fallbacks` (beta) are never sent. Media generation:
147
- absent, awaiting an owner decision (OD8).
146
+ - **Across models ONLY by a declared `fallbackModels` (`llm()`, `agent()`), on
147
+ `MODEL_FALLBACK_ON`**: billed per attempt, a span per model, a stream before its first chunk.
148
+ Server-side `fallbacks` never sent. Media: absent (OD8). Full rule: `docs/history/ai.md`.
148
149
  - **A slot inside a tag pair is DATA** (`prompt-fence.ts`, #689): `render` breaks every fence closer
149
150
  a fenced value wrote, in the ASSEMBLED prompt — never deletes, never touches a template's own.
150
151
  - `definePrompt` refuses a re-registered version whose hash moved; the hash is over core's
@@ -284,5 +285,3 @@ docker run -d -e POSTGRES_PASSWORD=ultimate -p 5432:5432 pgvector/pgvector:pg17
284
285
  TEST_DATABASE_URL=postgres://postgres:ultimate@localhost:5432/postgres \
285
286
  bun test ./packages/ai/src/pg-vector.live.test.ts
286
287
  ```
287
-
288
- Why each rule above is shaped the way it is: [`docs/history/ai.md`](../../docs/history/ai.md).
package/README.md CHANGED
@@ -140,7 +140,7 @@ default store at `replicas: 6` is six ledgers of twenty million, which is a budg
140
140
  | A budget **refuses**, never truncates | a shortened prompt yields a confidently wrong answer with no signal |
141
141
  | Cost is **integer minor units** (`@ultimat3/money`) | token spend is money; the house rule has no exception |
142
142
  | Cost rounds **up** | a rounded-away fraction is money the framework absorbs and a budget under-reports |
143
- | `temperature` / `top_p` / `top_k` are never sent | rejected with a 400 on every current model — steer with the prompt |
143
+ | `temperature` / `top_p` / `top_k` are never sent unasked | rejected with a 400 on every current reasoning model — steer with the prompt; `temperature` goes only to a row that takes it, `top_p` only through `providerOptions.openai` |
144
144
  | `effort` goes in `output_config` | a top-level `effort` is silently ignored |
145
145
  | The reasoning half of the body is **per model** | `effort` and adaptive thinking arrived with 4.6; sending them to an older model is a 400 on every request |
146
146
  | A control the model lacks is **refused**, never dropped | a declaration reading `effort: 'max'` that quietly runs at the default is the failure nobody can see |
@@ -148,13 +148,15 @@ default store at `replicas: 6` is six ledgers of twenty million, which is a budg
148
148
  | A refusal is `X_LLM_REFUSED`, not a schema failure | it is a 200 with no answer in it, and a repair turn buys the same refusal again |
149
149
  | The refusal's `alternative` is only ever a **more capable** model | registration order is most-capable-first and `moreCapableThan` walks it upward; retrying a refusal on a weaker model is the one retry that cannot help, so an unbeatable model gets no suggestion at all |
150
150
  | A local refusal is never collected into `X_AI_PROVIDER_UNAVAILABLE` | `X_AI_KEY_MISSING` and `X_AI_REQUEST_INVALID` are raised before the request leaves; retrying them across providers burns attempts on the same answer and discards the runnable `fix:`. `generate()` and `stream()` therefore answer the same misconfiguration the same way |
151
- | Fallback is across **providers serving one model**, never across models | a silent model swap changes what answered, what it cost and which eval baseline the answer belongs to; the gateway stamps `result.provider`, and `llm()` puts it on the span as `gen_ai.provider.name`, so the fallback that does exist is never silent |
151
+ | Fallback is across **providers serving one model**; across models **only** through the request's declared `fallbackModels` | a silent model swap changes what answered, what it cost and which eval baseline the answer belongs to; the gateway stamps `result.provider`, and `llm()` puts it on the span as `gen_ai.provider.name`, so the fallback that does exist is never silent |
152
+ | `fallbackModels` falls over on a **declared class** only (`MODEL_FALLBACK_ON`: `rate_limited` 429, `overloaded` 529, `timeout` 408/504/`ETIMEDOUT`, `unavailable` other 5xx, dropped sockets, every breaker open) | a 4xx, a refusal, a budget or an abort fails the same way on every model. Each model reserves and settles on its own; on `llm()`, `agent()` (each turn; a run's own `model()` left out of the chain) or a raw request; the run meter counts a failed model as an `unsettled` attempt, the last one too when it fails outside the class, and prices a fallback's answer at its own rate; one parent span, an `ai.model.attempt` child per model; `result.fallbacks` names each failed model. A stream falls over only before its first chunk. The chain is screened first: unregistered `X_AI_MODEL_UNKNOWN`, repeated `X_AI_REQUEST_INVALID`; all failing is one `X_AI_PROVIDER_UNAVAILABLE` naming `a → b` |
153
+ | Wire parameters go through **`providerOptions`, one typed bag per wire** (`PROVIDER_OPTION_KEYS`: `anthropic` `metadata`/`service_tier`; `openai` `top_p`/`frequency_penalty`/`presence_penalty`/`user`/`parallel_tool_calls`/`service_tier`) | an unknown wire, key, type or range is `X_AI_REQUEST_INVALID` before any request — at `llm()` / `agent()` declaration, in the gateway, and in each body builder; each provider sends only its own wire's bag; the bag is in the response cache key |
152
154
  | The repair turn replays the tool call's arguments, never an empty `text` | an answer through the `respond` tool leaves `text` empty, and an empty text block is a 400 — the repair came back as `X_AI_PROVIDER_UNAVAILABLE` |
153
155
  | `reserve()` **debits, then checks** | the in-memory scopes check and debit with no `await` between, the store's through its atomic `take`; a read-then-write let concurrent calls — one request per scope racing one org key — all read the same `spent()` and all pass. `record` reconciles and `release` gives it back |
154
156
  | The cache key is every tool **whole**, through core's `fingerprint` | every `llm()` tool is named `respond`, so a key over names served an answer shaped for an old `output` schema; a cache `set` that throws is logged, never turned into a failure of a call already paid for |
155
157
  | A refusal is never cached | a cached one keeps serving a classifier decision after the prompt was fixed |
156
158
  | A cache hit reads zero `usage`, `cost` and `costExact`, in the same currency | it is not debited, so a meter summing the stored figures read more than the budget beside it |
157
- | `retry` is **core's `RetryPolicy`**; the default is full jitter (`DEFAULT_GATEWAY_RETRY`: `{ attempts: 3, base: 500, max: 8_000, jitter: 'full' }`) | synchronised retries from N workers reproduce the rate limit. `backoffMs` is `@ultimat3/core`'s `backoffDelay` over the policy, `timeBudgetMs` bounds the whole call across providers, and the roll is `providerGateway({ random })` — injectable, so the schedule is a unit test rather than a range |
159
+ | `retry` is **core's `RetryPolicy`**; the default is full jitter (`DEFAULT_GATEWAY_RETRY`: `{ attempts: 3, base: 500, max: 8_000, jitter: 'full' }`) | synchronised retries from N workers reproduce the rate limit. `backoffMs` is `@ultimat3/core`'s `backoffDelay` over the policy, `timeBudgetMs` bounds the whole call across providers and a `fallbackModels` chain, checked before every call after the first (`providerGateway({ clock })` injects its clock), and the roll is `providerGateway({ random })` — injectable, so the schedule is a unit test rather than a range |
158
160
  | **One breaker per provider**, on by default: `{ failures: 5, cooldownMs: 30_000 }` (`DEFAULT_GATEWAY_BREAKER`) | a provider that ran out its retries five passes in a row is skipped, no call and no sleep, until one probe after the cooldown answers; without it every call re-spent every attempt on a dead provider. `providerGateway({ breaker })` takes `GatewayBreakerOption`, `((provider) => Breaker) \| 'off'`: your own core `breaker({ … })` per provider, or `'off'` for the old behaviour. A stream goes to the first provider whose breaker admits it |
159
161
  | A 4xx is never retried **except 408, 409 and 425** | the same body gets the same rejection and burns the budget — but a request the server stopped reading (408), a round a concurrent writer won (409) and a handshake that had not finished (425) are transient by construction, and core's `isRetryableStatus` is the one table that says so |
160
162
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/ai",
3
- "version": "31.25.0",
3
+ "version": "31.27.0",
4
4
  "description": "LLM gateway, versioned prompts, evals as tests, embeddings, hybrid vector search, RAG",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,17 +45,17 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/action": "31.25.0",
49
- "@ultimat3/cache": "31.25.0",
50
- "@ultimat3/core": "31.25.0",
51
- "@ultimat3/db": "31.25.0",
52
- "@ultimat3/http": "31.25.0",
53
- "@ultimat3/jobs": "31.25.0",
54
- "@ultimat3/money": "31.25.0",
55
- "@ultimat3/schema": "31.25.0",
56
- "@ultimat3/time": "31.25.0"
48
+ "@ultimat3/action": "31.27.0",
49
+ "@ultimat3/cache": "31.27.0",
50
+ "@ultimat3/core": "31.27.0",
51
+ "@ultimat3/db": "31.27.0",
52
+ "@ultimat3/http": "31.27.0",
53
+ "@ultimat3/jobs": "31.27.0",
54
+ "@ultimat3/money": "31.27.0",
55
+ "@ultimat3/schema": "31.27.0",
56
+ "@ultimat3/time": "31.27.0"
57
57
  },
58
58
  "devDependencies": {
59
- "@ultimat3/policy": "31.25.0"
59
+ "@ultimat3/policy": "31.27.0"
60
60
  }
61
61
  }
@@ -67,7 +67,8 @@ function writerRequest(
67
67
  messages: readonly AiMessage[],
68
68
  ): GenerateRequest {
69
69
  if (writer === base.model) return { ...base, messages, maxTokens };
70
- const { effort: _effort, thinking: _thinking, ...rest } = base;
70
+ // Nor the run model's fallback chain: a separate writer is its own choice, and may be in it.
71
+ const { effort: _effort, thinking: _thinking, fallbackModels: _chain, ...rest } = base;
71
72
  return { ...rest, model: writer, messages, maxTokens };
72
73
  }
73
74
 
@@ -195,7 +195,9 @@ export function compactor(input: CompactorInput): Compactor {
195
195
  // Its own meter, inside the run's: the bill reaches the run as a nested call's does — on the
196
196
  // same ledger, in `tokensPerRun` and `costPerRun`, priced at the summary model's own rates.
197
197
  result = await input.deadline.guard(
198
- runMeter().call(reportedCall(request.model ?? writer, input.gateway.generate(request))),
198
+ runMeter().call(() =>
199
+ reportedCall(request.model ?? writer, input.gateway.generate(request)),
200
+ ),
199
201
  );
200
202
  } catch (error) {
201
203
  throwIfAborted(input.ctx);
package/src/agent-def.ts CHANGED
@@ -14,6 +14,7 @@ import type { ModelId } from './models';
14
14
  import type { Prompt, PromptVars } from './prompt';
15
15
  import type { PromptCacheOption } from './prompt-cache';
16
16
  import type { StopReason, TokenUsage } from './provider';
17
+ import type { ProviderOptions } from './provider-options';
17
18
  import type { AgentTool } from './tools';
18
19
 
19
20
  export interface AgentBudget extends LlmBudget {
@@ -71,6 +72,14 @@ export interface AgentDef<
71
72
  * model the run started on or is refused.
72
73
  */
73
74
  readonly model?: AgentModel<TInput>;
75
+ /**
76
+ * Tried in order, per turn, when the run's model fails with a declared class
77
+ * (`MODEL_FALLBACK_ON`) — never on a 400, a refusal or a budget. Each attempt is reserved and
78
+ * billed. The handle stays bound to the run's model; `onTurn` names the model that answered.
79
+ */
80
+ readonly fallbackModels?: readonly ModelId[];
81
+ /** Wire parameters the framework does not model, one bag per wire, screened at declaration. */
82
+ readonly providerOptions?: ProviderOptions;
74
83
  readonly input: TInput;
75
84
  readonly output: TOutput;
76
85
  readonly prompt: Prompt<V>;
@@ -61,3 +61,11 @@ export function runTotal(
61
61
  costExact: addMoney(base.costExact, below.cost),
62
62
  };
63
63
  }
64
+
65
+ /**
66
+ * The model a run's OWN usage is priced on after `result`: the one the call asked for. A turn that
67
+ * fell over to a `fallbackModels` model answered at that model's price, billed apart
68
+ * (`RunMeter.below`), so it must not re-price the rest.
69
+ */
70
+ export const pricedOn = (result: GenerateResult): ModelId =>
71
+ result.fallbacks?.[0]?.model ?? result.model;
package/src/agent.ts CHANGED
@@ -48,15 +48,17 @@ import type { ToolRun } from './agent-tools';
48
48
  import { DEFAULT_TOOL_CONCURRENCY, toolTurn } from './agent-tools';
49
49
  import { assistantTurn, repairTurn } from './agent-transcript';
50
50
  import { assertAnswerable, observeTurn } from './agent-turn';
51
- import { runTotal } from './agent-usage';
51
+ import { pricedOn, runTotal } from './agent-usage';
52
52
  import { budgetKeysFor, currentBudget, withBudget } from './budget';
53
53
  import { AgentMaxTurnsError, AgentToolUnexposedError, LlmOutputInvalidError } from './errors';
54
54
  import { answerAttributes } from './llm-answer';
55
55
  import { reportedCall } from './llm-instrument';
56
+ import { declaredFallbacks } from './model-fallback';
56
57
  import type { PromptVars } from './prompt';
57
58
  import { promptCacheHint } from './prompt-cache';
58
59
  import type { AiMessage, GenerateRequest } from './provider';
59
60
  import { estimateCost } from './provider';
61
+ import { screenProviderOptions } from './provider-options';
60
62
  import { assertNoSecrets } from './redaction';
61
63
  import type { Respond } from './respond';
62
64
  import { RESPOND, respondFor } from './respond';
@@ -102,6 +104,8 @@ export function agent<
102
104
  // This declaration's identity for `.run()` / `.continue()` sessions (`claimAgentSession`).
103
105
  const owner = {};
104
106
  const sampling = screenSampling(SUBJECT, def);
107
+ // A bag the wire would refuse fails the boot, not the first turn — `llm()`'s screen.
108
+ screenProviderOptions(def.providerOptions);
105
109
  const compact = screenCompact(def.compact, bounds.maxTokens);
106
110
  const toolConcurrency = finiteCount(
107
111
  SUBJECT,
@@ -245,6 +249,9 @@ async function run<
245
249
  ...(prompt.effort === undefined ? {} : { effort: prompt.effort }),
246
250
  ...(prompt.thinking === undefined ? {} : { thinking: prompt.thinking }),
247
251
  ...sampling,
252
+ // Every turn walks the same chain; the run's own model is never one of its fallbacks.
253
+ ...declaredFallbacks(model, def.fallbackModels),
254
+ ...(def.providerOptions === undefined ? {} : { providerOptions: def.providerOptions }),
248
255
  tools: [...adapted.offered, respond.tool],
249
256
  // The caller's own signal, forwarded to the transport. A disconnect has to reach the socket,
250
257
  // not just the top of the next turn: a provider call already in flight is the expensive one.
@@ -293,7 +300,7 @@ async function run<
293
300
  send: (request) => {
294
301
  assertCost(request);
295
302
  // `reportedCall`: each turn is one model call, so each is one `ai.llm` (`llm-instrument.ts`).
296
- const answered = reportedCall(request.model ?? model, gateway.generate(request));
303
+ const answered = () => reportedCall(request.model ?? model, gateway.generate(request));
297
304
  return deadline.guard(meter.call(answered)).catch((error: unknown) => {
298
305
  // The caller left mid-call: the aborted socket reads as a provider failure, which is
299
306
  // RETRYABLE. Say what happened instead.
@@ -376,7 +383,7 @@ async function run<
376
383
  cost: result.cost,
377
384
  ...(result.costExact === undefined ? {} : { costExact: result.costExact }),
378
385
  ...(rejected === undefined ? {} : { repairOf: rejected }),
379
- run: runTotal(result.model, prior?.usage, meter.total(), meter.below()),
386
+ run: runTotal(pricedOn(result), prior?.usage, meter.total(), meter.below()),
380
387
  });
381
388
  if (result.text !== '') emit({ type: 'text', turn, text: result.text });
382
389
  // Before a tool runs and before the answer is read (`X_LLM_REFUSED`, `X_LLM_TRUNCATED`).
@@ -394,7 +401,7 @@ async function run<
394
401
  if (parsed.issues === undefined) {
395
402
  // Kept only for `.run()` / `.continue()`: a plain call leaves nothing behind.
396
403
  if (session !== undefined) {
397
- const usage = runTotal(result.model, prior?.usage, meter.total(), meter.below());
404
+ const usage = runTotal(pricedOn(result), prior?.usage, meter.total(), meter.below());
398
405
  session.finished = {
399
406
  transcript: sealTranscript(binding, {
400
407
  messages: [...messages, assistantTurn(result)],
@@ -18,6 +18,7 @@ import { promptCacheRule } from './prompt-cache';
18
18
  import { anthropicPrompt } from './prompt-cache-blocks';
19
19
  import { screenCacheRows } from './prompt-cache-rows';
20
20
  import type { GenerateRequest, GenerateResult, Provider, StreamChunk } from './provider';
21
+ import { providerOptionsBody } from './provider-options';
21
22
  import { samplingBody } from './sampling';
22
23
  import { readSse } from './sse';
23
24
  import { trackSent, trackStreamBill } from './stream-bill';
@@ -78,7 +79,8 @@ export function anthropicProvider(input: AnthropicProviderInput): AnthropicProvi
78
79
  * The real Messages API shape. The request-surface rules are encoded rather than documented,
79
80
  * because getting them wrong is a 400:
80
81
  * - `top_p`/`top_k` are never sent, and `temperature` only to a model whose row takes it
81
- * (`ModelSpec.sampling`): a reasoning model rejects all three.
82
+ * (`ModelSpec.sampling`): a reasoning model rejects all three. `providerOptions.anthropic`
83
+ * is the one pass-through, and its keys are a closed, screened set (`./provider-options`).
82
84
  * - `thinking.budget_tokens` is REJECTED. Use `output_config.effort`.
83
85
  * - `effort` and adaptive thinking are per-model, and ./models owns which model takes which.
84
86
  */
@@ -204,6 +206,8 @@ export class AnthropicProvider implements Provider {
204
206
  messages: prompt.messages,
205
207
  ...reasoningBody(model, request.effort, request.thinking),
206
208
  ...samplingBody('anthropic', model, request),
209
+ // The app's explicit wire parameters, screened; no key collides with a field set above.
210
+ ...providerOptionsBody('anthropic', request.providerOptions),
207
211
  };
208
212
  if (prompt.system !== undefined) body['system'] = prompt.system;
209
213
  if (request.tools !== undefined && request.tools.length > 0) body['tools'] = request.tools;
package/src/errors.ts CHANGED
@@ -5,6 +5,7 @@ import { UltimateError } from '@ultimat3/core';
5
5
  // The codes, their titles and the single registration call are `./error-codes`, imported here for
6
6
  // that side effect.
7
7
  import './error-codes';
8
+ import type { ModelFallback, ModelFallbackClass } from './model-fallback';
8
9
 
9
10
  // No `docs:` on the subclasses below. `UltimateError` fills it from `describeErrorCode(code).docs`,
10
11
  // which is `@ultimat3/core`'s `ERROR_DOCS_URL` — one page for every code, never one per code, because
@@ -15,6 +16,9 @@ import './error-codes';
15
16
 
16
17
  /** Every configured provider refused or errored. Carries what each one said. */
17
18
  export class AiProviderUnavailableError extends UltimateError {
19
+ readonly fallback: ModelFallbackClass | undefined;
20
+ readonly fellOver: readonly ModelFallback[] | undefined;
21
+
18
22
  constructor(input: {
19
23
  model: string;
20
24
  attempts: readonly string[];
@@ -26,6 +30,13 @@ export class AiProviderUnavailableError extends UltimateError {
26
30
  * classification, so the retry vocabulary stays in one file.
27
31
  */
28
32
  readonly unserved?: boolean;
33
+ /**
34
+ * The declared class this failure falls over on (`./model-fallback`), set by the retry loop only
35
+ * when EVERY collected failure had one. Absent: the next model in a chain is not asked.
36
+ */
37
+ readonly fallback?: ModelFallbackClass | undefined;
38
+ /** Set when a whole `fallbackModels` chain failed: each model's attempt, for the run meter. */
39
+ readonly fellOver?: readonly ModelFallback[] | undefined;
29
40
  }) {
30
41
  super({
31
42
  code: 'X_AI_PROVIDER_UNAVAILABLE',
@@ -33,6 +44,8 @@ export class AiProviderUnavailableError extends UltimateError {
33
44
  fix: 'check ai.providers in app.config.ts and the provider API key env var',
34
45
  retry: input.unserved === true ? 'terminal' : undefined,
35
46
  });
47
+ this.fallback = input.fallback;
48
+ this.fellOver = input.fellOver;
36
49
  }
37
50
  }
38
51
 
@@ -16,6 +16,8 @@ import {
16
16
  tryUseContext,
17
17
  } from '@ultimat3/core';
18
18
  import { AiProviderUnavailableError } from './errors';
19
+ import type { ModelFallbackClass } from './model-fallback';
20
+ import { transportFallbackClass } from './model-fallback';
19
21
  import type { ModelId } from './models';
20
22
  import type { GenerateResult, Provider } from './provider';
21
23
 
@@ -112,23 +114,48 @@ export interface AttemptInput {
112
114
  readonly random: Random | undefined;
113
115
  readonly gateOf: (provider: Provider) => Breaker | undefined;
114
116
  readonly call: (provider: Provider) => Promise<GenerateResult>;
117
+ /** When the whole call began — a `fallbackModels` chain shares one `timeBudgetMs`. */
118
+ readonly startedAt?: number;
119
+ /** The clock `startedAt` was read from; `systemClock` absent. */
120
+ readonly monotonic?: () => number;
121
+ /** A later model of a chain: the budget is checked before its FIRST call too. */
122
+ readonly continuing?: boolean;
115
123
  }
116
124
 
117
125
  /**
118
126
  * Try every provider that serves the model, retrying each on a retryable failure with full-jitter
119
- * backoff, skipping one whose breaker is open — no call, no sleep. Fallback is across PROVIDERS
120
- * serving one model, never across models: a silent model swap changes what answered and what it
121
- * cost. The provider that answered is stamped onto the result.
127
+ * backoff, skipping one whose breaker is open — no call, no sleep. This loop falls back across
128
+ * PROVIDERS serving one model, never across models: a model swap is only ever the request's own
129
+ * declared `fallbackModels` (`./model-fallback`), which this loop's thrown verdict feeds. The
130
+ * provider that answered is stamped onto the result.
122
131
  */
123
132
  export async function attemptProviders(input: AttemptInput): Promise<GenerateResult> {
124
133
  const { model, retry } = input;
125
134
  const failures: string[] = [];
135
+ // The model chain's verdict (`./model-fallback`): the first declared class seen, and whether
136
+ // EVERY failure had one — a single deterministic answer means the next model is not asked.
137
+ let fallback: ModelFallbackClass | undefined;
138
+ let classed = true;
139
+ const classify = (reason: ModelFallbackClass | undefined): void => {
140
+ if (reason === undefined) classed = false;
141
+ else fallback ??= reason;
142
+ };
143
+ const unavailable = (): AiProviderUnavailableError =>
144
+ new AiProviderUnavailableError({
145
+ model,
146
+ attempts: failures,
147
+ fallback: classed ? fallback : undefined,
148
+ });
126
149
  // Read once, and only compared when a budget is set: core's `retryLoop` rule — a wait that would
127
- // end past `timeBudgetMs` is never started, across every provider of this call.
128
- const startedAt = systemClock.monotonic();
150
+ // end past `timeBudgetMs` is never started, across every provider (and model) of this call.
151
+ const monotonic = input.monotonic ?? (() => systemClock.monotonic());
152
+ const startedAt = input.startedAt ?? monotonic();
129
153
  const overruns = (delayMs: number): boolean =>
130
- retry.timeBudgetMs !== undefined &&
131
- systemClock.monotonic() - startedAt + delayMs > retry.timeBudgetMs;
154
+ retry.timeBudgetMs !== undefined && monotonic() - startedAt + delayMs > retry.timeBudgetMs;
155
+ // Calls this loop made. The very first call of a whole call always goes out; every later one —
156
+ // the next provider, the next model's first — is checked against the budget first, exactly as a
157
+ // wait is: a budget spent by the last attempt is spent, whoever would be asked next.
158
+ let made = 0;
132
159
  if (input.candidates.length === 0) {
133
160
  throw new AiProviderUnavailableError({
134
161
  model,
@@ -141,9 +168,18 @@ export async function attemptProviders(input: AttemptInput): Promise<GenerateRes
141
168
  const ticket = gate?.admit();
142
169
  if (gate !== undefined && ticket === undefined) {
143
170
  failures.push(`${provider.name}: breaker open`);
171
+ classify('unavailable');
144
172
  continue;
145
173
  }
146
174
  for (let attempt = 1; attempt <= retry.attempts; attempt += 1) {
175
+ if ((made > 0 || input.continuing === true) && overruns(0)) {
176
+ // Nothing was sent: the probe goes back, and the next model is not asked either.
177
+ gate?.released(ticket);
178
+ failures.push(`${provider.name}: retry.timeBudgetMs spent before this call`);
179
+ classed = false;
180
+ throw unavailable();
181
+ }
182
+ made += 1;
147
183
  try {
148
184
  const answer = { ...(await input.call(provider)), provider: provider.name };
149
185
  gate?.succeeded(ticket);
@@ -162,6 +198,7 @@ export async function attemptProviders(input: AttemptInput): Promise<GenerateRes
162
198
  // `renderThrowable`: this line becomes a `cause`, and a renderer that throws would replace
163
199
  // the coded refusal with a `TypeError`. It bounds a provider's 1 MB body too.
164
200
  failures.push(`${provider.name}#${attempt}: ${renderThrowable(error)}`);
201
+ classify(transportFallbackClass(error));
165
202
  if (!isRetryable(error)) {
166
203
  // A 400 is the provider answering: it is up, and a 400 never opens its breaker.
167
204
  gate?.succeeded(ticket);
@@ -174,13 +211,15 @@ export async function attemptProviders(input: AttemptInput): Promise<GenerateRes
174
211
  const delayMs = backoffMs(retry, attempt, input.random);
175
212
  if (overruns(delayMs)) {
176
213
  exhausted(gate, ticket);
177
- throw new AiProviderUnavailableError({ model, attempts: failures });
214
+ // The call's time is spent: the next model would only spend more of it.
215
+ classed = false;
216
+ throw unavailable();
178
217
  }
179
218
  await input.sleep(delayMs);
180
219
  }
181
220
  }
182
221
  }
183
- throw new AiProviderUnavailableError({ model, attempts: failures });
222
+ throw unavailable();
184
223
  }
185
224
 
186
225
  /**
@@ -209,6 +248,7 @@ export function admittedProvider(
209
248
  throw new AiProviderUnavailableError({
210
249
  model,
211
250
  attempts: candidates.map((p) => `${p.name}: breaker open`),
251
+ fallback: 'unavailable',
212
252
  });
213
253
  }
214
254
 
@@ -0,0 +1,79 @@
1
+ // Single responsibility: the gateway's per-call arithmetic that is not routing — a failed call's
2
+ // settle, the abort test, a cache hit's zero bill, the screened completion ceiling and the
3
+ // response cache key. Split from ./gateway at its line ceiling; ./gateway re-exports the key.
4
+
5
+ import { fingerprint, finiteCount } from '@ultimat3/core';
6
+ import type { Billed } from './billed';
7
+ import { billedOf } from './billed';
8
+ import type { BudgetLedger, BudgetReservation } from './budget';
9
+ import type { GenerateRequest, GenerateResult } from './provider';
10
+ import { ZERO_USAGE } from './wire';
11
+
12
+ /**
13
+ * A failed call's reservation: reconciled against its bill when the failure carries one — else
14
+ * against `running`, what a stream's wire reported before it stopped — else given back.
15
+ */
16
+ export async function settleFailure(
17
+ ledger: BudgetLedger | undefined,
18
+ reservation: BudgetReservation | undefined,
19
+ error: unknown,
20
+ running?: Billed,
21
+ ): Promise<void> {
22
+ const billed = billedOf(error) ?? running;
23
+ if (billed === undefined) return ledger?.release(reservation);
24
+ await ledger?.record(billed.usage, billed.cost, reservation);
25
+ }
26
+
27
+ /** The caller's abort — its signal, or the `AbortError` a fetch raises for it. */
28
+ export function abortedBy(request: GenerateRequest, error: unknown): boolean {
29
+ if (request.signal?.aborted === true) return true;
30
+ return error instanceof Error && error.name === 'AbortError';
31
+ }
32
+
33
+ /** The stored answer as a hit delivers it: no token spent, no money, in the currency it named. */
34
+ export const freeOf = (stored: GenerateResult): GenerateResult => ({
35
+ ...stored,
36
+ usage: ZERO_USAGE,
37
+ cost: { ...stored.cost, minor: 0 },
38
+ ...(stored.costExact === undefined ? {} : { costExact: { ...stored.costExact, minor: 0 } }),
39
+ });
40
+
41
+ /**
42
+ * The request's completion ceiling, screened at the one seam every model call in an app passes
43
+ * through — `llm()`, `agent()`, an eval, a judge and a hand-built `generate()` alike.
44
+ *
45
+ * It is not the request that a `NaN` here breaks, and that is why it is refused before anything
46
+ * else happens: `maxTokens` IS the pre-flight estimate, `want > remaining` is false for a `NaN`
47
+ * want, and `BudgetLedger.debit` then writes it onto the ambient ledger and the per-process
48
+ * `BudgetStore`. Both counters are `NaN` from then on, so every later comparison against them is
49
+ * false too — one unscreened declaration turns off every actor and org ceiling in the process,
50
+ * permanently, and reports nothing. Screened before the reservation, so the ledger never sees it.
51
+ */
52
+ export function ceilingOf(request: GenerateRequest): number {
53
+ return finiteCount('the AI gateway', 'maxTokens', request.maxTokens, 1);
54
+ }
55
+
56
+ /**
57
+ * Cache key. Every field that changes the answer is in it — a key that ignores `effort` or
58
+ * `system` would serve one prompt's answer for another — and each tool WHOLE: every `llm()` tool
59
+ * is named `respond`, so a key over names alone served an answer shaped for an old `output` schema
60
+ * after the schema changed. Core's `fingerprint`, so key order never splits one request in two and
61
+ * the width is the one every other sharing key in the framework has.
62
+ */
63
+ export function promptCacheKey(request: GenerateRequest): string {
64
+ return fingerprint({
65
+ model: request.model,
66
+ system: request.system ?? '',
67
+ messages: request.messages,
68
+ maxTokens: request.maxTokens,
69
+ effort: request.effort ?? 'high',
70
+ thinking: request.thinking ?? 'adaptive',
71
+ tools: request.tools ?? [],
72
+ stop: request.stopSequences ?? [],
73
+ // Only when asked for: an absent knob must leave every key written before it existed as it was.
74
+ ...(request.temperature === undefined ? {} : { temperature: request.temperature }),
75
+ ...(request.seed === undefined ? {} : { seed: request.seed }),
76
+ // A wire parameter changes the answer; absent leaves every older key as it was.
77
+ ...(request.providerOptions === undefined ? {} : { providerOptions: request.providerOptions }),
78
+ });
79
+ }