UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

353 lines (352 loc) • 27.3 kB
/** * PrepareTask's POLICY-CHAIN phase, verbatim from the driver: the caller policy * and its name audit (advisory once per deployment; the two hard refusals), the session / ancestor / frozen-projection / * skill-scope deny-narrowing layers and their fold, the resume-edit base policy, the hook record with its timeout seat * and observational half, the same-instance arbitration machinery (the caller slot's first-decision record), the * inherited-unavailable marker channel, the grant record, the sandbox-admission mode's arming and its three * sideband maps, the source-identity and risk-axes factories, the two permission-rule lanes and the rule-offer * factory, the approved-edit re-check, the inherited-constraint wrappers (the same-instance adapter and the true * wrapper), the instrumented chain, the integrity guards, the fold, and the same-instance arbitration refresh that is the * effective policy. The advised-names dedupe pair only this section reads moved with it. * The interface is the dependency list the segment had implicitly. * * ASYNC PHASE: the stretch awaits the session-policy store (the task's own rules and each ancestor's live re-read) * exactly where the segment did; the closures it builds await at tool-call time. The phase boundary adds one * continuation between its last await and the driver's next read — the accepted class under {@link RunInternals} * `@contract prepare.deps-read-stable`. * * NOT CHANGED HERE: the ask-origin vocabulary. This phase is a mint site for `AskOrigin` words (through the inherited * arms' `judgeInheritedClassifier` / `inheritedAskCarry`), and it carries them verbatim — the closed set, its fence and * every spelling are exactly the driver's. */ import type { AgentTool } from "../../internal/harness.js"; import type { ExecutionEnv } from "../../internal/harness.js"; import { type AskClass } from "../ask-class.js"; import { unavailableLandingOf } from "../unavailable-landing.js"; import { type AutoModeDecider } from "../auto-mode.js"; import { type InheritedInstallation, type LegModBus, type ModChainLink } from "../mods/stations.js"; import type { LockedPreflight } from "../locked-config.js"; import type { RunTimeAnnounced } from "./announce-once-ledger.js"; import type { SessionPermissionRules } from "../session-policy-store.js"; import { type AskSourceIdentity, type OnAsk, type ToolCallRequest, type ToolPolicy } from "../tool-policy.js"; import { type ApprovalParkNotResumable } from "../park-resumability.js"; import type { PathRuleBases } from "../permission-rule-model.js"; import type { HeadLeads } from "../path-rule-binding.js"; import { type RetiredNameView } from "../tool-name-aliases.js"; import type { RunnerDeps, RuntimeCaps, TaskSpec, ToolEffect } from "../types.js"; import type { CwdRef } from "../../tools/fs/fs-shared.js"; import type { ReadDenyMatcher } from "../../tools/fs/read-deny.js"; import { type SkillGrantLane, type SkillGrantSource, type SkillGrantTable } from "../skill-grant.js"; import { type GrantBindingOf } from "../skill-grant-binding.js"; import type { ToolSelector } from "../tool-face.js"; import { type AllowEntryLane, type AllowEntryTable } from "../allow-entry.js"; import type { AutoStrippedRule } from "./auto-strip-notice.js"; import type { InheritedGate, IrreversibilityTier, PrepareResume, StopForDenialLimit } from "./contracts.js"; import type { RosterSpec } from "./caller-roster.js"; import { type Arbitration, type CallRiskAxes } from "../ask-origin.js"; import { type ModeGateSeats, type PermissionModeController } from "../mode-policy.js"; import { type DeferredAsk, type MarkerChannel } from "./deferred-ask.js"; import type { ApprovalWordsSeat } from "../approval-words.js"; import type { EngineText } from "../../prompt-assembly/engine-text.js"; import { type InheritedAskGrant } from "./inherited-ask-grants.js"; import { createRuleOffersOf, type PermissionRuleLanes } from "./permission-rule-lanes.js"; import { createCallGrantDoorOf } from "./session-call-grant-station.js"; import { type CallBindingSeat } from "../session-call-grant.js"; import type { ToolCallLike } from "../tool-registry.js"; import { type CallShellOf } from "../call-shell.js"; import { type HostFloor } from "../host-floor.js"; import { type CommandSandboxPlan } from "../command-sandbox.js"; export interface PreparePolicyChainInput { /** borrowed-readonly — the leg's reading of a retired tool name in a rule, computed once at the task's start (`TaskStartDoors.retiredNames`). */ retiredNames: RetiredNameView; /** borrowed-readonly — the run's command sandbox side of a call on its args (`AskRequest.commandSandbox` on the inherited stations' asks). */ commandSandboxSideOf: (call: { readonly toolName: string; readonly toolCallId: string; }, args: unknown) => { commandSandbox?: "inside" | "outside"; }; /** borrowed-readonly — where a call to an A2A peer's skill goes (`AskRequest.destination` on the inherited stations' asks). */ destinationOf: (toolName: string) => { destination?: import("../mcp-server-spec.js").AskDestination; }; /** borrowed-readonly — the gate's own plan port: an inherited station classes an escaping call as the gate does. */ sandboxPlanOf: (call: { readonly toolName: string; readonly toolCallId: string; readonly args: unknown; }) => CommandSandboxPlan; /** borrowed-readonly — the deployment's host floor as the config doors compiled it: the leading narrowing layer when declared. */ hostFloor: HostFloor | undefined; /** borrowed-readonly — the REBOUND spec. Read: `sessionId` / `principal` (the session-rule read and the lanes' identity), * `durableApproval` / `checkpointStore` (the mandate-park facility test and the sandbox arming's park prerequisites), * `tools` (the names the caller mounted, for the name audit), `classifyAllShell` (every allow member's auto strip). Never mutated. */ spec: Pick<RosterSpec, "durableApproval"> & Pick<TaskSpec, "sessionId" | "principal" | "checkpointStore" | "tools" | "classifyAllShell" | "readDenyBuiltinExclude">; /** borrowed-readonly — the deployment seats: `sessionPolicyStore` (the rule reads), * `permissionRuleStore` / `localOwnerRules` (the lanes and the offer factory), `onError` / `onNotice` (the advisories, * the refusal disclosures, the late-ask observer), `tracer` (the admission and rule-store frames), `checkpointStore` (the park facility). Receiver preserved; * the advisory dedupe is KEYED on this object's identity. */ deps: Pick<RunnerDeps, "sessionPolicyStore" | "permissionRuleStore" | "localOwnerRules" | "onError" | "onNotice" | "tracer" | "checkpointStore" | "a2a" | "sessionStore" | "readDenyBuiltinRequestExcludable">; /** borrowed-readonly — the acquired session id (the config-phase error tags and the earlier-grammar notice's session). */ sessionId: string; /** borrowed-readonly — the session the person's session-scope permission rules are read and written at ({@link import("../leg-identity.js").ruleSessionOf}). */ ruleSessionId: string; /** borrowed-readonly — whether this leg is in its delegation tree's rule session (the same reading's `inTree`): its inherited stations put an * ancestor's question to this leg's person-rule lane first; a leg outside it keeps the station's mandate and hears no lane. */ ruleSessionInTree: boolean; /** borrowed-readonly — the run's invocation id (the late-ask observer's detail). */ runId: string; /** borrowed-readonly — the per-task identity (the trace frames' taskId; the rule-store disclosure; the late-ask observer's detail). */ hostTaskId: string; /** borrowed-readonly — the leg's carrier for the approving person's written words ({@link ApprovalWordsSeat}): an inherited station puts its * card to the ancestor's approver, and the words a person writes there are about this leg's call, so they reach this leg's model. */ approvalWords: ApprovalWordsSeat; /** borrowed-readonly — the run's engine text reading (its locale): an inherited station's card headline is minted in it. */ engineText: EngineText; /** borrowed-readonly — the FINAL task root (path rules resolve against it; the lanes' and the offers' root). */ taskRootFinal: string; /** borrowed-readonly — the leg's canonical write roots beyond its write location (`additionalDirectories` + advertised writable * dirs): the `acceptEdits` mode gate allows writes inside the write location and these, and asks outside them all. */ additionalRootsCanonical: readonly string[]; /** borrowed-readonly — the leg's ONE write-location reader (`writeLocationOf`), read per call by the `acceptEdits` gate. */ writeLocation: () => string; /** borrowed-readonly — the run's resolved env (path rules resolve in it; the sandbox declaration is read off it). */ executionEnv: ExecutionEnv; /** borrowed-readonly — the frozen preflight as installed on this leg: `toolPolicy` (the caller slot), `basePolicyForResumeEdit` (the * lock-aware resume-edit override), their path rules anchored where this leg installed them, and `a2a` (the peers the gate reads). */ lockedPreflight: Pick<LockedPreflight, "toolPolicy" | "basePolicyForResumeEdit" | "a2a">; /** borrowed-readonly — the path rules' anchors on this leg: `leg` (this leg's root and environment home — where this * leg's own lists are installed) and `chainTop` (the top leg's: the person's global / session rows and every `~/`). */ pathRuleAnchors: { readonly leg: PathRuleBases; readonly chainTop: PathRuleBases; }; /** borrowed-readonly — the leg's one resolution of where rule heads lead (the rows' twins). */ headLeads: HeadLeads; /** borrowed-readonly — the run's ONE tool roster, read only here (the name audit's universe: names + aliases). */ tools: ReadonlyArray<AgentTool>; /** borrowed-readonly — the harness list (placeholders keep their deferred names), the audit universe's second half. */ harnessTools: ReadonlyArray<AgentTool>; /** borrowed-readonly — the leg's compiled tool selector: the name audit reads the delegation tools it leaves ({@link delegationPoolReading}). */ selector: Pick<ToolSelector, "admits">; /** borrowed-readonly — the effect collection, read by the narrowing layers (path-confinable write tools). */ toolEffects: ReadonlyMap<string, ToolEffect>; /** borrowed-readonly — the egress mark set (the risk axes, the boundary predicate, the offer factory). */ egressTools: ReadonlySet<string>; /** borrowed-readonly — the folded irreversibility tiers (the risk axes, the offer factory). */ irreversibilityTier: IrreversibilityTier; /** borrowed-readonly — the explicit negative declarations per tool (the risk axes' "engine judged it false"). */ axisExplicitNegatives: ReadonlyMap<string, { irreversible?: false; egress?: false; }>; /** borrowed-readonly — the ENGINE HAND roster: every tool whose effect dispatches through the task's execution env, * membership minted at the mount sites (the sandbox boundary predicate's one containment fact). */ envHandToolNames: ReadonlySet<string>; /** borrowed-readonly — the shell-seat provenance set (the offer factory's `shellGated` mandate term, read per call). */ shellGatedTools: ReadonlySet<string>; /** borrowed-readonly — who marked each name's seat (the offer factory's `shellGated` term reads it as the gate does). */ toolMarkSources: ReadonlyMap<string, ReadonlySet<import("../ask-origin.js").ToolMarkSource>>; /** borrowed-readonly — the tracked-cwd seat, read per call by the lanes and the offer factory (never written here). */ handsCwdRef: CwdRef | undefined; /** borrowed-readonly — the compiled read-deny judge, or undefined (the offer factory's directory negative control). */ readDenyMatcher: ReadDenyMatcher | undefined; /** borrowed-readonly — the file read station a leg that refuses reads outside its directories mounts as a refusal, on the run's * newest tables; absent elsewhere. Judged ahead of every inherited question about a call (`readBoundaryRefusalOver`). */ readBlockJudge: import("../../tools/fs/shell-read-check.js").ShellReadCheck | undefined; /** borrowed-readonly — the run's one reader of the person's rules (`person-path-rows.ts`): the lanes take each call's * pinned read from it. */ personRows: import("./person-path-rows.js").PersonPathRows; /** borrowed-readonly — whether the question tool mounted (the lanes' question-tool exclusion). */ questionToolMounted: boolean; /** borrowed-readonly — the resolved per-principal entitlements; only `forceDurableGate` (the mandate-park facility and * the sandbox arming's prerequisite). */ runtimeCaps: Pick<RuntimeCaps, "forceDurableGate"> | undefined; /** borrowed-readonly — the driver's leg fact `approvalParkNotResumable` (the opt-in judge's third input). */ approvalParkNotResumable: ApprovalParkNotResumable | undefined; /** borrowed-readonly — the word its refusals say (`notResumableSaysOf`). */ notResumableSays: ApprovalParkNotResumable | undefined; /** borrowed-readonly — the driver's refusal fact: an inherited ask on such a leg is refused in the fold, never put to an ancestor's approver. */ forcedGateNotResumable: ApprovalParkNotResumable | false | undefined; /** borrowed-readonly — the ancestors' session-rule snapshots (each re-read live-preferring, floor kept). * Never written: an entry is some other leg's or some host's object — see `ancestorSessionRulesRef`. */ inheritedAncestorRules: InheritedGate["ancestorRules"]; /** borrowed-mutable — THIS leg's record of what each ancestor layer now ENFORCES, keyed by the entry's * POSITION (see the seat's own declaration in `prepare-inherited-gate.ts` for why position and not * identity). Writer: this phase, through each ancestor layer's `onEnforced`. */ ancestorSessionRulesRef: { current: Map<number, { sessionId: string; principal?: string; rev: number; gen?: number; rules: SessionPermissionRules; }>; }; /** borrowed-readonly — the ancestors' caller-policy constraints, ancestors first (one wrapper each). */ inheritedParentConstraints: NonNullable<InheritedGate["parentConstraints"]>[number][] | undefined; /** borrowed-readonly — the kinds of persisted-rule bucket the legs above read (the rule lanes refuse this leg if its Runner cannot read one). */ inheritedRuleBuckets: InheritedGate["persistedRuleBuckets"]; /** borrowed-readonly — the resumed leg's SEED half; only `constraintChain` (the frozen deny projections). */ seedInheritedGate: Pick<NonNullable<PrepareResume["seed"]["inheritedGate"]>, "constraintChain"> | undefined; /** borrowed-readonly — the run's skill grant table; this phase binds its lane to the call facts the person's rule lane * reads (root, session, live cwd, the execution environment's home). Not written here. */ skillGrants: SkillGrantTable; /** borrowed-readonly — the loaded skills (the table the `Skill` tool activates from); {@link PreparePolicyChainResult.grantBindingOf} reads them. */ skillSpecs: readonly SkillGrantSource[]; /** borrowed-readonly — the request's and the deployment's allow-entry tables (prepare seeded them); this phase binds * their lanes to the same call facts. Not written here. */ allowedToolTables: { readonly request: AllowEntryTable; readonly deployment: AllowEntryTable; }; /** borrowed-readonly — the FROZEN approver seat (the pass-through test's approver identity). */ frozenOnAsk: OnAsk | undefined; /** borrowed-readonly — the identity of this task's hook-env source (the pass-through test's environment term). */ hookEnvSource: unknown; /** borrowed-readonly — the leg's own failure lane (`onError`, phase `hook`, swallow-guarded): an inherited policy that threw. */ notifyOwnHookCrash: (err: unknown) => void; /** borrowed-readonly — the leg's mods bus (whether this leg's own phase 1 judges with `classic.PreToolUse` — the pass-through test). */ modBus: LegModBus; /** borrowed-readonly — this leg's chain identity as its admission recorded it (`chainOfBus`) — the stand-in test's chain term. */ ownModChain: readonly ModChainLink[]; /** borrowed-readonly — LATE-BOUND: this task's own classifier instance (the pass-through test's decider term), read at chain * assembly (the arming runs after this phase, and again on a steer into `auto`). */ autoModeDecider: () => AutoModeDecider | undefined; /** borrowed-readonly — the leg's occurrence bracket (`Prepared.toolOccurrences.whileHeld`): an ancestor's frozen classifier judging a call * of THIS leg holds it under `classifier`, its frozen approver deciding it under `approval` — inside a screening too (`tool_progress.gate`). */ whileHeld: import("./tool-occurrence.js").ToolOccurrenceTable["whileHeld"]; /** borrowed-readonly — the leg's resolved read face (`undefined` with no hands), read per call into the inherited stations' class derivation. */ readFace: () => import("../../tools/fs/containment-face.js").ContainmentFace | undefined; /** borrowed-readonly — the leg's live permission-mode seat: the mode gate policy layer and the inherited stations' arbitration * read `current` per call. */ permissionMode: PermissionModeController; /** borrowed-readonly — the leg's account of an allow rule auto mode does not use ({@link import("./auto-strip-notice.js").createAutoStripNotice}): * the gate's allow members hand it each entry the strip took from a call that entry speaks for. */ autoStripNotice: (rule: AutoStrippedRule, call: ToolCallRequest) => void; /** borrowed-readonly — the leg's live roster seat; the mode write gate reads `current` per call. */ toolRosterDeltas: NonNullable<ModeGateSeats["roster"]>; /** borrowed-readonly — the run's ONE typed stop for a denial-limit bound (the fallback settlements call it). */ stopForDenialLimit: StopForDenialLimit; /** borrowed-readonly — the leg's one ask source ({@link import("../leg-identity.js").mintAskSourceIdentity}): every ask mint here spreads it. */ askSource: AskSourceIdentity; /** borrowed-readonly — LATE-BOUND (the park phase runs after this one): the call's park route on THIS leg (`callParkRoute`) and the leg's "no suspend target" fact, per call. */ parkRouteOf: (toolCallId: string) => Pick<Parameters<typeof unavailableLandingOf>[0], "parkRoute" | "suspendTargetGap"> & { readonly approvalParkWithheld?: true; }; /** borrowed-readonly — the run's abort controller; only `signal` (the default call signal of every closure here). */ abortController: Pick<AbortController, "signal">; /** borrowed-readonly — the injectable wall-clock (the inherited arms' human-wait timing). */ now: () => number; /** borrowed-mutable — the own session-rules snapshot seat (the inherited-gate phase mints it; `inheritedGateForChildren` * reads it late). Writer: THIS phase — the own layer's seed at prepare, then each row the layer comes to enforce. */ ownSessionRulesRef: { current?: { sessionId: string; principal?: string; rev: number; gen?: number; rules: SessionPermissionRules; }; }; /** borrowed-mutable — the session's announced record (run-time face), the earlier-grammar notice's once-per-session seat (./earlier-grammar-notice.ts). */ announced: RunTimeAnnounced; } export interface PreparePolicyChainResult { acceptEditsGate: ToolPolicy; /** owned — the resume-edit base policy (`Prepared.basePolicyForResumeEdit`), or undefined. */ basePolicyForResumeEdit: ToolPolicy | undefined; /** owned — the deny-narrowing fold (`Prepared.denyNarrowingPolicy`), or undefined when no layer exists. */ denyNarrowingPolicy: ToolPolicy | undefined; /** owned — the skill grant lane (`Prepared.skillGrants`; the gate's skill member and deny rows read it). */ skillGrantLane: SkillGrantLane; /** owned — whether each session-rule layer's last read could not read its store (this task's own; an ancestor's by its position * in the inherited entries): the shell read boundary's seats beyond read it beside the rows the layer enforces. */ sessionRulesUnread: { readonly own: () => boolean; readonly ancestor: (position: number) => boolean; }; /** owned — the request's and the deployment's allow-entry lanes (the gate's two entry-list members). */ allowEntryLanes: { readonly request: AllowEntryLane; readonly deployment: AllowEntryLane; }; /** owned — the caller-facing policy layers (the wiring manifest reads their COUNT). */ policyLayers: ToolPolicy[]; /** owned — THE effective policy the gate station adjudicates with (the fold, plus the same-instance arbitration refresh), or undefined. */ effectivePolicy: ToolPolicy | undefined; /** borrowed-mutable — the inherited-unavailable marker channel: per call, each station's mark and the bytes it is bound to * ({@link MarkerChannel}). Writers: the inherited arms here (mark; lift on the station's own approver's yes); the gate station * (the lifecycle-end sweep) and the park lane's consumers (delete on consumption). */ inheritedUnavailableAsks: MarkerChannel; /** owned — per call, the question an approver deferred to the park (writers: the inherited marks here, the ask lane). */ deferredAskIdentities: Map<string, DeferredAsk>; /** owned — the inherited installations THIS leg's gate judges its calls on after its own bus (`classic.PreToolUse` at phase 1, * `tool.check` at the verdict read; every screening entry the leg's own gate does not stand in for), each with the environment * face it was installed against and the settlement its question takes. */ inheritedInstallations: readonly InheritedInstallation[]; /** owned — the caller's and the ancestors' host policies under this leg's retired-name view, for the leg's other judges (#1781). */ hostPoliciesUnderView: { readonly caller: ToolPolicy | undefined; readonly inherited: readonly ToolPolicy[]; }; /** owned — the inherited stations' MODE ARBITRATIONS by tool call (a release or a refusal made inside the fold, * where an ancestor's ask is arbitrated before its frozen approver). Writers: the three inherited stations here; the gate's * exit reads it onto the disposition and the gate station deletes it at the call's end. */ ancestorArbitrations: Map<string, Exclude<Arbitration, { kind: "ask"; }>>; /** owned — the inherited stations' RULE CLEARS by tool call (a person's stored allow row answered an ancestor's question at another * instance's station): the clearance the allowed disposition names and the rules it stands on. Writer: that station; the gate's exit * reads it where its own allow layer cleared nothing, and the gate station deletes it at the call's end. */ ancestorRuleClears: Map<string, import("../hooks.js").AncestorRuleClear>; /** borrowed-mutable — the grant record. Writers: the inherited arms here (record a clean allow at a live approver); * the gate station (consume on reuse, sweep at settlement). */ inheritedAskGrants: Map<string, InheritedAskGrant>; /** owned — the engine-judged risk axes for an ask, from the same resolved sources the safety tightens use. */ riskAxesOf: (call: Pick<ToolCallLike, "toolName" | "face">) => { riskAxes?: CallRiskAxes; }; /** owned — the ONE rule-offer factory for all five ask-mint sites. */ ruleOffersOf: ReturnType<typeof createRuleOffersOf>; /** owned — the session call grant's door (over {@link ruleOffersOf}'s ladder) and the reading seat the lane judges grants with. */ callGrantDoorOf: ReturnType<typeof createCallGrantDoorOf>; callBindingSeat: (call: CallShellOf) => CallBindingSeat; /** owned — the ONE Skill-card binding factory for the same five sites: a call to the engine's `Skill` tool carries the skill and * its two lists (`boundGrants`) and their hash (`boundGrantDigest`) on the live ask, an ancestor's and the parked row alike. */ grantBindingOf: GrantBindingOf; /** owned — the personal permission-rule lane, or undefined. */ permissionRuleLane: PermissionRuleLanes["personal"]; /** owned — the same lane as the gate reads it: it also tells what the auto strip took from a call (the gate stations' lane). */ permissionRuleGateLane: PermissionRuleLanes["personal"]; /** owned — the leg's facts the two lanes judge against (session, root and anchors, head leads, sinks), for the consolidation * write judge, which builds its own two lanes over the reader the run's cut does not end (it is asked after the run). */ ruleLaneFacts: import("./memory-consolidation-write-judge.js").ConsolidationWriteJudgeLeg["lanes"]; /** owned — the org permission-rule lane (`Prepared.permissionRuleOrg`), or undefined. */ permissionRuleOrgLane: PermissionRuleLanes["org"]; /** owned — the two lanes' whole-tool readings over one read (the tool table's view), or undefined. */ storedRuleWholeToolRefusals: PermissionRuleLanes["wholeToolRefusals"]; /** owned — whether the sandbox-admission mode armed (declared isolation with its park prerequisites). */ sandboxAdmissionArmed: boolean; /** owned — the NOT-CONTAINED classification: a call the declared sandbox does not contain. */ sandboxBoundaryCapable: (call: Pick<ToolCallLike, "toolName" | "face">) => boolean; /** owned — the admission disclosure's trace emitter (the gate station emits it once the fold settles). */ emitSandboxAdmitted: (info: { toolCallId: string; toolName: string; askClasses: ReadonlyArray<{ cls: AskClass; layer: string; }>; boundary: "sandbox_internal"; }) => void; /** borrowed-mutable — the per-call fold ask-class record. Writers: the instrumented chain here (record); the gate station * (read for strict dominance, then sweep). */ foldAskClasses: Map<string, Array<{ cls: AskClass; layer: string; }>>; /** borrowed-mutable — the ancestor arms' deferred sandbox admissions. Writers: the inherited arms here (record); the gate * station (emit once the fold settles, then sweep). */ ancestorSandboxAdmissions: Map<string, Array<{ cls: AskClass; layer: string; }>>; } /** The M17 phase body — prepareTask's policy-chain stretch, verbatim (see the module header). */ export declare function preparePolicyChain(input: PreparePolicyChainInput): Promise<PreparePolicyChainResult>;