UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

304 lines (303 loc) • 23.1 kB
/** * PrepareTask's two GATE STATIONS, verbatim from the driver: the `tool_call` station (the final-roster * effect sync, the write-protection judge compiled once per task, the arming predicate, the compliance and plan-mode * short-circuits, the `runToolGate` call with every seat it is handed, the lifecycle sweep, the deferred sandbox-admission * disclosure, the PreToolUse context stash, the gate record's write on the call's occurrence and the bare-human-rejection boundary) and the * `tool_result` station's registration (its body, the PostToolUse / PostToolUseFailure seats and the PreToolUse context * drain, lives in call-hook-stations.ts). The two module-scope * helpers only these stations called moved with them (the settlement screen, the rejection-boundary judgment). The * interface is the dependency list the stations had implicitly. * * The stations REGISTER handlers on the harness (the side effect this phase exists for) and report only two observation * seats back; the order they register in — after the file-history boundary lease the driver registers, and in this order * (call before result) — is the order handlers run in. * * SYNCHRONOUS FUNCTION, SYNCHRONOUS CALL: the stretch has no await of its own (the handlers run per tool call / per tool * result), so the phase adds no yield between the park closure before it and the context lane after it. * Read-stability of the host handles for the call: {@link RunInternals} (`@contract prepare.deps-read-stable`). * * The `tool_call` station is built exactly when the ask lane and the park closure are (the same predicate as the whole * gate-machinery block, kept as the block's one guard here); the `tool_result` station keys off the hook record alone, as * it always did. * * Every station this file holds is a `deniedBy` / settlement WRITE site the decomposition's next slice maps onto one * gate outcome; nothing here changes a word, a source or an order — the stations are moved, not re-adjudicated. */ import type { AgentHarness, AgentTool } from "../../internal/harness.js"; import type { CallTargetStamp } from "../effective-path-target.js"; import type { AskClass } from "../ask-class.js"; import type { Arbitration, ToolMarkSource } from "../ask-origin.js"; import { type PermissionModeController } from "../mode-policy.js"; import { type AutoModeDecider, type AutoModeDenialTracker } from "../auto-mode.js"; import { type ComplianceCapability } from "../compliance.js"; import type { InheritedInstallation, LegModBus } from "../mods/stations.js"; import { type HookEnvCapabilities, type HookInvocationIdentity } from "../hooks.js"; import type { ToolPolicy } from "../tool-policy.js"; import { type WorkflowContinuationGate } from "./continuation-gate.js"; import { type GateOutcome } from "../gate-outcome.js"; import type { RunnerDeps, TaskSpec } from "../types.js"; import type { LegNotice } from "../leg-identity.js"; import { type WiringManifest } from "../wiring-manifest.js"; import type { WriteProtectionCheck } from "../write-protect.js"; import type { ShellReadCheck } from "../../tools/fs/shell-read-check.js"; import type { CwdRef } from "../../tools/fs/fs-shared.js"; import type { ContainmentFace } from "../../tools/fs/containment-face.js"; import type { AskLane, GateSeatInputsFor, IrreversibilityTier, ParkAsk, Prepared, ReversibilityProbes, StopForDenialLimit } from "./contracts.js"; import type { PermissionRuleLanes } from "./permission-rule-lanes.js"; import { type ToolRosterDeltaSeat } from "../tool-roster.js"; import type { ToolCallLike } from "../tool-registry.js"; import type { FrameSettlement } from "../frame-settlement.js"; import { type ApprovedCallScreen } from "./call-hook-stations.js"; import { type CommandSandboxPlan } from "../command-sandbox.js"; /** * The parent-thread human-rejection boundary — THE judgment behind every halt on a person's "no", read off the one * record a decide mints (a live gate pass's, a parked tool approval's, a plan pause's), never off message text. CC * parity: the reference's reject handler (one handler for a tool call's card and the plan card) aborts the turn * exactly when there is no feedback, no attached content and the run is not a subagent; a rejection WITH the decider's * note, and every delegated child — forks included — keep the continue / adapt-or-report posture. True iff the record * IS a person's refusal ({@link isHumanRefusal}), the refusal carried NO note (`settlement.note` absent — a fact composed * at the refusal, never re-derived from message text), and the leg is not a delegated child (the raw trusted * delegation facet — the same fact that selects the refusal text's posture, so the boundary and the words the model * was told always agree). Policy/hook/classifier denies and window/abort settlements never satisfy it. A leg it * answers true for ends its turn awaiting the user: the live batch through {@link maybeHumanRejectionHalt}'s * directive, a resumed leg by recording the decision and requesting nothing more. */ export declare function isBareHumanRefusal(gate: GateOutcome | undefined, isDelegatedChild: boolean): boolean; /** * The loop directive a bare refusal of a CALL ({@link isBareHumanRefusal}) hands the batch it halts: it settles every * never-started same-batch sibling with honest known-not-executed wording plus the machine mark (`error`/`code` twin — * the wire errorCode lift reads `details.code`; `details.error` is the in-band mark result consumers grep) naming the * rejected call. `undefined` = no boundary (the block stands alone). */ export declare function maybeHumanRejectionHalt(input: { gate: GateOutcome | undefined; isDelegatedChild: boolean; toolName: string; toolCallId: string; }): { reason: string; details: Record<string, unknown>; } | undefined; export interface PrepareGateStationsInput { /** borrowed-readonly — the in-stream ask lane, or undefined when the gate machinery is inactive (then no `tool_call` * station is built). Read: `adjudicate`, `resolveAskBound`, `notifyPermissionDenied`, `notifyHookError`. */ askLane: AskLane | undefined; /** borrowed-readonly — the park closure and the content-ask routing closure, or undefined (same law). Handed to the gate. */ parkAsk: ParkAsk | undefined; /** borrowed-readonly — the FINAL mount roster: iterated once for the effect sync and the write-protection arming. Never * mutated here. */ tools: readonly AgentTool[]; /** borrowed-readonly — the leg's delta seat: its current roster is the face source for every gated call. */ toolRosterDeltas: ToolRosterDeltaSeat; /** borrowed-readonly — the deployment seats these stations read, as a Pick over the SAME `deps` object (receiver * preserved for `deps.onError?.()`): the write-protection table and its data root, the tracer, the error face, and * the notice sink (the gate's unresolvable-ask exit delivers `delegation.ask_unresolvable` through it). */ deps: Pick<RunnerDeps, "writeProtectedPaths" | "memoryEngineDir" | "tracer" | "onError" | "onNotice">; /** borrowed-mutable — the protocol-tools phase's arming belt. Writer here: `armed` ← the registration predicate, the * one write; the refresh seam reads it. */ toolCallGateArmedRef: { armed: boolean; }; /** borrowed-readonly — the policy chain's effective policy, or undefined; presence only (the arming predicate). */ effectivePolicy: ToolPolicy | undefined; /** borrowed-readonly — the leg's mods bus: `classic.PreToolUse` presence arms the gate; the screenings and the post-call * events are raised on it. */ modBus: LegModBus; /** borrowed-readonly — the inherited installations the gate judges its calls on after `modBus` (`classic.PreToolUse` at phase 1, * `tool.check` at the verdict read; the policy-chain phase's). */ inheritedInstallations: readonly InheritedInstallation[]; /** borrowed-readonly — the egress vocabulary: arming, and the per-call `egress` flag handed to the gate. */ egressTools: ReadonlySet<string>; /** borrowed-readonly — the irreversible vocabulary: arming only. */ irreversibleTools: ReadonlySet<string>; /** borrowed-readonly — the REBOUND spec: `enablePlanMode` (arming) and `signal` (the failure seat's interrupt fact). */ spec: Pick<TaskSpec, "enablePlanMode" | "signal">; /** borrowed-readonly — the compliance denials (the web_fetch veto's call-time lock, and its arming term). */ complianceDenies: ReadonlySet<ComplianceCapability>; /** borrowed-mutable — the built harness. Writer here: `on("tool_call")` / `on("tool_result")` — the registrations this * phase exists for, in this order, after the driver's boundary-lease handler. */ harness: Pick<AgentHarness, "on" | "isBatchSafe">; /** borrowed-mutable — the blocked/suspended call ids (`Prepared.blockedToolCalls`). Writers here: the head-of-evaluation * hygiene `delete`, the two short-circuits' and the gate outcome's `add`, the `tool_result` station's one-shot `delete`. */ blockedToolCalls: Set<string>; /** borrowed-mutable — the duplicate-frame ask-grant record. Writer here: the head-of-evaluation and lifecycle-end `delete`. */ inheritedAskGrants: Map<string, unknown>; /** borrowed-mutable — the inherited-unavailable marker channel (per call, each station's mark). Writer here: the lifecycle-end `delete`; `has` is handed to * the gate as the read-only `isMarkedUnresolvable`. */ inheritedUnavailableAsks: Map<string, unknown>; /** borrowed-mutable — the deferred-question identities ({@link import("../tool-policy.js").AskRequest.checkpointId}). Writer * here: the head-of-evaluation and lifecycle-end `delete`. */ deferredAskIdentities: Map<string, unknown>; /** borrowed-mutable — the per-call ask-class record the sandbox admission reads. Writer here: the lifecycle-end `delete`. */ foldAskClasses: Map<string, Array<{ cls: AskClass; layer: string; }>>; /** borrowed-mutable — the deferred ancestor sandbox admissions. Writer here: the unconditional read-and-`delete` after the * fold settles. */ ancestorSandboxAdmissions: Map<string, Array<{ cls: AskClass; layer: string; }>>; /** borrowed-mutable — PreToolUse `additionalContext` per call id. Writers here: the `tool_call` station's stash (`set`, only * for calls that will execute) and the `tool_result` station's one-shot drain (`delete`). */ preToolContexts: Map<string, string[]>; /** borrowed-mutable — the leg's occurrence table (`Prepared.toolOccurrences`). Writers here: the one screened gate record per * gated call, and the holds around the gate's two asking seats (`approval`) and its classifier (`classifier`). */ toolOccurrences: Prepared["toolOccurrences"]; /** borrowed-readonly — the leg's decision-screen seat (`Prepared.hookScreens`): every `classic.PreToolUse` screening the gate and * the approved-call re-screen run holds the call (`hook`) and is framed (`hook_progress`). */ hookScreens: Prepared["hookScreens"]; /** borrowed-mutable — the turn halt fact (`Prepared.batchHaltRef`). Writer here: the bare-rejection boundary (`current`). */ batchHaltRef: Prepared["batchHaltRef"]; /** borrowed-readonly — whether blocked/suspended ids are tracked at all (the post-tool callbacks exist). */ blockedTracked: boolean; /** borrowed-readonly — the leg's identity envelope every classic event and PermissionDeniedPayload carries. */ hookIdentity: HookInvocationIdentity; /** borrowed-readonly — the leg's reminder provenance mark (every model-facing deny reason and hook context carries it). */ reminderMark: string; /** borrowed-readonly — the per-task identity (the trace rows' taskId). */ hostTaskId: string; /** borrowed-readonly — the acquired session id (the settlement defects' error tag). */ sessionId: string; /** borrowed-readonly — where this station's user-face notices go and under what admission they are delivered * (`Prepared.legNotice`, minted once per leg beside the ask source): the leg's own session on a top-level leg; the * delegation tree's root, naming this leg, on a delegated one — every notice below spreads its `route.address` in place of the * bare session id and is delivered under `admits` (absent outside a Runner, and for a top-level leg). */ legNotice: LegNotice; /** borrowed-readonly — the hand's live tracked cwd, or undefined; `current` is read per screening / per post seat. Not * written here. */ handsCwdRef: CwdRef | undefined; /** borrowed-readonly — the leg's target-reading stamp, or undefined (hands-less): the gate stamps its request with it. */ stampCallTarget: CallTargetStamp | undefined; /** borrowed-readonly — the read-only env capability face every hook context carries, or undefined. */ hookEnvFace: HookEnvCapabilities | undefined; /** borrowed-readonly — the leg's write-protection gate input, compiled ONCE by the wiring-manifest phase * (which runs first and has to report the judge's own target view), or undefined when the deployment * emptied the table: no judge, and no tighten mounted at all. Carried rather than compiled a second time * here — two compiles are two judges, free to disagree about the seats they were handed. */ writeProtectionCheck: WriteProtectionCheck | undefined; /** borrowed-readonly — the leg's shell READ STATION (`ToolGateInput.shellReadCheck`), mounted by the hands phase, or * undefined with no real shell: no station, nothing judged. */ shellReadCheck: ShellReadCheck | undefined; /** borrowed-readonly — the leg's cross-boundary seat (`ToolGateInput.crossBoundaryCheck`), or undefined on a leg whose station is not engaged. */ crossBoundaryCheck: import("../cross-boundary-taint.js").CrossBoundaryCheck | undefined; /** borrowed-readonly — PRESENT ⇔ the Runner declares its shape (`RunnerDeps.deploymentShape`): the legs one call declares, off the * leg's cross-boundary lane (`CrossBoundaryLane.legsOf`), and the deny rows one call may meet — the gate's `confined` seat reads them. */ confinedLeg?: { readonly legsOf: (call: import("../cross-boundary-taint.js").CrossBoundaryCall) => readonly import("../cross-boundary-taint.js").BoundaryLeg[]; readonly denyRows: (toolCallId: string) => import("../shell-read-silence.js").ConfinedDenyRows; }; /** borrowed-readonly — the leg's resolved read face (`undefined` with no hands), read per call into the class derivation. */ readFace: () => ContainmentFace | undefined; /** borrowed-readonly — the read-deny table the call is judged with (`ToolGateInput.readDenyInForce`): the active built-in * tiers and the rows beside them (the deployment's and the task's patterns, the read-face rule rows). Empty ⇒ no table. */ readDenyInForce: (toolCallId: string) => { readonly tiers: readonly string[]; readonly rows: readonly string[]; }; /** borrowed-readonly — the per-tool irreversibility tier handed to the gate per call. */ irreversibilityTier: IrreversibilityTier; /** borrowed-readonly — the per-tool reversibility probes handed to the gate per call. */ reversibilityProbes: ReversibilityProbes; /** borrowed-readonly — prepare's abort seat; only `.signal` is read (the gate's probe bound, the post seats' bound, the * failure seat's interrupt fact). */ abortController: { readonly signal: AbortSignal; }; /** borrowed-readonly — the shell-seat provenance set: the shell-running tools whose tier is the engine's shell seat's, not a * deployment mark (the gate's `shellGated` attribution is the membership of the name the call's tier was read under). */ shellGatedTools: ReadonlySet<string>; /** borrowed-readonly — the armed classifier's live seat (read per call: a leg steered into `auto` arms after prepare). */ autoModeDecider: { readonly current: AutoModeDecider | undefined; }; /** borrowed-readonly — the denial tracker's live seat beside the decider's. */ autoModeDenialTracking: { readonly current: AutoModeDenialTracker | undefined; }; /** borrowed-readonly — the leg's ONE ask derivation (`wiring_manifest.ask`: form + effective), read for the classifier's seat. */ askRoute: WiringManifest["ask"]; /** borrowed-readonly — the leg's fact "its parks cannot be resumed" as the driver derived it (source + forced gate); the gate's deny * exit and question refusal read it. Absent ⇔ the leg's parks can be resumed. */ notResumable: import("../park-resumability.js").NotResumableLeg | undefined; /** borrowed-mutable — the run's refused-ask list (`TaskResult.refusedAsks`), one entry per refused call. */ refusedAsks: import("../task-result.js").RefusedAsk[]; /** borrowed-readonly — the leg's live permission-mode seat: the gate's arbitration point reads `current` per call. */ permissionMode: PermissionModeController; /** borrowed-readonly — WHO marked each tool's seat (the safety scan's map, the protocol fold's rows); read per call into * the gate's class derivation. */ toolMarkSources: ReadonlyMap<string, ReadonlySet<ToolMarkSource>>; /** borrowed-readonly — the deployment's A2A isolation switch (`RunnerDeps.a2a.isolatePeers`), when set. */ a2aIsolatePeers?: true; /** borrowed-readonly — which inside peer a call goes to, per tool name (`a2aInsidePeerReader` over the door's A2A snapshot). */ a2aInsidePeerOf: (toolName: string) => import("../a2a-bound-grant.js").A2aInsidePeer | undefined; /** borrowed-readonly — the run's invocation id (the classifier-unavailable seat's detail). */ runId: string; /** borrowed-mutable — the inherited stations' mode arbitrations, keyed by tool call (the policy-chain phase writes; the * gate's exit reads and this station deletes at the call's end, the fold-record lifecycle). */ ancestorArbitrations: Map<string, Exclude<Arbitration, { kind: "ask"; }>>; /** borrowed-mutable — the inherited stations' rule clears, keyed by tool call: the same writer, reader and lifecycle. */ ancestorRuleClears: Map<string, import("../hooks.js").AncestorRuleClear>; /** borrowed-readonly — the headless denial-limit stop seat (wired unconditionally). */ stopForDenialLimit: StopForDenialLimit; /** borrowed-readonly — the persisted allow-rule lane, or undefined (absent entirely with no store). */ permissionRuleLane: PermissionRuleLanes["personal"]; /** borrowed-readonly — the call's seat inputs: the permission seat (static, or the `Skill` tool's per-call reader) and the run's skill rows. */ seatInputsFor: GateSeatInputsFor; /** borrowed-readonly — the org rule lane, or undefined (absent on an ungoverned deployment). */ permissionRuleOrgLane: PermissionRuleLanes["org"]; /** borrowed-readonly — whether the ENGINE's question tool is what is mounted under the reserved name (the org lane's * content-ask exemption predicate). */ questionToolMounted: boolean; /** borrowed-readonly — the question-face phase's `durableQuestionFace`: the leg's one fact "a question may park here", handed to the gate. */ durableQuestionFace: boolean; /** borrowed-readonly — the wiring phase's `suspendTargetGap` (the clause the park closure refuses every attempt on), handed to the gate's landing. */ suspendTargetGap: string | undefined; /** borrowed-mutable — the calls the engine's continuation is judging now (no park route: its caller awaits in this process). Writer: the * continuation gate, for its pass; readers: this station's park closure hand-off and the inherited stations' landing (`parkRouteOf`). */ continuationCalls: Set<string>; /** borrowed-readonly — `RunInternals.workflowParkGap`: the stores a workflow lacked to hand this agent the host's opt-in; the refused ask's notice carries it. */ workflowParkGap: readonly import("../ask-unresolvable-notice.js").WorkflowParkGap[] | undefined; /** borrowed-readonly — whether sandbox admission is armed (isolated env + park prerequisites). */ sandboxAdmissionArmed: boolean; /** borrowed-readonly — the run requires a command sandbox and its environment keeps one: the gate is armed for it (a call it * lets go carries its plan), whatever else arms it. */ commandSandboxArmed: boolean; /** borrowed-readonly — one call's command sandbox plan by its wire name (`command-sandbox.ts`), minted where the gate lets the * call go and handed to the loop on the result (`BeforeToolCallResult.sandboxPlan`). */ sandboxPlanOf: (call: { readonly toolName: string; readonly toolCallId: string; readonly args: unknown; }) => CommandSandboxPlan; /** borrowed-readonly — the per-call boundary-capability fact the sandbox admission reads (the call's wire name and names). */ sandboxBoundaryCapable: (call: Pick<ToolCallLike, "toolName" | "face">) => boolean; /** borrowed-readonly — the sandbox-admission trace sink (the deferred ancestor disclosure and the gate's own). */ emitSandboxAdmitted: (info: { toolCallId: string; toolName: string; askClasses: ReadonlyArray<{ cls: AskClass; layer: string; }>; boundary: "sandbox_internal"; }) => void; /** borrowed-readonly — the effective delegation facts (the rejection boundary's isDelegatedChild). */ delegation: { isDelegatedChild: boolean; }; /** borrowed-mutable — the leg's settlement seam. Writer here: the `tool_result` station marks a carrier whose output * a host hook rewrote (`noteHostRewrite`), so a frame the rewrite removed settles as the host's decision. */ frameSettlement: FrameSettlement; } export interface PrepareGateStationsResult { /** owned — whether the `tool_call` station registered (the arming predicate's value; observation seat only). */ toolCallStationArmed: boolean; /** owned — whether the `tool_result` station registered (a post or screening hook is wired; observation seat only). */ toolResultStationArmed: boolean; /** owned — the approved call's PreToolUse re-screen (the gate's face and seat), present exactly when a face is wired. */ approvedCallScreen?: ApprovedCallScreen; /** owned — this leg's gate for the engine's continuation of a finished workflow run; present iff the `tool_call` station registered. */ continuationGate?: WorkflowContinuationGate; } /** The M20 phase body — prepareTask's two gate stations, verbatim (see the module header). */ export declare function prepareGateStations(input: PrepareGateStationsInput): PrepareGateStationsResult;