UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

139 lines (138 loc) • 9.98 kB
/** * Rebuild the hands' read-before-write state from a session's own transcript (ruled 2026-08-05). * * `readFileState` is minted per TASK and, until this module existed, was only ever re-seeded from a * durable-resume checkpoint. An ordinary session CONTINUATION — a new `runTask` carrying the previous * `sessionId` — therefore started blind: turn 1 Read the file, turn 2 was told "File has not been * read yet", and every file cost a re-read round-trip on every turn of a long conversation. * * The transcript already records what is needed, so no new persisted surface is minted here: the * tool results carry the file's whole text in their `details` card. This module walks those records * and reports, per file, the LAST content the transcript can prove — the caller turns each into a * read-state entry whose staleness hash is computed from THAT text. * * Two rules make the reconstruction safe rather than merely convenient: * * 1. **The content never comes from disk.** Every hash the caller derives from these records is a * hash of what the transcript recorded. A file changed between the turns (by the user, a linter, * a `git checkout`, a bash command — anything this transcript does not record) therefore fails * the staleness comparison and the edit is refused, exactly as it is inside a single task. A * reconstruction that re-read the file to build its hash would instead wave the dirty edit * through; that is the one thing this module must never do. (This is * deliberately STRICTER than CC's own rehydrate, whose Edit arm re-reads the disk and would * admit a between-turns external change — same gate satisfaction, no staleness give-up.) * 2. **Only records whose full post-condition is PROVABLE qualify.** A whole-file `Read` and a * `Write` carry the text verbatim. An `Edit` card carries a diff BASE — the * pre-edit whole text plus the resolved mutations — so its post-condition is RECOMPUTED through * the same single-source application step the tool itself used (`applyRecordedEdit`); a card * that cannot recompute (malformed, offloaded, or its oldString absent from its own base) falls * back to RETRACTING the file's record, never to a guess. A page the token cap cut * proves a read that saw only part of the file, and is rebuilt as the partial view the live read * recorded (no whole text, so no hash a write could match: the read-first rule refuses it as it * does live, and a write that may change a file never read does not reach it). An explicit * slice and a notebook projection prove no whole text and leave no record; like every read or * change no record stands for, the file is reported as read without an entry * ({@link readStateFromTranscript}), so the waiver does not reach it and a write waits for a read. * * A successful `Read` result the 7.69.1 Read tool wrote with no `details` — its note for an empty file or for a read past the * end, the two reads it answered without a card — is a file seen with no content the transcript proves: named by its call's * own path argument (the latest call site before it with its id, as the request view pairs them), it enters no record and * retracts none; a result whose call is not shown as a Read, or a relative path, names no file and marks the leg, as a * relative spelling does. The note is the result's first block (a hook's context or an appended block may follow it); a * result with no `details` whose first block is anything else (a tool a deployment mounted under the name, a first block a hook * changed) is inert, as a foreign card is. * * A compaction's summary on the branch marks the leg the same way: the reads it summarized away are not shown, so no file can * be said never to have been read (what the kept tail and the restore frames after it show still has its entry). */ import type { AgentMessage } from "../../internal/harness.js"; import { type UserAttachmentObservation } from "../../internal/llm.js"; import { type ReadEntry } from "../../tools/fs/safety.js"; import type { TaskSpec } from "../task-spec.js"; import type { LegReadCarrier } from "./session-read-file-states.js"; /** What the transcript proves about one file: its whole text at that moment (a tool's card), or the read-state entry a * delivery that carried no whole text committed — an attachment frame's (its record's observation, verbatim — hash, view * and partial-view flag), or a `Read` the token cap cut (a partial view, {@link cutPageFromReadCard}). */ export type TranscriptFileRecord = { /** The path as the tool recorded it — absolute (see {@link wholeFileRecordsFromTranscript}). */ path: string; /** The file's ENTIRE text at that moment, in the decoded coordinate the fs tools hash. */ content: string; /** The recording message's own timestamp — the most honest "last read at" available. */ at: number; /** A Read result's call id — the transmission that carried the text (a Write's or an Edit's post-condition: none). */ transmittedByToolCallId?: string; } | { path: string; /** The entry the delivery committed, its witness set the frame that carried it (a trim that drops the frame retires it). */ observation: UserAttachmentObservation["entry"] & { witnesses: readonly string[]; }; at: number; }; /** * Per-file, the last whole-file content the transcript proves — in transcript order, last record wins. * * Records are read only from SUCCESSFUL results (an `isError` result changed nothing and proves * nothing). A `Write` proves the post-condition it just persisted; a whole-file `Read` proves what it * just served. An `Edit` card proves the post-condition RECOMPUTED from its recorded * diff base + mutations — or, when it cannot prove (malformed / offloaded / inconsistent), retracts * whatever an earlier record said (leaving a stale entry behind would blame the user for the agent's * own edit, "modified since read", the next turn). A `NotebookEdit` always retracts (deliberate * residual — see {@link RETRACTING_RESULTS}). A `Read` the token cap cut proves a partial view * ({@link cutPageFromReadCard}). Anything else (explicit slices, notebook projections, image/document reads, foreign * tools) is inert: it neither proves nor retracts, because reading a file does not change it. * * The parameter is the session's own message lane (`AgentMessage`, custom lanes included) rather than * the narrowed model-facing union: this reads the branch as the session stores it, and every lane that * is not a tool result falls out on the first line of the loop. * * A user-attachment frame (`UserMessage.attachment` with an observation) proves the read state its delivery committed, * keyed by the canonical key it carries — the same entry the live commit wrote, so a rebuilt partial view stays one; an * instruction frame that withdraws a file retracts the key it names while an instruction frame's record holds it, as its * live delivery deleted the entry only then. * * Paths are reported only when the tool recorded an ABSOLUTE one. A relative spelling was resolved * against the tracked working directory of that moment, which this task cannot reconstruct; re- * resolving it here could key the entry to a different file. * * The records half of {@link readStateFromTranscript}. */ export declare function wholeFileRecordsFromTranscript(messages: readonly AgentMessage[]): TranscriptFileRecord[]; /** * What the transcript says of the files the model read or changed: the records ({@link wholeFileRecordsFromTranscript}), and * the files it read or changed for which no record stands — the reads and changes whose live counterpart left a read entry * the transcript cannot rebuild (an explicit slice, an Edit card that cannot prove its result, a notebook's read or change, * a record a later one retracted, a `Read` result the 7.69.1 Read tool wrote with no card, named by its call's path). Such a file is not one the model never read: the read-first waiver does not reach it, * so a change to it waits for a read, as it did before the waiver existed. * * `paths`: those files' absolute spellings, as recorded. `unplaced`: a read or change recorded under a relative spelling, * which was resolved against the tracked working directory of that moment (the Read tool's resolution, `resolveKey` over * the leg's `cwdRef`) — the transcript keeps no working directory per message, so no file can be named for it, and no file * on the leg can be said never to have been read; so does a compaction's summary (the reads it summarized away are not * shown). Reads that leave no live entry (an image or a PDF, a refused read) are not reported: the waiver answers for them * on every Runner alike. */ export declare function readStateFromTranscript(messages: readonly AgentMessage[]): { records: TranscriptFileRecord[]; unentered: { paths: string[]; unplaced: boolean; }; }; /** * Does a leg's read state carry in files a compaction on it re-delivers (the post-compaction restore re-reads the files the read * state holds, through the environment)? Read before the leg's environment starts, off the carrier the hands phase seeds the * state from (`legReadCarrier`): a resume leg's checkpoint seed, the session's live seat, or the transcript's whole-file * records. A leg that turns the restore off (`compaction.attachWorkingFiles: false`) carries none. `undefined` = only the * transcript can tell and none was handed. */ export declare function legCarriedReads(input: { readonly spec: Pick<TaskSpec, "compaction">; readonly carrier: LegReadCarrier; readonly resume: { readonly seed: { readonly readFileState?: Iterable<readonly [string, ReadEntry]>; }; } | undefined; readonly transcript?: readonly AgentMessage[]; }): boolean | undefined;