@sema-agent/core
Version:
Stateless, task-oriented AI agent core
293 lines (292 loc) • 17.2 kB
TypeScript
import type { DocumentContent, ImageContent, TextContent } from "../../internal/llm.js";
import type { AgentTool, ExecutionEnv } from "../../internal/harness-types.js";
import { errorResult } from "../../core/tools.js";
import type { ToolReturn } from "../../core/tool-spec.js";
import { type ReadEntry, type ReadFileState, type RootsSeat } from "./safety.js";
import { type ImageDimensions, type ImageDownsampler } from "../../core/image-downsample.js";
import { type PdfModelCapabilities } from "./pdf.js";
import { type CwdRef } from "./fs-shared.js";
import { type BoundOpening } from "./bound-open.js";
import { type ReminderDisclosureCounts, type ReminderDisclosureEffects, type ReminderDisclosureVerdict } from "../../core/reminder-disclosure.js";
import { type DirectoryListing } from "./dir-entries.js";
import type { BoundFileObject, FileError, Result } from "../../internal/harness.js";
import type { ContextRoomSeat } from "../../core/runner/context-room.js";
/**
* The Read tool, and the ONE read of a file for the model it is built on, split into three steps so every
* carrier shares it:
*
* readForModel(args) → a value: the external data blocks, the engine's STRUCTURED notes about the read,
* the read-state observation, the deferred effects, an outcome word;
* commit(result) → the side effects, applied when the carrier actually delivers the result (the
* read-state entry, the disclosure throttle windows and counters);
* render → per carrier. {@link renderReadToolResult} is the Read tool's: it reproduces the
* tool result byte for byte (the Read pins are the proof); a carrier that delivers
* a file somewhere else renders the same notes in its own words.
*
* `readForModel` is side-effect free toward the run: it reads the filesystem (and, on the PDF lane, runs
* the poppler readers), it READS the read state and the throttle windows, and it writes neither. One write
* is not deferred to `commit`: a read `allow_large` raised books what it serves against its reply's context
* room ({@link ModelFileReaderOptions.contextRoom}) at the moment it decides to serve it, with no await
* between the decision and the booking, so two raised reads of one reply cannot both take the same room.
*
* What is DATA and what is a NOTE. `data` holds what the file itself supplies, in order — the
* line-numbered body, the notebook cell blocks, the image block. Everything the engine says ABOUT the
* read (empty file, offset past the end, the range
* header, the partial-view marker, the corrupt-notebook prefix, the 0-cell placeholder, the resize
* coordinates, the disclosure verdict) is a structured {@link ReadNote} — never a pre-rendered string, so
* no carrier inherits the tool carrier's wording (a name inside an engine sentence is the tool
* carrier's own byte, not a rule for other carriers). The PDF lane is the one exception: its blocks are
* the Read tool's PDF projection as-is (engine headers interleaved with the fenced text layer) — a
* carrier other than the Read tool does not present them as file data.
*
* A refusal is the Read tool's own error envelope (`refusal`), minted where it is decided, with
* `outcome: "not_attached"`.
*/
/** What happened to the file's contents. `partial` = a default read the token cap cut (the partial-view
* marker); `not_attached` = nothing of the contents was served (a refusal, an offset past the end, a PDF whose
* degradation chain bottomed out). A read of contents the request already carries is still `attached`, never decided
* at the read: a Read result is sent as those contents on every request; an attachment frame may be sent as the
* sentence that they are not repeated beside an earlier copy (the request's own projection,
* `request-copy-projection.ts`).
* Exported to carriers by the seat that needs it, not from the package. */
export declare const READ_OUTCOMES: readonly ["attached", "partial", "not_attached"];
export type ReadOutcome = (typeof READ_OUTCOMES)[number];
/** The lane the read took. Absent on a refusal raised before the lane was known. A corrupt notebook served
* as raw text is `text` (with the `notebook_fallback` note). `directory`: the path is a directory — judged in one
* place, before the lanes; the Read tool refuses it, a carrier that lists directories reads the kind. */
export type ReadKind = "text" | "notebook" | "image" | "pdf" | "directory";
/** The engine's statements about one read, as data. The Read carrier's rendering is
* {@link renderReadNoteForTool}; the frame carrier renders the same members its own way. */
export type ReadNote = {
kind: "empty_file";
} | {
kind: "past_eof";
offset: number;
totalLines: number;
}
/** A served window that is not the whole file (an explicit slice), no partial-view marker. */
| {
kind: "range";
path: string;
start: number;
end: number;
total: number;
}
/** A default read the token cap cut by lines. `room`: the read was judged against the context room `allow_large` raised it
* to (the banner names that room, not the base cap); `offer`: what `allow_large` would do for the whole file. */
| {
kind: "partial_page";
end: number;
total: number;
approxTokens: number;
room?: number;
offer?: LargeReadOffer;
}
/** A default read whose first line alone overflows the cap, served as a character prefix (`room` / `offer` as above). */
| {
kind: "partial_chars";
cut: number;
totalChars: number;
approxTokens: number;
room?: number;
offer?: LargeReadOffer;
}
/** A `.ipynb` that does not parse, served as raw text. */
| {
kind: "notebook_fallback";
}
/** A parsed notebook with no cells. */
| {
kind: "notebook_no_cells";
}
/** The image was downsampled; the coordinates map back to the original. */
| {
kind: "image_resized";
dimensions: ImageDimensions;
}
/** External bytes carried reminder- or envelope-shaped text. */
| {
kind: "disclosure";
verdict: ReminderDisclosureVerdict;
}
/** A PDF read as a reference only ({@link ReadForModelOptions.pdfAsReference}): its size and page count, when known. */
| {
kind: "pdf_reference";
bytes?: number;
pages?: number;
};
/** The read-state entry a delivery records, minus the delivery's own facts (when, which transmission). */
export interface ReadObservation {
key: string;
entry: Pick<ReadEntry, "hash" | "totalLines" | "truncated" | "isPartialView" | "view">;
}
/** The Read tool's error envelope for a refusal. */
export type ReadRefusal = ReturnType<typeof errorResult>;
export interface ReadForModelResult {
outcome: ReadOutcome;
kind?: ReadKind;
data: Array<TextContent | ImageContent | DocumentContent>;
notes: ReadNote[];
/** The host face (the Read tool's `details`), shared by every carrier. */
details?: Record<string, unknown>;
/** The Read tool's refusal (its error envelope: the sentence and its structured details) — present exactly on a
* refusal. */
refusal?: ReadRefusal;
/** Present when a delivery records read state. */
observation?: ReadObservation;
effects: {
disclosure: ReminderDisclosureEffects[];
};
}
/** The facts of the read the caller supplies (the tool context's subset). */
export interface ReadForModelContext {
signal?: AbortSignal;
toolCallId?: string;
taskId?: string;
/** The run's working-state key (`ToolContext.isolationScope`): the scope a background output file is registered under. */
isolationScope?: string;
}
/** How a carrier other than the Read tool asks for the read. Absent members ⇒ exactly the Read tool's read. */
export interface ReadForModelOptions {
/** A read of an object the carrier holds: the canonical key the carrier resolved and the object it bound there
* ({@link ModelFileReader.openBound}), the one it had judged. A path that resolves to another key is refused; the kind,
* the size and every byte come from the bound object, never from the path — as they come from the object every read
* opens at its judged key. The carrier closes it. */
bound?: {
key: string;
object: BoundFileObject;
};
/** The read delivers into a context other than the live one (a compaction's restore: the context the landed summary
* leaves) — it is not held back by the disclosure throttle (the disclosure the window remembers left with that
* context). */
freshContext?: true;
/** A carrier that presents the read as file data (an attachment frame) takes a PDF as a reference — its size and page
* count, no pipeline run — since the Read projection interleaves engine text with the file's. Nothing else makes a
* reference: a held object's PDF is read in full like any other. */
pdfAsReference?: boolean;
/** The canonical key the carrier's judgment of this path landed on, for a carrier that judged it without holding the
* object (a bound read carries it as `bound.key`): a path whose final resolution is elsewhere is refused, the refusal
* marked `details.type: "target_moved"` so a frame says it in the attachment's own words. */
judgedKey?: string;
}
/** What a text read of a file found ({@link ModelFileReader.readText}): its text in the decoded coordinate, or the one
* word for why there is none. `refused` — the path's own resolution refused it (nothing is said about the file);
* `moved` — it resolved elsewhere than the key the carrier's judgment landed on; `absent` — nothing is there;
* `not_text` — a directory, an identified binary format, a binary sniff, a body that is not UTF-8 or a truncated UTF-16
* body; `oversize` — past the carrier's byte cap, by the stat or by the bytes read (never cut); `unavailable` — the stat
* or the read failed. */
export type TextReading = {
readonly kind: "text";
readonly text: string;
} | {
readonly kind: "absent";
} | {
readonly kind: "refused";
} | {
readonly kind: "moved";
} | {
readonly kind: "not_text";
} | {
readonly kind: "oversize";
} | {
readonly kind: "unavailable";
};
/** What `allow_large` offers a text read that is over Read's size limits — the clause its over-limit sentence ends with.
* `read_anyway`: the call may be repeated with the key and the file fits the room left this turn; `over_room`: even with the
* key it does not (said also to a call that set the key and was still over); `unavailable`: the call set the key where no
* context room can be measured. */
export type LargeReadOffer = "read_anyway" | "over_room" | "unavailable";
/** The tokens a served text body costs, with no tokenizer: its characters at the model's coefficient, and never fewer than
* half its UTF-8 bytes (a multi-byte script is not under-counted by its character length). */
export declare function servedReadTokens(body: string, charsPerToken: number): number;
export interface ModelFileReaderOptions {
env: ExecutionEnv;
state: ReadFileState;
rootCanonical: string;
cwdRef?: CwdRef;
additionalRoots?: RootsSeat;
/** The run's image processor seat (`RunnerDeps.imageProcessor`): a processor, `false` (none), absent = auto-detect. */
imageProcessor?: ImageDownsampler | false;
pdfCapabilities?: PdfModelCapabilities;
/** See createReadFileTool's seat of the same name. */
bgOutputReadExemption?: (canonicalKey: string, ctx: {
taskId?: string;
isolationScope?: string;
toolCallId?: string;
}) => boolean;
readDeny?: import("./read-deny.js").ReadDenyMatcher;
readFace?: import("./containment-face.js").ContainmentFace;
/** The remedy an out-of-root refusal names in place of the escape hint (`resolveKey`'s `outsideRemedy`): the run's read
* face carries it on a leg that refuses reads outside its declared directories. Absent ⇒ the escape hint. */
outsideRemedy?: string;
reminderMark?: string;
reminderDisclosureCounts?: ReminderDisclosureCounts;
/** The bare-form disclosure throttle windows, keyed by canonical file key. Owned by whoever builds the
* reader; every carrier that reads through the same reader shares them. Absent ⇒ a fresh map. */
disclosureWindows?: Map<string, number>;
/** The leg's context-room seat: a text read whose call set `allow_large` has its limits raised to the room measured for the
* call, and an over-limit sentence says what the key would do. Absent ⇒ no room is measured here (a library-direct mount):
* a call that set the key is told so when it is over the limits. */
contextRoom?: ContextRoomSeat;
}
export interface ModelFileReader {
readForModel(args: unknown, ctx: ReadForModelContext, opts?: ReadForModelOptions): Promise<ReadForModelResult>;
/** The path's resolution alone — the same step `readForModel` opens with (the read-deny table, the roots, the device
* and UNC refusals): its canonical key, or the Read tool's refusal. */
resolveTarget(path: string, ctx: ReadForModelContext): Promise<{
ok: true;
key: string;
} | {
ok: false;
refusal: ReadRefusal;
}>;
/** The file's text as the Read tool's text lane decodes it, with none of the Read's layout: the same resolution
* (refused before anything is said about the file), the judged key held to it (`judgedKey`), the object opened there as
* the Read opens it (another object found there is `moved`), its size (`capBytes` judged on it, never a cut), the read
* judged against the cap again, the lane's binary judgment and its decode — a
* body that is not UTF-8 is not text here (the write tools refuse to rewrite one). No line numbers, no window, no
* dedup, no disclosure plan, and nothing recorded: a text read never stands for the model having read the file.
* `opened`: the answer of the carrier's own `openBound` at the key, read as {@link BoundOpening} with no second open: held ⇒ its
* bytes are read, with no path lookup after the judgment; cannot bind ⇒ by name; refused ⇒ not read (as when this read's own open is refused). */
readText(path: string, ctx: ReadForModelContext, opts: {
judgedKey?: string;
capBytes: number;
opened?: {
key: string;
opening: BoundOpening;
};
}): Promise<TextReading>;
/** Bind a read to the object at a resolved key, for a carrier that judges and then reads that same object (the
* environment's `openBound`, read as {@link BoundOpening}: an environment with no `openBound`, or one that answers
* `not_supported` on the target, cannot bind). The carrier closes the object it is given. */
openBound(key: string, signal?: AbortSignal): Promise<BoundOpening>;
/** One level of a held directory, every entry through the walk's per-entry read-deny judge. */
listDirectory(bound: {
key: string;
object: BoundFileObject;
}, signal?: AbortSignal): Promise<Result<DirectoryListing, FileError>>;
/** Plan the disclosure over external text this reader did not read (the same pipeline, throttle windows and
* counters); the effects commit with the result that carries them. */
planDisclosure(segments: string[], throttleKey: string): {
note?: ReadNote;
effects: ReminderDisclosureEffects;
};
/** Apply the result's effects: the read-state entry (stamped `lastReadAt`, the transmission that carried it
* joining the entry's witness set) and the disclosure windows / counters. Once per result: a second commit throws. */
commit(result: ReadForModelResult, at?: {
transmittedByToolCallId?: string;
now?: number;
}): void;
}
export declare function createModelFileReader(opts: ModelFileReaderOptions): ModelFileReader;
/** The Read carrier's sentence for one note — the bytes the Read tool has always emitted for it. The
* data-adjacent notes (range header, partial marker, fallback prefix, 0-cell placeholder, resize line,
* disclosure trailer) render without their joining separators; {@link renderReadToolResult} places them. */
export declare function renderReadNoteForTool(note: ReadNote, mark: string | undefined): string;
/** The Read tool's result for one read — the composition each lane has always returned. */
export declare function renderReadToolResult(r: ReadForModelResult, mark: string | undefined): ToolReturn;
export declare function createReadFileTool(env: ExecutionEnv, state: ReadFileState, rootCanonical: string, cwdRef?: CwdRef, additionalRoots?: RootsSeat, imageProcessor?: ImageDownsampler | false, pdfCapabilities?: PdfModelCapabilities, bgOutputReadExemption?: (canonicalKey: string, ctx: {
taskId?: string;
isolationScope?: string;
toolCallId?: string;
}) => boolean, readDeny?: import("./read-deny.js").ReadDenyMatcher, readFace?: import("./containment-face.js").ContainmentFace, reminderMark?: string, reminderDisclosureCounts?: ReminderDisclosureCounts, sharedReader?: ModelFileReader): AgentTool;