UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

174 lines (173 loc) • 10.5 kB
import { AsyncLocalStorage } from "node:async_hooks"; import { noticeAttentionOf } from "./governance-codes.js"; import { factKeyOver } from "./notice-fact.js"; import { egressAccount, egressText } from "./untrusted-egress.js"; export { announceDigest, endNoticeFact, factUnder } from "./notice-fact.js"; const NOTICE_SEAT_NAMES = { runner: "RunnerDeps.onNotice", environment: "the `onNotice` option of the execution environment", toolkit: "the `onNotice` option of the toolkit" }; let defaultNoticeSeat; export function setDefaultEngineNoticeSeat(seat) { if (seat !== undefined && typeof seat !== "function") throw Object.assign(new Error(`setDefaultEngineNoticeSeat: the seat must be a function, or undefined to remove it (got ${seat === null ? "null" : typeof seat})`), { code: "config.invalid_argument" }); defaultNoticeSeat = seat; } let malformedNoticeSeatAnnounced = false; const seatsDelivering = new AsyncLocalStorage(); function writeProcessLine(text) { try { console.warn(text); } catch { } } export function __resetMalformedNoticeSeatAnnouncement() { malformedNoticeSeatAnnounced = false; } export function deliverEngineNotice(onNotice, notice, admission, told, seat) { notice = { ...notice, message: typeof notice.message === "string" ? egressText("same-principal", notice.message) : notice.message, ...(notice.detail !== undefined ? { detail: egressAccount("same-principal", notice.detail) } : {}), }; if (notice.sessionId === undefined && typeof notice.detail?.["sessionId"] === "string") { notice = { ...notice, sessionId: notice.detail["sessionId"] }; } const attention = noticeAttentionOf(notice.code); const factKey = factKeyOver(notice.code, notice.detail); if (notice.attention !== undefined || notice.factKey !== undefined) { const { attention: _minted, factKey: _mintedKey, ...rest } = notice; notice = rest; } if (attention !== undefined || factKey !== undefined) notice = { ...notice, ...(attention !== undefined ? { attention } : {}), ...(factKey !== undefined ? { factKey } : {}) }; if (admission !== undefined && !admission(notice)) return; if (told !== undefined && factKey !== undefined) { if (told.has(factKey)) return; handToSeat(onNotice, notice, seat); told.add(factKey); return; } handToSeat(onNotice, notice, seat); } function handToSeat(onNotice, notice, named) { const seat = onNotice === undefined ? defaultNoticeSeat : onNotice; if (typeof seat === "function") { const delivering = seatsDelivering.getStore() ?? []; if (delivering.includes(seat)) { writeProcessLine(notice.message); return; } const bound = seat; try { seatsDelivering.run([...delivering, bound], () => { const r = bound(notice); if (typeof r?.then === "function") { r.then(undefined, () => { }); } }); } catch { } return; } if (onNotice !== undefined && !malformedNoticeSeatAnnounced) { malformedNoticeSeatAnnounced = true; writeProcessLine(`The structured notice sink (${named !== undefined ? NOTICE_SEAT_NAMES[named] : "an `onNotice` seat: RunnerDeps.onNotice, or the option of the execution environment or toolkit that was given one"}) holds ${onNotice === null ? "null" : typeof onNotice} — not a ` + `function. Notices fall back to console.warn until the wiring is fixed (omit the key, or wire a function).`); } writeProcessLine(notice.message); } export function parkedInputIdsOf(records) { const ids = (lane) => lane.flatMap((r) => (typeof r === "object" && r !== null && typeof r.inputId === "string" ? [r.inputId] : [])); return { steer: ids(records.steer), followUp: ids(records.followUp) }; } export function owedUserInputCounts(held, migrated, continuation) { const owedContinuation = (continuation.rowReturned ? continuation.frames.filter((f) => f.seq === undefined).length : continuation.frames.length) - continuation.carried; return { steer: Math.max(0, (held?.steer ?? 0) - migrated.steer) + Math.max(0, owedContinuation), followUp: Math.max(0, (held?.followUp ?? 0) - migrated.followUp), }; } export function owedUserInputIds(held, migrated, continuation) { const gone = (lane) => new Set(migrated.inputIds?.[lane] ?? []); const live = (lane) => (held?.inputIds?.[lane] ?? []).filter((id) => !gone(lane).has(id)); const carried = new Set(continuation.carriedInputIds ?? []); const frames = (continuation.rowReturned ? continuation.frames.filter((f) => f.seq === undefined) : continuation.frames).filter((f) => !(typeof f.inputId === "string" && carried.has(f.inputId))); const continuationIds = frames.flatMap((f) => (typeof f.inputId === "string" ? [f.inputId] : [])); return { steer: [...continuationIds, ...live("steer")], followUp: live("followUp") }; } export function settleOwedUserInput(account, rowReturned, ids, onNotice) { if (SETTLED_OWED_ACCOUNTS.has(account)) return; SETTLED_OWED_ACCOUNTS.add(account); try { const owed = owedUserInputCounts(account.held, account.migrated, { ...account.continuation, rowReturned }); const inputIds = owedUserInputIds(account.held, account.migrated, { ...account.continuation, rowReturned }); const approval = account.continuation.approval; const approvalFeedback = approval === undefined || rowReturned ? 0 : Math.max(0, approval.owed - approval.carried); const approvalCarry = approvalFeedback > 0 ? approval?.refusal : undefined; for (const notice of undrainedUserInputNotices({ ...owed, inputIds, ...(approvalFeedback > 0 ? { approvalFeedback } : {}), ...(approvalCarry !== undefined ? { approvalCarry } : {}) }, ids.taskId, ids.sessionId, ids.runId, ids.parent)) deliverEngineNotice(onNotice, notice); } catch { } } const SETTLED_OWED_ACCOUNTS = new WeakSet(); export const USER_INPUT_UNDRAINED_CAUSES = Object.freeze(["leg_end", "crashed", "park_expired"]); const STEER_UNDRAINED = "task.user_steer_undrained"; const FOLLOWUP_UNDRAINED = "task.user_followup_undrained"; export const USER_INPUT_UNDRAINED_FAMILIES = Object.freeze({ steer: Object.freeze({ code: STEER_UNDRAINED, countKey: "steer" }), followUp: Object.freeze({ code: FOLLOWUP_UNDRAINED, countKey: "followUp" }), }); export function parentLegIds(internals) { const parentSessionId = internals?.parentSessionId; if (typeof parentSessionId !== "string" || parentSessionId === "") return undefined; const parentTaskId = internals?.parentTaskId; return { sessionId: parentSessionId, ...(typeof parentTaskId === "string" && parentTaskId !== "" ? { taskId: parentTaskId } : {}) }; } export function undrainedUserInputNotices(counts, taskId, sessionId, runId, parent) { const tid = taskId !== undefined ? { taskId } : {}; const sid = sessionId !== undefined ? { sessionId } : {}; const rid = runId !== undefined ? { runId } : {}; const tail = `accepted as "queued" were never consumed — the run ended first. They are NOT redelivered; re-send against a live run if still wanted.`; const parentSession = typeof parent?.sessionId === "string" && parent.sessionId !== "" ? parent.sessionId : undefined; const toParent = parentSession !== undefined && typeof sessionId === "string" && sessionId !== "" && parentSession !== sessionId; const ptid = typeof parent?.taskId === "string" && parent.taskId !== "" ? { taskId: parent.taskId } : {}; const copyTail = ` (a child leg, ${sessionId})`; const own = []; const copies = []; const cause = "leg_end"; const inputIdsOf = (ids, counted) => (ids !== undefined && ids.length === counted ? { inputIds: [...ids] } : {}); if (counts.steer > 0) { const message = `${counts.steer} user steer(s) ${tail}`; const count = { [USER_INPUT_UNDRAINED_FAMILIES.steer.countKey]: counts.steer, cause }; own.push({ code: STEER_UNDRAINED, message, detail: { ...count, ...inputIdsOf(counts.inputIds?.steer, counts.steer), ...tid, ...sid, ...rid } }); if (toParent) copies.push({ code: STEER_UNDRAINED, message: `${message}${copyTail}`, detail: { ...count, ...inputIdsOf(counts.inputIds?.steer, counts.steer), ...ptid, sessionId: parentSession, childSessionId: sessionId } }); } const approvalFeedback = counts.approvalFeedback ?? 0; if (approvalFeedback > 0) { const why = counts.approvalCarry === "steering.invalid_content" ? "the leg paused with them still owed and the parked-steer carrier refused them (longer than a parked steer may be)" : counts.approvalCarry === "steering.queue_full" ? "the leg paused with them still owed and the parked-steer carrier refused them (its queue was full)" : "the leg ended before the message carrying them was committed"; const message = `${approvalFeedback} approval-card feedback(s) (the words a person wrote when approving a tool call) never reached the model — ${why}. They are NOT redelivered; re-send if still wanted.`; const count = { [USER_INPUT_UNDRAINED_FAMILIES.steer.countKey]: approvalFeedback, cause, kind: "approval_feedback", ...(counts.approvalCarry !== undefined ? { carry: counts.approvalCarry } : {}) }; own.push({ code: STEER_UNDRAINED, message, detail: { ...count, ...tid, ...sid, ...rid } }); if (toParent) copies.push({ code: STEER_UNDRAINED, message: `${message}${copyTail}`, detail: { ...count, ...ptid, sessionId: parentSession, childSessionId: sessionId } }); } if (counts.followUp > 0) { const message = `${counts.followUp} user follow-up(s) ${tail}`; const count = { [USER_INPUT_UNDRAINED_FAMILIES.followUp.countKey]: counts.followUp, cause }; own.push({ code: FOLLOWUP_UNDRAINED, message, detail: { ...count, ...inputIdsOf(counts.inputIds?.followUp, counts.followUp), ...tid, ...sid, ...rid } }); if (toParent) copies.push({ code: FOLLOWUP_UNDRAINED, message: `${message}${copyTail}`, detail: { ...count, ...inputIdsOf(counts.inputIds?.followUp, counts.followUp), ...ptid, sessionId: parentSession, childSessionId: sessionId } }); } return [...own, ...copies]; }