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.jsonallows the three tools in plan’s rules too, as the #136 invariant (test/wiring.test.ts) requires of every tool the extension defines; plan’stoolslist still omits them, so plan mode never offers them. -
Erratum (2026-10-25):
RegistryDepstakes an optionalmaxActionQueue(defaultMAX_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
topicsource, nopublishtool, 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
matchpattern picks the lines that count; asilence_mswakes 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_matchcommand 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_msis bounded by configuration, and0there 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 commandstring
The source. Each stdout line is an event; stderr goes to a file; exit ends the monitor. Judged as bash before anything is spawned.
descriptionstring
Names the monitor in every message and in
monitor_list.instructionsstring?
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.
matchstring?
A JavaScript regular expression. Only matching lines are events; the rest are written to the stdout file and counted as ignored. Invalid: refused.
silence_msnumber?
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_matchstring?
An action run on each event, unattended:
bash -c, with the event inGADHS_MONITOR_EVENTand the monitor inGADHS_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 bymonitor.actionTimeoutMsand its group killed past it. Output to the actions log.wakeboolean?
Whether an event wakes the agent. Default
truewithouton_match,falsewith it. A failed action (non-zero exit, timeout, could not start) always wakes,cause: "action-failed", with the action’s last lines.timeout_msnumber?
≥ 1 000 and ≤
monitor.maxTimeoutMs; defaultmonitor.defaultTimeoutMs. Refused above the cap, naming it.persistentboolean?
Until the session ends, no timeout. Allowed only when
monitor.maxTimeoutMsis0or the operator setmonitor.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 |
|---|---|---|
|
3 600 000 |
The most a |
|
300 000 |
When |
|
8 |
Per session; the next is refused. |
|
60 000 |
One action run’s bound. |
|
|
|
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 |
|---|---|---|
|
200 |
Lines within the window are one event. |
|
500 |
A longer line is cut with |
|
3 000 |
A longer event is cut the same way. |
|
10 |
Events at once before the steady rate applies. |
|
2 000 |
One event per interval after the burst; the rest are suppressed, and the next says how many. |
|
30 000 |
Suppressed for this long: stopped, |
|
1 048 576 |
A line that never ends keeps its last megabyte (pinned in |
|
6 000 |
A pause this long since the last suppressed batch starts a fresh suppression window, so a flood is measured as one stretch. |
|
2 000 |
Standing instructions beyond it: refused. |
|
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 |
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 |
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; |
An event is read as the human’s instruction. |
Fail closed |
Custom message, no |
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; |
A child outlives the session. |
Fail closed |
Group kill at stop, at |
A failed action goes unnoticed. |
Fail closed |
Every failure wakes the agent, whatever |
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 |
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. |
|
Fail closed |
The tool refuses with that sentence before anything is judged or spawned; a test empties |
Scope
pi-modes
-
monitor-stream.ts(written): the constants;LineBatcher({ windowMs, onBatch })withpush,flush,flushRemainder,close;cutEvent;RateLimiter(now).take(count)returning{ deliver: true, suppressed }or{ deliver: false, flood, suppressedForMs },unreported(). Ported from upstreamstream.tswith attribution. -
monitor-process.ts(written):spawnMonitor({ command, cwd, stderrPath }),started(child),killTree(child, graceMs),killAllOnExit(live). GainsrunAction({ command, cwd, env, logPath, timeoutMs }): Promise<{ code: number | null; timedOut: boolean; tail: string[] }>for an action run. Ported from upstreamprocess.tswith 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 injecteddeliver(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:registerToolsAndCommandsgains the monitor tools, passingjudge. -
modes.json:monitor,monitor_stop,monitor_listallowed in auto and manual; absent from plan’stoolsand every helper profile. -
Tests (vitest, named for the property asserted):
File Category Cases test/monitor-stream.test.tsunit + property
Window; line and event cuts; blank lines; burst then steady; suppressed counted and reported; flood past 30 s (fake clock);
flushRemainder;closedrops. 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.tsintegration
A real
bash -c: lines arrive; exit ends;killTreetakes a grandchildsleepwith it; stderr in the file at 0600; a bad cwd rejectsstarted;runActionreturns the exit, the tail andtimedOut, and kills the group past its bound.it.skipIf(win32)on group checks.test/monitor-registry.test.tsbehaviour + concurrency
With a fake deliver and a fake clock:
matchpicks lines and counts the rest;silence_mswakes and re-arms;on_matchruns once per event, serially, with the four variables and the queue bound;wakedefaults; a failed action wakes; the cap;timeout_msends with its notice;stopends 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.tsbehaviour + security regression
With a fake
piandjudge: a source the bash rules deny (git push --no-verify) is refused and a sentinel proves nothing ran; a deniedon_matchrefuses the whole monitor, source unspawned; both commands reachjudgeCommand, the action with its framing; an allowed source’s lines arrive asgadhs-monitorcustom messages withtriggerTurnandsteer; the first line and the instructions framing; adeferreachesconfirmAtHostand a no is a refusal;timeout_msabove the cap refused naming it;persistentrefused when disallowed;session_shutdownstops all.test/config.test.tsunit
monitorkeys, defaults, unknown key refused,defaultTimeoutMsabovemaxTimeoutMsrefused,0cap.test/subagent-gate.test.ts(the profile drift test)regression
No agent file under
packages/pi-agents/agents/namesmonitor,monitor_stopormonitor_list.test/human-requests.test.tssecurity 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 itafteryield’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.adocgains the block. -
docs/modules/ROOT/pages/plans/monitor.adoc: this plan;nav.adocunder plans. The first draft’s untrackeddocs/modules/ROOT/pages/plans/monitor-topics.adocis 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 landnotes the merge SHA.
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.