@sema-agent/core
Version:
Stateless, task-oriented AI agent core
327 lines (326 loc) • 26 kB
TypeScript
import type { ThinkingLevel } from "../internal/harness-types.js";
import type { Model } from "../internal/llm.js";
import type { HostRole } from "../prompt-assembly/catalog/schema.js";
import { type RoleBaseDeclaration } from "../prompt-assembly/role-base.js";
import { type FastTierTell } from "./fast-tier-door.js";
import type { ModelPricing } from "./pricing.js";
import { type ModelRef, type ModelRole, type ModelRoles, type RoleSpec } from "./types.js";
import { type ConfigRefusalInput } from "./config-refusal-input.js";
export type { ModelRole, RoleSpec, ModelRoles } from "./types.js";
export { MODEL_ROLES } from "./types.js";
export { bindingShown } from "./model-receipt.js";
/**
* The catalog's answer for a model word — every read of a catalog's entry: the entry's snapshot from the model door, received as the
* catalog entry it is, with its `fallbacks` chain. An entry a caller wrote is received here, at the read, and its words are resolved
* over the catalog it sits in ({@link chainedRead}); a snapshot the catalog holds — an entry of a catalog the catalog door received, or
* of a slice or copy of one, or a key a tier expansion laid out — is handed back as itself, with the chain it was resolved with. Only
* the entry behind the word and the entries its chain names are read. `seat` names where the word was written; the entry is named as
* the catalog entry that word resolved to.
*/
export declare function catalogModel(ref: string, models: Record<string, Model> | undefined, seat: string, what?: string): Model | undefined;
/** Whether `ref` names an entry of this catalog: the membership half of {@link catalogModel}, for a reader that lists names
* and must not receive (or throw on) the entry behind each one. */
export declare function isCatalogEntry(ref: string, models: Record<string, Model> | undefined): boolean;
/** The catalog narrowed to the one word `ref`: no entry, or `ref` with the entry {@link catalogEntry} read once. A reader that
* answers membership and then receives the same entry reads the slice twice and the caller's table once. */
export declare function catalogSliceOf(ref: string, models: Record<string, Model> | undefined): Record<string, Model>;
/**
* The role receipt — a role map read ONCE per operation (one public entry of this module: a task's resolution, a role's model if set, the
* preset's role base, the classifier seat, the deployment's subagent tier): the map a plain record whose every member is read once and
* received ({@link receiveRoleSpec}), the copy frozen. The map stays the caller's between operations (a deployment may change it in place);
* within one, every reader reads this copy, and an entry that calls back in hands the copy, which is received as itself. `field` names the
* map (`RunnerDeps.roles` / `TaskSpec.roles`).
*/
export declare function receiveRoleMap(roles: ModelRoles | undefined, field: string): ModelRoles | undefined;
/**
* Resolve a ModelRef against the catalog (a Model object passes through). A word the catalog does not hold, and a value that is no model
* reference, are refused by `config.unknown_role` with `detail { field: seat, reason }` — `seat` names where the caller wrote the word
* (`"model"` when the caller names none).
*/
export declare function resolveModel(ref: ModelRef, models?: Record<string, Model>, seat?: string): Model;
/** 档位降档链(强→弱)。解析某档无绑定时沿链向后找第一个有绑定的档(fail-open 可用性优先;绑定缺口
* 在部署 catalog 审计面可见)。`ultra` 预留:排在 `max` 前,今天不绑,未来加档零码改。 */
export declare const DEFAULT_TIER_ORDER: readonly string[];
/** CC 档位词 → sema 档位(内置固定,兼容层):fable/mythos→max · opus→pro · sonnet→flash · haiku→lite。 */
export declare const CC_MODEL_TIER_ALIASES: Readonly<Record<string, string>>;
/** the DISPLAY face of a string model ref: a CC tier ALIAS (haiku/sonnet/…) resolves to its
* sema tier name (lite/flash/…) for labels — the alias verbatim reads as a strong claim about a
* specific vendor's model while the actual routing may land anywhere ("haiku" showing over a
* DeepSeek run, an operator field report). A non-alias string is the deployment's own model key — its
* honest name — and passes through unchanged. Display only; routing (`expandTiers`) is untouched. */
export declare function resolveModelDisplayLabel(ref: string): string;
/**
* A host's tier expansion of its own catalog ({@link expandTierKeys}, the body the catalog door expands with): without bindings
* (absent, or a record of none) the catalog itself; with them a new, unfrozen catalog holding the caller's own entries and, under the
* tier words, the snapshots of the entries the bindings name — each with its `fallbacks` chain resolved over this expansion, as the
* door resolves its generation's (a tier word in a chain is a key here; an entry expanded again over a replaced hop names the snapshot
* that carries the new one). Only the entries a binding names, and the entries their chains name, are read. A refusal names the
* binding seat (`tiers.<the bound tier>`).
*/
export declare function expandTiers(models: Record<string, Model> | undefined, tiers: Record<string, ModelRef> | undefined): Record<string, Model> | undefined;
/** Whether `models` is a catalog the catalog door made ({@link receiveModelCatalog}). */
export declare function isReceivedCatalog(models: Record<string, Model> | undefined): boolean;
/** The catalog door's generation of a deps bag's catalog and the tier bindings beside it: a catalog the door made (a Runner's own) as
* it is; any other received here by the door `new Runner` takes it through ({@link receiveModelCatalog} at `RunnerDeps`), whole, at
* every call (nothing is held) — so a host that judges a catalog before it hands it over, with the same models and pricing, meets the
* refusal `new Runner` gives the same catalog, and gets the generation a Runner would read. A read by word reads only what the word
* reaches ({@link catalogModel}). */
export declare function catalogOfDeps(deps: {
models?: Record<string, Model>;
tiers?: Record<string, ModelRef>;
pricing?: Record<string, ModelPricing>;
}): Record<string, Model> | undefined;
/**
* The CATALOG DOOR — a catalog generation (a model catalog and the tier bindings over it) received whole, where a Runner takes one: at
* `new Runner` and at `swapDeps`. The catalog is a plain record read once; every entry with a model behind it is received by the model door
* now (a catalog entry no task names yet is judged as well as one a task names: a catalog is configuration, and a bad entry is a boot error,
* not a first-use one); the bindings are a plain record read once, every binding a word or a Model object (received), a binding a catalog
* key shadows included; THEN the bindings are expanded over the received catalog ({@link expandTierKeys} — its marks are written on its own
* output, so they are never lost to a copy) and the result frozen; last, every entry passes the fast-tier door against the deployment's
* `pricing` (`fast-tier-door.ts`; absent ⇒ a deployment that declares no table, as a `RunnerDeps` without one). `field` names the door (`RunnerDeps` / `swapDeps`). Throws the first refusal; nothing is written by
* the caller before it returns. The door's notices (an entry serving fast mode whose table declares no fast tier) go to `tell`: the Runner's
* two doors hold them until the generation is written and tell them once per Runner; a pre-check passes none.
*/
export declare function receiveModelCatalog(models: Record<string, Model> | undefined, tiers: Record<string, ModelRef> | undefined, field: string, pricing?: Record<string, ModelPricing>, tell?: FastTierTell): {
models?: Record<string, Model>;
tiers?: Record<string, ModelRef>;
};
/**
* What it is for a fixed tier word to be ABSENT (#2614), in two clauses: `gap` says what the deployment's tiers lack, `fix` where a model is
* bound. The expansion lays a tier word out as the nearest bound tier at or below it, so a word it does not hold has nothing bound at its tier
* or under it (a CC alias reads as the tier it stands for). `best` names no tier: it reads only the DEFAULT tiers ({@link DEFAULT_TIER_ORDER})
* bound directly, so it is absent when none of those five is bound — a deployment of tiers it invented alone has bound none of them, and
* binding another tier of its own does not answer `best`. The one place the refusal sentences ({@link unboundTierNote}) and the notice
* (`roleDefaultedNotice`) take their words from.
*/
export declare function absentTierReading(word: string): {
gap: string;
fix: string;
};
/**
* The words a catalog word stands in for under the tier layer, nearest first — what {@link expandTiers}
* recorded for a key IT wrote: the tier words its resolution passed through and the binding's own catalog
* word, each naming the model the key resolves to. A deployment's own key (a shadowing one included), and any
* catalog that was not tier-expanded, stands in for nothing.
*/
export declare function tierAliasVia(word: string, models: Record<string, Model> | undefined): readonly string[];
export interface ModelMention {
/** The matched model name — always one of `allowedNames` — or undefined if none was found. */
model?: string;
/** The message with the matched `@model` token removed and whitespace tidied. */
cleanedText: string;
}
/**
* Parse a leading/inline `@model` mention out of a user message, restoring the chat "@-model" UX.
* Returns the matched model **name** (a catalog ref the caller resolves), never a Model object — and
* **only ever a name from `allowedNames`**. This is the security boundary: untrusted end-user text can
* pick *which configured model* to use, but can never inject an arbitrary `baseUrl`/`apiKey`/Model
* (see design/11). Matches the first allow-listed mention; the rest of the text is returned cleaned.
*
* **Case-INSENSITIVE, deliberately** — and deliberately UNLIKE the catalog, whose lookups
* ({@link resolveModel}) are exact. The two answer different questions and the asymmetry is the
* design, not an oversight: a chat mention is a HUMAN-typed UX surface where `@Opus` and `@opus` are
* the same intent, so intake is wide; a catalog key is a machine identifier a deployment declared, so
* lookup is exact. The join is safe because the wide half never widens the narrow one: this returns
* the allowlist's OWN canonical spelling (never the user's casing), so the value handed to
* `resolveModel` is always a key the deployment wrote. The only visible consequence is that a catalog
* carrying two keys differing ONLY in case is addressed by whichever the allowlist iterates last —
* `@x` cannot name both, and there is no spelling that disambiguates them.
*
* Typical use: `const { model, cleanedText } = parseModelMention(userMsg, Object.keys(runner.agentCatalog.models ?? {}));`
* then `runTask({ objective: cleanedText, model })` (omit `model` to fall back to the default role).
*
* **Feed it the EXPANDED table.** The allowlist this takes is the host's own, and on a deployment that
* configured `RunnerDeps.tiers` the host's `deps.models` is NOT what the Runner resolves against: the
* constructor runs {@link expandTierKeys} once and keeps the expansion PRIVATE, so tier words and CC
* aliases (`pro`/`flash`/`opus`/`sonnet`/`best`/…) are catalog keys inside the Runner and absent from
* the host's table. Passing `Object.keys(deps.models)` therefore makes a user's `@opus` silently not
* match — the mention falls through as ordinary text and the task quietly runs on the default role.
* `runner.agentCatalog.models` is the expanded table (a per-read copy); a caller that has no Runner in
* hand can pre-expand its own with the exported {@link expandTiers}.
*/
export declare function parseModelMention(text: string, allowedNames: Iterable<string>): ModelMention;
/**
* Role → 档位默认表(裁定 2026-07-11:「role 体系用户不感知」)。配了 `RunnerDeps.tiers` 的部署,
* 各 role 未显式配置时自动落到语义档位——用户/壳只感知档位,roles 降级为内部路由层:
* - `default` → `pro`(主力档兜底;用户/部署 roles.default / TaskSpec.model 恒可覆盖);
* - `summarize` → `flash`(压缩本该便宜;flash 未绑沿降档链到 lite);
* - `verifier` → `pro`;
* - `classifier` → `flash`(design/143 批2b:auto-mode 权限分类腿是便宜档;flash 未绑沿降档链到 lite);
* - `subagent` 无档位默认 = 走 FALLBACK 继承主模型(LLM 可经 model 参数自选档);
* - `consolidate` 同样无档位默认,但它的 FALLBACK 刻意只有 `summarize` 一站(design/376,见
* {@link FALLBACK} 的注):未配即响亮拒,不静默骑主模型。
* 未配 tiers 的部署:catalog 无 TIERS_ACTIVE 标记 → 表整体 INERT,行为与从前逐字节一致
* (即使 catalog 恰有裸模型名 `pro`/`flash` 也不入档位路由——INERT 靠配置成立,不靠键名运气)。
*
* WHERE A ROLE LANDS WHEN ITS TIER IS ABSENT (#2614) — one answer, the walk of {@link roleHop} / {@link resolveTaskModel}:
* 1. a tier word lands on the nearest bound tier at or below it ({@link DEFAULT_TIER_ORDER}); that is the expansion's own reading
* (`expandTierKeys`), and every reader of a tier word — a role's tier default, a word written at a seat, a classifier / advisor
* tier read — asks the expanded catalog's key, so "absent" has this one definition: no key;
* 2. a role's tier DEFAULT with no key supplies no model — the walk goes on to the next role of its chain (`summarize → default`;
* the reference's small-model seat goes on to the main model the same way), without a word: the seat stated nothing that went unmet;
* 3. a seat that WROTE the absent tier word (or a name the catalog does not hold) is read as unset by the same walk and said once
* (`config.entries_not_applied`, kind `model_word_unknown`, the entry's `reason` `tier_unbound` / `unknown_model_ref`);
* 4. a chain that ends with no model is refused (`config.unknown_role`, `no_model_for_role`; or the first unheld seat's own), the refusal
* naming the absent tier when the deployment declared tiers. The walk never goes UP the order: a deployment that binds only tiers above
* the one a role defaults to supplies the role no model.
*/
export declare const ROLE_TIER_DEFAULTS: Readonly<Partial<Record<ModelRole, string>>>;
/**
* Whether a RoleSpec NAMES a model — a string ref, a Model object, or a config object carrying `model` or
* `select` — as opposed to a preset-only object (`{ thinking }`, `{ systemPrompt }`) that shapes the role's
* request but leaves its model to the defaults. The classifier seat's own default (the tier below the run's
* main model, `classifier-ladder.ts`) applies exactly when this is false: a `{select}` keeps its selection, a
* preset-only role does not disable the relative pick. One reader, the same parts {@link specParts} reads.
*/
export declare function roleSpecNamesModel(spec: RoleSpec | undefined): boolean;
/** Merge two role maps, field-aware per role (task `over` wins). Every key and every value of both maps is judged first: a value that is no binding
* (`null`, a number, a boolean, a word the catalog does not hold) is refused at its own seat before the merge reads it (the merge would otherwise read a
* number as a record, or let a task's bad value vanish into the base); a list or a function written at a role seat still reads as an empty record (#2223 ⑦). */
/**
* One role map's door — every key a role word, every entry a binding whose parts are each in their domain (its role word
* included) and whose named model has a binding's shape. `field` names the map (`RunnerDeps.roles` / `TaskSpec.roles`).
* Every entry is judged, read or not: a resume's screen calls it before the claim, and the merge below calls it on both
* maps, so an entry no task of this leg selects still refuses loudly.
*/
export declare function screenRoleMap(roles: ModelRoles | undefined, field: "RunnerDeps.roles" | "TaskSpec.roles"): ModelRoles | undefined;
/**
* WHY a role seat's word supplies no model — the closed set behind the `reason` of `config.entries_not_applied`'s `model_word_unknown` entries (#2571, #2614). `unknown_model_ref`: the
* catalog holds no entry of that name. `tier_unbound`: the word is of the tier layer's fixed vocabulary (a tier, a CC alias, `best`) and the
* deployment declared tiers, but bound none at that tier or below it — a tier word is laid out as the nearest bound tier at or below it
* (`expandTierKeys`), so an ABSENT one is exactly a tier with nothing under it. Both are read by the one reading below ({@link seatRead}): the
* seat is an unset one, and the tier default and the fallback chain follow.
*/
export declare const ROLE_SEAT_STAND_IN_CAUSES: readonly ["unknown_model_ref", "tier_unbound"];
export type RoleSeatStandInCause = (typeof ROLE_SEAT_STAND_IN_CAUSES)[number];
/** A role seat whose word the catalog does not hold: the role, the seat as the refusal names it, the word written there, why it is not held,
* and whether the role's OWN tier default is bound in that catalog (the walk's tier step then supplies this role a model: {@link roleTierModel}). */
export interface UnheldRoleSeat {
role: ModelRole;
seat: string;
word: string;
cause: RoleSeatStandInCause;
ownTierBound: boolean;
}
/**
* The ONE test of "this seat names a word the deployment's catalog does not declare": the word a role entry writes — the string
* itself, or the `model` member of a config record — when it is a string and no key of the catalog answers it. A Model object, a
* `select`, a preset-only record and an absent seat name no word. Total: it reads, never judges the shape (a value that is no binding
* is the screen's refusal, `screenRoleMap`).
*/
export declare function unheldSeatWord(spec: unknown, models: Record<string, Model> | undefined): string | undefined;
/** Every role seat of the merged maps (deployment and task) that names a word the catalog does not hold, in vocabulary order — the facts
* {@link seatRead} stands in for. `default` is never listed (it refuses) and neither is `classifier` unless asked (it says it itself). */
export declare function unheldRoleSeats(spec: {
roles?: ModelRoles;
}, deps: {
models?: Record<string, Model>;
roles?: ModelRoles;
}, only?: readonly ModelRole[]): UnheldRoleSeat[];
/** The refusal of an unheld seat — the seat's own `config.unknown_role` / `unknown_model_ref`, for the place where a chain ends with no model;
* a seat whose word is an absent tier says so beside it (the reason word of the refusal is the same: the notice's `tier_unbound` is its cause). */
export declare function unheldSeatRefusal(u: UnheldRoleSeat): Error;
/** The refusal for a chain of roles that supplied no model while one of its seats was written but not held — that seat's own
* `config.unknown_role`; `undefined` when no seat of the chain is unheld (the caller's own "no seat" refusal stands). */
export declare function unheldChainRefusal(chain: readonly ModelRole[], models: Record<string, Model> | undefined, roles: ModelRoles | undefined): Error | undefined;
/** The roles a role falls back to when its seat supplies nothing, nearest first (what {@link unheldRoleSeats} says it stands in for). */
export declare function roleFallbackChain(role: ModelRole): readonly ModelRole[];
export interface ResolvedRole {
model: Model;
/**
* WHICH REF CHOSE {@link model} — the word, when a word chose it (the explicit `spec.model` string, the
* role's own `model` ref, or the role→tier default's catalog key), else the `Model` object itself (an
* explicit object, or one a `select` criteria picked: neither has a catalog word).
*
* The distinction is load-bearing wherever a LATER tick must ask the catalog the same question again: a
* word re-resolves against the catalog generation in force at that tick (a hot swap redirects it, a
* retirement refuses it loudly), while an object is pinned and never re-resolved. The engine-spawned
* child that inherits its parent's model inherits THIS, not the resolved object, so it lands on the
* generation its own prepare sees rather than on the one its parent started under; the same word keys
* the deployment's per-model context-window overlay.
*/
modelRef: ModelRef;
/** The effective thinking level, the one reading of the chain: explicit `spec.thinking` wins, else the role's default,
* else the resolved model's own `Model.defaultThinking` ({@link thinkingOf}); absent ⇒ no tier is named anywhere, so the
* request writes no thinking key and the provider's default governs. */
thinking?: ThinkingLevel;
/** The requested role's role-base statement, if it made one (independent of model fallback): its word (the host role
* and the catalog variant it selects) and its text (which replaces that base) — the second source of the role-base
* decision, after the task's own (`src/prompt-assembly/role-base.ts`). */
promptRole?: HostRole;
systemPrompt?: string;
}
/**
* The task's requested role word — `modelRole`, `"default"` when absent — judged against the vocabulary ({@link assertKnownRole}): the
* door the chain head reads it through, and the one a resume's screen calls before its claim (the config alone decides it; no catalog,
* no role map is read). Only an absent role defaults; a `null` written there is a word the vocabulary does not hold.
*/
export declare function screenModelRole(word: unknown): ModelRole;
/** The run's model as a leg's prepare resolves it: the {@link ResolvedRole} and the input the Model's own declarations came from
* (`modelInput`) — the request when the Model object is written in it (`TaskSpec.model`, a `TaskSpec.roles` binding), else the
* deployment (a catalog entry the word, the criteria or the tier default named; a deployment role's object). Engine-internal: the
* doors that judge what the model declares (its `extraBody`, capabilities, prompt traits, price table) are entered with it. */
export type PreparedRole = ResolvedRole & {
readonly modelInput: ConfigRefusalInput;
};
/**
* The requested role's role-base statement as the task path reads it — the chain-head role over the merged maps, its
* word and its text whole (the role-base decision's second source, `src/prompt-assembly/role-base.ts`); `undefined` ⇒
* the preset names none. For a station that must write the preset onto a child's own seat before prepare (the
* workflow lane's persona frame) — it reads exactly what prepare will, and refuses what prepare would.
*/
export declare function presetRoleBaseOf(spec: {
modelRole?: ModelRole;
roles?: ModelRoles;
}, deps: {
roles?: ModelRoles;
}): RoleBaseDeclaration | undefined;
/**
* Resolve the model (and default thinking) for a task. Explicit `spec.model` wins; otherwise walk the
* `modelRole`'s fallback chain over the merged roles (task overrides runner) and use the first role
* that supplies a model. A seat on that chain whose word the catalog does not hold supplies none ({@link seatRead}); when the whole
* chain supplies none, the first such seat's own refusal is the answer. Throws a helpful error if nothing resolves.
*
* @contract roles.side_channels_deployment_only — an engine SIDE CHANNEL (the auto-mode classifier,
* the compaction/summarize lane, memory consolidation, next-prompt suggestion) resolves here with a
* `modelRole` and NO run model: it runs on the deployment's roles alone — the boot default at the end of
* its chain — and never follows the model a run was switched to. Only a run's CHILDREN follow the parent:
* the delegation seat (`childModelSeat`) passes the parent's `Model` as `spec.model` with the role kept
* on `modelRole` — and keeps that role on an EXPLICIT-model seat too, so the explicit branch below reads
* the child's presets off the subagent role, not the default one. A side channel that must follow a run
* passes that run's model explicitly; nothing here infers it.
*/
export declare function resolveTaskModel(spec: {
model?: ModelRef;
modelRole?: ModelRole;
roles?: ModelRoles;
thinking?: ThinkingLevel;
}, deps: {
models?: Record<string, Model>;
roles?: ModelRoles;
}): ResolvedRole;
/** {@link resolveTaskModel} with the input the model's own declarations came from ({@link PreparedRole}); every refusal of the chain
* leaves with the input it is about — the request's seats (`TaskSpec.model`, `thinking`, `modelRole`) the request, a role seat the map
* that supplied its binding, a catalog entry the deployment, and a chain that supplies no model whoever asked for the role. */
export declare function resolvePreparedRole(spec: {
model?: ModelRef;
modelRole?: ModelRole;
roles?: ModelRoles;
thinking?: ThinkingLevel;
}, deps: {
models?: Record<string, Model>;
roles?: ModelRoles;
}): PreparedRole;
/**
* Resolve a role's model **only if that exact role key is configured** (no fallback chain). Used for
* the `summarize` compaction model: override only when a summarize-specific model is set, otherwise
* let the caller fall back to the main model (unchanged behavior). A seat naming a word the catalog does not hold is "not set" here,
* as in the walk ({@link roleHop}, the one reading of a role's own supply); a caller that needs a model asks {@link unheldRoleSeats} for the
* refusal when it gets none.
*/
export declare function roleModelIfSet(role: ModelRole, spec: {
roles?: ModelRoles;
}, deps: {
models?: Record<string, Model>;
roles?: ModelRoles;
}): Model | undefined;