@sema-agent/core
Version:
Stateless, task-oriented AI agent core
51 lines (50 loc) • 2.08 kB
JavaScript
export function createFrameSettlement() {
return { awaiting: new Map(), receipts: new Map(), withheld: new Set(), hostRewritten: new Set(), hostWithheld: new Set(), consumed: new Map(), compactions: [] };
}
export function settleConsumedFrame(seam, key, by, reason) {
if (!seam.awaiting.delete(key))
return;
seam.consumed.set(key, Object.freeze({ by, reason }));
}
export function settleUndeliveredFrame(seam, key) {
if (!seam.awaiting.delete(key))
return;
seam.withheld.add(key);
}
export function toolResultReceiptKey(toolCallId) {
return `tool_result:${toolCallId}`;
}
const foldWhitespace = (text) => text.replace(/\s+/g, " ");
export function frameSurvivesInToolResult(committedContent, frameText) {
const frame = foldWhitespace(frameText);
if (typeof committedContent === "string")
return foldWhitespace(committedContent).includes(frame);
if (!Array.isArray(committedContent))
return false;
return committedContent.some((b) => b.type === "text" && typeof b.text === "string" && foldWhitespace(b.text).includes(frame));
}
export function noteHostRewrite(seam, toolCallId) {
const carrier = toolResultReceiptKey(toolCallId);
for (const ask of seam.awaiting.values()) {
if (ask.carrier === carrier) {
seam.hostRewritten.add(carrier);
return;
}
}
}
export function settleWithheldResult(seam, toolCallId, content) {
noteHostRewrite(seam, toolCallId);
recordFrameReceipt(seam, toolResultReceiptKey(toolCallId), content, "");
}
export function recordFrameReceipt(seam, carrier, committedContent, entryId) {
const hostRewrote = seam.hostRewritten.delete(carrier);
for (const [key, ask] of seam.awaiting) {
if (ask.carrier !== carrier)
continue;
seam.awaiting.delete(key);
if (ask.frameText === undefined || frameSurvivesInToolResult(committedContent, ask.frameText))
seam.receipts.set(key, entryId);
else
(hostRewrote ? seam.hostWithheld : seam.withheld).add(key);
}
}