Plan: the monitor - any process, bus or data source wakes the agent or acts on its behalf

Closes: #446. Branch: feat/monitor. Status: Done (2026-10-25) — monitor, monitor_stop and monitor_list in pi-modes, command-only, both commands judged as bash

  • Erratum (2026-10-25): modes.json allows the three tools in plan’s rules too, as the #136 invariant (test/wiring.test.ts) requires of every tool the extension defines; plan’s tools list still omits them, so plan mode never offers them.

  • Erratum (2026-10-25): RegistryDeps takes an optional maxActionQueue (default MAX_ACTION_QUEUE), so the queue bound is testable: behind the rate limit, 100 queued events take minutes to produce.

  • Erratum (2026-10-25): when the source exits, actions already owed for its last events run before the closing notice; the plan’s "one closing notice and nothing after" holds, and a source that prints its result and exits still gets its action.

Design

The decision, and what changed since the first plan

Written in pi-modes, borrowing pi-cc-monitor 0.7.4’s stream and process code with attribution (MIT inside AGPL). The reasons stand from the first plan (vendoring would carry a Monitor tool that spawns with no policy check, a /pi_cc panel and loop coupling; pi-remote’s hub is for remote human control and must not be a dependency). The operator’s decisions at implementation start (2026-10-25) replaced the rest:

  • Command-only, generic. No topic source, no publish tool, no ntfy code. A tool that knows one transport is the wrong shape; a tool that turns any command’s lines into events covers every transport that can print a line, and every command is judged.

  • Act on things happening or not happening. A match pattern picks the lines that count; a silence_ms wakes the agent when nothing has arrived for that long.

  • Standing instructions. The agent says at setup what it means to do when woken; every wake carries that text, so the woken turn knows its job without re-reading the transcript.

  • An unattended action. An optional on_match command runs on each event with no model in the loop, judged once at setup. The event reaches it as an environment variable, never interpolated into the command.

  • The time cap is the operator’s. timeout_ms is bounded by configuration, and 0 there is no bound.

No ADR: one package’s tool, reversible by deleting it.

The tools

Three tools, in auto, manual and yolo; not in plan mode’s list (plan designs; the acting mode monitors). Helpers do not get them: pi-subagents hands a helper a custom tool only when its agent file’s tools: names it (node_modules/@gotgenes/pi-subagents/src/config/agent-types.ts:100, getToolNamesForType(type) { return this.resolveAgentConfig(type).toolNames ?? […​BUILTIN_TOOL_NAMES]; }, where BUILTIN_TOOL_NAMES is read, bash, edit, write, grep, find, ls), no file under packages/pi-agents/agents/ names monitor, and the pi-modes profile drift test gains the assertion that none does. Registered as ask and count are (command-wiring.ts, registerAskTool): pi.registerTool({ name, label, description, promptSnippet, promptGuidelines, parameters: Type.Object(…​), execute }).

monitor

Starts one and returns its id.

Parameter Type Meaning

command

string

The source. Each stdout line is an event; stderr goes to a file; exit ends the monitor. Judged as bash before anything is spawned.

description

string

Names the monitor in every message and in monitor_list.

instructions

string?

The agent’s standing instructions to itself, ≤ 2 000 chars, carried on every wake. Framed in the message as the agent’s own words, not the human’s.

match

string?

A JavaScript regular expression. Only matching lines are events; the rest are written to the stdout file and counted as ignored. Invalid: refused.

silence_ms

number?

Wake with cause: "silence" when no event has arrived for this long (≥ 1 000). Re-arms after each silence wake; the agent stops the monitor when it no longer wants the heartbeat.

on_match

string?

An action run on each event, unattended: bash -c, with the event in GADHS_MONITOR_EVENT and the monitor in GADHS_MONITOR_ID, GADHS_MONITOR_DESCRIPTION, GADHS_MONITOR_CAUSE. Judged as bash at setup, with the ask saying it runs unattended on every event. One at a time per monitor; events during a run queue (≤ 100, then dropped and counted); each run is bounded by monitor.actionTimeoutMs and its group killed past it. Output to the actions log.

wake

boolean?

Whether an event wakes the agent. Default true without on_match, false with it. A failed action (non-zero exit, timeout, could not start) always wakes, cause: "action-failed", with the action’s last lines.

timeout_ms

number?

≥ 1 000 and ≤ monitor.maxTimeoutMs; default monitor.defaultTimeoutMs. Refused above the cap, naming it.

persistent

boolean?

Until the session ends, no timeout. Allowed only when monitor.maxTimeoutMs is 0 or the operator set monitor.allowPersistent; default allowed.

monitor_stop

id. The source’s group and any running action are killed; one closing notice.

monitor_list

Per monitor: id, description, status, since when, events, ignored, suppressed, actions run and failed, exit code, and the three file paths.

Files, under <agentDir>/gadhs-pi-monitor/ (0700): <id>.stdout, <id>.stderr, <id>.actions.log, each 0600. Nothing is replayed from them; the model reads them with read when it wants history.

Configuration

ModesConfig.monitor, validated beside unattended in config.ts with nonNegativeInteger and the same unknown-key refusal:

Key Default Meaning

maxTimeoutMs

3 600 000

The most a timeout_ms may ask; 0 is no bound.

defaultTimeoutMs

300 000

When timeout_ms is omitted; refused above maxTimeoutMs at load.

maxMonitors

8

Per session; the next is refused.

actionTimeoutMs

60 000

One action run’s bound.

allowPersistent

true

false refuses persistent.

Both commands are bash

JudgeWiring (judge-wiring.ts) gains judgeCommand(command: string, framing?: string): Promise<AttributedVerdict>: adjudicateAsk’s pipeline on a synthesised ask `{ toolName: "bash", surface: "bash", command, fullCommand: command, toolInputPreview: framing } - normalise, decideAtGate, askBeyondTheGate, recordVerdict, the debug pair - with the log stampedLog(modes, tapJudgeCalls(deps, undefined)) as adjudicateAsk builds it when the permission system passes none. So the source and the action meet the rules, the safety valve, the high-consequence list, the denial threshold, the judge, the pending queue and the phone exactly as the bash tool’s command would. The action’s framing is monitor action: runs unattended on every event, the event text in $GADHS_MONITOR_EVENT, so the judge decides it as what it is. A defer that askBeyondTheGate leaves untouched (the terminal, no phone) goes to confirmAtHost (host-ask.ts) with the command as the subject; a no, a timeout or a stopped turn is a refusal. Nothing is spawned unless both verdicts are allow; a refusal’s tool result is the verdict’s reason or the pending queue’s text, so the model retries when the human approves, as with bash. The permission system also gates the three tools as tools: modes.json allows each with "*" in auto and manual, as count is.

Sources and actions

Source. spawn("bash", ["-c", command], { detached: platform !== "win32", stdio: ["ignore", "pipe", stderrFd] }), cwd the session’s. bash must be on PATH (the distribution’s guards already need Git Bash on Windows) or the tool refuses with that sentence. stdout is copied to the stdout file and fed to the LineBatcher. Stop: SIGTERM to the group, SIGKILL 2 s later if alive; win32 taskkill /T /F. All monitors stop at session_shutdown; a synchronous process.on("exit") hook SIGKILLs every live group on an abnormal exit.

Action. bash -c on_match with the session’s env plus the four variables, same cwd, its own group, stdout and stderr appended to the actions log with a timestamp and the exit, killed past actionTimeoutMs. The event text in the variable is the batch’s text (≤ MAX_EVENT_CHARS), never written into the command line.

Recipes (docs, not code). A log: tail -n0 -F deploy.log. CI: glab ci status --live. ntfy: curl -sN https://ntfy.example/topic/json with match: '"event":"message"'; sending is a bash curl -d. Another session on the box: one monitors tail -n0 -F ~/.local/state/gadhs/inbox-<name>, the other appends with bash; a test demonstrates it. A socket: nc -l 127.0.0.1 9000. A watchdog: silence_ms on a heartbeat source. Forwarding: on_match: 'curl -sd "$GADHS_MONITOR_EVENT" https://ntfy.example/me', judged once.

Events and wakes

An event is pi.sendMessage({ customType: "gadhs-monitor", content, display: true, details }, { triggerTurn: true, deliverAs: "steer" }) - pi’s ExtensionAPI.sendMessage, declared in the installed pi (~/.local/share/pi-node/current/lib/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/types.d.ts:1258: sendMessage<T = unknown>(message: Pick<CustomMessage<T>, "customType" \| "content" \| "display" \| "details">, options?: { triggerTurn?: boolean; deliverAs?: "steer" \| "followUp" \| "nextTurn"; }): void;), the call pi’s own examples/extensions/file-trigger.ts makes with { triggerTurn: true }; subagent-wiring.ts already calls sendMessage without options for a yield. content: a fixed first line monitor <id> · <description> · outside signal, not the human’s instruction; then standing instructions (the agent’s own, set at monitor start): <instructions> when set; then the lines, or no event for <n> s for a silence, or the failed action’s last lines. details: { monitorId, cause, lines, eventCount, ignored, suppressed, exitCode }. Steer: idle, it starts a turn; busy, it lands after the current tool call. Ending (exit, timeout, error, stopped, flooded) sends one closing notice and nothing after it; a monitor with wake: false still sends its closing notice.

Cost and noise

The stream constants are at the top of monitor-stream.ts (written), pi-cc-monitor’s numbers; the last two are at the top of monitor-registry.ts (new). Blank lines are not events. The limiter counts every batch, wake or action; a flood stops the monitor, actions included.

Constant Value Effect

BATCH_MS

200

Lines within the window are one event.

MAX_LINE_CHARS

500

A longer line is cut with …(truncated).

MAX_EVENT_CHARS

3 000

A longer event is cut the same way.

BURST

10

Events at once before the steady rate applies.

STEADY_MS

2 000

One event per interval after the burst; the rest are suppressed, and the next says how many.

FLOOD_STOP_MS

30 000

Suppressed for this long: stopped, cause: "flooded".

MAX_PARTIAL_LINE_CHARS

1 048 576

A line that never ends keeps its last megabyte (pinned in test/monitor-stream.test.ts).

QUIET_GAP_MS

6 000

A pause this long since the last suppressed batch starts a fresh suppression window, so a flood is measured as one stretch.

MAX_INSTRUCTIONS_CHARS

2 000

Standing instructions beyond it: refused.

MAX_ACTION_QUEUE

100

Events waiting for a running action; beyond it, dropped and counted.

Authority

An event is a custom message: humanReplyText (#266) counts only typed or rpc input, or text a paired device vouched for, as the human’s, and a custom message fires no input event, so no monitor text can become a human request or answer a pending ask. The first line tells the model the same, and the instructions are framed as the agent’s own. before_agent_start runs started by an event have messageType: "custom" and no prompt; onBeforeAgentStart (session-wiring.ts) reads only event.systemPrompt, so such a run gets the same composed prompt. Nothing here registers before_agent_start, context or before_provider_request, so events only append and the prompt cache holds.

Risks

Risk Posture Mitigation

A source or action runs with no policy check.

Fail closed

Nothing spawns unless judgeCommand says allow for each; a sentinel-file test proves a refused command never ran.

Data from the source reaches a shell.

Fail closed

The event is an environment variable; the action’s command line is the text the judge saw. A test feeds $(touch sentinel) and backticks as event text and asserts no file.

An action runs unattended for a long time, doing something the judge allowed once.

Fail closed at setup, open after

The ask says unattended and repeated; manual mode’s human sees it; monitor_list shows actions run; the time cap and allowPersistent are the operator’s.

An event is read as the human’s instruction.

Fail closed

Custom message, no input event; the first line; a test asserts no human request is recorded.

A chatty source buys a turn or an action per line.

Fail closed

The limits table; serial actions with a bounded queue; the flood stop; maxMonitors.

A child outlives the session.

Fail closed

Group kill at stop, at session_shutdown, and in the synchronous exit hook; actions in their own groups, killed at their timeout.

A failed action goes unnoticed.

Fail closed

Every failure wakes the agent, whatever wake says.

A silence watchdog never fires because the source died.

Fail closed

Exit ends the monitor with a closing notice; silence is only measured while it runs (pinned in test/monitor-registry.test.ts: a source that exits before silence_ms sends the exit notice, never a silence wake).

A secret in the session’s env reaches an action.

Fail open, as bash is

The action runs as the bash tool’s commands do, with the same env; nothing new is exposed.

bash is not on PATH.

Fail closed

The tool refuses with that sentence before anything is judged or spawned; a test empties PATH and asserts it.

What is not done

A custom renderer. Reconnecting a source that exits (the agent restarts it; the closing notice says so). A /monitor command or footer count. Monitors for helpers or plan mode. Replay from the files. Per-monitor model or thinking overrides for the woken turn.

Scope

pi-modes

  • monitor-stream.ts (written): the constants; LineBatcher({ windowMs, onBatch }) with push, flush, flushRemainder, close; cutEvent; RateLimiter(now).take(count) returning { deliver: true, suppressed } or { deliver: false, flood, suppressedForMs }, unreported(). Ported from upstream stream.ts with attribution.

  • monitor-process.ts (written): spawnMonitor({ command, cwd, stderrPath }), started(child), killTree(child, graceMs), killAllOnExit(live). Gains runAction({ command, cwd, env, logPath, timeoutMs }): Promise<{ code: number | null; timedOut: boolean; tail: string[] }> for an action run. Ported from upstream process.ts with attribution.

  • monitor-registry.ts (new): MAX_INSTRUCTIONS_CHARS, MAX_ACTION_QUEUE; MonitorRecord, MonitorRegistry - ids, the cap, start (source spawn, batcher, limiter, match, silence timer, timeout), the action queue, ends, stop(id), list(), stopAll(), and delivery through one injected deliver(message) function. No pi import: testable with fakes.

  • monitor-tools.ts (new): the three tools, registerMonitorTools(pi, modes, judge, config, agentDir), the message content, session_shutdown. Each handler under 40 lines.

  • judge-wiring.ts: JudgeWiring.judgeCommand(command, framing?).

  • config.ts: ModesConfig.monitor, MONITOR_KEYS, defaults, monitorLimits(config); validation.

  • index.ts: registerToolsAndCommands gains the monitor tools, passing judge.

  • modes.json: monitor, monitor_stop, monitor_list allowed in auto and manual; absent from plan’s tools and every helper profile.

  • Tests (vitest, named for the property asserted):

    File Category Cases

    test/monitor-stream.test.ts

    unit + property

    Window; line and event cuts; blank lines; burst then steady; suppressed counted and reported; flood past 30 s (fake clock); flushRemainder; close drops. fast-check over arbitrary chunkings of a line stream: no throw, every output within the caps, the same lines whatever the chunking, delivered + suppressed = batches.

    test/monitor-process.test.ts

    integration

    A real bash -c: lines arrive; exit ends; killTree takes a grandchild sleep with it; stderr in the file at 0600; a bad cwd rejects started; runAction returns the exit, the tail and timedOut, and kills the group past its bound. it.skipIf(win32) on group checks.

    test/monitor-registry.test.ts

    behaviour + concurrency

    With a fake deliver and a fake clock: match picks lines and counts the rest; silence_ms wakes and re-arms; on_match runs once per event, serially, with the four variables and the queue bound; wake defaults; a failed action wakes; the cap; timeout_ms ends with its notice; stop ends an action in flight; stopAll; one closing notice and nothing after. Security regression: event text $(touch sentinel) reaches the action as a variable and no sentinel appears. The file recipe: two registries in one process, one tailing a file the other appends to.

    test/monitor-tools.test.ts

    behaviour + security regression

    With a fake pi and judge: a source the bash rules deny (git push --no-verify) is refused and a sentinel proves nothing ran; a denied on_match refuses the whole monitor, source unspawned; both commands reach judgeCommand, the action with its framing; an allowed source’s lines arrive as gadhs-monitor custom messages with triggerTurn and steer; the first line and the instructions framing; a defer reaches confirmAtHost and a no is a refusal; timeout_ms above the cap refused naming it; persistent refused when disallowed; session_shutdown stops all.

    test/config.test.ts

    unit

    monitor keys, defaults, unknown key refused, defaultTimeoutMs above maxTimeoutMs refused, 0 cap.

    test/subagent-gate.test.ts (the profile drift test)

    regression

    No agent file under packages/pi-agents/agents/ names monitor, monitor_stop or monitor_list.

    test/human-requests.test.ts

    security regression

    An event’s text never becomes a human request.

Docs and notes

  • docs/modules/ROOT/pages/modes.adoc: == The monitor: any source wakes the agent or acts for it after yield’s section - the tools and parameters, both-commands-are-bash, events and wakes, standing instructions, actions and their variables, the limits, the configuration, the recipes, and the credential warning (a topic or inbox anyone can write to is a way to put text in front of the model). `modes.adoc’s top-level config table gains `monitor; tuning.adoc gains the block.

  • docs/modules/ROOT/pages/plans/monitor.adoc: this plan; nav.adoc under plans. The first draft’s untracked docs/modules/ROOT/pages/plans/monitor-topics.adoc is deleted at implementation start.

  • CHANGELOG.adoc == Unreleased, Added: one entry.

  • Release after it lands: pi-modes 0.75.0, pi-remote bumped with it, pi 0.117.0.

  • Close: the commit says Closes #446; task land notes the merge SHA.

Out of scope

  • Anything in pi-remote. Vendoring pi-cc-monitor or pi-cc-loop interop. Built-in transports of any kind.

Review-Context

packages/pi-modes/judge-wiring.ts (adjudicateAsk, decideAtGate, askBeyondTheGate, JudgeWiring), packages/pi-modes/host-ask.ts (confirmAtHost), packages/pi-modes/pending-queue.ts (humanReplyText), packages/pi-modes/command-wiring.ts (registerAskTool, registerCountTool), packages/pi-modes/config.ts (ModesConfig, unattended, ConfigCheck), packages/pi-modes/index.ts, packages/pi-modes/modes.json, packages/pi-modes/session-wiring.ts (onBeforeAgentStart), packages/pi-modes/monitor-stream.ts, packages/pi-modes/monitor-process.ts.

Edit this page · latest