@sema-agent/core
Version:
Stateless, task-oriented AI agent core
221 lines (220 loc) • 17.6 kB
TypeScript
import { type RetentionDeclaration } from "../../core/retention.js";
import type { ToolResultBytes, ToolResultDeletionReport, ToolResultEntryKind, ToolResultProvenance, ToolResultRekeyVerdict, ToolResultSessionListing, ToolResultSlice, ToolResultStore } from "../../core/tool-result-store.js";
import { type IdentityRekeyInput, type IdentityRekeyPlan, type OneStepRekeyMode, type RekeyDone } from "../../core/identity-rekey.js";
import { type CorruptReadInfo } from "./corrupt-read-sink.js";
/**
* design/80 §2.5 — file {@link ToolResultStore}: write-once-idempotent, ONE content file per ref — `<stem>.txt` for text,
* `<stem>.bin` for the byte arm ({@link FileToolResultStore.putBytes}), never both — beside one owner record.
*
* `ref = tr_<sessionId>~<toolCallId>` (engine-minted, already globally unique; the separator is the
* backlog #119 injective form). `put` is an `O_CREAT|O_EXCL` create → on `EEXIST` it no-ops
* (write-once-idempotent; never re-writes — a re-write risks a non-identical preview and breaks the
* prompt cache, §2.5 / the in-memory store's `map.has(ref)` check). Content is fsync'd before return.
* `get` slices the file by `{offset, limit}` over CHARS to match `ToolResultSlice.totalChars` semantics;
* an unknown ref → `undefined` (the model is told it's gone — degrades, never crashes).
* `withToolResultOffload` joins text with `\n` and stores the joined string verbatim, so the char-offset
* slice here is exactly the in-memory store's slice.
*
* Provenance (#119) lives in a SIDECAR file next to the content one (`<encoded>.owner.json`), not in a
* header inside it: the content file's bytes are the stored result verbatim, which is what makes the
* char slice identical to every other backend's and what keeps files written by older versions readable
* with no format migration.
*
* That is TWO published objects, so the window is stated rather than hidden (falsification review): the
* content link is the write-once election and the sidecar follows it, so a crash in between leaves an
* entry content-complete and momentarily UNOWNED. Publishing the sidecar FIRST would close that window
* and open a worse one — an ownerless writer's row could then be claimed by whoever raced it — so the
* order stands and the entry stays unowned: fail-closed, refused by a host read face, never
* mis-attributed, and never adopted by a later write (adoption is an adjudicated contract rule, not a
* local choice — see the `put` body). What a `put` no longer does is walk over DAMAGE: a sidecar that
* is present but unreadable stops the write loudly, where treating it as "no owner" would report
* success and leave the entry unclaimable forever.
*/
export interface FileToolResultStoreOptions {
/** Disclosure seat for an owner sidecar that is PRESENT but unreadable: {@link
* FileToolResultStore.ownerOf} answers `undefined` — the same word it uses for an entry nobody owns,
* so a host that authorizes on it reads damage as "unowned". Swallow-guarded. */
onCorruptRead?: (info: CorruptReadInfo) => void;
/** The store's managed-retention declaration (retention.ts), stated by the party that runs the sweep; default `"none"`, a third
* word refused (`config.retention_capability`). */
retention?: RetentionDeclaration;
}
export declare class FileToolResultStore implements ToolResultStore {
/** {@link FileToolResultStoreOptions.retention}, as read at construction. */
readonly retention: RetentionDeclaration;
private readonly dir;
private readonly discloseCorrupt;
/** The tool-result store's {@link HolderLatch} (no close of its own): the dispose of the backend that built it closes it. */
private readonly latch;
constructor(root: string, options?: FileToolResultStoreOptions);
/** The one delivery point for {@link FileToolResultStoreOptions.onCorruptRead}. */
private disclose;
/** The directory a ref's files live in, and their shared stem. See {@link encodeRefFilename} for why
* a FOLDED name gets its own directory instead of sharing one with identity names. */
private locate;
/** The content file of `ref`'s entry of `kind` — one name per kind in {@link CONTENT_SUFFIX}, beside one owner record. */
private pathFor;
/** The cross-kind half of the write-once election: a ref whose stem already holds the OTHER kind's content file refuses this
* write, typed, before anything is linked — one stem, one content file. Under the data root's single writer the check and
* the link that follows are adjacent synchronous steps. */
private refuseOtherKind;
/** #119 — the provenance sidecar's path. Same directory and stem as {@link pathFor}, so the pair is
* found by one encoding step and a ref that cannot be encoded has no sidecar either. */
private ownerPathFor;
put(ref: string, content: string, provenance?: ToolResultProvenance): void;
/** The byte arm's write (interface: {@link ToolResultStore.putBytes}): the same election as {@link put}, the content file
* `<stem>.bin`, the media type in the owner record. */
putBytes(ref: string, bytes: Uint8Array, provenance: ToolResultProvenance, mediaType?: string): void;
/** The one write-once election both kinds run: refuse the other kind, link the content file, then publish the owner record. */
private publish;
/** #119 — the recorded owner, or `undefined` for an unknown ref AND for a stored-but-unowned one.
* Lenient by design on the READ face (see {@link readOwnerFile}). */
ownerOf(ref: string): ToolResultProvenance | undefined;
/**
* #119 — read the owner sidecar. `loud` splits the two faces on purpose, the same split this backend
* already applies to ref safety: a READ (`ownerOf`, an authorization question) degrades an
* unreadable or malformed sidecar to "unowned" so a corrupt file cannot crash a page-back, while a
* WRITE refuses to proceed over one it cannot read — silently treating damage as "no owner" is how a
* write reports success and leaves the entry unclaimable forever (falsification review round 4).
* A MISSING sidecar is not damage in either face: it is the honest "unowned".
*/
private readOwnerFile;
/** #119 — publish the owner sidecar (write-once, like the content file it accompanies). */
private writeOwnerFile;
get(ref: string, opts?: {
offset?: number;
limit?: number;
}): ToolResultSlice | undefined;
/** The byte arm's read (interface: {@link ToolResultStore.bytesOf}): the `.bin` file's size, the media type its owner record
* carries, and its bytes when asked. `undefined` for a ref holding no bytes — and, as on {@link get}'s face, for a ref no write
* could store. */
bytesOf(ref: string): ToolResultBytes | undefined;
/**
* Erase every entry owned by `sessionId` (interface: {@link ToolResultStore.deleteBySession}). Without
* it a session deletion leaves this store's files on disk for the lifetime of the data root.
*
* Selection matches on the SIDECAR's `sessionId`, never on the filename. That is not a preference, it
* is the only thing available: the mint separates segments with `~`, which is outside this backend's
* filename charset, so every engine-minted ref folds to `<base>-<sha256 of the raw ref>` and the
* session segment is gone from the name (and the readable base is a lossy, many-to-one prefix, so
* matching on it would reach a neighbouring session's files). `taskId`, where an older write site
* stamped one, is ignored — it narrows the same session.
*
* Both namespaces are swept: identity-named files in the store dir (refs a caller minted inside the
* filename charset, and everything written before the injective mint) and {@link FOLDED_SUBDIR}; in each, only the names
* this store writes ({@link entryPartOf}) — a text or a byte entry is removed alike, and a staging file is never touched here
* (it has no owner; the age sweeps remove a dead write's).
*
* Removal order is CONTENT then SIDECAR, and it is load-bearing. Interrupted after the content unlink,
* the next sweep still finds the sidecar, matches the same session and converges; interrupted after a
* sidecar-first unlink, the content file would be left owner-less — readable, attributable to nobody,
* and beyond the reach of every future session sweep. Same reasoning as `put`'s publication order, in
* the opposite direction. The pair is then re-examined ONCE after both unlinks, which is what keeps
* a `put` racing the two from leaving bytes whose owner this sweep removed — and what keeps that
* re-examination from deleting a row a DIFFERENT session claimed in the same window (see the body).
*
* What the re-examination is NOT is atomic: it reads the owner and then acts, so a writer landing
* inside THAT gap is narrowed, not excluded. Stated rather than locked away, because the locking that
* would close it is ruled out one layer down — `fs-atomic.ts` §2.4 admits exactly one file lock, the
* boot lock, on the premise that a data root has a single writing process (`FileStorageBackend`
* acquires it before constructing this store; cross-process correctness is a database backend's job,
* as everywhere else in this family). Under that premise there is no gap at all: both `put` and this
* sweep are wholly synchronous, so nothing can interleave with either. The narrowing above is what
* remains worth doing for a root someone shares anyway, and it costs one `readFileSync`.
*
* Failure posture: an entry that vanished between `readdir` and the unlink is honest absence (ENOENT
* ok, the concurrent sweeper's row). Any OTHER unlink error throws — a deletion face that cannot
* delete has to be loud — and because the sweep is idempotent, the retry after the operator clears
* the cause resumes where it stopped. A sidecar that cannot be READ (EACCES, torn JSON, a shape that
* is not the whole record) is counted `unattributable` and its content is left alone: a file we could
* not read carries no evidence about whose it is, and this store's rows stay readable through `get`
* even with a damaged owner record, so removing one on a guess would destroy another session's output.
*/
deleteBySession(sessionId: string): ToolResultDeletionReport;
/**
* Age out the entries stored more than `maxAgeMs` before `now` (interface: {@link ToolResultStore.reap}). An entry's
* age is its content file's modification time: the write-once publication sets it and nothing rewrites the file.
* Both namespaces are swept, and only names this store writes are judged ({@link entryPartOf}): text and byte entries alike.
* Removal is content then owner record, the order {@link deleteBySession} keeps; an owner
* record whose content is already gone — the leftover of an interrupted pass, or of a session sweep — is removed
* once it is past the cutoff too, and is not counted (it was not an entry); so is a staging file a write left behind when
* its process died between opening it and linking it (a live write's staging file is as new as the write). Synchronous: under
* the data root's single writer nothing interleaves with it.
*/
reap(now: number, opts?: {
maxAgeMs?: number;
}): number;
/**
* Delete the entries with no owner record stored before `cutoffMs` (interface: {@link ToolResultStore.deleteUnattributable}): a
* content file with no owner record beside it. A present owner record keeps its entry whether it reads or not, and age is the
* content file's modification time, as {@link reap} reads it — so a `put` caught between its content and its owner record (its
* content is as new as the write) is never past a cutoff in the past. The owner record is looked for again just before the
* unlink, so one that landed after the listing still keeps its entry. Both namespaces; names this store writes only
* ({@link entryPartOf}), text and byte entries alike; a dead write's staging file past the cutoff goes too, uncounted, as in {@link reap}.
*/
deleteUnattributable(cutoffMs: number): number;
/**
* The entries `sessionId` owns, as ref + recorded owner (interface: {@link ToolResultStore.listBySession}). The selection is
* {@link deleteBySession}'s own: it walks the same two namespaces and matches on the SIDECAR's `sessionId`, never on a file name; a
* sidecar that cannot be read, and content with no sidecar, are counted `unattributable` and not listed.
*
* Naming the ref is this backend's one extra step, because a folded name is a digest of the ref and cannot be read back. An entry
* written by this engine carries its ref in its sidecar; an identity-named entry (a ref inside the filename charset) is its own stem.
* The ref a record states is believed only when its own encoding is the very file the record sits beside — a record that names a ref
* stored somewhere else is not this entry's. An entry owned by the session whose ref can be named by neither is counted
* `unaddressable` (a folded entry written before the sidecar carried it): it is still removed by a sweep, and is never listed under a
* guessed ref. An entry is what the sweep counts: an owner record whose content file is gone (the leftover of an interrupted sweep, which
* the next sweep finishes) is listed like the sweep counts it, and `get` answers `undefined` for it — the honest absence a reader of a
* listing already handles.
*/
listBySession(sessionId: string): ToolResultSessionListing;
/** The identity re-key (interface: {@link ToolResultStore.rekeyIdentity}) — {@link rekeyToolResultDirectory} over this store's
* directory. Synchronous inside: under the data root's single writer nothing interleaves with it. */
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "plan";
}): Promise<IdentityRekeyPlan>;
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "leave";
}): Promise<RekeyDone>;
/** The ref an entry stored at `dir`/`stem` is stored under, or `undefined` when none can be named: the ref its sidecar states when
* that ref's own location is this file, else — for an identity-named entry — the stem itself. */
private refOfEntry;
}
/**
* The file backend's identity re-key over a tool-result directory (`<data root>/tool-results`) — the one implementation the store's
* member and the data root's adoption leg (which runs while every store constructor is refused) both run. The input is read first
* (`readIdentityRekeyInput`: a `TypeError`, nothing read). Both namespaces are walked, owner records only ({@link entryPartOf}); each
* is judged by the seat's one law ({@link rekeyToolResultOwner}) and, on `leave`, replaced atomically (staged beside it, renamed over
* it) by the same record with only its two identity members rewritten — every other member it holds (the session, the task, the ref,
* the media type, a member a newer engine wrote) as it stands. The content file is never touched, so the entry's age is unchanged. An
* owner record removed between the listing and its read, or present but not an owner record, is what
* {@link FileToolResultStore.ownerOf} reads it as — no owner — and not this move's. One that cannot be read at all is thrown, as the
* session-policy seat's re-key throws for its rows: a step that skipped it would answer as though it had judged it (a `leave` that
* returns has judged every record it listed), and a re-run after the repair completes the move.
*/
export declare function rekeyToolResultDirectory(storeDir: string, input: IdentityRekeyInput, onUnrekeyable?: (ref: string) => void): IdentityRekeyPlan | RekeyDone;
/**
* The walk {@link rekeyToolResultDirectory} runs, with the judgment of one owner record handed in: every owner record of both
* namespaces read, judged by `judge`, and on `leave` rewritten as that function's comment states. The seat's re-key hands it the one
* law ({@link rekeyToolResultOwner}); the data root's local-owner adoption hands it the judgment of the local owner's own entries.
* `onUnrekeyable` is told the ref of each record judged `unrekeyable` (the ones `plan` counts as conflicting).
*/
export declare function refileToolResultDirectory(storeDir: string, mode: OneStepRekeyMode, judge: (owner: ToolResultProvenance) => ToolResultRekeyVerdict, onUnrekeyable?: (ref: string) => void): IdentityRekeyPlan | RekeyDone;
/** One file of this store's, as {@link entryPartOf} reads its name. */
export type ToolResultEntryPart = {
readonly stem: string;
readonly part: "content";
readonly kind: ToolResultEntryKind;
} | {
readonly stem: string;
readonly part: "owner";
} | {
readonly stem: string;
readonly part: "staging";
};
/**
* THE one reading of "is this file one of this store's, and which part of which entry": every sweep and the write's path
* composition read names through this table and nothing else. A name it answers `undefined` for is not an entry, whatever its
* suffix — no sweep deletes it and no count includes it (`folded` = the {@link FOLDED_SUBDIR} namespace, whose stems are digests).
*/
export declare function entryPartOf(name: string, folded: boolean): ToolResultEntryPart | undefined;