UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

281 lines (280 loc) • 23.7 kB
/** * PrepareTask's WIRING-MANIFEST phase, verbatim from the driver: the run's own frozen approver * seat, the loud ungated-write warning (hand band / destructive MCP / first-party write tools with no effect-aware gate, * deduped per deployment and tool-set shape), the PreToolUse context stash and the blocked-call set, the settlement and * bare-rejection sidebands, the turn halt fact, the suspend infrastructure predicates (restore surface gap, durable * infra, the task-axis lane with its INACTIVE line), usage governance, the platform-suspend arming, the synthesized * durableApproval, the effective wiring manifest, the peer lane's ask fold and drain binding, the park predicate as ONE * named const, the durable-gate-unavailable notice, the hook identity mint and the hook env face. The four helpers only * this segment called moved with it (usage governance, the per-deployment warn ledger, the MCP manifest projection, the * durable-gate notice). The interface is the dependency list the segment had implicitly. * * SYNCHRONOUS FUNCTION, SYNCHRONOUS CALL: the stretch has no await, so the phase adds no yield between the policy-chain * station before it and the gate registration after it (a stretch with no await is extracted as a sync * function). Read-stability of the host handles for the call: {@link RunInternals} (`@contract prepare.deps-read-stable`). * * One read changed spelling and nothing else: the manifest's MCP face read `mcp?.statuses ?? []` while `mcp` had long * been the protocol-tools phase's non-null handle; the optional chain was dead and is now the plain member read. */ import type { AgentHarness, ExecutionEnv } from "../../internal/harness.js"; import { type PeerLaneRefs } from "../../agents/peer-session-drain.js"; import type { SessionAddress, SessionBoxBinding } from "../task-notification.js"; import type { OnQuestion } from "../ask-question.js"; import type { CheckpointStore } from "../checkpoint-store.js"; import { type HookEnvCapabilities, type HookInvocationIdentity } from "../hooks.js"; import type { ModBus } from "../mods/kernel/index.js"; import type { LockedPreflight } from "../locked-config.js"; import type { MaterializedMcp } from "../mcp.js"; import type { SessionStore } from "../session.js"; import { type ToolResultSeat } from "../tool-result-store.js"; import { type OnAsk, type ToolPolicy } from "../tool-policy.js"; import { type ApprovalParkNotResumable } from "../park-resumability.js"; import type { RunnerDeps, RuntimeCaps, TaskSpec, ToolEffect, ToolExecuteContext } from "../types.js"; import { type LegWriteGuard, type LegWriteProtection } from "./write-protection-station.js"; import { type UsageWindow } from "../usage-window-store.js"; import { type ToolRoster } from "../tool-roster.js"; import type { ToolMountPlan } from "../tool-mount-plan.js"; import { type AskEffective, type AutoModeArmFact, type SuspendLaneReason, type WiringManifest } from "../wiring-manifest.js"; import { type PermissionModeController } from "../mode-policy.js"; import type { AnnounceOnceSink, Prepared, PrepareResume, RunInternals, UsageGovernance } from "./contracts.js"; import type { RosterSpec } from "./caller-roster.js"; import { type SessionProjectVerdict } from "../memory-engine/scope-contract.js"; export interface PrepareWiringManifestInput { /** borrowed-readonly — the REBOUND spec. Read: `onQuestion` (the question seam), `handsReadOnly` / `tools` (the ungated scan), * `resourceSuspend` (the task-axis lane), `durableApproval` / `principal` (the synthesis and the notice), `interactiveTools` / * `mcp` / `checkpointStore` (manifest cells and the notice's cause), `enablePlanMode` (the gate-machinery predicate's * plan-mode term), `writeProtectedAdditions` (the request's rows of the write-protection table). Never mutated. */ spec: Pick<RosterSpec, "durableApproval"> & Pick<TaskSpec, "onQuestion" | "handsReadOnly" | "tools" | "resourceSuspend" | "preemptSignal" | "principal" | "interactiveTools" | "mcp" | "checkpointStore" | "enablePlanMode" | "peerPresence" | "writeProtectedAdditions">; /** borrowed-readonly — the deployment seats, whole: `onError` (the warning), `executionEnv` * (the hook-env predicate), `checkpointStore` (durable infra), the manifest's dozen wiring facts (`backgroundAgentStore`, * `permissionRuleStore`, `permissionRuleSyncWired`, `onBackgroundChildEvent`, `lockedConfig`, `compliancePostureResolver`, * `memoryScopeAdmission`, `retentionPolicy`, `onElicit`), `onNotice`, the write-protection judge's compile seats * (`writeProtectedPaths`, `memoryEngineDir`), and the usage-governance seats (`usageWindowStore`, * `now`, `onUsageGovernance`…) the helper reads through the whole record. */ deps: RunnerDeps; /** borrowed-readonly — the trusted spawn-side channel: `questionFaceStripped`, `isDelegatedChild`, `onTaskNotification`, * `peerSelfRef`, `explicitAgentName`, `principalInboxAssistant` (the drain + the identity), `insideFork` / `agentName` / `spawnAgentType` / `parentToolCallId` (the identity). */ internals: Pick<RunInternals, "questionFaceStripped" | "isDelegatedChild" | "observerLeg" | "onTaskNotification" | "peerSelfRef" | "explicitAgentName" | "principalInboxAssistant" | "spawnAgentType" | "insideFork" | "agentName" | "parentToolCallId" | "rootSessionId" | "workflowMember"> | undefined; /** borrowed-readonly — the resume leg, or undefined (the manifest's leg derivation reads presence only). */ resume: Pick<PrepareResume, "seed"> | undefined; /** borrowed-readonly — the acquired session id. */ sessionId: string; /** borrowed-readonly — the run's invocation id. */ runId: string; /** borrowed-readonly — epoch ms minted once beside {@link runId} at prepare entry; stamped on `manifest.leg.instance.startedAt`. */ legStartedAt: number; /** borrowed-readonly — the per-task identity (the hook identity's taskId). */ hostTaskId: string; /** borrowed-readonly — the registry scope the peer drain binds under. */ taskScope: string; /** borrowed-readonly — this leg's checkpoint scope (the driver's one derivation): the scope of the synthesized `durableApproval`. */ checkpointScope: string; /** borrowed-readonly — the leg's mods bus: the tracked flag, the hook-env consumer test, and `mods[]` (its admission records). */ modBus: ModBus; /** borrowed-readonly — the leg's STANDING chain (`LegMods.standing`: without the skills' registrations, which judge only while * their skill is active): the effect-aware-gate term — a gate that covers every call, not one that may open. */ standingModBus: ModBus; /** borrowed-readonly — the caller-facing policy layers; only their COUNT is read (an effect-aware gate exists). */ policyLayers: ReadonlyArray<unknown>; /** borrowed-readonly — the policy chain's effective policy, or undefined; only its PRESENCE is read (the first term of the * gate-machinery predicate below). Never called here. */ effectivePolicy: ToolPolicy | undefined; /** borrowed-readonly — whether an execution env is wired (the hand band exists at all). */ handsEnabled: boolean; /** borrowed-readonly — a wired factory was not asked (the leg read that it needs no environment): the hands seam's `not_needed`. */ skippedFactory: boolean; /** borrowed-readonly — the resolved task root: the base a `base: "root"` write tool's relative spelling resolves against. */ taskRootFinal: string; /** borrowed-readonly — the leg's write-guard seats: its one exempt root (the driver's single resolution of * `RunnerDeps.memoryEngineDir`) and the chain's guarded write rows, compiled into the leg's one write judgment. */ legWriteGuard: LegWriteGuard; /** borrowed-readonly — the materialized MCP handle: `tools` (the destructive-ungated scan) and `statuses` (the manifest face). */ mcp: Pick<MaterializedMcp, "tools" | "statuses">; /** borrowed-readonly — the materialized A2A handle's `statuses` (the manifest's per-peer face). */ a2a: Pick<import("../a2a.js").MaterializedA2a, "statuses">; /** borrowed-readonly — the assembled safety vocabulary (the ungated scans and the manifest's armed cell). Read only. */ irreversibleTools: ReadonlySet<string>; /** borrowed-readonly — see `irreversibleTools`. */ egressTools: ReadonlySet<string>; /** borrowed-readonly — the hands phase mounted the shell READ STATION (a real shell was mounted): the gate machinery must run for it, under every doctrine. */ shellReadStationArmed: boolean; /** borrowed-readonly — the leg's cross-boundary station is engaged (a declared posture, a target leg, a governed tree): the gate machinery runs for it. */ crossBoundaryStationEngaged: boolean; /** borrowed-readonly — the effect collection; read only here (the ungated scans). */ toolEffects: ReadonlyMap<string, ToolEffect>; /** borrowed-readonly — the per-task owned env when a factory minted one (durable infra, the hook-env predicate). */ ownedEnv: ExecutionEnv | undefined; /** borrowed-readonly — the run's resolved env (the hook env face is built over it). */ executionEnv: ExecutionEnv; /** borrowed-readonly — the run's offload store, or undefined (a volatile store disqualifies durable suspend). */ offloadStore: ToolResultSeat | undefined; /** borrowed-readonly — the once-per-session ledger's operator sink (the INACTIVE line, once per session). */ onceLedger: Pick<AnnounceOnceSink, "onError">; /** borrowed-readonly — the resolved usage windows, or undefined. */ usageWindows: readonly UsageWindow[] | undefined; /** borrowed-readonly — the env-lifetime suspend instant, or undefined (platform-suspend arming). */ envLifetimeSuspendAt: number | undefined; /** borrowed-readonly — the resolved per-principal entitlements (forceDurableGate). */ runtimeCaps: RuntimeCaps | undefined; /** borrowed-readonly — the resolved interaction posture (a manifest cell). */ resolvedInteractionPosture: ToolExecuteContext["interactionPosture"]; /** borrowed-readonly — the question-face phase's durable-face decision (the composition-lie detector reuses it). */ durableQuestionFace: boolean; /** borrowed-readonly — the live question face, or undefined (the notice's effective fact). */ liveQuestionFace: OnQuestion | undefined; /** borrowed-readonly — the leg's checkpoint store, resolved once by the question-face phase. */ checkpointStore: CheckpointStore | undefined; /** borrowed-readonly — the session store (durability declaration and transcript tier). */ sessions: SessionStore; /** borrowed-readonly — the model gate's per-leg read face, or undefined. */ modelGateManifest: WiringManifest["modelGate"]; /** borrowed-readonly — the leg's minted tool roster: rides the manifest's `tools` section and is the * source of the hand band's write-capable names for the ungated-write warning (what actually MOUNTED) and of each MCP server's * `toolCount` (its tools among the roster's names). */ toolRoster: ToolRoster; /** borrowed-readonly — the leg's mount plan, settled against the roster above (every member mounted): rides the manifest's * `toolPlan` section. */ toolPlan: ToolMountPlan; /** borrowed-readonly — from the read-face phase: the built-in read-deny TIERS that leg's own * resolution materially activated; relayed onto the manifest (present iff non-empty), never * re-derived from `deps` here (which by this phase sits past that phase's await). */ readDenyBuiltinTiersActive: readonly string[]; /** borrowed-readonly — from the read-face phase: the byte floor's judgment of the table that leg compiled (its rows ⇔ rows on an environment that does not keep the floor, else `false`); relayed as `readDenyFloor`, never re-derived here. */ readFloorUnkept: import("../../tools/fs/read-floor.js").ReadFloorRows | false; /** borrowed-readonly — from the LSP phase's manager fold: gates the manifest's LSP section (absent ⇒ byte-identical manifest). */ lspManagerWired: boolean; /** borrowed-readonly — from the LSP phase: is the diagnostics lane live? The `lane` word's only input. */ lspDiagnosticsLive: boolean; /** borrowed-readonly — from the file-history phase's one fold of the two off switches: the manifest's word, relayed. */ fileHistoryFact: NonNullable<WiringManifest["fileHistory"]>; /** borrowed-readonly — from the project-context phase: did it call the deployment's seam (the arm's own predicate), relayed. */ projectMemoryFact: NonNullable<WiringManifest["projectMemory"]>; /** borrowed-readonly — from the policy-chain phase: this leg's own session-rule layer published its key for the children's chain (`ownSessionRulesRef.current !== undefined`), relayed as `sessionRules.childrenReadLive`. */ sessionRulesChildrenReadLive: boolean; /** borrowed-readonly — the config doors' one reading of the leg's run origin, relayed into `leg` (absent ⇒ the host said nothing). */ runOrigin: NonNullable<WiringManifest["leg"]>["runOrigin"]; /** borrowed-readonly — the run's command sandbox, judged once at the leg's anchors: the manifest's cell (relayed), and an armed one is * gate work (a call let go carries its plan). */ commandSandboxFact: { readonly state: "off"; } | { readonly state: "not_needed"; } | { readonly state: "armed"; } | { readonly state: "unavailable"; readonly reason: string; }; /** borrowed-readonly — the leg's declared places (the driver's one mint): the write table's roots, and the manifest's count of each. */ callerPlaces: import("./leg-caller-places.js").LegCallerPlaces; /** borrowed-readonly — the advisor phase's answer, relayed. */ advisorFact?: WiringManifest["advisor"]; /** borrowed-readonly — the config doors' compiled host floor's posture, relayed (absent ⇒ none declared). */ hostFloorPosture: WiringManifest["hostFloor"]; /** borrowed-readonly — this leg's project verdict from `resolveSessionProject` (same mint as `workspace_changed.project` and P-e refusal detail), relayed into `project` / `projectMarkerUnreadable`; absent ⇒ no verdict. */ sessionProject?: Pick<SessionProjectVerdict, "project" | "markerFault">; /** borrowed-readonly — the arming outcome the caps phase reads live (the manifest's auto-mode face at this leg's start). */ autoModeArmReason: () => AutoModeArmFact; /** borrowed-readonly — the leg's live permission-mode seat: its receipt at this leg's start rides the manifest, and the * peer lane reads the effective mode through the refs filled here. */ permissionMode: PermissionModeController; /** borrowed-readonly — the leg's fast mode: its reading at this leg's start rides the manifest when the leg is engaged (absent on a * hand-built input: no reading rides). */ fastMode?: Pick<import("./fast-mode-seat.js").FastModeLeg, "engaged" | "readingOf">; /** borrowed-readonly — the frozen preflight; only `mcp` (the declared servers the manifest face joins). */ lockedPreflight: Pick<LockedPreflight, "mcp">; /** borrowed-mutable — the peer lane's late-bound facts. Writer here: `askEffective` ← the manifest's ask derivation (the * one fold of this session's permission-mode class). */ peerLaneRefs: PeerLaneRefs; /** borrowed-mutable — #1036's settlement seam, minted by the orchestrator. This phase writes * its two predicate seats (`boxBacked` / `wantsEffects`) when it binds the drain; the ledgers * themselves are written later, by the harness receipt sink, the compaction commit beat and the * drain's own passes. */ frameSettlement: import("../frame-settlement.js").FrameSettlement; /** borrowed-readonly — the leg's receiving station (bound to the leg's bus by the orchestrator, after this phase): the * drain's pull face hands each record it reads to it. */ receiveSeat: import("../task-notification.js").FrameReceiver; /** borrowed-readonly — the session-box drain's mount verdict (prepare-task's one judgment): present ⇒ this leg drains its own box. */ sessionBox: SessionBoxBinding | undefined; /** borrowed-readonly — the leg's own session address (`sessionAddressOf`): the box is drained for it. */ sessionAddress: SessionAddress; /** borrowed-mutable — the run's end: the drain hands what it binds the session's process-level seats through it (absent outside a stream). */ runEnd?: import("./end-of-run.js").RunEnd | undefined; /** borrowed-readonly, read late — the memory session's one-way pollution face (absent with no memory session). The drain marks * it when it INJECTS a letter from another principal (the injection path; the tool path is accounted by `ReadInbox`'s class). */ memoryPollution?: () => Pick<NonNullable<Prepared["memoryEngineSession"]>["pollution"], "markPolluted"> | undefined; /** borrowed-readonly — the built harness the peer drain binds to. */ harness: AgentHarness; /** borrowed-readonly — the durable-suspend holder; the drain's parked predicate reads `token` at run time. Not written here. */ pausedRef: Prepared["pausedRef"]; /** borrowed-readonly — the run's approval seat as the config doors froze it: the gate's approver and the notice's facts (its * value), the manifest's ask cell (its form and provenance). */ askSeat: import("../wiring-manifest.js").AskSeat; /** borrowed-readonly — the LIVE half of the inherited chain (the notice reads its content mandates). */ liveInheritedGate: RunInternals["inheritedGate"]; /** borrowed-readonly — the effective delegation facts (the identity's isDelegatedChild). */ delegation: { isDelegatedChild: boolean; }; /** borrowed-readonly — the driver's one leg fact (`approvalParkNotResumableOf`): the synthesis, the park lane's atom and the suspend gap read it. */ approvalParkNotResumable: ApprovalParkNotResumable | undefined; /** borrowed-readonly — the driver's refusal fact (the entitlement ∧ `approvalParkNotResumable`, its source word; the store is not a term): the notice's `leg_not_resumable`. */ forcedGateNotResumable: ApprovalParkNotResumable | false | undefined; } export interface PrepareWiringManifestResult { /** owned — the run's own approver seat (spec over deps), read by the gate-fold station. */ onAsk: OnAsk | undefined; /** borrowed-mutable — PreToolUse `additionalContext` per call id. Writers: the gate (phase 1 stash), the post-tool handler * (one-shot drain). */ preToolContexts: Map<string, string[]>; /** borrowed-mutable — the call ids the gate blocked or suspended (`Prepared.blockedToolCalls`). Writers: the gate; readers * delete one-shot. */ blockedToolCalls: Set<string>; /** borrowed-mutable — the turn's halt fact (`Prepared.batchHaltRef`). Writer: the judgment site; cleared at the next request. */ batchHaltRef: Prepared["batchHaltRef"]; /** owned — whether any consumer of the blocked set is wired (populate only then). */ blockedTracked: boolean; /** owned — why the per-task env is in NEITHER suspend target, as the clause every suspend lane's refusal names it by * (`is not a RemoteExecutionEnv …` / `does not declare …` / `declares … but …`), or undefined. */ suspendTargetGap: string | undefined; /** owned — the infrastructure half of suspend eligibility (no task opt-in in it). */ durableSuspendInfraReady: boolean; /** owned — why that infrastructure is not ready, as the clauses of every missing piece joined (`Prepared.suspendLaneGap`), * or undefined when it is. */ suspendLaneGap: string | undefined; /** owned — the task-axis lane: the infrastructure plus the caller's opt-in. */ resourceSuspendEligible: boolean; /** owned — the run's usage-governance handle, or undefined (`Prepared.usageGovernance`). */ usageGovernance: UsageGovernance | undefined; /** owned — whether the suspend saga must be armed for a PLATFORM cause. */ platformSuspendArmed: boolean; /** owned — the effective durable-approval opt-in: the caller's, or the scope synthesized for a forced durable gate. */ durableApproval: import("../task-spec.js").DurableApprovalOptIn | undefined; /** owned — this leg's EFFECTIVE wiring manifest (`Prepared.wiringManifest`). */ wiringManifest: WiringManifest; /** owned — the seat's own `ask.effective` (no mode; `askSeatEffective` over the manifest's facts), minted once: the runtime readers read it beside the live mode. */ askSeatWord: AskEffective; /** owned — the leg's write judgment: its gate input (`mount.check`, absent when the table was emptied — no tighten * mounted) for the gate station and its one target judgment for the shell station — one compile, never two. */ writeProtection: LegWriteProtection; /** owned — THE park predicate as one named const (`parkLane.effective === true`). */ parkLaneArmed: boolean; /** owned — THE gate-machinery activation predicate as one named const: a policy, a screening hook, an egress or * irreversible tool, an eligible resource lane, an armed platform lane, or plan mode. The ask lane, the suspend saga, * the boundary parks, the park closure and the gate station are built exactly when it holds. */ gateMachineryActive: boolean; /** owned — THE identity mint of this leg (`Prepared.hookIdentity`), one frozen envelope every hook station reuses. */ hookIdentity: HookInvocationIdentity; /** owned — the read-only env capability face every hook context carries, or undefined (no hook consumer, or no env wired). */ hookEnvFace: HookEnvCapabilities | undefined; /** owned — the session box this leg's drain was BOUND on (the mount judgment ∧ an injector to drain into); the notification * lane binds the park seat on exactly this value, so "parked here" and "drained there" are one fact. */ sessionBoxBound: SessionBoxBinding | undefined; } /** One missing piece of the durable-suspend infrastructure: its manifest code and the clause a refusal names it by. */ export interface SuspendInfraGap { readonly code: SuspendLaneReason; readonly why: string; } /** * THE durable-suspend infrastructure derivation: every missing piece, in the order an operator wires them (the store, the * tool-result offload, the per-task env). Empty ⇔ the leg can suspend durably. Its readers are the suspend lanes' exposure, * the manifest's `suspendLane` (the codes) and every refusal that names why (the clauses) — never a second spelling. */ export declare function durableSuspendInfraGaps(facts: { readonly storeWired: boolean; /** The leg's one fact says its LANE holds no park of it (source `lane`): no suspend of it is resumed by anyone. The host's word * (source `host`) is not a gap here — it speaks for the decision parks only. */ readonly laneHoldsNoPark: boolean; readonly volatileToolResults: boolean; readonly envGap: { readonly code: Extract<SuspendLaneReason, `env_${string}`>; readonly clause: string; } | undefined; }): SuspendInfraGap[]; /** The M18 phase body — prepareTask's wiring-manifest stretch, verbatim (see the module header). */ export declare function prepareWiringManifest(input: PrepareWiringManifestInput): PrepareWiringManifestResult;