UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

336 lines (335 loc) • 25.5 kB
import type { ThinkingLevel } from "../internal/harness-types.js"; import { type ModelCapability } from "./model-capability.js"; /** * Unified reasoning-intensity abstraction (design/96 S3). * * The intensity a caller requests IS a {@link ThinkingLevel} — we reuse the existing 7-tier vendor scale * (`off | minimal | low | medium | high | xhigh | max`) rather than forking a parallel "fast/standard/deep" * enum, so there is ONE knob, not two that must be kept in sync. This module is the single place that maps a * requested intensity to what a given endpoint can ACTUALLY honor, and reports the EFFECTIVE intensity — so a * request that can't be honored as asked ("high" on a binary enable-only provider like qwen/zai, or * "xhigh"/"max" on an endpoint whose `reasoning_effort` only accepts up to "high") is observable rather than * silently swallowed or 422'd (design/96 §E honesty red-line; design/46 anti-drift). * * The wire applier (reasoning-request.ts) consumes these tables; what a request's keys SAY about the tier is said there, * where the keys are written, and the reported resolution is derived from that one answer. */ export type ReasoningIntensity = ThinkingLevel; /** The seven tiers in rank order, read off the one rank table — for a sentence that names the closed set. */ export declare const THINKING_LEVELS: readonly ThinkingLevel[]; /** Type guard: is `v` one of the 7 {@link ThinkingLevel} tiers? (A legacy/unknown reasoning string is not.) */ export declare function isThinkingLevel(v: unknown): v is ThinkingLevel; /** * THE thinking-request ENTRY predicate — does this request enter an applier's emission path at all? * One conjunction, three arms: the request sends the requester's reasoning (on a request an engine brain builds — `withheld` * present — `capabilityTried`, the requester's reader of the one capability declaration: declared on, or undeclared and not in * the request's `withheld` set; for any other caller `capabilityHeld`, the declaration alone — a declaration of the wrong shape * throws there instead of reading by truthiness), the requested value is a real * {@link ThinkingLevel} (an out-of-contract value — a typo'd tier, a caller's own enum — reads as * ABSENCE, never as a declared tier), and it is not the explicit `"off"`. A tier the ENGINE chooses for its own request * reaches this gate only where the declaration carries it (`engineSeatTier`, reasoning-request.ts). * * ENTRY gate, deliberately NOT an emitted-a-key guarantee: past this gate the per-lane arms of the wire applier * (`applyReasoningToRequest`, reasoning-request.ts) still decide what (if anything) lands on the wire — * `supportsReasoningEffort:false` on a lane whose only carrier is the effort key, a `null` levelmap entry, the binary * enable keys — and each says, where it writes, what its keys say about the tier. */ export declare function reasoningRequestCarried(model: { reasoning?: boolean; }, reasoning: unknown, withheld?: readonly ModelCapability[]): reasoning is ThinkingLevel; /** * THE judge of a thinking tier a caller STATES: absent (`undefined`) is the one unset reading and answers itself; one of the seven * {@link ThinkingLevel} tiers answers itself; anything else — a typo'd tier, another casing, `null`, a number — is refused by name * (`config.invalid_argument`, `detail.field` = `seat`), never read as "no tier". A request that names a tier the engine cannot * honor must not run on the provider's own default (a default-on gateway would be thinking on every turn) with nothing said. * Asked at every seat where a tier is stated — a task's own `thinking`, a role record's `thinking`, an agent definition's `thinking`, the * resolver's `requested` — so one vocabulary has one sentence. */ export declare function judgeThinkingLevel(value: unknown, seat: string): ThinkingLevel | undefined; /** Ordinal rank of a level (`off`=0 … `max`=6). */ export declare function rankOf(level: ThinkingLevel): number; /** * The `reasoning_effort` tiers an OpenAI-family endpoint accepts by DEFAULT. Conservative on purpose: a value * the endpoint rejects 422s the whole request, so we ship the set stock OpenAI takes * (`minimal | low | medium | high`) and clamp anything higher ("xhigh"/"max") down to "high". An endpoint that * genuinely accepts a higher tier declares it via `compat.reasoningEffortLevels`. */ export declare const DEFAULT_EFFORT_LEVELS: readonly ThinkingLevel[]; /** * The per-provider thinking wire format (mirrors `compat.thinkingFormat`). `"budget"` is the synthetic tag for * Anthropic's extended-thinking budget path (no `thinkingFormat` — the anthropic brain doesn't read one), kept * here so a request's carriage names ONE dialect-or-lane discriminant across every wire family. */ export type ReasoningFormat = "openai" | "openrouter" | "deepseek" | "together" | "zai" | "qwen" | "qwen-chat-template" | "budget" /** Anthropic `output_config.effort` (Fable-5 class, design/119): the tier is a named * effort string, clamped to `compat.effortLevels` — the anthropic-side twin of the OpenAI * `reasoning_effort` path (thinking FORM is `thinkingMode`; effort carries the intensity). */ | "effort" /** OpenAI Responses API (`openai-responses` / `azure-openai-responses`, design/163): the tier rides * the NESTED `reasoning: { effort }` request field (the Responses arm of `applyReasoningToRequest`), clamped * by the same {@link resolveEffort} against `compat.reasoningEffortLevels` — NOT the completions * top-level `reasoning_effort` the `"openai"` tag names. #325 review r3: before this member the * resolver fell through to the completions default and labeled Responses resolutions `"openai"`. */ | "responses"; /** The chat-completions dialect names — `compat.thinkingFormat` on a completions-family model. */ export type CompletionsThinkingFormat = Exclude<ReasoningFormat, "budget" | "effort" | "responses">; /** The chat-completions dialect names, in the closed set's order — for a sentence that names the set. */ export declare const COMPLETIONS_THINKING_FORMATS: readonly CompletionsThinkingFormat[]; /** Whether `v` is one of the chat-completions dialect names ({@link COMPLETIONS_THINKING_FORMATS}). */ export declare function isCompletionsThinkingFormat(v: unknown): v is CompletionsThinkingFormat; /** * THE judge of a completions dialect name — the one read of `compat.thinkingFormat`: absent (or `null`) is no declaration * (`undefined`), a name in the closed set of {@link COMPLETIONS_OFF_SPELLING} is itself, and anything else — a string outside the * set, an array, a number — is refused by name (`config.invalid_argument`, `detail.field` = `compat.thinkingFormat`), never read * as "no dialect". Every reader of the name asks it (through {@link completionsFormatOf} where absence means `"openai"`): the wire * applier, {@link offSpelling} (so {@link thinkingOffSpelled} and the answer-only seat), and the model gate's receipt, which * refuses the entry before any request is built. */ export declare function declaredCompletionsFormat(compat: { thinkingFormat?: unknown; }): CompletionsThinkingFormat | undefined; /** The completions dialect a request is written in: the judged declaration, `"openai"` when none is declared. */ export declare function completionsFormatOf(compat: { thinkingFormat?: unknown; }): CompletionsThinkingFormat; /** * The Open Responses API family — every `Api` value `createOpenResponsesBrain` serves (design/163). * The SINGLE family discriminant: request-params.ts (reserved-key set selection) and the wire applier's lane * selection (reasoning-request.ts) both key off THIS set, so a new * Responses api value added here reaches every family-scoped behavior instead of one of two twins. */ export declare const RESPONSES_APIS: ReadonlySet<string>; /** The keys every resolution of a requested intensity carries, whatever vocabulary its `effective` speaks. */ export interface ReasoningResolutionKeys { /** The level the caller asked for. */ requested: ThinkingLevel; /** * True exactly when `effective` is one of the six enabled tiers — the wire names an intensity. False for `off`, for `on` * (thinking is on and no tier rides: a binary enable key, adaptive thinking, a knob-fixed budget, a `null` levelmap entry * behind an enable key) and for `provider_default`. */ graded: boolean; /** True exactly when `effective` differs from {@link requested} (the request did not carry the tier as asked). */ clamped: boolean; } /** How a requested intensity resolved against one endpoint's real capability — the brains' hot-path form: `effective` is one of the * seven tiers. The reported face ({@link ResolvedReasoning}) widens `effective` by the one word of {@link ReasoningEffective}. */ export interface ReasoningResolution extends ReasoningResolutionKeys { /** The level actually in effect after mapping to what the endpoint accepts. */ effective: ThinkingLevel; } /** * The words {@link ResolvedReasoning.effective} can say — what a request's thinking keys SAY, read where they are written * (`ReasoningCarriage.said`, in reasoning-request.ts): * · one of the seven tiers — the keys name it: `off` is a disable key (or a deployment-declared off value), an enabled tier is * the lane's tier key (an effort value, after the clamp; on the Messages budget form with no budget knob, the budget the * tier's share sized); * · `"on"` — the keys turn thinking on and name no tier (a binary enable key, `thinking:{type:"adaptive"}`, a budget a knob * fixed, openrouter's `reasoning` object with no effort in it); * · `"provider_default"` — the request put NO thinking key on the wire (the {@link ResolvedReasoning.dropped} arm), so whether * the model thinks, and at which tier, is the provider's own default. Never `"off"` for that case: a request that carried * nothing says nothing, and a default-on gateway reasons on it. * * The list of the nine words is {@link REASONING_EFFECTIVE_WORDS}, exported at the package root; the type is read off it, so the two * cannot part. It is the seven tiers ({@link THINKING_LEVELS}, in rank order) then the two words above. The tiers are spelled in the list * (a closed set the release manifest reads is spelled out, not derived), and the fence below fails to compile when a `ThinkingLevel` * is missing from the list (a misspelled or dropped tier); that the list holds nothing but the seven tiers and the two words is the * runtime pin's (`test/backlog4550-closed-word-lists.test.ts`). */ export declare const REASONING_EFFECTIVE_WORDS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max", "on", "provider_default"]; export type ReasoningEffective = (typeof REASONING_EFFECTIVE_WORDS)[number]; /** Anthropic's hard floor for an extended-thinking budget. Lives HERE (not the anthropic brain) so * the cap-wins predicate below and the brain's budget-window math read ONE constant. */ export declare const MIN_THINKING_TOKENS = 1024; /** * The anthropic BUDGET path's cap-wins arm (#346, single-sourced; design/119 #2 review): * a HARD per-request output cap (an engine-imposed override or the caller's explicit * `options.maxTokens` — the two lanes the brain refuses to raise) too small to host a legal thinking * budget (≥ {@link MIN_THINKING_TOKENS}) plus answer room means the CAP WINS and thinking is skipped * for the request. Read by the Messages lane of the wire applier, which acts on it and then says what the request * carries (nothing, when the skip took the only thinking key). A soft (model/config-sourced) cap never skips: the lane * raises it to host the budget instead (`hardCap === false`). */ export declare function budgetCapSkipsThinking(outputCapTokens: number, hardCap: boolean): boolean; /** The model slice the off-capability reads: the API family, the reasoning bit, the compat declaration and the levelmap. */ export interface OffCapabilityModel { api?: string; reasoning?: boolean; compat?: unknown; thinkingLevelMap?: Readonly<Partial<Record<ThinkingLevel, string | null>>>; } /** * The DEPLOYMENT-declared spelling of the explicit "off" tier on an effort-only wire (stock openai * completions, the Responses lane): `thinkingLevelMap.off` as a non-empty string (a provider's own * "none" tier), on an endpoint that takes an effort value at all (`supportsReasoningEffort` not * false) — else `undefined`: there is nothing to send. The effort formats have no disable key, and an * effort VALUE is never off (it enables reasoning at that tier), so off on those wires is spelled only * when the deployment says how. The two appliers and {@link thinkingOffSpelled} read this ONE * function, so what the wire carries and what the capability table claims cannot disagree. */ export declare function declaredOffSpelling(model: OffCapabilityModel): string | undefined; /** * The model-entry input a wire still needs before it can spell the explicit `"off"` tier — what an operator would add: * `compat.thinkingFormat` (a completions model that does not hold reasoning and declares no dialect), `thinkingLevelMap.off` (an effort-only wire — stock openai completions, * the Responses lane — with no declared off value), or `none` (no declaration spells it: the anthropic adaptive form, an * effort-only endpoint that takes no effort value, a Messages or Responses model that does not hold reasoning). */ export type OffSpellingMissing = "compat.thinkingFormat" | "thinkingLevelMap.off" | "none"; /** {@link offSpelling}'s answer: the wire spells off, or it does not and this is the input it lacks. */ export type OffSpelling = { readonly spelled: true; } | { readonly spelled: false; readonly missing: OffSpellingMissing; }; /** * THE off-spelling table — whether the wire will CARRY a disable key for this model, and, when it will not, which declared input * it lacks. Off is SPELLED, never assumed. Per wire: * * - Messages: the budget form spells `{type:"disabled"}` on a model that holds reasoning; the ADAPTIVE form rejects it (those * models think on every request) — `none`. A Messages model that does not hold reasoning is sent nothing (`none`). * - Responses: effort-only — spelled through a deployment-declared off value ({@link declaredOffSpelling}) on a model that holds * reasoning, else `thinkingLevelMap.off` (or `none` where the endpoint takes no effort value at all). A Responses model that * does not hold reasoning is sent nothing (`none`). * - Chat completions: the dialect is the operator's EXPLICIT `compat.thinkingFormat`, whatever the model's `reasoning` * declaration says — a declared dialect is how its disable key is spelled, and sending it never asks the model to think. With * no format declared, a model that holds reasoning is on the default (`openai`) dialect, and one that does not is left to its * provider's default: the engine does not guess a dialect for it (`compat.thinkingFormat`). A name outside the closed set is * refused by the one judge ({@link completionsFormatOf}). On the dialect: deepseek `{type:"disabled"}`, the * binary enable keys at `false` and openrouter / together `reasoning:{enabled:false}` always spell it; stock openai is * effort-only (`thinkingLevelMap.off`, or `none`). * * The reasoning declaration decides whether thinking can be turned ON (`reasoningRequestCarried`); it gates off only where the * wire has no declared dialect to spell it in. The engine sizes a request by what it SENT, never by what it hopes a gateway does * when told nothing — a default-on gateway thinks on a request that carries no key (three of four live endpoints, 2026-09-15). * What this table cannot see is a gateway that IGNORES the key it was sent — the classifier's re-ask on a no-verdict reply is * the seat that learns that from the reply. * * Read by {@link thinkingOffSpelled}, by every explicit-off arm of the wire applier (`applyReasoningToRequest`, in * reasoning-request.ts), and by the classifier's defaulted-seat sentence, which names {@link OffSpellingMissing} — one table, so * what the wire carries, what the capability answer claims and what the sentence asks an operator to declare cannot disagree. * * The wire family is the entry's own `api` unless the caller names it: the applier passes the request's family, which is what * picks its lane, so a host whose model slice carries no `api` is judged on the family it asked for. */ export declare function offSpelling(model: OffCapabilityModel, api?: string | undefined): OffSpelling; /** * Whether the wire will CARRY a disable key for this model — {@link offSpelling}'s `spelled`. * * THE answer to "can this model's thinking be turned off", for every reader: the engine's seats, and a host that serves a model * listing (the Claude Code catalog row calls it `supportsThinkingOff`; a host wraps this answer under that name, beside `reasoning` * — `reasoning: true` with this `false` is a model that cannot be turned off). It is DERIVED from the wire table — the API * family, `compat` and `thinkingLevelMap.off` of the entry, and its `reasoning` declaration — so the catalog row grows no key for * it, the way `reasoningEffortLevelsOf` (reasoning-request.ts) derives the supported tiers: a second, declared copy could only * disagree with the wire. */ export declare function thinkingOffSpelled(model: OffCapabilityModel): boolean; /** * OPTIONAL output-cap facts for `resolveReasoning` (reasoning-request.ts): the cap the request will carry and whether * it is a HARD bound. The resolver hands them to the wire applier as the request body's `max_tokens` and the budget's * `capIsHard`, so a Messages budget-form answer weighs the same cap-wins skip ({@link budgetCapSkipsThinking}) the wire * does; absent, the applier sees a soft cap that never skips. A Runner leg does not pass them: its first request's own * answer reaches the leg's seat on the request's terminal message, which already weighed the cap that request carried. */ export interface ReasoningWireFacts { /** The request's resolved output cap (the wire `max_tokens` at the moment the thinking arm judges). */ outputCapTokens: number; /** True when the cap is HARD (engine override / caller `options.maxTokens`) — the lanes the brain * refuses to raise; a soft model/config cap is raised to host the budget instead. */ hardOutputCap: boolean; } /** * The anthropic-`effortLevels` PRESENCE/SHAPE gate the Messages lane of the wire applier reads — whether the request * carries its tier as `output_config.effort` (and is reported in the `effort` format) or on the budget form. A truthy * NON-ARRAY (a string — `.length > 0` holds) reads as undeclared rather than reaching a `.filter`. Only the container shape * is judged here; MEMBER validity is {@link sanitizeEffortLevels}' job (the single bad-value seat). */ export declare function declaredEffortLevels(v: unknown): readonly ThinkingLevel[] | undefined; /** * The effort-lane WIRE-VALUE mint — clamp ({@link resolveEffort}) + the `Model.thinkingLevelMap` * translation in ONE place, consumed by both effort-lane arms of `applyReasoningToRequest` (completions, * Responses): the clamped tier is what the lane's `said` names when the value is written. Map semantics (the field's * contract): a MISSING key ⇒ provider default (the clamped tier name as-is); a STRING ⇒ that provider-specific spelling * (same tier, still honored); `null` ⇒ the tier is UNSUPPORTED on this model — `wireValue: undefined`, no effort value on * the wire (thinking still turns on through a dialect's own enable key where one exists, and the request then says `on`). */ export declare function mintEffortWireValue(requested: ThinkingLevel, model: { thinkingLevelMap?: Readonly<Partial<Record<ThinkingLevel, string | null>>>; }, allowed: readonly ThinkingLevel[] | undefined): { resolution: ReasoningResolution; wireValue: string | undefined; }; /** * How a requested tier resolved on one request — a pure function of the request (`resolutionOf`, reasoning-request.ts): * `effective` is what the request's thinking keys say, and the three booleans are projections of it. The `reasoning.resolved` * trace frame and `TaskResult.effectiveReasoning` carry it. */ export interface ResolvedReasoning extends ReasoningResolutionKeys { /** What the request's thinking keys say ({@link ReasoningEffective}): a tier, `"on"`, or `"provider_default"` when the request * carried no thinking key at all (the {@link dropped} arm). */ effective: ReasoningEffective; /** The dialect or lane the keys are spelled in — always a member of {@link ReasoningFormat}. */ format: ReasoningFormat; /** A coarse endpoint label for the trace (`model.api` — e.g. `openai-completions`, `anthropic-messages`). */ endpoint: string; /** * Present (true) exactly when `effective` is `"provider_default"`: the request carried no thinking key at all — the model does * not hold reasoning, the wire cannot spell the requested `off`, the lane's only carrier is withheld (`supportsReasoningEffort: * false`, a `null` levelmap entry on an effort-only wire), or a hard output cap too small for a legal budget skipped thinking * ({@link budgetCapSkipsThinking}). What the provider then does is its own default. `format` / `endpoint` name the family that * would have carried the tier. Absent otherwise. */ dropped?: true; } /** The ONE sanitizer behind every effort clamp set: invalid members dropped ("hgih", a sparse hole, `"off"`), a non-array / * empty / no-valid-member declaration reads as undeclared → the conservative default. */ export declare function sanitizeEffortLevels(allowed: unknown): readonly ThinkingLevel[]; /** * Resolve a requested intensity for an effort-based endpoint (`reasoning_effort` / `reasoning.effort`). Picks * the requested tier when supported; otherwise the highest supported tier ≤ requested (clamp DOWN, never * silently up); if none is ≤ requested (the endpoint's set is entirely higher — unusual), the lowest supported * tier. Never returns a value outside `allowed`, so the brain can't emit a tier the endpoint would 422. * A malformed `allowed` reads as UNDECLARED → the conservative default set (non-array, empty, or no * valid member); individually invalid MEMBERS (garbage strings, sparse holes, `"off"` — not a legal * member of the 6-tier compat effort sets) are dropped, so they can never become a clamp target. */ export declare function resolveEffort(requested: ThinkingLevel, allowed?: readonly ThinkingLevel[]): ReasoningResolution; /** * Extended-thinking budget as a FRACTION of `max_tokens` per intensity tier, for budget-based endpoints * (Anthropic). Lets a higher intensity actually buy a larger thinking budget — before this, the budget was a * fixed share regardless of the requested tier, so the intensity had no effect on Anthropic (design/96 §D/§E). * The brain clamps the resulting budget to Anthropic's `[1024, max_tokens-1]` window; an explicit * `thinkingBudgetTokens` / `thinkingBudgetShare` in config still overrides this table. */ export declare const REASONING_BUDGET_SHARE: Record<ThinkingLevel, number>; /** The extended-thinking budget share for a given intensity tier (see {@link REASONING_BUDGET_SHARE}). */ export declare function reasoningBudgetShare(level: ThinkingLevel): number; /** * design/96 §D (S4) — a user-facing NAMED reasoning tier, DISTINCT from the raw 7-tier {@link ThinkingLevel} * ({@link ReasoningIntensity}). A profile maps it to engine flags via {@link resolveReasoningProfile}. This is * the "ultracode" parity axis: a high tier (`ultra`) buys both a higher thinking level AND a thoroughness/ * self-verify prompt nudge. */ export type ReasoningTier = "off" | "fast" | "standard" | "deep" | "ultra"; /** The engine flags a {@link ReasoningTier} resolves to (design/96 §D table). A profile may override the * default; core ships sane defaults. */ export interface ReasoningProfileFlags { /** The vendor thinking level to run at (clamped per-endpoint downstream by {@link resolveEffort}). */ thinking: ThinkingLevel; /** * Compose `ORCHESTRATION_AWARENESS` — a high-tier thoroughness/self-verify nudge. 🔴 NOT the `run_workflow` * tool (that is gated by a hard sandbox, S8 §6.3); this is purely about how the model reasons. Independent * of self-orchestration (a task can be both). */ awarenessGuidance: boolean; /** Advisory HINT that goal mode suits this tier. Core NEVER forces intensity→mode (constitution: the * mapping is profile data); a profile/caller decides whether to actually run `runGoal`. */ goalSuggested: boolean; } /** * design/96 §D (S4) — map a named {@link ReasoningTier} to its engine {@link ReasoningProfileFlags} (default * mapping). G2: the intensity→capability mapping is PROFILE-layer data — core gives this primitive + * a sane default; a profile/scenario layer calls it (and may override the table) to set a task's `thinking` + * prompt flags. Core never forces it. Returns a fresh COPY (callers may mutate). */ export declare function resolveReasoningProfile(tier: ReasoningTier): ReasoningProfileFlags;