UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

49 lines (48 loc) • 3.18 kB
import { isHumanRefusal } from "../gate-outcome.js"; import { attest } from "../engine-attestation.js"; import { editOfAnswer, exactBoundInputHashOf } from "../canonical-json.js"; export function continuationGateOf(input) { return { judge: async (call, answer) => { let unanswerable = false; let cause; const seats = { resolveAsk: async (decision, req, callSignal) => { const classes = decision.action === "ask" ? decision.classes : undefined; if (answer === "person" && classes !== undefined && classes.length === 1 && classes[0] === "ordinary") { const settlement = { kind: "human_allowed", who: { party: "person" }, when: input.now(), note: "the person's decision for the parked card, continued by the engine" }; return attest({ action: "allow" }, req, { settlement, ...(decision.action === "ask" && decision.origin !== undefined ? { origin: decision.origin } : {}), classes, ...((d) => (d !== undefined ? { inputDigest: d } : {}))(exactBoundInputHashOf(req.toolName, req.args)) }); } const resolved = await input.toolOccurrences.whileHeld(req.toolCallId, "approval", () => (callSignal !== undefined ? input.resolveAskBound(decision, req, callSignal) : input.resolveAskBound(decision, req))); if (resolved.action === "deny" && resolved.approverUnavailable === true) unanswerable = true; return resolved; }, onAskUnresolvable: (facts) => void ((unanswerable = true), (cause = facts.cause)), }; let result; let gate; input.continuationCalls.add(call.toolCallId); try { result = await input.judgeToolCall({ type: "tool_call", toolCallId: call.toolCallId, toolName: call.toolName, input: { ...call.input } }, seats); } finally { gate = input.toolOccurrences.get(call.toolCallId)?.gateRounds.at(-1); if (input.toolOccurrences.get(call.toolCallId) !== undefined) input.toolOccurrences.close(call.toolCallId, "settled"); input.preToolContexts.delete(call.toolCallId); input.blockedToolCalls.delete(call.toolCallId); input.continuationCalls.delete(call.toolCallId); } const block = result !== null && typeof result === "object" && result.block === true; if (!block && editOfAnswer(call.toolName, exactBoundInputHashOf(call.toolName, call.input), result?.updatedInput) !== undefined) return { kind: "call_changed" }; if (!block) return { kind: "allow" }; if (unanswerable) return { kind: "ask_unanswerable", ...(cause === "approval_window_expired" ? { code: cause } : {}) }; const disposition = gate?.disposition; return { kind: "denied", layer: disposition?.kind !== "denied" ? "policy" : disposition.deniedBy, explicit: isHumanRefusal(gate) }; }, }; }