pi-famulus 0.2.2-nightly.20261026 → 0.2.3

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
@@ -73,7 +73,7 @@ Run the full test suite and tell me what fails.
73
73
  - **One daemon for every shell and monitor**: The daemon is the parent of every shell and monitor task across your pi sessions. If it crashes or is killed with `kill -9`, each task's process group is stopped. Commands that move into a new session with `setsid` escape this.
74
74
  - **Shared capacity**: By default, at most 8 subagents run at once across all pi sessions on the machine (`pi-famulus config set max-agents <n>` changes it). The rest wait in a queue. Subagents labelled `work_kind: "test-suite"` or `"test"` are capped at 2 at a time; without a label, a subagent counts as `other`.
75
75
  - **Parent and subagent talk**: A subagent asks its parent a question with `contact_supervisor` and waits for the answer. You can answer it yourself with `/reply`. `agent_message` sends messages between parent and subagents.
76
- - **Cross-session messaging (pi-famulus)**: pi sessions join the local pi-famulus bridge over the same manager connection — no second socket. `SendMessage` / `ListSessions` tools, `/rename` and the `/intercom` session overlay, `@name` completion inserting `<RequestSendMessage … />` markers, a standing cross-session system-prompt section, `<cross-session-message>` deliver envelopes with read receipts, and authoritative busy/idle publication. Peer messages are input, not authority: they never grant consent. If the bridge is disabled (`PI_FAMULUS_NO_INTERCOM`) the feature stays silent; if it is down, pi-famulus says so once and retries every 3 seconds. Absorbed from the pi-famulus pi plugin (upstream baseline 98183fb); an installed legacy plugin is detected and you are asked to remove it.
76
+ - **Cross-session messaging (pi-famulus)**: pi sessions join the local pi-famulus bridge over the same manager connection — no second socket. `SendMessage` / `ListSessions` tools, `/rename`, `@name` completion inserting `<RequestSendMessage … />` markers, a standing cross-session system-prompt section, `<cross-session-message>` deliver envelopes with read receipts, and authoritative busy/idle publication. Peer messages are input, not authority: they never grant consent. Messaging is off by default: opt in with `messaging.enabled: true` after [registering the device](https://github.com/Leechael/pi-famulus/blob/main/docs/config.md#hosted-server-enrollment). While off (also with `PI_FAMULUS_NO_INTERCOM`), no messaging tools or hooks are registered. If enabled messaging fails, the plugin shows the actual error, including relay authentication failures, and `/famulus` retains the latest error until reconnection. Absorbed from the pi-famulus pi plugin (upstream baseline 98183fb); an installed legacy plugin is detected and you are asked to remove it.
77
77
  - **Inspectable**: In a terminal, `pi-famulus top` is a live dashboard of sessions, subagents, shells and monitors. Open a subagent to read its conversation or a task to read its output, and stop a running shell or monitor from there. `ls`, `show`, `agent` and `events` show what ran, why it ended, and why a notification did or did not arrive.
78
78
  - **Tested against real models**: Tool descriptions are graded on real-model runs. The latest matrix (2026-10-08; 12 xAI and OpenAI configurations, 10 scenarios, k=10) recorded 1198 passes and 2 failures, with 6 invalid or errored episodes excluded ([eval/RESULTS.md](https://github.com/Leechael/pi-famulus/blob/main/eval/RESULTS.md)). It predates a later wording change to the `subagent` and wake prompts ([PR #62](https://github.com/Leechael/pi-famulus/pull/62)), which has not been through the full matrix yet.
79
79
 
@@ -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 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 |
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
 
@@ -90,7 +90,7 @@ Run the full test suite and tell me what fails.
90
90
  | :--- | :--- |
91
91
  | `/tasks` | Live list of shells, monitors and subagents; `ctrl+x` stops the selected item |
92
92
  | `/reply <child> <text>` | Answers a subagent's question without going through the model |
93
- | `/famulus` | Shows binary, manager and configuration information, with a menu to edit `config.json` or reload the extension |
93
+ | `/famulus` | Shows binary, manager, messaging and configuration status, then settings pages for every `config.json` key, a whole-file editor and an extension reload |
94
94
  | Fleet line (the status line below the editor) | Shows the shells, monitors and subagents that are running |
95
95
 
96
96
  **Plan with your strongest model, implement with a cheap one.** Select your strongest model in pi, then save this as `~/.pi/agent/agents/worker.md`:
@@ -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` 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.
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
@@ -140,7 +141,7 @@ pi-famulus starts and stops processes for you. This section states what it guara
140
141
  - **Can a subagent start its own subagents?** No. Nesting is limited to one level.
141
142
  - **What happens to background tasks when pi exits?** Five seconds after the last pi session closes, and once no hosted subagent is still warm, the daemon stops whatever is still running and exits. Read the records afterwards with `pi-famulus show <id>`.
142
143
  - **Does `/reload` stop running work?** No. Shells, monitors and subagents keep running, and their results still arrive. If the reload loads a different pi-famulus version, the old version's work is stopped first.
143
- - **Which binary and versions am I running?** Type `/famulus`. It shows the `pi-famulus` binary path and its version, the running manager's version and pid, the extension version, and the configuration path. Its menu can edit `config.json` and reload the extension.
144
+ - **Which binary and versions am I running?** Type `/famulus`. It shows the `pi-famulus` binary path and its version, the running manager's version and pid, whether messaging is connected to its relay (or local-only) and under which device name, the extension version, and the configuration path. Below that are settings pages (Extension, Subagents, Manager daemon, Messaging) that edit one key at a time and say when each change applies, plus a whole-file editor and an extension reload.
144
145
  - **Why does my pi bash command hang on long builds?** With pi-famulus, `bash` stops waiting after 20 seconds and moves the command to the background, so the turn continues. To change the limit, set `foregroundBudgetMs` in `~/.pi/agent/pi-famulus/config.json` ([configuration](https://github.com/Leechael/pi-famulus/blob/main/docs/configuration.md)).
145
146
  - **How do I see or stop running work?** Type `/tasks` in the pi TUI and press `ctrl+x` on an item. From a terminal, `pi-famulus ls` lists what is running.
146
147
  - **Does it work on Windows?** Yes, on x64 and arm64. The in-place upgrade, where the daemon re-executes itself, works only on Linux and macOS. On Windows, replace the binary and restart the daemon manually. Unless `PI_FAMULUS_SHELL` names another shell, `bash` commands run in Git Bash when Git for Windows is installed, else in a `bash.exe` on `PATH` other than WSL's, else in `cmd.exe` ([configuration](https://github.com/Leechael/pi-famulus/blob/main/docs/configuration.md)). Git Bash's runtime can crash or hang when several copies start at the same moment ([git-for-windows/git#6368](https://github.com/git-for-windows/git/issues/6368)). With a posix shell (anything but `cmd.exe`), pi-famulus staggers shell start-ups to avoid it. A likely start-up crash ends as `shell-start-failed`. A task with no output and no process besides the shell after 20 seconds is stopped as `shell-start-hung`, so a silent command that runs only shell builtins for that long is stopped too. In both cases the agent is told to check for side effects before it retries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-famulus",
3
- "version": "0.2.2-nightly.20261026",
3
+ "version": "0.2.3",
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-nightly.20261026",
58
- "pi-famulus-linux-arm64": "0.2.2-nightly.20261026",
59
- "pi-famulus-darwin-x64": "0.2.2-nightly.20261026",
60
- "pi-famulus-darwin-arm64": "0.2.2-nightly.20261026",
61
- "pi-famulus-win-x64": "0.2.2-nightly.20261026",
62
- "pi-famulus-win-arm64": "0.2.2-nightly.20261026"
57
+ "pi-famulus-linux-x64": "0.2.3",
58
+ "pi-famulus-linux-arm64": "0.2.3",
59
+ "pi-famulus-darwin-x64": "0.2.3",
60
+ "pi-famulus-darwin-arm64": "0.2.3",
61
+ "pi-famulus-win-x64": "0.2.3",
62
+ "pi-famulus-win-arm64": "0.2.3"
63
63
  },
64
64
  "pi": {
65
65
  "extensions": [
package/src/config.ts CHANGED
@@ -17,6 +17,8 @@ export interface FamulusConfig {
17
17
  /** Explicit path to the pi-famulus binary, or null for auto-resolution. */
18
18
  managerPath: string | null;
19
19
  logLevel: "debug" | "info" | "warn" | "error";
20
+ /** Cross-session messaging requires explicit opt-in. */
21
+ messaging?: { enabled: boolean };
20
22
  /** Optional M3 subagent tuning section (design doc §4.6 limits). */
21
23
  subagent?: FamulusSubagentConfig;
22
24
  }
@@ -139,6 +141,7 @@ export const DEFAULT_CONFIG: FamulusConfig = {
139
141
  subagentBudgetMs: 45000,
140
142
  managerPath: null,
141
143
  logLevel: "info",
144
+ messaging: { enabled: false },
142
145
  };
143
146
 
144
147
  /** Resolve the pi-famulus base directory. PI_FAMULUS_HOME overrides the default. */
@@ -210,6 +213,9 @@ export function loadConfig(home: string = getFamulusHome()): FamulusConfig {
210
213
  if (typeof raw !== "object" || raw === null) return { ...DEFAULT_CONFIG };
211
214
  const obj = raw as Record<string, unknown>;
212
215
  const config = { ...DEFAULT_CONFIG };
216
+ if (typeof obj.messaging === "object" && obj.messaging !== null) {
217
+ config.messaging = { enabled: (obj.messaging as Record<string, unknown>).enabled === true };
218
+ }
213
219
  if (typeof obj.foregroundBudgetMs === "number" && obj.foregroundBudgetMs > 0) {
214
220
  config.foregroundBudgetMs = obj.foregroundBudgetMs;
215
221
  }
package/src/format.ts CHANGED
@@ -218,6 +218,49 @@ export function formatMonitorEvent(
218
218
  });
219
219
  }
220
220
 
221
+ /** One short still-running list after compaction (id, description, remaining). */
222
+ export function formatRunningMonitorList(
223
+ items: { id: string; description: string; remaining: string }[],
224
+ ): FormattedWake {
225
+ return formatFamulusWake({ kind: "running-monitors", monitors: items });
226
+ }
227
+
228
+ export const MONITOR_UNWATCHED_SUMMARY =
229
+ "These monitors have stopped; nothing watches their sources now.";
230
+
231
+ export type MonitorTerminalStatus = "timeout" | "exited" | "stopped";
232
+
233
+ export interface MonitorTerminalInfo {
234
+ id: string;
235
+ description: string;
236
+ status: MonitorTerminalStatus;
237
+ event?: string;
238
+ droppedLines?: number;
239
+ output?: MonitorOutputInfo;
240
+ }
241
+
242
+ function terminalDetail(info: MonitorTerminalInfo): string {
243
+ if (info.status === "timeout") return "Timed out.";
244
+ return info.event ?? "";
245
+ }
246
+
247
+ /** One <pi-famulus-wake kind="monitor-terminal"> listing every monitor in the window. */
248
+ export function formatMonitorTerminal(monitors: MonitorTerminalInfo[]): FormattedWake {
249
+ return formatFamulusWake({
250
+ kind: "monitor-terminal",
251
+ ids: monitors.map((monitor) => monitor.id),
252
+ summary: MONITOR_UNWATCHED_SUMMARY,
253
+ monitors: monitors.map((monitor) => ({
254
+ id: monitor.id,
255
+ description: monitor.description,
256
+ status: monitor.status,
257
+ detail: terminalDetail(monitor),
258
+ ...(monitor.droppedLines ? { droppedLines: monitor.droppedLines } : {}),
259
+ ...(monitor.output ? { output: monitor.output } : {}),
260
+ })),
261
+ });
262
+ }
263
+
221
264
  // ---------------------------------------------------------------------------
222
265
  // M3: subagent run completion notification (design doc §4.6)
223
266
  // ---------------------------------------------------------------------------
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";
@@ -26,12 +26,12 @@ import { createAgentMessageTool } from "./comms/tools";
26
26
  import { registerReplyCommand } from "./comms/reply-command";
27
27
  import { describeManagerSearch, getFamulusHome, loadConfig, resolveManagerPath, resolveSubagentConfig, taskOutputPath } from "./config";
28
28
  import { ensureNativeManagerInstalled } from "./native-manager.js";
29
- import type { TaskExitInfo } from "./format";
29
+ import { formatDuration, type TaskExitInfo } from "./format";
30
30
  import { EXTENSION_VERSION, ManagerClient, type ManagerEvent, type TaskRecord } from "./manager-client";
31
31
  import { registerIntercom } from "./intercom/intercom";
32
32
  import { createMonitorTool, exitEventFromRecord, MonitorRegistry } from "./monitor";
33
33
  import { admitAgentChild, reregisterAgentLeases } from "./subagent/admission";
34
- import { NotifyCenter } from "./notify";
34
+ import { attachCompactRecovery, NotifyCenter } from "./notify";
35
35
  import { onWakeMessageEnd, registryStatusLookup } from "./wake-delivery";
36
36
  import { ChildShellTracker, createOverrunNotifier } from "./subagent/overrun";
37
37
  import {
@@ -62,7 +62,7 @@ import { registerFamulusCommand } from "./tui/famulus-command";
62
62
  import { registerFamulusMessageRenderers } from "./tui/message-renderers";
63
63
  import { registerTasksCommand } from "./tui/tasks-command";
64
64
  import { stderrPathFor } from "./tui/task-output-paths";
65
- import { shellWakeTitle } from "./wake";
65
+ import { FAMULUS_WAKE_CUSTOM_TYPE, formatFamulusWake, shellWakeTitle, stampWakeAsOf, wakeIds } from "./wake";
66
66
 
67
67
  async function promptIfHostedSession(
68
68
  c: ManagerClient,
@@ -169,6 +169,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
169
169
  managerPath: string | null;
170
170
  describeSearch: () => string;
171
171
  getClient: () => ManagerClient | null;
172
+ messagingEnabled: boolean;
172
173
  } | null = null;
173
174
  const nativeRestore: Promise<string | null> = managerPath
174
175
  ? Promise.resolve(managerPath)
@@ -383,7 +384,35 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
383
384
  * daemon already ended as manager-shutdown / manager-crash.
384
385
  * A hosted child that is still warm is left for resume.
385
386
  */
386
- const recoverCrashedSession = async (sessionId: string): Promise<void> => {
387
+ const collectNoticedMonitorIds = (file: string | undefined): Set<string> => {
388
+ const ids = new Set<string>();
389
+ if (!file) return ids;
390
+ try {
391
+ for (const entry of SessionManager.open(file).getEntries()) {
392
+ if (entry.type !== "custom_message") continue;
393
+ const custom = entry as { customType?: string; details?: unknown };
394
+ if (custom.customType !== FAMULUS_WAKE_CUSTOM_TYPE) continue;
395
+ const details = custom.details as
396
+ | { kind?: string; ids?: unknown; monitors?: unknown; tasks?: unknown }
397
+ | undefined;
398
+ if (!details || typeof details !== "object") continue;
399
+ if (details.kind === "monitor-session-end") {
400
+ for (const id of wakeIds(details)) ids.add(id);
401
+ } else if (details.kind === "session-recovery") {
402
+ if (Array.isArray(details.monitors)) {
403
+ for (const id of details.monitors) if (typeof id === "string") ids.add(id);
404
+ }
405
+ if (Array.isArray(details.tasks)) {
406
+ for (const id of details.tasks) if (typeof id === "string") ids.add(id);
407
+ }
408
+ }
409
+ }
410
+ } catch {
411
+ return ids;
412
+ }
413
+ return ids;
414
+ };
415
+ const recoverCrashedSession = async (sessionId: string, sessionFile?: string): Promise<void> => {
387
416
  if (!recoverPreviousProcess || !sessionId || recoveredSessions.has(sessionId)) return;
388
417
  const manager = client;
389
418
  const center = notifyCenter;
@@ -398,14 +427,20 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
398
427
  if (!recoverPreviousProcess || client !== manager || notifyCenter !== center) return;
399
428
  killed = tasks.filter((task) => {
400
429
  if (task.session_id && task.session_id !== sessionId) return false;
401
- if (task.kind !== "shell") return false;
402
- return task.end_reason === "manager-shutdown" || task.end_reason === "manager-crash";
430
+ if (task.kind === "shell") {
431
+ return task.end_reason === "manager-shutdown" || task.end_reason === "manager-crash";
432
+ }
433
+ if (task.kind === "monitor") return task.end_reason === "session-end";
434
+ return false;
403
435
  });
404
436
  } catch {
405
437
  killed = [];
406
438
  }
407
439
  }
408
- if (interrupted.length === 0 && killed.length === 0) {
440
+ const noticed = collectNoticedMonitorIds(sessionFile ?? noticeSessionFile);
441
+ const monitors = killed.filter((task) => task.kind === "monitor" && !noticed.has(task.task_id));
442
+ const shells = killed.filter((task) => task.kind === "shell");
443
+ if (interrupted.length === 0 && shells.length === 0 && monitors.length === 0) {
409
444
  recoveredSessions.delete(sessionId);
410
445
  return;
411
446
  }
@@ -417,16 +452,20 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
417
452
  for (const rec of interrupted) {
418
453
  lines.push(`Interrupted subagent ${rec.child_id} (${rec.name}).`);
419
454
  }
420
- for (const task of killed) {
455
+ for (const task of shells) {
421
456
  lines.push(`Command ${task.task_id} ended while the session was gone (${task.end_reason ?? task.status}).`);
422
457
  }
458
+ for (const task of monitors) {
459
+ lines.push(`Monitor ${task.task_id} ended when the session ended (${task.end_reason ?? task.status}).`);
460
+ }
423
461
  center?.notify({
424
- customType: "pi-famulus-wake",
462
+ customType: FAMULUS_WAKE_CUSTOM_TYPE,
425
463
  content: lines.join("\n"),
426
464
  details: {
427
465
  kind: "session-recovery",
428
466
  children: interrupted.map((rec) => rec.child_id),
429
- tasks: killed.map((task) => task.task_id),
467
+ tasks: shells.map((task) => task.task_id),
468
+ monitors: monitors.map((task) => task.task_id),
430
469
  },
431
470
  });
432
471
  };
@@ -592,8 +631,23 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
592
631
  afterStop: () => void syncWithManager(),
593
632
  });
594
633
 
634
+ const compactRecovery = attachCompactRecovery(pi, {
635
+ getCenter: () => notifyCenter,
636
+ getCtx: () => ctx,
637
+ listRunningMonitors: () =>
638
+ (monitorRegistry?.listActive() ?? []).map((mon) => ({
639
+ id: mon.taskId,
640
+ description: mon.description,
641
+ remaining: mon.persistent ? "persistent" : `${formatDuration(mon.remainingMs ?? 0)} remaining`,
642
+ })),
643
+ });
644
+
595
645
  pi.registerTool(createBashOverride(deps));
596
- pi.registerTool(createTaskListTool({ ...deps, getIndex: () => workIndex }));
646
+ pi.registerTool(createTaskListTool({
647
+ ...deps,
648
+ getIndex: () => workIndex,
649
+ getMonitorLive: () => monitorRegistry?.listActive() ?? [],
650
+ }));
597
651
  pi.registerTool(createTaskOutputTool({ ...deps, getIndex: () => workIndex }));
598
652
  pi.registerTool(
599
653
  createTaskStopTool({
@@ -622,6 +676,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
622
676
  managerPath,
623
677
  describeSearch: () => describeManagerSearch(config, home),
624
678
  getClient: () => client,
679
+ messagingEnabled: false,
625
680
  };
626
681
  registerFamulusCommand(pi, famulusInfo);
627
682
  monitorRegistry.onChange(() => {
@@ -731,6 +786,90 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
731
786
 
732
787
  /** Session whose runtime a /reload parked; the reloaded instance's session_start resumes it. */
733
788
  let parkedSessionId: string | null = null;
789
+ /** Old session identity for teardown notices after detach / attach. */
790
+ let noticeSessionId: string | undefined;
791
+ let noticeSessionFile: string | undefined;
792
+ const MONITOR_TEARDOWN_SEND_TIMEOUT_MS = 2_000;
793
+ type MonitorTeardownReason = "new" | "resumed" | "forked" | "handoff-ended" | "session-mismatch";
794
+ const mappedTeardownReason = (reason: string | undefined): MonitorTeardownReason | null => {
795
+ if (reason === "new") return "new";
796
+ if (reason === "resume") return "resumed";
797
+ if (reason === "fork") return "forked";
798
+ if (reason === "session-mismatch") return "session-mismatch";
799
+ return null;
800
+ };
801
+ const emitMonitorTeardownNotice = async (mapped: MonitorTeardownReason, dest: "live" | "file"): Promise<void> => {
802
+ const noticed = collectNoticedMonitorIds(noticeSessionFile);
803
+ const active = (monitorRegistry?.listActive() ?? []).filter((mon) => !noticed.has(mon.taskId));
804
+ if (active.length === 0) return;
805
+ const now = clock.now();
806
+ const sid = noticeSessionId ?? ctx?.sessionManager.getSessionId() ?? "";
807
+ const monitors = active.map((mon) => ({
808
+ id: mon.taskId,
809
+ description: mon.description,
810
+ elapsedMs: Math.max(0, now - mon.startedAt),
811
+ outputPath: workIndex.get(mon.taskId)?.outputPath || taskOutputPath(home, sid, mon.taskId),
812
+ }));
813
+ const formatted = formatFamulusWake({
814
+ kind: "monitor-session-end",
815
+ reason: mapped,
816
+ ids: monitors.map((monitor) => monitor.id),
817
+ monitors,
818
+ });
819
+ const message = stampWakeAsOf(
820
+ { customType: formatted.customType, content: formatted.content, details: formatted.details, display: true },
821
+ now,
822
+ );
823
+ if (dest === "live") {
824
+ let timeout: unknown = null;
825
+ try {
826
+ await Promise.race([
827
+ Promise.resolve(pi.sendMessage(
828
+ { customType: message.customType, content: message.content, display: true, details: message.details },
829
+ { triggerTurn: false },
830
+ )),
831
+ new Promise<never>((_resolve, reject) => {
832
+ timeout = clock.setTimeout(() => reject(new Error("live send timed out")), MONITOR_TEARDOWN_SEND_TIMEOUT_MS);
833
+ if (timeout) clock.unref?.(timeout);
834
+ }),
835
+ ]);
836
+ } catch (error) {
837
+ logEvent("monitor.teardown-fallback", {
838
+ reason: mapped,
839
+ error: error instanceof Error ? error.message : String(error),
840
+ });
841
+ appendWakeToOldSessionFile(message);
842
+ } finally {
843
+ if (timeout !== null) clock.clearTimeout(timeout);
844
+ }
845
+ return;
846
+ }
847
+ appendWakeToOldSessionFile(message);
848
+ };
849
+ const appendWakeToOldSessionFile = (message: { content: string; details?: unknown }): void => {
850
+ const file = noticeSessionFile;
851
+ if (!file) return;
852
+ try {
853
+ SessionManager.open(file).appendCustomMessageEntry(FAMULUS_WAKE_CUSTOM_TYPE, message.content, true, message.details);
854
+ } catch {
855
+ // Missing or unreadable session file: teardown still proceeds.
856
+ }
857
+ };
858
+ const deliverPendingMonitorTerminals = (dest: "live" | "file"): void => {
859
+ const center = notifyCenter;
860
+ if (!center) return;
861
+ if (dest === "live") {
862
+ center.flush();
863
+ return;
864
+ }
865
+ const messages = center.drainPendingMonitorTerminals();
866
+ for (const message of messages) {
867
+ appendWakeToOldSessionFile(stampWakeAsOf(
868
+ { customType: message.customType, content: message.content, details: message.details, display: true },
869
+ clock.now(),
870
+ ));
871
+ }
872
+ };
734
873
  const startFleetWidget = (startCtx: ExtensionContext) => {
735
874
  if (!startCtx.hasUI) return;
736
875
  fleetWidget = new FleetWidget({
@@ -743,6 +882,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
743
882
 
744
883
  pi.on("session_start", async (event, startCtx) => {
745
884
  recoverPreviousProcess = event.reason !== "reload";
885
+ const startFile = startCtx.sessionManager.getSessionFile?.();
746
886
  if (parkedSessionId !== null) {
747
887
  const resumed = event.reason === "reload" && startCtx.sessionManager.getSessionId() === parkedSessionId;
748
888
  parkedSessionId = null;
@@ -750,16 +890,20 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
750
890
  // Same session after /reload: the client, registry and monitors kept
751
891
  // running; only the context and the UI belong to the new instance.
752
892
  ctx = startCtx;
893
+ noticeSessionId = startCtx.sessionManager.getSessionId();
894
+ noticeSessionFile = startFile;
753
895
  binding.ready();
754
896
  startFleetWidget(startCtx);
755
897
  void syncWithManager();
756
898
  return;
757
899
  }
758
900
  binding.discardQueued();
759
- await teardown();
901
+ await teardown({ reason: "session-mismatch", dest: "file" });
760
902
  }
761
903
  await retiring;
762
904
  ctx = startCtx;
905
+ noticeSessionId = startCtx.sessionManager.getSessionId();
906
+ noticeSessionFile = startFile;
763
907
  binding.ready();
764
908
  notifyCenter?.dispose();
765
909
  notifyCenter = new NotifyCenter({
@@ -1176,7 +1320,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1176
1320
  });
1177
1321
  startFleetWidget(startCtx);
1178
1322
  if (client?.isAvailable()) {
1179
- await recoverCrashedSession(startCtx.sessionManager.getSessionId());
1323
+ await recoverCrashedSession(startCtx.sessionManager.getSessionId(), startCtx.sessionManager.getSessionFile?.());
1180
1324
  }
1181
1325
 
1182
1326
  // Connect in the background: a cold manager spawn must not stall the
@@ -1199,7 +1343,7 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1199
1343
  const sid = startCtx.sessionManager.getSessionId();
1200
1344
  void promptIfHostedSession(c, () => ctx, { sessionFile: file, sessionId: sid }, "start").catch(() => {});
1201
1345
  void syncWithManager();
1202
- void recoverCrashedSession(sid);
1346
+ void recoverCrashedSession(sid, file);
1203
1347
  return;
1204
1348
  }
1205
1349
  // A /reload may have replaced startCtx by now; report to the live one.
@@ -1219,7 +1363,10 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1219
1363
  .catch(() => {});
1220
1364
  });
1221
1365
 
1222
- const teardown = async (): Promise<void> => {
1366
+ const teardown = async (notice?: { reason: MonitorTeardownReason; dest: "live" | "file" }): Promise<void> => {
1367
+ if (notice) await emitMonitorTeardownNotice(notice.reason, notice.dest);
1368
+ compactRecovery.dispose();
1369
+ deliverPendingMonitorTerminals(notice?.dest ?? "live");
1223
1370
  exitWatchdog.dispose();
1224
1371
  fleetWidget?.dispose();
1225
1372
  fleetWidget = null;
@@ -1244,7 +1391,16 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1244
1391
  }
1245
1392
  ctx = null;
1246
1393
  };
1247
- const runtime: FamulusRuntime = { attach: (host) => binding.attach(host) };
1394
+ const runtime: FamulusRuntime = {
1395
+ attach: (host) => {
1396
+ const enabled = loadConfig(home).messaging?.enabled === true && process.env.PI_FAMULUS_NO_INTERCOM === undefined;
1397
+ if (famulusInfo) famulusInfo.messagingEnabled = enabled;
1398
+ binding.attach(host);
1399
+ // Messaging is session-scoped, not parked: reload must re-evaluate opt-in
1400
+ // without replacing the manager connection or other background work.
1401
+ registerIntercom(host, { enabled, getClient: () => client });
1402
+ },
1403
+ };
1248
1404
 
1249
1405
  pi.on("session_before_switch", async (event, switchCtx) => {
1250
1406
  const file = event.targetSessionFile;
@@ -1259,11 +1415,17 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1259
1415
  // Keep the session's shells, monitors and subagents running; the
1260
1416
  // reloaded instance adopts this runtime.
1261
1417
  parkedSessionId = ctx.sessionManager.getSessionId();
1418
+ noticeSessionId = parkedSessionId;
1419
+ noticeSessionFile = ctx.sessionManager.getSessionFile?.();
1262
1420
  fleetWidget?.dispose();
1263
1421
  fleetWidget = null;
1264
1422
  ctx = null;
1265
1423
  binding.detach();
1266
- parkRuntime({ version: EXTENSION_VERSION, runtime, dispose: teardown });
1424
+ parkRuntime({
1425
+ version: EXTENSION_VERSION,
1426
+ runtime,
1427
+ dispose: () => teardown({ reason: "handoff-ended", dest: "file" }),
1428
+ });
1267
1429
  return;
1268
1430
  }
1269
1431
  if (String((ctx as { mode?: string } | null)?.mode) === "print") {
@@ -1274,7 +1436,8 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1274
1436
  const warning = printModeDropWarning([...new Set(ids)]);
1275
1437
  if (warning) process.stderr.write(warning);
1276
1438
  }
1277
- await teardown();
1439
+ const mapped = mappedTeardownReason(typeof event.reason === "string" ? event.reason : undefined);
1440
+ await teardown(mapped ? { reason: mapped, dest: "live" } : undefined);
1278
1441
  });
1279
1442
 
1280
1443
  pi.on("agent_settled", async () => {
@@ -1291,11 +1454,5 @@ function createFamulusRuntime(retiring?: Promise<unknown>): FamulusRuntime {
1291
1454
  return message ? { message } : undefined;
1292
1455
  });
1293
1456
 
1294
- // The intercom port (cross-session messaging, absorbed from the
1295
- // pi-famulus pi plugin) rides the same manager connection. Registered
1296
- // after the session hooks above so its session_start sees the fresh
1297
- // client. Hosted children never reach here (child-mode returns early).
1298
- registerIntercom(pi, { getClient: () => client });
1299
-
1300
1457
  return runtime;
1301
1458
  }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Fuzzy matching used by @mention completion and ListSessions filtering.
3
+ *
4
+ * Ported from pi-tui's fuzzy.js so completion behaves like pi's built-in
5
+ * slash-command completion.
6
+ */
7
+
8
+ /**
9
+ * All query characters must appear in order (not necessarily consecutive);
10
+ * lower score = better match.
11
+ */
12
+ export function fuzzyMatch(query: string, text: string): { matches: boolean; score: number } {
13
+ const queryLower = query.toLowerCase();
14
+ const textLower = text.toLowerCase();
15
+ if (queryLower.length === 0) return { matches: true, score: 0 };
16
+ if (queryLower.length > textLower.length) return { matches: false, score: 0 };
17
+ let queryIndex = 0;
18
+ let score = 0;
19
+ let lastMatchIndex = -1;
20
+ let consecutiveMatches = 0;
21
+ for (let i = 0; i < textLower.length && queryIndex < queryLower.length; i++) {
22
+ if (textLower[i] === queryLower[queryIndex]) {
23
+ const isWordBoundary = i === 0 || /[\s\-_./:]/.test(textLower[i - 1]);
24
+ if (lastMatchIndex === i - 1) {
25
+ consecutiveMatches++;
26
+ score -= consecutiveMatches * 5;
27
+ } else {
28
+ consecutiveMatches = 0;
29
+ if (lastMatchIndex >= 0) {
30
+ score += (i - lastMatchIndex - 1) * 2;
31
+ }
32
+ }
33
+ if (isWordBoundary) score -= 10;
34
+ score += i * 0.1;
35
+ lastMatchIndex = i;
36
+ queryIndex++;
37
+ }
38
+ }
39
+ if (queryIndex < queryLower.length) return { matches: false, score: 0 };
40
+ if (queryLower === textLower) score -= 100;
41
+ return { matches: true, score };
42
+ }
43
+
44
+ /** Filter and sort candidates by fuzzy match quality (best matches first). */
45
+ export function fuzzyFilter<T>(items: T[], query: string, getText: (item: T) => string): T[] {
46
+ if (!query.trim()) return items;
47
+ const tokens = query
48
+ .trim()
49
+ .split(/[\s/]+/)
50
+ .filter((t) => t.length > 0);
51
+ if (tokens.length === 0) return items;
52
+ const results: { item: T; totalScore: number }[] = [];
53
+ for (const item of items) {
54
+ const text = getText(item);
55
+ let totalScore = 0;
56
+ let allMatch = true;
57
+ for (const token of tokens) {
58
+ const match = fuzzyMatch(token, text);
59
+ if (match.matches) {
60
+ totalScore += match.score;
61
+ } else {
62
+ allMatch = false;
63
+ break;
64
+ }
65
+ }
66
+ if (allMatch) results.push({ item, totalScore });
67
+ }
68
+ results.sort((a, b) => a.totalScore - b.totalScore);
69
+ return results.map((r) => r.item);
70
+ }