pi-famulus 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/package.json +7 -7
- package/src/config.ts +4 -0
- package/src/format.ts +73 -2
- package/src/idle-turn-guard.ts +118 -0
- package/src/index.ts +177 -18
- package/src/intercom/intercom.ts +20 -66
- package/src/intercom/surface.ts +57 -0
- package/src/manager-client.ts +17 -3
- package/src/monitor-batching.ts +586 -13
- package/src/monitor.ts +292 -41
- package/src/notify.ts +465 -14
- package/src/prompts.generated.ts +29 -8
- package/src/task-tools.ts +47 -9
- package/src/tui/famulus-command.ts +5 -30
- package/src/tui/message-renderers.ts +30 -0
- package/src/wake.ts +121 -13
package/src/monitor.ts
CHANGED
|
@@ -3,21 +3,34 @@
|
|
|
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
|
-
*
|
|
8
|
-
*
|
|
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";
|
|
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
|
|
|
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 {
|
|
20
|
+
import {
|
|
21
|
+
LineBatcher,
|
|
22
|
+
RateLimiter,
|
|
23
|
+
OverloadController,
|
|
24
|
+
LegacyLineAssembler,
|
|
25
|
+
LEGACY_PARTIAL_MAX_CHARS,
|
|
26
|
+
OVERLOAD_SUMMARY_LINES_PER_SEC,
|
|
27
|
+
OVERLOAD_WINDOW_MS,
|
|
28
|
+
SUMMARY_CADENCE_MS,
|
|
29
|
+
type OverloadControllerOptions,
|
|
30
|
+
type OverloadEnterReason,
|
|
31
|
+
type OverloadInput,
|
|
32
|
+
type OverloadSummaryOutput,
|
|
33
|
+
} from "./monitor-batching";
|
|
21
34
|
import type { NotifyCenter } from "./notify";
|
|
22
35
|
import { fill, fillList, PROMPTS } from "./prompts.generated";
|
|
23
36
|
import { statusGlyph, toolComponent } from "./tui/tool-component";
|
|
@@ -27,10 +40,9 @@ import type { WorkIndex } from "./work-index";
|
|
|
27
40
|
const DEFAULT_TIMEOUT_MS = 300_000;
|
|
28
41
|
const MIN_TIMEOUT_MS = 1_000;
|
|
29
42
|
const MAX_TIMEOUT_MS = 3_600_000;
|
|
30
|
-
/**
|
|
31
|
-
const
|
|
32
|
-
const
|
|
33
|
-
const SATURATION_MIN_BATCHES = 10;
|
|
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;
|
|
34
46
|
/**
|
|
35
47
|
* A clean exit this soon after an event was caused by it (`grep -m1`). Its
|
|
36
48
|
* notice is appended without starting a turn: as a wake it cost every such monitor a
|
|
@@ -72,6 +84,8 @@ export interface MonitorDeps {
|
|
|
72
84
|
* with its exit event lost, in which case no further event will settle it.
|
|
73
85
|
*/
|
|
74
86
|
afterStop?: () => void;
|
|
87
|
+
/** Optional overload-policy overrides for tests. Production uses draft constants. */
|
|
88
|
+
overload?: Partial<OverloadControllerOptions>;
|
|
75
89
|
}
|
|
76
90
|
|
|
77
91
|
interface MonitorEntry {
|
|
@@ -84,18 +98,34 @@ interface MonitorEntry {
|
|
|
84
98
|
recordCursor: number;
|
|
85
99
|
lastRecordKind?: "line" | "progress";
|
|
86
100
|
limiter: RateLimiter;
|
|
87
|
-
|
|
101
|
+
overload: OverloadController;
|
|
102
|
+
legacyLines: LegacyLineAssembler;
|
|
88
103
|
droppedLinesPending: number;
|
|
89
104
|
timeoutTimer: ClockTimer | null;
|
|
105
|
+
/** Epoch ms when the extension-side timeout fires; null when persistent. */
|
|
106
|
+
timeoutDeadlineAt: number | null;
|
|
90
107
|
stopped: boolean;
|
|
91
108
|
cursor: number;
|
|
92
109
|
recovering: boolean;
|
|
93
110
|
queuedOutput: { chunk: string; cursor?: number; records?: MonitorOutputRecord[] }[];
|
|
94
111
|
lastEventAt?: number;
|
|
112
|
+
/** Last accepted line or newline-completed raw chunk, including later-deduped/rate-limited output. */
|
|
113
|
+
lastOutputAt?: number;
|
|
95
114
|
/** The model asked to stop it (task_stop): what is left is not news. */
|
|
96
115
|
stopRequested?: boolean;
|
|
97
116
|
/** Prevents autoStop from re-entering while it drains the 200ms batcher. */
|
|
98
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;
|
|
99
129
|
}
|
|
100
130
|
|
|
101
131
|
export class MonitorRegistry {
|
|
@@ -116,11 +146,22 @@ export class MonitorRegistry {
|
|
|
116
146
|
return () => this.changeListeners.delete(cb);
|
|
117
147
|
}
|
|
118
148
|
|
|
119
|
-
/** Active monitors for the fleet status surface. */
|
|
120
|
-
listActive(): { taskId: string; description: string; startedAt: number }[] {
|
|
149
|
+
/** Active monitors for the fleet status surface and task_list extras. */
|
|
150
|
+
listActive(): { taskId: string; description: string; startedAt: number; remainingMs: number | null; persistent: boolean; lastEventAt?: number; lastOutputAt?: number; wakeOn?: string; stallAfterMs?: number }[] {
|
|
151
|
+
const now = this.clock.now();
|
|
121
152
|
return [...this.entries.values()]
|
|
122
153
|
.filter((e) => !e.stopped)
|
|
123
|
-
.map((e) => ({
|
|
154
|
+
.map((e) => ({
|
|
155
|
+
taskId: e.taskId,
|
|
156
|
+
description: e.description,
|
|
157
|
+
startedAt: e.startedAt,
|
|
158
|
+
persistent: e.timeoutDeadlineAt === null,
|
|
159
|
+
remainingMs: e.timeoutDeadlineAt === null ? null : Math.max(0, e.timeoutDeadlineAt - now),
|
|
160
|
+
lastEventAt: e.lastEventAt,
|
|
161
|
+
lastOutputAt: e.lastOutputAt,
|
|
162
|
+
...(e.wakeOn ? { wakeOn: e.wakeOn.source } : {}),
|
|
163
|
+
...(e.stallAfterMs !== null ? { stallAfterMs: e.stallAfterMs } : {}),
|
|
164
|
+
}))
|
|
124
165
|
.sort((a, b) => a.startedAt - b.startedAt);
|
|
125
166
|
}
|
|
126
167
|
|
|
@@ -140,7 +181,7 @@ export class MonitorRegistry {
|
|
|
140
181
|
|
|
141
182
|
/** Start a monitor process and subscribe to its output stream. */
|
|
142
183
|
async start(
|
|
143
|
-
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 },
|
|
144
185
|
ctx: ExtensionContext,
|
|
145
186
|
): Promise<{ taskId: string; timeoutMs: number | null }> {
|
|
146
187
|
const client = this.deps.getClient();
|
|
@@ -155,6 +196,26 @@ export class MonitorRegistry {
|
|
|
155
196
|
throw new RangeError("fingerprint_mode must be exact or ignore-timestamps");
|
|
156
197
|
}
|
|
157
198
|
const persistent = params.persistent === true;
|
|
199
|
+
if (persistent && params.timeout_ms !== undefined) {
|
|
200
|
+
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");
|
|
201
|
+
}
|
|
202
|
+
if (params.timeout_ms !== undefined && params.timeout_ms > MAX_TIMEOUT_MS) {
|
|
203
|
+
throw new RangeError("timeout_ms exceeds the 1-hour maximum; for longer watches use persistent:true instead of re-arming");
|
|
204
|
+
}
|
|
205
|
+
let wakeOn: RegExp | null = null;
|
|
206
|
+
if (params.wake_on !== undefined) {
|
|
207
|
+
if (typeof params.wake_on !== "string" || params.wake_on.length === 0) {
|
|
208
|
+
throw new RangeError("wake_on must be a non-empty regular expression source");
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
wakeOn = new RegExp(params.wake_on);
|
|
212
|
+
} catch (error) {
|
|
213
|
+
throw new RangeError(`wake_on is not a valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
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)) {
|
|
217
|
+
throw new RangeError(`stall_after_ms must be an integer between ${MIN_STALL_MS} and ${MAX_STALL_MS}`);
|
|
218
|
+
}
|
|
158
219
|
let timeoutMs: number | null = null;
|
|
159
220
|
if (!persistent) {
|
|
160
221
|
const requested = params.timeout_ms ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -174,27 +235,38 @@ export class MonitorRegistry {
|
|
|
174
235
|
this.deps.trackTask(task_id, { kind: "monitor", command: params.command, cwd: ctx.cwd });
|
|
175
236
|
this.deps.logEvent?.("monitor.start", { id: task_id, description: params.description });
|
|
176
237
|
|
|
238
|
+
const now = this.clock.now();
|
|
177
239
|
const entry: MonitorEntry = {
|
|
178
240
|
taskId: task_id,
|
|
179
241
|
description: params.description,
|
|
180
|
-
startedAt:
|
|
242
|
+
startedAt: now,
|
|
181
243
|
batcher: null as unknown as LineBatcher, // assigned below (self-reference in callback)
|
|
182
244
|
output: null as unknown as MonitorOutputBuffer,
|
|
183
245
|
legacyOutput: {},
|
|
184
246
|
recordCursor: -1,
|
|
185
247
|
limiter: new RateLimiter({ clock: this.clock }),
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
dropRatio: SATURATION_DROP_RATIO,
|
|
189
|
-
minimumBatches: SATURATION_MIN_BATCHES,
|
|
190
|
-
}),
|
|
248
|
+
overload: null as unknown as OverloadController,
|
|
249
|
+
legacyLines: new LegacyLineAssembler(),
|
|
191
250
|
droppedLinesPending: 0,
|
|
192
251
|
timeoutTimer: null,
|
|
252
|
+
timeoutDeadlineAt: timeoutMs === null ? null : now + timeoutMs,
|
|
193
253
|
stopped: false,
|
|
194
254
|
cursor: 0,
|
|
195
255
|
recovering: false,
|
|
196
256
|
queuedOutput: [],
|
|
257
|
+
wakeOn,
|
|
258
|
+
stallAfterMs: params.stall_after_ms ?? null,
|
|
259
|
+
stallTimer: null,
|
|
260
|
+
lastActivityAt: now,
|
|
261
|
+
stallNotified: false,
|
|
197
262
|
};
|
|
263
|
+
entry.overload = new OverloadController({
|
|
264
|
+
clock: this.clock,
|
|
265
|
+
...this.deps.overload,
|
|
266
|
+
onSummary: (text, output) => this.emitOverloadNotice(entry, text, output),
|
|
267
|
+
onEnter: (reason) => this.emitOverloadNotice(entry, this.enterNotice(reason)),
|
|
268
|
+
onExit: () => this.emitOverloadNotice(entry, "[Monitor overload: leaving summary mode. Individual lines resume.]"),
|
|
269
|
+
});
|
|
198
270
|
entry.batcher = new LineBatcher({
|
|
199
271
|
onFlush: (text, info) => {
|
|
200
272
|
const output = mergeOutputInfo(entry.legacyOutput, info);
|
|
@@ -216,6 +288,7 @@ export class MonitorRegistry {
|
|
|
216
288
|
}, timeoutMs);
|
|
217
289
|
this.clock.unref?.(entry.timeoutTimer);
|
|
218
290
|
}
|
|
291
|
+
if (entry.stallAfterMs !== null) this.armStall(entry, entry.stallAfterMs);
|
|
219
292
|
this.entries.set(task_id, entry);
|
|
220
293
|
this.emitChange();
|
|
221
294
|
// Replay what arrived before we knew the id: lines first, then the exit.
|
|
@@ -267,22 +340,136 @@ export class MonitorRegistry {
|
|
|
267
340
|
if (records !== undefined) {
|
|
268
341
|
// Empty metadata arrays deliberately hold raw fragments for Rust framing.
|
|
269
342
|
entry.batcher.flush();
|
|
343
|
+
const accepted: MonitorOutputRecord[] = [];
|
|
344
|
+
let filteredLines = 0;
|
|
345
|
+
let metadataTookOver = false;
|
|
270
346
|
for (const record of records) {
|
|
271
347
|
if (!validRecord(record, entry.cursor)) continue;
|
|
272
348
|
if (record.cursor_end < entry.recordCursor || (record.cursor_end === entry.recordCursor && !(entry.lastRecordKind === "progress" && record.kind === "line"))) continue;
|
|
349
|
+
metadataTookOver = true;
|
|
273
350
|
entry.recordCursor = record.cursor_end;
|
|
274
351
|
entry.lastRecordKind = record.kind;
|
|
352
|
+
if (record.kind === "line") entry.lastOutputAt = this.clock.now();
|
|
353
|
+
this.noteActivity(entry);
|
|
354
|
+
// Filtered-out records reach neither dedup nor wake accounting,
|
|
355
|
+
// only the stop backstop.
|
|
356
|
+
if (!admits(entry, record.preview)) {
|
|
357
|
+
if (record.kind === "line") filteredLines++;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
275
360
|
entry.output.push(record);
|
|
361
|
+
if (record.kind === "line") accepted.push(record);
|
|
362
|
+
}
|
|
363
|
+
if (metadataTookOver) entry.legacyLines.reset();
|
|
364
|
+
this.noteFilteredLines(entry, filteredLines);
|
|
365
|
+
if (accepted.length > 0) {
|
|
366
|
+
this.noteInput(entry, {
|
|
367
|
+
lines: accepted.length,
|
|
368
|
+
bytes: accepted.reduce((n, r) => n + (r.cursor_end - r.cursor_start), 0),
|
|
369
|
+
text: accepted.map((r) => r.preview).join("\n"),
|
|
370
|
+
cursorStart: Math.min(...accepted.map((r) => r.cursor_start)),
|
|
371
|
+
cursorEnd: Math.max(...accepted.map((r) => r.cursor_end)),
|
|
372
|
+
});
|
|
276
373
|
}
|
|
277
374
|
} else if (deliver.byteLength > 0) {
|
|
278
375
|
// Legacy manager or unavailable replay metadata: fail open, never hash in JS.
|
|
279
376
|
entry.output.flush();
|
|
377
|
+
const cursorStart = Math.max(previousCursor, entry.cursor - deliver.byteLength);
|
|
378
|
+
const text = deliver.toString("utf8");
|
|
379
|
+
if (text.includes("\n")) {
|
|
380
|
+
entry.lastOutputAt = this.clock.now();
|
|
381
|
+
this.noteActivity(entry);
|
|
382
|
+
}
|
|
383
|
+
const assembled = entry.legacyLines.push(text, deliver.byteLength, cursorStart, entry.cursor);
|
|
384
|
+
if (entry.wakeOn) {
|
|
385
|
+
// Raw chunks are filtered per completed line; a trailing fragment
|
|
386
|
+
// waits for its newline (or the exit).
|
|
387
|
+
if (assembled) this.admitLegacyLines(entry, assembled);
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
280
390
|
entry.legacyOutput = mergeOutputInfo(entry.legacyOutput, {
|
|
281
391
|
firstObservedAt: this.clock.now(), lastObservedAt: this.clock.now(),
|
|
282
|
-
cursorStart
|
|
392
|
+
cursorStart, cursorEnd: entry.cursor,
|
|
283
393
|
});
|
|
284
|
-
|
|
394
|
+
if (assembled) {
|
|
395
|
+
this.noteInput(entry, {
|
|
396
|
+
lines: assembled.lines,
|
|
397
|
+
bytes: assembled.bytes,
|
|
398
|
+
text: assembled.text ?? "",
|
|
399
|
+
cursorStart: assembled.cursorStart ?? cursorStart,
|
|
400
|
+
cursorEnd: assembled.cursorEnd ?? entry.cursor,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
entry.batcher.push(text);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** wake_on on the raw path: pass only matching completed lines on to overload accounting and the batcher. */
|
|
408
|
+
private admitLegacyLines(entry: MonitorEntry, assembled: OverloadInput): void {
|
|
409
|
+
const all = (assembled.text ?? "").split("\n");
|
|
410
|
+
const lines = all.filter((line) => admits(entry, line));
|
|
411
|
+
this.noteFilteredLines(entry, all.length - lines.length);
|
|
412
|
+
if (lines.length === 0) return;
|
|
413
|
+
const now = this.clock.now();
|
|
414
|
+
entry.legacyOutput = mergeOutputInfo(entry.legacyOutput, {
|
|
415
|
+
firstObservedAt: now, lastObservedAt: now,
|
|
416
|
+
cursorStart: assembled.cursorStart, cursorEnd: assembled.cursorEnd,
|
|
417
|
+
// The assembler keeps at most LEGACY_PARTIAL_MAX_CHARS of a line.
|
|
418
|
+
truncated: lines.some((line) => line.length >= LEGACY_PARTIAL_MAX_CHARS),
|
|
419
|
+
});
|
|
420
|
+
this.noteInput(entry, {
|
|
421
|
+
lines: lines.length,
|
|
422
|
+
bytes: lines.reduce((n, line) => n + Buffer.byteLength(line) + 1, 0),
|
|
423
|
+
text: lines.join("\n"),
|
|
424
|
+
cursorStart: assembled.cursorStart ?? entry.cursor,
|
|
425
|
+
cursorEnd: assembled.cursorEnd ?? entry.cursor,
|
|
426
|
+
});
|
|
427
|
+
entry.batcher.push(lines.map((line) => `${line}\n`).join(""));
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Any new output proves the source is alive: re-arm a stall notice that already went out. */
|
|
431
|
+
private noteActivity(entry: MonitorEntry): void {
|
|
432
|
+
entry.lastActivityAt = this.clock.now();
|
|
433
|
+
if (entry.stallAfterMs !== null && entry.stallNotified) {
|
|
434
|
+
entry.stallNotified = false;
|
|
435
|
+
this.armStall(entry, entry.stallAfterMs);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private armStall(entry: MonitorEntry, delayMs: number): void {
|
|
440
|
+
if (entry.stallTimer !== null) this.clock.clearTimeout(entry.stallTimer);
|
|
441
|
+
entry.stallTimer = this.clock.setTimeout(() => this.onStallDue(entry), delayMs);
|
|
442
|
+
this.clock.unref?.(entry.stallTimer);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** One timer per monitor, re-checked lazily, so output never touches timers. */
|
|
446
|
+
private onStallDue(entry: MonitorEntry): void {
|
|
447
|
+
entry.stallTimer = null;
|
|
448
|
+
if (entry.stopped || entry.stallAfterMs === null) return;
|
|
449
|
+
const idle = this.clock.now() - entry.lastActivityAt;
|
|
450
|
+
if (idle < entry.stallAfterMs) {
|
|
451
|
+
this.armStall(entry, entry.stallAfterMs - idle);
|
|
452
|
+
return;
|
|
285
453
|
}
|
|
454
|
+
entry.stallNotified = true;
|
|
455
|
+
if (entry.stopRequested || entry.stopping) return;
|
|
456
|
+
const center = this.deps.getNotifyCenter();
|
|
457
|
+
if (!center) return;
|
|
458
|
+
this.deps.logEvent?.("monitor.stall", { id: entry.taskId, idleMs: idle });
|
|
459
|
+
center.notifyMonitorEvent(entry.description, entry.taskId, fill("tools.monitor.event.stalled", { idle: formatDuration(idle) }), 0, {});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Lines wake_on kept from waking still count toward the input-rate stop backstop. */
|
|
463
|
+
private noteFilteredLines(entry: MonitorEntry, lines: number): void {
|
|
464
|
+
if (lines <= 0) return;
|
|
465
|
+
entry.overload.recordFilteredLines(lines);
|
|
466
|
+
if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) void this.autoStop(entry);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Count complete raw lines/chunks before limiter (includes later-deduped lines). */
|
|
470
|
+
private noteInput(entry: MonitorEntry, input: { lines: number; bytes: number; text: string; cursorStart: number; cursorEnd: number }): void {
|
|
471
|
+
entry.overload.recordInput(input);
|
|
472
|
+
if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) void this.autoStop(entry);
|
|
286
473
|
}
|
|
287
474
|
|
|
288
475
|
/**
|
|
@@ -310,10 +497,16 @@ export class MonitorRegistry {
|
|
|
310
497
|
this.earlyFor(taskId).exit = event;
|
|
311
498
|
return false;
|
|
312
499
|
}
|
|
313
|
-
// Drain remaining buffered lines before closing out.
|
|
500
|
+
// Drain remaining buffered lines before closing out. Unfiltered raw
|
|
501
|
+
// output already holds the trailing fragment in the batcher.
|
|
502
|
+
if (entry.wakeOn) {
|
|
503
|
+
const partial = entry.legacyLines.drainPartial();
|
|
504
|
+
if (partial) this.admitLegacyLines(entry, partial);
|
|
505
|
+
}
|
|
314
506
|
entry.batcher.flush();
|
|
315
507
|
entry.output.flush();
|
|
316
508
|
const alreadyStopped = entry.stopped;
|
|
509
|
+
if (!alreadyStopped && !entry.stopRequested) entry.overload.flushSummary();
|
|
317
510
|
this.cleanup(entry);
|
|
318
511
|
this.deps.onExited?.(taskId, event);
|
|
319
512
|
if (alreadyStopped) return true; // timeout/saturation owns the pending summary
|
|
@@ -329,19 +522,27 @@ export class MonitorRegistry {
|
|
|
329
522
|
this.clock.now() - entry.lastEventAt <= EXIT_AFTER_EVENT_MS;
|
|
330
523
|
const duration =
|
|
331
524
|
typeof event.duration_ms === "number" ? `${(event.duration_ms / 1000).toFixed(1)}s` : "unknown duration";
|
|
332
|
-
|
|
525
|
+
const facts = {
|
|
526
|
+
...(event.end_reason ? { endReason: event.end_reason } : {}),
|
|
527
|
+
...(event.signal ? { signal: event.signal } : {}),
|
|
528
|
+
exitCode,
|
|
529
|
+
...(entry.stopRequested ? { stopRequested: true } : {}),
|
|
530
|
+
};
|
|
531
|
+
const exitContext = `After ${duration}.${startFailureNote(event.end_reason)} No further events will be delivered.${entry.droppedLinesPending > 0 ? ` ${entry.droppedLinesPending} output lines were dropped.` : ""}`;
|
|
532
|
+
const detail = `${formatExitFacts(facts)} ${exitContext}`;
|
|
533
|
+
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: event.end_reason ?? "unknown" });
|
|
333
534
|
this.deps.getNotifyCenter()?.notify(
|
|
334
535
|
formatMonitorEvent(
|
|
335
536
|
entry.description,
|
|
336
537
|
entry.taskId,
|
|
337
|
-
|
|
538
|
+
detail,
|
|
338
539
|
"exited",
|
|
339
|
-
{ droppedLines: entry.droppedLinesPending, ...(summary.suppressedCount ? { output: summary } : {}) },
|
|
540
|
+
{ droppedLines: entry.droppedLinesPending, exitFacts: facts, exitContext, ...(summary.suppressedCount ? { output: summary } : {}) },
|
|
340
541
|
),
|
|
341
542
|
{ passive: causedByEvent || entry.stopRequested === true, quietEvents: entry.stopRequested === true },
|
|
342
543
|
);
|
|
343
544
|
this.deps.toast?.(
|
|
344
|
-
`Monitor "${entry.description}"
|
|
545
|
+
`Monitor "${entry.description}": ${detail}`,
|
|
345
546
|
exitCode === 0 || exitCode === null ? "info" : "warning",
|
|
346
547
|
);
|
|
347
548
|
return true;
|
|
@@ -395,22 +596,49 @@ export class MonitorRegistry {
|
|
|
395
596
|
this.early.clear();
|
|
396
597
|
}
|
|
397
598
|
|
|
599
|
+
private enterNotice(reason: OverloadEnterReason): string {
|
|
600
|
+
const windowMs = this.deps.overload?.windowMs ?? OVERLOAD_WINDOW_MS;
|
|
601
|
+
const cadenceMs = this.deps.overload?.cadenceMs?.[0] ?? SUMMARY_CADENCE_MS[0];
|
|
602
|
+
const linesPerSec = this.deps.overload?.summaryLinesPerSec ?? OVERLOAD_SUMMARY_LINES_PER_SEC;
|
|
603
|
+
const windowSecs = Math.round(windowMs / 1000);
|
|
604
|
+
const why = reason === "drop-ratio"
|
|
605
|
+
? `drop-ratio ≥50% over ${windowSecs}s`
|
|
606
|
+
: reason === "line-rate"
|
|
607
|
+
? `input >${linesPerSec} lines/s over ${windowSecs}s`
|
|
608
|
+
: `drop-ratio ≥50% over ${windowSecs}s and input >${linesPerSec} lines/s`;
|
|
609
|
+
return `[Monitor overload: entering summary mode (${why}). Individual lines are suppressed. First summary after ${Math.round(cadenceMs / 1000)}s. Raw output via task_output.]`;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
private emitOverloadNotice(entry: MonitorEntry, text: string, output?: OverloadSummaryOutput): void {
|
|
613
|
+
if (entry.stopped || entry.stopRequested) return;
|
|
614
|
+
const center = this.deps.getNotifyCenter();
|
|
615
|
+
if (!center) return;
|
|
616
|
+
center.notifyMonitorEvent(entry.description, entry.taskId, text, 0, output ? { output } : {});
|
|
617
|
+
entry.lastEventAt = this.clock.now();
|
|
618
|
+
}
|
|
619
|
+
|
|
398
620
|
private onBatch(entry: MonitorEntry, text: string, output?: MonitorOutputInfo, onDelivered?: () => void): boolean {
|
|
399
621
|
if (entry.stopped) return false;
|
|
400
622
|
const center = this.deps.getNotifyCenter();
|
|
401
623
|
if (!center) return false;
|
|
402
624
|
const now = this.clock.now();
|
|
625
|
+
if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) {
|
|
626
|
+
void this.autoStop(entry);
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
403
629
|
const accepted = entry.limiter.tryConsume();
|
|
404
|
-
entry.
|
|
630
|
+
entry.overload.recordBatch(!accepted);
|
|
631
|
+
if (entry.overload.shouldStop() && !entry.stopRequested && !entry.stopping) {
|
|
632
|
+
void this.autoStop(entry);
|
|
633
|
+
return false;
|
|
634
|
+
}
|
|
405
635
|
if (!accepted) {
|
|
406
636
|
const droppedLines = text.split("\n").length;
|
|
407
637
|
this.deps.logEvent?.("monitor.drop", { id: entry.taskId, lines: droppedLines });
|
|
408
638
|
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
639
|
}
|
|
640
|
+
if (entry.overload.inSummary()) return false;
|
|
641
|
+
if (!accepted) return false;
|
|
414
642
|
const droppedLines = entry.droppedLinesPending;
|
|
415
643
|
entry.droppedLinesPending = 0;
|
|
416
644
|
entry.lastEventAt = now;
|
|
@@ -430,48 +658,54 @@ export class MonitorRegistry {
|
|
|
430
658
|
entry.batcher.flush();
|
|
431
659
|
entry.output.flush();
|
|
432
660
|
if (entry.stopped) return; // A flush may already have tripped overload protection.
|
|
661
|
+
entry.overload.flushSummary();
|
|
433
662
|
entry.stopped = true;
|
|
434
663
|
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "timeout" });
|
|
435
664
|
const client = this.deps.getClient();
|
|
436
|
-
|
|
665
|
+
let stopFailed = false;
|
|
666
|
+
let stopError: unknown;
|
|
667
|
+
if (client) await client.stop(entry.taskId, "timeout").catch((error: unknown) => { stopFailed = true; stopError = error; });
|
|
668
|
+
const stopDetail = stopFailed ? `Stop request failed: ${String(stopError)}. Exit unconfirmed.` : client ? "Stop requested; exit unconfirmed." : "Stop request unavailable; exit unconfirmed.";
|
|
437
669
|
this.deps.getNotifyCenter()?.notify(
|
|
438
670
|
formatMonitorEvent(
|
|
439
671
|
entry.description,
|
|
440
672
|
entry.taskId,
|
|
441
|
-
|
|
442
|
-
|
|
673
|
+
`Timeout elapsed. ${stopDetail}`,
|
|
443
674
|
"timeout",
|
|
444
675
|
{ droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
|
|
445
676
|
),
|
|
446
677
|
);
|
|
447
|
-
this.deps.toast?.(`Monitor "${entry.description}"
|
|
678
|
+
this.deps.toast?.(`Monitor "${entry.description}": timeout elapsed. ${stopDetail}`, "warning");
|
|
448
679
|
this.cleanup(entry);
|
|
449
680
|
this.deps.afterStop?.();
|
|
450
681
|
}
|
|
451
682
|
|
|
452
|
-
/**
|
|
683
|
+
/** Extreme sustained input rate: stop and notify (unverified safety backstop). */
|
|
453
684
|
private async autoStop(entry: MonitorEntry): Promise<void> {
|
|
454
685
|
if (entry.stopped || entry.stopping) return;
|
|
455
686
|
entry.stopping = true;
|
|
456
687
|
entry.batcher.flush();
|
|
457
688
|
entry.output.flush();
|
|
458
689
|
if (entry.stopped) return;
|
|
690
|
+
entry.overload.flushSummary();
|
|
459
691
|
entry.stopped = true;
|
|
460
692
|
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "rate-limit" });
|
|
461
693
|
const client = this.deps.getClient();
|
|
462
|
-
|
|
694
|
+
let stopFailed = false;
|
|
695
|
+
let stopError: unknown;
|
|
696
|
+
if (client) await client.stop(entry.taskId, "rate-limit").catch((error: unknown) => { stopFailed = true; stopError = error; });
|
|
697
|
+
const stopDetail = stopFailed ? `Stop request failed: ${String(stopError)}. Exit unconfirmed.` : client ? "Stop requested; exit unconfirmed." : "Stop request unavailable; exit unconfirmed.";
|
|
463
698
|
this.deps.getNotifyCenter()?.notify(
|
|
464
699
|
formatMonitorEvent(
|
|
465
700
|
entry.description,
|
|
466
701
|
entry.taskId,
|
|
467
|
-
|
|
468
|
-
|
|
702
|
+
`${entry.overload.stopNotice()} ${stopDetail}`,
|
|
469
703
|
"stopped",
|
|
470
704
|
{ droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
|
|
471
705
|
),
|
|
472
706
|
);
|
|
473
707
|
this.deps.toast?.(
|
|
474
|
-
`Monitor "${entry.description}"
|
|
708
|
+
`Monitor "${entry.description}": input rate safety backstop. ${stopDetail}`,
|
|
475
709
|
"warning",
|
|
476
710
|
);
|
|
477
711
|
this.cleanup(entry);
|
|
@@ -483,15 +717,24 @@ export class MonitorRegistry {
|
|
|
483
717
|
entry.batcher.dispose();
|
|
484
718
|
entry.output.dispose();
|
|
485
719
|
entry.limiter.dispose();
|
|
720
|
+
entry.overload.dispose();
|
|
486
721
|
if (entry.timeoutTimer !== null) {
|
|
487
722
|
this.clock.clearTimeout(entry.timeoutTimer);
|
|
488
723
|
entry.timeoutTimer = null;
|
|
489
724
|
}
|
|
725
|
+
if (entry.stallTimer !== null) {
|
|
726
|
+
this.clock.clearTimeout(entry.stallTimer);
|
|
727
|
+
entry.stallTimer = null;
|
|
728
|
+
}
|
|
490
729
|
this.entries.delete(entry.taskId);
|
|
491
730
|
this.emitChange();
|
|
492
731
|
}
|
|
493
732
|
}
|
|
494
733
|
|
|
734
|
+
function admits(entry: MonitorEntry, line: string): boolean {
|
|
735
|
+
return entry.wakeOn === null || entry.wakeOn.test(line);
|
|
736
|
+
}
|
|
737
|
+
|
|
495
738
|
function validRecord(record: MonitorOutputRecord, cursor: number): boolean {
|
|
496
739
|
return record?.version === 1 && (record.kind === "line" || record.kind === "progress") &&
|
|
497
740
|
typeof record.preview === "string" && record.preview.length <= 2000 &&
|
|
@@ -537,6 +780,14 @@ const monitorParameters = Type.Object({
|
|
|
537
780
|
persistent: Type.Optional(Type.Boolean({ description: PROMPTS["tools.monitor.param.persistent"] })),
|
|
538
781
|
dedup_window_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 3_600_000, description: PROMPTS["tools.monitor.param.dedup_window_ms"] })),
|
|
539
782
|
fingerprint_mode: Type.Optional(Type.Union([Type.Literal("exact"), Type.Literal("ignore-timestamps")], { description: PROMPTS["tools.monitor.param.fingerprint_mode"] })),
|
|
783
|
+
wake_on: Type.Optional(Type.String({ minLength: 1, description: PROMPTS["tools.monitor.param.wake_on"] })),
|
|
784
|
+
stall_after_ms: Type.Optional(
|
|
785
|
+
Type.Integer({
|
|
786
|
+
minimum: MIN_STALL_MS,
|
|
787
|
+
maximum: MAX_STALL_MS,
|
|
788
|
+
description: fill("tools.monitor.param.stall_after_ms", { minMs: MIN_STALL_MS, maxMs: MAX_STALL_MS }),
|
|
789
|
+
}),
|
|
790
|
+
),
|
|
540
791
|
});
|
|
541
792
|
|
|
542
793
|
export function createMonitorTool(
|