@sema-agent/core
Version:
Stateless, task-oriented AI agent core
220 lines (219 loc) • 11.2 kB
JavaScript
import { createHash } from "node:crypto";
import { failureClassLine, owesAuthorization } from "../mcp-failure.js";
import { egressText } from "../untrusted-egress.js";
import { inlineUntrusted } from "../untrusted-text.js";
import { foreignLine } from "../protocol-http-auth.js";
import { thrownText } from "../thrown-value.js";
import { announceDigest, factUnder } from "../engine-notice.js";
export const ANNOUNCE_ONCE_MAX_DIGESTS = 200;
const RUNNER_ANNOUNCED = new WeakMap();
export function oncePerRunner(sink, key, deliver) {
if (sink === undefined)
return;
const told = RUNNER_ANNOUNCED.get(sink) ?? new Set();
RUNNER_ANNOUNCED.set(sink, told);
if (told.has(key))
return;
deliver();
told.add(key);
if (told.size > ANNOUNCE_ONCE_MAX_DIGESTS)
told.delete(told.values().next().value);
}
export { noticeOncePerSink, __resetNoticedOncePerSink } from "../notice-once-per-seat.js";
const DROPPED_TOOL_MODEL_LANE = "mcp_dropped_tools";
export { announceDigest };
export function warningDigest(err) {
const e = err;
const code = typeof e?.code === "string" ? e.code : "";
const message = thrownText(err);
return announceDigest(code, egressText("same-principal", message));
}
const MEMORY_MOUNT_ADVISORY = {
shared: { label: "Shared memory tools", classification: "shared-memory-not-mounted", tail: "the pair mounts together or not at all" },
engine: { label: "Memory tools", classification: "memory-tools-not-mounted", tail: "these tools mount together or not at all" },
};
export function announceMemoryNotMounted(sink, sessionId, pair, names, reason) {
const p = MEMORY_MOUNT_ADVISORY[pair];
sink.onErrorOncePerRunner(new Error(`${p.label} ${names.join("/")} were NOT mounted: ${reason} — ${p.tail}.`), { phase: "config", sessionId, classification: p.classification });
}
export function droppedToolDigest(d) {
return announceDigest(DROPPED_TOOL_MODEL_LANE, `${d.server}\n${d.tool}\n${d.reason}`);
}
export function withAnnounceDigests(existing, add) {
const out = [...(existing ?? [])];
const seen = new Set(out);
for (const d of add) {
if (seen.has(d))
continue;
seen.add(d);
out.push(d);
}
return out.length > ANNOUNCE_ONCE_MAX_DIGESTS ? out.slice(out.length - ANNOUNCE_ONCE_MAX_DIGESTS) : out;
}
export function tellOncePerSession(announced, digest, deliver, formerly = []) {
const record = announced.announcedListingsRef;
const held = record.advisories ?? [];
if (held.includes(digest))
return;
const at = held.findIndex((d) => formerly.includes(d));
if (at === -1) {
deliver();
record.advisories = withAnnounceDigests(held, [digest]);
}
else {
record.advisories = held.flatMap((d, i) => (i === at ? [digest] : formerly.includes(d) ? [] : [d]));
}
announced.frameReceipts.listingSnapshotOwed = true;
}
const toldAuthorization = (a) => `needs authorization (${a.reason}, ${createHash("sha256").update(JSON.stringify([a.reason, a.authorizeUrl ?? ""])).digest("hex").slice(0, 16)})`;
function sameFailure(a, b) {
return a.name === b.name && a.error === b.error;
}
export async function flushOwedAnnouncedSnapshot(prepared) {
if (!prepared.frameReceipts.listingSnapshotOwed)
return;
prepared.frameReceipts.listingSnapshotOwed = false;
if (!prepared.announcedSnapshotRecovered)
return;
await prepared.session.appendAnnouncedListing(prepared.announcedListingsRef).catch(() => undefined);
}
export function settleMcpUnavailable(prepared, delivered) {
prepared.mcpUnavailable?.pending.splice(0, delivered.length);
const told = delivered.filter((f) => f.connecting !== true).map(({ name, error }) => ({ name, ...(error !== undefined ? { error } : {}) }));
prepared.announcedListingsRef.mcpFailed = [...(prepared.announcedListingsRef.mcpFailed ?? []), ...told];
prepared.frameReceipts.listingSnapshotOwed = true;
}
export function inMemoryNoticeTold() {
const keys = new Set();
return {
has: (key) => keys.has(key),
add: (key) => void keys.add(key),
release: (key) => void [...keys].filter((k) => factUnder(k, key)).forEach((k) => keys.delete(k)),
};
}
export async function loadAnnounceOnceLedger(session, checkpointMirror, onError) {
let recovered = true;
const entry = await session.getAnnouncedListing().catch(() => {
recovered = false;
return undefined;
});
const seed = checkpointMirror?.mcpFailed !== undefined || checkpointMirror?.advisories !== undefined || checkpointMirror?.advisor !== undefined || checkpointMirror?.language !== undefined || checkpointMirror?.commandSandbox !== undefined ? checkpointMirror : entry;
const listingSrc = checkpointMirror?.agents !== undefined || checkpointMirror?.skills !== undefined || checkpointMirror?.models !== undefined ? checkpointMirror : entry;
let mcpFailed = (seed?.mcpFailed ?? []).map((f) => ({ ...f }));
const advisories = new Set(seed?.advisories ?? []);
let dirty = false;
const oncePerSession = (digest, deliver) => {
if (advisories.has(digest))
return;
deliver();
advisories.add(digest);
dirty = true;
};
let runTime;
const released = new Set();
const isReleased = (d) => [...released].some((k) => factUnder(d, k));
const told = {
has: (key) => (runTime !== undefined ? runTime.announcedListingsRef.advisories?.includes(key) === true : advisories.has(key)),
add: (key) => {
if (runTime !== undefined) {
runTime.announcedListingsRef.advisories = withAnnounceDigests(runTime.announcedListingsRef.advisories, [key]);
runTime.frameReceipts.listingSnapshotOwed = true;
return;
}
advisories.add(key);
dirty = true;
},
release: (key) => {
if (runTime !== undefined) {
const record = runTime.announcedListingsRef;
const held = record.advisories;
if (held === undefined || !held.some((d) => factUnder(d, key)))
return;
record.advisories = held.filter((d) => !factUnder(d, key));
runTime.frameReceipts.listingSnapshotOwed = true;
return;
}
released.add(key);
for (const d of [...advisories])
if (factUnder(d, key) && advisories.delete(d))
dirty = true;
},
};
return {
entry,
recovered,
told,
onError: (err, ctx) => {
if (onError !== undefined)
oncePerSession(warningDigest(err), () => onError(err, ctx));
},
oncePerSession,
onErrorOncePerRunner: (err, ctx) => {
if (onError !== undefined)
oncePerRunner(onError, warningDigest(err), () => onError(err, ctx));
},
mcpFailuresToAnnounce: (statuses, remembered, withRemoteWords) => {
const current = statuses
.filter((s) => s.status === "failed")
.map((s) => ({ name: inlineUntrusted(s.name, 160), ...(remembered(s.name) ? { remembered: true } : {}), ...(s.authorization !== undefined && owesAuthorization(s.authorization) ? { error: toldAuthorization(s.authorization), authorization: { ...s.authorization } } : !withRemoteWords ? failureClassLine(s) : s.error !== undefined ? { error: foreignLine(s.error, 240) } : {}) }));
const carried = mcpFailed.filter((r) => current.some((c) => sameFailure(c, r)));
if (carried.length !== mcpFailed.length)
dirty = true;
mcpFailed = carried;
return current.filter((c) => !carried.some((r) => sameFailure(c, r)));
},
pruneDroppedTools: (dropped) => {
for (let i = dropped.length - 1; i >= 0; i--) {
if (advisories.has(droppedToolDigest(dropped[i])))
dropped.splice(i, 1);
}
},
arms: () => ({
...(listingSrc?.agents !== undefined ? { agents: [...listingSrc.agents] } : {}),
...(listingSrc?.skills !== undefined ? { skills: [...listingSrc.skills] } : {}),
...(listingSrc?.models !== undefined ? { models: [...listingSrc.models] } : {}),
...(mcpFailed.length > 0 ? { mcpFailed: mcpFailed.map((f) => ({ ...f })) } : {}),
...(advisories.size > 0 ? { advisories: withAnnounceDigests(undefined, [...advisories]) } : {}),
...(seed?.advisor !== undefined ? { advisor: { ...seed.advisor } } : {}),
...(seed?.language !== undefined ? { language: { ...seed.language } } : {}),
...(seed?.commandSandbox !== undefined ? { commandSandbox: { ...seed.commandSandbox } } : {}),
}),
settle: async (s, ref, receipts) => {
const seeded = ref.advisories;
if (seeded !== undefined && seeded.some(isReleased)) {
ref.advisories = seeded.filter((d) => !isReleased(d));
dirty = true;
}
if (advisories.size > 0)
ref.advisories = withAnnounceDigests(ref.advisories, [...advisories].filter((d) => seed?.advisories?.includes(d) !== true || isReleased(d)));
runTime = { announcedListingsRef: ref, frameReceipts: receipts };
if (!dirty || !recovered)
return;
await s
.appendAnnouncedListing({
...(ref.agents !== undefined ? { agents: ref.agents } : {}),
...(ref.skills !== undefined ? { skills: ref.skills } : {}),
...(ref.models !== undefined ? { models: ref.models } : {}),
...(ref.mcpFailed !== undefined && ref.mcpFailed.length > 0 ? { mcpFailed: ref.mcpFailed } : {}),
...(ref.advisories !== undefined && ref.advisories.length > 0 ? { advisories: ref.advisories } : {}),
...(ref.advisor !== undefined ? { advisor: ref.advisor } : {}),
...(ref.language !== undefined ? { language: ref.language } : {}),
...(ref.commandSandbox !== undefined ? { commandSandbox: ref.commandSandbox } : {}),
})
.catch(() => undefined);
},
};
}
export function serializeAnnouncedListings(ref) {
const out = {
...(ref.agents !== undefined ? { agents: [...ref.agents] } : {}),
...(ref.skills !== undefined ? { skills: [...ref.skills] } : {}),
...(ref.models !== undefined ? { models: [...ref.models] } : {}),
...(ref.mcpFailed !== undefined ? { mcpFailed: ref.mcpFailed.map((f) => ({ ...f })) } : {}),
...(ref.advisories !== undefined ? { advisories: [...ref.advisories] } : {}),
...(ref.advisor !== undefined ? { advisor: { ...ref.advisor } } : {}),
...(ref.language !== undefined ? { language: { ...ref.language } } : {}),
...(ref.commandSandbox !== undefined ? { commandSandbox: { ...ref.commandSandbox } } : {}),
};
return Object.keys(out).length > 0 ? out : undefined;
}