@sema-agent/core
Version:
Stateless, task-oriented AI agent core
273 lines (272 loc) • 19.5 kB
TypeScript
/**
* Fast mode: the provider's faster output tier for the SAME model (not a switch to another model). One module holds what
* the brain layer knows about it: the closed words, the wire spelling, the per-model availability reading, the request
* applier the adapters call, and the rule that decides when a request that asked for fast speed is re-sent at standard
* speed. The session half (what the person asked for, the cooldown, what each endpoint answered) is the Runner's
* (`core/fast-mode-seat.ts`); it reaches a request as one per-call handle, {@link FastModeCall}.
*
* What a session learns from an endpoint is that endpoint's: the beta it was sent and what it refused are keyed by the
* ROUTE the model's catalog entry names ({@link fastModeRouteOf}), the one key the reference never needs (it sends fast speed
* to one first-party endpoint only). The latched beta goes only to a request whose catalog entry serves fast mode.
*
* The words are the reference implementation's: `fast_mode_state` (`off` | `cooldown` | `on`) and the subset of its
* `fast_mode_disabled_reason` set this engine can observe itself, `sdk_opt_in_required` (cli321.js:276998) among those it cannot. Reasons the reference reads off an
* account (a subscription tier, an organization lookup in flight or failed, its own process switches) have no reading here:
* availability is the deployment's declaration on the catalog entry (`Model.fastMode`).
*/
import type { Model } from "../internal/llm.js";
import { type FailedBody } from "./errors.js";
import { type CapabilityRequestSpeed } from "./model-capability.js";
/** The fast-mode state of a session's model: not serving fast (`off`), asked for but paused after the provider pushed back
* (`cooldown`), or serving fast (`on`). */
export declare const FAST_MODE_STATES: readonly ["off", "cooldown", "on"];
export type FastModeState = (typeof FAST_MODE_STATES)[number];
/**
* Why fast mode cannot serve a model right now (absent when nothing stands in its way — a request may still choose standard
* speed). A cooldown is not one of these: it is the `cooldown` state.
* - `not_first_party` — the model's wire is not the Anthropic Messages API, the only wire with a fast-speed parameter.
* - `model_not_allowed` — the catalog entry declares fast mode off (`Model.fastMode: false`), or the endpoint the model's
* requests reach refused the fast-speed parameter for this model in this session.
* - `unknown` — the catalog entry does not declare fast mode; it is not sent to an entry that does not.
* - `preference` — the endpoint the model's requests reach answered that fast mode is not enabled (in this session).
* - `extra_usage_disabled` — that endpoint refused fast speed for the account's usage credits (in this session).
*/
export declare const FAST_MODE_UNAVAILABLE_REASONS: readonly ["not_first_party", "model_not_allowed", "unknown", "preference", "extra_usage_disabled"];
export type FastModeUnavailableReason = (typeof FAST_MODE_UNAVAILABLE_REASONS)[number];
/** The reasons read off the catalog entry alone (its wire, its declaration) — whether the entry serves fast mode at all. */
export type FastModeEntryReason = Extract<FastModeUnavailableReason, "not_first_party" | "model_not_allowed" | "unknown">;
/** The reasons an endpoint gives, which the session remembers for that route (see {@link FastModeCall.refusedFor}):
* `model_not_allowed` for the one model it named, the other two for every model the route serves. */
export type FastModeRefusal = Extract<FastModeUnavailableReason, "model_not_allowed" | "preference" | "extra_usage_disabled">;
/** Why a cooldown started: the provider rate-limited a fast request (`rate_limit`), or was overloaded / failing (`overloaded`). */
export declare const FAST_MODE_COOLDOWN_REASONS: readonly ["rate_limit", "overloaded"];
export type FastModeCooldownReason = (typeof FAST_MODE_COOLDOWN_REASONS)[number];
/** The usage-credit causes a rate-limited fast request may name after which the reference re-sends that one request at
* standard speed and says so, and asks for fast speed again from the next request (`C2n` / `mZi`, cli321.js:277306). Any
* other cause refuses fast speed on the route (`extra_usage_disabled`). */
export declare const FAST_MODE_OVERAGE_CAUSES: readonly ["out_of_credits", "org_level_disabled_until", "org_spend_cap_reached"];
export type FastModeOverageCause = (typeof FAST_MODE_OVERAGE_CAUSES)[number];
/** The one reading of a session's fast mode for one model — what a host renders (a toggle, its disabled reason, a countdown). */
export interface FastModeReading {
readonly state: FastModeState;
/** Present when something stands in the way of fast mode for this model, whether or not it was asked for. */
readonly reason?: FastModeUnavailableReason;
/** Present exactly when `state` is `cooldown`: when it ends (epoch milliseconds) and why it started. */
readonly cooldown?: {
readonly until: number;
readonly reason: FastModeCooldownReason;
};
}
/** The beta a request carrying the fast-speed parameter needs. */
export declare const FAST_MODE_BETA = "fast-mode-2026-02-01";
/** The body key `api`'s wire carries fast speed under (undefined = the wire has none) — what a standard-speed re-send drops. */
export declare function fastSpeedKeyOf(api: string): string | undefined;
/**
* The route a model's requests reach, as its catalog entry names it: the entry's route key (`routeKeyOf(model.baseUrl)`, the
* key the route pairing law compares; "" = the deployment's own root). The applier, the engine's fallback rule and the
* session's reading all key what an endpoint answered by it, so a reading taken before a request names the route that request
* goes to. A key, never rendered (a root's query may carry a secret).
*/
export declare function fastModeRouteOf(model: Pick<Model, "baseUrl">): string;
/** What happened to a request that asked for fast speed, as the brain reports it to the session ({@link FastModeCall.observe}).
* `route` is its model's {@link fastModeRouteOf}. */
export type FastModeObservation =
/** A request carrying the fast-speed parameter was sent to `route`: from now on that route's requests keep the beta. */
{
readonly kind: "sent";
readonly route: string;
}
/** The provider pushed back on a fast request: fast speed pauses for the whole session until `until` (epoch ms). */
| {
readonly kind: "cooldown";
readonly modelId: string;
readonly until: number;
readonly reason: FastModeCooldownReason;
}
/** The endpoint at `route` refused fast speed (for `modelId` alone when the reason is `model_not_allowed`): it is not asked
* there again in this session. */
| {
readonly kind: "refused";
readonly route: string;
readonly modelId: string;
readonly reason: FastModeRefusal;
}
/** The endpoint at `route` refused the fast-mode beta itself (on a request for `modelId`), and the engine re-sent that request
* without it (reported only then: a beta the deployment declares is not the engine's to drop): neither the beta nor fast
* speed goes there again in this session, for any model — turning fast mode on again does not ask again (the endpoint does
* not know the header). Every model there reads `model_not_allowed`. */
| {
readonly kind: "beta_refused";
readonly route: string;
readonly modelId: string;
}
/** A fast request met one of the usage-credit causes ({@link FAST_MODE_OVERAGE_CAUSES}): that request went again at standard
* speed; nothing is remembered, and the next request asks for fast speed again. */
| {
readonly kind: "overage";
readonly modelId: string;
readonly cause: FastModeOverageCause;
};
/**
* A call's view of its session's fast mode — the per-call option `SimpleStreamOptions.fastMode`. The Runner builds it before
* each main-loop call and hands it to the requests made from the session's conversation beside it (a compaction pass's
* summary, the next-prompt suggestions), as the reference's forks copy their caller's options; a brain reads it per model (a
* fallback chain's hops each get the same handle) and reports what the endpoint answered through {@link observe}. Absent from
* every call of a session that has neither asked for fast mode nor sent it.
*/
export interface FastModeCall {
/** Fast speed is asked for on this call: the session wants it and is not cooling down. */
readonly requested: boolean;
/** The session has sent the fast-speed parameter to `route` and the endpoint has not refused the beta: the beta stays on
* that route's requests to an entry that serves fast mode, fast or not, so their shape does not change when the speed does. */
betaLatchedOn(route: string): boolean;
/** The reason the endpoint at `route` refused fast speed for `modelId` in this session, if it did. */
refusedFor(route: string, modelId: string): FastModeRefusal | undefined;
/** Report what a request that asked for fast speed met. Never throws into the brain. */
observe(observation: FastModeObservation): void;
}
/**
* Whether the catalog entry serves fast mode (undefined = it does): the wire, then the declaration — read by the one
* capability reading, the requester's reader (`capabilityTried`): what an undeclared entry means is fast mode's `requested`
* cell (`UNKNOWN_CAPABILITY_READS`), never decided here. The reading and every adapter read this; what an endpoint answered is
* the session's, and comes after.
*/
export declare function fastModeUnavailableFor(model: Pick<Model, "id" | "api" | "fastMode">): FastModeEntryReason | undefined;
/**
* THE fast-mode reading of one model — the one place `state`, `reason` and `cooldown` are computed. A host reads it without a
* session (`{ model, requested }`: what the catalog entry allows, to render a toggle and its disabled reason); the Runner reads
* it with what the session learned — what the endpoint this model's requests reach refused (`refused`), and the session's
* cooldown — for the wiring manifest, the result, the stream verb's receipt and `model.fast_mode_changed`. `reason` is said
* whether or not fast mode was asked for; `on` / `cooldown` only when it was asked for and nothing stands in its way.
*/
export declare function fastModeReadingOf(args: {
readonly model: Pick<Model, "id" | "api" | "fastMode">;
readonly requested: boolean;
readonly refused?: FastModeRefusal;
/** The session is cooling down until `until` (epoch ms); a past `until` is read as no cooldown. */
readonly cooldown?: {
readonly until: number;
readonly reason: FastModeCooldownReason;
};
readonly now?: number;
}): FastModeReading;
/** Tell the call's handle what a request met. A handle is the session's account, never part of the request: one that throws
* (a host's own handle) changes nothing about the call that met it, and has no consumer to be told. */
export declare function observeFastMode(call: FastModeCall | undefined, observation: FastModeObservation): void;
/** What {@link applyFastModeToRequest} adds to a request: the body (a new object when it adds the key), the beta header to
* merge (absent = none), and whether the request carries the fast-speed parameter. */
export interface FastModeRequestPart {
readonly body: Record<string, unknown>;
readonly headers?: Readonly<Record<string, string>>;
readonly fastSpeed: boolean;
}
/**
* The speed a request to `model` on the call `call` goes at — the one reading of it: `fast` when the call asks for fast speed,
* the catalog entry serves it ({@link fastModeUnavailableFor}), the endpoint at the model's route ({@link fastModeRouteOf}) has
* not refused it, and the engine is not re-sending this request at standard speed (`standardSpeed`); otherwise `standard`.
* Read ONCE per request build, by the brain that builds it: the same value keys its capability memory read (`requestWithheld`,
* brain/model-capability.ts) and is what the applier ({@link applyFastModeToRequest}) writes — so the memory a request was
* decided by is the memory of the speed it goes at.
*/
export declare function requestSpeedOf(args: {
model: Model;
call: FastModeCall | undefined;
standardSpeed: boolean;
}): CapabilityRequestSpeed;
/**
* The one request applier every wire adapter calls. With no handle the body is returned as it came. Nothing is added for an
* entry that does not serve fast mode ({@link fastModeUnavailableFor}): neither the key nor the beta. For one that does, the
* fast-speed key goes out when the request's speed (`speed`, the build's one {@link requestSpeedOf} reading) is fast; the
* beta goes out with it, and on every later request to the same route (the latch) — but on none of a call the engine re-sends
* without it (`withoutBeta`: the endpoint refused the beta itself; such a request is at standard speed). A call that asked for
* fast speed of an entry that does not serve it is reported as a withheld capability (the session says so once per model); a
* refusal by an endpoint is not reported again here — it was said when it happened.
*/
export declare function applyFastModeToRequest(args: {
model: Model;
call: FastModeCall | undefined;
speed: CapabilityRequestSpeed;
body: Record<string, unknown>;
withoutBeta?: boolean;
}): FastModeRequestPart;
/** The reference's ladder numbers, `fastModeSent` (cli321.js:287622): a provider wait shorter than this keeps fast speed for the retry,
* as long as the waits a call keeps fast speed through sum under it too; the shortest cooldown; the cooldown when a
* rate-limited or overloaded response names no wait. */
export declare const FAST_MODE_SHORT_WAIT_MS = 20000;
export declare const FAST_MODE_MIN_COOLDOWN_MS = 600000;
export declare const FAST_MODE_DEFAULT_COOLDOWN_MS = 1800000;
/** What {@link fastModeFallbackOf} decides for a failed request that carried the fast-speed parameter. */
export type FastModeFallback =
/** Not the fast-mode rule's failure: the engine's ladder decides. With `shortWaitMs`, a short provider wait: the rule's own
* retry — this request again at fast speed after `shortWaitMs` (the wait the engine takes before it, the rule's input
* `retryWaitMs`), one of the call's attempts, sent whatever the response's own retry verdict says (the reference's short-wait
* arm runs before any). The caller sums `shortWaitMs` across the call. */
{
readonly kind: "keep";
readonly shortWaitMs?: number;
}
/** Re-send now at standard speed — once: the re-send carries no fast speed, so it never meets this rule again. `observation` is
* what the session is told (none: nothing to tell); `counted` = the re-send is one of the call's attempts. */
| {
readonly kind: "standard";
readonly observation?: FastModeObservation;
readonly counted?: true;
}
/** The re-send would be an attempt and the call has none left: the session learns `observation`, nothing is re-sent, and the
* failure ends the call as it is. */
| {
readonly kind: "end";
readonly observation: FastModeObservation;
};
/**
* A failed response says the fast-mode beta itself was refused — the reference's reader of a refused beta (`Wtt`, with `Bmn`
* and `wxe`, cli321.js:285903), for this one beta: a gateway's token naming it anywhere in the body, whatever the status; the
* API's sentence naming it among the refused betas, whatever the status when it opens the failure's message (the stated
* envelope's `error.message`, else the body's text; its first line, as the reference's `lln` reads it) and anywhere in a 400's
* body. The engine's beta heal reads it before fast mode's rule (`stream-engine.ts`).
*/
export declare function fastModeBetaRefused(status: number, body: FailedBody | undefined): boolean;
/** A failed fast request's server error, as the rule counts them: a 5xx that is not an overload ({@link overloadedStated};
* `tIe` ∧ ¬`a1`, cli321.js:287622 "Os=tIe(Ro)&&!a1(Ro)"). The caller counts each one into `serverErrors`. */
export declare function fastModeServerError(status: number, body: FailedBody | undefined): boolean;
/**
* The reference's rule for a request that carried fast speed and failed, its retry loop `fastModeSent` (cli321.js:287622), as
* one pure function, in the reference's order (a refused beta is healed before it, by the engine: {@link fastModeBetaRefused}):
* - 429, an overload ({@link overloadedStated}: a 529, or any status whose body says `overloaded_error`), or a server error
* ({@link fastModeServerError}) that is the call's second, or has no retry left, or says `x-should-retry: false`, or names a
* wait of 20 s or more: a 429 / overload naming the usage-limit header ⇒ for one of the usage-credit causes
* ({@link FAST_MODE_OVERAGE_CAUSES}) this request alone goes at standard speed (`overage`), for any other the route is refused
* (`extra_usage_disabled`) — the reference's split, `mZi` (cli321.js:277306); a 429 / overload naming a wait under 20 s, with a
* retry left and the waits the call kept at fast speed plus this retry's own (`retryWaitMs`, the wait the engine takes before
* it — never less than its backoff, as the reference sums `mD`) under 20 s ⇒ `keep` with that wait, the rule's own retry at
* fast speed; otherwise ⇒ a cooldown of `max(wait ?? (server error ? 10 min : 30 min), 10 min)`, `rate_limit` for a 429 and
* `overloaded` for the rest — except a first server error, which re-sends this call at standard speed with no cooldown.
* - 400 naming that fast mode is not enabled ⇒ the route is refused (`preference`); 400 naming that this model does not support
* the `speed` parameter ⇒ the route refuses this model (`model_not_allowed`) — the name read through the one model-id reading
* ({@link sameModelNamed}: another spelling of this model is this model, as the reference compares `Lp` of both sides,
* `Elt` cli321.js:287622).
* Every `standard` answer re-sends at once at standard speed. The cooldown, first-server-error and usage-limit re-sends do not
* count as an attempt; the two 400 refusals of fast speed do (the reference's loop gives the attempt back on the others only),
* so such a 400 met with no retry left is `end`: the session still learns the refusal, and the 400 ends the call.
*/
export declare function fastModeFallbackOf(input: {
readonly status: number;
readonly headers?: {
get(name: string): string | null;
};
/** The failed response's body as read (`FailedBody`): the 400 arms read its text; an overload is read off its stated envelope
* only (a body that did not end states nothing). */
readonly body?: FailedBody;
/** The failed request's route ({@link fastModeRouteOf} of its model). */
readonly route: string;
readonly modelId: string;
/** How many server errors ({@link fastModeServerError}) this call's fast requests met, this one included. */
readonly serverErrors: number;
readonly retriesLeft: boolean;
/** The waits already kept at fast speed on this call (each its `retryWaitMs`). */
readonly shortWaitSpentMs: number;
/** How long the engine waits before this request's retry, should the rule keep fast speed for it: the retry ladder's backoff
* floored by the provider's wait hints, the one number the ladder then sleeps. */
readonly retryWaitMs: number;
readonly now: number;
}): FastModeFallback;