UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

236 lines (235 loc) • 17.1 kB
import { type RepetitionEvent } from "./repetition.js"; import { type AssistantMessage, type ModelOutputInvalid, type StreamDropCause, type StreamDropTurn } from "../internal/llm.js"; /** * design/157 A10 — stream-parser pieces that the anthropic and openai SSE lanes carried BYTE-IDENTICALLY * (verified by diff at 1469481: a 16-line repetition-telemetry closure). Provider-agnostic policy, so it * lives here once and each lane keeps a pointer comment. * * REF-B1 extends that: the fail-closed ARGUMENT PARSE inside each lane's `closeToolCall*` (identical down to * its comment) is hoisted here as {@link parseStreamedToolArgs}. Only the parse — each lane keeps its own * accumulator fields, its `closedTc` cache and its own id prefix, which are real wire-format differences. * * Deliberately NOT hoisted: each lane's own degenerate-cut bookkeeping (`degenTextBlock` / `degenFace` are * lane-specific content shapes). * * Internal module: not re-exported from `src/index.ts`. */ /** The warning (the reference's former words; later replaced by a resume request) stamped beside `partialFinalized` when a stream ended before its close — by the * mid-stream promotion (the body threw) and by the parsers' own finalize (content arrived, no finish frame). */ export declare const STREAM_TORN_WARNING = "Connection closed mid-response. The response above may be incomplete."; /** A provider word as a stream-end seat carries it: the word in the provider echo shape that the stream's mint * (`providerWords`) leaves as it is, else `?` — the fact that a word arrived survives, bytes outside the shape or holding * what the request was declared with do not (the echo discipline: dropped, never rewritten). */ export declare function echoFoldedWord(raw: string, providerWords: (words: string) => string): string; /** * The record of what arrived after a stream's first terminal statement — the one ordering rule both wire parsers * apply: the first ending (a finish / stop reason, a message stop, an in-band error) decides the turn; after it the * turn is frozen, only the usage trailer is read, and every later ending or content frame is refused and counted * here. Rides `AssistantMessage.streamEndIgnored` (the first refused frame's kind and word, how many came); the * Runner announces it (`route.stream_end_ignored`). */ export declare function createStreamEndLedger(providerWords: (words: string) => string): { note(statement: StreamEndStatement, word: string, output?: string): void; readonly ignored: AssistantMessage["streamEndIgnored"]; }; type StreamEndStatement = NonNullable<AssistantMessage["streamEndIgnored"]>["statement"]; /** * REF-B1 — turn a streamed tool call's accumulated argument bytes into its arguments object, FAIL-CLOSED. The ONE * judge of a streamed call's arguments: a call runs only with arguments that are a complete JSON object. * * - valid JSON **object** → that object (a complete `{}` included); * - no bytes (`""`) → `{}` when the wire closed the call — the provider's frame carried no arguments, a no-argument * call; `undefined` when it did not — the stream stopped before the call's first argument byte arrived, and nothing * says it was a no-argument call rather than a cut one; * - anything else (truncated/invalid JSON, or a top-level string/array/number/null) → `undefined`. * * `closed` is the lane's evidence that the wire ended THIS call, with no default (a lane that does not state it does * not compile): the call's own close frame, or a stream end that says the model finished its turn (not the output-cap * stop, not no stop at all). Another call opening is no evidence — a gateway may open several calls before any * argument byte arrives. One reading in the three lanes; each lane states which of these it has. * * bug-hunt #6 (kept from finalize): a non-object must never reach `tool.execute` / the MCP wire. `undefined` * means "do not emit a `toolcall_end` for this call"; callers must NOT cache that outcome — finalize retries * the parse against the complete accumulation. */ export declare function parseStreamedToolArgs(json: string, closed: boolean): Record<string, unknown> | undefined; /** * The cause of a call slot that never received its NAME — the other component of a call, judged by the same evidence as * its arguments ({@link parseStreamedToolArgs}'s `closed`): a slot the wire closed has no name because none was sent * (`unnamed`); a slot nothing closed was cut before its name arrived (`truncated`). A call is whole only with both parts; * a missing part on an unclosed call is a cut call, whichever part is missing. */ export declare function nameMissingCause(closed: boolean): "unnamed" | "truncated"; /** One drop note of a turn: what was dropped, how many, and the sentence the model reads. */ export interface TurnNote { readonly cause: StreamDropCause; readonly count: number; readonly text: string; } /** * Place a turn's engine notes in its final content: AHEAD of the first tool call, in order, or at the end of a turn * that has none. Every dropped call (cut arguments, no tool name) and dropped stream frames are stated so the model * re-issues them — also when text survived and no call did; a partial batch still executes its valid calls. No block * may follow the calls: the Anthropic Messages API rejects a `tool_use` followed by anything but another `tool_use`. * The same notes are stamped on the turn's message as its stream drops (`stampStreamDrops`, with the turn's facts — * `turn`), the run's source for the person's line (`task.tool_turn_incomplete`): the model's sentence and the person's * line come from one list. One rule for the three lanes. */ export declare function placeTurnNotes(message: Pick<AssistantMessage, "diagnostics">, content: AssistantMessage["content"], notes: readonly TurnNote[], turn: StreamDropTurn): void; /** * How a turn that dropped tool calls (cut arguments, no tool name) ends when none of its calls survived, whatever else it * carries: a turn that lost its calls never ends as a clean success. When the caller will ask the model again * (`StreamOptions.reissueDroppedCalls`, the loop while its malformed-tool-use retry has a re-ask left) it is a `toolUse` * stop that carries no call — the model ended the turn to call tools, and that retry asks again on it (the drop notes, in * the content, name what to re-issue). Otherwise it fails (`modelOutputInvalid`): a direct call, a loop with no such * retry, and the loop at its cap all get the failure. `undefined`: no call was dropped, or one survived — the lane's own * stop reading stands. One reading for the three lanes. */ export declare function droppedCallsEnding(turn: { dropped: boolean; survivingCalls: number; }, options: { readonly reissueDroppedCalls?: boolean; } | undefined): "toolUse" | "failed" | undefined; /** The request's whole input as a turn's usage states it — the context the request presented, cached parts included, on * every wire's reading (`totalTokens` is input + output there, the cached parts counted in whichever side holds them) — * or `undefined` when the counts do not state one. */ export declare function requestInputTokensOf(usage: { readonly totalTokens?: unknown; readonly output?: unknown; } | undefined): number | undefined; /** * The cause clause of a dropped call's "not valid JSON" message. The output cap is named only when the stream says * the cap cut it — the lane's own cap stop, or a counted output at or over the cap on the wire; a stream that ended * without its stop frame names the transport instead; any other stop adds nothing (naming the cap there sent a reader * after a budget that was never reached). The model's declared window is named only when the numbers show the request * could not fit in it — the reported input plus the request's output cap over it — and then as those numbers, no more. * One rule for the lanes that carry the clause. */ export declare function truncationCauseClause(facts: TurnCapFacts & { terminalFrameSeen: boolean; inputTokens: number | undefined; contextWindow: number | undefined; }): string; /** One turn's output-cap facts as the lane holds them — the record {@link truncationCauseClause} words and * {@link modelOutputInvalidOf} carries: the lane's cap stop, the provider's output count (as reported), the cap the * committed request carried. */ export interface TurnCapFacts { capStop: boolean; outputTokens: number | undefined; capTokens: number | undefined; } /** * The door's reading of a stream frame's members, one reading for every lane's frame decoder: a member the * lane reads is taken only in the shape the wire defines — an object (non-null, non-array), an array, a string (`word`), * a count. `null` and absent state nothing (`undefined`, not recorded) — a member and an array's entry alike: `null` holds no * bytes. Any other value is a member in no shape: it reads * as `undefined` — never coerced, never dereferenced — and the reader records it (`outOfShape`), so the lane says the loss * where that member's loss is already said. A lane keeps one reader per outlet (the frame, the call stream, the usage), so * one outlet's record never speaks for another's. */ export interface MemberReader { object(v: unknown): Record<string, unknown> | undefined; array(v: unknown): readonly unknown[] | undefined; word(v: unknown): string | undefined; count(v: unknown): number | undefined; /** * A member whose own law lives in a reading elsewhere (the reasoning count: `reasoningTokensOf`): absent and `null` state * nothing (`undefined`); anything else is a STATEMENT and is handed on as it came — in no count shape included, so that reading * can tell "said nothing" from "said something it cannot read". A statement in no count shape is recorded (`outOfShape`) as * `count` records one. */ claim(v: unknown): unknown; /** * {@link claim} of `container[key]`. A container in no object shape may have held the member: it states something in no count * shape (a value that is no count whatever the container was — `5` would otherwise read as a count), recorded — not an absence. */ claimIn(container: unknown, key: string): unknown; /** Did a member this reader read hold a value in no shape? */ readonly outOfShape: boolean; } /** * The one rule for a response's tool calls when its stream held bytes the engine could not place — for every lane that keeps * one; each lane only decodes (what a slot is, what closes it, where a frame's bytes belong) and reports the fact here. * * 1. Before the stream's first ending statement, a frame holding content the lane could not read (no JSON, a top level in no * object shape, a call-stream member in no shape — {@link MemberReader}) or call bytes with no place to go (for a call * already sealed — a new start on it included —, for a slot never opened, for a block of another kind, a slot that never * became a call by the end) leaves where those bytes belonged unknown: no call of the response that was not sealed before * it runs — a call opened after it included. A frame that is null says nothing and is not a loss; any other non-object * frame is. Each withheld call is a call not received in full (`truncated`), beside the frame's `bad_frame` (or the * slot's `unnamed`). * 2. A call is sealed when the wire closed it (the lane's own close frame for that call; the OpenAI shape has no such frame and * seals on its early close: a higher slot opened while this one held a whole object, its `toolcall_end` emitted), or when * the stream's first ending statement arrived: the bytes held then are all of it. After that ending a frame is counted on * the stream-end ledger ({@link createStreamEndLedger}), never held against a call. * * A lane caches a call's close only while nothing was lost, so "sealed before the loss" is "its close is cached". */ export interface CallLoss { /** A frame before the ending held what the lane could not read, or call bytes with no place to go. */ lose(): void; /** Did one arrive? Once true it stays true: the lane seals no call after it. */ readonly lost: boolean; /** Is a call withheld: a loss arrived and the call was not sealed before it (`sealed` — its close is cached)? */ withholds(sealed: boolean): boolean; } export declare function createCallLoss(): CallLoss; /** A `data:` payload that carries no content: nothing, or the OpenAI-shape end sentinel `[DONE]` (no lane reads a statement * from it — each lane's ending is its own frame). A lane that asks here reads it as no frame: not read, not counted, never * held against a call. */ export declare function carriesNoContent(data: string): boolean; /** The dropped-calls sentence for the calls {@link CallLoss} withholds — their bytes may well be a whole object, so the cut-call * sentence ("not valid JSON") would say what is not so. `ending` = the lane's ending label (`finish_reason="…"`). */ export declare function withheldCallsClause(ending: string, calls: readonly string[]): string; export declare function memberReader(): MemberReader; /** The word a seat reads when something arrived there in no word shape — the echo seat's placeholder: an ending in no * word, a late frame the door could not read. */ export declare const NO_WORD = "?"; /** The stream's ending seat as both wires read it (`finish_reason`, `stop_reason`), before AND after the end, by one rule: * a falsy value states no ending (as it always read); a string is the provider's word; any other value (a number, `true`, * an object) is an ending in no word the engine reads — {@link NO_WORD}. */ export declare function endingWordOf(raw: unknown): string | null; /** Did the ending seat hold a non-word ({@link endingWordOf}'s third answer) — not a provider that spelled `?`? */ export declare function endingInNoWord(raw: unknown): boolean; /** The one sentence a turn's dropped frames are stated in (the `bad_frame` note), for the three lanes: `data:` frames that * were not valid JSON, or that held members in no shape the stream defines ({@link MemberReader}) — counted together, the * first one's bytes as the sample. */ export declare function droppedFramesNote(count: number, sample: string | undefined): string; /** * The structured account of a turn that FAILED for its dropped tool calls (`AssistantMessage.modelOutputInvalid`) — * the lane calls it on the arm whose message is the dropped-calls sentence. `cause` is `truncated` when any call was not * received in full (its arguments cut, or the call withheld at a {@link CallLoss}), else `unnamed`; `outputLimit` rides with `truncated`, read off the * same {@link TurnCapFacts} the sentence's cap clause reads. One rule for the three lanes. */ export declare function modelOutputInvalidOf(drops: { truncated: number; unnamed: number; }, cap: TurnCapFacts): ModelOutputInvalid | undefined; /** Repetition telemetry for ONE stream — the cut event plus the allowance-spared hits. */ export interface RepetitionPoll { /** Inspect the accumulated text; returns whether it is degenerate (the caller trips its own cut). */ poll(text: string): boolean; /** The cut event, once a poll tripped. */ readonly cut: RepetitionEvent | undefined; /** Allowance-spared hits, deduped by rule+segment with the loop's PEAK depth kept. */ readonly spared: RepetitionEvent[]; } /** * Repetition telemetry (2026-07-10): the cut event + allowance-spared hits for THIS stream. * Polls re-inspect the same growing text every ~64 chars — dedupe spared by rule+segment so one * boot block doesn't log once per poll. Attached to the final message as `repetition`. */ export declare function createRepetitionPoll(): RepetitionPoll; /** Record the provider's OWN name for the model that answered, on the shared partial (hence on the final * message every lane spreads `...partial` into) — ONE rule for the three lanes' spellings (`chunk.model` / * `message_start.message.model` / `response.model`), WRITE twin of `providerReportedModel` * (`core/message-utils.ts`). The LAST frame that NAMES a model decides and the seat carries it only when it * differs; naming nothing (no name, or the empty string — {@link providerEchoReading}) is not an update, naming the * REQUESTED id RETRACTS an earlier substitution. A name outside {@link isProviderEchoShape}, or one the stream's mint * (`providerWords`) would not leave as it is — it holds what the request was declared with, or a credential shape — is * dropped, never rewritten — not an update — and counted once per response (`echo_dropped`, `field: "responseModel"`). */ export declare function noteResponseModel(partial: { responseModel?: string; }, reported: unknown, requestedId: string, providerWords: (words: string) => string): void; export {};