pi-famulus 0.2.2 → 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/src/notify.ts CHANGED
@@ -13,13 +13,61 @@
13
13
  * <pi-famulus-wake kind="task"> payload, and the same task/event pair is only
14
14
  * ever delivered once.
15
15
  */
16
- import { formatMonitorEvent, formatTaskNotification, type TaskExitInfo } from "./format";
16
+ import { formatMonitorEvent, formatMonitorTerminal, formatRunningMonitorList, formatTaskNotification, type MonitorTerminalStatus, type TaskExitInfo } from "./format";
17
17
  import { FAMULUS_WAKE_CUSTOM_TYPE, stampWakeAsOf, wakeIds, type MonitorOutputInfo, type WakeItem } from "./wake";
18
18
  import { realClock, type Clock, type ClockTimer } from "./clock";
19
19
 
20
+ /**
21
+ * Fixed, non-resetting window that coalesces timeout/exited/stopped monitor notices.
22
+ * Nearby expiries share one wake for completeness. A busy agent is already turn-bound,
23
+ * so this adds no extra delay before the next turn. An idle agent with a single exit
24
+ * may wake up to 10s later. The window starts on the first notice and does not reset;
25
+ * NotifyCenter.flush() and session teardown release pending terminals immediately.
26
+ */
27
+ export const MONITOR_TERMINAL_BATCH_MS = 10_000;
28
+
29
+ const TERMINAL_STATUS_RANK: Record<MonitorTerminalStatus, number> = {
30
+ exited: 1,
31
+ stopped: 2,
32
+ timeout: 3,
33
+ };
34
+
20
35
 
21
36
  type MonitorDeliveryAck = (visiblePreview?: string) => void;
22
37
 
38
+ const MONITOR_TERMINAL_STATUSES = new Set<string>(["timeout", "exited", "stopped"]);
39
+
40
+ function isMonitorTerminalStatus(status: string | undefined): status is MonitorTerminalStatus {
41
+ return status !== undefined && MONITOR_TERMINAL_STATUSES.has(status);
42
+ }
43
+
44
+ interface PendingMonitorTerminal {
45
+ id: string;
46
+ description: string;
47
+ status: MonitorTerminalStatus;
48
+ event: string;
49
+ droppedLines?: number;
50
+ output?: MonitorOutputInfo;
51
+ passive: boolean;
52
+ }
53
+
54
+ function mergeTerminal(previous: PendingMonitorTerminal, next: PendingMonitorTerminal): PendingMonitorTerminal {
55
+ const status =
56
+ TERMINAL_STATUS_RANK[next.status] > TERMINAL_STATUS_RANK[previous.status] ? next.status : previous.status;
57
+ const event = (next.event?.length ?? 0) > (previous.event?.length ?? 0) ? next.event : previous.event;
58
+ const description = next.description.length > previous.description.length ? next.description : previous.description;
59
+ const droppedLines = Math.max(previous.droppedLines ?? 0, next.droppedLines ?? 0);
60
+ return {
61
+ id: previous.id,
62
+ description,
63
+ status,
64
+ event,
65
+ ...(droppedLines > 0 ? { droppedLines } : {}),
66
+ output: mergeMonitorOutput(previous.output, next.output),
67
+ passive: previous.passive && next.passive,
68
+ };
69
+ }
70
+
23
71
  export interface NotifyMessage {
24
72
  customType: string;
25
73
  content: string;
@@ -113,10 +161,15 @@ export class NotifyCenter {
113
161
  >();
114
162
  private readonly seen = new Set<string>();
115
163
  private timer: ClockTimer | null = null;
164
+ private pendingTerminals: PendingMonitorTerminal[] = [];
165
+ private terminalTimer: ClockTimer | null = null;
166
+ /** Ids already delivered in a monitor-terminal wake; late duplicates do not open another window. */
167
+ private readonly seenTerminalIds = new Set<string>();
116
168
  private disposed = false;
117
169
  /** A wake started or steered a run that has not settled yet. */
118
170
  private runPending = false;
119
- private held: { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string }[] = [];
171
+ private holdAll = false;
172
+ private held: { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean }[] = [];
120
173
 
121
174
  constructor(deps: NotifyCenterDeps) {
122
175
  this.deps = deps;
@@ -144,14 +197,37 @@ export class NotifyCenter {
144
197
  * Send a notification immediately, routed by idle/busy state. A monitor's
145
198
  * own notice (exit, timeout, stop) first delivers that monitor's coalesced
146
199
  * events: they happened before it, and the model must not hear "exited"
147
- * ahead of the lines the command printed.
200
+ * ahead of the lines the command printed. timeout/exited/stopped notices then
201
+ * join one fixed 10s window rather than each starting a turn.
148
202
  */
149
203
  notify(message: NotifyMessage, opts: { passive?: boolean; quietEvents?: boolean } = {}): void {
150
204
  if (this.disposed) return;
205
+ const wake = message.details as {
206
+ kind?: string;
207
+ id?: string;
208
+ description?: string;
209
+ status?: string;
210
+ event?: string;
211
+ droppedLines?: number;
212
+ output?: MonitorOutputInfo;
213
+ } | undefined;
214
+ if (wake?.kind === "monitor" && typeof wake.id === "string") {
215
+ this.flushMonitor(wake.id, opts.quietEvents);
216
+ if (isMonitorTerminalStatus(wake.status)) {
217
+ this.queueTerminal({
218
+ id: wake.id,
219
+ description: wake.description ?? wake.id,
220
+ status: wake.status,
221
+ event: wake.event ?? "",
222
+ droppedLines: wake.droppedLines,
223
+ output: wake.output,
224
+ passive: opts.passive === true,
225
+ });
226
+ return;
227
+ }
228
+ }
151
229
  // Stamped on arrival: a held passive notice keeps the time it was built.
152
230
  message = stampWakeAsOf(message, this.clock.now());
153
- const wake = message.details as { kind?: string; id?: string } | undefined;
154
- if (wake?.kind === "monitor" && typeof wake.id === "string") this.flushMonitor(wake.id, opts.quietEvents);
155
231
  if (!opts.passive) {
156
232
  this.deliver(message);
157
233
  } else {
@@ -161,7 +237,7 @@ export class NotifyCenter {
161
237
 
162
238
  private deliverPassive(message: NotifyMessage, onDelivered?: MonitorDeliveryAck, sourcePreview?: string): void {
163
239
  message = stampWakeAsOf(message, this.clock.now());
164
- if (this.runPending || !this.deps.isIdle()) this.held.push({ message, onDelivered, sourcePreview });
240
+ if (this.holdAll || this.runPending || !this.deps.isIdle()) this.held.push({ message, onDelivered, sourcePreview, passive: true });
165
241
  else this.deliver(message, true, onDelivered, sourcePreview);
166
242
  }
167
243
 
@@ -175,7 +251,58 @@ export class NotifyCenter {
175
251
  this.runPending = false;
176
252
  this.flushMonitorEvents();
177
253
  if (this.runPending) return;
178
- for (const { message, onDelivered, sourcePreview } of this.held.splice(0)) this.deliver(message, true, onDelivered, sourcePreview);
254
+ for (const item of this.held.splice(0)) {
255
+ this.deliver(item.message, item.passive === true, item.onDelivered, item.sourcePreview);
256
+ }
257
+ }
258
+
259
+ /** Compaction is in progress: do not send; coalesced/held wakes wait for {@link settledAfterCompact}. */
260
+ beginHold(): void {
261
+ if (this.disposed) return;
262
+ this.holdAll = true;
263
+ }
264
+
265
+ endHold(): void {
266
+ this.holdAll = false;
267
+ }
268
+
269
+ /**
270
+ * After compaction has actually gone idle: drain held/pending wakes and an
271
+ * optional passive running-monitor list. If any active wake exists, append
272
+ * the entire batch before the final message starts one turn.
273
+ */
274
+ settledAfterCompact(extra?: NotifyMessage): void {
275
+ if (this.disposed) return;
276
+ this.holdAll = false;
277
+ this.runPending = false;
278
+ const batch: { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean }[] = [];
279
+ for (const taskId of [...this.pendingMonitors.keys()]) {
280
+ const item = this.takeMonitor(taskId);
281
+ if (item) batch.push(item);
282
+ }
283
+ const terminals = this.takePendingTerminals();
284
+ if (terminals.length > 0) {
285
+ const ids = new Set(terminals.map((item) => item.id));
286
+ batch.push(...this.takeHeldMonitorEvents(ids));
287
+ const wake = formatMonitorTerminal(terminals);
288
+ batch.push({
289
+ message: { customType: wake.customType, content: wake.content, details: wake.details },
290
+ passive: terminals.every((item) => item.passive),
291
+ });
292
+ }
293
+ batch.push(...this.held.splice(0));
294
+ if (extra) batch.push({ message: extra, passive: true });
295
+ if (batch.length === 0) return;
296
+ const anyActive = batch.some((item) => !item.passive);
297
+ if (extra && anyActive) {
298
+ const list = batch.pop()!;
299
+ let lastActive = batch.length - 1;
300
+ while (lastActive >= 0 && batch[lastActive].passive) lastActive--;
301
+ batch.splice(lastActive, 0, list);
302
+ }
303
+ for (let i = 0; i < batch.length; i++) {
304
+ this.sendCompactFlush(batch[i], anyActive && i === batch.length - 1);
305
+ }
179
306
  }
180
307
 
181
308
  /**
@@ -194,7 +321,7 @@ export class NotifyCenter {
194
321
  if (pending?.onDelivered && opts.onDelivered && pending.onDelivered !== opts.onDelivered) {
195
322
  throw new Error(`Monitor ${taskId} requires a stable onDelivered callback while pending`);
196
323
  }
197
- if (this.deps.isIdle() && !pending && !opts.quiet) {
324
+ if (this.deps.isIdle() && !this.holdAll && !pending && !opts.quiet) {
198
325
  const wake = formatMonitorEvent(description, taskId, event, undefined, { droppedLines, output: opts.output });
199
326
  this.deliver({ customType: wake.customType, content: wake.content, details: wake.details }, false, opts.onDelivered);
200
327
  return;
@@ -219,8 +346,15 @@ export class NotifyCenter {
219
346
 
220
347
  /** Deliver one monitor's coalesced events, if any, in the current mode. */
221
348
  private flushMonitor(taskId: string, quiet = false): void {
222
- const item = this.pendingMonitors.get(taskId);
349
+ const item = this.takeMonitor(taskId, quiet);
223
350
  if (!item) return;
351
+ if (item.passive) this.deliverPassive(item.message, item.onDelivered, item.sourcePreview);
352
+ else this.deliver(item.message, false, item.onDelivered, item.sourcePreview);
353
+ }
354
+
355
+ private takeMonitor(taskId: string, quiet = false): { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean } | undefined {
356
+ const item = this.pendingMonitors.get(taskId);
357
+ if (!item) return undefined;
224
358
  this.pendingMonitors.delete(taskId);
225
359
  const { head, tail, omittedChars } = item.preview;
226
360
  const preview = omittedChars > 0 ? `${head}\n[... ${omittedChars} characters omitted ...]\n${tail}` : head;
@@ -239,23 +373,133 @@ export class NotifyCenter {
239
373
  tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : "",
240
374
  ].filter(Boolean).join("\n")
241
375
  : head;
242
- if (quiet || item.quiet) this.deliverPassive(message, item.onDelivered, sourcePreview);
243
- else this.deliver(message, false, item.onDelivered, sourcePreview);
376
+ return { message, onDelivered: item.onDelivered, sourcePreview, passive: quiet || item.quiet };
244
377
  }
245
378
 
246
- /** Flush any pending task exit notifications now. */
379
+ /** Flush any pending task exit notifications and monitor-terminal notices now. */
247
380
  flush(): void {
248
381
  this.clearTimer();
249
382
  this.flushExits();
383
+ this.flushAllTerminals();
250
384
  this.flushMonitorEvents();
251
385
  }
252
386
 
387
+ /**
388
+ * Take pending monitor-terminal items without sending through pi.
389
+ * File teardown appends each returned message to the old session file instead.
390
+ * Held output for those terminal ids comes first, in held order; the terminal wake is last.
391
+ * Taking a held output message counts as delivery for its acknowledgement.
392
+ */
393
+ drainPendingMonitorTerminals(): NotifyMessage[] {
394
+ const items = this.takePendingTerminals();
395
+ const ids = new Set(items.map((item) => item.id));
396
+ for (const item of this.held) {
397
+ const details = item.message.details as { kind?: string } | undefined;
398
+ if (details?.kind === "monitor-terminal") {
399
+ for (const id of wakeIds(details)) ids.add(id);
400
+ }
401
+ }
402
+ if (items.length === 0 && ids.size === 0) return [];
403
+ const held = this.takeHeldMonitorEvents(ids, true);
404
+ const messages: NotifyMessage[] = [];
405
+ for (const item of held) {
406
+ messages.push(item.message);
407
+ this.acknowledgeHeld(item);
408
+ }
409
+ if (items.length > 0) {
410
+ const wake = formatMonitorTerminal(items);
411
+ messages.push({ customType: wake.customType, content: wake.content, details: wake.details });
412
+ }
413
+ return messages;
414
+ }
415
+
253
416
  dispose(): void {
254
- this.disposed = true;
417
+ if (this.disposed) return;
255
418
  this.clearTimer();
419
+ this.flushAllTerminals();
420
+ const leftover = this.held.splice(0);
421
+ this.disposed = true;
422
+ this.clearTerminalTimer();
256
423
  this.pendingExits = [];
257
424
  this.pendingMonitors.clear();
258
- this.held = [];
425
+ this.pendingTerminals = [];
426
+ for (const { message, onDelivered, sourcePreview } of leftover) {
427
+ this.deliver(message, true, onDelivered, sourcePreview);
428
+ }
429
+ }
430
+
431
+ private queueTerminal(item: PendingMonitorTerminal): void {
432
+ if (this.seenTerminalIds.has(item.id)) return;
433
+ const existing = this.pendingTerminals.findIndex((pending) => pending.id === item.id);
434
+ if (existing >= 0) {
435
+ this.pendingTerminals[existing] = mergeTerminal(this.pendingTerminals[existing], item);
436
+ return;
437
+ }
438
+ this.pendingTerminals.push(item);
439
+ if (this.terminalTimer !== null) return;
440
+ this.terminalTimer = this.clock.setTimeout(() => {
441
+ this.terminalTimer = null;
442
+ this.flushAllTerminals();
443
+ }, MONITOR_TERMINAL_BATCH_MS);
444
+ this.clock.unref?.(this.terminalTimer);
445
+ }
446
+
447
+ private takePendingTerminals(): PendingMonitorTerminal[] {
448
+ this.clearTerminalTimer();
449
+ const items = this.pendingTerminals;
450
+ this.pendingTerminals = [];
451
+ for (const item of items) this.seenTerminalIds.add(item.id);
452
+ return items;
453
+ }
454
+
455
+ private takeHeldMonitorEvents(ids: Set<string>, includeTerminals = false): typeof this.held {
456
+ if (this.held.length === 0) return [];
457
+ if (ids.size === 0 && !includeTerminals) return [];
458
+ const rest: typeof this.held = [];
459
+ const drain: typeof this.held = [];
460
+ for (const item of this.held) {
461
+ const details = item.message.details as { kind?: string; id?: string } | undefined;
462
+ if (details?.kind === "monitor" && typeof details.id === "string" && ids.has(details.id)) drain.push(item);
463
+ else if (includeTerminals && details?.kind === "monitor-terminal" && wakeIds(details).some((id) => ids.has(id))) drain.push(item);
464
+ else rest.push(item);
465
+ }
466
+ this.held = rest;
467
+ return drain;
468
+ }
469
+
470
+ private acknowledgeHeld(item: (typeof this.held)[number]): void {
471
+ const details = item.message.details as { kind?: string; event?: string } | undefined;
472
+ item.onDelivered?.(item.sourcePreview ?? (details?.kind === "monitor" ? details.event : undefined));
473
+ }
474
+
475
+ private drainHeldMonitorEvents(ids: Set<string>): void {
476
+ for (const { message, onDelivered, sourcePreview } of this.takeHeldMonitorEvents(ids)) {
477
+ this.deliver(message, true, onDelivered, sourcePreview);
478
+ }
479
+ }
480
+
481
+ private flushAllTerminals(): void {
482
+ const items = this.takePendingTerminals();
483
+ if (items.length === 0) return;
484
+ const ids = new Set(items.map((item) => item.id));
485
+ const allPassive = items.every((item) => item.passive);
486
+ const hold = this.runPending || !this.deps.isIdle();
487
+ const wake = formatMonitorTerminal(items);
488
+ const message = { customType: wake.customType, content: wake.content, details: wake.details };
489
+ if (allPassive && hold) {
490
+ this.deliverPassive(message);
491
+ return;
492
+ }
493
+ this.drainHeldMonitorEvents(ids);
494
+ if (allPassive) this.deliverPassive(message);
495
+ else this.deliver(message);
496
+ }
497
+
498
+ private clearTerminalTimer(): void {
499
+ if (this.terminalTimer !== null) {
500
+ this.clock.clearTimeout(this.terminalTimer);
501
+ this.terminalTimer = null;
502
+ }
259
503
  }
260
504
 
261
505
  private scheduleFlush(): void {
@@ -286,9 +530,35 @@ export class NotifyCenter {
286
530
  });
287
531
  }
288
532
 
533
+ private sendCompactFlush(
534
+ item: { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean },
535
+ triggerTurn: boolean,
536
+ ): void {
537
+ const message = stampWakeAsOf(item.message, this.clock.now());
538
+ const msg = { ...message, display: true };
539
+ const details = message.details as { kind?: string; eventCount?: number; event?: string } | undefined;
540
+ if (details?.kind) {
541
+ const ids = wakeIds(details);
542
+ this.deps.logEvent?.("wake.emit", {
543
+ kind: details.kind,
544
+ ids,
545
+ batch: ids.length > 1 || (details.kind === "monitor" && (details.eventCount ?? 0) > 1),
546
+ });
547
+ }
548
+ const mode = triggerTurn ? "trigger" : item.passive ? "passive" : "append";
549
+ this.deps.logEvent?.("wake.deliver", { kind: details?.kind ?? "unknown", mode });
550
+ if (triggerTurn) this.runPending = true;
551
+ this.deps.sendMessage(msg, { triggerTurn });
552
+ item.onDelivered?.(item.sourcePreview ?? (details?.kind === "monitor" ? details.event : undefined));
553
+ }
554
+
289
555
  private deliver(message: NotifyMessage, passive = false, onDelivered?: MonitorDeliveryAck, sourcePreview?: string): void {
290
556
  // Wakes built here (task batches, monitor events) are stamped now.
291
557
  message = stampWakeAsOf(message, this.clock.now());
558
+ if (this.holdAll) {
559
+ this.held.push({ message, onDelivered, sourcePreview, passive });
560
+ return;
561
+ }
292
562
  const msg = { ...message, display: true };
293
563
  const details = message.details as { kind?: string; eventCount?: number } | undefined;
294
564
  if (details?.kind) {
@@ -313,3 +583,147 @@ export class NotifyCenter {
313
583
  }
314
584
 
315
585
  }
586
+
587
+ /** Next-tick idle check with 25ms retry; new run/compaction callers cancel. */
588
+ export function scheduleIdleCheck(opts: {
589
+ isReady: () => boolean;
590
+ onReady: () => void;
591
+ setTimeout?: typeof setTimeout;
592
+ clearTimeout?: typeof clearTimeout;
593
+ }): { cancel: () => void } {
594
+ const start = opts.setTimeout ?? setTimeout;
595
+ const stop = opts.clearTimeout ?? clearTimeout;
596
+ let timer: ReturnType<typeof setTimeout> | undefined;
597
+ let cancelled = false;
598
+ const tick = (delayMs: number) => {
599
+ timer = start(() => {
600
+ timer = undefined;
601
+ if (cancelled) return;
602
+ if (!opts.isReady()) {
603
+ tick(25);
604
+ return;
605
+ }
606
+ opts.onReady();
607
+ }, delayMs);
608
+ timer.unref?.();
609
+ };
610
+ tick(0);
611
+ return {
612
+ cancel() {
613
+ cancelled = true;
614
+ if (timer !== undefined) stop(timer);
615
+ timer = undefined;
616
+ },
617
+ };
618
+ }
619
+
620
+ export function attachCompactRecovery(
621
+ pi: { on(event: string, handler: (event: unknown, ctx: { isIdle(): boolean; hasPendingMessages?: () => boolean }) => unknown): unknown },
622
+ deps: {
623
+ getCenter: () => NotifyCenter | null;
624
+ getCtx: () => { isIdle(): boolean; hasPendingMessages?: () => boolean } | null;
625
+ listRunningMonitors: () => { id: string; description: string; remaining: string }[];
626
+ now?: () => number;
627
+ setTimeout?: typeof setTimeout;
628
+ clearTimeout?: typeof clearTimeout;
629
+ idleHoldMs?: number;
630
+ maxHoldMs?: number;
631
+ },
632
+ ): { dispose: () => void } {
633
+ const idleHoldMs = deps.idleHoldMs ?? 1_000;
634
+ const maxHoldMs = deps.maxHoldMs ?? 600_000;
635
+ const now = deps.now ?? Date.now;
636
+ const startTimer = deps.setTimeout ?? setTimeout;
637
+ const stopTimer = deps.clearTimeout ?? clearTimeout;
638
+ let handle: { cancel: () => void } | undefined;
639
+ let watchdog: { cancel: () => void } | undefined;
640
+ const cancel = () => {
641
+ handle?.cancel();
642
+ handle = undefined;
643
+ watchdog?.cancel();
644
+ watchdog = undefined;
645
+ };
646
+ const flushHeld = () => {
647
+ cancel();
648
+ const center = deps.getCenter();
649
+ if (!center) return;
650
+ const running = deps.listRunningMonitors();
651
+ const extra = running.length > 0 ? formatRunningMonitorList(running) : undefined;
652
+ center.settledAfterCompact(extra);
653
+ };
654
+ const startWatchdog = () => {
655
+ watchdog?.cancel();
656
+ const holdStarted = now();
657
+ let idleSince: number | undefined;
658
+ let timer: ReturnType<typeof setTimeout> | undefined;
659
+ let cancelled = false;
660
+ const tick = () => {
661
+ timer = startTimer(() => {
662
+ timer = undefined;
663
+ if (cancelled) return;
664
+ const t = now();
665
+ if (t - holdStarted >= maxHoldMs) {
666
+ flushHeld();
667
+ return;
668
+ }
669
+ const ctx = deps.getCtx();
670
+ const idle = !!ctx && ctx.isIdle() && ctx.hasPendingMessages?.() !== true;
671
+ if (idle) {
672
+ idleSince ??= t;
673
+ if (t - idleSince >= idleHoldMs) {
674
+ flushHeld();
675
+ return;
676
+ }
677
+ } else {
678
+ idleSince = undefined;
679
+ }
680
+ tick();
681
+ }, 25);
682
+ timer.unref?.();
683
+ };
684
+ tick();
685
+ watchdog = {
686
+ cancel() {
687
+ cancelled = true;
688
+ if (timer !== undefined) stopTimer(timer);
689
+ timer = undefined;
690
+ },
691
+ };
692
+ };
693
+ const afterCompact = () => {
694
+ cancel();
695
+ handle = scheduleIdleCheck({
696
+ isReady: () => {
697
+ const ctx = deps.getCtx();
698
+ return !!ctx && ctx.isIdle() && ctx.hasPendingMessages?.() !== true;
699
+ },
700
+ onReady: () => {
701
+ handle = undefined;
702
+ flushHeld();
703
+ },
704
+ setTimeout: startTimer,
705
+ clearTimeout: stopTimer,
706
+ });
707
+ };
708
+ pi.on("session_before_compact", () => {
709
+ cancel();
710
+ deps.getCenter()?.beginHold();
711
+ startWatchdog();
712
+ });
713
+ pi.on("session_compact", afterCompact);
714
+ pi.on("session_compact_failed", afterCompact);
715
+ pi.on("before_agent_start", () => {
716
+ cancel();
717
+ deps.getCenter()?.endHold();
718
+ });
719
+ pi.on("agent_start", () => {
720
+ cancel();
721
+ deps.getCenter()?.endHold();
722
+ });
723
+ return {
724
+ dispose() {
725
+ cancel();
726
+ deps.getCenter()?.endHold();
727
+ },
728
+ };
729
+ }
@@ -17,7 +17,7 @@ export const PROMPTS = {
17
17
  "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
18
  "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
19
  "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."],
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.","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
21
  "tools.bash.param.command": "The bash command to execute",
22
22
  "tools.bash.param.timeout": "Hard kill timeout in seconds (optional, no default timeout)",
23
23
  "tools.bash.param.run_in_background": "Start the command in the background and return immediately. You will be notified when it completes.",
@@ -34,13 +34,13 @@ export const PROMPTS = {
34
34
  "tools.child.contact_supervisor.snippet": "Ask the parent agent for a decision or report progress",
35
35
  "tools.child.contact_supervisor.param.reason": "\"need_decision\" blocks until the supervisor (parent agent) replies; \"progress_update\" is fire-and-forget.",
36
36
  "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}}",
37
+ "tools.monitor.description": "Start a background monitor process whose stdout lines are injected back to you as <pi-famulus-wake kind=\"monitor\"> messages (batched over 200ms, rate-limited). The command must be line-buffered: each event must be a single line. It must keep running and follow its source, e.g. `tail -n +1 -F file | grep --line-buffered PATTERN`; a command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep to stop after the first match. Silence is not success: print explicit success and terminal failures. Routine unchanged retries may stay silent; do not print a heartbeat on every check. Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll. Repeated Rust-framed lines are suppressed within dedup_window_ms (default 60000); exact matching is the default. Enable ignore-timestamps only when edge ISO timestamps are incidental. Wakes contain bounded head/tail previews and original-byte references; use task_output for missing details, not polling. timeout_ms defaults to 5 minutes (max 1 hour). Expiry ends the monitor; nothing watches the source afterwards, and the timeout notice can arrive late while you are busy. Use persistent:true for long monitoring. If you use timeouts for several monitors, stagger them. Prefer `tail -F` / `journalctl -f` over polling. Write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. {{monitorIdle}}",
38
38
  "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."],
39
+ "tools.monitor.rules": ["Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash.","{{monitorIdle}}","When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation.","Use persistent:true for long monitoring."],
40
40
  "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
41
  "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.",
42
+ "tools.monitor.param.timeout_ms": "Stop the monitor after this many milliseconds (default {{defaultMs}} / 5 minutes, min {{minMs}}, max {{maxMs}} / 1 hour).",
43
+ "tools.monitor.param.persistent": "Keep the monitor alive until the session ends (no timeout). Default false. Use persistent:true for long monitoring.",
44
44
  "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.",
45
45
  "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.",
46
46
  "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}}",
@@ -86,6 +86,7 @@ export const PROMPTS = {
86
86
  "tools.task_stop.param.task_id": "Task id to stop, e.g. sh_a1b2c3d4",
87
87
  "wakes.lead-in": "System wake — not a new user message. Handle this <pi-famulus-wake> before other work.",
88
88
  "wakes.monitor.output-hint": "Read original bytes with task_output using this monitor id and cursor-start, with a bounded max_bytes (for example 8192); next_cursor continues the read. The range may include interleaved events. A preview is not the full log.",
89
+ "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
90
  "wakes.handover.changed-active": "Its result arrives as a new wake when it finishes.",
90
91
  "wakes.done.changed-active": "The run is active again; another subagent-done arrives when it finishes.",
91
92
  "wakes.overrun.summary": "{{name}} has run {{elapsed}} in this turn, past its {{budget}} budget, and is still running{{shell}}.",
@@ -170,6 +171,11 @@ export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string;
170
171
  "tooldesc.monitor-follow": {"prompt":"tools.monitor.description","text":"It must keep running and follow its source, e.g. `tail -n +1 -F file | grep --line-buffered PATTERN`; a command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep to stop after the first match. "},
171
172
  "tooldesc.monitor-silence": {"prompt":"tools.monitor.description","text":"Silence is not success: print explicit success and terminal failures. Routine unchanged retries may stay silent; do not print a heartbeat on every check. "},
172
173
  "tooldesc.monitor-wake": {"prompt":"tools.monitor.description","text":"Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll."},
174
+ "tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"timeout_ms defaults to 5 minutes (max 1 hour). Expiry ends the monitor; nothing watches the source afterwards, and the timeout notice can arrive late while you are busy. "},
175
+ "tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"Use persistent:true for long monitoring. "},
176
+ "tooldesc.monitor-stagger": {"prompt":"tools.monitor.description","text":"If you use timeouts for several monitors, stagger them. "},
177
+ "tooldesc.monitor-edge": {"prompt":"tools.monitor.description","text":"Write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. "},
178
+ "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
179
  "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
180
  "rules.monitor-wake": {"prompt":"tools.monitor.rules","text":"When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation."},
175
181
  "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."},
package/src/task-tools.ts CHANGED
@@ -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<{ taskId: string; remainingMs: number | null; persistent: boolean; lastOutputAt?: number }>;
32
34
  }
33
35
 
34
36
  function requireClient(deps: TaskToolsDeps): Promise<ManagerClient> {
@@ -71,6 +73,16 @@ 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
+ function formatMonitorLive(
77
+ live: { remainingMs: number | null; persistent: boolean; lastOutputAt?: number },
78
+ now: number,
79
+ ): string {
80
+ const timeout = live.persistent ? "persistent" : `timeout in ${formatAge(now, now + (live.remainingMs ?? 0), now)}`;
81
+ const last =
82
+ live.lastOutputAt === undefined ? "no output yet" : `last output ${formatAge(live.lastOutputAt, undefined, now)} ago`;
83
+ return ` ${timeout}; ${last}`;
84
+ }
85
+
74
86
  function formatTaskLine(task: TaskRecord, now: number): string {
75
87
  const exit =
76
88
  task.status === "running"
@@ -114,6 +126,8 @@ export function createTaskListTool(
114
126
  const lines: string[] = [];
115
127
  const seen = new Set<string>();
116
128
  let running = false;
129
+ const monitorLive = new Map<string, { remainingMs: number | null; persistent: boolean; lastOutputAt?: number }>();
130
+ for (const live of deps.getMonitorLive?.() ?? []) monitorLive.set(live.taskId, live);
117
131
 
118
132
  const pushItem = (item: WorkItem) => {
119
133
  if (seen.has(item.id)) return;
@@ -121,7 +135,12 @@ export function createTaskListTool(
121
135
  seen.add(item.id);
122
136
  const age = formatAge(item.startedAt, item.endedAt, now);
123
137
  running ||= item.status === "running" || item.status === "pending";
124
- lines.push(`${item.id} [${item.kind}] ${item.status} (${age}) "${item.title}"`);
138
+ let line = `${item.id} [${item.kind}] ${item.status} (${age}) "${item.title}"`;
139
+ if (item.kind === "monitor") {
140
+ const live = monitorLive.get(item.id);
141
+ if (live) line += formatMonitorLive(live, now);
142
+ }
143
+ lines.push(line);
125
144
  };
126
145
 
127
146
  if (index) {