@sema-agent/core
Version:
Stateless, task-oriented AI agent core
205 lines (204 loc) • 16.6 kB
TypeScript
/**
* The MODEL LANE — the one walk of a model request's fallback chain (the rule is stated in `core/model-fallbacks.ts`: the
* requested catalog entry, then the entries its `Model.fallbacks` words name; every hop served by the deployment's own Brain;
* only a failure before the first content, for a reason the gate admits, moves the request to the next hop).
*
* The lane is the Runner's Brain seat: `RunnerDeps.brain` wrapped once (`core/runner/model-lane-seat.ts` is the one accessor
* every engine read of the seat goes through), so the main loop and every side lane (compaction, the permission classifier, a
* side query, a mod's model call, the advisor) walk the same chain. A request for a model with no chain is judged (below) and
* then the deployment Brain's own call, unchanged — the stream, the message and the error are exactly what the Brain answered.
*
* WHETHER a hop is dispatched is the deployment Brain's route judgment (`adjudicateRoute`), asked before EVERY hop — the requested
* model first — with the per-call identity that hop is dispatched with (the requested model: the request's `apiKey` / `headers`;
* a later hop: none, see below). A hop it refuses is not dispatched (never sent, never billed) and is named on the answer's
* `skipped` with the refusal's code and fix; a judgment that throws or answers no verdict (it answers synchronously) refuses its
* hop the same way ({@link ROUTE_JUDGMENT_FAILED}). A refused hop always moves the walk on, whatever the policy's gate words —
* nothing was sent, so nothing would be replayed. When no hop is dispatched and serves,
* the answer is the requested model's own terminal: when its own route was refused, that refusal — `[invalid_request]
* <code>: <fix>`, the very error a first-party brain's request gate throws (`routeRefusalError`). A cancelled request is not
* judged — and one cancelled while it is judged is not refused: its requested model is the Brain's to answer, and no later hop
* is walked to. The judgment chooses; the sending
* boundary is unchanged (a first-party brain's request gate judges again while it builds and when it commits the request).
*
* The three faces of the Brain contract:
* - `stream` walks hop by hop. Each hop's leading `start` and block-opening events are HELD; the first other event (a delta, a
* block end — content) commits the request to that hop, and from then on its outcome is the request's, success or failure
* (nothing is replayed: no tool runs twice, no text is said twice). A hop that is not the chain's last may carry the
* deployment's first-token deadline (`RunnerDeps.modelFallback.firstTokenMs`): it races every wait on the hop (the stream
* promise, each step, `result()`) and, when it fires, aborts the hop's signal with a coded `network` failure — a circuit
* breaker inside the deployment Brain counts it — and leaves the hop whatever the Brain does next.
* - `complete` is always present. A walked request walks the face its policy needs: the stream (above, read to its final
* message) when the policy sets a first-token deadline — a deadline is a fact about a stream's events — and otherwise the
* deployment Brain's non-streaming face hop by hop ({@link completeOf}: its own `complete`, else its stream read to its result),
* returning the hop's message as the Brain answered it (its `errorKind` included).
* - `adjudicateRoute` is the deployment Brain's own, passed through (the requested model is the one judged first).
*
* Hops other than the first are dispatched without the request's per-call identity (`apiKey`, `headers`, `metadata`): those
* were resolved for the requested model, and a hop is served with what the deployment Brain holds for the hop's own model.
*
* A walked request's answer carries a marker diagnostic ({@link DEGRADED_DIAGNOSTIC_TYPE}): who asked, which hops were tried,
* which were refused before dispatch, why the walk began, whether a hop served or the chain was exhausted, and which hop's message this is. An exhausted chain
* answers the FIRST hop's own terminal: the requested model's failure is the one its caller's recovery is built for.
*
* Every request an answer left behind on its way rides the answer in ONE diagnostic ({@link LEFT_BEHIND_DIAGNOSTIC_TYPE}): the
* hops the lane walked past and the gateways the failover decorator moved off, each with the usage its own message reported —
* every attempt is billed once, at its own model's price ({@link servedReadingOf}). The answer's own `usage` stays the answer's
* (the context reading of the next request is that message's).
*/
import { type AssistantMessage, type AssistantMessageDiagnostic, type AssistantMessageEvent, type Model, type PerModelAuth, type SimpleStreamOptions, type Usage } from "../internal/llm.js";
import type { Brain } from "../core/types.js";
import { BrainError } from "./errors.js";
import { ROUTE_JUDGMENT_FAILED, type JudgedRefusal } from "./route-adjudicator.js";
import { type DegradeReason, type HopGate, type ReceivedModelFallbackPolicy } from "../core/model-fallbacks.js";
export { DEGRADE_REASONS, type DegradeReason } from "../core/model-fallbacks.js";
/** The `type` of the marker diagnostic a walked request's answer carries. */
export declare const DEGRADED_DIAGNOSTIC_TYPE = "degraded";
/** How a walk ended: a hop after the first served the request, or no hop did (the first hop's terminal is the answer). */
export type FallbackOutcome = "served" | "exhausted";
/** The `type` of the diagnostic that lists the requests an answer left behind on its way. */
export declare const LEFT_BEHIND_DIAGNOSTIC_TYPE = "left_behind";
/** One request an answer left behind on its way — a hop the lane walked past, a gateway the failover decorator moved off: the model
* it asked for and the usage its own message reported (`usageMissing` when it reported none the engine can trust — a request cut at
* its deadline, a request whose Brain threw, an entry of a list that did not read). `model` is `""` for a request no one can name. */
export interface LeftRequest {
model: string;
usage: Usage;
usageMissing?: true;
}
/** The marker, as read back off an answer. */
export interface DegradationInfo {
/** The requested model's id. */
from: string;
/** The last hop tried (the hop that served, for `served`). */
to: string;
/** Why the request left the first hop (`route_refused`: its own route was refused before dispatch). */
reason: DegradeReason;
/** The hops tried after the first, in order. */
chain?: string[];
/** How the walk ended (absent on a marker that does not state it). */
outcome?: FallbackOutcome;
/** Whose message the answer is: `to` when a hop served, `from` when the chain was exhausted. */
answeredBy?: string;
/** The hops the deployment Brain's route judgment refused before they were dispatched, in chain order (the requested model
* first when its own route was refused — `reason: "route_refused"`) — each the model it names and the refusal code and fix the
* judgment stated ({@link ROUTE_JUDGMENT_FAILED} for a judgment that did not answer one; each absent when it stated none).
* Absent when no hop was refused. */
skipped?: SkippedHop[];
}
/** A hop of a walk the deployment Brain's route judgment refused before dispatch: never sent, never billed — the model, the code the
* refusal stated and its fix sentence (each absent when the judgment gave none; a credential refusal's fix names the root the
* credential belongs to and the one the request was going to). */
export interface SkippedHop {
model: string;
code?: string;
fixHint?: string;
}
/** The `code` of a hop whose route judgment did not answer one — it THREW, or answered no verdict (a Promise: a judgment answers
* synchronously; any other value; a verdict whose members would not read): the hop is refused like any other — never sent (a
* judgment that did not answer cannot show it servable) — and, when no hop was dispatched and served, the requested model's
* terminal names how (`[invalid_request] route.judgment_failed: …`). Not a `RouteRefusalCode`: no judgment stated it. The one
* reading is `readRouteJudgment`'s (a derived seat's pre-flight reads the same answer the same way). */
export { ROUTE_JUDGMENT_FAILED };
/** The `type` of the diagnostic a request's answer carries when its walk began and no hop was tried — every hop the walk reached
* was refused before dispatch: the answer is the requested model's own and carries no marker — this says why none was tried. */
export declare const FALLBACK_UNSENT_DIAGNOSTIC_TYPE = "fallback_unsent";
/** A walk that sent no hop, as read back off an answer: the requested model's id, why the request left it, and the hops refused. */
export interface FallbackUnsent {
from: string;
reason: DegradeReason;
skipped: SkippedHop[];
}
/**
* The marker off an answer, or `undefined`. Strict on every member: a marker whose required members do not parse, or whose
* optional members are present and malformed, is not read at all (a half-read marker would bill some hops and drop others). An
* optional member that would not read is not an absent one — it comes back unreadable and fails the shape check like any malformed one.
*/
export declare function readDegradation(msg: {
diagnostics?: AssistantMessageDiagnostic[];
} | undefined): DegradationInfo | undefined;
/** The walk that sent no hop off an answer ({@link FALLBACK_UNSENT_DIAGNOSTIC_TYPE}), or `undefined` — strict on every member, as the marker is. */
export declare function readFallbackUnsent(msg: {
diagnostics?: AssistantMessageDiagnostic[];
} | undefined): FallbackUnsent | undefined;
/**
* What a request left behind stands for in the list of the answer that moved past it: the requests IT left behind (its own list —
* a gateway the failover decorator moved off before this hop failed too), then itself, at the model it asked for. A message that
* reported no usage the engine can read is listed with a zero usage marked as a lower bound.
*/
export declare function leftEntriesOf(msg: AssistantMessage, model: string): LeftRequest[];
/** The answer carries the requests left behind on its way: its own list (the requests it left behind itself), then `left`. */
export declare function carryLeftBehind(msg: AssistantMessage, left: readonly LeftRequest[]): void;
/** Who answered one message of a request for `requested`, and the requests billed beside it — each resolved to its `Model`. */
export interface ServedReading {
/** The model whose message this is. */
readonly served: Model;
/** The requests the answer left behind on its way, each billed at its own model's price. */
readonly attempts: readonly {
readonly model: Model;
readonly usage: Usage;
readonly usageMissing?: true;
}[];
/** The marker, when the answer is a walked request's. */
readonly degraded?: DegradationInfo;
/** The walk that began and sent no hop (every hop it reached refused before dispatch), when the answer is such a request's own. */
readonly unsent?: FallbackUnsent;
}
/**
* THE reading every accounting point makes of an answer: which model answered and which requests were left behind beside it,
* resolved over the chain the catalog door resolved for `requested` (ids are unique along a chain — the door refuses a repeat).
* The two are read independently: an answer the failover decorator served after moving off a gateway lists what it left behind
* with no marker at all. A marker that does not belong to this request (it names another requested model, or a hop the chain does
* not hold) is not this lane's and is not read: the message is the requested model's own. The list is read entry by entry: an entry
* the chain holds is billed at its model with the usage it reported; an entry that does not read whole, or names a model the chain
* does not hold, bills nothing priced and is booked as a lower bound at the requested model — what the account cannot price it says
* it is short of, rather than leaving it out.
*/
export declare function servedReadingOf(requested: Model, msg: {
diagnostics?: AssistantMessageDiagnostic[];
} | undefined): ServedReading;
/**
* The terminal for a request whose Brain threw (or whose stream broke its protocol) instead of answering: the request was handed
* to the Brain, so what it cost is unknown — the usage is a lower bound (`usageMissing`), never a known zero. A request refused
* before it was dispatched (`sent: false`) cost nothing: its zero usage is a known zero. The model's id is read once, guarded
* ({@link sayableModelId}): an error terminal is minted for a model whose id will not read too.
*/
export declare function errorMessageOf(model: Model, e: unknown, aborted: boolean, sent?: boolean): AssistantMessage;
/** The terminal event of a message: an error frame for an error / aborted message, else `done`. */
export declare function terminalOf(message: AssistantMessage): AssistantMessageEvent;
/** The message a terminal event carries (the one to tag and to read). */
export declare function terminalMessage(terminal: AssistantMessageEvent, fallback: AssistantMessage): AssistantMessage;
/** Whether a message carries content (the `complete` face's reading of "after the first content"). */
export declare function carriesContent(msg: AssistantMessage): boolean;
/**
* The gate's reading of one hop's outcome, over one row of the hop gate ({@link HopGate}): the reason word that moves the request
* to the next hop, `"next"` for a move that carries no reason word of its own (a non-first hop's `invalid_request` — a fact about
* that hop, not about the request — and any failure a row that admits every failure lets through), or `undefined` — the walk stops
* here. Never moves, whatever the row: a hop that committed (content reached the caller), a caller's abort, the run's spend
* account refusing the hop (`isSpendRefusal`: what is left does not fit, so no other hop is sent either), `length_empty`, an
* image or tool schema the provider refused (`errorKind`; the caller's request view repairs it). Never moves a reason-word row: a
* first hop's `invalid_request`, `refusal`, and a failure the Brain stated no code for (it did not classify it; the lane does not
* guess).
*/
export declare function gateReadingOf(msg: AssistantMessage, hop: number, expired: boolean, callerAborted: boolean, gate: HopGate): DegradeReason | "next" | undefined;
/** The per-call answer a hop is dispatched with, as the judgment is handed it — the whole {@link PerModelAuth} the request carries
* (its header bag already a copy read once: by the answer's one reader, `askPerModelAuth`, and in the main loop by the merge with
* the run's own bag):
* the options' `apiKey`, `headers`, `credentialOrigin` and the engine's `credentialOriginUnsettled` mark (none for a later hop —
* {@link hopOptionsOf} drops them), and the call's `plaintextOrigins` (every hop's: it is the request's, not the answer's);
* `undefined` when there is none. The judgment judges the request the Brain would build from it. */
export declare function identityOf(options: SimpleStreamOptions | undefined): PerModelAuth | undefined;
export declare function refusalErrorOf(id: string, refusal: JudgedRefusal): BrainError;
/**
* The model lane over a deployment Brain and a received fallback policy — one Brain per (Brain, policy) pair, so every read of
* the seat answers the same object. A request whose model has no chain is judged, then the inner Brain's own call (its route
* refused: that refusal, nothing sent); so is a request whose options stand resilience down (`resilience.allowDegrade: false`).
* A lane handed in is answered as it is: a chain is walked
* once, by one lane, and every hop is the deployment Brain's own call.
*/
export declare function modelLaneBrain(inner: Brain, policy?: ReceivedModelFallbackPolicy): Brain;
/**
* A pass-through of one Brain's stream that keeps the stream protocol whatever the Brain does: a Brain that rejects, or a stream
* that ends with no terminal event, still leaves one error terminal (otherwise `result()` would never settle and the caller
* would hang).
*/
export declare function passthroughStream(brain: Brain, model: Model, context: Parameters<Brain["stream"]>[1], options: Parameters<Brain["stream"]>[2]): ReturnType<Brain["stream"]>;