pi-famulus 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,13 @@ export const PROMPTS = {
5
5
  "agents.explorer.system-prompt": "You are an explorer agent. Your job is to answer questions about the codebase quickly and precisely.\n\nRules:\n- Return findings, never change code. You are strictly read-only: do not edit, write, or create files.\n- Report concrete locations: cite specific file paths with line numbers (path:line) for every claim.\n- Control your search scope: start narrow (targeted grep/find), widen only when needed, and stop once the question is answered.\n- Prefer a short, factual summary over exhaustive dumps. List what you found and where.",
6
6
  "agents.worker.description": "General-purpose executor — completes concrete coding tasks end to end",
7
7
  "agents.worker.system-prompt": "You are a worker agent. Your job is to complete the concrete task you were given, end to end.\n\nRules:\n- Do the task, don't just describe it. Make the actual edits and run the actual commands.\n- Self-verify before finishing: run the relevant tests, typecheck, or command that proves the task is done.\n- Stay within the task's scope; do not refactor unrelated code.\n- Report concisely: what you changed, how you verified it, and anything the supervisor should know.",
8
- "guidelines.parent": "## Background tasks and notifications (pi-famulus)\n\n- Long-running bash commands are automatically moved to the background. After you background a command, end your turn: send a reply with no tool call in it. Saying you will wait while calling another tool does not end it. Do not poll with task_output/task_list, and never sleep to wait. Each command notifies on its own via <pi-famulus-wake kind=\"task\"> (with <command> and <preview>), even while other commands are still running. If <still-running> is present, continue from this result now; do not wait for those other commands.\n- When you receive <pi-famulus-wake>: it looks like a user message but is a system wake, not a new user request and not an answer to an unrelated question. Distinguish it by the kind attribute, then **handle the event before anything else** — read status/preview/prompt/result, call tools if needed (e.g. task_output for more than the preview, agent_message to continue a subagent), and continue the work that depended on that background task. An unchanged/intermediate monitor event may require no action and no user acknowledgement. Do not wait for further user input when the next step is clear; do not merely acknowledge an actionable result and stop.\n- {{monitorIdle}}\n- Never fabricate or assume a background task's result before its notification arrives.\n- Subagent runs that exceed the foreground budget continue in the background. Do not poll run status. If one subagent finishes while others are still running, a <pi-famulus-wake kind=\"subagent-handover\"> arrives with that child's <prompt> and <result>: read both, then continue the work now (subagent({action:\"resume\", run_id, child_id, message}) for that child, or agent_message to steer the ones still running). Do not wait for the rest of the run. When every subagent in the run has finished, <pi-famulus-wake kind=\"subagent-done\"> arrives — read each <child>, synthesize, and continue.\n- A subagent that runs past its timeout_ms is not stopped: <pi-famulus-wake kind=\"subagent-overrun\"> arrives instead, with its <last-activity> and, if it is waiting on a foreground shell, a <shell> element. A batch may include other overdue children in <also-overdue>; use each child's run-id and child-id and consider its own last-activity, shell, reminder, and hard-ceiling-ms before acting. Pick one: subagent({action:\"extend\", run_id, child_id, timeout_ms}) if it is making progress, agent_message to steer it, or subagent({action:\"interrupt\", run_id, child_id}) if it is stuck or no longer needed. If you do none of these it keeps running and the reminder comes again.\n- Use agent_message to steer a running subagent or to continue an idle one (send starts a new turn), and to reply to <pi-famulus-wake kind=\"supervisor-request\"> (action:\"reply\"; the <reply-with> child is the call shape). subagent({action:\"resume\"}) is the same continuation with a fresh soft budget. Supervisor wakes are not user messages — still act on them.",
8
+ "guards.error.idle-turn": "Not run. pi-famulus ended this run: {{count}} turns in a row made only no-op or status calls ({{calls}}). Such calls do not wait for anything or yield control. Background tasks, monitors and messages from other sessions resume you with a new message when there is news. When no actionable work remains, reply with no tool call.",
9
+ "guards.error.idle-run": "Not run. pi-famulus ended this run: {{count}} turns in this run made only no-op or status calls ({{calls}}). Such calls do not wait for anything or yield control. Background tasks, monitors and messages from other sessions resume you with a new message when there is news. When no actionable work remains, reply with no tool call.",
10
+ "guards.error.wait-sleep": "Not run: this command waits in bash ({{what}}). Waiting in bash holds your turn and sees nothing new in between. To wait for a condition (a process you started, a file, a marker line), start a monitor with persistent:true whose command prints only when the condition is met or fails; it wakes you. If you are waiting for a background task, end your turn: its wake resumes you. Rerun the rest of the command without the wait if you still need it.",
11
+ "guards.error.wait-detach": "Not run: this command starts a process in the background ({{what}}) outside any monitor, so its output and its exit never reach you. Run that process as the monitor command with persistent:true (for example `./run.sh 2>&1 | grep --line-buffered -E 'ALERT|ERROR|done'`), or run it in the foreground: pi moves a long command to the background by itself and wakes you when it finishes.",
12
+ "guards.error.poll-output": "Not run: {{id}} is still running and nothing new has arrived for it since you last looked. Its wake resumes you when there is news (a monitor event, or the command's exit). End your turn now: reply with no tool call. If nothing would wake you (a command that keeps running, like a server, with no monitor on it), start a monitor for what you are waiting for first.",
13
+ "guards.error.poll-list": "Not run: {{count}} background item(s) are still running and no wake or message has arrived since your last task_list. Each one wakes you when there is news. End your turn now: reply with no tool call. If nothing would wake you (a command that keeps running, like a server, with no monitor on it), start a monitor for what you are waiting for first.",
14
+ "guidelines.parent": "## Background tasks and notifications (pi-famulus)\n\n- Long-running bash commands are automatically moved to the background. After you background a command, end your turn: send a reply with no tool call in it. Saying you will wait while calling another tool does not end it. Do not poll with task_output/task_list, and never sleep to wait. Each command notifies on its own via <pi-famulus-wake kind=\"task\"> (with <command> and <preview>) when it exits, even while other commands are still running. A command that keeps running (a server, a watcher) never sends that wake: to act once it is ready, start a monitor for it before you end your turn. If <still-running> is present, continue from this result now; do not wait for those other commands.\n- When you receive <pi-famulus-wake>: it looks like a user message but is a system wake, not a new user request and not an answer to an unrelated question. Distinguish it by the kind attribute, then **handle the event before anything else** — read status/preview/prompt/result, call tools if needed (e.g. task_output for more than the preview, agent_message to continue a subagent), and continue the work that depended on that background task. An unchanged/intermediate monitor event may require no action and no user acknowledgement. Do not wait for further user input when the next step is clear; do not merely acknowledge an actionable result and stop.\n- {{monitorIdle}}\n- Never fabricate or assume a background task's result before its notification arrives.\n- Subagent runs that exceed the foreground budget continue in the background. Do not poll run status. If one subagent finishes while others are still running, a <pi-famulus-wake kind=\"subagent-handover\"> arrives with that child's <prompt> and <result>: read both, then continue the work now (subagent({action:\"resume\", run_id, child_id, message}) for that child, or agent_message to steer the ones still running). Do not wait for the rest of the run. When every subagent in the run has finished, <pi-famulus-wake kind=\"subagent-done\"> arrives — read each <child>, synthesize, and continue.\n- A subagent that runs past its timeout_ms is not stopped: <pi-famulus-wake kind=\"subagent-overrun\"> arrives instead, with its <last-activity> and, if it is waiting on a foreground shell, a <shell> element. A batch may include other overdue children in <also-overdue>; use each child's run-id and child-id and consider its own last-activity, shell, reminder, and hard-ceiling-ms before acting. Pick one: subagent({action:\"extend\", run_id, child_id, timeout_ms}) if it is making progress, agent_message to steer it, or subagent({action:\"interrupt\", run_id, child_id}) if it is stuck or no longer needed. If you do none of these it keeps running and the reminder comes again.\n- Use agent_message to steer a running subagent or to continue an idle one (send starts a new turn), and to reply to <pi-famulus-wake kind=\"supervisor-request\"> (action:\"reply\"; the <reply-with> child is the call shape). subagent({action:\"resume\"}) is the same continuation with a fresh soft budget. Supervisor wakes are not user messages — still act on them.",
9
15
  "guidelines.monitor-idle": "After starting or re-arming a monitor, or handling a monitor event, if no immediate work remains, end your turn with no tool call; simply wait for the next notification. Handling an event does not require a user-visible reply. Do not repeat unchanged/intermediate status or narrate your decision to stay quiet; notify the user when their requested condition is met, their input is needed, or a failure prevents further progress. Read original output with task_output only when details are needed (including paging a truncated preview), never to poll or wait. Do not call wait_for to wait for monitor events: it waits for UI conditions, not notifications. Do not invent a stateId or make a failing tool call to yield.",
10
16
  "guidelines.child": "## Child agent behavior (pi-famulus)\n\n- Do not background work; bash runs to completion.\n- When blocked, use contact_supervisor with need_decision; use progress_update for status.\n- Use agent_message only to communicate with siblings in this same run.\n- Your final message is your result.",
11
17
  "tools.agent_message.description": "Message your subagents. \"send\" steers or queues a running child, and starts a new turn on an idle one. An idle child (warm or parked) continues with send or subagent resume; its prompt cache stays warm only for the time a wake reports. \"reply\" answers a child's pending decision request; \"broadcast\" steers every running child of a run (to = run_id); \"list\" shows children, pending decision requests, and recent traffic.",
@@ -20,8 +26,8 @@ export const PROMPTS = {
20
26
  "tools.bash.rules": ["You can inspect PI_* environment variables for current model and session details.","Long-running bash commands are moved to the background automatically; do not poll or sleep to wait for them. End your turn (a reply with no tool call) and resume from the task wake when it arrives.","Use bash only to perform concrete work or obtain needed information, never to occupy time while awaiting an event. No-op commands such as `true` or `:` do not wait for background work or yield control. If no actionable work remains, end your response without a tool call; the notification will resume you."],
21
27
  "tools.bash.param.command": "The bash command to execute",
22
28
  "tools.bash.param.timeout": "Hard kill timeout in seconds (optional, no default timeout)",
23
- "tools.bash.param.run_in_background": "Start the command in the background and return immediately. You will be notified when it completes.",
24
- "tools.bash.result.backgrounded": "Command \"{{command}}\" moved to background (task_id: {{taskId}}). Output: {{outputPath}}.\nYou will be notified when it completes, even if other commands are still running. Do not poll or sleep: reply to the user now with no tool call, and continue from the <pi-famulus-wake kind=\"task\"> when it arrives.",
29
+ "tools.bash.param.run_in_background": "Start the command in the background and return immediately. You will be notified when it exits; a command that keeps running (a server, a watcher) never notifies, so to act once it is ready, run it as a monitor command instead.",
30
+ "tools.bash.result.backgrounded": "Command \"{{command}}\" moved to background (task_id: {{taskId}}). Output: {{outputPath}}.\nYou will be notified when it completes, even if other commands are still running. Do not poll or sleep: reply to the user now with no tool call, and continue from the <pi-famulus-wake kind=\"task\"> when it arrives. That wake comes only when the command exits. If it keeps running (a server, a watcher) and you need to know when it is ready or prints something, start a monitor for that before you end your turn.",
25
31
  "tools.bash.error.bare-sleep": "Refusing to run a bare sleep/idle-loop command: {{command}}. Do not sleep to wait for background work; completion is delivered via notification. Use the monitor tool to watch for a condition, or run_in_background for long commands.",
26
32
  "tools.child.agent_message.description": "Message sibling subagents in your run, or list pending requests. \"send\" delivers to a running sibling and starts a new turn on an idle one. \"broadcast\" steers every running sibling in your run; \"list\" shows pending decision requests and recent traffic. Cross-run messaging is rejected.",
27
33
  "tools.child.agent_message.snippet": "Message sibling subagents in your run",
@@ -34,15 +40,18 @@ export const PROMPTS = {
34
40
  "tools.child.contact_supervisor.snippet": "Ask the parent agent for a decision or report progress",
35
41
  "tools.child.contact_supervisor.param.reason": "\"need_decision\" blocks until the supervisor (parent agent) replies; \"progress_update\" is fire-and-forget.",
36
42
  "tools.child.contact_supervisor.param.message": "Message for the supervisor.",
37
- "tools.monitor.description": "Start a background monitor process whose stdout lines are injected back to you as <pi-famulus-wake kind=\"monitor\"> messages (batched over 200ms, rate-limited). The command must be line-buffered: each event must be a single line. It must keep running and follow its source, e.g. `tail -n +1 -F file | grep --line-buffered PATTERN`; a command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep to stop after the first match. Silence is not success: print explicit success and terminal failures. Routine unchanged retries may stay silent; do not print a heartbeat on every check. Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll. Repeated Rust-framed lines are suppressed within dedup_window_ms (default 60000); exact matching is the default. Enable ignore-timestamps only when edge ISO timestamps are incidental. Wakes contain bounded head/tail previews and original-byte references; use task_output for missing details, not polling. timeout_ms defaults to 5 minutes (max 1 hour). Expiry ends the monitor; nothing watches the source afterwards, and the timeout notice can arrive late while you are busy. Use persistent:true for long monitoring. If you use timeouts for several monitors, stagger them. Prefer `tail -F` / `journalctl -f` over polling. Write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. {{monitorIdle}}",
43
+ "tools.monitor.description": "Start a background monitor process whose stdout lines are injected back to you as <pi-famulus-wake kind=\"monitor\"> messages (batched over 200ms, rate-limited). The command must be line-buffered: each event must be a single line. It must keep running and follow its source. When you start the producer yourself, make it the command (`node app.js | grep --line-buffered ALERT`); do not start it in bash and tail its output. Use `tail -n +1 -F file | grep --line-buffered PATTERN` or `journalctl -f` for a source you did not start. A command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep only when the first match should end the watch. Silence is not success: print explicit success and terminal failures of what you watch. Routine unchanged retries may stay silent; without wake_on, do not print a heartbeat on every check. The monitor's own exit or timeout is reported to you; do not add end-of-watch lines. Status lines may stay when you set wake_on to the problem pattern: only matching lines wake you, and task_output keeps every line. Use stall_after_ms instead of heartbeats to learn that the source went silent. Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll. Repeated Rust-framed lines are suppressed within dedup_window_ms (default 60000); exact matching is the default. Enable ignore-timestamps only when edge ISO timestamps are incidental. Wakes contain bounded head/tail previews and original-byte references; use task_output for missing details, not polling. A monitor runs until its command exits or you stop it with task_stop: it has no time limit unless you set one. Stop it once you no longer need it. Set timeout_ms (max 1 hour) only when the user asked for a time-bounded watch (\"for the next 10 minutes\"); expiry stops the monitor and the notice can arrive late while you are busy. Do not size a timeout to how long you expect to wait, and do not re-arm monitors. Never set timeout_ms with persistent:true, and never put the lifetime inside the command (`timeout 3600`, your own timer). If you use timeouts for several monitors, stagger them. Without wake_on, write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. {{monitorIdle}}",
38
44
  "tools.monitor.snippet": "Watch a command's line stream and get injected events",
39
- "tools.monitor.rules": ["Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash.","{{monitorIdle}}","When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation.","Use persistent:true for long monitoring."],
45
+ "tools.monitor.rules": ["Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash.","{{monitorIdle}}","When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation. Report from the <event> itself; do not re-read the source, task_output or task_list to confirm it.","A monitor runs until its command exits or you stop it; when you no longer need it, stop it with task_stop. Set timeout_ms only when the user asked for a time limit.","For a monitor that stays up, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."],
40
46
  "tools.monitor.param.command": "Command producing one event per line on stdout. Must be line-buffered (e.g. use `stdbuf -oL` / `grep --line-buffered` where needed).",
41
47
  "tools.monitor.param.description": "Short human-readable description of what is being watched",
42
- "tools.monitor.param.timeout_ms": "Stop the monitor after this many milliseconds (default {{defaultMs}} / 5 minutes, min {{minMs}}, max {{maxMs}} / 1 hour).",
43
- "tools.monitor.param.persistent": "Keep the monitor alive until the session ends (no timeout). Default false. Use persistent:true for long monitoring.",
48
+ "tools.monitor.param.timeout_ms": "Only when the user asked for a time-bounded watch. Stop the monitor after this many milliseconds (min {{minMs}}, max {{maxMs}} / 1 hour). Without it the monitor runs until its command exits or you stop it; persistent:false without it stops after {{defaultMs}} ms. Exclusive with persistent:true.",
49
+ "tools.monitor.param.persistent": "Not needed: a monitor without timeout_ms already runs until its command exits, you stop it, or the session ends. persistent:false applies the 5-minute default. Exclusive with timeout_ms.",
44
50
  "tools.monitor.param.dedup_window_ms": "Deduplication window for Rust-framed complete lines (default 60000ms; 0 disables dedup; maximum 3600000). Starts when a surviving preview is delivered; repeats do not extend it. Missing metadata, capacity eviction, and omitted representatives fail open rather than hiding unseen output.",
51
+ "tools.monitor.param.wake_on": "JavaScript RegExp source tested against each output line. When set, only matching lines wake you (and only they count for dedup and overload); every line is still recorded for task_output. Exit, timeout and stall notices still arrive. Strongly recommended for persistent monitors: match the problem, e.g. `ERROR|unacked=[1-9]`.",
52
+ "tools.monitor.param.stall_after_ms": "Send one notice when the command prints nothing at all (matching wake_on or not) for this many milliseconds while still running (min {{minMs}}, max {{maxMs}}). The next output re-arms it. Use it instead of heartbeat lines.",
45
53
  "tools.monitor.param.fingerprint_mode": "Default exact. Explicit ignore-timestamps mode ignores only supported leading/trailing ISO timestamps when comparing Rust-framed lines; original output is unchanged. Numbers, paths, resource identities, and interior timestamps remain significant.",
54
+ "tools.monitor.event.stalled": "[No output for {{idle}}; the monitor is still running. No further stall notice until output resumes.]",
46
55
  "tools.monitor.result.started": "You will get <pi-famulus-wake kind=\"monitor\"> notifications for admitted output and a notice when it exits or times out. Repeated lines may be suppressed and previews may be truncated; original output remains available through task_output byte ranges while the task log is retained. Read details only when needed; do not repeatedly poll task_list, task_output, or the watched source, and do not sleep to wait. {{monitorIdle}}",
47
56
  "tools.subagent.description": "Run subagents in parallel (tasks) or sequentially (chain with {previous}/{outputs.<label>} interpolation). By default the call waits up to a foreground budget (default 45s); longer runs continue in the background. Each child that finishes while others are still running wakes you with <pi-famulus-wake kind=\"subagent-handover\"> (its prompt and result). The whole run wakes you with <pi-famulus-wake kind=\"subagent-done\">. Never poll or sleep to wait. A subagent still running past its timeout_ms is not stopped; it wakes you with <pi-famulus-wake kind=\"subagent-overrun\"> so you can extend, steer, or interrupt it. Use action=list/get/status/interrupt/resume/steer/extend to manage existing runs.",
48
57
  "tools.subagent.snippet": "Fan out subagents in parallel or sequence them in a chain",
@@ -84,6 +93,8 @@ export const PROMPTS = {
84
93
  "tools.task_stop.description": "Stop a running background task (SIGTERM to the process group, SIGKILL after a 2s grace).",
85
94
  "tools.task_stop.snippet": "Stop a background task",
86
95
  "tools.task_stop.param.task_id": "Task id to stop, e.g. sh_a1b2c3d4",
96
+ "tools.task_stop.result.stopped": "Task {{taskId}} stopped (SIGTERM; SIGKILL after 2s grace if needed).",
97
+ "tools.task_stop.result.already-ended": "Task {{taskId}} had already ended ({{outcome}}); nothing was stopped.",
87
98
  "wakes.lead-in": "System wake — not a new user message. Handle this <pi-famulus-wake> before other work.",
88
99
  "wakes.monitor.output-hint": "Read original bytes with task_output using this monitor id and cursor-start, with a bounded max_bytes (for example 8192); next_cursor continues the read. The range may include interleaved events. A preview is not the full log.",
89
100
  "wakes.running-monitors.guidance": "This is an informational list of monitors still running after compaction, not an event. No response is needed; do not use it to poll.",
@@ -103,6 +114,12 @@ export type PromptId = keyof typeof PROMPTS;
103
114
 
104
115
  /** Placeholder names of each template prompt. */
105
116
  export interface PromptVars {
117
+ "guards.error.idle-turn": "count" | "calls";
118
+ "guards.error.idle-run": "count" | "calls";
119
+ "guards.error.wait-sleep": "what";
120
+ "guards.error.wait-detach": "what";
121
+ "guards.error.poll-output": "id";
122
+ "guards.error.poll-list": "count";
106
123
  "guidelines.parent": "monitorIdle";
107
124
  "tools.agent_message.error.finished-child": "childId" | "name" | "status" | "runId";
108
125
  "tools.bash.description": "maxLines" | "maxKb";
@@ -112,7 +129,9 @@ export interface PromptVars {
112
129
  "tools.child.bash.error.bare-sleep": "command";
113
130
  "tools.monitor.description": "monitorIdle";
114
131
  "tools.monitor.rules": "monitorIdle";
115
- "tools.monitor.param.timeout_ms": "defaultMs" | "minMs" | "maxMs";
132
+ "tools.monitor.param.timeout_ms": "minMs" | "maxMs" | "defaultMs";
133
+ "tools.monitor.param.stall_after_ms": "minMs" | "maxMs";
134
+ "tools.monitor.event.stalled": "idle";
116
135
  "tools.monitor.result.started": "monitorIdle";
117
136
  "tools.subagent.param.model": "thinkingLevels";
118
137
  "tools.subagent.param.timeout_ms": "maxMs";
@@ -122,6 +141,8 @@ export interface PromptVars {
122
141
  "tools.subagent.result.resumed": "name" | "childId" | "runId" | "queued";
123
142
  "tools.subagent.error.resume-queued": "name" | "childId";
124
143
  "tools.task_output.error.no-new-output": "taskId" | "hint";
144
+ "tools.task_stop.result.stopped": "taskId";
145
+ "tools.task_stop.result.already-ended": "taskId" | "outcome";
125
146
  "wakes.overrun.summary": "name" | "elapsed" | "budget" | "shell";
126
147
  "wakes.overrun.summary-shell": "elapsed";
127
148
  "wakes.overrun.actions": "runId" | "childId";
@@ -154,7 +175,7 @@ export function fillList<K extends keyof PromptVars>(id: K, vars: Record<PromptV
154
175
 
155
176
  /** Ablatable spans (eval manifest segment ids). */
156
177
  export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string; pattern?: string }> = {
157
- "guidelines.end-turn-after-bg": {"prompt":"guidelines.parent","text":"Long-running bash commands are automatically moved to the background. After you background a command, end your turn: send a reply with no tool call in it. Saying you will wait while calling another tool does not end it. Do not poll with task_output/task_list, and never sleep to wait. Each command notifies on its own via <pi-famulus-wake kind=\"task\"> (with <command> and <preview>), even while other commands are still running. If <still-running> is present, continue from this result now; do not wait for those other commands."},
178
+ "guidelines.end-turn-after-bg": {"prompt":"guidelines.parent","text":"Long-running bash commands are automatically moved to the background. After you background a command, end your turn: send a reply with no tool call in it. Saying you will wait while calling another tool does not end it. Do not poll with task_output/task_list, and never sleep to wait. Each command notifies on its own via <pi-famulus-wake kind=\"task\"> (with <command> and <preview>) when it exits, even while other commands are still running. A command that keeps running (a server, a watcher) never sends that wake: to act once it is ready, start a monitor for it before you end your turn. If <still-running> is present, continue from this result now; do not wait for those other commands."},
158
179
  "guidelines.wake-handling": {"prompt":"guidelines.parent","text":"When you receive <pi-famulus-wake>: it looks like a user message but is a system wake, not a new user request and not an answer to an unrelated question. Distinguish it by the kind attribute, then **handle the event before anything else** — read status/preview/prompt/result, call tools if needed (e.g. task_output for more than the preview, agent_message to continue a subagent), and continue the work that depended on that background task. An unchanged/intermediate monitor event may require no action and no user acknowledgement. Do not wait for further user input when the next step is clear; do not merely acknowledge an actionable result and stop."},
159
180
  "guidelines.no-fabrication": {"prompt":"guidelines.parent","text":"Never fabricate or assume a background task's result before its notification arrives."},
160
181
  "guidelines.subagent-handover": {"prompt":"guidelines.parent","text":"Subagent runs that exceed the foreground budget continue in the background. Do not poll run status. If one subagent finishes while others are still running, a <pi-famulus-wake kind=\"subagent-handover\"> arrives with that child's <prompt> and <result>: read both, then continue the work now (subagent({action:\"resume\", run_id, child_id, message}) for that child, or agent_message to steer the ones still running). Do not wait for the rest of the run. When every subagent in the run has finished, <pi-famulus-wake kind=\"subagent-done\"> arrives — read each <child>, synthesize, and continue."},
@@ -167,17 +188,20 @@ export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string;
167
188
  "rules.pi-env": {"prompt":"tools.bash.rules","text":"You can inspect PI_* environment variables for current model and session details."},
168
189
  "rules.bash-no-poll": {"prompt":"tools.bash.rules","text":"Long-running bash commands are moved to the background automatically; do not poll or sleep to wait for them."},
169
190
  "result.bash-bg-instruction": {"prompt":"tools.bash.result.backgrounded","text":"\nYou will be notified when it completes, even if other commands are still running. Do not poll or sleep: reply to the user now with no tool call, and continue from the <pi-famulus-wake kind=\"task\"> when it arrives."},
191
+ "result.bash-bg-exit-only": {"prompt":"tools.bash.result.backgrounded","text":" That wake comes only when the command exits. If it keeps running (a server, a watcher) and you need to know when it is ready or prints something, start a monitor for that before you end your turn."},
170
192
  "result.sleep-block-advice": {"prompt":"tools.bash.error.bare-sleep","text":" Do not sleep to wait for background work; completion is delivered via notification. Use the monitor tool to watch for a condition, or run_in_background for long commands."},
171
- "tooldesc.monitor-follow": {"prompt":"tools.monitor.description","text":"It must keep running and follow its source, e.g. `tail -n +1 -F file | grep --line-buffered PATTERN`; a command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep to stop after the first match. "},
172
- "tooldesc.monitor-silence": {"prompt":"tools.monitor.description","text":"Silence is not success: print explicit success and terminal failures. Routine unchanged retries may stay silent; do not print a heartbeat on every check. "},
193
+ "tooldesc.monitor-follow": {"prompt":"tools.monitor.description","text":"It must keep running and follow its source. When you start the producer yourself, make it the command (`node app.js | grep --line-buffered ALERT`); do not start it in bash and tail its output. Use `tail -n +1 -F file | grep --line-buffered PATTERN` or `journalctl -f` for a source you did not start. A command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep only when the first match should end the watch. "},
194
+ "tooldesc.monitor-silence": {"prompt":"tools.monitor.description","text":"Silence is not success: print explicit success and terminal failures of what you watch. Routine unchanged retries may stay silent; without wake_on, do not print a heartbeat on every check. The monitor's own exit or timeout is reported to you; do not add end-of-watch lines. "},
195
+ "tooldesc.monitor-wake-on": {"prompt":"tools.monitor.description","text":"Status lines may stay when you set wake_on to the problem pattern: only matching lines wake you, and task_output keeps every line. Use stall_after_ms instead of heartbeats to learn that the source went silent. "},
173
196
  "tooldesc.monitor-wake": {"prompt":"tools.monitor.description","text":"Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll."},
174
- "tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"timeout_ms defaults to 5 minutes (max 1 hour). Expiry ends the monitor; nothing watches the source afterwards, and the timeout notice can arrive late while you are busy. "},
175
- "tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"Use persistent:true for long monitoring. "},
197
+ "tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"A monitor runs until its command exits or you stop it with task_stop: it has no time limit unless you set one. Stop it once you no longer need it. Set timeout_ms (max 1 hour) only when the user asked for a time-bounded watch (\"for the next 10 minutes\"); expiry stops the monitor and the notice can arrive late while you are busy. "},
198
+ "tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"Do not size a timeout to how long you expect to wait, and do not re-arm monitors. Never set timeout_ms with persistent:true, and never put the lifetime inside the command (`timeout 3600`, your own timer). "},
176
199
  "tooldesc.monitor-stagger": {"prompt":"tools.monitor.description","text":"If you use timeouts for several monitors, stagger them. "},
177
- "tooldesc.monitor-edge": {"prompt":"tools.monitor.description","text":"Write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. "},
200
+ "tooldesc.monitor-edge": {"prompt":"tools.monitor.description","text":"Without wake_on, write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. "},
178
201
  "tooldesc.monitor-sampling": {"prompt":"tools.monitor.description","text":"Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. "},
179
202
  "rules.monitor-use": {"prompt":"tools.monitor.rules","text":"Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash."},
180
- "rules.monitor-wake": {"prompt":"tools.monitor.rules","text":"When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation."},
203
+ "rules.monitor-wake": {"prompt":"tools.monitor.rules","text":"When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation. Report from the <event> itself; do not re-read the source, task_output or task_list to confirm it."},
204
+ "rules.monitor-wake-on": {"prompt":"tools.monitor.rules","text":"For a monitor that stays up, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."},
181
205
  "result.monitor-started-instruction": {"prompt":"tools.monitor.result.started","text":"You will get <pi-famulus-wake kind=\"monitor\"> notifications for admitted output and a notice when it exits or times out. Repeated lines may be suppressed and previews may be truncated; original output remains available through task_output byte ranges while the task log is retained. Read details only when needed; do not repeatedly poll task_list, task_output, or the watched source, and do not sleep to wait."},
182
206
  "tooldesc.subagent-wakes": {"prompt":"tools.subagent.description","text":"Each child that finishes while others are still running wakes you with <pi-famulus-wake kind=\"subagent-handover\"> (its prompt and result). The whole run wakes you with <pi-famulus-wake kind=\"subagent-done\">. Never poll or sleep to wait. "},
183
207
  "tooldesc.subagent-overrun": {"prompt":"tools.subagent.description","text":"A subagent still running past its timeout_ms is not stopped; it wakes you with <pi-famulus-wake kind=\"subagent-overrun\"> so you can extend, steer, or interrupt it. "},
package/src/task-tools.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import { Type } from "typebox";
5
5
  import { realClock, type Clock } from "./clock";
6
6
  import type { ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
7
- import type { ManagerClient, TaskRecord } from "./manager-client";
7
+ import type { ManagerClient, StopResult, TaskRecord } from "./manager-client";
8
8
  import { fnv1a64 } from "./config";
9
9
  import { fill, PROMPTS } from "./prompts.generated";
10
10
  import {
@@ -30,7 +30,7 @@ export interface TaskToolsDeps {
30
30
  /** task_stop on a monitor: its leftover lines and exit should not wake the model. */
31
31
  noteStopRequested?: (taskId: string) => (() => void) | void;
32
32
  /** Live monitor remaining timeout and last output, from the in-session registry. */
33
- getMonitorLive?: () => Iterable<{ taskId: string; remainingMs: number | null; persistent: boolean; lastOutputAt?: number }>;
33
+ getMonitorLive?: () => Iterable<MonitorLive>;
34
34
  }
35
35
 
36
36
  function requireClient(deps: TaskToolsDeps): Promise<ManagerClient> {
@@ -73,14 +73,22 @@ function formatDuration(startedAt: number, endedAt: number | null, now: number):
73
73
  return `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000)}s`;
74
74
  }
75
75
 
76
- function formatMonitorLive(
77
- live: { remainingMs: number | null; persistent: boolean; lastOutputAt?: number },
78
- now: number,
79
- ): string {
76
+ interface MonitorLive {
77
+ taskId: string;
78
+ remainingMs: number | null;
79
+ persistent: boolean;
80
+ lastOutputAt?: number;
81
+ wakeOn?: string;
82
+ stallAfterMs?: number;
83
+ }
84
+
85
+ function formatMonitorLive(live: MonitorLive, now: number): string {
80
86
  const timeout = live.persistent ? "persistent" : `timeout in ${formatAge(now, now + (live.remainingMs ?? 0), now)}`;
81
87
  const last =
82
88
  live.lastOutputAt === undefined ? "no output yet" : `last output ${formatAge(live.lastOutputAt, undefined, now)} ago`;
83
- return ` ${timeout}; ${last}`;
89
+ const filter = live.wakeOn === undefined ? "" : `; wakes only on /${live.wakeOn}/`;
90
+ const stall = live.stallAfterMs === undefined ? "" : `; stall notice after ${formatAge(now, now + live.stallAfterMs, now)}`;
91
+ return ` ${timeout}; ${last}${filter}${stall}`;
84
92
  }
85
93
 
86
94
  function formatTaskLine(task: TaskRecord, now: number): string {
@@ -126,7 +134,7 @@ export function createTaskListTool(
126
134
  const lines: string[] = [];
127
135
  const seen = new Set<string>();
128
136
  let running = false;
129
- const monitorLive = new Map<string, { remainingMs: number | null; persistent: boolean; lastOutputAt?: number }>();
137
+ const monitorLive = new Map<string, MonitorLive>();
130
138
  for (const live of deps.getMonitorLive?.() ?? []) monitorLive.set(live.taskId, live);
131
139
 
132
140
  const pushItem = (item: WorkItem) => {
@@ -312,6 +320,12 @@ const taskStopParameters = Type.Object({
312
320
  task_id: Type.String({ description: PROMPTS["tools.task_stop.param.task_id"] }),
313
321
  });
314
322
 
323
+ function endedOutcome(ended: NonNullable<StopResult["alreadyEnded"]>): string {
324
+ if (ended.signal) return `${ended.status}, killed by ${ended.signal}`;
325
+ if (ended.exitCode !== null) return `${ended.status}, exit code ${ended.exitCode}`;
326
+ return ended.status;
327
+ }
328
+
315
329
  export function createTaskStopTool(
316
330
  deps: TaskToolsDeps,
317
331
  ): ToolDefinition<typeof taskStopParameters, { task_id: string; stopped: boolean }> {
@@ -335,8 +349,9 @@ export function createTaskStopTool(
335
349
  }
336
350
  const client = await requireClient(deps);
337
351
  const undoNote = deps.noteStopRequested?.(params.task_id);
352
+ let result: StopResult | undefined;
338
353
  try {
339
- await client.stop(params.task_id, "tool");
354
+ result = await client.stop(params.task_id, "tool");
340
355
  } catch (err) {
341
356
  undoNote?.();
342
357
  throw err;
@@ -344,13 +359,17 @@ export function createTaskStopTool(
344
359
  // Stopping a task that already ended emits no new exit event.
345
360
  await deps.syncWithManager?.();
346
361
  }
362
+ const ended = result?.alreadyEnded;
363
+ if (ended) {
364
+ // Nothing was stopped, so its exit is not a stop the model asked for.
365
+ undoNote?.();
366
+ return {
367
+ content: [{ type: "text", text: fill("tools.task_stop.result.already-ended", { taskId: params.task_id, outcome: endedOutcome(ended) }) }],
368
+ details: { task_id: params.task_id, stopped: false },
369
+ };
370
+ }
347
371
  return {
348
- content: [
349
- {
350
- type: "text",
351
- text: `Task ${params.task_id} stopped (SIGTERM; SIGKILL after 2s grace if needed).`,
352
- },
353
- ],
372
+ content: [{ type: "text", text: fill("tools.task_stop.result.stopped", { taskId: params.task_id }) }],
354
373
  details: { task_id: params.task_id, stopped: true },
355
374
  };
356
375
  },
@@ -119,14 +119,14 @@ function collapsedText(details: FamulusWake, theme: Theme): string {
119
119
  return `${theme.fg("muted", "↑")} ${theme.fg("muted", "supervisor update")} ${details.message.slice(0, 100)}`;
120
120
  case "monitor-session-end": {
121
121
  const n = details.ids.length || details.monitors.length;
122
- return `${theme.fg("warning", "✗")} ${theme.fg("muted", "session monitors")} ${n} stopped · ${details.reason}`;
122
+ return `${theme.fg("warning", "✗")} ${theme.fg("muted", "session monitors")} ${n} teardown · ${details.reason}`;
123
123
  }
124
124
  case "running-monitors":
125
125
  return `${theme.fg("accent", "›")} ${theme.fg("muted", "running")} ${details.monitors.length} monitor${details.monitors.length === 1 ? "" : "s"}`;
126
126
  case "monitor-terminal": {
127
127
  const n = details.ids.length || details.monitors.length;
128
128
  const statuses = countStatuses(details.monitors.map((monitor) => monitor.status));
129
- return `${theme.fg("warning", "✗")} ${theme.fg("muted", "monitors")} ${n} stopped · ${statuses}`;
129
+ return `${theme.fg("warning", "✗")} ${theme.fg("muted", "monitors")} ${n} lifecycle updates · ${statuses}`;
130
130
  }
131
131
  }
132
132
  }
@@ -208,7 +208,7 @@ export function expandedWakeText(details: FamulusWake | undefined, content: stri
208
208
  return [`Update from ${details.name} (${details.from})`, details.message].join("\n");
209
209
  case "monitor-session-end":
210
210
  return [
211
- `Session monitors stopped (${details.reason}). They are no longer watched.`,
211
+ `Session monitor teardown (${details.reason}); process exits are not confirmed by this notice.`,
212
212
  ...details.monitors.map((monitor) =>
213
213
  `${monitor.id} "${monitor.description}" elapsed ${formatDuration(monitor.elapsedMs)}; original output: task_output({task_id: "${monitor.id}"}) ${monitor.outputPath} while the log is retained`,
214
214
  ),
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Wait guard: blocks bash commands that wait instead of watching.
3
+ *
4
+ * In the 2026-11-07 log-monitor session (deepseek-flash) the agent waited in
5
+ * bash 76 times (`sleep 45; check`, `while …; do sleep 5; done`) and started
6
+ * its producers with `(./run.sh > out 2>&1 &)`, then checked on them with
7
+ * `ps`. The monitor description and rules already said not to; a replay of
8
+ * that session at ten decision points (eval/replay) showed that rewording
9
+ * them did not change the choice. The harness has to refuse it.
10
+ *
11
+ * Two shapes are blocked, with a reason that names the alternative:
12
+ * wait `sleep N` with N >= WAIT_SLEEP_MIN_S, or any while/until/for loop
13
+ * that sleeps: use a persistent monitor, or end the turn.
14
+ * detach a lone `&`, nohup, setsid or disown: run the producer as the
15
+ * monitor command, or in the foreground (pi backgrounds it).
16
+ * Quoted strings, heredoc bodies and comments are ignored, so a sleep or `&`
17
+ * inside `ansible -a '…'`, a Python heredoc or a URL does not count.
18
+ */
19
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
20
+ import { fill } from "./prompts.generated.ts";
21
+
22
+ /** Shorter sleeps settle a restart; longer ones wait for something. */
23
+ export const WAIT_SLEEP_MIN_S = 10;
24
+
25
+ export type WaitShape = { kind: "wait"; what: string } | { kind: "detach"; what: string };
26
+
27
+ /** Remove what the local shell does not execute as words: heredoc bodies, quotes, comments. */
28
+ export function shellWords(command: string): string {
29
+ let s = command.replace(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?=\n|$)/g, "<<heredoc");
30
+ s = s.replace(/'[^']*'/g, "''").replace(/"(?:\\.|[^"\\])*"/g, '""');
31
+ s = s.replace(/(^|\s)#[^\n]*/g, "$1");
32
+ return s;
33
+ }
34
+
35
+ const SLEEP = /\bsleep\s+(\d+(?:\.\d+)?)/g;
36
+ // A sleep inside a loop body (between `do` and its `done`), not one after the loop.
37
+ const SLEEP_LOOP = /\b(while|until|for)\b[\s\S]*?\bdo\b(?:(?!\bdone\b)[\s\S])*\bsleep\b/;
38
+ const DETACH = /(^|[^&>|])&(?![&>])|\b(nohup|setsid|disown)\b/m;
39
+
40
+ export function waitShape(command: string): WaitShape | null {
41
+ const words = shellWords(command);
42
+ if (SLEEP_LOOP.test(words)) return { kind: "wait", what: "a loop that sleeps" };
43
+ for (const m of words.matchAll(SLEEP)) {
44
+ if (Number(m[1]) >= WAIT_SLEEP_MIN_S) return { kind: "wait", what: `sleep ${m[1]}` };
45
+ }
46
+ const d = DETACH.exec(words);
47
+ if (d) return { kind: "detach", what: d[2] ?? "&" };
48
+ return null;
49
+ }
50
+
51
+ export interface WaitGuardOptions {
52
+ enabled: boolean;
53
+ onBlock?: (info: { kind: WaitShape["kind"]; what: string }) => void;
54
+ }
55
+
56
+ export function installWaitGuard(pi: Pick<ExtensionAPI, "on">, opts: WaitGuardOptions): void {
57
+ if (!opts.enabled) return;
58
+ pi.on("tool_call", async (event) => {
59
+ if (event.toolName !== "bash") return;
60
+ const command = (event.input as { command?: unknown } | null)?.command;
61
+ if (typeof command !== "string") return;
62
+ const shape = waitShape(command);
63
+ if (!shape) return;
64
+ opts.onBlock?.({ kind: shape.kind, what: shape.what });
65
+ const reason = fill(shape.kind === "wait" ? "guards.error.wait-sleep" : "guards.error.wait-detach", { what: shape.what });
66
+ return { block: true, reason };
67
+ });
68
+ }
package/src/wake.ts CHANGED
@@ -30,6 +30,7 @@ export interface TaskWake {
30
30
  exitCode: number | null;
31
31
  /** Signal name ("SIGTERM" | "SIGKILL"). Omitted when the exit had no signal. */
32
32
  signal?: string;
33
+ endReason?: string;
33
34
  }
34
35
 
35
36
  export type WakeChildStatus = "pending" | "running" | "completed" | "failed" | "interrupted";
@@ -105,6 +106,13 @@ export interface MonitorOutputInfo {
105
106
  omittedChars?: number;
106
107
  }
107
108
 
109
+ export interface MonitorExitFacts {
110
+ endReason?: string;
111
+ signal?: string;
112
+ exitCode?: number | null;
113
+ stopRequested?: boolean;
114
+ }
115
+
108
116
  export type FamulusWake = FamulusWakeBody & WakeTiming;
109
117
 
110
118
  type FamulusWakeBody =
@@ -118,6 +126,8 @@ type FamulusWakeBody =
118
126
  eventCount?: number;
119
127
  droppedLines?: number;
120
128
  output?: MonitorOutputInfo;
129
+ exitFacts?: MonitorExitFacts;
130
+ exitContext?: string;
121
131
  }
122
132
  | {
123
133
  kind: "subagent-handover";
@@ -175,7 +185,7 @@ type FamulusWakeBody =
175
185
  }
176
186
  | {
177
187
  kind: "running-monitors";
178
- monitors: { id: string; description: string; remaining: string }[];
188
+ monitors: { id: string; description: string; remaining: string; wakeOn?: string }[];
179
189
  }
180
190
  | {
181
191
  kind: "monitor-terminal";
@@ -188,6 +198,7 @@ type FamulusWakeBody =
188
198
  detail: string;
189
199
  droppedLines?: number;
190
200
  output?: MonitorOutputInfo;
201
+ exitFacts?: MonitorExitFacts;
191
202
  }>;
192
203
  };
193
204
 
@@ -546,7 +557,7 @@ function renderRunningMonitors(details: Extract<FamulusWake, { kind: "running-mo
546
557
  ];
547
558
  for (const monitor of details.monitors) {
548
559
  parts.push(
549
- ` <monitor id="${escapeXmlAttr(monitor.id)}" remaining="${escapeXmlAttr(monitor.remaining)}">${escapeXml(monitor.description)}</monitor>`,
560
+ ` <monitor id="${escapeXmlAttr(monitor.id)}" remaining="${escapeXmlAttr(monitor.remaining)}"${monitor.wakeOn ? ` wake-on="${escapeXmlAttr(monitor.wakeOn)}"` : ""}>${escapeXml(monitor.description)}</monitor>`,
550
561
  );
551
562
  }
552
563
  parts.push("</pi-famulus-wake>");
@@ -592,7 +603,7 @@ function renderMonitorTerminal(details: Extract<FamulusWake, { kind: "monitor-te
592
603
  function renderMonitorSessionEnd(details: Extract<FamulusWake, { kind: "monitor-session-end" }>): string {
593
604
  const parts = [
594
605
  `<pi-famulus-wake kind="monitor-session-end" reason="${escapeXmlAttr(details.reason)}">`,
595
- ` <summary>${escapeXml(`These monitors stopped (${details.reason}). They are no longer watched.`)}</summary>`,
606
+ ` <summary>${escapeXml(`Session monitor teardown (${details.reason}); process exits are not confirmed by this notice.`)}</summary>`,
596
607
  ];
597
608
  for (const monitor of details.monitors) {
598
609
  const pointer = `task_output({task_id: "${monitor.id}"}) ${monitor.outputPath} while the log is retained`;