@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,036 lines • 82.4 kB
TypeScript
import type { AgentTool } from "../internal/harness-types.js";
import { type EngineNotice } from "./types.js";
import { type IdentityReadVerdict, type OwnerIdentity } from "./owner-identity.js";
import { type IdentityRekeyInput, type IdentityRekeyMap, type IdentityRekeyPlan, type RekeyDone } from "./identity-rekey.js";
import { type RetentionDeclaration } from "./retention.js";
import { type KeptBytes, type ToolResultBytesKeeper, type ToolResultBytesSeat } from "./tool-result-bytes.js";
/**
* Pluggable backing store for **offloaded large tool results** (design/30). When a tool returns more
* text than the threshold, the full content is moved here and the conversation keeps only a preview +
* a `ref`; the model fetches the rest via the injected `read_tool_result` tool. This is the local,
* provider-agnostic equivalent of CC's `toolResultStorage` (no Anthropic `cache_edits` dependency).
*
* Default is {@link InMemoryToolResultStore} (task-scoped, lives only for the run). Inject a durable
* implementation (TiDB/blob, keyed by the opaque `ref`) so an offloaded result survives wake/resume;
* with the in-memory default, a fetch after a cross-process wake returns undefined and the model is told
* the output is no longer available — the preview still stands in context, so it degrades, never crashes.
*/
export interface ToolResultStore {
/**
* Managed-retention declaration (retention.ts): `"managed"` says this store's rows are deleted on
* schedule by the deployment (a `ManagedRetentionCapability` executor — scheduled, tenant-scoped,
* audited deletion — runs over them); `"none"` (or ABSENT — read fail-closed as `"none"`) says
* nothing deletes them on schedule. The party that runs the sweep states it when it constructs the
* store. A deployment with a LOCKED retention policy refuses to start over a `"none"` store.
* Declaration, never duck-typing.
*/
readonly retention?: RetentionDeclaration;
/**
* Persist full content under a stable `ref`. **Write-once and idempotent**: if `ref` already exists,
* keep the existing content and do nothing (the aggregate budget re-runs every query with the same
* deterministic ref, so `put` for an already-stored ref MUST be a no-op — re-writing would risk a
* non-identical preview and break the prompt cache). A durable backend treats `ref` as the primary key
* and should validate/sanitize it (it is composed from sessionId+toolCallId, not raw model input, but a
* durable store still owns key hygiene for its storage layer). The floor of that hygiene is
* NOT per-backend — every implementation rejects the unsafe ref set via {@link assertSafeToolResultRef}
* (a volatile backend silently accepting what a durable one rejects is the drift this closes).
*
* `provenance` (backlog #119, 2026-08-10) states WHO the stored bytes belong to, so a host-side read
* face can authorize a fetch without parsing the ref. Its rules, uniform on every backend:
* - **the write-once election decides the owner too** — whoever wins the race to store the content
* is the owner, and no later writer can change that. A backend that publishes content and owner
* as two objects (the file one does) may, if it is interrupted between them, leave an entry
* content-complete and UNOWNED; that is the fail-closed direction (a read face refuses it) and it
* is never mis-attribution, but it does mean "unowned" is a reachable state, not only a
* pre-provenance one. A single-row backend (memory/SQL) has no such window;
* - a later `put` on the same ref carrying the **same** provenance (or none) is the usual idempotent
* no-op — the stored owner is neither re-written nor erased;
* - a later `put` carrying a **different** provenance is a typed refusal
* ({@link ToolResultRefConflictError}, `code: "tool_result.ref_conflict"`), never a silent no-op:
* `ref` is the storage PRIMARY KEY, and with a host-supplied `sessionId` two distinct owners can
* land on one ref — under a silent write-once the second owner would read back the first owner's
* bytes, which is an identity fault, not a caching detail;
* - provenance must never be FINER-GRAINED than the ref's own key. A ref keyed on
* (session, tool call) is legitimately written by two different tasks of one session — the
* Runner shares one store across its tasks on purpose, and a BYOM brain may mint the same
* tool-call id in both — so stamping a `taskId` there would turn a designed sharing case into a
* refusal. Every engine write site therefore states the session only (#167) — including the
* background-agent and monitor spills, whose ref DOES carry the registry handle id: that id is
* an addressing segment of the ref, not an ownership coordinate a read-face caller can present
* (see {@link ToolResultProvenance.taskId} for the namespace rule);
* - an entry stored **without** provenance (written by an older engine, or by a call site that has
* none) stays UNOWNED: `put` never back-fills an owner onto it (that would be adoption by a party
* that cannot prove it wrote it) and {@link ownerOf} keeps answering `undefined`, which a read face
* reads fail-closed. Back-filling such rows is an explicit migration, never a side effect of a write.
*/
put(ref: string, content: string, provenance?: ToolResultProvenance): Promise<void> | void;
/** Read a slice of the stored content. Unknown `ref` → undefined. */
get(ref: string, opts?: {
offset?: number;
limit?: number;
}): Promise<ToolResultSlice | undefined> | ToolResultSlice | undefined;
/**
* Backlog #119 — the READ-side half of provenance: who owns `ref`. `undefined` for an unknown ref AND
* for a stored-but-unowned one (a row whose write stated no owner), which a read face treats identically:
* fail-closed, nobody is authorized. Without this operation a `put`-only provenance parameter would be
* write-only bookkeeping — the read face would still have nothing to decide on.
*
* **The engine's own read faces authorize on it.** `ReadToolResult` and `SaveToolResult` read a ref through the run's
* {@link LegToolResultView}, which asks this first and answers the ref only when the recorded owner is the reading run's
* identity ({@link identityReadVerdict}: the same principal and the same isolation scope). So the answer must carry every
* member the write recorded — `principal` (a `null` included: it is the anonymous identity, not "none") and `isolationScope`
* — exactly as stored: a store that drops them answers an owner no run can read.
*
* Typed OPTIONAL so an implementation compiled against an older engine still satisfies the interface;
* the published contract kit (`toolResultStoreContract`) nevertheless REQUIRES it, and a store without it backs no read:
* every ref it holds reads as absent to the engine's read faces.
*/
ownerOf?(ref: string): Promise<ToolResultProvenance | undefined> | ToolResultProvenance | undefined;
/**
* Erase every entry this store recorded as belonging to `sessionId` — the DELETE half of the same
* ownership coordinate {@link ownerOf} answers on. Without it a durable backend keeps a deleted
* session's offloaded and spilled results on its media indefinitely: `put`/`get` alone give a
* deployment no way to complete a session deletion, and the engine ships no scheduler that would
* eventually collect them.
*
* Rules every implementation follows:
* - **selection is by RECORDED PROVENANCE, never by parsing the ref.** A ref is an opaque handle:
* its session segment may be folded ({@link buildToolResultRef}), refs minted before the
* injective form decompose two ways (`tr_team_blue_x` is both ("team","blue_x") and
* ("team_blue","x")), and a caller may mint its own. Prefix-matching a ref therefore both
* misses rows and reaches rows of a NEIGHBOURING session, and over-deletion here destroys a
* live session's readable bytes. The owner recorded at the winning write is the one coordinate
* that means exactly one thing, and it is the same one a read face authorizes against;
* - **`taskId` is ignored in the match.** A stored `{sessionId, taskId}` is a NARROWING of the
* same session, not a different owner — write sites stamped one before the namespace rule
* settled the shape (#167), and such rows still belong to the session being deleted;
* - **an UNOWNED entry is never deleted.** A row whose write stated no provenance (an older
* engine, a call site that has none, or a two-object backend interrupted between publishing
* content and owner) belongs to no session this sweep can name, and it is still READABLE via
* `get` — deleting it on a guess would destroy another session's output. It is counted instead
* ({@link ToolResultDeletionReport.unattributable}) so the caller learns the deletion was
* incomplete rather than being told a clean "done";
* - **idempotent**: deleting a session with no entries is a no-op, and a repeat call after a
* partial (loudly failed) sweep resumes it;
* - **concurrency-tolerant**: an entry that disappears between enumeration and removal is honest
* absence, not an error.
*
* Typed OPTIONAL, and an OPTIONAL leg of the published contract kit (`toolResultStoreContract`,
* its #196 case): unlike `ownerOf`, a backend that cannot enumerate by owner is still a usable
* offload store, so absence is never a contract breach — the kit verifies the four-state
* semantics when the member is present and reports absence through its `onOptionalMember`
* callback (a checkable fact, not a failure). Present ⇒ the store can complete a session
* deletion; absent ⇒ the deployment owns that gap.
*
* Implementing it does NOT make a store `retention: "managed"` — that declaration says the
* deployment deletes this store's rows on schedule through a whole
* {@link import("./retention.js").ManagedRetentionCapability} executor (domain enumeration, tombstones,
* audit receipts, scheduled execution), of which this is one caller-driven erase.
*/
deleteBySession?(sessionId: string): Promise<ToolResultDeletionReport> | ToolResultDeletionReport;
/**
* Age out the entries stored more than `opts.maxAgeMs` before `now` (epoch ms): the age bound a deployment states for
* offloaded results, read the same way by every backend — a SQL backend's sweep leg reads the same bound. An entry's
* age is the time its winning write stored it; the content and its owner record go together. Answers how many
* entries it removed.
*
* Rules every implementation follows:
* - **no bound, no deletion**: `opts` or `opts.maxAgeMs` absent ⇒ nothing is removed — the default keeps every
* entry, as a transcript is kept;
* - **a bound that cannot be evaluated is refused** before any entry is touched (`config.retention_policy_invalid`:
* a `maxAgeMs` that is not a finite number of milliseconds of 0 or more, a `now` that is not a finite number) —
* never read as "no bound";
* - **age only**: ownership is not consulted, and an entry still reachable from a transcript is removed when it
* is old enough — the model's read of it then says it may have expired (the honest degradation the read
* already has);
* - **idempotent**, and an entry that disappears between enumeration and removal is honest absence.
*
* Optional: absent ⇒ this store keeps entries until their session is deleted. An OPTIONAL leg of the contract kit
* (`toolResultStoreContract`), reported through its `onOptionalMember` callback.
*/
reap?(now: number, opts?: {
maxAgeMs?: number;
}): Promise<number> | number;
/**
* Delete the entries stored with NO owner record that were stored before `cutoffMs` (epoch ms) — the orphan-tool-results domain's
* leg ({@link import("./retention.js").RETENTION_CASCADE}). No session can claim such an entry (written without provenance, or a
* winning write interrupted between its content and its owner record), so no session deletion ever reaches it; the cutoff is the
* one bound it has. Answers how many entries it removed.
*
* Rules every implementation follows:
* - **an owned entry is never this verb's**, however old — its session's deletion is its way out;
* - **an owner record that is present but unreadable is not "no owner"**: that entry is kept, because a guess would destroy
* another session's output (the same posture {@link deleteBySession} counts as `unattributable`);
* - **the bound is the call's**: a `cutoffMs` that is not a finite number is refused (`config.retention_policy_invalid`)
* before any entry is touched; no policy object is read;
* - whether a transcript still points at an unowned entry is the caller's to judge (it holds the transcripts); this verb
* judges the store's own two facts, the owner record and the write time;
* - **idempotent**, and an entry that disappears between enumeration and removal is honest absence.
*
* Optional: absent ⇒ unowned entries leave only through {@link reap}'s age bound, which does not consult ownership. A store
* that records no write time cannot age an entry and does not implement it (the in-memory store keeps none).
*/
deleteUnattributable?(cutoffMs: number): Promise<number> | number;
/**
* The READ half of the same ownership coordinate {@link deleteBySession} erases by: every entry this store recorded as belonging to
* `sessionId`, as the ref and the owner recorded at its winning write. Without it the offloaded results a session's transcript
* points at have no way out of a store, so a session moved to another store reads references it cannot dereference.
*
* The listing is the whole of the export: each listed ref is read the one way every reader reads a ref ({@link bytesOf}'s
* dispatch rule: text through {@link get}, bounded slices with `totalChars` saying how much; failing that, bytes through
* {@link bytesOf}) and lands in the other store through the matching write (`put` / `putBytes`, with `entry.provenance`) — that
* store's write-once election makes a repeated move an idempotent no-op and a ref that already belongs to a different owner a
* typed refusal ({@link ToolResultRefConflictError}). A destination with no byte arm cannot take a byte entry: the mover counts it
* and says so, and the transcript's ref to it reads as absent in the new store.
*
* Rules every implementation follows, the same selection as {@link deleteBySession}:
* - **selection is by RECORDED PROVENANCE, never by parsing the ref**; `taskId` is ignored in the match (the entry's
* `provenance` still carries the one that was recorded — it is the very owner the importing `put` states);
* - **an UNOWNED entry is never listed**: it belongs to no session this call can name. It is counted in
* {@link ToolResultSessionListing.unattributable} (store-wide, the same figure a sweep reports), so a caller learns the
* listing cannot speak for such rows rather than being told a clean "that is all";
* - an entry the session owns but whose ref the store cannot name — only an entry written before the store recorded the ref beside
* it — is counted in {@link ToolResultSessionListing.unaddressable}, never listed under a guessed ref;
* - the listing is a snapshot with no order promised; an entry that disappears before the caller reads it is honest absence
* (`get` answers `undefined`), and a listing of a session with no entries is empty, not an error.
*
* Typed OPTIONAL, and an OPTIONAL leg of the published contract kit (`toolResultStoreContract`): a store that cannot enumerate
* by owner is still a usable offload store, so absence is a checkable fact reported through `onOptionalMember`, never a
* contract breach. Implementing it does NOT make a store `retention: "managed"`.
*/
listBySession?(sessionId: string): Promise<ToolResultSessionListing> | ToolResultSessionListing;
/**
* The BYTE ARM's write: store binary content a tool result carried (bytes the model cannot receive as content) under `ref`, as an
* entry of this store like any other — the same owner record, the same age, the same sweeps. Its rules:
* - **one ref, one entry, of one kind**: the write-once election {@link put} runs decides bytes too, across kinds — a
* `putBytes` on a ref that holds text, or a `put` on a ref that holds bytes, is the typed refusal
* ({@link ToolResultRefConflictError}, with its `kinds`), never a second entry under one key; a repeat on a ref that holds
* bytes is the idempotent no-op under the owner rules {@link put} states;
* - **`provenance` is required**: an engine write always has its session, and a byte entry with no owner is reachable only by
* an interrupted write or a foreign writer — the orphan leg's ({@link deleteUnattributable});
* - `mediaType` (the claimed type, in the form a sentence may repeat) is stored with the entry and answered by {@link bytesOf};
* - **a store with this member implements {@link deleteBySession}**: bytes a session's tools produced must leave with the
* session; the contract kit refuses the one without the other;
* - **every sweep reads a byte entry as an entry**: {@link deleteBySession}, {@link reap}, {@link deleteUnattributable} and
* {@link listBySession} select, age and count it exactly as they do a text entry — its lifetime is the store's, not a second
* one;
* - **a store with a bound may refuse ONE piece that is, by itself, larger than it** — with {@link ToolResultBytesOverLimitError}
* (`code: "tool_result.bytes_over_limit"`, `limit` = the largest piece it takes, in bytes) and nothing stored, never by evicting
* what it holds to make room for it. The run's keep reads that refusal as `over_limit` with that bound; any other throw is
* `store_failed`. Either way the refusal's message is the store's words to the operator (`saveError` on the operator's
* account; never the model's line): a store names there what to raise;
* - **one result's pieces never displace each other**: `held` names the refs the caller kept earlier in the same result (the
* run's keep passes them, and they stay held only until that result is done). A store that makes room by evicting never
* evicts a held ref for this write: the room a piece has is the bound less what the held refs hold, and a piece over that
* room is refused as above, `limit` = the most bytes it could take beside them. A store that never evicts ignores it.
*
* Optional, and an OPTIONAL leg of the contract kit (`toolResultStoreContract`, reported through `onOptionalMember`): absent ⇒ the
* run keeps no binary tool results, and says so where the bytes would have been. Both bundled stores implement it.
*/
putBytes?(ref: string, bytes: Uint8Array, provenance: ToolResultProvenance, mediaType?: string, held?: readonly string[]): Promise<void> | void;
/**
* The BYTE ARM's read: the byte entry stored under `ref` — its length and stored media type, and its bytes on demand (a reader that
* describes an entry never has to load it) — or `undefined` when `ref` holds no bytes. Present exactly when {@link putBytes} is.
*
* **The one way a single ref is read**, by every reader (the reader tools, a host read face, a mover): at most one face answers,
* because the election above keeps one kind per ref — ask {@link get} first, and when it answers `undefined` ask `bytesOf`; both
* `undefined` = the ref is absent. A ref is never parsed for its kind (it stays opaque). The read face is lenient like `get`'s: a
* ref no write could store answers `undefined`, never a throw.
*/
bytesOf?(ref: string): Promise<ToolResultBytes | undefined> | ToolResultBytes | undefined;
/**
* The tool-result seat's identity re-key — REQUIRED: an entry records the identity of the run that stored it and a run reads only
* its own, so a person moved to another identity (an adoption, a merge of accounts) reads nothing they stored before unless the
* owner records move with them; a `put` cannot do it (another identity on an occupied ref is the typed refusal). A one-step seat
* ({@link import("./identity-rekey.js").ONE_STEP_REKEY_MODES}), the checkpoint seat's twin: the same input, read by `readIdentityRekeyInput` before anything
* else (a `TypeError`, nothing read), `plan` answering {@link IdentityRekeyPlan}, `leave` answering the entries it re-filed. Only
* a migration calls it; a run's view of the store does not carry it ({@link ToolResultSeat}).
*
* @contract tool_result.rekey_identity — `rekeyIdentity({ fromPrincipal, toPrincipal, scopes, mode })` re-files, in place (the
* ref is the key: no entry moves, its content and age are untouched), the identity of every entry whose owner record names one
* the mapping changes, by the one law {@link rekeyToolResultOwner} (`rekeyOwnerIdentity` over the record's identity members): the
* session and task it records stay. An entry with no owner record, or one that names no identity, is not this move's (nobody reads
* it; giving it an identity is adoption); an owner record the store cannot read at all is read as {@link ownerOf} reads it — no
* owner. An owner record whose identity members are not of their shape and that holds a value the mapping changes is left as it is
* and counted by `plan` as `conflicting`; `plan` counts as `unpairedScopeRows` the re-filed entries whose principal moves while
* no scope pair names their partition's value. Each entry is decided on its owner record as it stands at the write. `leave` answers the
* entries it re-filed; refs are unique, so no entry stands in another's way and there is no `conflict` answer; a `leave` cut
* short is completed by running it again (a re-filed record names no value the mapping changes).
*/
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "plan";
}): Promise<IdentityRekeyPlan>;
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "leave";
}): Promise<RekeyDone>;
}
/** What a run's writers and readers reach of a tool-result store: every member but the store owner's migration verb
* ({@link ToolResultStore.rekeyIdentity}). A run's view ({@link LegToolResultView}) and the Runner-shared default's per-task
* namespace ({@link ScopedToolResultStore}) are seats of this shape; a store a deployment injects is a whole {@link ToolResultStore}. */
export type ToolResultSeat = Omit<ToolResultStore, "rekeyIdentity">;
/** What {@link rekeyToolResultOwner} answers for one owner record. */
export type ToolResultRekeyVerdict =
/** The mapping changes no value the record names (or the record names no identity): not this move's. */
{
readonly kind: "untouched";
}
/** The owner record to write: the same session and task, the re-filed identity; `partitionLeft` as `rekeyOwnerIdentity` says. */
| {
readonly kind: "rekeyed";
readonly owner: ToolResultProvenance;
readonly partitionLeft: boolean;
}
/** Its identity members are not of their shape and one holds a value the mapping changes: left as it is, counted. */
| {
readonly kind: "unrekeyable";
};
/**
* THE tool-result seat's law of one owner record (every backend writes what it answers): the identity the record names, read as the
* read judge reads it ({@link recordedOwnerIdentityOf}), re-filed by the one identity law ({@link rekeyOwnerIdentity}); on `rekeyed` the
* record to write keeps the session and the task and carries the new identity in the canonical form. `undefined` (no owner record)
* and a record naming no identity are `untouched`; a record whose members are not of their shape is `unrekeyable` when a member, as a
* string, holds a value the mapping changes (a principal the principal pair moves, or a scope a scope pair moves), else `untouched`.
*/
export declare function rekeyToolResultOwner(owner: ToolResultProvenance | undefined, map: IdentityRekeyMap): ToolResultRekeyVerdict;
/** What {@link ToolResultStore.bytesOf} answers for a byte entry. */
export interface ToolResultBytes {
/** The entry's length in bytes. */
readonly byteLength: number;
/** The media type stored with the entry, when its write stated one. */
readonly mediaType?: string;
/** The entry's bytes, read when asked. */
bytes(): Promise<Uint8Array> | Uint8Array;
}
/** The two kinds of content an entry holds: text ({@link ToolResultStore.put} / `get`) or bytes (`putBytes` / `bytesOf`). */
export type ToolResultEntryKind = "text" | "bytes";
/** One entry a {@link ToolResultStore.listBySession} listing names: the ref and the owner recorded at its winning write — the two
* arguments an importing store's `put` takes beside the content `get` returns. */
export interface ToolResultListedEntry {
readonly ref: string;
readonly provenance: ToolResultProvenance;
}
/** What a {@link ToolResultStore.listBySession} call answers. */
export interface ToolResultSessionListing {
/** The session's entries, in no particular order. */
readonly entries: readonly ToolResultListedEntry[];
/** Entries the store could not attribute to ANY session (stored without provenance, or with an unreadable owner record) and so did
* not list: store-wide, the same figure {@link ToolResultDeletionReport.unattributable} reports. */
readonly unattributable: number;
/** Entries the session owns whose ref this store cannot name, so they are not listed. It counts ONE thing only — entries written
* before the store recorded the ref beside the entry (a file backend's folded file name is a digest of the ref, and the owner record
* it writes now carries the ref; records written by earlier versions do not). It is not a second kind of entry: a store whose
* entries were all written by a version that records the ref reports `0`, always. Such an entry is still removed by
* {@link ToolResultStore.deleteBySession}, so `entries.length + unaddressable` is the number a sweep of the session then deletes. */
readonly unaddressable: number;
}
/**
* What a {@link ToolResultStore.deleteBySession} sweep actually did. A count, not a `void`, because the
* sweep has a documented INCOMPLETE outcome (unowned entries it must not delete) and a caller running a
* session-deletion face has to be able to tell "the session's results are gone" from "some rows survive
* that no session can clear".
*/
export interface ToolResultDeletionReport {
/** Entries removed by THIS call. A retry of an already-swept session reports `0`, not an error. */
readonly deleted: number;
/**
* Entries the sweep could not attribute to ANY session and therefore left in place: stored without
* provenance, or with an owner record that is present but unreadable. Store-wide, not
* session-specific — an unowned row may or may not have been this session's, which is precisely why
* it cannot be deleted — so the same figure recurs on every session's sweep until a migration or an
* operator clears those rows.
*/
readonly unattributable: number;
}
/**
* Backlog #119 — WHO a stored tool result belongs to. Structured (not a single opaque string) because
* the read face authorizes by COMPARING fields it already knows; `taskId` is present when the write site
* has one (it is a narrowing of the session, never a substitute for it).
*
* A stamped `taskId` must name a coordinate the read face's CALLER presents —
* the host's own task/run id — never an engine-internal registry handle id. A handle id lives in a
* namespace only the engine's in-memory registry can resolve, so an owner stamped with one compares
* unequal to every caller coordinate forever: the entry becomes readable by NOBODY across the wire
* (fail-closed, but pointlessly — the disclosure text tells the caller to read it back). The engine's
* own write sites all state the session only; the handle id, where a ref needs it, is an ADDRESSING
* segment of the ref, not part of the owner.
*
* Deliberately NOT part of it: `toolCallId`. It is a retention/addressing coordinate, not an ownership
* one — two different tool calls in one session are the same owner.
*
* Two coordinates answer two questions. `sessionId` (and `taskId`) say WHICH SESSION's results these are: a session's
* deletion, listing and move select on it. `principal` and `isolationScope` say WHOSE they are — the identity of the run that
* stored them ({@link OwnerIdentity}) — and that is what a read authorizes on ({@link identityReadVerdict}): a session id
* is not an identity (another person's run may hold it, a fork of it is another session of the same person's work).
*/
export interface ToolResultProvenance {
readonly sessionId: string;
readonly taskId?: string;
/** The storing run's principal ({@link OwnerIdentity.principal}): a name, or `null` for a run that names none. ABSENT on an
* entry written without an identity (an engine before this member existed, or a writer that states none) — no run can read
* such an entry, because no identity is recorded to match. */
readonly principal?: string | null;
/** The storing run's isolation scope when it is not its principal ({@link OwnerIdentity.isolationScope}). */
readonly isolationScope?: string;
}
/** Backlog #119 — the `code` on {@link ToolResultRefConflictError}, so callers branch on a constant. */
export declare const TOOL_RESULT_REF_CONFLICT_CODE = "tool_result.ref_conflict";
/**
* Backlog #119 — a write the occupied ref cannot take: its provenance disagrees with the stored one, or (`kinds` present) it
* offers the other kind of content than the entry holds (one ref, one entry — {@link ToolResultStore.putBytes}). Typed (a `code`,
* like `CheckpointError`/`WorkflowRunStoreError`) rather than a silent no-op: these are the write-once outcomes where "keep what
* is there" would hand the second caller a reference to something other than what it stored. `stored` / `incoming` are the two
* owners — always both present for an owner conflict; for a kind conflict, whichever side recorded one.
*/
export declare class ToolResultRefConflictError extends Error {
readonly ref: string;
readonly stored: ToolResultProvenance | undefined;
readonly incoming: ToolResultProvenance | undefined;
readonly kinds?: {
readonly stored: ToolResultEntryKind;
readonly incoming: ToolResultEntryKind;
} | undefined;
readonly code = "tool_result.ref_conflict";
constructor(ref: string, stored: ToolResultProvenance | undefined, incoming: ToolResultProvenance | undefined, kinds?: {
readonly stored: ToolResultEntryKind;
readonly incoming: ToolResultEntryKind;
} | undefined);
}
/** The code of {@link ToolResultBytesOverLimitError}. */
export declare const TOOL_RESULT_BYTES_OVER_LIMIT_CODE = "tool_result.bytes_over_limit";
/**
* A store's refusal of ONE byte entry that is, by itself, larger than the store's bound ({@link ToolResultStore.putBytes}): nothing
* is stored and nothing the store holds is evicted for it. `limit` is the largest piece the store takes, in bytes. The run's keep
* reads it as `over_limit` with that bound (`keepToolResultBytes`); a store refuses this way, with this code, or not at all. The
* message is what the operator's account carries as the store's words (`saveError`): this class says the bound; a store that has
* more to say — which bound to raise — words its own refusal (the `code` and `limit` members are what make it this one).
*/
export declare class ToolResultBytesOverLimitError extends Error {
readonly ref: string;
readonly bytes: number;
readonly limit: number;
readonly code = "tool_result.bytes_over_limit";
constructor(ref: string, bytes: number, limit: number);
}
/**
* Backlog #119 — the ONE comparison every backend uses, so "same owner" cannot mean two things in two
* stores. A missing PROVENANCE on either side ⇒ no verdict (an unowned entry is never adopted, and a
* put with no provenance never disturbs a stored owner). Both present ⇒ every field must agree,
* including `taskId` and the identity (`principal`, `isolationScope`): a missing member is a DIFFERENT owner from a stated one,
* not a wildcard that matches it — two writers that disagree about how narrowly they own a key have not proven they are
* the same writer, and an entry stored without an identity is never adopted by a write that states one. Unequal ⇒
* {@link ToolResultRefConflictError}.
*/
export declare function assertToolResultProvenanceMatch(ref: string, stored: ToolResultProvenance | undefined, incoming: ToolResultProvenance | undefined): void;
/** Normalize to the stored shape: an ABSENT member and an explicit `undefined` one are one value, so round-tripping through a
* durable backend (NULL column, missing JSON key) compares equal. `principal: null` is a value (the anonymous identity) and is
* kept. */
export declare function normalizeToolResultProvenance(p: ToolResultProvenance): ToolResultProvenance;
/**
* The ref-safety half of the {@link ToolResultStore} contract, shared by every backend.
*
* Why it is central and not per-backend: the file backend has always rejected these refs (its path
* component guard, `stores/file/fs-atomic.ts:48`), while the in-memory backend accepted them
* silently — the SAME ref stored fine in dev and threw in a durable deployment. That is the
* "backend outside the shared contract drifts on its own" mechanism (same family as RB-86/MB1 on
* MailboxStore), and the honest direction is the strict one: a ref that no durable backend can key
* is a defect at the WRITE, not something a volatile backend should quietly absorb.
*
* The rejected set is deliberately the intersection-unsafe one — empty / `.` / `..` / path
* separators / control characters — i.e. refs that are unusable as a key ANYWHERE (they traverse in
* a path-backed store and are ambiguous in every other). Backends may still be stricter about their
* own storage layer (the file backend additionally enforces a filename charset); that extra
* strictness is a backend capability, not part of this contract.
*
* Read face stays lenient by design: `get` with such a ref returns `undefined` (an unknown ref), it
* does NOT throw — the model is told the output is gone and the run degrades instead of crashing.
*
* RB-273 amends one clause of the above: a backend may be stricter about its own STORAGE LAYER, but not
* about which refs it accepts. A ref this function accepts must round-trip on every backend — a backend
* whose native key space is narrower (the file one's filename charset) owns an injective ENCODING into
* that space, not a rejection. Otherwise the same "dev green / deployment red" split this rule closed
* for `..` simply reappears one charset over (it did: a `:` in a provider-minted toolCallId).
*
* A ref is a STRING. Any other value (a boxed string, an array, a number, a record) is refused here, at the contract's own door, by
* its kind and unread: every backend keys on the ref as given, and one that was handed a value whose spelling differs by read, or that
* a backend's encoding turns into a string of its own, would store under a name the caller's string does not have. The refusal is the
* sentence an unsafe string gets (a plain `Error` with no code, whatever the value).
*/
export declare function assertSafeToolResultRef(ref: string): void;
/**
* The rule of {@link assertSafeToolResultRef}, asked instead of thrown: the sentence it refuses `ref` with, or `undefined` for a ref it
* accepts. A reader that has to tell "this ref is refused" from "something else failed" — the file backend's lenient `get` answers
* `undefined` for the first and lets the second be seen — asks this before it builds a path, so no reader needs the first words of a
* thrown sentence. The throwing door is built on this, so the rule and its sentence have one author.
*/
export declare function toolResultRefRefusal(ref: unknown): string | undefined;
/**
* The SINGLE mint point for a tool-result `ref`. Three call sites compose the same
* `tr_<sessionId>~<toolCallId>` string (`withToolResultOffload` here, the aggregate budget's preview
* pass, and the runner's clear-with-offload persist); this is that string's one definition.
*
* Why it must sanitize: `sessionId` is engine-minted, but **`toolCallId` is PROVIDER-minted** — it is
* whatever the model gateway put in the tool-call frame, not something core controls. Providers ship
* ids with `:` in them, and nothing stops one shipping a `/`. Composed raw, that produced two distinct
* failures, both far from their cause:
* - `/` or a control char ⇒ the ref violates {@link assertSafeToolResultRef} ⇒ `put` THROWS at mint,
* i.e. an offload (a context-economy optimization) turns a working tool call into a failed one;
* - `:` ⇒ accepted by memory/pg, rejected by the file backend's filename charset ⇒ the classic
* dev-green/deployment-red split (`probe-r5-store-parity-matrix`'s last two divergent cells).
*
* The mapping is IDENTITY for every id already in the native charset — which is all of them in practice
* (`toolu_…`, `call_…`, uuids) — so refs minted before this existed are byte-identical afterwards and
* the prompt-cache stability the preview rests on is untouched. Only an out-of-charset (or absurdly
* long) segment is folded, and then INJECTIVELY: readable base + a sha256 of the RAW segment, the same
* construction (and the same reason: two distinct ids must never collide onto one ref, which would
* cross-serve one tool's output as another's) as `sanitizeScope` in the file store.
*
* Read-back of refs minted BEFORE this change is unaffected in both directions: safe ids are unchanged,
* and an unsafe one only ever lived in a memory/pg deployment, where the ref the model reads back comes
* from the `<persisted-output ref="…">` text already in its context — the read path does not re-mint,
* and `get` is keyed on that literal string.
*
* ── Backlog #119 (2026-08-10): the composition is now INJECTIVE ───────────────────────────────────
* It was not. With `_` between the segments — a character legal INSIDE both — `tr_team_blue_x`
* decomposed as ("team","blue_x") and as ("team_blue","x"), i.e. two distinct (session, tool call)
* pairs minted one ref. `ref` is the store's PRIMARY KEY under a write-once contract, so the second
* pair did not get an error, it got the FIRST pair's bytes back — and `sessionId` is host-supplied in a
* BYOM deployment, so the two pairs need not be the same tenant. (Measured on the published artifact:
* ("s","1_a_b") and ("s_1","a_b") produced the same ref.)
*
* The separator is now {@link REF_SEGMENT_SEPARATOR} — a character OUTSIDE {@link NATIVE_REF_CHARSET}.
* `refSegment` emits only characters from that charset (identity branch by test; fold branch by
* construction: a readable base with every out-of-charset char replaced, plus hex), so the separator
* can never occur inside a segment and `tr_<seg>~<seg>` decomposes exactly one way. Injectivity of the
* whole map then follows from `refSegment`'s own injectivity per segment.
*
* Why this is NOT a breaking change, spelled out because it looks like one:
* - refs are OPAQUE HANDLES. A ref reaches the model inside the preview text and comes back verbatim
* to `ReadToolResult`; `get` is keyed on that literal string and no read path re-mints;
* - so an entry written under the old form stays readable forever: an old ref in an old context reads
* back byte-for-byte, on every backend (the file backend's filename encoding is likewise keyed on
* the literal ref, and is identity for the old form);
* - the mint is deterministic per process, so a ref MINTED here is also RESOLVED here — there is no
* window in which one process writes `~` and another expects `_` for the same pair. The upgrade
* boundary is a process restart, and it needs no double-read window;
* - the only observable change is the ref STRING for newly offloaded results, which no wire contract
* pins (it is generated text, and the length ceiling downstream validators apply is unchanged).
* The store-key charset is unchanged as far as the shared rule is concerned ({@link assertSafeToolResultRef}
* accepts `~`: it is not empty/dot/separator/control). A backend whose NATIVE key space excludes `~`
* (the file one's filename charset) already owns an injective encoding into it — the RB-273 rule — so
* for that backend this simply moves engine refs from the identity branch to the digest branch.
*
* `extraSegments` (also #119) is how a call site that addresses something FINER than one tool call —
* a `details` member's JSON path, a stale-projection content digest — keeps that coordinate in its own
* segment instead of splicing it into the `toolCallId` one. Splicing was the ticket's other residue:
* a ref built from the compound `"<callId> <path>"` is exactly the ref another call would mint if its
* provider-assigned toolCallId happened to BE that whole string. With the coordinate in its own
* segment the two can no longer coincide — the separator cannot occur inside a segment, so refs with
* different segment COUNTS are always distinct, and same-count refs are distinct unless every segment
* matches.
*/
export declare function buildToolResultRef(sessionId: string, toolCallId: string, ...extraSegments: string[]): string;
/** The task whose result `ref` holds, read off the segment {@link buildTaskArtifactRef} put it in — `undefined` for every other
* ref, which by construction is not a task's result (only that mint carries {@link TASK_ARTIFACT_SEGMENT}). An origin, never an
* owner: who may read the bytes is still {@link ToolResultStore.ownerOf}'s answer. A task id the mint had to fold comes back as
* its folded segment, which names no task — the reading of a task that is gone. */
export declare function taskArtifactOriginOf(ref: string): string | undefined;
/** Whether `ref` has the shape {@link buildTaskArtifactRef} writes — `tr_<session>~fold.task~<task>~<content>`, four segments, each
* one {@link isRefSegment} accepts — and nothing else: a string with a path separator, a control character, a quote, whitespace,
* an empty or over-long segment or a different segment count is not a ref the mint ever wrote. Shape only: it says nothing about
* whether the row is still held or who may read it ({@link ToolResultStore.ownerOf}), and {@link taskArtifactOriginOf} stays the
* lenient origin reading a read face's boundary legs rest on. */
export declare function isTaskArtifactRef(ref: string): boolean;
/**
* Backlog #119 — the ceiling on a ref this module can mint, so a durable backend can size its key
* column from a stated invariant instead of a guess (TiDB's was `VARCHAR(191)`, which a long
* three-segment ref overruns — a truncating key aliases distinct refs).
*
* Derivation: `"tr_"` (3) + four segments at their own ceiling + three separators. A segment is either
* an identity one (≤ {@link MAX_REF_SEGMENT_CHARS}) or a folded one (marker + ≤32 base + `-` + 64 hex
* = 102), so {@link MAX_REF_SEGMENT_CHARS} is the larger. Four segments is the engine's own widest
* shape (session + tool call + a `details` path + the content coordinate); `buildToolResultRef` is
* variadic, so a caller that passes more owns the wider bound.
*/
export declare const MAX_MINTED_TOOL_RESULT_REF_CHARS: number;
/**
* Backlog #119 (falsification review, round 2) — the CONTENT coordinate of an offload ref.
*
* A tool-call id carries no cross-turn uniqueness contract: a BYOM brain legitimately mints recurring
* ids like `call-1`, and the Runner shares one store across a session's tasks on purpose. Keyed on
* (session, tool call) alone, the second result under a recurring id hits a write-once no-op — a
* SUCCESSFUL put that stored nothing — while its own preview goes out naming that ref, so paging it
* back returns the FIRST result's bytes. Provenance cannot see this (both writers are the same
* session, and they legitimately are), so the ref itself has to carry content identity.
*
* 128 bits, the same width and the same reasoning as the stale-result projection that closed this in
* its own lane earlier: tool results are untrusted text (web content rides them), and a 48-bit
* truncation is birthday-collidable at ~2^24 work — a deliberate collision plus a recurring id would
* re-open exactly the cross-serving this closes. Deterministic, so a re-derived ref for identical
* content is byte-identical and the preview stays prompt-cache stable.
*/
export declare function toolResultContentSegment(text: string): string;
/**
* The content coordinate of a BYTE entry's ref ({@link ToolResultStore.putBytes}): `b` + 128 bits of a sha256 over the claimed
* media type (the form a sentence may repeat, `""` when none) and the bytes — the same width and the same reason as
* {@link toolResultContentSegment}, whose `s` it never shares, so a byte ref and any text ref the engine mints differ in their last
* segment by construction. The type is inside the digest because the entry stores one type: the same bytes claimed as two types are
* two entries, each answering its own. Distinct (type, bytes) ⇒ distinct refs rests on the same collision-resistance assumption as
* every digest here; identical ones are one entry, which the write-once election makes idempotent.
*/
export declare function toolResultBytesSegment(mediaType: string, bytes: Uint8Array): string;
export interface ToolResultSlice {
content: string;
/** Byte/char offset this slice starts at. */
offset: number;
/** Total chars of the full stored content. */
totalChars: number;
}
/** Default in-memory store (no cross-process durability); write-once per ref.
*
* Field-reported (`ReadToolResult(ref)` came back empty for a workflow child's
* offloaded output): the Runner now shares ONE instance across its tasks (instead of a per-task
* island), so a parent can deref a child's ref within the process. A shared long-lived instance
* needs a bound — `maxTotalChars` FIFO-evicts the oldest refs past the cap (an evicted deref lands
* on the existing honest "may have expired" text). Durability across restarts still requires a real
* store (e.g. FileToolResultStore) via `RunnerDeps.toolResultStore`.
*
* The byte arm ({@link ToolResultStore.putBytes} / `bytesOf`): a byte entry is held as the base64 characters of its bytes, in the
* same map and under the same bound — the bound counts the characters the store holds, whichever kind they spell — so a byte entry
* is evicted, swept, listed and counted toward emptiness (what a durable suspend is judged on) exactly as a text entry is. One
* piece whose characters alone are over the bound is refused ({@link ToolResultBytesOverLimitError}) rather than evicting
* everything else for it. */
export declare class InMemoryToolResultStore implements ToolResultStore {
/** Managed-retention declaration (retention.ts): whether this store's rows are deleted on schedule by the deployment — given by
* the party that runs the sweep (the `retention` option), `"none"` when none is given; the store itself is put/get only. */
readonly retention: RetentionDeclaration;
/** The entry is content AND owner as ONE value — the write-once election that decides the
* content decides the owner in the same step (no window where an entry exists ownerless). `bytes` marks a byte entry, whose
* `content` is the base64 of its bytes (with the media type its write stated); a text entry has none. */
private readonly map;
private totalChars;
/** @param opts.retention the store's managed-retention declaration, default `"none"`; a word other than the two is refused
* (`config.retention_capability`). */
/** The bound, read once at construction by the integer reading (`undefined` = unbounded): the one value the eviction enforces. */
private readonly maxTotalChars;
constructor(options?: {
maxTotalChars?: number;
retention?: RetentionDeclaration;
});
put(ref: string, content: string, provenance?: ToolResultProvenance): void;
/** The byte arm's write: the bytes held as their base64 characters, under the same election and the same bound as `put`. A piece
* whose characters are over its room — the bound less what the `held` refs (the same result's earlier pieces) hold — is refused
* ({@link ToolResultBytesOverLimitError}, `limit` = the most bytes whose base64 fits that room), and nothing is stored or evicted
* for it; a piece that fits evicts the oldest entries other than the held ones. */
putBytes(ref: string, bytes: Uint8Array, provenance: ToolResultProvenance, mediaType?: string, held?: readonly string[]): void;
/** The byte arm's read: the byte entry under `ref` — its length, stored type and bytes — or `undefined` (no entry, or a text one). */
bytesOf(ref: string): ToolResultBytes | undefined;
/** The write-once election over an occupied ref, both kinds: another kind is the typed refusal (one ref, one entry); the same kind
* under a DIFFERENT owner is the typed refusal too — a quiet no-op is what would later serve the first owner's content to the
* second one. `true` = the ref is occupied and the write is the idempotent no-op. */
private occupied;
/** Store a new entry and apply the one bound: the oldest entries go, first in first out, until the held characters are within it
* — never the just-written ref, nor one of `keep` (the same result's earlier pieces, which a byte write's room already left out). */
private admit;
/** The owner recorded at the winning write; `undefined` for unknown AND for unowned entries,
* which a read face treats identically (fail-closed). */
ownerOf(ref: string): ToolResultProvenance | undefined;
/** Erase this session's entries, selected on the owner recorded at the winning write (the interface
* states the rules). Implemented here as well as on the durable backends so the bundled pair does
* not answer the same operation two ways: the entry holds content and owner as ONE value, so the
* same provenance match applies with none of the file backend's two-object bookkeeping. Deleting
* from a Map while iterating it is defined (a removed key is simply not revisited). */
deleteBySession(sessionId: string): ToolResultDeletionReport;
/** This session's entries, selected on the owner recorded at the winning write — the very match {@link deleteBySession} runs (the
* interface states the rules). The ref is the map key, so every owned entry is nameable. */
listBySession(sessionId: string): ToolResultSessionListing;
/** The identity re-key (interface: {@link ToolResultStore.rekeyIdentity}): every owner record judged by the seat's one law and,
* on `leave`, re-filed in place in one synchronous stretch (the entry keeps its content, kind, place in the eviction order). */
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "plan";
}): Promise<IdentityRekeyPlan>;
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "leave";
}): Promise<RekeyDone>;
/** design/80 D-2: true when NOTHING has been offloaded — a durable suspend can then proceed safely even on
* this in-memory store, because a cross-replica resume has no offloaded result to deref to null. */
isEmpty(): boolean;
get(ref: string, opts?: {
offset?: number;
limit?: number;
}): ToolResultSlice | undefined;
}
/** Marker subclass for the Runner's own shared fallback instance (no injected store). prepare-task
* detects it and wraps a per-task {@link ScopedToolResultStore} around it (a storage namespace per trust scope); an INJECTED
* store is not namespaced. Who may read an entry is decided the same way over both — by {@link LegToolResultView}. */
export declare class RunnerSharedToolResultStore extends InMemoryToolResultStore {
}
/**
* Per-task view over the Runner-shared fallback (impl-review 2026-07-03):
* 1. **Tenant isolation**: refs are namespaced by the task's trust scope (principal), so tenant B's
* `ReadToolResult` can never deref tenant A's ref — the per-task-instance era made this isolation
* implicit; sharing one instance re-opened it. Same-scope cross-task deref (the A2 fix's whole
* point) still works: same scope ⇒ same namespace.
* 2. **D-2 durable-suspend gate fidelity**: `isEmpty()` reflects only THIS task's offloads (local put
* count) — matching the per-task-instance semantics the gate was written against — so an unrelated
* prior task's offloaded entry can no longer disable durable suspend for a task that offloaded
* nothing (prepare-task's fail-fast reads `isEmpty()`).
*/
export declare class ScopedToolResultStore implements ToolResultSeat {
private readonly inner;
private readonly scope;
private localPuts;
/** True when the underlying shared store is process-memory (volatile across replicas) — the D-2
* suspend gate treats a NON-empty volatile store as unsafe to durably suspend. */
readonly volatileBacking: boolean;
/** The byte arm, present exactly when the inner store's is: the same namespaced key as `put` / `get`, the provenance unchanged. A
* byte write counts toward THIS task's emptiness once the inner store took it (a refused piece stored nothing). */
readonly putBytes?: (ref: string, bytes: Uint8Array, provenance: ToolResultProvenance, mediaType?: string, held?: readonly string[]) => Promise<void> | void;
readonly bytesOf?: (ref: string) => Promise<ToolResultBytes | undefined> | ToolResultBytes | undefined;
constructor(inner: ToolResultSeat, scope: string);
/** Length-prefixed namespace — unambiguous for any scope string (no delimiter-injection ambiguity).
* The scope segment is ENCODED (injective, and its output charset carries no path separator
* or control character), so a deployment whose trust scope contains one cannot compose a key the
* inner store must reject — the ref-safety rule then applies to the caller's ref alone. */
private key;
put(ref: string, content: string, provenance?: ToolResultProvenance): Promise<void> | void;
get(ref: string, opts?: {
offset?: number;
limit?: number;
}): Promise<ToolResultSlice | undefined> | ToolResultSlice | undefined;
/** Same namespacing as {@link get}. `undefined` when the inner store predates the operation
* (an unowned answer, which the read face reads fail-closed — never a fabricated owner). */
ownerOf(ref: string): Promise<ToolResultProvenance | undefined> | ToolResultProvenance | undefined;
/** THIS task's offload count only — the D-2 gate's per-task semantics (see class doc). */
isEmpty(): boolean;
}
/** The store a leg's offload writes to and its read faces read from: the leg's {@link LegToolResultView} for `identity` over
* {@link legBackingStore}. */
export declare function legToolResultStore(injected: ToolResultSeat | undefined, scope: string, identity: OwnerIdentity, onRefused?: (refusal: ToolResultReadRefusal) => void): LegToolResultView;
/**
* One refused read of an entry the store holds — or of a ref whose owner the store failed to read, held or not — as
* {@link LegToolResultView} tells it (the operator's account; the model reads the miss sentence a ref that is not there reads).
* `reason` is the closed set:
* - `"other_identity"` — the entry records an identity that is not the reader's;
* - `"no_identity"` — the entry's owner record names no identity (stored before identities were recorded, or by a store that
* does not keep them);
* - `"unowned"` — the entry was stored without provenance;
* - `"owner_unreadable"` — the store answered something that is not an owner record of the contract's shape;
* - `"owner_read_failed"` — the store's `ownerOf` threw (`cause`: what it threw) — told whether or not the store holds the ref;
* - `"no_owner_read"` — the store has no `ownerOf`, so no entry it holds can be read.
* `owner` is the owner record's members of the contract's shape, as the store answered them.
*/
export interface ToolResultReadRefusal {
readonly ref: string;
readonly reason: Exclude<IdentityReadVerdict, "readable" | "no_owner"> | "unowned" | "owner_read_failed" | "no_owner_read";
readonly reader: OwnerIdentity;
readonly owner?: {
readonly sessionId?: string;
readonly taskId?: string;
readonly principal?: string | null;
readonly isolationScope?: string;
};
readonly cause?: string;
}
/** The operator's notice for one refused read (`tool_result.read_refused`, audience operator): which identity read, which one the
* entry records, and why — e.g. a lane of the deployment running under another principal; an owner read the store failed says so
* without claiming the entry exists. The model read the miss sentence. */
export declare function toolResultReadRefusedNotice(refusal: ToolResultReadRefusal, sessionId: string | undefined): EngineNotice;
/** The store underneath a leg's view, over the deployment's injected one: the Runner's shared default viewed per task under the
* trust scope, an injected store as it is, a task-local in-memory store when there is none. The leg's prepare and the static tool
* plan both read it through this one function (the plan asks whether it keeps bytes — the view's byte arm is present exactly
* when this store's is). */
export declare function legBackingStore(injected: ToolResultSeat | undefined, scope: string): ToolResultSeat;
/**
* The store as ONE run sees it: every entry the run stores records the run's identity, and the run reads an entry only when the
* entry records that same identity ({@link identityReadVerdict} over the store's {@link ToolResultStore.ownerOf}). It is the one
* place the engine's read faces (`ReadToolResult`, `SaveToolResult`) and its writers (the offload wrapper, the per-request budget,
* the clear-with-offload persist, the byte keep, a task's result artifact) reach the store, so the identity a run writes as and
* the identity it reads as are one value.
*
* A ref the run may not read answers exactly as a ref that is not there (`undefined` from {@link get}, {@link bytesOf} and
* {@link read}): its content is never returned, and whether the ref exists under another identity is not said. (A refusal with no
* owner record behind it — stored without provenance, or a store with no `ownerOf` — asks the store whether it holds the ref, to
* tell the operator only of held entries; a store whose `get` loads a whole entry — the file one — loads it for that question, and
* drops it. An `ownerOf` that throws is told without asking.)
*
* The owner is read before the content, in consecutive calls to the store within the one `read` (the owner, then the text, then the
* byte entry and — for a save, `loadBytes` — its bytes; no reader takes content later): an entry deleted and written again under
* the same ref between them is read as the new one. Every ref the engine mints carries a digest of its content (`toolResultContentSegment`,
* `toolResultBytesSegment`, the task-result mint), so a ref written again holds the same content; a host that writes refs of its own
* minting into a shared store owns that window.
*
* Writes: the writer states the session (and a task, where it has one); this view adds the identity. A write that states no
* provenance stores an unowned entry, which no run reads.
*
* Not forwarded: `ownerOf` (the view is the reader of it), and the session / age / orphan sweeps and the listing — those are the
* store owner's verbs over every identity's entries, never a run's.
*/
export declare class LegToolResultView implements ToolResultSeat {
/** The store underneath: the Runner-shared default's scoped view, the injected store, or a task-local one. */
readonly backing: ToolResultSeat;
/** The run's identity — `ownerIdentityOf` of its spec (`owner-identity.ts`). */
readonly identity: OwnerIdentity;
/** Told of every refused read of an entry the store HOLDS (never of a ref that is simply not there), and of every owner read
* that failed (`owner_read_failed`, whether or not the ref exists: the store could not say) — the operator's account of why
* (`reason`) and of both identities; the model reads only the miss sentence. A throw from it is contained. */
private readonly onRefused?;
/** The byte arm, present exactly when the backing store's is. */
readonly putBytes?: (ref: string, bytes: Uint8Array, provenance: ToolResultProvenance, mediaType?: string, held?: readonly string[]) => Promise<void> | void;
readonly bytesOf?: (ref: string) => Promise<ToolResultBytes | undefined>;
constructor(
/** The store underneath: the Runner-shared default's scoped view, the injected store, or a task-local one. */
backing: ToolResultSeat,
/** The run's identity — `ownerIdentityOf` of its spec (`owner-identity.ts`). */
identity: OwnerIdentity,
/** Told of every refused read of an entry the store HOLDS (never of a ref that is simply not there), and of every owner read
* that failed (`owner_read_failed`, whether or not the ref exists: the store could not say) — the operator's account of why
* (`reason`) and of both identities; the model reads only the miss sentence. A throw from it is contained. */
onRefused?: ((refusal: ToolResultReadRefusal) => void) | undefined);
put(ref: string, content: string, provenance?: ToolResultProvenance): Promise<void> | void;
get(ref: string, opts?: {
offset?: number;
limit?: number;
}): Promise<ToolResultSlice | undefined>;
/** THE read of one ref, as the run's read faces take it: judged once, then the one way a ref is read — text (`opts` slices it),
* else bytes ({@link ToolResultStore.bytesOf}). `undefined` = nothing this run can read under `ref` (absent, or not the run's).
* `loadBytes`: a reader that will use a byte entry's content (a save) takes it here, in the same read the judgment admitted
* (`data`), rather than through the entry's lazy reader later — a reader that only describes the entry leaves it unloaded. */
read(ref: string, opts?: {
offset?: number;
limit?: number;
loadBytes?: boolean;
}): Promise<{
readonly text: ToolResultSlice;
} | {
readonly bytes: ToolResultBytes;
readonly data?: Uint8Array;
} | undefined>;
/** Whether this run may read `ref`: {@link identityReadVerdict} of the backing store's recorded owner. No `ownerOf` on the store,
* or an owner read that throws, is no as well. A refusal of an entry the store holds is told to {@link onRefused}. */
private readable;
/** Whether the backing store holds an entry under `ref`, of either kind — asked only to decide whether a refusal is worth telling. */
private holds;
/** The writer's session (and task) with this run's identity — the identity is the view's alone, whatever the writer stated. */
private stamp;
/** The D-2 durable-suspend gate's emptiness question, answered by the backing store (only a volatile backing is asked). */
isEmpty(): boolean;
}
/** True when a durable suspend would lose offloaded results held only in process memory (D-2 gate). */
export declare function isVolatileOffloadStore(store: ToolResultSeat): boolean;
/** Reserved name of the injected large-result reader (design/108 PascalCase: `read_tool_result`→`ReadToolResult`). */
export declare const OFFLOAD_TOOL_NAME = "ReadToolResult";
/** The ref the clear-with-offload persist ({@link createOffloadPersist}) writes one result's full text under: the session, the
* call and the text's digest. Read alone (writing nothing) where a marker is checked against the ref a clear would name. */
export declare function offloadRefOf(sessionId: string, toolCallId: string, fullText: string): string;
/**
* How long a request waits for the clear-with-offload puts in flight ({@link OffloadPersist.flush}) before it is sent without
* them. The wait exists so a model that pages a just-cleared result back at once reads the whole text from a slow but healthy
* store; one row to a remote, loaded database is a second or a few, never tens — the figure of the engine's other store waits
* that give up into a stated answer (`WORKFLOW_STORE_WAIT_BOUND_MS`, `PARK_SELFCHECK_STEP_TIMEOUT_MS`). Longer would hold every
* batch of clears that long on a store that is not answering, where the release before waited for none.
*/
export declare const OFFLOAD_PUT_WAIT_BOUND_MS = 10000;
/** Per-put outcome reported by {@link waitForOffloadPuts}: settled with its value, rejected with its reason, or still pending when the bound or abort ended the wait. */
export type OffloadPutWaitOutcome<T> = {
readonly status: "settled";
readonly value: T;
} | {
readonly status: "rejected";
readonly reason: unknown;
} | {
readonly status: "pending";
};
/** Aggregate result of {@link waitForOffloadPuts}: per-put outcomes fixed at the moment the wait ended, plus whether the bound or an abort ended it. */
export interface OffloadPutWaitResult<T> {
readonly outcomes: readonly OffloadPutWaitOutcome<T>[];
readonly timedOut: boolean;
readonly aborted: boolean;
}
/** Shared deadline handle so one tool call's `details` and content waits draw from one {@link OFFLOAD_PUT_WAIT_BOUND_MS} timer from the first wait. */
interface OffloadWaitWindow {
readonly expired: boolean;
start(): void;
onExpire(fn: () => void): () => void;
dispose(): void;
}
/**
* Wait for one or more engine-awaited tool-result store writes at most {@link OFFLOAD_PUT_WAIT_BOUND_MS}, ending at once on
* `signal` abort when given. Every promise gets a settlement handler at entry so a write abandoned at the bound or on abort
* keeps running in the background without ever raising `unhandledRejection` (late rejections are reported nowhere, and late
* settlements never mutate the returned outcomes). Internal — not exported from the package root.
*/
export declare function waitForOffloadPuts<T>(puts: readonly Promise<T>[], opts?: {
readonly signal?: AbortSignal;
readonly window?: OffloadWaitWindow;
}): Promise<OffloadPutWaitResult<T>>;
/** The run's offload persist: called, it starts the put under this session's ref and returns the ref at once; `flush` settles
* when every put started so far has settled (a rejected put settles too — it is reported, never rethrown), when `signal`
* aborts (a cut ends the wait, not the put), or at {@link OFFLOAD_PUT_WAIT_BOUND_MS}: the puts still owed then are told once
* (`tool_result.offload_put_unsettled`), run on, and no later `flush` waits for them again. */
export interface OffloadPersist {
(toolCallId: string, fullText: string): string;
readonly flush: (signal?: AbortSignal) => Promise<void>;
}
/**
* The runner's clear-with-offload persist, as ONE construction point (the closure used to
* live inline in prepare-task). The caller gets the ref synchronously; the put runs on, and the request builder waits for the
* puts in flight (`flush`) before the refs reach the model, giving way to a cut of the turn.
*
* A failed put REPORTS the loss, it never writes under the ref. The previous arm
* wrote a lost-marker row under the SAME ref "so the page-back face reports the true cause", and that
* one write carried two defects:
* - **revival**: the put and a session purge can race. When the put loses, the marker write lands
* AFTER the purge — re-inserting a row into a session the deployment just deleted, alive until the
* backend's own TTL. A failure arm must not be able to out-write a deletion;
* - **retry contamination**: the per-request re-clear legitimately re-invokes this persist with the same
* (toolCallId, fullText) — the write-once retry path. With a marker occupying the ref, that
* retry's put of the REAL bytes hit the write-once no-op (same owner ⇒ keep what is there), so a
* transient first failure served the marker forever even though the full text was still in hand.
* Now the failure arm writes NOTHING (a later persist call retries the real bytes against an empty
* ref) and announces the failed write loudly instead: through the deployment's structured notice sink
* when one is wired, else the process's default seat, else one process line (the loud-bad-value announcement dialect — a silent catch
* here would be a silent data loss). The announcement claims only what this arm can know: THIS
* attempt stored nothing — the same (toolCallId, fullText) persist recurs per request (write-once
* idempotent re-put), so an EARLIER attempt may already have landed the row and a rejected re-put is
* then no loss at all; declaring "the ref is empty" here would fabricate a data-loss incident on a
* transient outage. Page-back of a ref no attempt ever landed serves the generic miss, which is
* honest: nothing is stored under it.
*
* One refusal is not a lost attempt: the ref holds this session's OWN entry with no identity recorded
* ({@link isOwnEntryWithoutIdentity} — stored before identities were recorded, or by a store that does
* not keep them). The entry is there, no run reads it, and every later attempt meets the same refusal,
* so it is told once per session (`tellOnce`), not per attempt. And when the store refuses at once
* (a synchronous store: the engine's file and in-memory ones), the persist throws the refusal instead
* of returning the ref, so the clear writes its marker without one (`clearOneResult`: a persist that
* throws leaves no ref note) — a ref that reads back for no run is never offered for reading. A store
* that answers later is heard after the marker already named the ref; that marker stands.
*/
export declare function createOffloadPersist(store: ToolResultSeat, sessionId: string,
/** Structured sink for the loss announcement, delivered through the shared guarded form
* (`deliverEngineNotice`, #170): a wired FUNCTION seat REPLACES the console line, swallow-guarded
* (a throwing/rejecting sink never turns an announcement into a failure); a present NON-function
* seat falls back to the process line plus the once-per-process seat-defect announcement; absent ⇒
* the process's default seat, else the process line. */
onNotice?: (notice: import("./types.js").EngineNotice) => void,
/** The session's once-record for the one fact this persist tells once (an entry of the session's own with no identity
* recorded): runs `deliver` unless the session was already told. Absent ⇒ nothing remembers a telling, so every meeting is told. */
tellOnce?: (deliver: () => void) => void): OffloadPersist;
/**
* The byte sibling of {@link createOffloadPersist}: keep `bytes` (claimed `mimeType`) a tool result carried for the call
* `toolCallId` in the seat's store (its byte arm), under a content-addressed ref and the session's owner — or say why not, in
* the closed set (`tool-result-bytes.ts`). The one write every supplier of bytes reaches; the run's single-piece bound
* ({@link TOOL_RESULT_BYTES_KEEP_LIMIT}) is judged here, first, and a store's own bound on one piece is its refusal
* ({@link ToolResultBytesOverLimitError}) — both answer `over_limit` with the bound that was exceeded. Never throws, and never writes
* anywhere else: a store that cannot take the bytes for any other reason is answered `store_failed`, not routed around. Whenever
* the store threw — its bound refusal too — the record carries the store's words (`saveError`, the text it threw: the operator's);
* the run's own bound has none. No seat or no byte arm ⇒ `no_byte_store`. `held` is the same result's pieces kept so far (the
* keeper's list): the store is told not to displace them, and this piece joins them for the result's later pieces once its write
* starts (a result's pieces may be written concurrently) — leaving again if the write fails.
*/
export declare function keepToolResultBytes(seat: ToolResultBytesSeat | undefined, toolCallId: string, bytes: Uint8Array, mimeType: unknown, held?: string[]): Promise<KeptBytes>;
/**
* The clause a model-visible line ends with for one {@link KeptBytes}: the ref and how this run can write it to a file (or that it
* cannot) — the activation step worded as {@link offloadPagebackHint} words its own — or why the bytes were not kept.
*/
export declare function keptBytesClause(kept: KeptBytes, seat: ToolResultBytesSeat | undefined): string;
/** The one {@link ToolResultBytesKeeper}: {@link keepToolResultBytes} into `seat` for the call `toolCallId`, worded by
* {@link keptBytesClause}. Every supplier of bytes (the tool-result seat's admission, an MCP leg) is handed one of these PER RESULT:
* a keeper holds the pieces it kept, so a result's later piece never displaces an earlier one it already named to the model. */
export declare function toolResultBytesKeeper(seat: ToolResultBytesSeat | undefined, toolCallId: string): ToolResultBytesKeeper;
/** Backlog #119 — build the provenance a write site records, from the two coordinates every write site
* already has in hand. `taskId` is omitted (not `undefined`-valued) when the run declares none, so the
* stored shape compares equal across a durable round-trip. */
export declare function toolResultProvenanceOf(sessionId: string, taskId?: string): ToolResultProvenance;
/** Where a background task's result is written when its completion notification carries less than the whole of it: the
* offload store the receiving run's {@link OFFLOAD_TOOL_NAME} reads, and the session that run's refs are minted under. */
export interface TaskArtifactSeat {
readonly store: ToolResultSeat;
readonly sessionId: string;
}
/** What {@link persistTaskArtifact} answers: the ref the text is stored under, a write that failed or went unconfirmed
* (no ref — a ref nobody can read back is a false promise), or no store to write to. */
export type TaskArtifact = {
readonly kind: "stored";
readonly ref: string;
} | {
readonly kind: "unconfirmed";
} | {
readonly kind: "no_store";
};
/**
* THE one write of a background task's result artifact. The ref is CONTENT-ADDRESSED (task id + a digest of the text):
* two cycles of one task with different answers get different refs, and the same answer written twice lands on the same
* write-once row — no cycle number is read, so a row reseeded after a restart (whose cycle counter restarts) cannot
* land a new answer on an old ref. The put is awaited before the answer is returned, so a caller that announces the ref
* announces a write that already landed.
*/
export declare function persistTaskArtifact(seat: TaskArtifactSeat | undefined, taskId: string, text: string): Promise<TaskArtifact>;
/**
* RB-374① — the ONE source of the "page the offloaded text back" suggestion sentence, shared by
* {@link buildPreview} (offload preview tail) and context-edit's cleared-marker refNote. The two
* used to hard-code the same advice in independently drifting wordings, and neither knew whether
* the reader tool is even CALLABLE in the current session: with {@link OFFLOAD_TOOL_NAME} deferred
* (a design/36 placeholder), the suggestion was a self-referential dead end — the model follows it
* and the placeholder rejects with "not active yet".
*
* `reachableTools` is OPTIONAL: omitted ⇒ byte-identical to the historic sentences (the
* determinism/prompt-cache contract of both call sites rests on this default — notably the
* per-request aggregate-budget pass, which re-derives previews every query and therefore must
* never receive a session-varying set). Passed and missing {@link OFFLOAD_TOOL_NAME} ⇒ the honest
* two-step form (activate via ToolSearch first — wording kept close to tool-disclosure.ts's
* placeholder hint). The `core` fragment below is deliberately shared by both forms so the two
* faces cannot drift apart again (a wording change moves both, and both pins move with it).
*/
export declare function offloadPagebackHint(ref: string, form: "preview" | "cleared", reachableTools?: ReadonlySet<string>): string;
/** Leading marker of an offload preview (see {@link buildPreview}) — single source so the aggregate
* budget (design/64 §17.2) can recognize an already-offloaded result without re-deriving the string. */
export declare const PERSISTED_OUTPUT_PREFIX = "<persisted-output ref=";
/** Default per-result offload threshold (chars). ~5K tokens; configurable globally or per tool. */
export declare const DEFAULT_TOOL_RESULT_THRESHOLD_CHARS = 20000;
/** Head+tail preview of an offloaded result, pointing at {@link OFFLOAD_TOOL_NAME} via `ref`. Exported so
* the per-message aggregate budget (design/64 §17.2) produces the SAME preview format (deterministic →
* byte-identical across queries → prompt-cache safe).
*
* The truncation line states WHERE the rest is, not what anyone can do with it.
* "read more" alone reads as a promise that the full output is retrievable, and the model relays that
* promise to the person it is talking to; what is actually guaranteed is narrower and exactly two
* things: the text is retained in this run's tool-result store, and THIS chain can page it back. A
* host-side read face (an HTTP route that hands the user the whole output) is a separate deployment
* feature that may or may not exist — so the line names it as a deployment fact instead of implying
* it, and the model can answer "can I get the full log?" without guessing. */
export declare function buildPreview(full: string, ref: string, sizes?: {
head: number;
tail: number;
}, reachableTools?: ReadonlySet<string>): string;
/**
* Wrap an {@link AgentTool} so that an oversized text result is offloaded to `store` and replaced with a
* preview + `ref` before it ever reaches the session/model. `ref = tr_<sessionId>~<toolCallId>` is stable and the
* store is write-once: a **same-process** replay keeps an identical (cacheable) preview; a **cross-process**
* wake needs a durable store (the default in-memory store loses the full text — the preview still stands).
* Image blocks are left untouched; only text is offloaded. Forwards the `onUpdate` progress callback so a
* wrapped (e.g. MCP) streaming tool isn't broken.
*
* Backlog #175 — a failing store NEVER turns the wrapped tool's success into a failure: the content face
* falls back to the original (un-offloaded) result, and the `details` walk to a ref-free notice per lost
* member (see the two arms for why the degrades differ). The wrapper adds a storage step to a tool that
* has already run; it must not be able to invalidate that run.
*/
export declare function withToolResultOffload(tool: AgentTool, store: ToolResultSeat, thresholdChars: number, sessionId: string,
/** RB-374① — LIVE accessor for the session's currently CALLABLE tool set (evaluated per offload,
* so a mid-run ToolSearch activation is reflected by the next preview). Absent/`undefined`-returning
* ⇒ byte-identical historic preview. An accessor (not a snapshot) because the wrap happens at
* prepare time, before the deferred classification exists and before any activation can. */
reachableTools?: () => ReadonlySet<string> | undefined,
/** Structured notice seat for reporting tool-call offload writes still unsettled at {@link OFFLOAD_PUT_WAIT_BOUND_MS}. */
onNotice?: (notice: EngineNotice) => void): AgentTool;
/** The injected `read_tool_result` tool: pages through an offloaded result. `effect:"read"` (verifier/reconcile-safe).
* `legsOfRef` = the legs a page-back of one ref travels: a ref holding a background task's result (`persistTaskArtifact`, its
* origin in the ref — {@link taskArtifactOriginOf}) travels the legs a poll of that task travels — content from another tree is
* an off-target read however it is read back — and the registry's reading answers it; absent, or for any other ref (offloaded
* tool output), none. A ref is read the one way the store contract states: text first; a ref holding bytes instead
* (`bytesOf`) is answered — not an error — with its size and type and how this run can write them to a file (`bytesSeat`'s
* reach of SaveToolResult); a ref holding neither is the honest miss. `store` is the run's {@link LegToolResultView}: a ref this
* run may not read reads as absent, so it takes the miss sentence too. */
export declare function createReadToolResultTool(store: LegToolResultView, legsOfRef?: (ref: string, tree: import("./cross-boundary-taint.js").CrossBoundaryTreeToken) => import("./cross-boundary-taint.js").BoundaryLegsGiven, bytesSeat?: ToolResultBytesSeat): AgentTool;
export {};