@sema-agent/core
Version:
Stateless, task-oriented AI agent core
480 lines (479 loc) • 21.3 kB
JavaScript
import { createHash } from "node:crypto";
import { changedFilesNoticesOf, SECOND_RESULT_SEPARATOR, userAttachmentOf } from "../internal/llm.js";
import { MARKED_BLOCK_AFTER_DATA, mintSystemReminder, openSystemReminder } from "./reminder-mint.js";
import { isCleared } from "./context-edit.js";
import { pathConfinableWriteToolNames } from "./tool-registry.js";
import { writeTargetPath } from "../tools/fs/safety.js";
export const READ_TOOL_NAMES = new Set(["read", "Read", "read_file"]);
const sha256 = (text) => createHash("sha256").update(text, "utf8").digest("hex");
const WHOLE_VIEW = "whole";
const wholeIdentity = (hash) => `w:${hash}`;
const isRecord = (v) => typeof v === "object" && v !== null;
const textOf = (content) => {
if (typeof content === "string")
return content;
if (!Array.isArray(content))
return undefined;
const items = content;
let out = "";
for (const b of items) {
if (!isRecord(b) || b.type !== "text" || typeof b.text !== "string")
return undefined;
out += b.text;
}
return out;
};
const RETIRED_READ_STUB = /^\[([\s\S]+): unchanged since you last read it \(lines (\d+)-(\d+) of (\d+)\); content omitted to save context\]$/;
const SEEDED_BODY = 'This file is already in your context (see "Contents of ';
const SEEDED_TAIL = '" above) and has not changed on disk. Use that content instead of re-reading.</system-reminder>';
const BARE_OPEN = openSystemReminder(undefined);
function retiredSeededPath(text) {
const at = text.indexOf(SEEDED_BODY);
if (at <= 0 || !text.endsWith(SEEDED_TAIL))
return undefined;
const open = text.slice(0, at);
const mark = /^ mark="([^"]*)">$/.exec(open.slice(BARE_OPEN.length - 1))?.[1];
if (open !== BARE_OPEN && (mark === undefined || open !== openSystemReminder(mark)))
return undefined;
const path = text.slice(at + SEEDED_BODY.length, text.length - SEEDED_TAIL.length);
return path.length > 0 ? path : undefined;
}
export function isRetiredDedupStub(m) {
return retiredOf(m) !== undefined;
}
function retiredOf(m) {
if (!isRecord(m))
return undefined;
const frame = userAttachmentOf(m);
if (frame !== undefined) {
const outcome = frame.outcome;
return outcome === "unchanged" ? { carrier: "frame", attachment: frame, retired: true } : undefined;
}
if (m.role !== "toolResult" || m.isError === true || isCleared(m))
return undefined;
const details = m.details;
if (isRecord(details) && details.type === "file_unchanged") {
const file = isRecord(details.file) ? details.file : {};
const filePath = typeof file.filePath === "string" ? file.filePath : "the file";
const start = file.startLine, end = file.endLine, total = file.totalLines;
const window = typeof start === "number" && typeof end === "number" && typeof total === "number" ? { start, end, total } : undefined;
return { carrier: "read", filePath, ...(window !== undefined ? { window } : {}), retired: true };
}
if (typeof m.toolName !== "string" || !READ_TOOL_NAMES.has(m.toolName))
return undefined;
if (isRecord(details) && typeof details.type === "string")
return undefined;
const text = textOf(m.content);
if (text === undefined)
return undefined;
const plain = RETIRED_READ_STUB.exec(text);
if (plain !== null)
return { carrier: "read", filePath: plain[1], window: { start: Number(plain[2]), end: Number(plain[3]), total: Number(plain[4]) }, retired: true };
const seeded = retiredSeededPath(text);
if (seeded !== undefined)
return { carrier: "read", filePath: seeded, retired: true };
return undefined;
}
const identities = new WeakMap();
function copyOf(m) {
if (!isRecord(m))
return undefined;
const memo = identities.get(m);
if (memo !== undefined)
return memo ?? undefined;
const copy = mintCopy(m);
identities.set(m, copy ?? null);
return copy;
}
function frameLinesOf(m, frame, start, wholeText) {
const blocks = Array.isArray(m.content) ? m.content.slice(frame.dataBlocks.start, frame.dataBlocks.end) : [];
const text = textOf(blocks);
if (text === undefined || text === "")
return undefined;
const rows = text.split("\n");
const lines = [];
for (const [i, row] of rows.entries()) {
const tab = row.indexOf("\t");
if (tab < 0 || row.slice(0, tab) !== String(start + i))
return wholeText ? { start: 1, lines: rows } : undefined;
lines.push(row.slice(tab + 1));
}
return { start, lines };
}
function sightOf(m) {
const frame = userAttachmentOf(m);
if (frame !== undefined) {
const obs = frame.observation;
if (obs === undefined || frame.supply !== "path" || (frame.kind !== "text" && frame.kind !== "notebook"))
return undefined;
if ((frame.outcome !== "attached" && frame.outcome !== "partial") || obs.entry.totalLines <= 0)
return undefined;
if (frame.dataBlocks.end <= frame.dataBlocks.start)
return undefined;
const cut = frame.outcome !== "attached" || obs.entry.isPartialView === true;
const view = obs.entry.view;
const whole = obs.entry.truncated === false;
const shownView = frame.kind === "notebook" ? "nbf" : whole ? WHOLE_VIEW : `fr:${view?.start ?? 0}-${view?.end ?? 0}`;
const lines = frame.kind === "text" ? frameLinesOf(m, frame, view?.start ?? 1, whole && !cut) : undefined;
const shown = lines !== undefined && cut ? { ...lines, cutLast: true } : lines;
const paths = [frame.label, obs.key];
const mint = () => ({
carrier: "frame",
attachment: frame,
identity: frame.kind === "notebook" ? `nbf:${obs.entry.hash}` : whole ? wholeIdentity(obs.entry.hash) : `fr:${obs.entry.hash}:${view?.start ?? 0}-${view?.end ?? 0}`,
view: shownView,
...(shown !== undefined ? { shown } : {}),
paths,
});
return { view: shownView, ...(shown !== undefined ? { shown } : {}), paths, cut, mint };
}
if (m.role !== "toolResult" || m.isError === true || typeof m.toolName !== "string" || !READ_TOOL_NAMES.has(m.toolName))
return undefined;
if (isCleared(m))
return undefined;
const details = m.details;
if (!isRecord(details) || !isRecord(details.file) || typeof details.file.filePath !== "string")
return undefined;
const file = details.file;
const filePath = details.file.filePath;
if (details.type === "text") {
const content = file.content, start = file.startLine, numLines = file.numLines, total = file.totalLines;
if (typeof content !== "string" || typeof start !== "number" || typeof numLines !== "number" || typeof total !== "number")
return undefined;
if (total <= 0 || numLines <= 0)
return undefined;
const end = start + numLines - 1;
const whole = start === 1 && end === total;
const view = whole ? WHOLE_VIEW : `rr:${start}-${end}`;
const cut = file.truncatedByTokenCap === true;
const shown = { start, lines: content.split("\n"), ...(cut ? { cutLast: true } : {}) };
const mint = () => {
const hash = sha256(content);
return { carrier: "read", filePath, window: { start, end, total }, identity: whole ? wholeIdentity(hash) : `rr:${hash}:${start}-${end}:${total}`, view, shown, paths: [filePath] };
};
return { view, shown, paths: [filePath], cut, mint };
}
if (details.type === "notebook") {
if (!Array.isArray(file.cells) || file.cells.length === 0)
return undefined;
return { view: "nbr", paths: [filePath], cut: false, mint: () => ({ carrier: "read", filePath, identity: `nbr:${sha256(JSON.stringify(m.content))}`, view: "nbr", paths: [filePath] }) };
}
return undefined;
}
function mintCopy(m) {
const s = sightOf(m);
return s === undefined || s.cut ? undefined : s.mint();
}
function glimpseOf(m) {
if (!isRecord(m))
return undefined;
const s = sightOf(m);
return s === undefined || !s.cut ? undefined : { glimpse: true, view: s.view, ...(s.shown !== undefined ? { shown: s.shown } : {}), paths: s.paths };
}
function deliveryOf(m) {
return copyOf(m) ?? retiredOf(m) ?? glimpseOf(m);
}
function contradicts(a, b) {
if (a.view === b.view)
return true;
if (a.shown === undefined || b.shown === undefined)
return false;
const aEnd = a.shown.start + a.shown.lines.length;
const bEnd = b.shown.start + b.shown.lines.length;
for (let n = Math.max(a.shown.start, b.shown.start); n < Math.min(aEnd, bEnd); n++) {
if ((a.shown.cutLast === true && n === aEnd - 1) || (b.shown.cutLast === true && n === bEnd - 1))
return true;
if (a.shown.lines[n - a.shown.start] !== b.shown.lines[n - b.shown.start])
return true;
}
return false;
}
const baseName = (p) => p.split(/[\\/]/).pop() ?? p;
function writtenNames(m) {
const withdrawn = userAttachmentOf(m)?.withdraws;
if (withdrawn !== undefined)
return [baseName(withdrawn)];
if (!isRecord(m) || m.role !== "assistant" || !Array.isArray(m.content))
return [];
const writers = pathConfinableWriteToolNames();
const blocks = m.content;
const out = [];
for (const b of blocks) {
if (!isRecord(b) || b.type !== "toolCall" || typeof b.name !== "string" || !writers.has(b.name))
continue;
const target = writeTargetPath({ toolName: b.name, args: b.arguments });
if (target !== undefined)
out.push(baseName(target));
}
return out;
}
const sameFile = (spelling, key) => spelling === key || baseName(spelling) === baseName(key);
const holds = (h, spelling) => h.paths.has(spelling) || (h.seed === true && [...h.paths].some((key) => sameFile(spelling, key)));
class CopyWalk {
input;
heads = new Map();
told = new Set();
constructor(input) {
this.input = input;
for (const [key, hash] of input.seeded ?? []) {
const identity = wholeIdentity(hash);
this.heads.set(identity, [...(this.heads.get(identity) ?? []), { paths: new Set([key]), pointer: false, view: WHOLE_VIEW, seed: true }]);
}
}
toldBefore(f) {
const key = `${f.mtimeMs}\u0000${f.path}`;
if (this.told.has(key))
return true;
this.told.add(key);
return false;
}
end(ends) {
let ended = false;
for (const [identity, list] of this.heads) {
const kept = list.filter((h) => !ends(h, identity));
if (kept.length < list.length)
ended = true;
if (kept.length === 0)
this.heads.delete(identity);
else if (kept.length < list.length)
this.heads.set(identity, kept);
}
return ended;
}
write(names) {
if (names.length === 0)
return;
const hit = new Set(names);
this.end((h) => [...h.paths].some((p) => hit.has(baseName(p))));
}
endContradicted(d, sparesSeeds = false) {
return this.end((h, identity) => identity !== d.identity && !(sparesSeeds && h.seed === true) && d.paths.some((p) => holds(h, p)) && contradicts(h, d));
}
decide(d) {
if ("retired" in d)
return "pointer";
if ("glimpse" in d) {
this.endContradicted(d);
return "contents";
}
const standsFor = d.carrier === "frame";
const pointer = this.input.degraded?.has(d.identity) === true;
const list = this.heads.get(d.identity) ?? [];
const joined = list.filter((h) => d.paths.some((p) => holds(h, p)));
const head = joined[0];
const ended = this.endContradicted(d, head?.seed === true);
if (head !== undefined) {
if (head.shown === undefined && d.shown !== undefined)
head.shown = d.shown;
const chains = joined.filter((h) => h.seed !== true);
const keep = chains[0];
if (keep !== undefined) {
for (const p of d.paths)
keep.paths.add(p);
for (const h of chains.slice(1))
for (const p of h.paths)
keep.paths.add(p);
if (chains.length > 1)
this.heads.set(d.identity, list.filter((h) => !chains.slice(1).includes(h)));
}
if (!standsFor || ended)
return pointer ? "pointer" : "contents";
return head.seed === true ? "seeded" : head.pointer ? "pointer" : "not_repeated";
}
this.heads.set(d.identity, [...list, { paths: new Set(d.paths), pointer, view: d.view, ...(d.shown !== undefined ? { shown: d.shown } : {}) }]);
return pointer ? "pointer" : "contents";
}
}
function readPointerSentence(r) {
const w = r.window;
return w !== undefined
? `[${r.filePath}: lines ${w.start}-${w.end} of ${w.total} — contents not included in this result; read the file again if you need them]`
: `[${r.filePath}: contents not included in this result; read the file again if you need them]`;
}
function frameSentence(rendering) {
switch (rendering) {
case "not_repeated":
return "The file has not changed since you last read it, so its contents are not repeated.";
case "seeded":
return "This file is already in your context and has not changed, so its contents are not repeated.";
case "pointer":
return "Its contents are not included with this message. Use the Read tool if you need them.";
}
}
function renderFrame(m, a, rendering, input) {
const blocks = Array.isArray(m.content) ? m.content : [];
const head = blocks.slice(0, a.dataBlocks.start);
const closing = blocks.length > a.dataBlocks.end ? blocks.slice(-1) : [];
const sentence = { type: "text", text: `${MARKED_BLOCK_AFTER_DATA}${mintSystemReminder(frameSentence(rendering), input.mark)}` };
return Object.assign({}, m, { content: [...head, sentence, ...closing] });
}
export function projectRequestView(view, input = {}) {
const walk = new CopyWalk(input);
let out;
view.forEach((m, i) => {
walk.write(writtenNames(m));
const rendered = renderOne(m, walk, input);
if (rendered !== m)
(out ??= view.slice())[i] = rendered;
});
if (out === undefined)
return view;
const sent = out;
sent.forEach((m, i) => {
if (m !== undefined)
return;
const before = sent.slice(0, i).findLast((x) => x !== undefined);
const after = sent.slice(i + 1).find((x) => x !== undefined);
if (before !== undefined && messageRole(before) === "assistant" && (after === undefined || messageRole(after) === "assistant"))
sent[i] = view[i];
});
return sent;
}
const messageRole = (m) => (isRecord(m) ? m.role : undefined);
export function projectRequestCopies(view, input = {}) {
const sent = projectRequestView(view, input);
return sent === view ? view : sent.filter((m) => m !== undefined);
}
function renderOne(m, walk, input) {
if (!isRecord(m))
return m;
const notices = changedFilesNoticesOf(m);
if (notices !== undefined)
return renderNotices(m, notices, walk);
const parts = input.folds?.get(m);
if (parts !== undefined && m.role === "toolResult") {
const segments = parts.map((p) => {
const d = deliveryOf(p);
const rendering = d === undefined ? "contents" : walk.decide(d);
const own = isRecord(p) && Array.isArray(p.content) ? p.content : [];
return rendering === "contents" || d?.carrier !== "read" ? own : [{ type: "text", text: readPointerSentence(d) }];
});
if (parts.every((p, i) => segments[i] === (isRecord(p) && Array.isArray(p.content) ? p.content : undefined)))
return m;
const content = segments.flatMap((s, i) => (i === 0 ? [...s] : [{ type: "text", text: SECOND_RESULT_SEPARATOR }, ...s]));
return Object.assign({}, m, { content });
}
const d = deliveryOf(m);
if (d === undefined)
return m;
const rendering = walk.decide(d);
if (rendering === "contents" || "glimpse" in d)
return m;
if (d.carrier === "frame")
return renderFrame(m, d.attachment, rendering, input);
return Object.assign({}, m, { content: [{ type: "text", text: readPointerSentence(d) }], details: undefined });
}
const NOTICE_SEPARATOR_MAX = 2;
const untoldFilesOf = (n, walk) => n.files.filter((f) => !walk.toldBefore(f));
export function lastNoticeCarried(view) {
const last = view.at(-1);
if (last === undefined || changedFilesNoticesOf(last) === undefined)
return true;
const walk = new CopyWalk({});
let untold = false;
for (const m of view) {
const notices = changedFilesNoticesOf(m);
if (notices !== undefined)
untold = notices.map((n) => untoldFilesOf(n, walk).length > 0).includes(true);
}
return untold || projectRequestView(view)[view.length - 1] === last;
}
function renderNotices(m, notices, walk) {
const content = m.content;
if (typeof content !== "string" && !Array.isArray(content))
return m;
const parts = typeof content === "string" ? [] : content;
const text = typeof content === "string" ? content : parts.map((b) => (isRecord(b) && b.type === "text" && typeof b.text === "string" ? b.text : "")).join("");
const cuts = [];
for (const n of notices) {
const untold = untoldFilesOf(n, walk);
const told = n.files.filter((f) => !untold.includes(f));
if (told.length === 0)
continue;
if (told.length < n.files.length) {
for (const f of told)
cuts.push([f.start, f.end]);
continue;
}
let start = n.start, end = n.end;
const after = /^\n*/.exec(text.slice(end, end + NOTICE_SEPARATOR_MAX))[0].length;
if (after > 0)
end += after;
else
start -= /\n*$/.exec(text.slice(Math.max(0, start - NOTICE_SEPARATOR_MAX), start))[0].length;
cuts.push([start, end]);
}
if (cuts.length === 0)
return m;
const cutOut = (s, at) => {
let kept = "", from = 0;
for (const [a, b] of cuts) {
const lo = Math.max(a - at, 0), hi = Math.min(b - at, s.length);
if (hi <= lo)
continue;
kept += s.slice(from, Math.max(from, lo));
from = Math.max(from, hi);
}
return kept + s.slice(from);
};
const moved = (pos) => pos - cuts.reduce((n, [a, b]) => n + Math.max(0, Math.min(b, pos) - a), 0);
const ranges = movedEngineRanges(m, moved);
if (typeof content === "string") {
const left = cutOut(content, 0);
return left.trim().length === 0 ? undefined : Object.assign({}, m, { content: left, ...ranges });
}
let at = 0;
const blocks = [];
for (const b of parts) {
if (!isRecord(b) || b.type !== "text" || typeof b.text !== "string") {
blocks.push(b);
continue;
}
const left = cutOut(b.text, at);
at += b.text.length;
if (left.length > 0)
blocks.push(left === b.text ? b : { ...b, text: left });
}
const said = blocks.some((b) => !isRecord(b) || b.type !== "text" || (typeof b.text === "string" && b.text.trim().length > 0));
return said ? Object.assign({}, m, { content: blocks, ...ranges }) : undefined;
}
function movedEngineRanges(m, moved) {
const out = { changedFilesNotices: undefined };
if (typeof m.enginePrefixChars === "number" && Number.isInteger(m.enginePrefixChars)) {
const chars = moved(m.enginePrefixChars);
out.enginePrefixChars = chars > 0 ? chars : undefined;
}
if (Array.isArray(m.engineSegments)) {
const segments = m.engineSegments;
const ranges = [];
for (const s of segments)
if (isRecord(s) && typeof s.start === "number" && typeof s.end === "number" && Number.isInteger(s.start) && Number.isInteger(s.end))
ranges.push({ start: s.start, end: s.end });
if (ranges.length === segments.length) {
const left = ranges.flatMap((r) => {
const start = moved(r.start), end = moved(r.end);
return end > start ? [{ start, end }] : [];
});
out.engineSegments = left.length > 0 ? left : undefined;
}
}
return out;
}
export function copyIdentityOf(m) {
return copyOf(m)?.identity;
}
export function chooseDegraded(core, fits) {
const order = [];
for (const m of core) {
const id = copyIdentityOf(m);
if (id !== undefined && !order.includes(id))
order.push(id);
}
const degraded = new Set(order);
for (let i = order.length - 1; i >= 0; i--) {
degraded.delete(order[i]);
if (!fits(degraded))
degraded.add(order[i]);
}
return degraded;
}