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.
package/README.md CHANGED
@@ -82,7 +82,7 @@ Run the full test suite and tell me what fails.
82
82
  | Ask the agent | What happens |
83
83
  | :--- | :--- |
84
84
  | `Run the full test suite and tell me what fails.` | `bash` moves the run to the background after 20 seconds; the result arrives when it exits |
85
- | `Start the dev server and tell me if an error shows up in its output.` | `monitor` batches new output into bounded events; repeated lines are deduplicated within a configurable window |
85
+ | `Start the dev server and tell me if an error shows up in its output.` | `monitor` batches new output into bounded events; repeated lines are deduplicated within a configurable window. Default timeout is 5 minutes (max 1 hour); expiry stops the monitor and the notice can arrive late while you are busy. Use `persistent:true` for open-ended watches or anything longer than an hour (never both, no re-arming). If you use timeouts for several monitors, stagger them |
86
86
  | `Review these three modules in parallel with subagents.` | `subagent` runs the tasks in parallel; each subagent reports back when it finishes |
87
87
  | `Which models can subagents use?` | The agent calls `subagent({action: "models"})` and lists the choices |
88
88
 
@@ -129,7 +129,8 @@ pi-famulus starts and stops processes for you. This section states what it guara
129
129
  - Shells and monitors do not survive the last pi session closing. Five seconds after the last session disconnects, and once no hosted subagent is still warm, the daemon stops what is left and exits. A warm subagent keeps the daemon up after its parent disconnects. It parks at its retention deadline, or earlier when the warm-agent cap needs the slot. Records, output and transcripts stay on disk for 24 hours.
130
130
  - A subagent still running when its 30-minute turn budget ends is not killed, unless you set `hardTimeoutMs`. The parent is told and chooses to extend, steer or interrupt it.
131
131
  - A subagent with no activity for 5 minutes is resumed once on the same session, with its transcript kept. The timer pauses while a tool runs or a `contact_supervisor` question waits for an answer. If the subagent stalls again, it is marked failed.
132
- - `monitor` batches output every 200 ms. Rust-framed repeated complete lines from the same monitor are deduplicated for 60 seconds by default after a representative is delivered; legacy/raw fallback previews are not content-deduplicated, and missing metadata, capacity eviction, and omitted representatives fail open. Exact matching is the default, with timestamp normalization opt-in. Previews are bounded; original output remains readable with `task_output`. Deduplication does not count as overload loss. Admitted batches allow a burst of 10 events, then one event every 2 seconds. Batches over that limit are dropped. If at least half the batches are dropped over a 30-second window that holds at least 10 batches, the monitor stops and you are told.
132
+ - `monitor` takes one lifetime: timeout_ms (default 5 minutes, max 1 hour) for a watch that ends within an hour, where expiry stops the monitor and the notice can arrive late while you are busy; or `persistent:true` for open-ended watches or anything longer than an hour. Setting both, or timeout_ms above 1 hour, is rejected. If you use timeouts for several monitors, stagger them. Run a producer you start as the monitor command itself; use `tail -F` / `journalctl -f` for sources you did not start. 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. Status lines may stay if you set `wake_on` to the problem pattern: only matching lines wake the agent, and `task_output` keeps every line. Use `stall_after_ms` instead of heartbeats to learn that the source went silent.
133
+ - `monitor` batches output every 200 ms. Rust-framed repeated complete lines from the same monitor are deduplicated for 60 seconds by default after a representative is delivered; legacy/raw fallback previews are not content-deduplicated, and missing metadata, capacity eviction, and omitted representatives fail open. Exact matching is the default, with timestamp normalization opt-in. Previews are bounded; original output remains readable with `task_output`. Deduplication does not count as overload loss. Admitted batches allow a burst of 10 events, then one event every 2 seconds. Batches over that limit are dropped. The primary overload entry is that drop-ratio: with 200 ms batching and the token bucket, sustained about 1 distinct batch/s (~1 line/s) or more enters via drop ratio within tens of seconds; about 2 distinct lines/s around 30s; below about 0.9 batches/s does not enter. A rolling input average above 5 lines/s over 30s is only a supplementary trigger (draft value). On entry, one notice says individual lines are suppressed, the first summary comes after 30s, and raw output stays on `task_output`; on quiet exit, one notice resumes lines. Cadence after 30s is 60s, then 120s, then every 300s (300s draft value). It stops itself only if input stays near 1000 lines/s for 60s (unverified draft safety backstop).
133
134
  - On Linux and macOS, the daemon checks its own executable every 2 seconds. When the file is replaced, the running daemon re-executes itself with the same pid. `pi-famulus upgrade` does the same on demand. Running commands keep going and clients reconnect. The measured gap was 30 to 46 ms.
134
135
 
135
136
  ## FAQ
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-famulus",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Keep your main agent's context clean: subagents on cheaper models, long bash in the background, and monitors that wake the agent. One Rust daemon runs the shells.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -54,12 +54,12 @@
54
54
  "pi-famulus": "./bin/pi-famulus.js"
55
55
  },
56
56
  "optionalDependencies": {
57
- "pi-famulus-linux-x64": "0.2.2",
58
- "pi-famulus-linux-arm64": "0.2.2",
59
- "pi-famulus-darwin-x64": "0.2.2",
60
- "pi-famulus-darwin-arm64": "0.2.2",
61
- "pi-famulus-win-x64": "0.2.2",
62
- "pi-famulus-win-arm64": "0.2.2"
57
+ "pi-famulus-linux-x64": "0.2.4",
58
+ "pi-famulus-linux-arm64": "0.2.4",
59
+ "pi-famulus-darwin-x64": "0.2.4",
60
+ "pi-famulus-darwin-arm64": "0.2.4",
61
+ "pi-famulus-win-x64": "0.2.4",
62
+ "pi-famulus-win-arm64": "0.2.4"
63
63
  },
64
64
  "pi": {
65
65
  "extensions": [
package/src/config.ts CHANGED
@@ -19,6 +19,8 @@ export interface FamulusConfig {
19
19
  logLevel: "debug" | "info" | "warn" | "error";
20
20
  /** Cross-session messaging requires explicit opt-in. */
21
21
  messaging?: { enabled: boolean };
22
+ /** End a run that keeps making only no-op/status calls (src/idle-turn-guard.ts). */
23
+ idleTurnGuard?: boolean;
22
24
  /** Optional M3 subagent tuning section (design doc §4.6 limits). */
23
25
  subagent?: FamulusSubagentConfig;
24
26
  }
@@ -142,6 +144,7 @@ export const DEFAULT_CONFIG: FamulusConfig = {
142
144
  managerPath: null,
143
145
  logLevel: "info",
144
146
  messaging: { enabled: false },
147
+ idleTurnGuard: true,
145
148
  };
146
149
 
147
150
  /** Resolve the pi-famulus base directory. PI_FAMULUS_HOME overrides the default. */
@@ -216,6 +219,7 @@ export function loadConfig(home: string = getFamulusHome()): FamulusConfig {
216
219
  if (typeof obj.messaging === "object" && obj.messaging !== null) {
217
220
  config.messaging = { enabled: (obj.messaging as Record<string, unknown>).enabled === true };
218
221
  }
222
+ if (obj.idleTurnGuard === false) config.idleTurnGuard = false;
219
223
  if (typeof obj.foregroundBudgetMs === "number" && obj.foregroundBudgetMs > 0) {
220
224
  config.foregroundBudgetMs = obj.foregroundBudgetMs;
221
225
  }
package/src/format.ts CHANGED
@@ -109,6 +109,30 @@ function displayCommand(command: string): string {
109
109
  return shellWakeTitle(command);
110
110
  }
111
111
 
112
+ function stopSourceLabel(source: string): string {
113
+ return source === "tui" ? "TUI" : source === "cli" ? "CLI" : source;
114
+ }
115
+
116
+ export function exitReasonPhrase(endReason: string | undefined): string {
117
+ const source = endReason?.startsWith("stopped:") ? endReason.slice("stopped:".length) : undefined;
118
+ return source !== undefined
119
+ ? `Stopped via ${stopSourceLabel(source)} (reason: ${endReason})`
120
+ : endReason === "exited" ? "Process exited" : `Process ended (reason: ${endReason ?? "unknown"})`;
121
+ }
122
+
123
+ export function formatExitFacts(facts: import("./wake").MonitorExitFacts): string {
124
+ return `${exitReasonPhrase(facts.endReason)}; exit code ${facts.exitCode == null ? "unknown" : facts.exitCode}${facts.signal ? `; signal ${facts.signal}` : ""}.${facts.stopRequested ? " This agent requested a stop." : ""}`;
125
+ }
126
+
127
+ function killedPhrase(info: TaskExitInfo): string {
128
+ const details: string[] = [];
129
+ if (info.endReason) {
130
+ details.push(info.endReason.startsWith("stopped:") ? `stopped via ${stopSourceLabel(info.endReason.slice("stopped:".length))}` : info.endReason);
131
+ }
132
+ if (info.signal) details.push(info.signal);
133
+ return details.length ? `was killed (${details.join(", ")})` : "was killed";
134
+ }
135
+
112
136
  function statusPhrase(info: TaskExitInfo): string {
113
137
  const startFailure = shellStartStatus(info.endReason);
114
138
  if (startFailure) return startFailure;
@@ -119,7 +143,7 @@ function statusPhrase(info: TaskExitInfo): string {
119
143
  case "failed":
120
144
  return code ? `failed (${code})` : "failed";
121
145
  case "killed":
122
- return "was killed";
146
+ return killedPhrase(info);
123
147
  case "orphaned":
124
148
  return "ended when pi-famulus crashed";
125
149
  }
@@ -159,6 +183,7 @@ export function formatTaskNotification(
159
183
  durationMs: info.durationMs,
160
184
  exitCode: info.exitCode,
161
185
  ...(info.signal ? { signal: info.signal } : {}),
186
+ ...(info.endReason ? { endReason: info.endReason } : {}),
162
187
  })),
163
188
  },
164
189
  leadIn,
@@ -204,7 +229,7 @@ export function formatMonitorEvent(
204
229
  taskId: string,
205
230
  batchText: string,
206
231
  status?: string,
207
- extras: { eventCount?: number; droppedLines?: number; output?: MonitorOutputInfo } = {},
232
+ extras: { eventCount?: number; droppedLines?: number; output?: MonitorOutputInfo; exitFacts?: import("./wake").MonitorExitFacts; exitContext?: string } = {},
208
233
  ): FormattedWake {
209
234
  return formatFamulusWake({
210
235
  kind: "monitor",
@@ -215,6 +240,52 @@ export function formatMonitorEvent(
215
240
  ...(extras.eventCount !== undefined ? { eventCount: extras.eventCount } : {}),
216
241
  ...(extras.droppedLines !== undefined ? { droppedLines: extras.droppedLines } : {}),
217
242
  ...(extras.output ? { output: extras.output } : {}),
243
+ ...(extras.exitFacts ? { exitFacts: extras.exitFacts } : {}),
244
+ ...(extras.exitContext ? { exitContext: extras.exitContext } : {}),
245
+ });
246
+ }
247
+
248
+ /** One short still-running list after compaction (id, description, remaining). */
249
+ export function formatRunningMonitorList(
250
+ items: { id: string; description: string; remaining: string; wakeOn?: string }[],
251
+ ): FormattedWake {
252
+ return formatFamulusWake({ kind: "running-monitors", monitors: items });
253
+ }
254
+
255
+ export const MONITOR_UNWATCHED_SUMMARY =
256
+ "Monitor lifecycle updates.";
257
+
258
+ export type MonitorTerminalStatus = "timeout" | "exited" | "stopped";
259
+
260
+ export interface MonitorTerminalInfo {
261
+ id: string;
262
+ description: string;
263
+ status: MonitorTerminalStatus;
264
+ event?: string;
265
+ droppedLines?: number;
266
+ output?: MonitorOutputInfo;
267
+ exitFacts?: import("./wake").MonitorExitFacts;
268
+ }
269
+
270
+ function terminalDetail(info: MonitorTerminalInfo): string {
271
+ return info.event ?? "";
272
+ }
273
+
274
+ /** One <pi-famulus-wake kind="monitor-terminal"> listing every monitor in the window. */
275
+ export function formatMonitorTerminal(monitors: MonitorTerminalInfo[]): FormattedWake {
276
+ return formatFamulusWake({
277
+ kind: "monitor-terminal",
278
+ ids: monitors.map((monitor) => monitor.id),
279
+ summary: MONITOR_UNWATCHED_SUMMARY,
280
+ monitors: monitors.map((monitor) => ({
281
+ id: monitor.id,
282
+ description: monitor.description,
283
+ status: monitor.status,
284
+ detail: terminalDetail(monitor),
285
+ ...(monitor.droppedLines ? { droppedLines: monitor.droppedLines } : {}),
286
+ ...(monitor.output ? { output: monitor.output } : {}),
287
+ ...(monitor.exitFacts ? { exitFacts: monitor.exitFacts } : {}),
288
+ })),
218
289
  });
219
290
  }
220
291
 
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Idle turn guard: ends a run that keeps making no-op calls.
3
+ *
4
+ * Some models (k3.1-pro, k3-256k on 2026-11-07) cannot end a turn: after the
5
+ * work is done they answer "完成。" and call `true`, `date` or `task_list`,
6
+ * turn after turn, though the prompt says to reply with no tool call. Pi only
7
+ * ends a run on a reply without tool calls, so nothing stopped them.
8
+ *
9
+ * At `message_end` an assistant message whose every tool call is an idle
10
+ * probe is an idle turn. The run ends at IDLE_TURN_LIMIT idle turns in a row
11
+ * or IDLE_RUN_LIMIT in the run: each call of that batch is blocked with
12
+ * `terminate`, so pi ends the run after the batch, as if the model had
13
+ * stopped. A turn with other calls breaks the streak only; a reply without
14
+ * calls, a wake, a user or peer message, or a new run resets both counts.
15
+ * Queued steering still continues the run; wakes still start new ones.
16
+ */
17
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
+ import { fill } from "./prompts.generated.ts";
19
+
20
+ /** Idle turns in a row that end the run. */
21
+ export const IDLE_TURN_LIMIT = 2;
22
+ /**
23
+ * Idle turns in one run that end it, even with other calls in between. The
24
+ * 2026-11-07 replay interleaved no-ops with fresh read-only checks
25
+ * (`git status`, `gh pr view`, `read`), which reset a consecutive count.
26
+ */
27
+ export const IDLE_RUN_LIMIT = 3;
28
+
29
+ /** Whole commands that do nothing: no pipes, redirects, substitutions or chaining. */
30
+ const NOOP_BASH: RegExp[] = [
31
+ /^(true|:|pwd|exit( 0)?)$/,
32
+ /^date(\s+[^;&|<>`$()]*)?$/,
33
+ /^printf(\s+[^;&|<>`$()]*)?$/,
34
+ /^echo(\s+[^;&|<>`$()]*)?$/,
35
+ /^sleep\s+\d+(\.\d+)?[smh]?$/,
36
+ ];
37
+
38
+ const STATUS_TOOLS = new Set(["task_list"]);
39
+
40
+ export function isIdleProbe(toolName: string, args: unknown): boolean {
41
+ if (STATUS_TOOLS.has(toolName)) return true;
42
+ if (toolName !== "bash") return false;
43
+ const command = (args as { command?: unknown } | null)?.command;
44
+ if (typeof command !== "string") return false;
45
+ const trimmed = command.trim();
46
+ return NOOP_BASH.some((re) => re.test(trimmed));
47
+ }
48
+
49
+ function describeCall(name: string, args: unknown): string {
50
+ if (name !== "bash") return name;
51
+ const command = String((args as { command?: unknown }).command ?? "").trim();
52
+ return `bash: ${command.length > 40 ? `${command.slice(0, 39)}…` : command}`;
53
+ }
54
+
55
+ interface ToolCallPart {
56
+ type: "toolCall";
57
+ id: string;
58
+ name: string;
59
+ arguments: unknown;
60
+ }
61
+
62
+ export interface IdleTurnGuardOptions {
63
+ enabled: boolean;
64
+ /** Called once per tripped batch. `calls` lists the idle calls of the streak, oldest first. */
65
+ onTrip?: (info: { count: number; calls: string[] }) => void;
66
+ }
67
+
68
+ export function installIdleTurnGuard(pi: Pick<ExtensionAPI, "on">, opts: IdleTurnGuardOptions): void {
69
+ if (!opts.enabled) return;
70
+ let streak = 0;
71
+ let inRun = 0;
72
+ let idleCalls: string[] = [];
73
+ const blocked = new Map<string, string>();
74
+ const reset = () => {
75
+ streak = 0;
76
+ inRun = 0;
77
+ idleCalls = [];
78
+ blocked.clear();
79
+ };
80
+
81
+ // Every run starts clean: whatever started it (a prompt, a wake, a peer
82
+ // message) is new information.
83
+ pi.on("agent_start", async () => reset());
84
+
85
+ pi.on("message_end", async (event) => {
86
+ const message = event.message as { role?: string; content?: unknown };
87
+ if (message.role === "toolResult") return;
88
+ const calls = message.role === "assistant" && Array.isArray(message.content)
89
+ ? (message.content as { type?: string }[]).filter((p): p is ToolCallPart => p.type === "toolCall")
90
+ : [];
91
+ if (calls.length === 0) {
92
+ reset();
93
+ return;
94
+ }
95
+ if (!calls.every((c) => isIdleProbe(c.name, c.arguments))) {
96
+ streak = 0;
97
+ return;
98
+ }
99
+ streak += 1;
100
+ inRun += 1;
101
+ idleCalls.push(...calls.map((c) => describeCall(c.name, c.arguments)));
102
+ if (streak < IDLE_TURN_LIMIT && inRun < IDLE_RUN_LIMIT) return;
103
+ const shown = idleCalls.slice(-4);
104
+ const reason = streak >= IDLE_TURN_LIMIT
105
+ ? fill("guards.error.idle-turn", { count: String(streak), calls: shown.join("; ") })
106
+ : fill("guards.error.idle-run", { count: String(inRun), calls: shown.join("; ") });
107
+ for (const c of calls) blocked.set(c.id, reason);
108
+ opts.onTrip?.({ count: Math.max(streak, inRun), calls: shown });
109
+ });
110
+
111
+ pi.on("tool_call", async (event) => {
112
+ if (event.parentToolCallId) return;
113
+ const reason = blocked.get(event.toolCallId);
114
+ if (reason === undefined) return;
115
+ blocked.delete(event.toolCallId);
116
+ return { block: true, reason, terminate: true };
117
+ });
118
+ }
package/src/index.ts CHANGED
@@ -15,7 +15,7 @@ import { statSync } from "node:fs";
15
15
  import { readdir, readFile, stat } from "node:fs/promises";
16
16
  import { homedir } from "node:os";
17
17
  import { join } from "node:path";
18
- import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
18
+ import { SessionManager, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
19
19
  import { resolveAgent as resolveAgentDef } from "./agents/definition";
20
20
  import { createAgentLoader, type AgentLoader } from "./agents/loader";
21
21
  import { createBashOverride } from "./bash-override";
@@ -24,14 +24,15 @@ import { createComms, type CommsWithOrigin } from "./comms/comms";
24
24
  import { createRegistryCommsHost } from "./comms/registry-host";
25
25
  import { createAgentMessageTool } from "./comms/tools";
26
26
  import { registerReplyCommand } from "./comms/reply-command";
27
+ import { installIdleTurnGuard } from "./idle-turn-guard";
27
28
  import { describeManagerSearch, getFamulusHome, loadConfig, resolveManagerPath, resolveSubagentConfig, taskOutputPath } from "./config";
28
29
  import { ensureNativeManagerInstalled } from "./native-manager.js";
29
- import type { TaskExitInfo } from "./format";
30
+ import { formatDuration, type TaskExitInfo } from "./format";
30
31
  import { EXTENSION_VERSION, ManagerClient, type ManagerEvent, type TaskRecord } from "./manager-client";
31
32
  import { registerIntercom } from "./intercom/intercom";
32
33
  import { createMonitorTool, exitEventFromRecord, MonitorRegistry } from "./monitor";
33
34
  import { admitAgentChild, reregisterAgentLeases } from "./subagent/admission";
34
- import { NotifyCenter } from "./notify";
35
+ import { attachCompactRecovery, NotifyCenter } from "./notify";
35
36
  import { onWakeMessageEnd, registryStatusLookup } from "./wake-delivery";
36
37
  import { ChildShellTracker, createOverrunNotifier } from "./subagent/overrun";
37
38
  import {
@@ -62,7 +63,7 @@ import { registerFamulusCommand } from "./tui/famulus-command";
62
63
  import { registerFamulusMessageRenderers } from "./tui/message-renderers";
63
64
  import { registerTasksCommand } from "./tui/tasks-command";
64
65
  import { stderrPathFor } from "./tui/task-output-paths";
65
- import { shellWakeTitle } from "./wake";
66
+ import { FAMULUS_WAKE_CUSTOM_TYPE, formatFamulusWake, shellWakeTitle, stampWakeAsOf, wakeIds } from "./wake";
66
67
 
67
68
  async function promptIfHostedSession(
68
69
  c: ManagerClient,
@@ -384,7 +385,35 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
384
385
  * daemon already ended as manager-shutdown / manager-crash.
385
386
  * A hosted child that is still warm is left for resume.
386
387
  */
387
- const recoverCrashedSession = async (sessionId: string): Promise<void> => {
388
+ const collectNoticedMonitorIds = (file: string | undefined): Set<string> => {
389
+ const ids = new Set<string>();
390
+ if (!file) return ids;
391
+ try {
392
+ for (const entry of SessionManager.open(file).getEntries()) {
393
+ if (entry.type !== "custom_message") continue;
394
+ const custom = entry as { customType?: string; details?: unknown };
395
+ if (custom.customType !== FAMULUS_WAKE_CUSTOM_TYPE) continue;
396
+ const details = custom.details as
397
+ | { kind?: string; ids?: unknown; monitors?: unknown; tasks?: unknown }
398
+ | undefined;
399
+ if (!details || typeof details !== "object") continue;
400
+ if (details.kind === "monitor-session-end") {
401
+ for (const id of wakeIds(details)) ids.add(id);
402
+ } else if (details.kind === "session-recovery") {
403
+ if (Array.isArray(details.monitors)) {
404
+ for (const id of details.monitors) if (typeof id === "string") ids.add(id);
405
+ }
406
+ if (Array.isArray(details.tasks)) {
407
+ for (const id of details.tasks) if (typeof id === "string") ids.add(id);
408
+ }
409
+ }
410
+ }
411
+ } catch {
412
+ return ids;
413
+ }
414
+ return ids;
415
+ };
416
+ const recoverCrashedSession = async (sessionId: string, sessionFile?: string): Promise<void> => {
388
417
  if (!recoverPreviousProcess || !sessionId || recoveredSessions.has(sessionId)) return;
389
418
  const manager = client;
390
419
  const center = notifyCenter;
@@ -399,14 +428,20 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
399
428
  if (!recoverPreviousProcess || client !== manager || notifyCenter !== center) return;
400
429
  killed = tasks.filter((task) => {
401
430
  if (task.session_id && task.session_id !== sessionId) return false;
402
- if (task.kind !== "shell") return false;
403
- return task.end_reason === "manager-shutdown" || task.end_reason === "manager-crash";
431
+ if (task.kind === "shell") {
432
+ return task.end_reason === "manager-shutdown" || task.end_reason === "manager-crash";
433
+ }
434
+ if (task.kind === "monitor") return task.end_reason === "session-end";
435
+ return false;
404
436
  });
405
437
  } catch {
406
438
  killed = [];
407
439
  }
408
440
  }
409
- if (interrupted.length === 0 && killed.length === 0) {
441
+ const noticed = collectNoticedMonitorIds(sessionFile ?? noticeSessionFile);
442
+ const monitors = killed.filter((task) => task.kind === "monitor" && !noticed.has(task.task_id));
443
+ const shells = killed.filter((task) => task.kind === "shell");
444
+ if (interrupted.length === 0 && shells.length === 0 && monitors.length === 0) {
410
445
  recoveredSessions.delete(sessionId);
411
446
  return;
412
447
  }
@@ -418,16 +453,20 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
418
453
  for (const rec of interrupted) {
419
454
  lines.push(`Interrupted subagent ${rec.child_id} (${rec.name}).`);
420
455
  }
421
- for (const task of killed) {
456
+ for (const task of shells) {
422
457
  lines.push(`Command ${task.task_id} ended while the session was gone (${task.end_reason ?? task.status}).`);
423
458
  }
459
+ for (const task of monitors) {
460
+ lines.push(`Monitor ${task.task_id} ended when the session ended (${task.end_reason ?? task.status}).`);
461
+ }
424
462
  center?.notify({
425
- customType: "pi-famulus-wake",
463
+ customType: FAMULUS_WAKE_CUSTOM_TYPE,
426
464
  content: lines.join("\n"),
427
465
  details: {
428
466
  kind: "session-recovery",
429
467
  children: interrupted.map((rec) => rec.child_id),
430
- tasks: killed.map((task) => task.task_id),
468
+ tasks: shells.map((task) => task.task_id),
469
+ monitors: monitors.map((task) => task.task_id),
431
470
  },
432
471
  });
433
472
  };
@@ -593,8 +632,24 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
593
632
  afterStop: () => void syncWithManager(),
594
633
  });
595
634
 
635
+ const compactRecovery = attachCompactRecovery(pi, {
636
+ getCenter: () => notifyCenter,
637
+ getCtx: () => ctx,
638
+ listRunningMonitors: () =>
639
+ (monitorRegistry?.listActive() ?? []).map((mon) => ({
640
+ id: mon.taskId,
641
+ description: mon.description,
642
+ remaining: mon.persistent ? "persistent" : `${formatDuration(mon.remainingMs ?? 0)} remaining`,
643
+ ...(mon.wakeOn ? { wakeOn: mon.wakeOn } : {}),
644
+ })),
645
+ });
646
+
596
647
  pi.registerTool(createBashOverride(deps));
597
- pi.registerTool(createTaskListTool({ ...deps, getIndex: () => workIndex }));
648
+ pi.registerTool(createTaskListTool({
649
+ ...deps,
650
+ getIndex: () => workIndex,
651
+ getMonitorLive: () => monitorRegistry?.listActive() ?? [],
652
+ }));
598
653
  pi.registerTool(createTaskOutputTool({ ...deps, getIndex: () => workIndex }));
599
654
  pi.registerTool(
600
655
  createTaskStopTool({
@@ -733,6 +788,90 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
733
788
 
734
789
  /** Session whose runtime a /reload parked; the reloaded instance's session_start resumes it. */
735
790
  let parkedSessionId: string | null = null;
791
+ /** Old session identity for teardown notices after detach / attach. */
792
+ let noticeSessionId: string | undefined;
793
+ let noticeSessionFile: string | undefined;
794
+ const MONITOR_TEARDOWN_SEND_TIMEOUT_MS = 2_000;
795
+ type MonitorTeardownReason = "new" | "resumed" | "forked" | "handoff-ended" | "session-mismatch";
796
+ const mappedTeardownReason = (reason: string | undefined): MonitorTeardownReason | null => {
797
+ if (reason === "new") return "new";
798
+ if (reason === "resume") return "resumed";
799
+ if (reason === "fork") return "forked";
800
+ if (reason === "session-mismatch") return "session-mismatch";
801
+ return null;
802
+ };
803
+ const emitMonitorTeardownNotice = async (mapped: MonitorTeardownReason, dest: "live" | "file"): Promise<void> => {
804
+ const noticed = collectNoticedMonitorIds(noticeSessionFile);
805
+ const active = (monitorRegistry?.listActive() ?? []).filter((mon) => !noticed.has(mon.taskId));
806
+ if (active.length === 0) return;
807
+ const now = clock.now();
808
+ const sid = noticeSessionId ?? ctx?.sessionManager.getSessionId() ?? "";
809
+ const monitors = active.map((mon) => ({
810
+ id: mon.taskId,
811
+ description: mon.description,
812
+ elapsedMs: Math.max(0, now - mon.startedAt),
813
+ outputPath: workIndex.get(mon.taskId)?.outputPath || taskOutputPath(home, sid, mon.taskId),
814
+ }));
815
+ const formatted = formatFamulusWake({
816
+ kind: "monitor-session-end",
817
+ reason: mapped,
818
+ ids: monitors.map((monitor) => monitor.id),
819
+ monitors,
820
+ });
821
+ const message = stampWakeAsOf(
822
+ { customType: formatted.customType, content: formatted.content, details: formatted.details, display: true },
823
+ now,
824
+ );
825
+ if (dest === "live") {
826
+ let timeout: unknown = null;
827
+ try {
828
+ await Promise.race([
829
+ Promise.resolve(pi.sendMessage(
830
+ { customType: message.customType, content: message.content, display: true, details: message.details },
831
+ { triggerTurn: false },
832
+ )),
833
+ new Promise<never>((_resolve, reject) => {
834
+ timeout = clock.setTimeout(() => reject(new Error("live send timed out")), MONITOR_TEARDOWN_SEND_TIMEOUT_MS);
835
+ if (timeout) clock.unref?.(timeout);
836
+ }),
837
+ ]);
838
+ } catch (error) {
839
+ logEvent("monitor.teardown-fallback", {
840
+ reason: mapped,
841
+ error: error instanceof Error ? error.message : String(error),
842
+ });
843
+ appendWakeToOldSessionFile(message);
844
+ } finally {
845
+ if (timeout !== null) clock.clearTimeout(timeout);
846
+ }
847
+ return;
848
+ }
849
+ appendWakeToOldSessionFile(message);
850
+ };
851
+ const appendWakeToOldSessionFile = (message: { content: string; details?: unknown }): void => {
852
+ const file = noticeSessionFile;
853
+ if (!file) return;
854
+ try {
855
+ SessionManager.open(file).appendCustomMessageEntry(FAMULUS_WAKE_CUSTOM_TYPE, message.content, true, message.details);
856
+ } catch {
857
+ // Missing or unreadable session file: teardown still proceeds.
858
+ }
859
+ };
860
+ const deliverPendingMonitorTerminals = (dest: "live" | "file"): void => {
861
+ const center = notifyCenter;
862
+ if (!center) return;
863
+ if (dest === "live") {
864
+ center.flush();
865
+ return;
866
+ }
867
+ const messages = center.drainPendingMonitorTerminals();
868
+ for (const message of messages) {
869
+ appendWakeToOldSessionFile(stampWakeAsOf(
870
+ { customType: message.customType, content: message.content, details: message.details, display: true },
871
+ clock.now(),
872
+ ));
873
+ }
874
+ };
736
875
  const startFleetWidget = (startCtx: ExtensionContext) => {
737
876
  if (!startCtx.hasUI) return;
738
877
  fleetWidget = new FleetWidget({
@@ -745,6 +884,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
745
884
 
746
885
  pi.on("session_start", async (event, startCtx) => {
747
886
  recoverPreviousProcess = event.reason !== "reload";
887
+ const startFile = startCtx.sessionManager.getSessionFile?.();
748
888
  if (parkedSessionId !== null) {
749
889
  const resumed = event.reason === "reload" && startCtx.sessionManager.getSessionId() === parkedSessionId;
750
890
  parkedSessionId = null;
@@ -752,16 +892,20 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
752
892
  // Same session after /reload: the client, registry and monitors kept
753
893
  // running; only the context and the UI belong to the new instance.
754
894
  ctx = startCtx;
895
+ noticeSessionId = startCtx.sessionManager.getSessionId();
896
+ noticeSessionFile = startFile;
755
897
  binding.ready();
756
898
  startFleetWidget(startCtx);
757
899
  void syncWithManager();
758
900
  return;
759
901
  }
760
902
  binding.discardQueued();
761
- await teardown();
903
+ await teardown({ reason: "session-mismatch", dest: "file" });
762
904
  }
763
905
  await retiring;
764
906
  ctx = startCtx;
907
+ noticeSessionId = startCtx.sessionManager.getSessionId();
908
+ noticeSessionFile = startFile;
765
909
  binding.ready();
766
910
  notifyCenter?.dispose();
767
911
  notifyCenter = new NotifyCenter({
@@ -1178,7 +1322,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1178
1322
  });
1179
1323
  startFleetWidget(startCtx);
1180
1324
  if (client?.isAvailable()) {
1181
- await recoverCrashedSession(startCtx.sessionManager.getSessionId());
1325
+ await recoverCrashedSession(startCtx.sessionManager.getSessionId(), startCtx.sessionManager.getSessionFile?.());
1182
1326
  }
1183
1327
 
1184
1328
  // Connect in the background: a cold manager spawn must not stall the
@@ -1201,7 +1345,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1201
1345
  const sid = startCtx.sessionManager.getSessionId();
1202
1346
  void promptIfHostedSession(c, () => ctx, { sessionFile: file, sessionId: sid }, "start").catch(() => {});
1203
1347
  void syncWithManager();
1204
- void recoverCrashedSession(sid);
1348
+ void recoverCrashedSession(sid, file);
1205
1349
  return;
1206
1350
  }
1207
1351
  // A /reload may have replaced startCtx by now; report to the live one.
@@ -1221,7 +1365,10 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1221
1365
  .catch(() => {});
1222
1366
  });
1223
1367
 
1224
- const teardown = async (): Promise<void> => {
1368
+ const teardown = async (notice?: { reason: MonitorTeardownReason; dest: "live" | "file" }): Promise<void> => {
1369
+ if (notice) await emitMonitorTeardownNotice(notice.reason, notice.dest);
1370
+ compactRecovery.dispose();
1371
+ deliverPendingMonitorTerminals(notice?.dest ?? "live");
1225
1372
  exitWatchdog.dispose();
1226
1373
  fleetWidget?.dispose();
1227
1374
  fleetWidget = null;
@@ -1270,11 +1417,17 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1270
1417
  // Keep the session's shells, monitors and subagents running; the
1271
1418
  // reloaded instance adopts this runtime.
1272
1419
  parkedSessionId = ctx.sessionManager.getSessionId();
1420
+ noticeSessionId = parkedSessionId;
1421
+ noticeSessionFile = ctx.sessionManager.getSessionFile?.();
1273
1422
  fleetWidget?.dispose();
1274
1423
  fleetWidget = null;
1275
1424
  ctx = null;
1276
1425
  binding.detach();
1277
- parkRuntime({ version: EXTENSION_VERSION, runtime, dispose: teardown });
1426
+ parkRuntime({
1427
+ version: EXTENSION_VERSION,
1428
+ runtime,
1429
+ dispose: () => teardown({ reason: "handoff-ended", dest: "file" }),
1430
+ });
1278
1431
  return;
1279
1432
  }
1280
1433
  if (String((ctx as { mode?: string } | null)?.mode) === "print") {
@@ -1285,13 +1438,19 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1285
1438
  const warning = printModeDropWarning([...new Set(ids)]);
1286
1439
  if (warning) process.stderr.write(warning);
1287
1440
  }
1288
- await teardown();
1441
+ const mapped = mappedTeardownReason(typeof event.reason === "string" ? event.reason : undefined);
1442
+ await teardown(mapped ? { reason: mapped, dest: "live" } : undefined);
1289
1443
  });
1290
1444
 
1291
1445
  pi.on("agent_settled", async () => {
1292
1446
  notifyCenter?.settled();
1293
1447
  });
1294
1448
 
1449
+ installIdleTurnGuard(pi, {
1450
+ enabled: config.idleTurnGuard !== false,
1451
+ onTrip: (info) => logEvent("guard.idle-turn", { count: info.count, calls: info.calls }),
1452
+ });
1453
+
1295
1454
  // A wake entering the model's context (steer / triggerTurn); see wake-delivery.ts.
1296
1455
  pi.on("message_end", async (event) => {
1297
1456
  const message = onWakeMessageEnd(event.message, {