@sema-agent/core
Version:
Stateless, task-oriented AI agent core
114 lines (113 loc) • 8.93 kB
JavaScript
import { APPROVAL_REMEDY_KINDS, readApprovalRemedy } from "./ask-origin.js";
import { SUSPEND_LANE_REASONS, isSuspendLaneReason } from "./suspend-lane-reasons.js";
export const ASK_UNRESOLVABLE_CAUSES = Object.freeze(["approver_unavailable", "no_approver_wired", "mandate_unreconstructible", "approval_window_expired"]);
Object.freeze(ASK_UNRESOLVABLE_CAUSES);
const ASK_UNRESOLVABLE_CAUSE_SET = new Set(ASK_UNRESOLVABLE_CAUSES);
export function isAskUnresolvableCause(v) {
return ASK_UNRESOLVABLE_CAUSE_SET.has(v);
}
export const WORKFLOW_PARK_GAPS = Object.freeze(["launch_records"]);
export function isWorkflowParkGap(v) {
return WORKFLOW_PARK_GAPS.some((w) => w === v);
}
const DELEGATED = "delegated agent";
export const ASK_UNRESOLVABLE_CAUSE_WORDS = Object.freeze({
approver_unavailable: "nobody was available to answer it",
no_approver_wired: "nobody could be asked in this run",
mandate_unreconstructible: "its approval had to wait for a person, and this part of the run cannot wait",
approval_window_expired: "its approval window closed with no one answering it",
});
const CAUSE_SAYS_NO_WAIT = Object.freeze({ approver_unavailable: false, no_approver_wired: false, mandate_unreconstructible: true, approval_window_expired: false });
const PERSON_WAY_ON = "This step needs someone present to approve it — run the task again where you can be asked.";
const CAUSE_REMEDY_SEAT = {
approver_unavailable: "unavailable",
no_approver_wired: "absent",
mandate_unreconstructible: undefined,
approval_window_expired: "window_expired",
};
export function askUnresolvableRemedySeat(cause) {
return CAUSE_REMEDY_SEAT[cause];
}
export function refusedAskOf(facts) {
const remedy = facts.remedy ?? facts.notResumableWayOut;
const park = typeof facts.parkFailed === "string" && facts.parkFailed.length > 0 ? { parkFailed: facts.parkFailed, ...(facts.parkFailedReason !== undefined && isSuspendLaneReason(facts.parkFailedReason) ? { parkFailedReason: facts.parkFailedReason } : {}) } : {};
return { toolName: facts.toolName, toolCallId: facts.toolCallId, cause: facts.cause, ...(remedy !== undefined ? { remedy } : {}), ...(facts.modelRemedy !== undefined ? { modelRemedy: facts.modelRemedy } : {}), ...park };
}
export function askUnresolvableTeller(address) {
const told = new Set();
return (facts) => {
const { message, detail } = askUnresolvableNotice({ ...address, ...facts });
const { toolCallId: _call, ...rest } = detail ?? {};
const key = JSON.stringify([message, rest]);
if (told.has(key))
return false;
told.add(key);
return true;
};
}
export function askUnresolvableNotice(facts) {
const { sessionId, sourceSessionId, agentId, toolName, toolCallId, cause, parkLaneExisted, remedy, remedies, notResumableWayOut, notResumableSource, parkTargetGap, parkFailed, parkFailedReason, question, unbindable, workflowParkGap } = facts;
if (typeof sessionId !== "string" || sessionId.length === 0) {
throw new TypeError("delegation.ask_unresolvable: sessionId is required — a user-audience notice with no session routes nowhere");
}
if (sourceSessionId !== undefined && (typeof sourceSessionId !== "string" || sourceSessionId.length === 0)) {
throw new TypeError("delegation.ask_unresolvable: sourceSessionId, when present, names the delegated leg's session");
}
if (agentId !== undefined && (sourceSessionId === undefined || typeof agentId !== "string" || agentId.length === 0)) {
throw new TypeError("delegation.ask_unresolvable: agentId, when present, is a non-empty id riding beside sourceSessionId");
}
const delegated = sourceSessionId !== undefined;
if (typeof toolName !== "string" || toolName.length === 0) {
throw new TypeError("delegation.ask_unresolvable: toolName is required");
}
if (typeof toolCallId !== "string" || toolCallId.length === 0) {
throw new TypeError("delegation.ask_unresolvable: toolCallId is required");
}
if (!isAskUnresolvableCause(cause)) {
throw new TypeError(`delegation.ask_unresolvable: cause ${JSON.stringify(cause)} is not one of ${ASK_UNRESOLVABLE_CAUSES.join("/")}`);
}
if (notResumableSource !== undefined && notResumableSource !== "lane" && notResumableSource !== "host") {
throw new TypeError(`delegation.ask_unresolvable: notResumableSource ${JSON.stringify(notResumableSource)} is not one of lane/host`);
}
if (parkFailed !== undefined && (typeof parkFailed !== "string" || parkFailed.length === 0 || (typeof parkTargetGap === "string" && parkTargetGap.length > 0) || parkLaneExisted !== true || workflowParkGap !== undefined)) {
throw new TypeError("delegation.ask_unresolvable: parkFailed, when present, is the failed park attempt's non-empty sentence on a leg whose park lane was armed, never beside parkTargetGap or workflowParkGap");
}
if (parkFailedReason !== undefined && (parkFailed === undefined || !isSuspendLaneReason(parkFailedReason))) {
throw new TypeError(`delegation.ask_unresolvable: parkFailedReason, when present, rides beside parkFailed and is one of ${SUSPEND_LANE_REASONS.join("/")}`);
}
const parkGap = workflowParkGap === undefined || !Array.isArray(workflowParkGap) ? undefined : WORKFLOW_PARK_GAPS.filter((w) => workflowParkGap.includes(w));
if (workflowParkGap !== undefined && (parkGap === undefined || workflowParkGap.length === 0 || parkGap.length !== workflowParkGap.length || !workflowParkGap.every(isWorkflowParkGap))) {
throw new TypeError(`delegation.ask_unresolvable: workflowParkGap, when present, is a non-empty list of distinct words of ${WORKFLOW_PARK_GAPS.join("/")}`);
}
let remedyList;
if (remedies !== undefined) {
if (typeof remedy !== "string" || remedy.length === 0 || !Array.isArray(remedies) || remedies.length === 0) {
throw new TypeError("delegation.ask_unresolvable: remedies are a non-empty list of ways out riding beside the remedy sentence they restate");
}
remedyList = [];
for (let i = 0; i < remedies.length; i++) {
const read = Object.hasOwn(remedies, i) ? readApprovalRemedy(remedies[i]) : undefined;
if (read === undefined)
throw new TypeError(`delegation.ask_unresolvable: remedies[${i}] is not one way out of the closed set (${APPROVAL_REMEDY_KINDS.join("/")}) with exactly its own fields`);
remedyList.push(read);
}
}
const parkAt = remedyList?.findIndex((r) => r.kind === "park") ?? -1;
if ((parkFailed !== undefined) !== (parkAt >= 0) || parkAt > 0 || (remedyList?.filter((r) => r.kind === "park").length ?? 0) > 1) {
throw new TypeError("delegation.ask_unresolvable: a `park` way out rides exactly where parkFailed does, once, first of the remedies");
}
const why = ASK_UNRESOLVABLE_CAUSE_WORDS[cause];
const heldBack = typeof parkTargetGap === "string" && parkTargetGap.length > 0;
const parkFailedSaid = typeof parkFailed === "string" && parkFailed.length > 0;
const wayOn = typeof notResumableWayOut === "string" && notResumableWayOut.length > 0 ? (CAUSE_SAYS_NO_WAIT[cause] ? `To go on: ${notResumableWayOut}.` : `This part of the run cannot keep an approval waiting for a person — to go on: ${notResumableWayOut}.`) : heldBack ? `This part of the run cannot keep an approval waiting for a person, so nothing was set aside to wait for one. ${PERSON_WAY_ON}` : parkFailedSaid ? `The attempt to set it aside to wait for a person's approval failed. ${PERSON_WAY_ON}` : PERSON_WAY_ON;
const call = `"${toolName}"${delegated ? ` (a ${DELEGATED}'s call)` : ""}`;
return {
code: "delegation.ask_unresolvable",
message: question === true
? `A question${delegated ? ` a ${DELEGATED} asked` : " the agent asked"} was not put to anyone: ${why}. It went unanswered, and the agent was told to go on with its best judgment.`
: unbindable === true
? `${call} did not run: no approval can be tied to its arguments as they were written, so nobody could approve this call — it has to be changed.`
: `${call} did not run: it needed someone's approval, and ${why}. ${wayOn}`,
detail: { sessionId, ...(delegated ? { sourceSessionId } : {}), ...(agentId !== undefined ? { agentId } : {}), toolName, toolCallId, cause, parkLaneExisted: parkLaneExisted === true, ...(typeof remedy === "string" && remedy.length > 0 ? { remedy } : {}), ...(remedyList !== undefined ? { remedies: remedyList } : {}), ...(notResumableSource !== undefined ? { notResumableSource } : {}), ...(heldBack ? { parkTargetGap } : {}), ...(parkFailedSaid ? { parkFailed, ...(parkFailedReason !== undefined ? { parkFailedReason } : {}) } : {}), ...(parkGap !== undefined ? { workflowParkGap: parkGap } : {}) },
};
}