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/monitor.ts CHANGED
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Starts a long-lived `kind:"monitor"` process via pi-famulus, watches its
5
5
  * output stream, and injects line batches as <pi-famulus-wake kind="monitor"> messages.
6
- * Batching (LineBatcher) and throttling (RateLimiter) happen extension-side;
7
- * a monitor is stopped when at least half its batches are dropped in a rolling
8
- * 30-second window.
6
+ * Batching (LineBatcher) and throttling (RateLimiter) happen extension-side.
7
+ * Sustained drop-ratio or a rolling input line-rate enters summary mode (not stop).
8
+ * Auto-stop is only the unverified ~1000 lines/s for 60s safety backstop.
9
9
  */
10
10
  import { Type } from "typebox";
11
11
  import { shellStartStatus } from "./shell-start";
@@ -17,7 +17,18 @@ import { realClock, type Clock, type ClockTimer } from "./clock";
17
17
  import type { ManagerClient, ManagerEvent, MonitorOutputRecord, TaskRecord } from "./manager-client";
18
18
  import { DEFAULT_DEDUP_WINDOW_MS, MonitorOutputBuffer, mergeOutputInfo, type FingerprintMode } from "./monitor-output";
19
19
  import type { MonitorOutputInfo } from "./wake";
20
- import { LineBatcher, RateLimiter, SaturationWindow } from "./monitor-batching";
20
+ import {
21
+ LineBatcher,
22
+ RateLimiter,
23
+ OverloadController,
24
+ LegacyLineAssembler,
25
+ OVERLOAD_SUMMARY_LINES_PER_SEC,
26
+ OVERLOAD_WINDOW_MS,
27
+ SUMMARY_CADENCE_MS,
28
+ type OverloadControllerOptions,
29
+ type OverloadEnterReason,
30
+ type OverloadSummaryOutput,
31
+ } from "./monitor-batching";
21
32
  import type { NotifyCenter } from "./notify";
22
33
  import { fill, fillList, PROMPTS } from "./prompts.generated";
23
34
  import { statusGlyph, toolComponent } from "./tui/tool-component";
@@ -27,10 +38,6 @@ import type { WorkIndex } from "./work-index";
27
38
  const DEFAULT_TIMEOUT_MS = 300_000;
28
39
  const MIN_TIMEOUT_MS = 1_000;
29
40
  const MAX_TIMEOUT_MS = 3_600_000;
30
- /** Rolling-window drop ratio required before a monitor is auto-stopped. */
31
- const SATURATION_WINDOW_MS = 30_000;
32
- const SATURATION_DROP_RATIO = 0.5;
33
- const SATURATION_MIN_BATCHES = 10;
34
41
  /**
35
42
  * A clean exit this soon after an event was caused by it (`grep -m1`). Its
36
43
  * notice is appended without starting a turn: as a wake it cost every such monitor a
@@ -72,6 +79,8 @@ export interface MonitorDeps {
72
79
  * with its exit event lost, in which case no further event will settle it.
73
80
  */
74
81
  afterStop?: () => void;
82
+ /** Optional overload-policy overrides for tests. Production uses draft constants. */
83
+ overload?: Partial<OverloadControllerOptions>;
75
84
  }
76
85
 
77
86
  interface MonitorEntry {
@@ -84,14 +93,19 @@ interface MonitorEntry {
84
93
  recordCursor: number;
85
94
  lastRecordKind?: "line" | "progress";
86
95
  limiter: RateLimiter;
87
- saturation: SaturationWindow;
96
+ overload: OverloadController;
97
+ legacyLines: LegacyLineAssembler;
88
98
  droppedLinesPending: number;
89
99
  timeoutTimer: ClockTimer | null;
100
+ /** Epoch ms when the extension-side timeout fires; null when persistent. */
101
+ timeoutDeadlineAt: number | null;
90
102
  stopped: boolean;
91
103
  cursor: number;
92
104
  recovering: boolean;
93
105
  queuedOutput: { chunk: string; cursor?: number; records?: MonitorOutputRecord[] }[];
94
106
  lastEventAt?: number;
107
+ /** Last accepted line or newline-completed raw chunk, including later-deduped/rate-limited output. */
108
+ lastOutputAt?: number;
95
109
  /** The model asked to stop it (task_stop): what is left is not news. */
96
110
  stopRequested?: boolean;
97
111
  /** Prevents autoStop from re-entering while it drains the 200ms batcher. */
@@ -116,11 +130,20 @@ export class MonitorRegistry {
116
130
  return () => this.changeListeners.delete(cb);
117
131
  }
118
132
 
119
- /** Active monitors for the fleet status surface. */
120
- listActive(): { taskId: string; description: string; startedAt: number }[] {
133
+ /** Active monitors for the fleet status surface and task_list extras. */
134
+ listActive(): { taskId: string; description: string; startedAt: number; remainingMs: number | null; persistent: boolean; lastEventAt?: number; lastOutputAt?: number }[] {
135
+ const now = this.clock.now();
121
136
  return [...this.entries.values()]
122
137
  .filter((e) => !e.stopped)
123
- .map((e) => ({ taskId: e.taskId, description: e.description, startedAt: e.startedAt }))
138
+ .map((e) => ({
139
+ taskId: e.taskId,
140
+ description: e.description,
141
+ startedAt: e.startedAt,
142
+ persistent: e.timeoutDeadlineAt === null,
143
+ remainingMs: e.timeoutDeadlineAt === null ? null : Math.max(0, e.timeoutDeadlineAt - now),
144
+ lastEventAt: e.lastEventAt,
145
+ lastOutputAt: e.lastOutputAt,
146
+ }))
124
147
  .sort((a, b) => a.startedAt - b.startedAt);
125
148
  }
126
149
 
@@ -174,27 +197,33 @@ export class MonitorRegistry {
174
197
  this.deps.trackTask(task_id, { kind: "monitor", command: params.command, cwd: ctx.cwd });
175
198
  this.deps.logEvent?.("monitor.start", { id: task_id, description: params.description });
176
199
 
200
+ const now = this.clock.now();
177
201
  const entry: MonitorEntry = {
178
202
  taskId: task_id,
179
203
  description: params.description,
180
- startedAt: this.clock.now(),
204
+ startedAt: now,
181
205
  batcher: null as unknown as LineBatcher, // assigned below (self-reference in callback)
182
206
  output: null as unknown as MonitorOutputBuffer,
183
207
  legacyOutput: {},
184
208
  recordCursor: -1,
185
209
  limiter: new RateLimiter({ clock: this.clock }),
186
- saturation: new SaturationWindow({
187
- windowMs: SATURATION_WINDOW_MS,
188
- dropRatio: SATURATION_DROP_RATIO,
189
- minimumBatches: SATURATION_MIN_BATCHES,
190
- }),
210
+ overload: null as unknown as OverloadController,
211
+ legacyLines: new LegacyLineAssembler(),
191
212
  droppedLinesPending: 0,
192
213
  timeoutTimer: null,
214
+ timeoutDeadlineAt: timeoutMs === null ? null : now + timeoutMs,
193
215
  stopped: false,
194
216
  cursor: 0,
195
217
  recovering: false,
196
218
  queuedOutput: [],
197
219
  };
220
+ entry.overload = new OverloadController({
221
+ clock: this.clock,
222
+ ...this.deps.overload,
223
+ onSummary: (text, output) => this.emitOverloadNotice(entry, text, output),
224
+ onEnter: (reason) => this.emitOverloadNotice(entry, this.enterNotice(reason)),
225
+ onExit: () => this.emitOverloadNotice(entry, "[Monitor overload: leaving summary mode. Individual lines resume.]"),
226
+ });
198
227
  entry.batcher = new LineBatcher({
199
228
  onFlush: (text, info) => {
200
229
  const output = mergeOutputInfo(entry.legacyOutput, info);
@@ -267,24 +296,58 @@ export class MonitorRegistry {
267
296
  if (records !== undefined) {
268
297
  // Empty metadata arrays deliberately hold raw fragments for Rust framing.
269
298
  entry.batcher.flush();
299
+ const accepted: MonitorOutputRecord[] = [];
300
+ let metadataTookOver = false;
270
301
  for (const record of records) {
271
302
  if (!validRecord(record, entry.cursor)) continue;
272
303
  if (record.cursor_end < entry.recordCursor || (record.cursor_end === entry.recordCursor && !(entry.lastRecordKind === "progress" && record.kind === "line"))) continue;
304
+ metadataTookOver = true;
273
305
  entry.recordCursor = record.cursor_end;
274
306
  entry.lastRecordKind = record.kind;
307
+ if (record.kind === "line") entry.lastOutputAt = this.clock.now();
275
308
  entry.output.push(record);
309
+ if (record.kind === "line") accepted.push(record);
310
+ }
311
+ if (metadataTookOver) entry.legacyLines.reset();
312
+ if (accepted.length > 0) {
313
+ this.noteInput(entry, {
314
+ lines: accepted.length,
315
+ bytes: accepted.reduce((n, r) => n + (r.cursor_end - r.cursor_start), 0),
316
+ text: accepted.map((r) => r.preview).join("\n"),
317
+ cursorStart: Math.min(...accepted.map((r) => r.cursor_start)),
318
+ cursorEnd: Math.max(...accepted.map((r) => r.cursor_end)),
319
+ });
276
320
  }
277
321
  } else if (deliver.byteLength > 0) {
278
322
  // Legacy manager or unavailable replay metadata: fail open, never hash in JS.
279
323
  entry.output.flush();
324
+ const cursorStart = Math.max(previousCursor, entry.cursor - deliver.byteLength);
325
+ const text = deliver.toString("utf8");
326
+ if (text.includes("\n")) entry.lastOutputAt = this.clock.now();
280
327
  entry.legacyOutput = mergeOutputInfo(entry.legacyOutput, {
281
328
  firstObservedAt: this.clock.now(), lastObservedAt: this.clock.now(),
282
- cursorStart: Math.max(previousCursor, entry.cursor - deliver.byteLength), cursorEnd: entry.cursor,
329
+ cursorStart, cursorEnd: entry.cursor,
283
330
  });
284
- entry.batcher.push(deliver.toString("utf8"));
331
+ const assembled = entry.legacyLines.push(text, deliver.byteLength, cursorStart, entry.cursor);
332
+ if (assembled) {
333
+ this.noteInput(entry, {
334
+ lines: assembled.lines,
335
+ bytes: assembled.bytes,
336
+ text: assembled.text ?? "",
337
+ cursorStart: assembled.cursorStart ?? cursorStart,
338
+ cursorEnd: assembled.cursorEnd ?? entry.cursor,
339
+ });
340
+ }
341
+ entry.batcher.push(text);
285
342
  }
286
343
  }
287
344
 
345
+ /** Count complete raw lines/chunks before limiter (includes later-deduped lines). */
346
+ private noteInput(entry: MonitorEntry, input: { lines: number; bytes: number; text: string; cursorStart: number; cursorEnd: number }): void {
347
+ entry.overload.recordInput(input);
348
+ if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) void this.autoStop(entry);
349
+ }
350
+
288
351
  /**
289
352
  * task_stop is about to stop this monitor at the model's request. Returns
290
353
  * an undo for a stop that fails: the monitor keeps running and must keep
@@ -314,6 +377,7 @@ export class MonitorRegistry {
314
377
  entry.batcher.flush();
315
378
  entry.output.flush();
316
379
  const alreadyStopped = entry.stopped;
380
+ if (!alreadyStopped && !entry.stopRequested) entry.overload.flushSummary();
317
381
  this.cleanup(entry);
318
382
  this.deps.onExited?.(taskId, event);
319
383
  if (alreadyStopped) return true; // timeout/saturation owns the pending summary
@@ -395,22 +459,49 @@ export class MonitorRegistry {
395
459
  this.early.clear();
396
460
  }
397
461
 
462
+ private enterNotice(reason: OverloadEnterReason): string {
463
+ const windowMs = this.deps.overload?.windowMs ?? OVERLOAD_WINDOW_MS;
464
+ const cadenceMs = this.deps.overload?.cadenceMs?.[0] ?? SUMMARY_CADENCE_MS[0];
465
+ const linesPerSec = this.deps.overload?.summaryLinesPerSec ?? OVERLOAD_SUMMARY_LINES_PER_SEC;
466
+ const windowSecs = Math.round(windowMs / 1000);
467
+ const why = reason === "drop-ratio"
468
+ ? `drop-ratio ≥50% over ${windowSecs}s`
469
+ : reason === "line-rate"
470
+ ? `input >${linesPerSec} lines/s over ${windowSecs}s`
471
+ : `drop-ratio ≥50% over ${windowSecs}s and input >${linesPerSec} lines/s`;
472
+ return `[Monitor overload: entering summary mode (${why}). Individual lines are suppressed. First summary after ${Math.round(cadenceMs / 1000)}s. Raw output via task_output.]`;
473
+ }
474
+
475
+ private emitOverloadNotice(entry: MonitorEntry, text: string, output?: OverloadSummaryOutput): void {
476
+ if (entry.stopped || entry.stopRequested) return;
477
+ const center = this.deps.getNotifyCenter();
478
+ if (!center) return;
479
+ center.notifyMonitorEvent(entry.description, entry.taskId, text, 0, output ? { output } : {});
480
+ entry.lastEventAt = this.clock.now();
481
+ }
482
+
398
483
  private onBatch(entry: MonitorEntry, text: string, output?: MonitorOutputInfo, onDelivered?: () => void): boolean {
399
484
  if (entry.stopped) return false;
400
485
  const center = this.deps.getNotifyCenter();
401
486
  if (!center) return false;
402
487
  const now = this.clock.now();
488
+ if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) {
489
+ void this.autoStop(entry);
490
+ return false;
491
+ }
403
492
  const accepted = entry.limiter.tryConsume();
404
- entry.saturation.record(!accepted, now);
493
+ entry.overload.recordBatch(!accepted);
494
+ if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) {
495
+ void this.autoStop(entry);
496
+ return false;
497
+ }
405
498
  if (!accepted) {
406
499
  const droppedLines = text.split("\n").length;
407
500
  this.deps.logEvent?.("monitor.drop", { id: entry.taskId, lines: droppedLines });
408
501
  entry.droppedLinesPending += droppedLines;
409
- // Already stopping at the model's request, or draining for autoStop:
410
- // no nested rate-limit stop or wake.
411
- if (entry.saturation.isSaturated(now) && !entry.stopRequested && !entry.stopping) void this.autoStop(entry);
412
- return false;
413
502
  }
503
+ if (entry.overload.inSummary()) return false;
504
+ if (!accepted) return false;
414
505
  const droppedLines = entry.droppedLinesPending;
415
506
  entry.droppedLinesPending = 0;
416
507
  entry.lastEventAt = now;
@@ -430,6 +521,7 @@ export class MonitorRegistry {
430
521
  entry.batcher.flush();
431
522
  entry.output.flush();
432
523
  if (entry.stopped) return; // A flush may already have tripped overload protection.
524
+ entry.overload.flushSummary();
433
525
  entry.stopped = true;
434
526
  this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "timeout" });
435
527
  const client = this.deps.getClient();
@@ -438,24 +530,24 @@ export class MonitorRegistry {
438
530
  formatMonitorEvent(
439
531
  entry.description,
440
532
  entry.taskId,
441
- "[Monitor timed out — re-arm if needed.]",
442
-
533
+ "Timed out.",
443
534
  "timeout",
444
535
  { droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
445
536
  ),
446
537
  );
447
- this.deps.toast?.(`Monitor "${entry.description}" timed out — re-arm if needed.`, "warning");
538
+ this.deps.toast?.(`Monitor "${entry.description}" timed out; nothing watches this source now.`, "warning");
448
539
  this.cleanup(entry);
449
540
  this.deps.afterStop?.();
450
541
  }
451
542
 
452
- /** Rate limiter saturated for too long: stop and notify (§4.4). */
543
+ /** Extreme sustained input rate: stop and notify (unverified safety backstop). */
453
544
  private async autoStop(entry: MonitorEntry): Promise<void> {
454
545
  if (entry.stopped || entry.stopping) return;
455
546
  entry.stopping = true;
456
547
  entry.batcher.flush();
457
548
  entry.output.flush();
458
549
  if (entry.stopped) return;
550
+ entry.overload.flushSummary();
459
551
  entry.stopped = true;
460
552
  this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "rate-limit" });
461
553
  const client = this.deps.getClient();
@@ -464,14 +556,13 @@ export class MonitorRegistry {
464
556
  formatMonitorEvent(
465
557
  entry.description,
466
558
  entry.taskId,
467
- "[Monitor stopped: at least half of output batches were dropped in the last 30s.]",
468
-
559
+ entry.overload.stopNotice(),
469
560
  "stopped",
470
561
  { droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
471
562
  ),
472
563
  );
473
564
  this.deps.toast?.(
474
- `Monitor "${entry.description}" stopped — too much output (rate limit).`,
565
+ `Monitor "${entry.description}" stopped — input rate safety backstop.`,
475
566
  "warning",
476
567
  );
477
568
  this.cleanup(entry);
@@ -483,6 +574,7 @@ export class MonitorRegistry {
483
574
  entry.batcher.dispose();
484
575
  entry.output.dispose();
485
576
  entry.limiter.dispose();
577
+ entry.overload.dispose();
486
578
  if (entry.timeoutTimer !== null) {
487
579
  this.clock.clearTimeout(entry.timeoutTimer);
488
580
  entry.timeoutTimer = null;