@sema-agent/core
Version:
Stateless, task-oriented AI agent core
152 lines (151 loc) • 6.04 kB
JavaScript
import { adoptHostPromise } from "../host-promise.js";
import { mintGateOutcome } from "./gate-exit.js";
export const occurrenceClock = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
const TERMINAL = { announced: false, released: false, settled: true, interrupted: true };
const GATE_HOLD_ORDER = Object.freeze(["classifier", "approval", "hook"]);
export function gatePhaseOf(occ) {
return GATE_HOLD_ORDER.find((phase) => occ.holds[phase] > 0);
}
export function approvalHeldCalls(table) {
return table
.live()
.filter((occ) => occ.holds.approval > 0)
.map((occ) => ({ toolCallId: occ.toolCallId, tool: occ.wireName ?? occ.spelledName }));
}
export function reportApprovalHoldsOf(internals, table) {
try {
internals?.reportApprovalHolds?.(() => approvalHeldCalls(table));
}
catch {
}
}
export function createToolOccurrenceTable() {
const byId = new Map();
const attempts = new Map();
let listener;
const held = (toolCallId, verb) => {
const occ = byId.get(toolCallId);
if (occ === undefined)
throw new Error(`tool occurrence: ${verb} for call "${toolCallId}", which this leg does not hold`);
return occ;
};
const open = (start) => {
const attempt = (attempts.get(start.toolCallId) ?? 0) + 1;
attempts.set(start.toolCallId, attempt);
const now = occurrenceClock();
const occ = {
toolCallId: start.toolCallId,
spelledName: start.spelledName,
...(start.wireName !== undefined ? { wireName: start.wireName } : {}),
...(start.label !== undefined ? { label: start.label } : {}),
args: start.args,
...(start.requestedBy !== undefined ? { requestedBy: start.requestedBy } : {}),
...(start.resumesCheckpoint !== undefined ? { resumesCheckpoint: start.resumesCheckpoint } : {}),
attempt,
life: "announced",
holds: { classifier: 0, approval: 0, hook: 0 },
gateRounds: [],
startEmitted: false,
lastHeardAt: now,
beating: true,
};
byId.delete(start.toolCallId);
byId.set(start.toolCallId, occ);
listener?.();
return occ;
};
const hold = (toolCallId, phase) => {
const occ = byId.get(toolCallId);
if (occ === undefined)
return () => { };
occ.holds[phase] += 1;
let returned = false;
return () => {
if (returned)
return;
returned = true;
if (byId.get(toolCallId) !== occ)
return;
occ.holds[phase] -= 1;
if (phase === "approval" && occ.holds.approval === 0)
occ.lastHeardAt = occurrenceClock();
};
};
const bracket = (release, held) => {
let value;
try {
value = held();
}
catch (err) {
release();
throw err;
}
const valueAsync = adoptHostPromise(value);
if (valueAsync !== undefined)
valueAsync.then(release, release);
else
release();
return value;
};
return {
hold,
whileHeld: (toolCallId, phase, held) => bracket(hold(toolCallId, phase), held),
get: (toolCallId) => byId.get(toolCallId),
live: () => [...byId.values()],
open,
ensure: (start) => byId.get(start.toolCallId) ?? open(start),
noteStartEmitted(toolCallId) {
held(toolCallId, "a start frame").startEmitted = true;
},
release(toolCallId) {
const occ = held(toolCallId, "release");
if (occ.life !== "announced")
throw new Error(`tool occurrence: call "${toolCallId}" (attempt ${occ.attempt}) cannot be released from "${occ.life}"`);
occ.life = "released";
occ.releasedAt = occ.lastHeardAt = occurrenceClock();
},
gateRound(toolCallId, outcome, finalInput, rewrite) {
const occ = held(toolCallId, "a gate round");
occ.gateRounds.push(outcome);
if (finalInput !== undefined)
occ.finalInput = finalInput;
occ.rewrite = rewrite;
},
refuse(toolCallId, layer, facts) {
const occ = held(toolCallId, "a refusal");
const latest = occ.gateRounds.at(-1);
const round = mintGateOutcome({ deniedBy: layer, ...(facts?.extension !== undefined ? { extension: facts.extension } : {}), ...(facts?.echoed !== undefined ? { echoed: facts.echoed } : {}), ...(latest?.settlement !== undefined && latest.origin !== undefined ? { settled: { settlement: latest.settlement, origin: latest.origin } } : {}) });
occ.gateRounds.push(round);
return round;
},
answeredInPlace(toolCallId, by) {
const occ = held(toolCallId, "an answer in place of the body");
if (occ.answeredInPlaceBy !== undefined)
throw new Error(`tool occurrence: call "${toolCallId}" (attempt ${occ.attempt}) was already answered in place`);
occ.answeredInPlaceBy = by;
},
heard(toolCallId) {
const occ = byId.get(toolCallId);
if (occ !== undefined)
occ.lastHeardAt = occurrenceClock();
},
close(toolCallId, life) {
const occ = byId.get(toolCallId);
if (occ === undefined)
return undefined;
if (TERMINAL[occ.life])
throw new Error(`tool occurrence: call "${toolCallId}" (attempt ${occ.attempt}) is already ${occ.life}`);
occ.life = life;
occ.beating = false;
byId.delete(toolCallId);
return occ;
},
quiesce() {
for (const occ of byId.values())
occ.beating = false;
},
onOpen(l) {
listener = l;
},
};
}