@sema-agent/core
Version:
Stateless, task-oriented AI agent core
175 lines (174 loc) • 11.4 kB
TypeScript
import type { Context, Model, SimpleStreamOptions } from "../../internal/llm.js";
import type { SessionTreeEntry } from "../../internal/harness-types.js";
import type { PrefixChangeCause } from "../prefix-declaration.js";
import type { Brain } from "../model-seat.js";
/** Where in the canonical rendering a position falls. */
export type PrefixRegion = "params" | "system" | "tools" | "messages";
/** The first position at which a request stops repeating the previous main request of its model. */
export interface PrefixDivergence {
/** Where the request stops repeating, in the canonical rendering (UTF-16 units, not provider tokens): in `params` / `system` /
* `tools` the first differing unit (it can fall inside a character); in `messages` the start of the first changed message. */
readonly at: number;
/** The previous main request's length in the same rendering. */
readonly of: number;
readonly region: PrefixRegion;
/** `messages` only: the index of the first message that differs (or that the request no longer carries). */
readonly message?: number;
}
/** What one request is, as the ledger read it. */
export interface RequestPrefixReading {
/** sha256 of the request head (controls + system + tools), salted with the session's hash salt, first 16 hex digits. */
readonly head: string;
/** The number of messages the request carries. */
readonly messages: number;
/** The request's length in the canonical rendering. */
readonly chars: number;
/** `extends` — a byte extension of the previous main request of the same model; `no-baseline` — this process holds none
* (never saw one, or a declared history rewrite voided it); else where it stops repeating it. */
readonly prefix: "extends" | "no-baseline" | PrefixDivergence;
}
/**
* A main request that does not extend the previous one, with what was declared since. `at` / `of` are absent exactly when this
* process holds no earlier main request of this model for the session (a reloaded engine, a switch to a model not served here, a
* baseline a declared history rewrite voided): the leg start's comparison against the stored anchor found the change; `segments` names it.
*/
export interface PrefixChange {
readonly at?: number;
readonly of?: number;
readonly region: PrefixRegion;
readonly message?: number;
/** The head segments the leg start's anchor comparison found moved (prompt block ids, `tools`); present only then. */
readonly segments?: readonly string[];
/** Every word declared since the previous main request (empty: nothing was). */
readonly causes: readonly PrefixChangeCause[];
/** A declared word covers the region that changed ({@link REGION_CAUSES}). */
readonly declared: boolean;
}
/** The declaration words that can account for a change in each region. */
export declare const REGION_CAUSES: Readonly<Record<PrefixRegion, readonly PrefixChangeCause[]>>;
interface Rendered {
head: string;
/** Where the system and tool regions start inside `head` (params starts at 0). */
systemAt: number;
toolsAt: number;
digests: string[];
lengths: number[];
chars: number;
}
/** The canonical rendering of a request (see the module header). */
export declare function renderRequest(context: Context, options: SimpleStreamOptions | undefined): Rendered;
/** Where `now` stops repeating `prev`, or undefined when it extends it. */
export declare function divergenceOf(prev: Rendered, now: Rendered): PrefixDivergence | undefined;
/** Where a declared word applies: the head segments a leg start's anchor comparison found moved, and for a history word the
* first message index of the request its rewrite can change (absent ⇒ 0: the whole message region). */
export interface DeclarationReach {
readonly segments?: readonly string[];
/** {@link PrefixChangeDeclaration.from}: an index, or `"tail"` — resolved at the next main request against the previous one. */
readonly from?: number | "tail";
}
/** The session's ledger. */
export interface SessionPrefixLedger {
/** A word the main line declared before its next request (the turn snapshot's declarations; the leg start's opening, with
* the head segments its anchor comparison found moved; the leg start's reading of the store, {@link openLeg}). A word of
* the `messages` region covers a change there only at or after its `from`. */
declare(cause: PrefixChangeCause, reach?: DeclarationReach): void;
/**
* The leg start's reading of the store: `branchOf` reads the path (root first) the leg opens on, after any landing it made;
* `pathOf` reads the path to another entry. Against the branch the session's last leg in this process ended on it declares
* what the store says moved ({@link branchDeclaration}), then records the branch's leaf as the one this process stands on.
* With no such leg it reads nothing (there is nothing to compare; the leg's end records where it stood). A branch the store
* cannot read is a rewrite of the whole history, and leaves no leaf to compare the next leg with.
*/
openLeg(branchOf: () => Promise<readonly SessionTreeEntry[]>, pathOf: (entryId: string) => Promise<readonly SessionTreeEntry[]>): Promise<number>;
/** The leaf the leg `leg` (the number {@link openLeg} answered it) ended on, as the read started at its end answers — its own
* appends are the main line's, already in its last request or after it. The next {@link openLeg} waits for that read until its
* own read of the branch answers, never longer. A read that fails, answers something that is no leaf (neither a string nor
* null), or is still out then, leaves no leaf: the next leg compares nothing, as when no leg of this process stood on the
* session. */
closeLeg(leafId: Promise<unknown>, leg: number): void;
/**
* Read one request. `main` requests become the model's new baseline and, when they do not extend the previous one, come
* back with the change; a side request is read against the baseline and leaves it as it was.
*/
observe(input: {
model: Pick<Model, "provider" | "id">;
context: Context;
options?: SimpleStreamOptions;
main: boolean;
salt: Uint8Array;
}): {
reading: RequestPrefixReading;
change?: PrefixChange;
};
}
/** The reading of the request whose reply carried `usage`, when that request went through an observing brain. */
export declare function readingOfUsage(usage: object | undefined): RequestPrefixReading | undefined;
/** Read one request before it goes out; undefined = nothing to read (the leg's ledger is not seated, detection is off). */
export type RequestObserver = (model: Model, context: Context, options: SimpleStreamOptions | undefined) => RequestPrefixReading | undefined;
/**
* A brain whose every request is read by `observe` before it goes out, and whose every reply carries that reading
* ({@link readingOfUsage}). Both arms obey the same law; the reply is returned unchanged.
*/
export declare function observingBrain(brain: Brain, observe: RequestObserver): Brain;
/**
* The leg's publication seat for prefix changes: armed at prepare, before any request goes out; the run's stream subscribes
* once it exists (changes published before then are buffered, bounded, and flushed in order) and drops its sink when the leg
* ends (a late change buffers, unread).
*/
export declare class PrefixChangeSeat {
#private;
/** How many changes this leg published (the task-end low-hit summary stays silent once one was). */
get published(): number;
emit(change: PrefixChange): void;
subscribe(sink: (change: PrefixChange) => void): void;
unsubscribe(): void;
}
/** A leg's request observers over its session's ledger. */
export interface LegPrefixObservers {
readonly ledger: SessionPrefixLedger;
/** The main line's changes, as {@link observeMain} reads them. */
readonly changes: PrefixChangeSeat;
/** Reads a main-line request (it becomes the model's baseline; a change is published on {@link changes}). */
readonly observeMain: RequestObserver;
/** Reads a side request against the main line (the baseline stays as it was). */
readonly observeSide: RequestObserver;
/** Seat the session's hash salt (resolved with the prompt assembly); a request read before it is seated reads nothing. */
seatSalt(salt: Uint8Array): void;
}
/** The observers of one leg of `session`; with `detection` false (`RunnerDeps.cacheBreakDetection === false`) they read nothing. */
export declare function legPrefixObservers(session: object, detection: boolean): LegPrefixObservers;
/**
* A leg's end on its session's ledger. What the leg's last request carried and the next leg's first will not is declared by the
* seat that carried it — the limit-approach sentence rides the end of each request and is never written, so the next leg's first
* request no longer holds it where it stood (`history_rewrite` from the previous request's last message, the ledger's `"tail"`).
* Then the leaf the leg ended on is read for the next leg's start (`closeLeg`: the read starts here and is not awaited — the leg
* owes nothing to it; the next leg's start waits for it no longer than for its own read of the branch).
*
* Bookkeeping only: it never throws and never waits. A read that throws as it is asked is a read that failed (the ledger stands
* nowhere for that leg), so the leg's own end — its unsubscribes, its terminal and its answer — is the same whatever the read does.
*/
export declare function endPrefixLeg(ledger: SessionPrefixLedger, leg: number | undefined, approach: {
readonly carried?: unknown;
}, session: {
getLeafId(): Promise<string | null>;
}): void;
/** The ledger of `session` (one per session object). */
export declare function sessionPrefixLedgerOf(session: object): SessionPrefixLedger;
/**
* What the store says moved between two legs: `known` is the leaf the session's last leg in this process stood on, `branch`
* the path (root first) the next leg opens on.
* - `known` on the branch: the entries after it are what others appended — a `compaction` among them is the word `compaction`
* (its summary replaces the start of the history: from 0); messages and other entries only extend the history.
* - `known` off the branch (a rewind, a landing on another branch — by a run, a verb or another process): a `history_rewrite`
* from the first message of the request the two branches do not share (the messages the shared path sends: the context it
* builds, as the request converts it); a compaction on either side of the fork replaces the start of one of the two
* histories, so from 0 (`compaction` when it is on the new side); a path that cannot be read is a rewrite of the whole
* history (from 0).
* - no `known` (no leg of this process stood on the session): nothing — there is no main request to compare with.
*/
export declare function branchDeclaration(known: string | null | undefined, branch: readonly SessionTreeEntry[], pathOf: (entryId: string) => Promise<readonly SessionTreeEntry[]>): Promise<{
cause: "compaction" | "history_rewrite";
from: number;
} | undefined>;
export declare function createSessionPrefixLedger(): SessionPrefixLedger;
export {};