UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

266 lines (265 loc) • 20.8 kB
import { SEND_MESSAGE_TOOL_NAME } from "../../agents/send-message-tool.js"; import { mountedToolRequiresUserInteraction, seatInputsOfCall } from "../mode-policy.js"; import { heldWhileClassifying } from "../auto-mode.js"; import { complianceCallDenial } from "../compliance.js"; import { formatHookFeedback, runToolGate } from "../hooks.js"; import { continuationGateOf } from "./continuation-gate.js"; import { isHumanRefusal, screenGateOutcome } from "../gate-outcome.js"; import { directDeny, frozenInputSnapshot, permissionDeniedOf } from "./gate-exit.js"; import { emitTrace } from "../trace.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { askUnresolvableNotice, askUnresolvableTeller, refusedAskOf } from "../ask-unresolvable-notice.js"; import { approvalRouteOf, callMayTakeParkLane } from "../wiring-manifest.js"; import { classifierUnavailableSeat } from "./classifier-ladder.js"; import { PATH_CONFINABLE_WRITE_TOOLS } from "./session-rule-policy.js"; import { callFaceSeat, rosterToolName, toolCallFaceOf } from "../tool-roster.js"; import { heldBy, heldValues, seatOf, wireOf } from "../tool-name-readings.js"; import { createApprovedCallScreen, createToolResultStation } from "./call-hook-stations.js"; import { callParkRoute, extensionCallOf } from "../mods/extension-call.js"; import { extensionCallOverlap } from "../mods/tool-call.js"; import { leavesByEscape } from "../command-sandbox.js"; import { perTaskEnvParkRefusal } from "../remote-env.js"; import { destinationOnHands } from "./cross-boundary-lane.js"; const PEER_MESSAGE_NAMES = new Set([SEND_MESSAGE_TOOL_NAME]); function screenGateResult(result) { if (result.suspend !== undefined) return { defects: [] }; const gate = result.gate; if (gate === undefined) return { defects: ["a tool-gate result carried no outcome record on a terminal exit — every terminal exit mints one; the frame carries none"] }; const defects = screenGateOutcome(gate, { reading: "producer" }); const blocked = result.block === true; if ((gate.disposition.kind === "denied") !== blocked) { defects.push(`a tool-gate result's outcome reads "${gate.disposition.kind}" on ${blocked ? "a blocked" : "an executing"} call — the two faces of one verdict disagree; the frame carries no outcome`); } return defects.length > 0 ? { defects } : { gate, defects }; } export function isBareHumanRefusal(gate, isDelegatedChild) { return isHumanRefusal(gate) && gate.settlement.note === undefined && !isDelegatedChild; } export function maybeHumanRejectionHalt(input) { if (!isBareHumanRefusal(input.gate, input.isDelegatedChild)) return undefined; return { reason: `This tool call was NOT executed: the user rejected the "${input.toolName}" tool call in the same ` + `assistant message, which stops the rest of the batch. Nothing was run for this call — ` + `re-issue it after the user's direction only if it is still needed.`, details: { error: "gate.batch_halted", code: "gate.batch_halted", rejectedToolCallId: input.toolCallId, rejectedToolName: input.toolName, }, }; } export function prepareGateStations(input) { const { askLane, parkAsk, tools, refusedAsks, toolRosterDeltas, deps, toolCallGateArmedRef, effectivePolicy, egressTools, irreversibleTools, spec, complianceDenies, harness, blockedToolCalls, inheritedAskGrants, inheritedUnavailableAsks, deferredAskIdentities, foldAskClasses, ancestorSandboxAdmissions, preToolContexts, toolOccurrences, hookScreens, batchHaltRef, blockedTracked, hookIdentity, reminderMark, hostTaskId, sessionId, legNotice, handsCwdRef, stampCallTarget, hookEnvFace, writeProtectionCheck, shellReadCheck, crossBoundaryCheck, confinedLeg, readFace, readDenyInForce, irreversibilityTier, reversibilityProbes, abortController, shellGatedTools, autoModeDecider, autoModeDenialTracking, askRoute, notResumable, permissionMode, toolMarkSources, a2aIsolatePeers, a2aInsidePeerOf, ancestorArbitrations, ancestorRuleClears, runId, stopForDenialLimit, permissionRuleLane, permissionRuleOrgLane, questionToolMounted, durableQuestionFace, suspendTargetGap, continuationCalls, workflowParkGap, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, delegation, frameSettlement, seatInputsFor, modBus, inheritedInstallations, commandSandboxArmed, sandboxPlanOf } = input; const noticeAddress = legNotice.route.address; const admitsLegNotice = legNotice.admission; const tellAskUnresolvable = askUnresolvableTeller(noticeAddress); let continuationGate; if (askLane !== undefined && parkAsk !== undefined) { const { adjudicate, resolveAskBound, notifyPermissionDenied, notifyHookError } = askLane; const { resolveContentAsk, suspendAsk } = parkAsk; const writeProtectionArmed = writeProtectionCheck !== undefined && tools.some((t) => PATH_CONFINABLE_WRITE_TOOLS.has(t.name)); toolCallGateArmedRef.armed = effectivePolicy !== undefined || modBus.hasHandlers("classic.PreToolUse") || inheritedInstallations.length > 0 || egressTools.size > 0 || irreversibleTools.size > 0 || spec.enablePlanMode === true || complianceDenies.has("web_fetch") || writeProtectionArmed || shellReadCheck !== undefined || crossBoundaryCheck !== undefined || commandSandboxArmed; if (toolCallGateArmedRef.armed) { const judgeToolCall = async (called, seats) => { const e = { ...called, toolName: rosterToolName(toolRosterDeltas.current, called.toolName) }; const call = { toolName: e.toolName, ...callFaceSeat(toolCallFaceOf(toolRosterDeltas.current, called.toolName)) }; toolOccurrences.ensure({ toolCallId: e.toolCallId, spelledName: called.toolName, wireName: e.toolName, args: called.input }); const tierSeat = seatOf("gate.shellSeat", irreversibilityTier, call); const markSources = new Set(heldValues("gate.markSources", toolMarkSources, call).flatMap((s) => [...s])); blockedToolCalls.delete(e.toolCallId); inheritedAskGrants.delete(e.toolCallId); deferredAskIdentities.delete(e.toolCallId); { const complianceDeny = heldValues("gate.compliance", { get: (n) => complianceCallDenial(complianceDenies, n) }, call)[0]; if (complianceDeny !== undefined) { if (blockedTracked) blockedToolCalls.add(e.toolCallId); const gate = directDeny("compliance"); const finalInput = frozenInputSnapshot(e.input); toolOccurrences.gateRound(e.toolCallId, gate, finalInput); if (notifyPermissionDenied) { await notifyPermissionDenied(permissionDeniedOf({ toolName: e.toolName, finalInput, toolCallId: e.toolCallId, reason: complianceDeny, gate, identity: hookIdentity, permissionMode: permissionMode.observed })); } return { block: true, reason: formatHookFeedback(complianceDeny, reminderMark), preToolContext: [] }; } } let result; try { result = await runToolGate({ onNotifyError: (f) => emitTrace(deps.tracer, () => ({ kind: "observer.notify_failed", version: 1, taskId: hostTaskId, site: f.site, message: f.error.message, ts: Date.now() })), event: e, ...(e.signal !== undefined ? { callSignal: e.signal } : {}), identity: hookIdentity, whileScreened: hookScreens.call, reminderMark, modBus, ...(inheritedInstallations.length > 0 ? { inheritedInstallations } : {}), observedPermissionMode: () => permissionMode.observed, ...(handsCwdRef !== undefined ? { trackedCwd: () => handsCwdRef.current } : {}), ...(stampCallTarget !== undefined ? { stampCallTarget } : {}), ...(hookEnvFace !== undefined ? { hookEnv: hookEnvFace } : {}), toolFaceOf: (name) => toolCallFaceOf(toolRosterDeltas.current, name === e.toolName ? called.toolName : name), adjudicate, resolveAsk: seats?.resolveAsk ?? ((...args) => toolOccurrences.whileHeld(args[1].toolCallId, "approval", () => resolveAskBound(...args))), ...(callParkRoute(suspendAsk !== undefined && !continuationCalls.has(e.toolCallId) && callMayTakeParkLane(askRoute.effective, call.face), modBus, e.toolCallId) ? { suspendAsk } : {}), durableQuestionFace, ...(suspendTargetGap !== undefined ? { suspendTargetGap: perTaskEnvParkRefusal(suspendTargetGap) } : {}), resolveContentAsk: (...args) => toolOccurrences.whileHeld(args[0].toolCallId, "approval", () => resolveContentAsk(...args)), egress: heldBy("gate.egress", egressTools, call), peerMessage: heldBy("gate.peerMessage", PEER_MESSAGE_NAMES, call), ...(writeProtectionCheck !== undefined ? { writeProtectionCheck } : {}), ...(shellReadCheck !== undefined ? { shellReadCheck } : {}), ...(crossBoundaryCheck !== undefined ? { crossBoundaryCheck } : {}), readFace, readDenyInForce, irreversibility: tierSeat?.value, reversibilityProbe: tierSeat?.read(reversibilityProbes), abortSignal: abortController.signal, onHookError: notifyHookError, shellGated: tierSeat?.shellGated(shellGatedTools, toolMarkSources) === true, ...(autoModeDecider.current !== undefined ? { autoMode: { decider: heldWhileClassifying(autoModeDecider.current, (toolCallId, judge) => toolOccurrences.whileHeld(toolCallId, "classifier", judge)), ...(autoModeDenialTracking.current !== undefined ? { denialTracking: autoModeDenialTracking.current } : {}), unavailable: classifierUnavailableSeat({ station: "leg", ...(autoModeDecider.current.timeoutMs !== undefined ? { budgetMs: autoModeDecider.current.timeoutMs } : {}), route: approvalRouteOf(askRoute), onNotice: deps.onNotice, admission: admitsLegNotice, ...noticeAddress, runId }) } } : {}), permissionMode: () => permissionMode.current, askSeatForm: askRoute.form, ...(suspendAsk !== undefined && !callMayTakeParkLane(askRoute.effective, undefined) ? { approvalParkWithheld: true } : {}), ...(notResumable !== undefined ? { notResumable } : {}), ...(markSources.size > 0 ? { toolMarkSources: markSources } : {}), ...seatInputsOfCall(seatInputsFor(e.toolName, wireOf("gate.skillActivationSeat", call)), continuationCalls.has(e.toolCallId)), ...(mountedToolRequiresUserInteraction(tools, e.toolName) ? { requiresUserInteraction: true } : {}), ...(commandSandboxArmed ? { leavesCommandSandbox: (args) => leavesByEscape(sandboxPlanOf({ toolName: e.toolName, toolCallId: e.toolCallId, args })) } : {}), ...(confinedLeg !== undefined ? { confined: { staysOnHands: (args) => destinationOnHands(!sandboxBoundaryCapable(call), confinedLeg.legsOf({ toolName: e.toolName, args, toolCallId: e.toolCallId })), bypassArmed: () => permissionMode.armsAs("bypassPermissions") === "bypassPermissions", denyRows: () => confinedLeg.denyRows(e.toolCallId) } } : {}), ...(a2aIsolatePeers === true ? { a2aIsolatePeers: true } : {}), ...((inside) => (inside !== undefined ? { a2aInsidePeer: inside } : {}))(a2aInsidePeerOf(e.toolName)), ancestorArbitrationOf: (toolCallId) => ancestorArbitrations.get(toolCallId), ancestorClearanceOf: (toolCallId) => ancestorRuleClears.get(toolCallId), onHeadlessDenialLimit: stopForDenialLimit, onAskUnresolvable: seats?.onAskUnresolvable ?? ((facts) => { refusedAsks.push(refusedAskOf(facts)); const info = workflowParkGap !== undefined && !facts.parkLaneExisted ? { ...facts, workflowParkGap } : facts; if (tellAskUnresolvable(info)) deliverEngineNotice(deps.onNotice, askUnresolvableNotice({ ...noticeAddress, ...info }), admitsLegNotice); }), ...(permissionRuleLane ? { persistedRules: { adjudicate: permissionRuleLane.adjudicate, onResolved: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.persisted_rule_allowed", version: 2, taskId: hostTaskId, toolName: info.toolName, toolCallId: info.toolCallId, rules: [...info.rules], ts: Date.now(), })), }, } : {}), onReadOnlyAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.read_only_allowed", version: 1, taskId: hostTaskId, toolName: info.toolName, toolCallId: info.toolCallId, command: info.command, ts: Date.now(), })), ...(permissionRuleOrgLane ? { orgRules: { adjudicate: permissionRuleOrgLane.adjudicate, contentAskToolMounted: questionToolMounted, onUnavailable: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.org_snapshot_unavailable", version: 1, taskId: hostTaskId, toolName: info.toolName, toolCallId: info.toolCallId, message: info.message, ts: Date.now(), })), }, } : {}), isMarkedUnresolvable: (toolCallId) => inheritedUnavailableAsks.has(toolCallId), ...(sandboxAdmissionArmed ? { sandboxAdmission: { askClassesOf: (toolCallId) => foldAskClasses.get(toolCallId), boundaryCapable: sandboxBoundaryCapable(call), onAdmitted: emitSandboxAdmitted, }, } : {}), }); } finally { inheritedUnavailableAsks.delete(e.toolCallId); deferredAskIdentities.delete(e.toolCallId); inheritedAskGrants.delete(e.toolCallId); foldAskClasses.delete(e.toolCallId); ancestorArbitrations.delete(e.toolCallId); ancestorRuleClears.delete(e.toolCallId); } const ancestorAdmitted = ancestorSandboxAdmissions.get(e.toolCallId); ancestorSandboxAdmissions.delete(e.toolCallId); if (ancestorAdmitted !== undefined && !result.block && !result.suspend) { emitSandboxAdmitted({ toolCallId: e.toolCallId, toolName: e.toolName, askClasses: ancestorAdmitted, boundary: "sandbox_internal" }); result.preToolContext.push(`permission.sandbox_admitted: this call's inherited pending approval was auto-admitted because the deployment declares an isolated sandbox execution env and the request stays inside it. Recorded for audit.`); } if (!result.block && !result.suspend && result.preToolContext.length > 0) { preToolContexts.set(e.toolCallId, result.preToolContext); } if (blockedTracked && (result.block || result.suspend)) { blockedToolCalls.add(e.toolCallId); } const screened = screenGateResult(result); for (const defect of screened.defects) deps.onError?.(new Error(defect), { phase: "config", sessionId }); if (screened.gate !== undefined) toolOccurrences.gateRound(e.toolCallId, screened.gate, result.finalInput, result.rewrite); if (result.block) { const haltRemaining = seats !== undefined ? undefined : maybeHumanRejectionHalt({ gate: screened.gate, isDelegatedChild: delegation.isDelegatedChild === true, toolName: e.toolName, toolCallId: e.toolCallId, }); const details = result.details !== undefined ? { details: result.details } : {}; if (haltRemaining !== undefined) { batchHaltRef.current = { rejectedToolCallId: e.toolCallId }; return { block: true, reason: result.reason, ...details, haltRemaining }; } return { block: true, reason: result.reason, ...details }; } const overlap = result.suspend === undefined && extensionCallOf(modBus, e.toolCallId) !== undefined ? extensionCallOverlap({ occurrences: toolOccurrences, toolCallId: e.toolCallId, toolName: e.toolName, args: result.finalInput ?? e.input, batchSafe: (n, a) => harness.isBatchSafe(n, a) }) : undefined; if (overlap !== undefined) { toolOccurrences.refuse(e.toolCallId, "hook"); if (blockedTracked) blockedToolCalls.add(e.toolCallId); return { block: true, reason: formatHookFeedback(overlap, reminderMark) }; } if (result.suspend === undefined) toolOccurrences.release(e.toolCallId); const plan = sandboxPlanOf({ toolName: e.toolName, toolCallId: e.toolCallId, args: result.updatedInput !== undefined ? result.updatedInput : e.input }); const planned = plan.kind !== "none" ? { sandboxPlan: plan } : {}; return result.updatedInput !== undefined ? { updatedInput: result.updatedInput, ...planned } : plan.kind !== "none" ? planned : undefined; }; harness.on("tool_call", (called) => judgeToolCall(called)); continuationGate = continuationGateOf({ judgeToolCall, resolveAskBound, toolOccurrences, preToolContexts, blockedToolCalls, continuationCalls, now: () => Date.now() }); } } const toolResultStation = createToolResultStation({ modBus, blockedToolCalls, toolRosterDeltas, preToolContexts, inheritedScreens: inheritedInstallations.length > 0, abortController, spec, handsCwdRef, hookEnvFace, hookIdentity, permissionMode, reminderMark, frameSettlement }); if (toolResultStation !== undefined) harness.on("tool_result", toolResultStation); const approvedCallScreen = createApprovedCallScreen({ modBus, permissionMode, abortController, handsCwdRef, hookEnvFace, hookIdentity, preToolContexts, whileScreened: hookScreens.call }); return { toolCallStationArmed: toolCallGateArmedRef.armed, toolResultStationArmed: toolResultStation !== undefined, ...(approvedCallScreen !== undefined ? { approvedCallScreen } : {}), ...(continuationGate !== undefined ? { continuationGate } : {}) }; }