UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

464 lines (463 loc) • 31.4 kB
import { DENIED_BY_MAY_ECHO, modeReleaseOf, readDenyTableOf, screenGateOutcome, SETTLEMENT_IS_REFUSAL } from "../gate-outcome.js"; import { traceHookCrash } from "../gate-crash-trace.js"; import { thrownText } from "../thrown-value.js"; import { ASK_CLASSES, askFaceOf, classifyAsk, headlessApprovalRemedy, withParkRemedy, NOBODY_CAN_APPROVE, unresolvedAskDenialMessage } from "../ask-origin.js"; import { confinedCallOf } from "../shell-read-silence.js"; import { NOT_RESUMABLE_CARRY_ON, notResumableWayOut } from "../park-resumability.js"; import { wireOf } from "../tool-name-readings.js"; import { isProtectedWrite } from "../tool-registry.js"; import { attestationOf, decisionText, foldHookAsk, licenseCovers } from "../tool-policy.js"; import { engineSentenceOf, hostWindowUnanswered } from "../engine-attestation.js"; import { pathDenialCardOf } from "../../tools/fs/safety.js"; import { argsAsTheToolReads } from "../effective-path-target.js"; import { rewriteRecordOf } from "../rewrite-rejudge.js"; import { askUnresolvableRemedySeat } from "../ask-unresolvable-notice.js"; import { foreignLine } from "../protocol-http-auth.js"; import { isSuspendLaneReason } from "../suspend-lane-reasons.js"; import { unavailableLandingOf } from "../unavailable-landing.js"; import { notRecordedMark } from "../redaction-marks.js"; import { formatHookFeedback } from "../reminder-mint.js"; import { types } from "node:util"; import { receive } from "../mods/kernel/receive.js"; import { namedRegistration } from "../mods/kernel/registration.js"; import { describeBindingFault, MAX_DEPTH } from "../canonical-json.js"; export function mintGateOutcome(facts) { const settlement = facts.settled !== undefined ? Object.freeze({ ...facts.settled.settlement, who: Object.freeze({ ...facts.settled.settlement.who }) }) : undefined; const extension = namedRegistration(facts.extension); const attribution = facts.classifier !== undefined ? Object.freeze({ ...facts.classifier, ...(facts.classifier.fallback !== undefined ? { fallback: Object.freeze({ ...facts.classifier.fallback }) } : {}) }) : undefined; const outcome = Object.freeze({ disposition: Object.freeze(facts.deniedBy !== undefined ? { kind: "denied", deniedBy: facts.deniedBy, ...(facts.cause !== undefined ? { cause: facts.cause } : {}), ...(facts.reason !== undefined ? { reason: facts.reason } : {}), ...(facts.category !== undefined ? { category: facts.category } : {}), ...(extension !== undefined ? { extension } : {}), ...(facts.echoed !== undefined ? { echoed: Object.freeze(facts.echoed.map((e) => Object.freeze({ ...e }))) } : {}), ...(attribution !== undefined ? { classifier: attribution } : {}), ...(facts.modeRefusal !== undefined ? { mode: facts.modeRefusal.mode, askClass: facts.modeRefusal.askClass, classes: Object.freeze([...facts.modeRefusal.classes]) } : {}), } : { kind: "allowed", ...(attribution !== undefined ? { classifier: attribution } : {}), ...(facts.asked !== undefined ? { asked: Object.freeze({ askClass: facts.asked.askClass, classes: Object.freeze([...facts.asked.classes]) }) } : {}), ...(facts.released !== undefined ? { released: Object.freeze({ ...facts.released, classes: Object.freeze([...facts.released.classes]), ...((u) => (u !== undefined ? { readUnestablished: Object.freeze({ ...u, tiers: Object.freeze([...u.tiers]), rows: Object.freeze([...u.rows]) }) } : {}))(facts.released.readUnestablished) }) } : {}), ...(facts.clearedBy !== undefined ? { clearedBy: Object.freeze({ ...facts.clearedBy, entries: Object.freeze([...facts.clearedBy.entries]), ...(facts.clearedBy.positions !== undefined ? { positions: Object.freeze([...facts.clearedBy.positions]) } : {}) }) } : {}), }), ...(facts.settled !== undefined ? { settlement: settlement, origin: facts.settled.origin } : {}), }); const defects = screenGateOutcome(outcome, { reading: "producer" }); if (defects.length > 0) throw new Error(`the tool gate composed an outcome that violates its own record: ${defects.join("; ")}`); return outcome; } const TRACED_TABLE_SEATS = new WeakSet(); export function releaseRecordOf(pass, verdict) { if (pass.shellReadUnestablished !== true) return modeReleaseOf(verdict); return modeReleaseOf(verdict, (pass.unappliedTable ??= unappliedTableOf(pass))); } function unappliedTableOf(pass) { const seat = pass.input.readDenyInForce; if (seat === undefined) return "unread"; const failed = (what) => { if (typeof seat === "function") { if (TRACED_TABLE_SEATS.has(seat)) return "unread"; TRACED_TABLE_SEATS.add(seat); } traceHookCrash(pass.input, new Error(`the read-deny table for the release record of tool "${pass.toolName}" (toolCallId ${pass.toolCallId}) ${what}; the record says no table was read (\`tableUnread\`), and this seat's later failures are not traced again`), pass.notifier); return "unread"; }; let answer; try { answer = seat(pass.toolCallId); } catch (err) { return failed(`could not be read: ${thrownText(err)}`); } return readDenyTableOf(answer) ?? failed("is not two lists of strings"); } export function directDeny(deniedBy, extension) { return mintGateOutcome({ deniedBy, ...(extension !== undefined ? { extension } : {}) }); } const SETTLEMENT_IS_HUMAN = { human_allowed: true, human_refused: true, approval_window_expired: false, denial_limit_window_expired: false, park_sla_expired: false, no_approver: false, approver_unavailable: false, approver_error: false, approver_contract: false, presentation_failed: false, blanket_allow_refused: false, policy_allowed: false, policy_refused: false, task_aborted: false, approval_withdrawn: false, manager_allowed: false, manager_refused: false, }; const answerGroupOf = (r) => ({ ...(r.inputDigest !== undefined ? { licensed: r.inputDigest } : {}), ...(r.classes !== undefined ? { classes: r.classes } : {}) }); const sameClasses = (a, b) => a === undefined || b === undefined ? a === b : a.length === b.length && a.every((c, i) => c === b[i]); export function createSettlementLedger(call) { let settled; let yeses = []; const write = (next) => { settled = next; if (SETTLEMENT_IS_HUMAN[next.settlement.kind] && !SETTLEMENT_IS_REFUSAL[next.settlement.kind]) yeses.push(next); }; const contractRefusal = (origin) => ({ settlement: { kind: "approver_contract", who: { party: "none" }, when: Date.now() }, origin }); return { get settled() { return settled; }, get answered() { const held = new Set(yeses.flatMap((y) => y.classes ?? [])); return held.size > 0 ? ASK_CLASSES.filter((c) => held.has(c)) : undefined; }, set(next) { write(next); }, fromResolved(resolved, asked, req) { const record = attestationOf(resolved, call); const retired = typeof resolved === "object" && resolved !== null && Object.hasOwn(resolved, "settlement"); if (asked.action !== "ask" || asked.origin === undefined) { if (resolved.action === "allow" && record?.settlement === undefined && !retired) return resolved; throw new Error(`an ask for "${call.toolName}" was resolved without an origin word — the origin stamp precedes every resolution`); } const origin = asked.origin; const refused = (message, by) => { write(by); return { action: "deny", message, decisionReason: "mode" }; }; if (retired) { return refused(`the resolution for "${call.toolName}" carries the retired "settlement" member — what ended a wait is an engine-minted record ` + `(\`attestation\`), never a resolver's member; denied fail-closed rather than recording a settlement nobody can attribute`, contractRefusal(origin)); } const edited = resolved.action === "allow" && resolved.updatedInput !== undefined; const licensed = () => edited ? licenseCovers(record.inputDigest, call.toolName, resolved.updatedInput) : licenseCovers(record.inputDigest, call.toolName, req.args) && (resolved.presentedInput === undefined || licenseCovers(record.inputDigest, call.toolName, resolved.presentedInput)); const bound = record?.settlement !== undefined && record.origin === origin && sameClasses(record.classes, asked.classes) ? record.settlement : undefined; const refusal = bound !== undefined && SETTLEMENT_IS_REFUSAL[bound.kind] ? bound : undefined; if (resolved.action === "allow") { if (refusal !== undefined) return refused(`the resolution for "${call.toolName}" answered allow but its engine record names a refusal ("${refusal.kind}") — denied fail-closed`, { settlement: refusal, origin }); const answer = bound !== undefined && licensed() ? bound : undefined; if (answer !== undefined) { if (asked.requiresRealApproval === true && !SETTLEMENT_IS_HUMAN[answer.kind]) { return refused(`approval required for "${call.toolName}" — this ask requires real approval; the resolution's engine record names an answer that is not a person's ("${answer.kind}") — denied fail-closed: ${asked.message ?? ""}`, contractRefusal(origin)); } write({ settlement: answer, origin, ...answerGroupOf(record) }); return resolved; } if (asked.requiresRealApproval === true) { return refused(`approval required for "${call.toolName}" — this ask requires real approval and the resolution's allow carries no engine ` + `settlement record for it (an answer the engine cannot attribute to anyone); denied fail-closed: ${asked.message ?? ""}`, contractRefusal(origin)); } return resolved; } if (resolved.action !== "deny") return resolved; write(refusal !== undefined ? { settlement: refusal, origin } : contractRefusal(origin)); return resolved; }, fromDecision(decision) { if (decision.action === "ask") return { decision }; const record = attestationOf(decision, call); const answer = record?.settlement !== undefined && record.origin !== undefined ? { settlement: record.settlement, origin: record.origin, ...answerGroupOf(record) } : undefined; if (answer !== undefined) write(answer); const refusal = answer !== undefined && SETTLEMENT_IS_REFUSAL[answer.settlement.kind]; if (decision.action === "allow") { if (!refusal) return { decision }; return { decision: { action: "deny", message: `the decision for "${call.toolName}" says allow but its engine record names a refusal ("${answer.settlement.kind}") — denied fail-closed`, decisionReason: "rule" }, deniedBy: "ask_resolution" }; } return { decision, deniedBy: record?.stationRefusal?.layer ?? (refusal ? "ask_resolution" : "policy") }; }, keepForBytes(runs) { if (settled !== undefined && !licenseCovers(settled.licensed, call.toolName, runs)) settled = undefined; yeses = yeses.filter((y) => licenseCovers(y.licensed, call.toolName, runs)); }, causeOf(decision) { return decision.action === "deny" ? attestationOf(decision, call)?.classifierCause : undefined; }, classifierRoundOf(decision) { return attestationOf(decision, call)?.classifierRound; }, classifierAskedOf(decision) { return attestationOf(decision, call)?.classifierAsked; }, supersede() { settled = undefined; yeses = []; }, }; } function cloneObserverInput(input) { try { return structuredClone(input); } catch { if (Array.isArray(input)) return [...input]; if (input !== null && typeof input === "object") return { ...input }; return input; } } export function permissionDeniedOf(refusal) { const { toolName, finalInput, toolCallId, reason, gate, identity, permissionMode } = refusal; return { toolName, input: cloneObserverInput(finalInput), toolCallId, reason, gate, ...(identity !== undefined ? { identity } : {}), ...(permissionMode !== undefined ? { permissionMode } : {}) }; } export function refusalWordsOf(gate) { const d = gate?.disposition; if (d?.kind !== "denied") return undefined; return { deniedBy: d.deniedBy, ...(gate?.settlement !== undefined ? { settlement: gate.settlement.kind } : {}) }; } const RECORD_RECEIPT = Object.freeze({ accessors: "refuse", depth: MAX_DEPTH, others: "refuse", contain: true, isProxy: (v) => types.isProxy(v) }); export function frozenInputSnapshot(input) { const received = receive(input, RECORD_RECEIPT); if (!received.ok) return notRecorded(input, received.fault); const record = received.value; const symbolMarkers = new Map(); for (const fault of received.faults ?? []) { const above = fault.path.slice(0, -1); const holder = memberAt(record, above); const last = fault.path[fault.path.length - 1]; if (typeof holder !== "object" || holder === null || last === undefined) continue; const rawHolder = memberAt(input, above); const symbolKeyed = fault.kind === "hidden" && (Object.hasOwn(holder, last) || typeof rawHolder !== "object" || rawHolder === null || !Object.hasOwn(rawHolder, last)); if (symbolKeyed) { const listed = symbolMarkers.get(holder); if (listed === undefined) symbolMarkers.set(holder, [notRecorded(input, fault)]); else listed.push(notRecorded(input, fault)); } else Object.defineProperty(holder, last, { value: notRecorded(input, fault), enumerable: true, writable: true, configurable: true }); } for (const [holder, markers] of symbolMarkers) { let key = notRecordedMark("symbol-keyed members"); while (Object.hasOwn(holder, key)) key += "'"; Object.defineProperty(holder, key, { value: markers, enumerable: true, writable: true, configurable: true }); } return freezeRecord(record); } function freezeRecord(record) { const pending = [record]; for (let at = pending.pop(); at !== undefined || pending.length > 0; at = pending.pop()) { if (typeof at !== "object" || at === null || Object.isFrozen(at)) continue; Object.freeze(at); for (const member of Object.values(at)) pending.push(member); } return record; } const notRecorded = (input, fault) => notRecordedMark(describeBindingFault(input, fault)); function memberAt(value, path) { let at = value; for (const key of path) at = typeof at === "object" && at !== null ? at[key] : undefined; return at; } const PARK_FAILURE_CAUSE_MAX = 600; const suspendLaneReasonOf = (v) => (isSuspendLaneReason(v) ? v : undefined); function withParkFailureCause(reason, park, nobodyJudged) { if (park === undefined) return reason; if (park.kind === "no_target") return `${reason} — note: no durable park was attempted for this call, because this leg cannot hold one (${foreignLine(park.gap, PARK_FAILURE_CAUSE_MAX)}).`; const note = `${reason} — note: a durable approval park was attempted for this call and could not be minted (${foreignLine(park.cause, PARK_FAILURE_CAUSE_MAX)})`; return nobodyJudged ? `${note}; with nobody to judge the call, that is why it stopped — it can be issued again once its park can be minted.` : `${note}.`; } export const RE_ASKED_WAY_ON = "nobody could judge it this time; issued again, it is asked again, and it runs if its approver allows it then"; function wayOnOf(row) { if (!row.nobodyJudged || row.question || row.unbindable) return undefined; if (row.legHoldsNoPark && row.seatReAsked) return RE_ASKED_WAY_ON; if (!row.nobodyMayAnswer) return undefined; return row.nobodyRemedy !== undefined ? row.nobodyRemedy() : row.wayOut !== undefined ? NOBODY_CAN_APPROVE : undefined; } export function parkFailedBase(text, minted, park) { if (park === undefined || minted === undefined || !text.startsWith(minted.text)) return text; return `${unresolvedAskDenialMessage(minted.cause, minted.question, true)}${text.slice(minted.text.length)}`; } export function takeInheritedScreen(pass, read) { if (read?.floated !== undefined) pass.hookAsk = pass.hookAsk !== undefined ? foldHookAsk(pass.hookAsk, read.floated) : read.floated; pass.inheritedAllowedBy = read !== undefined && read.allowedBy.length > 0 ? read.allowedBy : undefined; if (read?.approved !== undefined) pass.screenApproval = read.approved; } export function settledScreen(read, judged) { return { kind: "settled", deny: read.decision, deniedBy: read.deniedBy ?? "policy", ...(read.cause !== undefined ? { cause: read.cause } : {}), ...judged }; } export function takeSettledScreen(pass, settled) { pass.deniedBy = settled.deniedBy; pass.denyCause = settled.cause; return settled.deny; } export async function settledScreenExit(pass, settled) { pass.decision = takeSettledScreen(pass, settled); return await exitGate(pass); } export function passAskFace(pass) { return askFaceOf(wireOf("gate.askFace", pass.req)); } export async function engineFailClosedExit(pass, reason, extension) { const { input, toolName, toolCallId, notifyPermissionDenied } = pass; const gate = directDeny("hook", extension); const finalInput = frozenInputSnapshot(pass.currentInput); await notifyPermissionDenied(permissionDeniedOf({ toolName, finalInput, toolCallId, reason, gate, identity: input.identity })); return { block: true, reason: formatHookFeedback(reason, input.reminderMark), gate, finalInput, preToolContext: pass.preToolContext }; } export const unownedArgsMessage = (subject, reason) => `${subject} could not be taken into the gate's own copy (${reason}) — denied fail-closed`; export async function untakenValueExit(pass, untaken) { pass.currentInput = untaken.value; pass.decision = { action: "deny", message: untaken.message }; pass.deniedBy = untaken.deniedBy; return await exitGate(pass); } export async function unownedArgsExit(pass, reason) { return await untakenValueExit(pass, { value: pass.currentInput, message: unownedArgsMessage(`the arguments of "${pass.toolName}"`, reason), deniedBy: "policy" }); } export function hookDenyExit(pass, deniedReason, extension) { const { input } = pass; return { block: true, reason: formatHookFeedback(deniedReason, input.reminderMark), gate: directDeny("hook", extension), finalInput: frozenInputSnapshot(pass.currentInput), preToolContext: pass.preToolContext, }; } const ancestorUnresolvedClassification = (call) => classifyAsk({ action: "ask", message: "" }, { call, contentQuestion: false, markedUnresolvable: true, org: undefined, tightened: undefined, mandateMarks: {} }); function unresolvableCauseOfSettlement(gate, record) { if (gate.disposition.kind !== "denied" || gate.disposition.deniedBy !== "ask_resolution" || gate.settlement === undefined) return undefined; if (gate.settlement.kind === "approver_unavailable") return "approver_unavailable"; if (gate.settlement.kind === "no_approver") return "no_approver_wired"; if (gate.settlement.kind === "approval_window_expired" && hostWindowUnanswered(record)) return "approval_window_expired"; return undefined; } function refusalEchoOf(pass, call) { const by = pass.deniedBy; if (by === undefined || !DENIED_BY_MAY_ECHO[by]) return undefined; return by === "read_boundary" ? pass.denyEchoed : by === "ask_resolution" ? engineSentenceOf(pass.decision, call)?.echoed : undefined; } function classifierBlockOf(pass, call) { if (pass.deniedBy === undefined || pass.denyCause !== undefined) return undefined; const said = attestationOf(pass.decision, call)?.classifierBlock; return said === undefined ? undefined : { ...(said.reason !== undefined ? { reason: said.reason } : {}), ...(said.category !== undefined ? { category: said.category } : {}) }; } export async function exitGate(pass) { const { input, toolName, toolCallId, ledger, notifyPermissionDenied } = pass; if (pass.decision.action === "deny") { if (pass.decision.updatedInput !== undefined) { pass.currentInput = argsAsTheToolReads(pass.req, pass.decision.updatedInput); } if (pass.deniedBy === undefined) throw new Error(`the tool gate refused "${toolName}" without a refusing layer — every deny site attributes itself`); const ancestorArbitration = pass.arbitration === undefined && pass.deniedBy === "policy" ? input.ancestorArbitrationOf?.(toolCallId) : undefined; const modeRefusal = pass.arbitration?.kind === "denied_by_mode" ? pass.arbitration : ancestorArbitration?.kind === "denied_by_mode" ? ancestorArbitration : undefined; if (modeRefusal !== undefined) { pass.deniedBy = "mode"; ledger.supersede(); } const echoed = refusalEchoOf(pass, { toolCallId, toolName }); const blockSaid = classifierBlockOf(pass, { toolCallId, toolName }); const gate = mintGateOutcome({ deniedBy: pass.deniedBy, ...(pass.deniedBy === "hook" && pass.deniedExtension !== undefined ? { extension: pass.deniedExtension } : {}), ...(echoed !== undefined ? { echoed } : {}), ...(pass.denyCause !== undefined ? { cause: pass.denyCause } : {}), ...(blockSaid ?? {}), ...(ledger.settled !== undefined ? { settled: ledger.settled } : {}), ...(pass.classifierRound !== undefined ? { classifier: pass.classifierRound } : {}), ...(modeRefusal !== undefined ? { modeRefusal: { mode: modeRefusal.mode, askClass: modeRefusal.askClass, classes: modeRefusal.classes } } : {}) }); const foldCause = attestationOf(pass.decision, { toolCallId, toolName })?.unresolvableCause; const unresolvable = foldCause ?? unresolvableCauseOfSettlement(gate, attestationOf(pass.decision, { toolCallId, toolName })); const tableSeat = unresolvable !== undefined ? askUnresolvableRemedySeat(unresolvable) : undefined; const remedySeat = tableSeat === "absent" && input.askSeatForm === "declared_none" && pass.askClassification?.classes.has("content_question") !== true ? "declared_none" : tableSeat === "unavailable" && input.askSeatForm === "policy_callback" ? "policy" : tableSeat; const bindingRefusal = attestationOf(pass.decision, { toolCallId, toolName })?.bindingRefusal; const wayOut = input.notResumable !== undefined ? notResumableWayOut(input.notResumable.source, input.notResumable.mandated, pass.askClassification?.classes.has("content_question") === true ? "answer" : "approval") : undefined; const floated = ledger.settled?.origin === "ancestor_marked"; const parkCanWait = unavailableLandingOf({ parkRoute: pass.suspendAsk !== undefined, suspendTargetGap: floated ? undefined : pass.suspendTargetGap, attemptFailed: false, question: false, durableQuestionFace: undefined }) === "park"; const nobodyMayAnswer = input.askSeatForm !== undefined && input.askSeatForm !== "callback" && !parkCanWait && pass.askClassification?.classes.has("content_question") !== true; const remedyOf = (approverSeat) => headlessApprovalRemedy({ mode: input.permissionMode?.(), classification: foldCause !== undefined ? ancestorUnresolvedClassification(pass.req) : pass.askClassification, approverSeat, ...(input.approvalParkWithheld === true ? { approvalParkWithheld: true } : {}), coveredWrite: isProtectedWrite(pass.req), ...(pass.shellUnplacedOptions !== undefined ? { unplacedOptions: pass.shellUnplacedOptions } : {}), ...(pass.shellWriteAskRow?.ownCard === true ? { writeAskRowOwnCard: true } : {}), ...(wayOut !== undefined ? { notResumableWayOut: wayOut } : {}), ...confinedCallOf(input.confined, pass, pass.policyRewrite ?? pass.currentInput, input.confined !== undefined ? input.trackedCwd?.() : undefined) }); const headless = bindingRefusal !== undefined || remedySeat === undefined ? undefined : remedyOf(remedySeat); const parkNote = pass.parkFailed !== undefined ? ((r) => ({ kind: "failed", cause: pass.parkFailed, ...(r !== undefined ? { reason: r } : {}) }))(suspendLaneReasonOf(pass.parkFailedReason)) : unresolvable !== undefined && pass.parkTargetGap !== undefined ? { kind: "no_target", gap: pass.parkTargetGap } : undefined; const parkFailedSaid = parkNote?.kind === "failed" && headless !== undefined ? foreignLine(parkNote.cause, PARK_FAILURE_CAUSE_MAX) : ""; const hostWay = headless !== undefined && parkFailedSaid !== "" ? withParkRemedy(headless, parkFailedSaid) : headless; const remedy = hostWay?.sentence; const question = pass.askClassification?.classes.has("content_question") === true; const modelWayOut = wayOnOf({ nobodyJudged: unresolvable !== undefined, question, unbindable: bindingRefusal !== undefined, legHoldsNoPark: !floated && parkNote?.kind === "no_target", seatReAsked: input.askSeatForm === undefined || input.askSeatForm === "callback" || input.askSeatForm === "policy_callback", nobodyMayAnswer, nobodyRemedy: remedy !== undefined ? () => remedyOf("nobody").sentence : undefined, wayOut }); const base = parkFailedBase(decisionText(pass.decision) ?? `tool "${toolName}" denied by policy`, attestationOf(pass.decision, { toolCallId, toolName })?.unanswered, parkNote); const tail = question ? "" : remedy !== undefined || (modelWayOut !== undefined && wayOut === undefined) ? ` — ${modelWayOut ?? remedy}` : unresolvable !== undefined && wayOut !== undefined && bindingRefusal === undefined ? (modelWayOut !== undefined ? `. To go on: ${modelWayOut}.` : `. To go on: ${wayOut}. ${NOT_RESUMABLE_CARRY_ON}`) : ""; const denyReason = withParkFailureCause(`${tail.startsWith(".") ? base.replace(/\.$/, "") : base}${tail}`, parkNote, unresolvable !== undefined && !question); if (unresolvable !== undefined) { const cause = unresolvable; const noticeRemedy = bindingRefusal ?? remedy; pass.notifier.notify(() => input.onAskUnresolvable?.({ toolName, toolCallId, cause, parkLaneExisted: pass.suspendAsk !== undefined, ...(parkNote?.kind === "no_target" ? { parkTargetGap: parkNote.gap } : {}), ...(parkFailedSaid !== "" ? { parkFailed: parkFailedSaid, ...(parkNote?.kind === "failed" && parkNote.reason !== undefined ? { parkFailedReason: parkNote.reason } : {}) } : {}), ...(noticeRemedy !== undefined ? { remedy: noticeRemedy } : {}), ...(modelWayOut !== undefined ? { modelRemedy: modelWayOut } : {}), ...(hostWay !== undefined ? { remedies: hostWay.remedies } : {}), ...(wayOut !== undefined && input.notResumable !== undefined ? { notResumableWayOut: wayOut, notResumableSource: input.notResumable.source } : {}), ...(question ? { question: true } : {}), ...(bindingRefusal !== undefined ? { unbindable: true } : {}) }), "toolGate.onAskUnresolvable"); } const finalInput = frozenInputSnapshot(pass.currentInput); await notifyPermissionDenied(permissionDeniedOf({ toolName, finalInput, toolCallId, reason: denyReason, gate, identity: input.identity })); return { block: true, reason: formatHookFeedback(denyReason, input.reminderMark), gate, finalInput, ...(() => { const record = attestationOf(pass.decision, { toolCallId, toolName }); const details = pathDenialCardOf(record?.pathDenial) ?? record?.stationRefusal?.details ?? pass.denyDetails ?? (modeRefusal !== undefined ? undefined : pass.shellReadDetails); return details !== undefined ? { details } : {}; })(), preToolContext: pass.preToolContext, }; } if (pass.decision.action === "allow") { const rw = pass.decision.updatedInput !== undefined ? pass.decision.updatedInput : pass.policyRewrite; if (rw !== undefined) pass.currentInput = argsAsTheToolReads(pass.req, rw); } ledger.keepForBytes(pass.currentInput); const crossBoundary = await input.crossBoundaryCheck?.exit({ toolName, args: pass.currentInput, toolCallId }, ledger.answered); if (crossBoundary !== undefined) { pass.decision = { action: "deny", message: crossBoundary.message, decisionReason: "safety" }; pass.deniedBy = "policy"; return exitGate(pass); } const release = pass.arbitration?.kind === "released" ? pass.arbitration : (() => { if (ledger.settled !== undefined) return undefined; const a = pass.arbitration === undefined ? input.ancestorArbitrationOf?.(toolCallId) : undefined; return a?.kind === "released" ? a : undefined; })(); const stationClear = pass.clearedBy === undefined && pass.classifierAsked === undefined && ledger.settled === undefined && release === undefined ? input.ancestorClearanceOf?.(toolCallId) : undefined; if (stationClear !== undefined) { if (input.permissionMode === undefined || input.permissionMode() === "auto") input.autoMode?.denialTracking?.recordAllow(); await pass.notifier.notifyAsync(() => input.persistedRules?.onResolved?.({ toolName, toolCallId, rules: stationClear.rules }), "toolGate.persistedRuleResolved"); } const clearedBy = pass.clearedBy ?? stationClear?.clearedBy; const finalInput = frozenInputSnapshot(pass.currentInput); const rewrite = rewriteRecordOf(pass.rewrites, pass.req, pass.currentInput, finalInput); return { updatedInput: pass.currentInput, gate: mintGateOutcome({ ...(ledger.settled !== undefined ? { settled: ledger.settled } : {}), ...(pass.classifierRound !== undefined ? { classifier: pass.classifierRound } : {}), ...(pass.classifierRound !== undefined && pass.classifierAsked !== undefined && ledger.settled === undefined && release === undefined && clearedBy === undefined ? { asked: pass.classifierAsked } : {}), ...(release !== undefined ? { released: releaseRecordOf(pass, release) } : {}), ...(clearedBy !== undefined && ledger.settled === undefined && release === undefined ? { clearedBy } : {}) }), finalInput, ...(rewrite !== undefined ? { rewrite } : {}), preToolContext: pass.preToolContext, }; }