pi-famulus 0.2.2 → 0.2.4

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,6 +5,8 @@ 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
+ "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.",
8
10
  "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.",
9
11
  "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
12
  "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.",
@@ -17,7 +19,7 @@ export const PROMPTS = {
17
19
  "tools.agent_message.error.finished-child": "Child {{childId}} ({{name}}) has finished ({{status}}), and this host cannot start another turn. Use subagent({ action: \"resume\", run_id: \"{{runId}}\", child_id: \"{{childId}}\", message: \"...\" }).",
18
20
  "tools.bash.description": "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last {{maxLines}} lines or {{maxKb}}KB (whichever is hit first). Foreground commands that exceed the foreground budget are automatically moved to the background; you will be notified when they complete. Optionally provide a timeout in seconds (hard kill limit), or run_in_background to background immediately.",
19
21
  "tools.bash.snippet": "Execute bash commands (ls, grep, find, etc.)",
20
- "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."],
22
+ "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
23
  "tools.bash.param.command": "The bash command to execute",
22
24
  "tools.bash.param.timeout": "Hard kill timeout in seconds (optional, no default timeout)",
23
25
  "tools.bash.param.run_in_background": "Start the command in the background and return immediately. You will be notified when it completes.",
@@ -34,15 +36,18 @@ export const PROMPTS = {
34
36
  "tools.child.contact_supervisor.snippet": "Ask the parent agent for a decision or report progress",
35
37
  "tools.child.contact_supervisor.param.reason": "\"need_decision\" blocks until the supervisor (parent agent) replies; \"progress_update\" is fire-and-forget.",
36
38
  "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. {{monitorIdle}}",
39
+ "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. Pick one lifetime. timeout_ms (default 5 minutes, max 1 hour) is for a watch that ends at a known time within an hour; expiry stops the monitor and the notice can arrive late while you are busy. Use persistent:true when the watch is open-ended or longer than an hour (\"rest of the day\", \"until I say\"); do not re-arm timed monitors instead. Never set both, 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
40
  "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."],
41
+ "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.","For a watch that is open-ended or longer than an hour, use persistent:true rather than timeout_ms.","For a persistent monitor, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."],
40
42
  "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
43
  "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}}, min {{minMs}}, max {{maxMs}})",
43
- "tools.monitor.param.persistent": "Keep the monitor alive until the session ends (no timeout). Default false.",
44
+ "tools.monitor.param.timeout_ms": "Stop the monitor after this many milliseconds (default {{defaultMs}} / 5 minutes, min {{minMs}}, max {{maxMs}} / 1 hour). Exclusive with persistent; for longer watches use persistent:true instead of re-arming.",
45
+ "tools.monitor.param.persistent": "No timeout: runs until stopped or the session ends. Default false. Use for open-ended watches or any horizon over 1 hour. Exclusive with timeout_ms.",
44
46
  "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.",
47
+ "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]`.",
48
+ "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
49
  "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.",
50
+ "tools.monitor.event.stalled": "[No output for {{idle}}; the monitor is still running. No further stall notice until output resumes.]",
46
51
  "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
52
  "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
53
  "tools.subagent.snippet": "Fan out subagents in parallel or sequence them in a chain",
@@ -84,8 +89,11 @@ export const PROMPTS = {
84
89
  "tools.task_stop.description": "Stop a running background task (SIGTERM to the process group, SIGKILL after a 2s grace).",
85
90
  "tools.task_stop.snippet": "Stop a background task",
86
91
  "tools.task_stop.param.task_id": "Task id to stop, e.g. sh_a1b2c3d4",
92
+ "tools.task_stop.result.stopped": "Task {{taskId}} stopped (SIGTERM; SIGKILL after 2s grace if needed).",
93
+ "tools.task_stop.result.already-ended": "Task {{taskId}} had already ended ({{outcome}}); nothing was stopped.",
87
94
  "wakes.lead-in": "System wake — not a new user message. Handle this <pi-famulus-wake> before other work.",
88
95
  "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.",
96
+ "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.",
89
97
  "wakes.handover.changed-active": "Its result arrives as a new wake when it finishes.",
90
98
  "wakes.done.changed-active": "The run is active again; another subagent-done arrives when it finishes.",
91
99
  "wakes.overrun.summary": "{{name}} has run {{elapsed}} in this turn, past its {{budget}} budget, and is still running{{shell}}.",
@@ -102,6 +110,8 @@ export type PromptId = keyof typeof PROMPTS;
102
110
 
103
111
  /** Placeholder names of each template prompt. */
104
112
  export interface PromptVars {
113
+ "guards.error.idle-turn": "count" | "calls";
114
+ "guards.error.idle-run": "count" | "calls";
105
115
  "guidelines.parent": "monitorIdle";
106
116
  "tools.agent_message.error.finished-child": "childId" | "name" | "status" | "runId";
107
117
  "tools.bash.description": "maxLines" | "maxKb";
@@ -112,6 +122,8 @@ export interface PromptVars {
112
122
  "tools.monitor.description": "monitorIdle";
113
123
  "tools.monitor.rules": "monitorIdle";
114
124
  "tools.monitor.param.timeout_ms": "defaultMs" | "minMs" | "maxMs";
125
+ "tools.monitor.param.stall_after_ms": "minMs" | "maxMs";
126
+ "tools.monitor.event.stalled": "idle";
115
127
  "tools.monitor.result.started": "monitorIdle";
116
128
  "tools.subagent.param.model": "thinkingLevels";
117
129
  "tools.subagent.param.timeout_ms": "maxMs";
@@ -121,6 +133,8 @@ export interface PromptVars {
121
133
  "tools.subagent.result.resumed": "name" | "childId" | "runId" | "queued";
122
134
  "tools.subagent.error.resume-queued": "name" | "childId";
123
135
  "tools.task_output.error.no-new-output": "taskId" | "hint";
136
+ "tools.task_stop.result.stopped": "taskId";
137
+ "tools.task_stop.result.already-ended": "taskId" | "outcome";
124
138
  "wakes.overrun.summary": "name" | "elapsed" | "budget" | "shell";
125
139
  "wakes.overrun.summary-shell": "elapsed";
126
140
  "wakes.overrun.actions": "runId" | "childId";
@@ -167,11 +181,18 @@ export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string;
167
181
  "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."},
168
182
  "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."},
169
183
  "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."},
170
- "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. "},
171
- "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. "},
184
+ "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. "},
185
+ "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. "},
186
+ "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. "},
172
187
  "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."},
188
+ "tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"Pick one lifetime. timeout_ms (default 5 minutes, max 1 hour) is for a watch that ends at a known time within an hour; expiry stops the monitor and the notice can arrive late while you are busy. "},
189
+ "tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"Use persistent:true when the watch is open-ended or longer than an hour (\"rest of the day\", \"until I say\"); do not re-arm timed monitors instead. Never set both, and never put the lifetime inside the command (`timeout 3600`, your own timer). "},
190
+ "tooldesc.monitor-stagger": {"prompt":"tools.monitor.description","text":"If you use timeouts for several monitors, stagger them. "},
191
+ "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. "},
192
+ "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. "},
173
193
  "rules.monitor-use": {"prompt":"tools.monitor.rules","text":"Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash."},
174
- "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."},
194
+ "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."},
195
+ "rules.monitor-wake-on": {"prompt":"tools.monitor.rules","text":"For a persistent monitor, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."},
175
196
  "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."},
176
197
  "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. "},
177
198
  "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 {
@@ -29,6 +29,8 @@ export interface TaskToolsDeps {
29
29
  syncWithManager?: () => Promise<unknown>;
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
+ /** Live monitor remaining timeout and last output, from the in-session registry. */
33
+ getMonitorLive?: () => Iterable<MonitorLive>;
32
34
  }
33
35
 
34
36
  function requireClient(deps: TaskToolsDeps): Promise<ManagerClient> {
@@ -71,6 +73,24 @@ function formatDuration(startedAt: number, endedAt: number | null, now: number):
71
73
  return `${Math.floor(ms / 60_000)}m${Math.round((ms % 60_000) / 1000)}s`;
72
74
  }
73
75
 
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 {
86
+ const timeout = live.persistent ? "persistent" : `timeout in ${formatAge(now, now + (live.remainingMs ?? 0), now)}`;
87
+ const last =
88
+ live.lastOutputAt === undefined ? "no output yet" : `last output ${formatAge(live.lastOutputAt, undefined, now)} ago`;
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}`;
92
+ }
93
+
74
94
  function formatTaskLine(task: TaskRecord, now: number): string {
75
95
  const exit =
76
96
  task.status === "running"
@@ -114,6 +134,8 @@ export function createTaskListTool(
114
134
  const lines: string[] = [];
115
135
  const seen = new Set<string>();
116
136
  let running = false;
137
+ const monitorLive = new Map<string, MonitorLive>();
138
+ for (const live of deps.getMonitorLive?.() ?? []) monitorLive.set(live.taskId, live);
117
139
 
118
140
  const pushItem = (item: WorkItem) => {
119
141
  if (seen.has(item.id)) return;
@@ -121,7 +143,12 @@ export function createTaskListTool(
121
143
  seen.add(item.id);
122
144
  const age = formatAge(item.startedAt, item.endedAt, now);
123
145
  running ||= item.status === "running" || item.status === "pending";
124
- lines.push(`${item.id} [${item.kind}] ${item.status} (${age}) "${item.title}"`);
146
+ let line = `${item.id} [${item.kind}] ${item.status} (${age}) "${item.title}"`;
147
+ if (item.kind === "monitor") {
148
+ const live = monitorLive.get(item.id);
149
+ if (live) line += formatMonitorLive(live, now);
150
+ }
151
+ lines.push(line);
125
152
  };
126
153
 
127
154
  if (index) {
@@ -293,6 +320,12 @@ const taskStopParameters = Type.Object({
293
320
  task_id: Type.String({ description: PROMPTS["tools.task_stop.param.task_id"] }),
294
321
  });
295
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
+
296
329
  export function createTaskStopTool(
297
330
  deps: TaskToolsDeps,
298
331
  ): ToolDefinition<typeof taskStopParameters, { task_id: string; stopped: boolean }> {
@@ -316,8 +349,9 @@ export function createTaskStopTool(
316
349
  }
317
350
  const client = await requireClient(deps);
318
351
  const undoNote = deps.noteStopRequested?.(params.task_id);
352
+ let result: StopResult | undefined;
319
353
  try {
320
- await client.stop(params.task_id, "tool");
354
+ result = await client.stop(params.task_id, "tool");
321
355
  } catch (err) {
322
356
  undoNote?.();
323
357
  throw err;
@@ -325,13 +359,17 @@ export function createTaskStopTool(
325
359
  // Stopping a task that already ended emits no new exit event.
326
360
  await deps.syncWithManager?.();
327
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
+ }
328
371
  return {
329
- content: [
330
- {
331
- type: "text",
332
- text: `Task ${params.task_id} stopped (SIGTERM; SIGKILL after 2s grace if needed).`,
333
- },
334
- ],
372
+ content: [{ type: "text", text: fill("tools.task_stop.result.stopped", { taskId: params.task_id }) }],
335
373
  details: { task_id: params.task_id, stopped: true },
336
374
  };
337
375
  },
@@ -7,7 +7,7 @@ import { dirname } from "node:path";
7
7
  import { stripVTControlCharacters } from "node:util";
8
8
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
9
9
  import { ManagerError, type ManagerClient, type MessagingStatus } from "../manager-client";
10
- import { SETTINGS_SECTIONS, listTheme, readConfigText, sectionPage, writeConfigText } from "./famulus-settings";
10
+ import { SETTINGS_SECTIONS, listTheme, sectionPage } from "./famulus-settings";
11
11
  import { loadPiTui, truncateToWidth, wrapTextWithAnsi } from "./pi-tui-load";
12
12
 
13
13
  export interface FamulusCommandDeps {
@@ -52,7 +52,7 @@ export function formatMessaging(info: FamulusInfo): string {
52
52
  const m = info.messaging;
53
53
  if (!m) return info.daemon ? "not reported by this manager" : "unknown (manager not connected)";
54
54
  const state = RELAY_STATES[m.state] ?? "unavailable";
55
- let label = m.name && RELAY_STATES[m.state] ? `${state} · name ${singleLine(m.name)}` : state;
55
+ let label = m.name && RELAY_STATES[m.state] ? `${state} · ${singleLine(m.name)}` : state;
56
56
  if (m.state === "disconnected" && typeof m.retry_at_ms === "number") {
57
57
  const seconds = Math.ceil((m.retry_at_ms - Date.now()) / 1000);
58
58
  label += seconds > 0 ? ` · retry in ${seconds}s` : " · retrying";
@@ -145,7 +145,7 @@ export async function collectFamulusInfo(deps: FamulusCommandDeps): Promise<Famu
145
145
  };
146
146
  }
147
147
 
148
- type OverviewChoice = "edit-raw" | "reload" | "reconnect" | undefined;
148
+ type OverviewChoice = "reload" | "reconnect" | undefined;
149
149
 
150
150
  /** Whether "Reconnect messaging now" makes sense for what the manager reported. */
151
151
  const canReconnect = (m: MessagingStatus | null) => m?.state === "disconnected" || m?.state === "unavailable";
@@ -206,13 +206,6 @@ function showOverview(
206
206
  currentValue: "",
207
207
  values: [""],
208
208
  }] : []),
209
- {
210
- id: "edit-raw",
211
- label: "Edit config.json",
212
- description: "The whole file in the editor, for webhook endpoints and anything not listed",
213
- currentValue: "",
214
- values: [""],
215
- },
216
209
  { id: "reload", label: "Reload extension", description: "Apply extension settings now", currentValue: "", values: [""] },
217
210
  ];
218
211
  const list = new piTui.SettingsList(
@@ -220,7 +213,7 @@ function showOverview(
220
213
  10,
221
214
  listTheme(theme),
222
215
  (id) => {
223
- if (id === "edit-raw" || id === "reload" || id === "reconnect") done(id);
216
+ if (id === "reload" || id === "reconnect") done(id);
224
217
  },
225
218
  () => done(undefined),
226
219
  );
@@ -272,25 +265,7 @@ export function registerFamulusCommand(pi: ExtensionAPI, deps: FamulusCommandDep
272
265
  await ctx.reload();
273
266
  return;
274
267
  }
275
- if (action !== "edit-raw") return;
276
- let current: string;
277
- try {
278
- current = readConfigText(deps.configPath);
279
- } catch (error) {
280
- ctx.ui.notify(`Cannot read ${deps.configPath}: ${(error as Error).message}`, "error");
281
- continue;
282
- }
283
- const edited = await ctx.ui.editor(`Edit ${deps.configPath}`, current);
284
- if (edited === undefined) continue;
285
- try {
286
- writeConfigText(deps.configPath, edited);
287
- ctx.ui.notify(
288
- `Saved ${deps.configPath}. Reload the extension for extension settings; restart the manager daemon for messaging settings.`,
289
- "info",
290
- );
291
- } catch (error) {
292
- ctx.ui.notify(`Configuration was not saved: ${(error as Error).message}`, "error");
293
- }
268
+ return;
294
269
  }
295
270
  },
296
271
  });
@@ -117,6 +117,17 @@ function collapsedText(details: FamulusWake, theme: Theme): string {
117
117
  ].join("\n");
118
118
  case "supervisor-update":
119
119
  return `${theme.fg("muted", "↑")} ${theme.fg("muted", "supervisor update")} ${details.message.slice(0, 100)}`;
120
+ case "monitor-session-end": {
121
+ const n = details.ids.length || details.monitors.length;
122
+ return `${theme.fg("warning", "✗")} ${theme.fg("muted", "session monitors")} ${n} teardown · ${details.reason}`;
123
+ }
124
+ case "running-monitors":
125
+ return `${theme.fg("accent", "›")} ${theme.fg("muted", "running")} ${details.monitors.length} monitor${details.monitors.length === 1 ? "" : "s"}`;
126
+ case "monitor-terminal": {
127
+ const n = details.ids.length || details.monitors.length;
128
+ const statuses = countStatuses(details.monitors.map((monitor) => monitor.status));
129
+ return `${theme.fg("warning", "✗")} ${theme.fg("muted", "monitors")} ${n} lifecycle updates · ${statuses}`;
130
+ }
120
131
  }
121
132
  }
122
133
 
@@ -195,6 +206,25 @@ export function expandedWakeText(details: FamulusWake | undefined, content: stri
195
206
  return [`Decision requested by ${details.name} (${details.from})`, `Request: ${details.message}`, `Reply with /reply ${details.from} <decision>`].join("\n");
196
207
  case "supervisor-update":
197
208
  return [`Update from ${details.name} (${details.from})`, details.message].join("\n");
209
+ case "monitor-session-end":
210
+ return [
211
+ `Session monitor teardown (${details.reason}); process exits are not confirmed by this notice.`,
212
+ ...details.monitors.map((monitor) =>
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
+ ),
215
+ ].join("\n");
216
+ case "running-monitors":
217
+ return [
218
+ `Still running after compaction (${details.monitors.length})`,
219
+ ...details.monitors.map((monitor) => `${monitor.id} — ${monitor.description} — ${monitor.remaining}`),
220
+ ].join("\n");
221
+ case "monitor-terminal":
222
+ return [
223
+ details.summary,
224
+ ...details.monitors.map((monitor) =>
225
+ `${monitor.id} "${monitor.description}" · ${monitor.status}${monitor.detail ? `: ${monitor.detail}` : ""}`,
226
+ ),
227
+ ].join("\n");
198
228
  }
199
229
  }
200
230
 
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";
@@ -166,7 +176,31 @@ type FamulusWakeBody =
166
176
  additional?: SubagentOverrunChild[];
167
177
  }
168
178
  | { kind: "supervisor-request"; from: string; name: string; message: string }
169
- | { kind: "supervisor-update"; from: string; name: string; message: string };
179
+ | { kind: "supervisor-update"; from: string; name: string; message: string }
180
+ | {
181
+ kind: "monitor-session-end";
182
+ reason: "new" | "resumed" | "forked" | "handoff-ended" | "session-mismatch";
183
+ ids: string[];
184
+ monitors: Array<{ id: string; description: string; elapsedMs: number; outputPath: string }>;
185
+ }
186
+ | {
187
+ kind: "running-monitors";
188
+ monitors: { id: string; description: string; remaining: string; wakeOn?: string }[];
189
+ }
190
+ | {
191
+ kind: "monitor-terminal";
192
+ ids: string[];
193
+ summary: string;
194
+ monitors: Array<{
195
+ id: string;
196
+ description: string;
197
+ status: "timeout" | "exited" | "stopped";
198
+ detail: string;
199
+ droppedLines?: number;
200
+ output?: MonitorOutputInfo;
201
+ exitFacts?: MonitorExitFacts;
202
+ }>;
203
+ };
170
204
 
171
205
  export interface FormattedWake {
172
206
  customType: typeof FAMULUS_WAKE_CUSTOM_TYPE;
@@ -207,8 +241,16 @@ export function wakeIds(details: { kind?: string }): string[] {
207
241
  from?: string;
208
242
  };
209
243
  if (d.kind === "task") return (d.tasks ?? []).map((task) => task.id);
244
+ if (d.kind === "running-monitors") {
245
+ return ((details as { monitors?: { id: string }[] }).monitors ?? []).map((monitor) => monitor.id);
246
+ }
210
247
  if (d.kind === "subagent-done") return (d.children ?? []).map((child) => child.childId);
211
248
  if (d.kind === "subagent-overrun") return [d.childId, ...((d as { additional?: { childId: string }[] }).additional ?? []).map((child) => child.childId)].filter((id): id is string => Boolean(id));
249
+ if (d.kind === "monitor-session-end" || d.kind === "monitor-terminal") {
250
+ const ids = (d as { ids?: string[] }).ids;
251
+ if (ids && ids.length > 0) return ids;
252
+ return ((d as { monitors?: { id: string }[] }).monitors ?? []).map((monitor) => monitor.id);
253
+ }
212
254
  return [d.id ?? d.taskId ?? d.childId ?? d.from].filter((id): id is string => Boolean(id));
213
255
  }
214
256
 
@@ -284,6 +326,12 @@ function renderWakeBody(details: FamulusWake): string {
284
326
  return renderRequest(details);
285
327
  case "supervisor-update":
286
328
  return renderUpdate(details);
329
+ case "monitor-session-end":
330
+ return renderMonitorSessionEnd(details);
331
+ case "running-monitors":
332
+ return renderRunningMonitors(details);
333
+ case "monitor-terminal":
334
+ return renderMonitorTerminal(details);
287
335
  }
288
336
  }
289
337
 
@@ -317,6 +365,19 @@ function renderTask(details: Extract<FamulusWake, { kind: "task" }>): string {
317
365
  return parts.join("\n");
318
366
  }
319
367
 
368
+ function renderMonitorOutputElement(output: MonitorOutputInfo | undefined, indent: string): string | undefined {
369
+ if (output?.cursorStart === undefined) return undefined;
370
+ const fields: string[] = [];
371
+ if (output.firstObservedAt !== undefined) fields.push(`first-observed-at="${wakeTimestamp(output.firstObservedAt)}"`);
372
+ if (output.lastObservedAt !== undefined) fields.push(`last-observed-at="${wakeTimestamp(output.lastObservedAt)}"`);
373
+ fields.push(`cursor-start="${output.cursorStart}"`);
374
+ if (output.cursorEnd !== undefined) fields.push(`cursor-end="${output.cursorEnd}"`);
375
+ if (output.truncated) fields.push('truncated="true"');
376
+ if (output.suppressedCount) fields.push(`duplicates-suppressed="${output.suppressedCount}"`);
377
+ if (output.omittedChars) fields.push(`omitted-chars="${output.omittedChars}"`);
378
+ return `${indent}<output ${fields.join(" ")}>${escapeXml(PROMPTS["wakes.monitor.output-hint"])}</output>`;
379
+ }
380
+
320
381
  function renderMonitor(details: Extract<FamulusWake, { kind: "monitor" }>): string {
321
382
  const attrs = [
322
383
  'kind="monitor"',
@@ -328,19 +389,9 @@ function renderMonitor(details: Extract<FamulusWake, { kind: "monitor" }>): stri
328
389
  if (details.droppedLines !== undefined && details.droppedLines > 0) {
329
390
  attrs.push(`dropped-lines="${details.droppedLines}"`);
330
391
  }
331
- const output = details.output;
332
392
  const parts = [`<pi-famulus-wake ${attrs.join(" ")}>`, ` <event>${escapeXml(details.event)}</event>`];
333
- if (output?.cursorStart !== undefined) {
334
- const fields: string[] = [];
335
- if (output.firstObservedAt !== undefined) fields.push(`first-observed-at="${wakeTimestamp(output.firstObservedAt)}"`);
336
- if (output.lastObservedAt !== undefined) fields.push(`last-observed-at="${wakeTimestamp(output.lastObservedAt)}"`);
337
- fields.push(`cursor-start="${output.cursorStart}"`);
338
- if (output.cursorEnd !== undefined) fields.push(`cursor-end="${output.cursorEnd}"`);
339
- if (output.truncated) fields.push('truncated="true"');
340
- if (output.suppressedCount) fields.push(`duplicates-suppressed="${output.suppressedCount}"`);
341
- if (output.omittedChars) fields.push(`omitted-chars="${output.omittedChars}"`);
342
- parts.push(` <output ${fields.join(" ")}>${escapeXml(PROMPTS["wakes.monitor.output-hint"])}</output>`);
343
- }
393
+ const outputXml = renderMonitorOutputElement(details.output, " ");
394
+ if (outputXml) parts.push(outputXml);
344
395
  parts.push("</pi-famulus-wake>");
345
396
  return parts.join("\n");
346
397
  }
@@ -499,6 +550,20 @@ function renderRequest(details: Extract<FamulusWake, { kind: "supervisor-request
499
550
  ].join("\n");
500
551
  }
501
552
 
553
+ function renderRunningMonitors(details: Extract<FamulusWake, { kind: "running-monitors" }>): string {
554
+ const parts = [
555
+ '<pi-famulus-wake kind="running-monitors">',
556
+ PROMPTS["wakes.running-monitors.guidance"],
557
+ ];
558
+ for (const monitor of details.monitors) {
559
+ parts.push(
560
+ ` <monitor id="${escapeXmlAttr(monitor.id)}" remaining="${escapeXmlAttr(monitor.remaining)}"${monitor.wakeOn ? ` wake-on="${escapeXmlAttr(monitor.wakeOn)}"` : ""}>${escapeXml(monitor.description)}</monitor>`,
561
+ );
562
+ }
563
+ parts.push("</pi-famulus-wake>");
564
+ return parts.join("\n");
565
+ }
566
+
502
567
  function renderUpdate(details: Extract<FamulusWake, { kind: "supervisor-update" }>): string {
503
568
  return [
504
569
  `<pi-famulus-wake kind="supervisor-update" from="${escapeXmlAttr(details.from)}" name="${escapeXmlAttr(details.name)}">`,
@@ -506,3 +571,46 @@ function renderUpdate(details: Extract<FamulusWake, { kind: "supervisor-update"
506
571
  "</pi-famulus-wake>",
507
572
  ].join("\n");
508
573
  }
574
+
575
+ function renderMonitorTerminal(details: Extract<FamulusWake, { kind: "monitor-terminal" }>): string {
576
+ const parts = [
577
+ `<pi-famulus-wake kind="monitor-terminal">`,
578
+ ` <summary>${escapeXml(details.summary)}</summary>`,
579
+ ];
580
+ for (const monitor of details.monitors) {
581
+ const attrs = [
582
+ `id="${escapeXmlAttr(monitor.id)}"`,
583
+ `description="${escapeXmlAttr(monitor.description)}"`,
584
+ `status="${escapeXmlAttr(monitor.status)}"`,
585
+ ];
586
+ if (monitor.droppedLines !== undefined && monitor.droppedLines > 0) {
587
+ attrs.push(`dropped-lines="${monitor.droppedLines}"`);
588
+ }
589
+ const outputXml = renderMonitorOutputElement(monitor.output, " ");
590
+ if (outputXml) {
591
+ parts.push(` <monitor ${attrs.join(" ")}>`);
592
+ if (monitor.detail) parts.push(` ${escapeXml(monitor.detail)}`);
593
+ parts.push(outputXml);
594
+ parts.push(" </monitor>");
595
+ } else {
596
+ parts.push(` <monitor ${attrs.join(" ")}>${escapeXml(monitor.detail)}</monitor>`);
597
+ }
598
+ }
599
+ parts.push("</pi-famulus-wake>");
600
+ return parts.join("\n");
601
+ }
602
+
603
+ function renderMonitorSessionEnd(details: Extract<FamulusWake, { kind: "monitor-session-end" }>): string {
604
+ const parts = [
605
+ `<pi-famulus-wake kind="monitor-session-end" reason="${escapeXmlAttr(details.reason)}">`,
606
+ ` <summary>${escapeXml(`Session monitor teardown (${details.reason}); process exits are not confirmed by this notice.`)}</summary>`,
607
+ ];
608
+ for (const monitor of details.monitors) {
609
+ const pointer = `task_output({task_id: "${monitor.id}"}) ${monitor.outputPath} while the log is retained`;
610
+ parts.push(
611
+ ` <monitor id="${escapeXmlAttr(monitor.id)}" description="${escapeXmlAttr(monitor.description)}" elapsed-ms="${Math.round(monitor.elapsedMs)}">${escapeXml(pointer)}</monitor>`,
612
+ );
613
+ }
614
+ parts.push("</pi-famulus-wake>");
615
+ return parts.join("\n");
616
+ }