@sema-agent/core
Version:
Stateless, task-oriented AI agent core
109 lines (108 loc) • 4.77 kB
JavaScript
import { LineageBreak, entryParentLinks, pathToRoot, replayLossText } from "../../internal/harness.js";
import { deliverEngineNotice } from "../engine-notice.js";
const LINEAGE_REROOTED = "session.lineage_rerooted";
export function viewThroughReplayLoss(storage, found) {
return new Proxy(storage, {
get(target, prop, receiver) {
if (prop === "getPathToRoot")
return (leafId) => branchReadingLoss(target, leafId, found);
const value = Reflect.get(target, prop, receiver);
return typeof value === "function" ? value.bind(target) : value;
},
});
}
async function branchReadingLoss(storage, leafId, found) {
let path;
try {
path = await storage.getPathToRoot(leafId);
}
catch (err) {
if (!(err instanceof LineageBreak) || err.replayLoss === undefined || err.replayLoss.dropped === 0 || leafId === null)
throw err;
const entries = await storage.getEntries();
const byId = new Map(entries.map((entry) => [entry.id, entry]));
const leaf = byId.get(leafId);
if (leaf === undefined)
throw err;
const rerooted = pathToRoot(leaf, entryParentLinks(byId), err.childId);
found({
break: true,
missingParentId: err.missingParentId,
rootedAt: err.childId,
recordsDropped: err.replayLoss.dropped,
recordsTotal: err.replayLoss.total,
leaf: leafId,
entriesOnPath: rerooted.length,
entriesCut: entries.length - descendantsOf(entries, err.childId),
});
return rerooted;
}
const loss = storage.getReplayLoss?.();
if (loss !== undefined && loss.dropped > 0)
found({ break: false, recordsDropped: loss.dropped, recordsTotal: loss.total, leaf: leafId, entriesOnPath: path.length });
return path;
}
function descendantsOf(entries, rootId) {
const children = new Map();
for (const entry of entries) {
const parent = entry.parentId || null;
if (parent === null)
continue;
const list = children.get(parent);
if (list === undefined)
children.set(parent, [entry.id]);
else
list.push(entry.id);
}
const seen = new Set([rootId]);
const todo = [rootId];
for (let id = todo.pop(); id !== undefined; id = todo.pop()) {
for (const child of children.get(id) ?? []) {
if (seen.has(child))
continue;
seen.add(child);
todo.push(child);
}
}
return seen.size;
}
const WHOLE_BRANCH = "\0whole";
function lossSentence(finding) {
const count = replayLossText({ dropped: finding.recordsDropped, total: finding.recordsTotal });
if (finding.break) {
return (`This session's log is damaged: entry ${finding.missingParentId}, the parent of ${finding.rootedAt}, is not in it (${count}). ` +
`The run continues from ${finding.rootedAt}: ${finding.entriesOnPath} entries of the conversation are kept, and ${finding.entriesCut} entries the log holds above the damage are not in its context.`);
}
if (finding.leaf === null)
return `This session's log is damaged: ${count}, and none of it is readable. The run starts from an empty conversation.`;
return (`This session's log is damaged: ${count}. The run continues from entry ${finding.leaf}, where the records the log still holds leave the conversation: ` +
`${finding.entriesOnPath} entries of it are kept, and what the unreadable records said — possibly its latest turns — is not in its context.`);
}
export function replayLossSeat(ids) {
const said = new Set();
return (finding, sessionId) => {
const key = finding.break ? `${finding.missingParentId}\n${finding.rootedAt}` : WHOLE_BRANCH;
if (said.has(key))
return;
said.add(key);
if (finding.break)
said.add(WHOLE_BRANCH);
deliverEngineNotice(ids.onNotice, { code: LINEAGE_REROOTED, message: lossSentence(finding), detail: { ...finding, sessionId, runId: ids.runId } });
};
}
export function replayLossLeg(ids) {
const say = replayLossSeat(ids);
let held = [];
return {
view: (storage, sessionId) => viewThroughReplayLoss(storage, (finding) => (held !== undefined ? void held.push({ finding, sessionId }) : say(finding, sessionId))),
discard: () => {
held = [];
},
settle: () => {
const found = [...(held ?? [])].sort((a, b) => Number(b.finding.break) - Number(a.finding.break));
held = undefined;
for (const { finding, sessionId } of found)
say(finding, sessionId);
},
};
}