@sema-agent/core
Version:
Stateless, task-oriented AI agent core
627 lines (626 loc) • 42.2 kB
JavaScript
import { Type } from "typebox";
import { defineTool, errorResult } from "../../core/tools.js";
import { sha256, resolveKey, violationText, violationDetails, binaryMagicFormat, hasBinaryExtension, isBinaryContent, imageMimeForRead, isPdfPath, } from "./safety.js";
import { decodeTextBytes } from "./encoding.js";
import { isNotebookPath, parseNotebookCells, renderNotebookCells, stripNotebookImageData, NOTEBOOK_IMAGE_BASE64_BUDGET } from "./notebook.js";
import { resolveImageProcessor } from "../../core/image-downsample.js";
import { countPdfPagesFromBytes, PDF_MAX_PAGES_PER_READ } from "./pdf.js";
import { MAX_READ_BYTES, SLICED_READ_MAX_BYTES, noProcessorImageCapHint, MAX_READ_OUTPUT_CHARS, BASE_READ_TOKENS, FILE_PATH_PARAMS, countLines, enoentMessage, witnessesAfterDelivery, } from "./fs-shared.js";
import { envErrorDetail } from "./env-error-detail.js";
import { objectOfOpening, openBoundAt, readObjectAt, readWithin, sameKeyAgain } from "./bound-open.js";
import { readPdfFile } from "./fs-pdf.js";
import { seatForCall, seatReady } from "./read-deny.js";
import { thrownText } from "../../core/thrown-value.js";
import { MARKED_BLOCK_AFTER_DATA, openSystemReminder } from "../../core/reminder-mint.js";
import { planReminderDisclosure, commitReminderDisclosureEffects, renderReminderDisclosureTrailer, } from "../../core/reminder-disclosure.js";
import { toolFace } from "../../core/tool-catalog-entries.js";
import { fileArgPath } from "../../core/tool-registry.js";
import { admitImageBytes, IMAGE_ADMISSION, imageReadCap, PDF_TARGET_RAW_SIZE, pdfMagicMatches, unprocessedSizeClause } from "../../core/image-admission.js";
import { createEntryDenyJudge, enumerateDirectory } from "./dir-entries.js";
export const READ_OUTCOMES = Object.freeze(["attached", "partial", "not_attached"]);
function textLaneOf(bytes) {
if (pdfMagicMatches(bytes))
return { kind: "pdf" };
const format = binaryMagicFormat(bytes);
if (format !== undefined)
return { kind: "binary_format", format };
const decoded = decodeTextBytes(bytes);
if (decoded.malformed === "truncated_utf16")
return { kind: "truncated_utf16" };
if (isBinaryContent(decoded.text.slice(0, 8192)))
return { kind: "binary_content" };
return { kind: "text", decoded };
}
const LARGE_READ_CLAUSE = {
read_anyway: " To read it anyway, up to what still fits in your context, call Read again with allow_large: true \u2014 only if you genuinely need all of it or the user asked for the whole file.",
over_room: " Even with allow_large, this is more than fits in the context you have left this turn (other large reads in the same turn share that room).",
unavailable: " allow_large is not available where this read runs; read it in parts with offset and limit.",
};
function raisedReadLimitsOf(ticket) {
if (ticket === undefined)
return undefined;
const room = ticket.room();
if (!(room > BASE_READ_TOKENS))
return undefined;
return { tokens: room, bytes: Math.min(SLICED_READ_MAX_BYTES, Math.max(MAX_READ_BYTES, Math.floor(room * ticket.charsPerToken * 3))) };
}
export function servedReadTokens(body, charsPerToken) {
return Math.max(Math.ceil(body.length / charsPerToken), Math.ceil(Buffer.byteLength(body, "utf8") / 2));
}
function leastServedReadTokens(bytes, charsPerToken) {
const utf8 = Math.ceil(Math.max(0, bytes - 3) / 2);
const units = Math.max(0, Math.floor((bytes - 2) / 2));
const utf16 = Math.max(Math.ceil(units / charsPerToken), Math.ceil(units / 2));
return Math.min(utf8, utf16);
}
const NO_EFFECTS = () => ({ disclosure: [] });
async function admitNotebookImages(blocks, imageProcessor) {
if (!blocks.some((b) => b.type === "image"))
return blocks;
const processor = await resolveImageProcessor(imageProcessor);
return Promise.all(blocks.map(async (b) => {
if (b.type !== "image")
return b;
const a = await admitImageBytes(Buffer.from(b.data, "base64"), b.mimeType, processor);
if (a.ok)
return a.block;
const why = a.reason === "dimensions_unreadable" || a.reason === "dimensions_too_large" ? `: ${unprocessedSizeClause(a)}` : "";
return { type: "text", text: `[image output not shown (media admission: ${a.reason})${why}]` };
}));
}
export function createModelFileReader(opts) {
const { env, state, rootCanonical, cwdRef, imageProcessor, pdfCapabilities, bgOutputReadExemption, readFace, reminderMark, readDeny: readDenySeat, additionalRoots: rootsSeat, contextRoom, outsideRemedy } = opts;
const windows = opts.disclosureWindows ?? new Map();
const refuse = (envelope, kind) => ({
outcome: "not_attached",
...(kind !== undefined ? { kind } : {}),
data: [],
notes: [],
refusal: envelope,
effects: NO_EFFECTS(),
});
const disclosureOf = (segments, outlet, key, throttled = true) => {
const plan = planReminderDisclosure({ segments, mark: reminderMark, outlet, defuseExactMark: false, ...(throttled ? { throttle: { key, windows } } : {}) });
const verdict = plan.verdict;
return { ...(verdict.reminder !== undefined || verdict.envelopeTags !== undefined ? { note: { kind: "disclosure", verdict } } : {}), effects: plan.effects };
};
const resolve = async (path, ctx) => {
if (ctx.toolCallId === undefined)
await seatReady(rootsSeat, ctx.signal);
return resolveKey(env, rootCanonical, path, ctx.signal, cwdRef?.current, seatForCall(rootsSeat, ctx.toolCallId), bgOutputReadExemption === undefined ? undefined : (key) => bgOutputReadExemption(key, ctx), seatForCall(readDenySeat, ctx.toolCallId), readFace, outsideRemedy);
};
const judgedAgain = (path, ctx, key) => sameKeyAgain((signal) => resolve(path, { ...ctx, signal: signal ?? ctx.signal }), key);
const readForModel = async (args, ctx, opts) => {
const opened = {};
try {
return await readOnce(args, ctx, opts, opened);
}
finally {
await opened.object?.close();
}
};
const readOnce = async (args, ctx, opts, opened) => {
const readDeny = seatForCall(readDenySeat, ctx.toolCallId);
const { offset, limit, pages, allow_large: allowLarge } = (args ?? {});
const optedIn = allowLarge === true;
const path = fileArgPath(args);
if (path === undefined)
return refuse(errorResult(`Error (Read): file_path is required.`));
const r = await resolve(path, ctx);
if (!r.ok)
return refuse(errorResult(violationText("Read", r.violation), violationDetails(r.violation)));
const moved = () => refuse(errorResult(`Error (Read): "${path.slice(0, 300)}" resolved to a different file while it was being checked, so it was not read.`, { type: "target_moved" }));
const judgedKey = opts?.bound?.key ?? opts?.judgedKey;
if (judgedKey !== undefined && r.key !== judgedKey)
return moved();
let info;
const sized = async (object) => {
const s = await object.size();
return s.ok ? { ok: true, value: { kind: object.kind, size: s.value, object } } : s;
};
let notOpened = false;
if (opts?.bound !== undefined)
info = await sized(opts.bound.object);
else {
const o = await readObjectAt(env, r.key, judgedAgain(path, ctx, r.key), ctx.signal);
if (!o.ok && o.error.code === "precondition_failed")
return moved();
if (o.ok)
opened.object = o.value;
else
notOpened = o.step === "open";
info = o.ok ? await sized(o.value) : o;
}
const unreadImage = (r) => errorResult(`Error (Read): cannot read image "${path}": ${envErrorDetail(r.error.message)}`);
const unreadPdf = (r) => errorResult(`Error (Read): cannot read PDF "${path.slice(0, 300)}": ${envErrorDetail(r.error.message)}`);
const unreadText = (r) => errorResult(`Error (Read): cannot read "${path}": ${envErrorDetail(r.error.message)}`);
const missing = async (kind) => {
if (opts?.bound !== undefined || opened.object !== undefined)
return undefined;
const ex = await env.exists(r.key, ctx.signal);
if (!ex.ok || ex.value)
return undefined;
return refuse(errorResult(`Error (Read): ${await enoentMessage(env, r.key, cwdRef?.current ?? rootCanonical, ctx.signal, readDeny)}`), kind);
};
if (info.ok && info.value.kind === "directory") {
return refuse(errorResult(`Error (Read): "${path}" is a directory, not a file; use glob/grep or list it with the shell.`), "directory");
}
const isNb = isNotebookPath(r.key);
const imageMime = imageMimeForRead(r.key);
if (imageMime !== undefined) {
const meta = info;
if (!meta.ok) {
return (await missing("image")) ?? refuse(notOpened ? unreadImage(meta) : errorResult(`Error (Read): cannot stat image "${path}" to verify its size before reading: ${envErrorDetail(meta.error.message)}`), "image");
}
const processor = await resolveImageProcessor(imageProcessor);
const readCap = imageReadCap(processor);
const noProcessorHint = processor === "none" ? ` ${noProcessorImageCapHint(imageProcessor)}` : "";
const tooLargeToRead = (bytes) => `Error (Read): image "${path}" is too large to read (${bytes} bytes > ${readCap}-byte cap).${noProcessorHint}`;
if (meta.value.size > readCap)
return refuse(errorResult(tooLargeToRead(meta.value.size)), "image");
const bin = await meta.value.object.readBytes(readCap, ctx.signal);
if (!bin.ok)
return refuse(unreadImage(bin), "image");
const admitted = await admitImageBytes(bin.value, imageMime, processor);
if (!admitted.ok) {
switch (admitted.reason) {
case "raw_too_large":
return refuse(errorResult(tooLargeToRead(bin.value.byteLength)), "image");
case "magic_mismatch":
case "mime_unsupported":
return refuse(errorResult(`Error (Read): "${path}" has an image extension but its content is not a valid ${imageMime} (empty, truncated, or mis-named). If it is text, rename it with a shell command (e.g. mv) to a name that is not an image and read it under that name.`), "image");
case "dimensions_unreadable":
case "dimensions_too_large":
return refuse(errorResult(`Error (Read): image "${path}" cannot be sent: ${unprocessedSizeClause(admitted)}.${noProcessorHint}`), "image");
case "base64_too_large":
return refuse(errorResult(`Error (Read): image "${path}" is too large to send (${bin.value.byteLength} bytes; base64 ${admitted.base64.length} chars exceeds the ${IMAGE_ADMISSION.hard.imageBase64Chars}-char / 5MB API image limit` +
(processor !== "none"
? "; processing could not bring it under the limit)."
: `; raw images over ${IMAGE_ADMISSION.soft.rawBytes} bytes always exceed it — shrink it first, e.g. with an image tool via bash).`)), "image");
}
}
const { block, dimensions, originalSize, resized } = admitted;
return {
outcome: "attached",
kind: "image",
data: [block],
notes: resized && dimensions !== undefined ? [{ kind: "image_resized", dimensions }] : [],
details: {
type: "image",
file: { ...(block.data.length <= 48_000 ? { base64: block.data } : {}), type: block.mimeType, originalSize, ...(dimensions ? { dimensions } : {}) },
},
effects: NO_EFFECTS(),
};
}
const pdfOf = async (preRead) => {
if (opts?.pdfAsReference === true) {
if (!info.ok)
return refuse(notOpened ? unreadPdf(info) : errorResult(`Error (Read): cannot size PDF "${path.slice(0, 300)}": ${envErrorDetail(info.error.message)}`), "pdf");
let held = preRead;
if (held === undefined && info.value.size <= PDF_TARGET_RAW_SIZE) {
const got = await info.value.object.readBytes(PDF_TARGET_RAW_SIZE, ctx.signal);
if (!got.ok)
return refuse(unreadPdf(got), "pdf");
held = got.value;
}
const pageCount = held !== undefined ? countPdfPagesFromBytes(held) : undefined;
return {
outcome: "attached",
kind: "pdf",
data: [],
notes: [{ kind: "pdf_reference", bytes: info.value.size, ...(pageCount !== undefined ? { pages: pageCount } : {}) }],
effects: NO_EFFECTS(),
};
}
if (!info.ok) {
return (await missing("pdf")) ?? refuse(notOpened ? unreadPdf(info) : errorResult(`Error (Read): cannot stat PDF "${path.slice(0, 300)}" to verify its size before reading: ${envErrorDetail(info.error.message)}`), "pdf");
}
const effects = [];
const out = await readPdfFile(env, path, { object: info.value.object, size: info.value.size }, pages, ctx.signal, imageProcessor, preRead, pdfCapabilities, readDeny, {
mark: reminderMark,
windows,
key: r.key,
effects,
});
if (typeof out === "string")
return refuse(errorResult(out), "pdf");
const details = out.details;
const outcome = details?.fallback?.level === 3 ? "not_attached" : details?.file?.timedOut === true ? "partial" : "attached";
return { outcome, kind: "pdf", data: out.content, notes: [], details: out.details, effects: { disclosure: effects } };
};
if (isPdfPath(r.key))
return pdfOf(undefined);
let ticketRead;
const ticketOf = () => (ticketRead ??= contextRoom === undefined ? Promise.resolve(undefined) : contextRoom.open(ctx.toolCallId));
const offerFor = async (size) => {
const t = await ticketOf();
if (t === undefined)
return optedIn ? "unavailable" : undefined;
const limits = raisedReadLimitsOf(t);
if (optedIn || limits === undefined)
return "over_room";
const fits = "bytes" in size ? (size.bytes <= limits.bytes && leastServedReadTokens(size.bytes, t.charsPerToken) <= limits.tokens) : servedReadTokens(size.body, t.charsPerToken) <= limits.tokens;
return fits ? "read_anyway" : "over_room";
};
const clauseFor = async (size) => {
const offer = await offerFor(size);
return offer === undefined ? "" : LARGE_READ_CLAUSE[offer];
};
const ticket = optedIn ? await ticketOf() : undefined;
const raised = raisedReadLimitsOf(ticket);
const bytesCap = raised?.bytes ?? MAX_READ_BYTES;
let wholeCap = bytesCap;
const binaryExt = hasBinaryExtension(r.key);
const binaryExtRefusal = () => refuse(errorResult(`Error (Read): "${path}" appears to be a binary file (by extension); this tool reads UTF-8 text only. Inspect or convert it with bash instead.`), "text");
const tooLargeInFull = (size, cap, clause) => refuse(errorResult(`Error (Read): "${path}" is too large to read in full (${size} bytes > ${cap}-byte cap); pass an explicit offset/limit to read a slice, or use grep to search it instead.${clause}`), "text");
if (info.ok) {
if (info.value.size > SLICED_READ_MAX_BYTES) {
if (binaryExt)
return binaryExtRefusal();
return refuse(errorResult(`Error (Read): "${path}" is too large to read with this tool even as an offset/limit slice ` +
`(${info.value.size} bytes > ${SLICED_READ_MAX_BYTES}-byte cap — the reader loads the whole file into memory before slicing). ` +
`Stream a portion with bash instead, e.g. \`sed -n '1,200p' <file>\` for a line range or \`head -c 65536 <file>\` for the leading bytes, or use grep to search it.`), "text");
}
if (!isNb && info.value.size > bytesCap && limit === undefined) {
if (binaryExt)
return binaryExtRefusal();
const offer = await offerFor({ bytes: info.value.size });
if (offer !== "read_anyway")
return tooLargeInFull(info.value.size, bytesCap, offer === undefined ? "" : LARGE_READ_CLAUSE[offer]);
wholeCap = raisedReadLimitsOf(await ticketOf())?.bytes ?? bytesCap;
}
}
else {
return (await missing("text")) ?? refuse(notOpened ? unreadText(info) : errorResult(`Error (Read): cannot determine the type of "${path.slice(0, 300)}" (stat failed: ${envErrorDetail(info.error.message)}); refusing to open it — if it is a FIFO/socket/device, reading it would hang. Retry if this was transient, or inspect it with Bash (e.g. \`file\`, \`ls -l\`).`), "text");
}
const readBin = await info.value.object.readBytes(!isNb && limit === undefined ? wholeCap : SLICED_READ_MAX_BYTES, ctx.signal);
if (!readBin.ok)
return refuse(unreadText(readBin), "text");
const lane = textLaneOf(readBin.value);
if (lane.kind === "pdf")
return pdfOf(readBin.value);
if (lane.kind === "binary_format") {
return refuse(errorResult(`Error (Read): "${path}" appears to be a binary file (${lane.format}, identified by its file signature — whatever its extension says); ` +
`this tool reads UTF-8 and BOM-marked UTF-16LE text only. Inspect or convert it with bash instead.`), "text");
}
if (lane.kind === "truncated_utf16") {
return refuse(errorResult(`Error (Read): "${path}" has a UTF-16 BOM but a truncated (odd-length) body — the file is corrupt or mis-labelled; repair/convert it with bash (e.g. \`iconv\`) first.`), "text");
}
if (lane.kind === "binary_content") {
return refuse(errorResult(`Error (Read): "${path}" appears to be a binary file (non-text content); this tool reads UTF-8 and BOM-marked UTF-16LE text only. ` +
`If it is UTF-16 without a BOM or a legacy encoding, convert it first (e.g. \`iconv -f UTF-16LE -t UTF-8\`) or inspect/transform it with bash.`), "text");
}
const decoded = lane.decoded;
const content = decoded.text;
const nbParsed = isNb ? parseNotebookCells(content, path) : undefined;
const nbForced = nbParsed !== undefined && nbParsed.ok;
const effOffset = nbForced ? undefined : offset;
const effLimit = nbForced ? undefined : limit;
const lines = content.length === 0 ? [] : content.split("\n");
const total = lines.length;
const start = Math.max(1, Math.floor(effOffset ?? 1));
const max = effLimit !== undefined ? Math.max(1, Math.floor(effLimit)) : Number.MAX_SAFE_INTEGER;
if (total > 0 && start > total) {
const observation = { key: r.key, entry: { hash: sha256(content), totalLines: countLines(content), truncated: true, view: { start, end: start - 1 } } };
const details = { type: "text", file: { filePath: path, content: "", numLines: 0, startLine: start, totalLines: total } };
return { outcome: "not_attached", kind: "text", data: [], notes: [{ kind: "past_eof", offset: start, totalLines: total }], details, observation, effects: NO_EFFECTS() };
}
let slice = lines.slice(start - 1, start - 1 + max);
let end = start - 1 + slice.length;
if (end === total - 1 && lines[total - 1] === "") {
slice = lines.slice(start - 1, total);
end = total;
}
const hash = sha256(content);
const notes = [];
if (nbParsed !== undefined) {
if (nbParsed.ok) {
const parsed = nbParsed;
const rendered = renderNotebookCells(parsed.cells, NOTEBOOK_IMAGE_BASE64_BUDGET);
if (rendered.textChars > MAX_READ_OUTPUT_CHARS) {
return refuse(errorResult(`Error (Read): notebook "${path}" projects to ~${Math.round(rendered.textChars / 4)} tokens of cell content, over the ${BASE_READ_TOKENS}-token limit ` +
`(offset/limit do not apply to notebooks — the whole notebook is always projected). Inspect portions with Bash + jq instead, e.g.\n` +
` cat "${path}" | jq '.cells[:20]' # First 20 cells\n` +
` cat "${path}" | jq '.cells | length' # Count total cells\n` +
` cat "${path}" | jq '.cells[] | select(.cell_type=="code") | .source' # All code sources`), "notebook");
}
const observation = { key: r.key, entry: { hash, totalLines: countLines(content), truncated: false, view: { start: 1, end: total } } };
if (rendered.blocks.length === 0)
notes.push({ kind: "notebook_no_cells" });
const disclosure = disclosureOf(rendered.blocks.filter((b) => b.type === "text").map((b) => b.text), "notebook", r.key, opts?.freshContext !== true);
if (disclosure.note !== undefined)
notes.push(disclosure.note);
return {
outcome: "attached",
kind: "notebook",
data: await admitNotebookImages(rendered.blocks, imageProcessor),
notes,
details: { type: "notebook", file: { filePath: path, cells: parsed.cells.map(stripNotebookImageData) } },
observation,
effects: { disclosure: [disclosure.effects] },
};
}
notes.push({ kind: "notebook_fallback" });
}
const renderBody = (sl) => sl.map((l, i) => `${start + i}\t${l}`).join("\n");
let body = renderBody(slice);
let partial;
const booked = raised !== undefined && ticket !== undefined ? { ticket, tokens: servedReadTokens(body, ticket.charsPerToken) } : undefined;
const lifted = booked !== undefined ? raisedReadLimitsOf(booked.ticket) : undefined;
const overBaseBytes = !isNb && limit === undefined && readBin.value.length > MAX_READ_BYTES;
if ((body.length > MAX_READ_OUTPUT_CHARS || overBaseBytes) && (lifted === undefined || booked === undefined || booked.tokens > lifted.tokens)) {
if (overBaseBytes)
return tooLargeInFull(readBin.value.length, MAX_READ_BYTES, await clauseFor({ body }));
const defaultFullRead = start <= 1 && effLimit === undefined;
const room = lifted !== undefined && booked !== undefined ? lifted.tokens : undefined;
const approxTokens = room !== undefined && booked !== undefined ? booked.tokens : Math.round(body.length / 4);
const offer = await offerFor({ body });
if (!defaultFullRead) {
return refuse(errorResult(`Error (Read): the requested range of "${path}" is ~${approxTokens} tokens, over the ${room ?? BASE_READ_TOKENS}-token limit. Narrow it with offset/limit, or use grep to search the file.${offer === undefined ? "" : LARGE_READ_CLAUSE[offer]}`), "text");
}
const told = { ...(room !== undefined ? { room } : {}), ...(offer !== undefined ? { offer } : {}) };
let n = Math.max(1, Math.min(slice.length, Math.floor(slice.length * (MAX_READ_OUTPUT_CHARS / body.length) * 0.95)));
let paged = slice.slice(0, n);
let pagedBody = renderBody(paged);
for (let attempt = 0; attempt < 8 && pagedBody.length > MAX_READ_OUTPUT_CHARS && n > 1; attempt++) {
n = Math.max(1, Math.floor(n * 0.7));
paged = slice.slice(0, n);
pagedBody = renderBody(paged);
}
if (pagedBody.length <= MAX_READ_OUTPUT_CHARS) {
slice = paged;
end = start - 1 + slice.length;
body = pagedBody;
partial = { kind: "partial_page", end, total, approxTokens, ...told };
}
else {
let cut = MAX_READ_OUTPUT_CHARS - 200;
const cc = slice[0].charCodeAt(cut - 1);
if (cc >= 0xd800 && cc <= 0xdbff)
cut -= 1;
slice = [slice[0].slice(0, cut)];
end = start;
body = renderBody(slice);
partial = { kind: "partial_chars", cut, totalChars: content.length, approxTokens, ...told };
}
}
const truncated = start > 1 || end < total || partial !== undefined;
if (booked !== undefined && partial === undefined)
booked.ticket.claim(booked.tokens);
const observation = {
key: r.key,
entry: { hash, totalLines: countLines(content), truncated, ...(partial !== undefined ? { isPartialView: true } : {}), view: { start, end } },
};
if (total === 0)
return { outcome: "attached", kind: "text", data: [], notes: [...notes, { kind: "empty_file" }], details: { type: "text", file: { filePath: path, content: "", numLines: 0, startLine: 1, totalLines: 0 } }, observation, effects: NO_EFFECTS() };
if (partial !== undefined)
notes.push(partial);
else if (truncated)
notes.push({ kind: "range", path, start, end, total });
const disclosure = disclosureOf([body], "read", r.key, opts?.freshContext !== true);
if (disclosure.note !== undefined)
notes.push(disclosure.note);
return {
outcome: partial !== undefined ? "partial" : "attached",
kind: "text",
data: [{ type: "text", text: body }],
notes,
details: {
type: "text",
file: {
filePath: path,
content: slice.join("\n"),
numLines: slice.length,
startLine: start,
totalLines: total,
...(partial !== undefined ? { truncatedByTokenCap: true } : {}),
},
},
observation,
effects: { disclosure: [disclosure.effects] },
};
};
const committed = new WeakSet();
return {
readForModel,
async resolveTarget(path, ctx) {
const r = await resolve(path, ctx).catch((err) => ({ ok: false, violation: { code: "invalid", message: thrownText(err) } }));
return r.ok ? { ok: true, key: r.key } : { ok: false, refusal: errorResult(violationText("Read", r.violation), violationDetails(r.violation)) };
},
async readText(path, ctx, { judgedKey, capBytes, opened }) {
const r = await resolve(path, ctx).catch(() => undefined);
if (r === undefined || !r.ok)
return { kind: "refused" };
if (judgedKey !== undefined && r.key !== judgedKey)
return { kind: "moved" };
if (opened !== undefined && opened.key !== r.key)
return { kind: "moved" };
if (opened?.opening.kind === "bound") {
const object = opened.opening.object;
if (object.kind === "directory")
return { kind: "not_text" };
const held = await object.readBytes(capBytes, ctx.signal);
if (!held.ok)
return held.error.code === "invalid" ? { kind: "oversize" } : { kind: "unavailable" };
const heldLane = textLaneOf(held.value);
return heldLane.kind === "text" && heldLane.decoded.malformed === undefined ? { kind: "text", text: heldLane.decoded.text } : { kind: "not_text" };
}
const rejudge = judgedAgain(path, ctx, r.key);
const o = opened !== undefined ? await objectOfOpening(env, r.key, rejudge, opened.opening, ctx.signal) : await readObjectAt(env, r.key, rejudge, ctx.signal);
if (!o.ok) {
if (o.error.code === "precondition_failed")
return { kind: "moved" };
const ex = await env.exists(r.key, ctx.signal);
return ex.ok && !ex.value ? { kind: "absent" } : { kind: "unavailable" };
}
try {
if (o.value.kind === "directory")
return { kind: "not_text" };
const read = await readWithin(o.value, capBytes, ctx.signal);
if (read.kind === "over")
return { kind: "oversize" };
if (read.kind === "failed")
return { kind: read.error.code === "precondition_failed" ? "moved" : "unavailable" };
const lane = textLaneOf(read.bytes);
return lane.kind === "text" && lane.decoded.malformed === undefined ? { kind: "text", text: lane.decoded.text } : { kind: "not_text" };
}
finally {
await o.value.close();
}
},
openBound: (key, signal) => openBoundAt(env, key, signal),
listDirectory: (bound, signal) => enumerateDirectory(env, bound.key, readDenySeat !== undefined ? createEntryDenyJudge(env, readDenySeat, signal) : undefined, signal, () => bound.object.list(signal)),
planDisclosure(segments, throttleKey) {
const d = disclosureOf(segments, "read", throttleKey);
return { ...(d.note !== undefined ? { note: d.note } : {}), effects: d.effects };
},
commit(result, at) {
if (committed.has(result))
throw new Error("ModelFileReader.commit: this read result was already committed — a delivery commits its read once");
committed.add(result);
if (result.observation !== undefined) {
const entry = result.observation.entry;
const prior = state.get(result.observation.key);
const witnesses = witnessesAfterDelivery(prior, entry, at?.transmittedByToolCallId);
state.set(result.observation.key, {
...entry,
lastReadAt: at?.now ?? Date.now(),
...(witnesses.length > 0 ? { witnesses } : {}),
});
}
for (const e of result.effects.disclosure)
commitReminderDisclosureEffects(e, { counts: opts.reminderDisclosureCounts, windows });
},
};
}
const partialCapPhrase = (room) => (room !== undefined ? `allow_large had room for ${room} tokens this turn` : `cap ${BASE_READ_TOKENS}`);
const partialOfferClause = (offer) => (offer !== undefined ? LARGE_READ_CLAUSE[offer] : "");
export function renderReadNoteForTool(note, mark) {
switch (note.kind) {
case "empty_file":
return `${openSystemReminder(mark)}Warning: the file exists but the contents are empty.</system-reminder>`;
case "past_eof":
return `${openSystemReminder(mark)}Warning: the file exists but is shorter than the provided offset (${note.offset}). The file has ${note.totalLines} lines.</system-reminder>`;
case "range":
return `[${note.path}: lines ${note.start}-${note.end} of ${note.total}${note.end < note.total ? " — use offset to see more" : ""}]\n`;
case "partial_page":
return (`[Truncated: PARTIAL view — showing lines 1-${note.end} of ${note.total} total (~${note.approxTokens} tokens, ${partialCapPhrase(note.room)}). ` +
`Call Read with offset=${note.end + 1} limit=${note.end} for the next page, or Grep to find a specific section.${partialOfferClause(note.offer)} ` +
`Do NOT answer from this page alone if the answer may be further in the file.]\n`);
case "partial_chars":
return (`[Truncated: PARTIAL view — showing the first ${note.cut} of ${note.totalChars} characters (~${note.approxTokens} tokens, ${partialCapPhrase(note.room)}); ` +
`this file has very long lines and cannot be paginated by line. Use Grep to find a specific section, or Read with offset/limit to page through it.${partialOfferClause(note.offer)} ` +
`Do NOT answer from this excerpt alone if the answer may be elsewhere in the file.]\n`);
case "notebook_fallback":
return "[not a parseable notebook — showing raw file text]\n";
case "notebook_no_cells":
return "[notebook has 0 cells]";
case "image_resized": {
const d = note.dimensions;
return `[Image: original ${d.originalWidth}x${d.originalHeight}, displayed at ${d.displayWidth}x${d.displayHeight}. Multiply coordinates by ${(d.originalWidth / d.displayWidth).toFixed(2)} to map to original image.]`;
}
case "disclosure":
return renderReminderDisclosureTrailer(note.verdict, mark) ?? "";
case "pdf_reference":
return `[PDF not read: ${note.bytes !== undefined ? `${note.bytes} bytes` : "size unknown"}, ${note.pages !== undefined ? `${note.pages} page${note.pages === 1 ? "" : "s"}` : "page count unknown"}. Read it with the pages parameter, at most ${PDF_MAX_PAGES_PER_READ} pages per request.]`;
}
}
export function renderReadToolResult(r, mark) {
if (r.refusal !== undefined)
return r.refusal;
const noteOf = (kind) => r.notes.find((n) => n.kind === kind);
const lead = r.notes.find((n) => n.kind === "past_eof" || n.kind === "empty_file");
if (lead !== undefined)
return r.details !== undefined ? { content: renderReadNoteForTool(lead, mark), details: r.details } : renderReadNoteForTool(lead, mark);
const disclosure = noteOf("disclosure");
const trailer = disclosure !== undefined ? renderReadNoteForTool(disclosure, mark) : undefined;
switch (r.kind) {
case "pdf":
return { content: r.data, details: r.details };
case "image": {
const resized = noteOf("image_resized");
return { content: [...r.data, ...(resized !== undefined ? [{ type: "text", text: renderReadNoteForTool(resized, mark) }] : [])], details: r.details };
}
case "notebook": {
const noCells = noteOf("notebook_no_cells");
return {
content: [
...(noCells !== undefined ? [{ type: "text", text: renderReadNoteForTool(noCells, mark) }] : r.data),
...(trailer !== undefined ? [{ type: "text", text: `${MARKED_BLOCK_AFTER_DATA}${trailer}` }] : []),
],
details: r.details,
};
}
default: {
const fallback = noteOf("notebook_fallback");
const header = noteOf("partial_page") ?? noteOf("partial_chars") ?? noteOf("range");
const body = r.data[0]?.text ?? "";
return {
content: `${fallback !== undefined ? renderReadNoteForTool(fallback, mark) : ""}${header !== undefined ? renderReadNoteForTool(header, mark) : ""}${body}${trailer !== undefined ? `${MARKED_BLOCK_AFTER_DATA}${trailer}` : ""}`,
details: r.details,
};
}
}
}
export function createReadFileTool(env, state, rootCanonical, cwdRef, additionalRoots, imageProcessor, pdfCapabilities, bgOutputReadExemption, readDeny, readFace, reminderMark, reminderDisclosureCounts, sharedReader) {
const reader = sharedReader ?? createModelFileReader({
env,
state,
rootCanonical,
...(cwdRef !== undefined ? { cwdRef } : {}),
...(additionalRoots !== undefined ? { additionalRoots } : {}),
imageProcessor,
...(pdfCapabilities !== undefined ? { pdfCapabilities } : {}),
...(bgOutputReadExemption !== undefined ? { bgOutputReadExemption } : {}),
...(readDeny !== undefined ? { readDeny } : {}),
...(readFace !== undefined ? { readFace } : {}),
...(reminderMark !== undefined ? { reminderMark } : {}),
...(reminderDisclosureCounts !== undefined ? { reminderDisclosureCounts } : {}),
});
const pathBoundLine = readFace === "open"
? "- `file_path` may be relative (resolved against the tracked working directory) or absolute. Reads are not confined to the workspace roots; a small sensitive-path deny list applies.\n"
: "- `file_path` may be relative (resolved against the tracked working directory) or absolute (within the configured roots).\n";
return defineTool({
name: "Read",
...toolFace("read"),
description: "Reads a file from the local filesystem.\n" +
"\n" +
pathBoundLine +
"- By default, it reads the whole file (from `offset`, 1-based); a very large file is served as a partial view with an explicit marker and the next-page call.\n" +
"- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters\n" +
"- Results are returned using cat -n format, with line numbers starting at 1\n" +
"- Reads images (PNG, JPG, …) and presents them visually. Reads PDFs via the `pages` parameter (e.g. \"1-5\", max 20 pages/request; a PDF whose detected page count exceeds 10 requires `pages`). Reads Jupyter notebooks (.ipynb) as cells with outputs (offset/limit do not apply).\n" +
"- Reading a directory, a missing file, or an empty file returns an error or system reminder rather than content.\n" +
"- Other binaries (archives, executables) are refused. A whole-file read of a text file over 256 KB is refused unless `allow_large` is set and the file fits the context left this turn — read it in slices with explicit offset/limit, or Grep it instead.\n" +
"- You must read a file before editing it.\n" +
"- Do NOT re-read a file you just edited to verify — Edit/Write would have errored if the change failed, and the harness tracks file state for you.",
descriptionVariants: [{ id: "classic", traits: { noneOf: ["lean_prompt"] }, text: "Reads a file from the local filesystem.\n" +
"\n" +
"Usage:\n" +
"- By default, it reads the whole file (from `offset`, 1-based); a very large file is served as a partial view with an explicit marker and the next-page call\n" +
"- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters\n" +
"- Results are returned using cat -n format, with each line prefixed by its line number and a tab\n" +
"- This tool allows the model to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually.\n" +
"- This tool can only read files, not directories. To read a directory, use Glob/Grep or an ls command via the Bash tool.\n" +
"- You must read a file before editing it.\n" +
"- Reads PDFs (.pdf): the document is provided to the model directly (text layer included). Use the `pages` parameter (e.g., \"1-5\") to read a page range; a PDF whose detected page count exceeds 10 requires `pages`. Maximum 20 pages per request.\n" +
"- Reads Jupyter notebooks (.ipynb) as cells with outputs (offset/limit do not apply).\n" +
"- Other binaries (archives, executables) are refused. A whole-file read of a text file over 256 KB is refused unless `allow_large` is set and the file fits the context left this turn — read it in slices with explicit offset/limit, or Grep it instead.\n" +
"- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n" +
"- Do NOT re-read a file you just edited to verify — Edit/Write would have errored if the change failed, and the harness tracks file state for you." }],
parameters: Type.Object({
...FILE_PATH_PARAMS,
offset: Type.Optional(Type.Integer({ minimum: 0, description: "The line number to start reading from. Only provide if the file is too large to read at once (1-based; default 1)." })),
limit: Type.Optional(Type.Integer({ minimum: 1, description: "The number of lines to read. Only provide if the file is too large to read at once. (Default: the whole file, bounded by the output-token cap.)" })),
pages: Type.Optional(Type.String({ description: `Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum ${PDF_MAX_PAGES_PER_READ} pages per request.` })),
allow_large: Type.Optional(Type.Boolean({
description: "Set to true to read a text file, or a line range of one, that is over the usual size limits, up to what still fits in your context. Only use this when you genuinely need all of it or the user asked for the whole file; otherwise read it in parts with offset and limit, or search it.",
})),
}),
execute: async (args, ctx) => {
const result = await reader.readForModel(args, ctx);
reader.commit(result, { transmittedByToolCallId: ctx.toolCallId });
return renderReadToolResult(result, reminderMark);
},
});
}