pi-famulus 0.2.3 → 0.2.5
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 +2 -2
- package/package.json +7 -7
- package/src/config.ts +12 -0
- package/src/format.ts +33 -5
- package/src/idle-turn-guard.ts +118 -0
- package/src/index.ts +18 -0
- package/src/intercom/intercom.ts +4 -47
- package/src/intercom/surface.ts +57 -0
- package/src/manager-client.ts +17 -3
- package/src/monitor-batching.ts +33 -9
- package/src/monitor.ts +178 -17
- package/src/notify.ts +42 -5
- package/src/poll-guard.ts +96 -0
- package/src/prompts.generated.ts +39 -15
- package/src/task-tools.ts +34 -15
- package/src/tui/message-renderers.ts +3 -3
- package/src/wait-guard.ts +68 -0
- package/src/wake.ts +14 -3
package/src/monitor-batching.ts
CHANGED
|
@@ -273,6 +273,16 @@ export class LegacyLineAssembler {
|
|
|
273
273
|
this.start = undefined;
|
|
274
274
|
}
|
|
275
275
|
|
|
276
|
+
/** Hand over the retained unterminated line (the monitor exited) and forget it. */
|
|
277
|
+
drainPartial(): OverloadInput | undefined {
|
|
278
|
+
const start = this.start;
|
|
279
|
+
const partial = start === undefined || this.bytes === 0
|
|
280
|
+
? undefined
|
|
281
|
+
: { lines: 1, bytes: this.bytes, text: this.text, cursorStart: start, cursorEnd: start + this.bytes };
|
|
282
|
+
this.reset();
|
|
283
|
+
return partial;
|
|
284
|
+
}
|
|
285
|
+
|
|
276
286
|
push(chunk: string, chunkBytes: number, cursorStart: number, cursorEnd: number): OverloadInput | undefined {
|
|
277
287
|
if (chunk.length === 0 && chunkBytes === 0) return undefined;
|
|
278
288
|
if (this.start !== undefined && cursorStart !== this.start + this.bytes) this.reset();
|
|
@@ -395,6 +405,8 @@ export interface OverloadInput {
|
|
|
395
405
|
* INPUT (line-rate / stop / interval bytes) is complete raw records (`kind:"line"`)
|
|
396
406
|
* or newline-terminated chunks counted in acceptOutput, before the token bucket.
|
|
397
407
|
* Later-deduped lines still count as input; dedup does not consume tokens or the drop budget.
|
|
408
|
+
* Lines a wake_on filter keeps from waking count only toward the stop backstop
|
|
409
|
+
* (recordFilteredLines): it protects CPU, disk and the task log, not the wake budget.
|
|
398
410
|
* Interval signature stats begin at summary-mode entry (line-rate trigger included;
|
|
399
411
|
* drop-ratio entry starts empty), then reset on each emitted summary.
|
|
400
412
|
*/
|
|
@@ -412,7 +424,10 @@ export class OverloadController {
|
|
|
412
424
|
private readonly onEnter?: OverloadControllerOptions["onEnter"];
|
|
413
425
|
private readonly onExit?: OverloadControllerOptions["onExit"];
|
|
414
426
|
private readonly saturation: SaturationWindow;
|
|
427
|
+
/** Admitted input: summary-mode line rate. */
|
|
415
428
|
private readonly lineBuckets: { sec: number; n: number; firstAt: number }[] = [];
|
|
429
|
+
/** Every output line, admitted or filtered out: the stop backstop. */
|
|
430
|
+
private readonly stopBuckets: { sec: number; n: number; firstAt: number }[] = [];
|
|
416
431
|
private signatures = new Map<string, { count: number; extra: number }>();
|
|
417
432
|
private previousSigs = new Set<string>();
|
|
418
433
|
private sigSeq = 0;
|
|
@@ -456,14 +471,17 @@ export class OverloadController {
|
|
|
456
471
|
|
|
457
472
|
stopNotice(): string {
|
|
458
473
|
const secs = Math.round(this.stopSustainMs / 1000);
|
|
459
|
-
return `[Monitor
|
|
474
|
+
return `[Monitor protection threshold reached: input exceeded ~${this.stopLinesPerSec} lines/s for ${secs}s (unverified safety backstop).]`;
|
|
460
475
|
}
|
|
461
476
|
|
|
462
477
|
recordInput(input: OverloadInput): void {
|
|
463
478
|
if (this.disposed) return;
|
|
464
479
|
const now = this.clock.now();
|
|
465
480
|
const lines = Math.max(0, input.lines);
|
|
466
|
-
if (lines > 0)
|
|
481
|
+
if (lines > 0) {
|
|
482
|
+
this.addLineBucket(this.lineBuckets, lines, now);
|
|
483
|
+
this.addLineBucket(this.stopBuckets, lines, now);
|
|
484
|
+
}
|
|
467
485
|
const wasSummary = this.summaryMode;
|
|
468
486
|
if (wasSummary) {
|
|
469
487
|
if (lines > 0 || input.bytes > 0) this.addInterval(input, now);
|
|
@@ -478,6 +496,12 @@ export class OverloadController {
|
|
|
478
496
|
this.evaluateExit(now);
|
|
479
497
|
}
|
|
480
498
|
|
|
499
|
+
/** Lines kept from waking by a filter: they feed only the stop backstop. */
|
|
500
|
+
recordFilteredLines(lines: number): void {
|
|
501
|
+
if (this.disposed || lines <= 0) return;
|
|
502
|
+
this.addLineBucket(this.stopBuckets, lines, this.clock.now());
|
|
503
|
+
}
|
|
504
|
+
|
|
481
505
|
recordBatch(dropped: boolean): void {
|
|
482
506
|
if (this.disposed) return;
|
|
483
507
|
const now = this.clock.now();
|
|
@@ -586,20 +610,20 @@ export class OverloadController {
|
|
|
586
610
|
this.onSummary?.(text, output);
|
|
587
611
|
}
|
|
588
612
|
|
|
589
|
-
private addLineBucket(n: number, now: number): void {
|
|
590
|
-
if (this.firstInputAt === undefined) this.firstInputAt = now;
|
|
613
|
+
private addLineBucket(buckets: { sec: number; n: number; firstAt: number }[], n: number, now: number): void {
|
|
614
|
+
if (buckets === this.lineBuckets && this.firstInputAt === undefined) this.firstInputAt = now;
|
|
591
615
|
const sec = Math.floor(now / 1000);
|
|
592
|
-
const last =
|
|
616
|
+
const last = buckets[buckets.length - 1];
|
|
593
617
|
if (last && last.sec === sec) {
|
|
594
618
|
const wasBelowStop = last.n < this.stopLinesPerSec;
|
|
595
619
|
last.n += n;
|
|
596
620
|
// Earlier low-rate input in this second is not the start of the flood.
|
|
597
621
|
if (wasBelowStop && last.n >= this.stopLinesPerSec) last.firstAt = now;
|
|
598
622
|
} else {
|
|
599
|
-
|
|
623
|
+
buckets.push({ sec, n, firstAt: now });
|
|
600
624
|
}
|
|
601
625
|
const cutoffSec = Math.floor((now - Math.max(this.windowMs, this.stopSustainMs)) / 1000) - 1;
|
|
602
|
-
while (
|
|
626
|
+
while (buckets.length > 0 && buckets[0].sec < cutoffSec) buckets.shift();
|
|
603
627
|
}
|
|
604
628
|
|
|
605
629
|
/** Average over the last `window` completed seconds; the current partial second is excluded. */
|
|
@@ -630,8 +654,8 @@ export class OverloadController {
|
|
|
630
654
|
let i = 0;
|
|
631
655
|
let runFirstAt: number | undefined;
|
|
632
656
|
for (let sec = from; sec <= to; sec++) {
|
|
633
|
-
while (i < this.
|
|
634
|
-
const bucket = this.
|
|
657
|
+
while (i < this.stopBuckets.length && this.stopBuckets[i].sec < sec) i++;
|
|
658
|
+
const bucket = this.stopBuckets[i];
|
|
635
659
|
if (!bucket || bucket.sec !== sec || bucket.n < this.stopLinesPerSec) return false;
|
|
636
660
|
if (runFirstAt === undefined) runFirstAt = bucket.firstAt;
|
|
637
661
|
}
|
package/src/monitor.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import { Type } from "typebox";
|
|
11
11
|
import { shellStartStatus } from "./shell-start";
|
|
12
12
|
import type { ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
13
|
-
import { formatMonitorEvent } from "./format";
|
|
13
|
+
import { formatDuration, formatExitFacts, formatMonitorEvent } from "./format";
|
|
14
14
|
import { MONITOR_IDLE_INSTRUCTION } from "./behavior-guidelines";
|
|
15
15
|
import { realClock, type Clock, type ClockTimer } from "./clock";
|
|
16
16
|
|
|
@@ -22,11 +22,13 @@ import {
|
|
|
22
22
|
RateLimiter,
|
|
23
23
|
OverloadController,
|
|
24
24
|
LegacyLineAssembler,
|
|
25
|
+
LEGACY_PARTIAL_MAX_CHARS,
|
|
25
26
|
OVERLOAD_SUMMARY_LINES_PER_SEC,
|
|
26
27
|
OVERLOAD_WINDOW_MS,
|
|
27
28
|
SUMMARY_CADENCE_MS,
|
|
28
29
|
type OverloadControllerOptions,
|
|
29
30
|
type OverloadEnterReason,
|
|
31
|
+
type OverloadInput,
|
|
30
32
|
type OverloadSummaryOutput,
|
|
31
33
|
} from "./monitor-batching";
|
|
32
34
|
import type { NotifyCenter } from "./notify";
|
|
@@ -38,6 +40,9 @@ import type { WorkIndex } from "./work-index";
|
|
|
38
40
|
const DEFAULT_TIMEOUT_MS = 300_000;
|
|
39
41
|
const MIN_TIMEOUT_MS = 1_000;
|
|
40
42
|
const MAX_TIMEOUT_MS = 3_600_000;
|
|
43
|
+
/** stall_after_ms bounds: shorter than 10s is a heartbeat; a day is the longest useful silence. */
|
|
44
|
+
const MIN_STALL_MS = 10_000;
|
|
45
|
+
const MAX_STALL_MS = 86_400_000;
|
|
41
46
|
/**
|
|
42
47
|
* A clean exit this soon after an event was caused by it (`grep -m1`). Its
|
|
43
48
|
* notice is appended without starting a turn: as a wake it cost every such monitor a
|
|
@@ -110,6 +115,17 @@ interface MonitorEntry {
|
|
|
110
115
|
stopRequested?: boolean;
|
|
111
116
|
/** Prevents autoStop from re-entering while it drains the 200ms batcher. */
|
|
112
117
|
stopping?: boolean;
|
|
118
|
+
/**
|
|
119
|
+
* wake_on: only lines matching it reach the batchers, dedup, overload
|
|
120
|
+
* accounting and wakes. Every line stays in the manager's task log.
|
|
121
|
+
*/
|
|
122
|
+
wakeOn: RegExp | null;
|
|
123
|
+
stallAfterMs: number | null;
|
|
124
|
+
stallTimer: ClockTimer | null;
|
|
125
|
+
/** Last new output (any line or progress record, matching wake_on or not). */
|
|
126
|
+
lastActivityAt: number;
|
|
127
|
+
/** The stall notice went out; the next output re-arms it. */
|
|
128
|
+
stallNotified: boolean;
|
|
113
129
|
}
|
|
114
130
|
|
|
115
131
|
export class MonitorRegistry {
|
|
@@ -131,7 +147,7 @@ export class MonitorRegistry {
|
|
|
131
147
|
}
|
|
132
148
|
|
|
133
149
|
/** 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 }[] {
|
|
150
|
+
listActive(): { taskId: string; description: string; startedAt: number; remainingMs: number | null; persistent: boolean; lastEventAt?: number; lastOutputAt?: number; wakeOn?: string; stallAfterMs?: number }[] {
|
|
135
151
|
const now = this.clock.now();
|
|
136
152
|
return [...this.entries.values()]
|
|
137
153
|
.filter((e) => !e.stopped)
|
|
@@ -143,6 +159,8 @@ export class MonitorRegistry {
|
|
|
143
159
|
remainingMs: e.timeoutDeadlineAt === null ? null : Math.max(0, e.timeoutDeadlineAt - now),
|
|
144
160
|
lastEventAt: e.lastEventAt,
|
|
145
161
|
lastOutputAt: e.lastOutputAt,
|
|
162
|
+
...(e.wakeOn ? { wakeOn: e.wakeOn.source } : {}),
|
|
163
|
+
...(e.stallAfterMs !== null ? { stallAfterMs: e.stallAfterMs } : {}),
|
|
146
164
|
}))
|
|
147
165
|
.sort((a, b) => a.startedAt - b.startedAt);
|
|
148
166
|
}
|
|
@@ -163,7 +181,7 @@ export class MonitorRegistry {
|
|
|
163
181
|
|
|
164
182
|
/** Start a monitor process and subscribe to its output stream. */
|
|
165
183
|
async start(
|
|
166
|
-
params: { command: string; description: string; timeout_ms?: number; persistent?: boolean; dedup_window_ms?: number; fingerprint_mode?: FingerprintMode },
|
|
184
|
+
params: { command: string; description: string; timeout_ms?: number; persistent?: boolean; dedup_window_ms?: number; fingerprint_mode?: FingerprintMode; wake_on?: string; stall_after_ms?: number },
|
|
167
185
|
ctx: ExtensionContext,
|
|
168
186
|
): Promise<{ taskId: string; timeoutMs: number | null }> {
|
|
169
187
|
const client = this.deps.getClient();
|
|
@@ -177,7 +195,29 @@ export class MonitorRegistry {
|
|
|
177
195
|
if (params.fingerprint_mode !== undefined && params.fingerprint_mode !== "exact" && params.fingerprint_mode !== "ignore-timestamps") {
|
|
178
196
|
throw new RangeError("fingerprint_mode must be exact or ignore-timestamps");
|
|
179
197
|
}
|
|
180
|
-
|
|
198
|
+
if (params.persistent === true && params.timeout_ms !== undefined) {
|
|
199
|
+
throw new RangeError("timeout_ms and persistent are exclusive: use timeout_ms for a watch that ends within 1 hour, persistent:true for an open-ended or longer watch");
|
|
200
|
+
}
|
|
201
|
+
if (params.timeout_ms !== undefined && params.timeout_ms > MAX_TIMEOUT_MS) {
|
|
202
|
+
throw new RangeError("timeout_ms exceeds the 1-hour maximum; for longer watches use persistent:true instead of re-arming");
|
|
203
|
+
}
|
|
204
|
+
let wakeOn: RegExp | null = null;
|
|
205
|
+
if (params.wake_on !== undefined) {
|
|
206
|
+
if (typeof params.wake_on !== "string" || params.wake_on.length === 0) {
|
|
207
|
+
throw new RangeError("wake_on must be a non-empty regular expression source");
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
wakeOn = new RegExp(params.wake_on);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
throw new RangeError(`wake_on is not a valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (params.stall_after_ms !== undefined && (!Number.isSafeInteger(params.stall_after_ms) || params.stall_after_ms < MIN_STALL_MS || params.stall_after_ms > MAX_STALL_MS)) {
|
|
216
|
+
throw new RangeError(`stall_after_ms must be an integer between ${MIN_STALL_MS} and ${MAX_STALL_MS}`);
|
|
217
|
+
}
|
|
218
|
+
// No lifetime given: run until the command exits or the monitor is stopped.
|
|
219
|
+
// persistent:false without timeout_ms keeps the 5-minute default.
|
|
220
|
+
const persistent = params.persistent === true || (params.persistent !== false && params.timeout_ms === undefined);
|
|
181
221
|
let timeoutMs: number | null = null;
|
|
182
222
|
if (!persistent) {
|
|
183
223
|
const requested = params.timeout_ms ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -216,6 +256,11 @@ export class MonitorRegistry {
|
|
|
216
256
|
cursor: 0,
|
|
217
257
|
recovering: false,
|
|
218
258
|
queuedOutput: [],
|
|
259
|
+
wakeOn,
|
|
260
|
+
stallAfterMs: params.stall_after_ms ?? null,
|
|
261
|
+
stallTimer: null,
|
|
262
|
+
lastActivityAt: now,
|
|
263
|
+
stallNotified: false,
|
|
219
264
|
};
|
|
220
265
|
entry.overload = new OverloadController({
|
|
221
266
|
clock: this.clock,
|
|
@@ -245,6 +290,7 @@ export class MonitorRegistry {
|
|
|
245
290
|
}, timeoutMs);
|
|
246
291
|
this.clock.unref?.(entry.timeoutTimer);
|
|
247
292
|
}
|
|
293
|
+
if (entry.stallAfterMs !== null) this.armStall(entry, entry.stallAfterMs);
|
|
248
294
|
this.entries.set(task_id, entry);
|
|
249
295
|
this.emitChange();
|
|
250
296
|
// Replay what arrived before we knew the id: lines first, then the exit.
|
|
@@ -297,6 +343,7 @@ export class MonitorRegistry {
|
|
|
297
343
|
// Empty metadata arrays deliberately hold raw fragments for Rust framing.
|
|
298
344
|
entry.batcher.flush();
|
|
299
345
|
const accepted: MonitorOutputRecord[] = [];
|
|
346
|
+
let filteredLines = 0;
|
|
300
347
|
let metadataTookOver = false;
|
|
301
348
|
for (const record of records) {
|
|
302
349
|
if (!validRecord(record, entry.cursor)) continue;
|
|
@@ -305,10 +352,18 @@ export class MonitorRegistry {
|
|
|
305
352
|
entry.recordCursor = record.cursor_end;
|
|
306
353
|
entry.lastRecordKind = record.kind;
|
|
307
354
|
if (record.kind === "line") entry.lastOutputAt = this.clock.now();
|
|
355
|
+
this.noteActivity(entry);
|
|
356
|
+
// Filtered-out records reach neither dedup nor wake accounting,
|
|
357
|
+
// only the stop backstop.
|
|
358
|
+
if (!admits(entry, record.preview)) {
|
|
359
|
+
if (record.kind === "line") filteredLines++;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
308
362
|
entry.output.push(record);
|
|
309
363
|
if (record.kind === "line") accepted.push(record);
|
|
310
364
|
}
|
|
311
365
|
if (metadataTookOver) entry.legacyLines.reset();
|
|
366
|
+
this.noteFilteredLines(entry, filteredLines);
|
|
312
367
|
if (accepted.length > 0) {
|
|
313
368
|
this.noteInput(entry, {
|
|
314
369
|
lines: accepted.length,
|
|
@@ -323,12 +378,21 @@ export class MonitorRegistry {
|
|
|
323
378
|
entry.output.flush();
|
|
324
379
|
const cursorStart = Math.max(previousCursor, entry.cursor - deliver.byteLength);
|
|
325
380
|
const text = deliver.toString("utf8");
|
|
326
|
-
if (text.includes("\n"))
|
|
381
|
+
if (text.includes("\n")) {
|
|
382
|
+
entry.lastOutputAt = this.clock.now();
|
|
383
|
+
this.noteActivity(entry);
|
|
384
|
+
}
|
|
385
|
+
const assembled = entry.legacyLines.push(text, deliver.byteLength, cursorStart, entry.cursor);
|
|
386
|
+
if (entry.wakeOn) {
|
|
387
|
+
// Raw chunks are filtered per completed line; a trailing fragment
|
|
388
|
+
// waits for its newline (or the exit).
|
|
389
|
+
if (assembled) this.admitLegacyLines(entry, assembled);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
327
392
|
entry.legacyOutput = mergeOutputInfo(entry.legacyOutput, {
|
|
328
393
|
firstObservedAt: this.clock.now(), lastObservedAt: this.clock.now(),
|
|
329
394
|
cursorStart, cursorEnd: entry.cursor,
|
|
330
395
|
});
|
|
331
|
-
const assembled = entry.legacyLines.push(text, deliver.byteLength, cursorStart, entry.cursor);
|
|
332
396
|
if (assembled) {
|
|
333
397
|
this.noteInput(entry, {
|
|
334
398
|
lines: assembled.lines,
|
|
@@ -342,6 +406,68 @@ export class MonitorRegistry {
|
|
|
342
406
|
}
|
|
343
407
|
}
|
|
344
408
|
|
|
409
|
+
/** wake_on on the raw path: pass only matching completed lines on to overload accounting and the batcher. */
|
|
410
|
+
private admitLegacyLines(entry: MonitorEntry, assembled: OverloadInput): void {
|
|
411
|
+
const all = (assembled.text ?? "").split("\n");
|
|
412
|
+
const lines = all.filter((line) => admits(entry, line));
|
|
413
|
+
this.noteFilteredLines(entry, all.length - lines.length);
|
|
414
|
+
if (lines.length === 0) return;
|
|
415
|
+
const now = this.clock.now();
|
|
416
|
+
entry.legacyOutput = mergeOutputInfo(entry.legacyOutput, {
|
|
417
|
+
firstObservedAt: now, lastObservedAt: now,
|
|
418
|
+
cursorStart: assembled.cursorStart, cursorEnd: assembled.cursorEnd,
|
|
419
|
+
// The assembler keeps at most LEGACY_PARTIAL_MAX_CHARS of a line.
|
|
420
|
+
truncated: lines.some((line) => line.length >= LEGACY_PARTIAL_MAX_CHARS),
|
|
421
|
+
});
|
|
422
|
+
this.noteInput(entry, {
|
|
423
|
+
lines: lines.length,
|
|
424
|
+
bytes: lines.reduce((n, line) => n + Buffer.byteLength(line) + 1, 0),
|
|
425
|
+
text: lines.join("\n"),
|
|
426
|
+
cursorStart: assembled.cursorStart ?? entry.cursor,
|
|
427
|
+
cursorEnd: assembled.cursorEnd ?? entry.cursor,
|
|
428
|
+
});
|
|
429
|
+
entry.batcher.push(lines.map((line) => `${line}\n`).join(""));
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Any new output proves the source is alive: re-arm a stall notice that already went out. */
|
|
433
|
+
private noteActivity(entry: MonitorEntry): void {
|
|
434
|
+
entry.lastActivityAt = this.clock.now();
|
|
435
|
+
if (entry.stallAfterMs !== null && entry.stallNotified) {
|
|
436
|
+
entry.stallNotified = false;
|
|
437
|
+
this.armStall(entry, entry.stallAfterMs);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
private armStall(entry: MonitorEntry, delayMs: number): void {
|
|
442
|
+
if (entry.stallTimer !== null) this.clock.clearTimeout(entry.stallTimer);
|
|
443
|
+
entry.stallTimer = this.clock.setTimeout(() => this.onStallDue(entry), delayMs);
|
|
444
|
+
this.clock.unref?.(entry.stallTimer);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** One timer per monitor, re-checked lazily, so output never touches timers. */
|
|
448
|
+
private onStallDue(entry: MonitorEntry): void {
|
|
449
|
+
entry.stallTimer = null;
|
|
450
|
+
if (entry.stopped || entry.stallAfterMs === null) return;
|
|
451
|
+
const idle = this.clock.now() - entry.lastActivityAt;
|
|
452
|
+
if (idle < entry.stallAfterMs) {
|
|
453
|
+
this.armStall(entry, entry.stallAfterMs - idle);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
entry.stallNotified = true;
|
|
457
|
+
if (entry.stopRequested || entry.stopping) return;
|
|
458
|
+
const center = this.deps.getNotifyCenter();
|
|
459
|
+
if (!center) return;
|
|
460
|
+
this.deps.logEvent?.("monitor.stall", { id: entry.taskId, idleMs: idle });
|
|
461
|
+
center.notifyMonitorEvent(entry.description, entry.taskId, fill("tools.monitor.event.stalled", { idle: formatDuration(idle) }), 0, {});
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Lines wake_on kept from waking still count toward the input-rate stop backstop. */
|
|
465
|
+
private noteFilteredLines(entry: MonitorEntry, lines: number): void {
|
|
466
|
+
if (lines <= 0) return;
|
|
467
|
+
entry.overload.recordFilteredLines(lines);
|
|
468
|
+
if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) void this.autoStop(entry);
|
|
469
|
+
}
|
|
470
|
+
|
|
345
471
|
/** Count complete raw lines/chunks before limiter (includes later-deduped lines). */
|
|
346
472
|
private noteInput(entry: MonitorEntry, input: { lines: number; bytes: number; text: string; cursorStart: number; cursorEnd: number }): void {
|
|
347
473
|
entry.overload.recordInput(input);
|
|
@@ -373,7 +499,12 @@ export class MonitorRegistry {
|
|
|
373
499
|
this.earlyFor(taskId).exit = event;
|
|
374
500
|
return false;
|
|
375
501
|
}
|
|
376
|
-
// Drain remaining buffered lines before closing out.
|
|
502
|
+
// Drain remaining buffered lines before closing out. Unfiltered raw
|
|
503
|
+
// output already holds the trailing fragment in the batcher.
|
|
504
|
+
if (entry.wakeOn) {
|
|
505
|
+
const partial = entry.legacyLines.drainPartial();
|
|
506
|
+
if (partial) this.admitLegacyLines(entry, partial);
|
|
507
|
+
}
|
|
377
508
|
entry.batcher.flush();
|
|
378
509
|
entry.output.flush();
|
|
379
510
|
const alreadyStopped = entry.stopped;
|
|
@@ -393,19 +524,27 @@ export class MonitorRegistry {
|
|
|
393
524
|
this.clock.now() - entry.lastEventAt <= EXIT_AFTER_EVENT_MS;
|
|
394
525
|
const duration =
|
|
395
526
|
typeof event.duration_ms === "number" ? `${(event.duration_ms / 1000).toFixed(1)}s` : "unknown duration";
|
|
396
|
-
|
|
527
|
+
const facts = {
|
|
528
|
+
...(event.end_reason ? { endReason: event.end_reason } : {}),
|
|
529
|
+
...(event.signal ? { signal: event.signal } : {}),
|
|
530
|
+
exitCode,
|
|
531
|
+
...(entry.stopRequested ? { stopRequested: true } : {}),
|
|
532
|
+
};
|
|
533
|
+
const exitContext = `After ${duration}.${startFailureNote(event.end_reason)} No further events will be delivered.${entry.droppedLinesPending > 0 ? ` ${entry.droppedLinesPending} output lines were dropped.` : ""}`;
|
|
534
|
+
const detail = `${formatExitFacts(facts)} ${exitContext}`;
|
|
535
|
+
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: event.end_reason ?? "unknown" });
|
|
397
536
|
this.deps.getNotifyCenter()?.notify(
|
|
398
537
|
formatMonitorEvent(
|
|
399
538
|
entry.description,
|
|
400
539
|
entry.taskId,
|
|
401
|
-
|
|
540
|
+
detail,
|
|
402
541
|
"exited",
|
|
403
|
-
{ droppedLines: entry.droppedLinesPending, ...(summary.suppressedCount ? { output: summary } : {}) },
|
|
542
|
+
{ droppedLines: entry.droppedLinesPending, exitFacts: facts, exitContext, ...(summary.suppressedCount ? { output: summary } : {}) },
|
|
404
543
|
),
|
|
405
544
|
{ passive: causedByEvent || entry.stopRequested === true, quietEvents: entry.stopRequested === true },
|
|
406
545
|
);
|
|
407
546
|
this.deps.toast?.(
|
|
408
|
-
`Monitor "${entry.description}"
|
|
547
|
+
`Monitor "${entry.description}": ${detail}`,
|
|
409
548
|
exitCode === 0 || exitCode === null ? "info" : "warning",
|
|
410
549
|
);
|
|
411
550
|
return true;
|
|
@@ -525,17 +664,20 @@ export class MonitorRegistry {
|
|
|
525
664
|
entry.stopped = true;
|
|
526
665
|
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "timeout" });
|
|
527
666
|
const client = this.deps.getClient();
|
|
528
|
-
|
|
667
|
+
let stopFailed = false;
|
|
668
|
+
let stopError: unknown;
|
|
669
|
+
if (client) await client.stop(entry.taskId, "timeout").catch((error: unknown) => { stopFailed = true; stopError = error; });
|
|
670
|
+
const stopDetail = stopFailed ? `Stop request failed: ${String(stopError)}. Exit unconfirmed.` : client ? "Stop requested; exit unconfirmed." : "Stop request unavailable; exit unconfirmed.";
|
|
529
671
|
this.deps.getNotifyCenter()?.notify(
|
|
530
672
|
formatMonitorEvent(
|
|
531
673
|
entry.description,
|
|
532
674
|
entry.taskId,
|
|
533
|
-
|
|
675
|
+
`Timeout elapsed. ${stopDetail}`,
|
|
534
676
|
"timeout",
|
|
535
677
|
{ droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
|
|
536
678
|
),
|
|
537
679
|
);
|
|
538
|
-
this.deps.toast?.(`Monitor "${entry.description}"
|
|
680
|
+
this.deps.toast?.(`Monitor "${entry.description}": timeout elapsed. ${stopDetail}`, "warning");
|
|
539
681
|
this.cleanup(entry);
|
|
540
682
|
this.deps.afterStop?.();
|
|
541
683
|
}
|
|
@@ -551,18 +693,21 @@ export class MonitorRegistry {
|
|
|
551
693
|
entry.stopped = true;
|
|
552
694
|
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "rate-limit" });
|
|
553
695
|
const client = this.deps.getClient();
|
|
554
|
-
|
|
696
|
+
let stopFailed = false;
|
|
697
|
+
let stopError: unknown;
|
|
698
|
+
if (client) await client.stop(entry.taskId, "rate-limit").catch((error: unknown) => { stopFailed = true; stopError = error; });
|
|
699
|
+
const stopDetail = stopFailed ? `Stop request failed: ${String(stopError)}. Exit unconfirmed.` : client ? "Stop requested; exit unconfirmed." : "Stop request unavailable; exit unconfirmed.";
|
|
555
700
|
this.deps.getNotifyCenter()?.notify(
|
|
556
701
|
formatMonitorEvent(
|
|
557
702
|
entry.description,
|
|
558
703
|
entry.taskId,
|
|
559
|
-
entry.overload.stopNotice()
|
|
704
|
+
`${entry.overload.stopNotice()} ${stopDetail}`,
|
|
560
705
|
"stopped",
|
|
561
706
|
{ droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
|
|
562
707
|
),
|
|
563
708
|
);
|
|
564
709
|
this.deps.toast?.(
|
|
565
|
-
`Monitor "${entry.description}"
|
|
710
|
+
`Monitor "${entry.description}": input rate safety backstop. ${stopDetail}`,
|
|
566
711
|
"warning",
|
|
567
712
|
);
|
|
568
713
|
this.cleanup(entry);
|
|
@@ -579,11 +724,19 @@ export class MonitorRegistry {
|
|
|
579
724
|
this.clock.clearTimeout(entry.timeoutTimer);
|
|
580
725
|
entry.timeoutTimer = null;
|
|
581
726
|
}
|
|
727
|
+
if (entry.stallTimer !== null) {
|
|
728
|
+
this.clock.clearTimeout(entry.stallTimer);
|
|
729
|
+
entry.stallTimer = null;
|
|
730
|
+
}
|
|
582
731
|
this.entries.delete(entry.taskId);
|
|
583
732
|
this.emitChange();
|
|
584
733
|
}
|
|
585
734
|
}
|
|
586
735
|
|
|
736
|
+
function admits(entry: MonitorEntry, line: string): boolean {
|
|
737
|
+
return entry.wakeOn === null || entry.wakeOn.test(line);
|
|
738
|
+
}
|
|
739
|
+
|
|
587
740
|
function validRecord(record: MonitorOutputRecord, cursor: number): boolean {
|
|
588
741
|
return record?.version === 1 && (record.kind === "line" || record.kind === "progress") &&
|
|
589
742
|
typeof record.preview === "string" && record.preview.length <= 2000 &&
|
|
@@ -629,6 +782,14 @@ const monitorParameters = Type.Object({
|
|
|
629
782
|
persistent: Type.Optional(Type.Boolean({ description: PROMPTS["tools.monitor.param.persistent"] })),
|
|
630
783
|
dedup_window_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 3_600_000, description: PROMPTS["tools.monitor.param.dedup_window_ms"] })),
|
|
631
784
|
fingerprint_mode: Type.Optional(Type.Union([Type.Literal("exact"), Type.Literal("ignore-timestamps")], { description: PROMPTS["tools.monitor.param.fingerprint_mode"] })),
|
|
785
|
+
wake_on: Type.Optional(Type.String({ minLength: 1, description: PROMPTS["tools.monitor.param.wake_on"] })),
|
|
786
|
+
stall_after_ms: Type.Optional(
|
|
787
|
+
Type.Integer({
|
|
788
|
+
minimum: MIN_STALL_MS,
|
|
789
|
+
maximum: MAX_STALL_MS,
|
|
790
|
+
description: fill("tools.monitor.param.stall_after_ms", { minMs: MIN_STALL_MS, maxMs: MAX_STALL_MS }),
|
|
791
|
+
}),
|
|
792
|
+
),
|
|
632
793
|
});
|
|
633
794
|
|
|
634
795
|
export function createMonitorTool(
|
package/src/notify.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
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, formatMonitorTerminal, formatRunningMonitorList, formatTaskNotification, type MonitorTerminalStatus, type TaskExitInfo } from "./format";
|
|
16
|
+
import { formatExitFacts, 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
|
|
|
@@ -48,13 +48,42 @@ interface PendingMonitorTerminal {
|
|
|
48
48
|
event: string;
|
|
49
49
|
droppedLines?: number;
|
|
50
50
|
output?: MonitorOutputInfo;
|
|
51
|
+
exitFacts?: import("./wake").MonitorExitFacts;
|
|
52
|
+
exitContext?: string;
|
|
51
53
|
passive: boolean;
|
|
52
54
|
}
|
|
53
55
|
|
|
54
|
-
function mergeTerminal(previous: PendingMonitorTerminal, next: PendingMonitorTerminal): PendingMonitorTerminal {
|
|
56
|
+
function mergeTerminal(previous: PendingMonitorTerminal, next: PendingMonitorTerminal, onConflict: (fields: string[]) => void): PendingMonitorTerminal {
|
|
55
57
|
const status =
|
|
56
58
|
TERMINAL_STATUS_RANK[next.status] > TERMINAL_STATUS_RANK[previous.status] ? next.status : previous.status;
|
|
57
|
-
const
|
|
59
|
+
const hasFacts = (facts: PendingMonitorTerminal["exitFacts"]) => !!facts &&
|
|
60
|
+
(facts.endReason !== undefined || facts.signal !== undefined || facts.exitCode !== undefined || facts.stopRequested === true);
|
|
61
|
+
const previousKnown = hasFacts(previous.exitFacts);
|
|
62
|
+
const nextKnown = hasFacts(next.exitFacts);
|
|
63
|
+
const chosen = previousKnown ? previous : nextKnown ? next : next.event.length > previous.event.length ? next : previous;
|
|
64
|
+
const other = chosen === next ? previous : next;
|
|
65
|
+
const a = chosen.exitFacts;
|
|
66
|
+
const b = other.exitFacts;
|
|
67
|
+
const conflicts: string[] = [];
|
|
68
|
+
if (a && b) {
|
|
69
|
+
if (a.endReason !== undefined && b.endReason !== undefined && a.endReason !== b.endReason) conflicts.push("endReason");
|
|
70
|
+
if (a.signal !== undefined && b.signal !== undefined && a.signal !== b.signal) conflicts.push("signal");
|
|
71
|
+
if (a.exitCode != null && b.exitCode != null && a.exitCode !== b.exitCode) conflicts.push("exitCode");
|
|
72
|
+
}
|
|
73
|
+
const conflict = conflicts.length > 0;
|
|
74
|
+
if (conflict) onConflict(conflicts);
|
|
75
|
+
const exitFacts = a && b && !conflict ? {
|
|
76
|
+
...b,
|
|
77
|
+
...a,
|
|
78
|
+
...(a.endReason === undefined && b.endReason !== undefined ? { endReason: b.endReason } : {}),
|
|
79
|
+
...(a.signal === undefined && b.signal !== undefined ? { signal: b.signal } : {}),
|
|
80
|
+
...(a.exitCode == null && b.exitCode != null ? { exitCode: b.exitCode } : {}),
|
|
81
|
+
...(a.stopRequested === true || b.stopRequested === true ? { stopRequested: true } : {}),
|
|
82
|
+
} : a;
|
|
83
|
+
const exitContext = chosen.exitContext ?? (!conflict ? other.exitContext : undefined);
|
|
84
|
+
const event = previousKnown && nextKnown && !conflict && exitFacts
|
|
85
|
+
? `${formatExitFacts(exitFacts)}${exitContext ? ` ${exitContext}` : ""}`
|
|
86
|
+
: chosen.event;
|
|
58
87
|
const description = next.description.length > previous.description.length ? next.description : previous.description;
|
|
59
88
|
const droppedLines = Math.max(previous.droppedLines ?? 0, next.droppedLines ?? 0);
|
|
60
89
|
return {
|
|
@@ -64,6 +93,8 @@ function mergeTerminal(previous: PendingMonitorTerminal, next: PendingMonitorTer
|
|
|
64
93
|
event,
|
|
65
94
|
...(droppedLines > 0 ? { droppedLines } : {}),
|
|
66
95
|
output: mergeMonitorOutput(previous.output, next.output),
|
|
96
|
+
exitFacts,
|
|
97
|
+
exitContext,
|
|
67
98
|
passive: previous.passive && next.passive,
|
|
68
99
|
};
|
|
69
100
|
}
|
|
@@ -210,6 +241,8 @@ export class NotifyCenter {
|
|
|
210
241
|
event?: string;
|
|
211
242
|
droppedLines?: number;
|
|
212
243
|
output?: MonitorOutputInfo;
|
|
244
|
+
exitFacts?: import("./wake").MonitorExitFacts;
|
|
245
|
+
exitContext?: string;
|
|
213
246
|
} | undefined;
|
|
214
247
|
if (wake?.kind === "monitor" && typeof wake.id === "string") {
|
|
215
248
|
this.flushMonitor(wake.id, opts.quietEvents);
|
|
@@ -221,6 +254,8 @@ export class NotifyCenter {
|
|
|
221
254
|
event: wake.event ?? "",
|
|
222
255
|
droppedLines: wake.droppedLines,
|
|
223
256
|
output: wake.output,
|
|
257
|
+
exitFacts: wake.exitFacts,
|
|
258
|
+
exitContext: wake.exitContext,
|
|
224
259
|
passive: opts.passive === true,
|
|
225
260
|
});
|
|
226
261
|
return;
|
|
@@ -432,7 +467,9 @@ export class NotifyCenter {
|
|
|
432
467
|
if (this.seenTerminalIds.has(item.id)) return;
|
|
433
468
|
const existing = this.pendingTerminals.findIndex((pending) => pending.id === item.id);
|
|
434
469
|
if (existing >= 0) {
|
|
435
|
-
this.pendingTerminals[existing] = mergeTerminal(this.pendingTerminals[existing], item)
|
|
470
|
+
this.pendingTerminals[existing] = mergeTerminal(this.pendingTerminals[existing], item, (fields) => {
|
|
471
|
+
this.deps.logEvent?.("monitor.exit-facts-conflict", { id: item.id, fields });
|
|
472
|
+
});
|
|
436
473
|
return;
|
|
437
474
|
}
|
|
438
475
|
this.pendingTerminals.push(item);
|
|
@@ -622,7 +659,7 @@ export function attachCompactRecovery(
|
|
|
622
659
|
deps: {
|
|
623
660
|
getCenter: () => NotifyCenter | null;
|
|
624
661
|
getCtx: () => { isIdle(): boolean; hasPendingMessages?: () => boolean } | null;
|
|
625
|
-
listRunningMonitors: () => { id: string; description: string; remaining: string }[];
|
|
662
|
+
listRunningMonitors: () => { id: string; description: string; remaining: string; wakeOn?: string }[];
|
|
626
663
|
now?: () => number;
|
|
627
664
|
setTimeout?: typeof setTimeout;
|
|
628
665
|
clearTimeout?: typeof clearTimeout;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Poll guard: blocks task_output/task_list calls that only check on running
|
|
3
|
+
* work with nothing new to read.
|
|
4
|
+
*
|
|
5
|
+
* In the 2026-11-07 log-monitor session (deepseek-flash) the agent made 258
|
|
6
|
+
* task_output calls, 326 of them answered "no new output"; the result text
|
|
7
|
+
* already told it to end its turn. In the 2026-11-08 agent-wait-ready and
|
|
8
|
+
* monitor-not-sleep probes gpt-6-luna kept a monitor running and still called
|
|
9
|
+
* task_list/task_output before the event came. The wait guard
|
|
10
|
+
* (wait-guard.ts) moves sleeps to exactly these calls.
|
|
11
|
+
*
|
|
12
|
+
* A call is a poll when the work it looks at is still active and no wake
|
|
13
|
+
* about it has arrived since the last look:
|
|
14
|
+
* task_output on an active task, without a cursor past 0 (paging on from
|
|
15
|
+
* an earlier read stays allowed; max_bytes alone is a fresh
|
|
16
|
+
* read), and no wake for that task since the last read of it.
|
|
17
|
+
* task_list while any work is active, and no wake, user or peer message
|
|
18
|
+
* since the last list or since work was last started (a list
|
|
19
|
+
* right after starting a task only checks that it runs).
|
|
20
|
+
* Finished work, a wake's details and reads after a new message stay open.
|
|
21
|
+
*
|
|
22
|
+
* The call is refused, not the run: ending the run could leave an agent with
|
|
23
|
+
* nothing that will wake it (a server it started without a monitor), so the
|
|
24
|
+
* reason says to start a monitor in that case.
|
|
25
|
+
*/
|
|
26
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
27
|
+
import { famulusWakeDetails } from "./wake-delivery.ts";
|
|
28
|
+
import { wakeIds } from "./wake.ts";
|
|
29
|
+
import { fill } from "./prompts.generated.ts";
|
|
30
|
+
|
|
31
|
+
export interface PollGuardIndex {
|
|
32
|
+
list(): { id: string; status: string; title?: string }[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PollGuardOptions {
|
|
36
|
+
enabled: boolean;
|
|
37
|
+
getIndex: () => PollGuardIndex | null;
|
|
38
|
+
onBlock?: (info: { tool: string; taskId?: string }) => void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isActive = (status: string) => status === "pending" || status === "running";
|
|
42
|
+
|
|
43
|
+
/** A tool result that started background work (bash backgrounded, monitor started). */
|
|
44
|
+
const STARTED = /moved to background \(task_id: |Monitor started · task /;
|
|
45
|
+
|
|
46
|
+
function resultText(content: unknown): string {
|
|
47
|
+
if (typeof content === "string") return content;
|
|
48
|
+
if (!Array.isArray(content)) return "";
|
|
49
|
+
return content.map((c: { type?: string; text?: string }) => (c?.type === "text" ? c.text ?? "" : "")).join("\n");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function installPollGuard(pi: Pick<ExtensionAPI, "on">, opts: PollGuardOptions): void {
|
|
53
|
+
if (!opts.enabled) return;
|
|
54
|
+
/** Task ids with a wake not yet followed by a task_output read of them. */
|
|
55
|
+
const news = new Set<string>();
|
|
56
|
+
/** A wake, user or peer message arrived since the last task_list. */
|
|
57
|
+
let listNews = true;
|
|
58
|
+
|
|
59
|
+
pi.on("message_end", async (event) => {
|
|
60
|
+
const message = event.message as { role?: string; content?: unknown };
|
|
61
|
+
if (message.role === "user") { listNews = true; return; }
|
|
62
|
+
if (message.role === "toolResult") {
|
|
63
|
+
if (STARTED.test(resultText(message.content))) listNews = false;
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const wake = famulusWakeDetails(event.message);
|
|
67
|
+
if (wake) {
|
|
68
|
+
listNews = true;
|
|
69
|
+
for (const id of wakeIds(wake)) news.add(id);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (message.role === "custom") listNews = true;
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
pi.on("tool_call", async (event) => {
|
|
76
|
+
if (event.toolName !== "task_output" && event.toolName !== "task_list") return;
|
|
77
|
+
const items = opts.getIndex()?.list() ?? [];
|
|
78
|
+
const active = items.filter((i) => isActive(i.status));
|
|
79
|
+
if (active.length === 0) return;
|
|
80
|
+
const input = (event.input ?? {}) as Record<string, unknown>;
|
|
81
|
+
|
|
82
|
+
if (event.toolName === "task_list") {
|
|
83
|
+
if (listNews) { listNews = false; return; }
|
|
84
|
+
opts.onBlock?.({ tool: "task_list" });
|
|
85
|
+
return { block: true, reason: fill("guards.error.poll-list", { count: active.length }) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const taskId = typeof input.task_id === "string" ? input.task_id : "";
|
|
89
|
+
const target = active.find((i) => i.id === taskId);
|
|
90
|
+
if (!target) return;
|
|
91
|
+
if (typeof input.cursor === "number" && input.cursor > 0) return;
|
|
92
|
+
if (news.delete(taskId)) return;
|
|
93
|
+
opts.onBlock?.({ tool: "task_output", taskId });
|
|
94
|
+
return { block: true, reason: fill("guards.error.poll-output", { id: taskId }) };
|
|
95
|
+
});
|
|
96
|
+
}
|