UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

104 lines (103 loc) • 8.19 kB
/** * design/135 G2 (审计 🔴) — the `Monitor` tool: run a shell command in the background and watch its * stdout as a stream of NOTIFICATION EVENTS (the自主循环 core piece: "watch this and tell me when something * happens" without burning poll turns). * * CC-parity semantics (live-harness schema, the archived ground truth): * ① every stdout LINE becomes one event; ② lines within the 200ms batch window coalesce into ONE * notification; ③ process exit ends the watch (exit code reported); ④ non-persistent watches are killed at * `timeout_ms` (default 5min, max 60min); ⑤ stderr never notifies but is mirrored to the output file (with stdout); * ⑥ an event storm is SUPPRESSED first and auto-stops the monitor only if it persists (RB-334, CC `PCo` * 220:403278-403321 two-level control — the suppressed count and the overload duration are disclosed * on both the suppression frame and the stop notification). * * Wiring: the process runs through the SAME ExecutionEnv background seam as Bash(run_in_background) * (`spawnBackground` — remote envs included); the watcher/batching/timeout machinery lives in * {@link TaskRegistry.registerMonitor} (background_bash G2b watcher's near kin); events ride the * TaskNotificationPayload lane at "next" priority (design/373 #445 ALIGNED re-seat: the running turn's * next boundary — consecutive frames drain as one boundary batch, the rate limiter + engine-note cap * with terminal preference keep a chatty watcher from monopolizing the run's boundaries). * (1.257): events born BETWEEN turns (run torn down / harness idle — the long-watch main case) * are no longer lost: the Runner parks them per session (bounded, drop-disclosing) and the session's next * run redelivers them through the same notification lane at its first turn boundary. * (CC parity): a monitor's lifetime = min(timeout_ms, process exit, TaskStop); a `persistent` * one is SESSION-anchored (reaped at session release). NEITHER is run-anchored: the run teardown leaves an * in-window non-persistent watch alive (process on the dispose except-list, watcher ticking, row kept), so * cross-turn watching — CC's main Monitor use case — works with the default persistent:false too; its * between-turns events AND its timeout/exit terminal ride the same pending lane. * The handle is a first-class m* registry task: its output file is the full record (Read-exempt like a background * Bash's, `TaskRegistry.isBackgroundOutputFile`), TaskStop stops the * watch (design/134 stoppedBy attribution applies automatically). * * Security posture: `command` is an arbitrary shell script ⇒ effect:"write", same as Bash; the catalog puts Monitor on the * SHELL FACE, so the `Bash(<command>)` rules, the shell seat, the read station and the removal guard judge its `command` * as they judge Bash's — Monitor is never a policy side-door around a gated Bash. * * Event sources: this tool supplies ONE source, the shell `command`. The reference's `Monitor` input has a second arm, * `ws?: { url; protocols? }` — a WebSocket whose text frames are events, not combined with `command` * (`MonitorInput` (sdk-tools-321.d.ts:2968-2988)) — and a default session of the reference lists it: `Monitor` is a deferred * tool there, so the schema is in the requests that follow a tool search, not in the first request's tool list. Not * supplying the `ws` arm is this engine's own choice (divergence register entry `monitor-ws-source-not-ported`), not an * alignment with the reference. (Full-desc density diff vs the live guidance card remains P1, a separate item.) */ import type { AgentTool, ExecutionEnv } from "../internal/harness-types.js"; import { type MountedModelShell } from "../core/model-shell.js"; import { type MonitorTimers, type TaskRegistry } from "../core/task-registry.js"; import { type TaskNotificationPayload } from "../core/task-notification.js"; import type { ShellReadAdmission } from "./fs/shell-read-check.js"; import type { ReadFloorSeat } from "./fs/read-floor.js"; import { type CommandSandboxSeat } from "../core/command-sandbox.js"; import { type OccupantMount } from "../core/task-registry-shared.js"; /** The refusal a watch gets where no event or completion would come back from it (no completion sink for the call, no * mount sink): nothing is spawned. */ export declare const MONITOR_NO_COMPLETION_CHANNEL = "Error (Monitor): a watch is not available here \u2014 no event or final notification would come back from one on this mount. Run the command in the foreground (with a timeout) instead."; export interface MonitorToolOptions extends OccupantMount { /** The leg's reading of the start for model text (`readModelShell`, `mounted`): the watch starts on its background start. A host * with no leg reads it once (`readModelShell(env)`) and hands it to every shell tool it mounts. */ modelShell: MountedModelShell; registry: TaskRegistry; /** Fallbacks when the runtime ctx carries no identity (direct mounts) — same posture as createBashTool. */ owner?: string; scope?: string; /** design/129: the session id — a `persistent` monitor registers session-scoped under it (outlives the * turn; reaped by the deployment's session release via `reapSessionBackground`). */ sessionId?: string; /** The notification sink (the run-local task-notification lane). A call carrying its run's lane delivers there * instead; with neither, the watch is refused before anything is spawned (nothing it saw would reach the model). */ onTaskNotification?: (n: TaskNotificationPayload, opts?: { priority?: "now" | "next" | "later"; }) => void; /** The tracked logical cwd (shared with the hands band) — the monitor spawns there, like Bash. */ cwdRef?: { current: string; }; /** design/87: injectable timers/clock for the watcher (tests drive ticks manually; default real timers). */ timers?: MonitorTimers; /** Test/deployment knobs (defaults: 200ms window, 50 batches/min). */ batchWindowMs?: number; maxBatchesPerMinute?: number; /** This run is a one-shot submission (`TaskSpec.oneShot`): its ending does not wait for the watch, and the * receipt says so with the one process-lane sentence a background command's receipt carries. */ oneShot?: boolean; /** The gate's shell read station's pre-spawn ADMISSION — the SAME option `createBashTool` takes: this face * spawns a shell command too, so what it runs is what the station judged, re-established before the watch * spawns. Absent ⇒ no station judged this mount; nothing is re-established. */ shellReadAdmission?: ShellReadAdmission; /** The byte floor's seat (read-floor.ts) — the SAME table the shell faces carry: the watched command's start hands it to * the environment. Absent ⇒ the start carries no floor. */ readFloor?: ReadFloorSeat; /** The command sandbox seat (`command-sandbox.ts`) — the SAME one the shell faces take: the watched command's start hands * its call's sandbox instruction to the environment, or is refused. Absent ⇒ the start carries no sandbox. */ commandSandbox?: CommandSandboxSeat; /** RB-465-b (HRD-PTL-3 残件): spec-level retain (`TaskSpec.retainBackgroundProcesses`) — the task lane of * THE retain predicate (`retainsBackgroundProcesses`), OR-composed with the env capability. Read twice, * by the same predicate: the persistent-watch receipt's wording, and the row's `retained` mark at * registration (so the session reap and the exit-boundary hard face judge the row the way the receipt * described it). */ retainBackgroundProcesses?: boolean; /** The task root in the SAME canonical spelling `createBashTool` is built with, so a dead-cwd self-heal * lands both tools on one directory. Absent ⇒ the diagnosis says it has no reset target, rather than * naming the cwd "the task root" or promising a recovery it cannot make. */ rootCanonical?: string; } export declare function createMonitorTool(env: ExecutionEnv, opts: MonitorToolOptions): AgentTool;