@sema-agent/core
Version:
Stateless, task-oriented AI agent core
352 lines (351 loc) • 16.3 kB
JavaScript
import { createHash } from "node:crypto";
import { bytesAreBinary, caughtFault, countRestoreLineDiff, fileHistoryBlobExchangeOf, modeProvenDifferent, mutationIndexOf, planFileHistoryRestore, rewindTargetOf } from "../file-history-store.js";
import { changesContentBudget, changesContentOf, changesSideOf } from "../session-changes.js";
import { readMember } from "../thrown-value.js";
import { legFirstInputOf, userRowSourceOf } from "../user-row-origin.js";
export const CHECKPOINT_ROUND_IDS = 102;
function faultOf(error) {
return { code: typeof error?.code === "string" ? error.code : "restore_failed", ...(error?.permanence === "transient" || error?.permanence === "terminal" ? { permanence: error.permanence } : {}) };
}
function thrownFault(err) {
const code = readMember(err, "code");
return { code: typeof code === "string" && code !== "" ? code : "restore_failed", ...caughtFault(err) };
}
function userRowsNewestFirst(path) {
const rows = [];
path.forEach((e, index) => {
if (e.type === "message" && e.message?.role === "user")
rows.push({ id: e.id, index });
});
return rows.reverse();
}
function seatOf(store) {
return typeof store.readBoundaries === "function" ? { kind: "batch", store: store } : { kind: "single", store };
}
async function scanCheckpoints(seat, scope, rows, from, need) {
const found = [];
let i = from;
while (found.length < need && i < rows.length) {
if (seat.kind === "single") {
const row = rows[i++];
let restorable;
try {
restorable = (await seat.store.canRestore(scope, row.id)) === true;
}
catch (err) {
return { ok: false, fault: thrownFault(err) };
}
if (restorable)
found.push({ ...row, read: { kind: "known" } });
continue;
}
const round = rows.slice(i, i + CHECKPOINT_ROUND_IDS);
i += round.length;
let answer;
try {
answer = await seat.store.readBoundaries(scope, round.map((r) => r.id));
}
catch (err) {
return { ok: false, fault: thrownFault(err) };
}
if (answer?.ok !== true)
return { ok: false, fault: faultOf(answer?.ok === false ? answer.error : undefined) };
for (const row of round) {
const one = typeof answer.boundaries?.get === "function" ? answer.boundaries.get(row.id) : undefined;
if (one === undefined)
found.push({ ...row, read: { kind: "damaged", fault: { code: "restore_failed" } } });
else if (!one.ok)
found.push({ ...row, read: { kind: "damaged", fault: faultOf(one.error) } });
else if (one.boundary !== null)
found.push({ ...row, read: { kind: "alive", entries: one.boundary.entries } });
if (found.length === need)
break;
}
}
return { ok: true, found };
}
function skippedBetween(path, from, to, seat) {
if (seat.kind !== "batch")
return undefined;
let n = 0;
for (let i = from + 1; i < (to ?? path.length); i++) {
const e = path[i];
if (e.type !== "message")
continue;
const m = e.message;
if (m?.role !== "user")
continue;
const source = userRowSourceOf(m);
if (source === undefined)
return undefined;
if (source.origin !== "human_input")
continue;
const first = legFirstInputOf(m);
if (first === undefined)
return undefined;
if (first)
n += 1;
}
return n;
}
function pairPlan(before, after) {
const afterBy = new Map(after.map((e) => [e.key, e.target]));
const keys = [...new Set([...before.map((e) => e.key), ...after.map((e) => e.key)])].sort();
const beforeBy = new Map(before.map((e) => [e.key, e.target]));
const plans = [];
for (const path of keys) {
const b = beforeBy.get(path);
const a = afterBy.get(path);
if (b === undefined || a === undefined) {
plans.push({ path, status: "uncompared", reason: "unreadable" });
continue;
}
if (b.kind === "frozen" || a.kind === "frozen")
continue;
if (b.kind === "base_unavailable" || a.kind === "base_unavailable")
plans.push({ path, status: "uncompared", reason: "base_unavailable" });
else if (b.kind === "record_missing" || a.kind === "record_missing")
plans.push({ path, status: "uncompared", reason: "unreadable" });
else if (b.kind === "absent" && a.kind === "absent")
continue;
else if (b.kind === "absent" && a.kind === "bytes")
plans.push({ path, status: "added", after: a.hash });
else if (b.kind === "bytes" && a.kind === "absent")
plans.push({ path, status: "deleted", before: b.hash });
else if (b.kind === "bytes" && a.kind === "bytes") {
if (b.hash !== a.hash)
plans.push({ path, status: "modified", before: b.hash, after: a.hash });
else if (modeProvenDifferent(b.mode, a.mode))
plans.push({ path, status: "modified", modeOnly: true });
}
}
return plans;
}
function blobReader(exchange, uses) {
const held = new Map();
return async (hash) => {
let p = held.get(hash);
if (p === undefined) {
p = exchange.get(hash).then((bytes) => (bytes instanceof Uint8Array && createHash("sha256").update(bytes).digest("hex") === hash ? bytes : "missing"));
held.set(hash, p);
}
const left = (uses.get(hash) ?? 1) - 1;
if (left <= 0) {
uses.delete(hash);
held.delete(hash);
}
else
uses.set(hash, left);
return p;
};
}
function uncomparedRow(path, reason, named, refusal) {
return { path, status: "uncompared", lines: { uncounted: reason }, ...(refusal !== undefined ? { refusal } : {}), ...(named ? { content: { omitted: reason } } : {}) };
}
function modeOnlyRow(path, named) {
return { path, status: "modified", modeOnly: true, lines: { insertions: 0, deletions: 0 }, ...(named ? { content: { omitted: "mode_only" } } : {}) };
}
function comparedRow(path, status, before, after, named, budget) {
const binary = (before !== null && bytesAreBinary(before)) || (after !== null && bytesAreBinary(after));
const lines = binary ? { uncounted: "binary" } : countRestoreLineDiff(before ?? undefined, after ?? undefined);
return { path, status, lines, ...(named ? { content: changesContentOf(changesSideOf(before), changesSideOf(after), budget) } : {}) };
}
async function pairRows(before, after, read, contentOf) {
const rows = [];
const budget = changesContentBudget();
for (const p of pairPlan(before, after)) {
const named = contentOf.has(p.path);
if (p.reason !== undefined)
rows.push(uncomparedRow(p.path, p.reason, named));
else if (p.modeOnly === true)
rows.push(modeOnlyRow(p.path, named));
else {
const b = p.before !== undefined ? await read(p.before) : null;
const a = p.after !== undefined ? await read(p.after) : null;
if (b === "missing" || a === "missing")
rows.push(uncomparedRow(p.path, "unreadable", named));
else
rows.push(comparedRow(p.path, p.status, b, a, named, budget));
}
}
return rows;
}
function usesOf(pairs) {
const uses = new Map();
for (const [b, a] of pairs) {
for (const p of pairPlan(b, a)) {
for (const h of [p.before, p.after])
if (h !== undefined)
uses.set(h, (uses.get(h) ?? 0) + 1);
}
}
return uses;
}
export async function readCheckpointList(input) {
const { store, scope, path, limit, before } = input;
const seat = seatOf(store);
const rows = userRowsNewestFirst(path);
const from = before === undefined ? 0 : rows.findIndex((r) => r.id === before);
if (from < 0)
return { kind: "unavailable", reason: "no_checkpoint" };
const lead = before === undefined ? 0 : 1;
const scanned = await scanCheckpoints(seat, scope, rows, from, lead + limit + 1);
if (!scanned.ok)
return { kind: "unavailable", reason: "history_unreadable", fault: scanned.fault };
const found = scanned.found;
if (before !== undefined && found[0]?.id !== before)
return { kind: "unavailable", reason: "no_checkpoint" };
const page = found.slice(lead, lead + limit);
const newer = (i) => (i === 0 ? (lead === 1 ? found[0] : undefined) : page[i - 1]);
const exchange = exchangeOf(store);
const pairs = [];
page.forEach((b, i) => {
const c = newer(i);
if (c !== undefined && b.read.kind === "alive" && c.read.kind === "alive")
pairs.push([b.read.entries, c.read.entries]);
});
const read = exchange !== undefined ? blobReader(exchange, usesOf(pairs)) : undefined;
const items = [];
for (let i = 0; i < page.length; i++) {
const b = page[i];
const c = newer(i);
items.push(await itemOf(input, seat, read, b, c));
}
return { kind: "page", items, ...(found.length > lead + limit && page.length > 0 ? { nextBefore: page[page.length - 1].id } : {}) };
}
async function itemOf(input, seat, read, b, c) {
if (b.read.kind === "damaged")
return { kind: "unavailable", entryId: b.id, reason: "history_unreadable", fault: b.read.fault };
if (c !== undefined && c.read.kind === "damaged")
return { kind: "unavailable", entryId: b.id, reason: "history_unreadable", fault: c.read.fault };
const skipped = skippedBetween(input.path, b.index, c?.index, seat);
if (c === undefined)
return input.newest(b.id, skipped);
if (b.read.kind !== "alive" || c.read.kind !== "alive" || read === undefined)
return { kind: "unavailable", entryId: b.id, reason: "store_cannot_read" };
let rows;
try {
rows = await pairRows(b.read.entries, c.read.entries, read, input.contentOf);
}
catch (err) {
return { kind: "unavailable", entryId: b.id, reason: "history_unreadable", fault: thrownFault(err) };
}
const after = { kind: "checkpoint", entryId: c.id, ...(skipped !== undefined ? { skipped } : {}) };
return { kind: "rows", before: { kind: "checkpoint", entryId: b.id }, after, rows };
}
function exchangeOf(store) {
try {
return fileHistoryBlobExchangeOf(store);
}
catch {
return undefined;
}
}
export async function readCheckpointItem(input) {
const { store, scope, path, entryId } = input;
const seat = seatOf(store);
const rows = userRowsNewestFirst(path);
const at = rows.findIndex((r) => r.id === entryId);
if (at < 0)
return { kind: "unavailable", reason: "no_checkpoint" };
const toward = [rows[at], ...rows.slice(0, at).reverse()];
let found;
if (seat.kind === "single") {
const own = await scanCheckpoints(seat, scope, toward.slice(0, 1), 0, 1);
if (!own.ok)
return { kind: "unavailable", reason: "history_unreadable", fault: own.fault };
if (own.found.length === 0)
return { kind: "unavailable", reason: "no_checkpoint" };
const newer = await scanCheckpoints(seat, scope, toward, 1, 1);
if (!newer.ok)
return { kind: "unavailable", reason: "history_unreadable", fault: newer.fault };
found = [...own.found, ...newer.found];
}
else {
const scanned = await scanCheckpoints(seat, scope, toward, 0, 2);
if (!scanned.ok)
return { kind: "unavailable", reason: "history_unreadable", fault: scanned.fault };
found = scanned.found;
}
const [b, c] = found;
if (b === undefined || b.id !== entryId)
return { kind: "unavailable", reason: "no_checkpoint" };
const exchange = exchangeOf(store);
const read = exchange !== undefined && c !== undefined && b.read.kind === "alive" && c.read.kind === "alive" ? blobReader(exchange, usesOf([[b.read.entries, c.read.entries]])) : undefined;
return itemOf(input, seat, read, b, c);
}
export function sinceTextsOf(contentOf, root) {
if (contentOf.size === 0)
return undefined;
const addressOf = rewindTargetOf(root);
const named = new Set([...contentOf].map(addressOf));
const budget = changesContentBudget();
const texts = new Map();
return {
at: texts,
readCurrent: (at, current, target) => {
if (named.has(at) && !texts.has(at))
texts.set(at, changesContentOf(changesSideOf(target), changesSideOf(current), budget));
},
};
}
export async function readSince(store, input, contentOf) {
const texts = sinceTextsOf(contentOf, input.root);
let plan;
try {
plan = await planFileHistoryRestore(store, { scope: input.scope, entryId: input.entryId, env: input.env, root: input.root, ...(input.signal !== undefined ? { signal: input.signal } : {}), ...(input.forkedSession === true ? { forkedSession: true } : {}), ...(texts !== undefined ? { readCurrent: texts.readCurrent } : {}) });
}
catch (err) {
return { kind: "unavailable", reason: "history_unreadable", fault: thrownFault(err) };
}
return sinceRowsOf(plan, contentOf, texts?.at ?? new Map());
}
function sinceLines(lines) {
return { insertions: lines.deletions, deletions: lines.insertions };
}
export function sinceRowsOf(plan, contentOf, texts) {
const restore = plan.restore;
if (restore.outcome === "failed" && restore.error?.code === "not_found")
return { kind: "unavailable", reason: "no_checkpoint" };
if (restore.outcome === "failed" || restore.error !== undefined)
return { kind: "unavailable", reason: "history_unreadable", fault: faultOf(restore.error) };
if (plan.unheld !== undefined || plan.unplacedForFork === true)
return { kind: "unavailable", reason: "history_unreadable", fault: { code: "restore_failed", permanence: "terminal" } };
const rows = [];
const handedAt = new Set();
const changesAt = mutationIndexOf(plan.changes);
for (const f of restore.files) {
if (f.refused !== undefined || f.failed !== undefined)
continue;
const named = contentOf.has(f.path);
const at = changesAt(f.targetPath);
const change = at.find((c) => c.action !== "mode");
if (change === undefined) {
rows.push(at.some((c) => c.action === "mode") ? modeOnlyRow(f.path, named) : uncomparedRow(f.path, "unreadable", named));
continue;
}
if (change.current === undefined || (change.action === "write" && change.target === undefined)) {
rows.push(uncomparedRow(f.path, "unreadable", named));
continue;
}
const before = change.action === "write" ? change.target : null;
const after = change.current;
if (before === null && after === null)
continue;
const status = before === null ? "added" : after === null ? "deleted" : "modified";
const binary = (before !== null && bytesAreBinary(before)) || (after !== null && after.binary);
const decided = named && !handedAt.has(change.at) ? texts.get(change.at) : undefined;
if (decided !== undefined)
handedAt.add(change.at);
rows.push({ path: f.path, status, lines: binary ? { uncounted: "binary" } : sinceLines(change.lines), ...(named ? { content: decided ?? { omitted: "unreadable" } } : {}) });
}
for (const r of restore.refused) {
const named = contentOf.has(r.path);
rows.push(r.class === "base_unavailable" ? uncomparedRow(r.path, "base_unavailable", named) : uncomparedRow(r.path, "rewind_refused", named, { class: r.class, reason: r.reason }));
}
for (const l of restore.leftAsIs ?? [])
rows.push(uncomparedRow(l.path, l.class, contentOf.has(l.path)));
for (const fl of restore.failed)
rows.push(uncomparedRow(fl.path, "unreadable", contentOf.has(fl.path)));
return { kind: "rows", rows };
}