@sema-agent/core
Version:
Stateless, task-oriented AI agent core
116 lines (115 loc) • 9.15 kB
JavaScript
import { classifyQuestionOutcome, isLiveQuestionFace, QUESTION_OUTCOME_FAULT_TEXT } from "../ask-question.js";
import { capturedJsonOf, editOfAnswer, exactBoundInputHashOf } from "../canonical-json.js";
import { bindingRefusalOf } from "../tool-policy.js";
import { CheckpointError, checkpointVersionOf, winnerFromOutcome } from "../checkpoint-store.js";
import { isGateKind, resumeGateMatches } from "../pause-registry.js";
import { sanitizeUntrustedText, sentinelTagRefusal } from "../untrusted-text.js";
import { assertOutcomeText, captureHostDecision, describeSuppliedValue, pendingContentAskCallId, refuseSuppliedKeys, sameWinner, SUPPLIED_RECORD_KEY } from "./decide-continuation.js";
import { refuseUnfitFeedback } from "./approval-feedback.js";
const REFUSED_DECIDE_KEYS = [
SUPPLIED_RECORD_KEY,
["settledBy", 'a retired key — the host supplies decision FACTS as hostDecision{decidedBy: "person" | "sla_timeout" | "policy", approver?} and core mints the settlement word from them'],
["approver", "a retired key — the attribution rides the facts it belongs to, as hostDecision.approver"],
];
export function resumePolicyOutcome(input) {
const { cp, outcome, config, runner } = input;
let suppliedAnswer;
let redeemedAnswer;
let plainPolicyOutcome;
const storedGateKind = cp.gate.kind;
if (isGateKind(storedGateKind) && resumeGateMatches(storedGateKind, "policy_ask")) {
const decide = outcome;
suppliedAnswer = decide.answer;
if (suppliedAnswer !== undefined) {
const reading = classifyQuestionOutcome(suppliedAnswer);
if (reading.shape !== "answered") {
const why = reading.shape === "contradictory"
? QUESTION_OUTCOME_FAULT_TEXT[reading.fault]
: 'the value claims "unavailable", which is not an answer';
throw new CheckpointError("checkpoint.invalid_outcome", `resume carried a content-ask \`answer\` that does not read as an answer (${why}) — ` +
"refusing pre-CAS rather than fabricating an empty human response; the checkpoint stays pending", { field: "answer" });
}
redeemedAnswer = reading.answer;
}
const updatedInputRaw = decide.updatedInput;
let updatedInput;
if (updatedInputRaw !== undefined) {
const captured = capturedJsonOf(updatedInputRaw);
if (!captured.ok)
throw new CheckpointError("checkpoint.invalid_outcome", bindingRefusalOf(cp.pendingAction.kind === "tool_approval" ? cp.pendingAction.toolName : "the parked call", updatedInputRaw, captured.fault), { field: "updatedInput" });
updatedInput = captured.value;
}
const decision = decide.decision;
if (decision !== "allow" && decision !== "deny") {
throw new CheckpointError("checkpoint.invalid_outcome", `resume decision "${describeSuppliedValue(decision)}" is outside the policy_ask domain — a decide is exactly "allow" or "deny"; refusing pre-CAS, the checkpoint stays pending`, { field: "decision" });
}
refuseSuppliedKeys(decide, REFUSED_DECIDE_KEYS);
const hostDecision = captureHostDecision(cp, decide.hostDecision, "policy_ask", { word: decision, allows: decision === "allow" });
const reason = decide.reason;
assertOutcomeText(reason, "reason", { field: "reason" });
const feedback = decide.feedback;
assertOutcomeText(feedback, "feedback", { field: "feedback" });
plainPolicyOutcome = {
gate: "policy_ask",
boundCallId: decide.boundCallId,
boundInputHash: decide.boundInputHash,
decision,
...(updatedInput !== undefined ? { updatedInput } : {}),
...(reason !== undefined ? { reason } : {}),
...(feedback !== undefined ? { feedback } : {}),
...(redeemedAnswer !== undefined ? { answer: redeemedAnswer } : {}),
hostDecision,
};
refuseUnfitFeedback(plainPolicyOutcome);
if (plainPolicyOutcome.decision === "deny" && plainPolicyOutcome.reason && sanitizeUntrustedText(plainPolicyOutcome.reason) !== plainPolicyOutcome.reason) {
throw new CheckpointError("checkpoint.invalid_outcome", sentinelTagRefusal("resume deny/reject reason"), { field: "reason" });
}
}
if (plainPolicyOutcome !== undefined) {
const boundTo = cp.pendingAction.kind === "tool_approval" ? cp.pendingAction.toolCallId : undefined;
if (plainPolicyOutcome.boundCallId !== boundTo) {
throw new CheckpointError("checkpoint.invalid_outcome", `resume boundCallId "${plainPolicyOutcome.boundCallId}" does not match the checkpoint's pending tool call "${boundTo ?? "(none)"}" — refusing to apply the decision: read the pending card again and send a decision made for the call it holds (that call's toolCallId as boundCallId)`, { field: "boundCallId" });
}
const boundHash = cp.pendingAction.kind === "tool_approval" ? cp.pendingAction.boundInputHash : undefined;
if (boundHash !== undefined) {
if (plainPolicyOutcome.boundInputHash !== boundHash) {
throw new CheckpointError("checkpoint.invalid_outcome", "resume boundInputHash does not match the checkpoint's pending tool call input — refusing to apply the decision: have the decider review the input the pending card holds and send their decision for it with the card's boundInputHash", { field: "boundInputHash" });
}
}
else {
throw new CheckpointError("checkpoint.invalid_outcome", `resume of a binding-version (v${checkpointVersionOf(cp)}) checkpoint whose pending tool call has no persisted boundInputHash — refusing to resume an unbound binding-version checkpoint (corruption / downgrade guard)`, { reason: "bound_input_hash_missing" });
}
if (cp.reopenReason === "env_failed") {
if (cp.resolvedOutcome === undefined) {
throw new CheckpointError("checkpoint.reopen_revote", "checkpoint was reopened after an env-restore failure (env_failed) but carries no persisted winner to replay — refusing to resume (inconsistent row, fail-closed)");
}
const incoming = winnerFromOutcome(plainPolicyOutcome);
const persistedWinner = (() => {
const w = cp.resolvedOutcome;
if (w?.answer === undefined)
return w;
const reading = classifyQuestionOutcome(w.answer);
return reading.shape === "answered" ? { ...w, answer: reading.answer } : w;
})();
const shown = cp.pendingAction.kind === "tool_approval" ? exactBoundInputHashOf(cp.pendingAction.toolName, cp.pendingAction.args) : undefined;
const asRead = (w) => (w.decision !== "allow" || cp.pendingAction.kind !== "tool_approval" || editOfAnswer(cp.pendingAction.toolName, shown, w.updatedInput) !== undefined ? w : ((plain) => (Reflect.deleteProperty(plain, "updatedInput"), plain))({ ...w }));
if (incoming === undefined || !sameWinner(asRead(incoming), asRead(persistedWinner))) {
throw new CheckpointError("checkpoint.reopen_revote", `this checkpoint was reopened after an env-restore failure (env_failed) — a re-resume is a system retry of the already-approved action, not a re-vote; the supplied decision must replay the persisted winner (boundCallId "${cp.resolvedOutcome.boundCallId}", decision "${cp.resolvedOutcome.decision}"), refusing a different decision`);
}
}
const contentAskCallId = pendingContentAskCallId(cp);
if (suppliedAnswer !== undefined && (contentAskCallId === undefined || plainPolicyOutcome.decision !== "allow")) {
throw new CheckpointError("checkpoint.invalid_outcome", contentAskCallId === undefined
? "resume carried a content-ask `answer` but the checkpoint's pending call is not the reserved question tool — an answer has no consumer on a side-effecting tool's approval; refusing rather than dropping it silently"
: "resume carried a content-ask `answer` on a `deny` — a denial injects a refusal, never an answer; refusing rather than dropping it silently", { field: "answer" });
}
if (contentAskCallId !== undefined && plainPolicyOutcome.decision === "allow" && suppliedAnswer === undefined) {
if (!isLiveQuestionFace(config.onQuestion ?? runner.deps.onQuestion)) {
throw new CheckpointError("checkpoint.invalid_outcome", "resume approved a content-ask (the reserved question tool) without an `answer`, and this resume has no live answering face — " +
'executing the question against nothing would hand the model a fabricated "no human is available" default while consuming the approval; ' +
"re-resume with the operator's answer on the outcome (or deny it), the checkpoint stays pending", { field: "answer" });
}
}
}
return { plainPolicyOutcome, redeemedAnswer };
}