@sema-agent/core
Version:
Stateless, task-oriented AI agent core
205 lines (204 loc) • 15.4 kB
TypeScript
import type { AgentMessage } from "../internal/harness.js";
import { type Model } from "../internal/llm.js";
import { type ContextWindowOverlay } from "./context-settings.js";
/**
* Last-resort, in-task context trim. Proper compaction (LLM summary) runs *between* tasks;
* this prevents a single task whose internal tool-loop balloons from overflowing the window.
*
* Keeps the request's irreducible core — every summary message and every row `held` names (the
* run's objective and its attachments, {@link objectiveInputRows}: the person's words are what the
* request is about, and a request without them answers nobody) — plus the most recent other
* messages that fit the budget, dropping older ones at a safe boundary (never starting on an orphan
* toolResult). The newest message rides the request unless it is itself part of the core. A core
* that alone exceeds the budget is not this function's to repair: the caller measures it with
* {@link irreducibleCoreTokens} and ends the request loudly instead. Returns the original array
* when already within budget.
*
* Every size is the message's own: `sizeOf` (absent ⇒ the structural estimate at `charsPerToken`, design/123 D2, default 3
* since design/374 slice 4) is what one message of `messages` costs as this request sends it — the request's copy
* projection renders a repeated copy of a file as one sentence, so its cost depends on the view ({@link RequestSize}); a
* trim that changes which copy comes first is measured again by the caller. `budgetTokens` is what the messages may take in
* that coordinate: the request's fixed prompt and the scale that converts estimates into what the provider counts are the
* caller's ({@link rowsRoom}) — a usage report is no argument here, since a report measures the request it answered, not
* one this trim makes.
*/
export declare function trimToBudget(messages: AgentMessage[], budgetTokens: number, charsPerToken?: number, held?: (m: AgentMessage) => boolean, sizeOf?: RequestSize, cut?: TrimCut): AgentMessage[];
/**
* The tokens of a request view's irreducible core — what no trim may drop: the compaction summaries and the rows `held`
* names (the run's objective and its attachments). One measure, read by the two places that ask whether the core fits
* one request: the guard chain's last resort (a core over the guard line ends the request loudly instead of being
* trimmed into one that answers nobody) and the objective's admission (refused before anything is sent when its core
* would not fit). Structural, in the model's coefficient — the trim's own estimator; `sizeOf` as the trim reads it.
*/
export declare function irreducibleCoreTokens(view: readonly AgentMessage[], held: ((m: AgentMessage) => boolean) | undefined, charsPerToken?: number, sizeOf?: RequestSize): number;
/** What one message of a request view costs as the request sends it (structural tokens, the model's coefficient). */
export type RequestSize = (m: AgentMessage) => number;
/**
* How the guard sizes a request it trims: `scale × (fixedTokens + its messages' sizes)`. `fixedTokens` is what every
* request carries beside its messages (the system prompt and the tool schemas); `scale` converts the structural estimate
* into what the provider counts, read off the latest usage report against the request it answered.
*/
export interface RequestSizing {
readonly fixedTokens: number;
readonly scale: number;
}
/** What the messages of a request sized by `sizing` may take under `line` — the budget {@link trimToBudget} fits the rows it may
* drop to (the guard's pointer arm reads the line itself). Negative when the fixed prompt alone is over the line (nothing then fits
* but the floor). */
export declare function rowsRoom(line: number, sizing: RequestSizing): number;
/** Where the guard's trim may start ({@link trimToBudget}): `stepped`, on its grid of steps; `notBefore`, an index into the view —
* the start of the previous request of the stretch — before which no droppable row is kept. */
export interface TrimCut {
readonly stepped?: true;
readonly notBefore?: number;
}
/**
* How the guard sizes a request it trims — a pure reading of `base` (the view's rows before the build's own clears), what each row
* costs as sent (`sizeOf`) and the fixed prompt (`overheadTokens`), which a request's admission can make as well as its build;
* `rowsRoom(line, requestSizingOf(…))` is what the messages may take under `line`. The scale is the latest usage report's request side (its count less its own output) over the estimate of
* the request it answered ({@link lastUsageReport}: the estimate a trimmed request's reply states, else the fixed prompt and every
* row before the reply), held to [{@link SIZING_SCALE_MIN}, {@link SIZING_SCALE_MAX}] — and to 1 at least when a later too-long
* refusal says the report measured less than its request. No report ⇒ 1.
*/
export declare function requestSizingOf(base: readonly AgentMessage[], sizeOf: RequestSize, overheadTokens: number): RequestSizing;
/**
* How one run sizes its requests across builds: a view that holds a report is sized off it ({@link requestSizingOf}) and the run
* remembers that scale; a view that holds none (a compaction just landed, or the session was compacted while idle) is sized at the
* scale the run read last — 1 only when it has read none.
*/
export declare function createRunSizing(): (base: readonly AgentMessage[], sizeOf: RequestSize, overheadTokens: number) => RequestSizing;
/** The size a view is judged at against a line: the latest report and the rows after it, or — no report anchoring the view — its
* estimate (its rows and the fixed prompt) at `scale`, the sizing's ({@link createRunSizing}; the 1e-6 as in {@link rowsRoom}: a
* product whole in exact arithmetic stays whole). */
export declare function judgedTokens(est: {
readonly tokens: number;
readonly lastUsageIndex: number | null;
}, scale?: number): number;
/** A trimmed request the fixed prompt leaves too little of the guard line for: what it kept (its core and its newest turn) is
* over the room. In the provider's count: `roomTokens = lineTokens − fixedTokens` (never below 0), `neededTokens` what the kept
* messages take. */
export interface RoomShortfall {
readonly fixedTokens: number;
readonly lineTokens: number;
readonly roomTokens: number;
readonly neededTokens: number;
}
/** The shortfall of a trim that kept `keptTokens` (its messages' sizes) against `line`, or none when they fit the room. */
export declare function roomShortfallOf(keptTokens: number, line: number, sizing: RequestSizing): RoomShortfall | undefined;
/** The run's objective input as the request guard holds it: the exact text the objective's message was sent with and the
* `human_input` key its attachment frames carry. */
export interface ObjectiveInput {
readonly text: string;
readonly inputId: string;
}
/**
* The rows of a request view that ARE the run's objective input: the newest user message that opens with the objective's
* exact text, and every attachment frame declared on it (its delivery record names the input; a compaction's restore
* frames are the engine's re-reads, not the person's input). Read off the view itself — the text and the delivery record
* are what a rebuilt, copied or reloaded transcript keeps; an older message with the same words is history.
*/
export declare function objectiveInputRows(view: readonly AgentMessage[], input: ObjectiveInput | undefined): ReadonlySet<AgentMessage>;
/**
* The engine frames a request carries beside the objective input — what the guard trim holds with it and what a landed
* compaction states again: the newest carrier of each `protectedTexts` frame (its text inside an ENGINE region of a user
* message — the permission posture's), and the newest frame of each task-root instruction file (by label; a later
* withdrawal of that label releases it). An older copy is history and trims like it. Read off the view itself.
*/
export declare function heldEngineFrames(view: readonly AgentMessage[], protectedTexts: readonly string[]): Set<AgentMessage>;
/**
* The tokens a landed compaction states again whatever it summarizes: the task-root instruction frames the view holds
* (each a frame message of its own, {@link heldEngineFrames}) and the frame texts a landing writes again — the
* `protectedTexts` (the permission posture: its text, never the message that carries it, which may be the objective's own)
* and the `restatedTexts` (the git frame). With the fixed prefix it is the floor no summary gets a request below — the
* compaction trigger's "window below overhead" judgment reads the two together, while the prefix alone stays what the
* anchor-less trigger adds.
*/
export declare function restatedFramesTokens(view: readonly AgentMessage[], held: {
readonly protectedTexts: readonly string[];
readonly restatedTexts: readonly string[];
}, charsPerToken?: number): number;
/** The request's irreducible core across one run leg: the objective input the guard trim holds (set when the leg's
* objective is sent; absent on a leg that sends none) and the typed terminal once a core cannot fit — the loop folds a
* request-build throw into a text-only failure message, so result assembly reads the code here. */
export interface RequestCoreRef {
objective?: ObjectiveInput;
terminalCode?: "irreducible_core_over_budget";
}
/** The one mint of the request-build guard's loud terminal: `what` names the core that does not fit. Parks the code on the
* ref (the surface bridge) and returns the error to throw. */
export declare function coreOverBudgetTerminal(ref: RequestCoreRef, what: string): Error & {
code: "irreducible_core_over_budget";
};
/** The verdict on a request that reached the guard's trim over the line: its irreducible core (`coreTokens`, summaries plus
* `heldRows` held rows) still over the line has no honest form — throws the typed terminal; otherwise returns. */
export declare function refuseCoreOverLine(coreTokens: number, budgetTokens: number, heldRows: number, ref: RequestCoreRef): void;
/**
* In-band notice for a request view whose oldest messages were dropped by the guard trim. Every
* other history-reducing pass in the pipeline announces itself to the model (compaction injects a
* summary); a silent trim leaves the model unaware that earlier instructions or constraints are no
* longer visible. MUST remain a single static string: the notice is re-inserted on every trimmed
* request, and a byte-identical prefix keeps provider prefix caching effective.
*/
export declare const CONTEXT_TRIM_NOTICE: string;
/**
* Insert the static trim notice ahead of the kept tail of a trimmed request view (after any
* always-kept summary messages, which lead the rebuilt array). Call ONLY when the trim actually
* dropped messages. Request-view only — the synthetic message is never persisted to the session
* (fixed timestamp keeps it fully deterministic).
*/
export declare function insertTrimNotice(trimmed: AgentMessage[]): AgentMessage[];
/** R2-3 (falsification round 2) — does the message's ENGINE-AUTHORED region cover [start, start+len)?
* The carrier scan must never crown a counterfeit: a tool result or a user paste can reproduce the
* wrapped frame bytes verbatim, but only ENGINE metadata (engineMinted whole-message, the
* enginePrefixChars head, or an engineSegments range) proves the engine put them there. */
export declare function engineRegionCovers(m: AgentMessage, start: number, len: number): boolean;
/** Outcome of {@link protectGitFrame} — `over_budget` means the irreducible core (summaries + the
* protected frame carrier) exceeds the budget even after the one-shot degraded shrink: the caller
* must fail the request LOUDLY (`irreducible_core_over_budget`) instead of pretending the trim
* succeeded or looping compaction/re-assertion. `core` (present iff the caller passed the rows it
* holds): the request's whole irreducible core in the returned view — the summaries, the held rows
* and the frame — for the caller's own verdict on it. */
export type GitFrameGuardOutcome = {
messages: AgentMessage[];
action: "kept" | "absent" | "reinserted" | "shrunk";
core?: number;
} | {
action: "over_budget";
};
/**
* env-tail migration — the git frame's UNCLIPPABLE-CORE protection over a trimmed request view.
* The frame's "value unchanged ⇒ never re-sent" contract makes a request-only drop uniquely
* dangerous for it: the commit receipt has already landed, so a trim that cuts the carrier makes
* the announced hash suppress every future re-send while the model never saw the frame. Rules:
* - REPLACE-BY-KEY SLOT: exactly ONE carrier is protected — the newest message whose flat text CONTAINS
* `protectedText` (the ENGINE-HELD wrapped frame segment; set at delivery/re-assert AND
* re-seeded on value-unchanged legs, so the protection survives legs that send nothing).
* Older frames trim like ordinary history.
* - Re-insert a dropped carrier after the leading summaries/trim-notice (its original relative
* position is always ≥ there — the carrier predates every kept tail message).
* - IRREDUCIBLE-CORE arc: when the core (always-kept summaries + the carrier) alone exceeds the
* budget, substitute the carrier's frame segment with the deterministic DEGRADED rendering —
* exactly once per run (`alreadyShrunk` latch, request-view only; the run loop re-announces the
* shrunk view through its own receipt machinery). Still over after the shrink ⇒ `over_budget`.
* - A total overshoot whose core FITS is left alone (turn-alignment overshoot is a pre-existing,
* tolerated trade — validity beats budget; this guard must not convert it into a failure).
* - `held` (the rows the trim holds — the run's objective input): the frame is part of a larger
* core. The one shrink step also runs when the frame alone fits but the whole core does not and
* the shrink makes it fit (the degraded rendering is engine bytes inside the objective's own
* message on the prefix-carry form); the whole core is returned as `core` for the caller to
* judge, while `over_budget` stays scoped to what it names (summaries + the frame).
*/
export declare function protectGitFrame(before: AgentMessage[], trimmed: AgentMessage[], budgetTokens: number, frame: {
protectedText: string;
substitute?: {
find: string;
replace: string;
};
}, // protectedText = the wrapped frame SEGMENT (see the carrier scan below)
charsPerToken?: number, held?: (m: AgentMessage) => boolean, sizeOf?: RequestSize): GitFrameGuardOutcome;
/** Budget the in-task guard targets for a model — CC-aligned headroom numbers with a 0.85
* small-window floor, sema-owned drop-oldest action (see {@link GUARD_HEADROOM_TOKENS}); always
* above the compaction/clearStale frontier. Dual-window semantics: deliberately the PHYSICAL
* window (`contextTokens ?? contextWindow`), NOT `autoCompactTokens` — the guard protects the
* real request limit; a lowered autocompact window only moves the trigger-side geometry. */
export declare function guardBudget(model: Model, overlay?: ContextWindowOverlay): number;