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/README.md +3 -2
- package/package.json +7 -7
- package/src/format.ts +43 -0
- package/src/index.ts +170 -18
- package/src/intercom/intercom.ts +19 -22
- package/src/manager-client.ts +1 -1
- package/src/monitor-batching.ts +562 -13
- package/src/monitor.ts +124 -32
- package/src/notify.ts +428 -14
- package/src/prompts.generated.ts +11 -5
- package/src/task-tools.ts +20 -1
- package/src/tui/famulus-command.ts +5 -30
- package/src/tui/message-renderers.ts +30 -0
- package/src/wake.ts +110 -13
package/src/monitor-batching.ts
CHANGED
|
@@ -165,7 +165,8 @@ export class SaturationWindow {
|
|
|
165
165
|
private readonly windowMs: number;
|
|
166
166
|
private readonly dropRatio: number;
|
|
167
167
|
private readonly minimumBatches: number;
|
|
168
|
-
private
|
|
168
|
+
private buckets: { sec: number; total: number; dropped: number }[] = [];
|
|
169
|
+
private firstAt: number | undefined;
|
|
169
170
|
|
|
170
171
|
constructor(opts: SaturationWindowOptions) {
|
|
171
172
|
this.windowMs = opts.windowMs;
|
|
@@ -174,26 +175,41 @@ export class SaturationWindow {
|
|
|
174
175
|
}
|
|
175
176
|
|
|
176
177
|
record(dropped: boolean, at: number): void {
|
|
178
|
+
if (this.firstAt === undefined) this.firstAt = at;
|
|
179
|
+
const sec = Math.floor(at / 1000);
|
|
180
|
+
const last = this.buckets[this.buckets.length - 1];
|
|
181
|
+
if (last && last.sec === sec) {
|
|
182
|
+
last.total += 1;
|
|
183
|
+
if (dropped) last.dropped += 1;
|
|
184
|
+
} else {
|
|
185
|
+
this.buckets.push({ sec, total: 1, dropped: dropped ? 1 : 0 });
|
|
186
|
+
}
|
|
177
187
|
this.prune(at);
|
|
178
|
-
this.samples.push({ at, dropped });
|
|
179
188
|
}
|
|
180
189
|
|
|
181
190
|
isSaturated(now: number): boolean {
|
|
182
191
|
this.prune(now);
|
|
183
|
-
if (this.
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
192
|
+
if (this.firstAt === undefined || now - this.firstAt < this.windowMs) return false;
|
|
193
|
+
const cutoffSec = Math.floor((now - this.windowMs) / 1000);
|
|
194
|
+
let total = 0;
|
|
195
|
+
let dropped = 0;
|
|
196
|
+
for (const bucket of this.buckets) {
|
|
197
|
+
if (bucket.sec >= cutoffSec) {
|
|
198
|
+
total += bucket.total;
|
|
199
|
+
dropped += bucket.dropped;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (total < this.minimumBatches) return false;
|
|
203
|
+
return dropped / total >= this.dropRatio;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
bucketCountForTest(): number {
|
|
207
|
+
return this.buckets.length;
|
|
190
208
|
}
|
|
191
209
|
|
|
192
210
|
private prune(now: number): void {
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
while (firstLive < this.samples.length && this.samples[firstLive].at < cutoff) firstLive++;
|
|
196
|
-
if (firstLive > 0) this.samples = this.samples.slice(firstLive);
|
|
211
|
+
const cutoffSec = Math.floor((now - this.windowMs) / 1000) - 1;
|
|
212
|
+
while (this.buckets.length > 0 && this.buckets[0].sec < cutoffSec) this.buckets.shift();
|
|
197
213
|
}
|
|
198
214
|
}
|
|
199
215
|
|
|
@@ -237,3 +253,536 @@ export class RateLimiter {
|
|
|
237
253
|
this.clock.clearInterval(this.interval);
|
|
238
254
|
}
|
|
239
255
|
}
|
|
256
|
+
|
|
257
|
+
/** Bound retained incomplete legacy/raw line across chunks. */
|
|
258
|
+
export const LEGACY_PARTIAL_MAX_CHARS = 500;
|
|
259
|
+
|
|
260
|
+
export class LegacyLineAssembler {
|
|
261
|
+
private text = "";
|
|
262
|
+
private bytes = 0;
|
|
263
|
+
private start: number | undefined;
|
|
264
|
+
|
|
265
|
+
retainedCharsForTest(): number {
|
|
266
|
+
return this.text.length;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Drop a retained partial: metadata owns those bytes, or the next raw cursor is discontinuous. */
|
|
270
|
+
reset(): void {
|
|
271
|
+
this.text = "";
|
|
272
|
+
this.bytes = 0;
|
|
273
|
+
this.start = undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
push(chunk: string, chunkBytes: number, cursorStart: number, cursorEnd: number): OverloadInput | undefined {
|
|
277
|
+
if (chunk.length === 0 && chunkBytes === 0) return undefined;
|
|
278
|
+
if (this.start !== undefined && cursorStart !== this.start + this.bytes) this.reset();
|
|
279
|
+
const savedStart = this.start ?? cursorStart;
|
|
280
|
+
if (this.start === undefined) this.start = cursorStart;
|
|
281
|
+
const parts = chunk.split("\n");
|
|
282
|
+
if (parts.length === 1) {
|
|
283
|
+
this.bytes += chunkBytes;
|
|
284
|
+
if (this.text.length < LEGACY_PARTIAL_MAX_CHARS) {
|
|
285
|
+
this.text = `${this.text}${chunk}`.slice(0, LEGACY_PARTIAL_MAX_CHARS);
|
|
286
|
+
}
|
|
287
|
+
return undefined;
|
|
288
|
+
}
|
|
289
|
+
const completeLines = parts.slice(0, -1);
|
|
290
|
+
const remainder = parts[parts.length - 1] ?? "";
|
|
291
|
+
const lines: string[] = [];
|
|
292
|
+
const first = `${this.text}${completeLines[0] ?? ""}`;
|
|
293
|
+
lines.push(first.length > LEGACY_PARTIAL_MAX_CHARS ? first.slice(0, LEGACY_PARTIAL_MAX_CHARS) : first);
|
|
294
|
+
for (let i = 1; i < completeLines.length; i++) {
|
|
295
|
+
const line = completeLines[i];
|
|
296
|
+
lines.push(line.length > LEGACY_PARTIAL_MAX_CHARS ? line.slice(0, LEGACY_PARTIAL_MAX_CHARS) : line);
|
|
297
|
+
}
|
|
298
|
+
const remainderBytes = Buffer.byteLength(remainder);
|
|
299
|
+
const completeBytes = this.bytes + chunkBytes - remainderBytes;
|
|
300
|
+
this.text = remainder.slice(0, LEGACY_PARTIAL_MAX_CHARS);
|
|
301
|
+
this.bytes = remainderBytes;
|
|
302
|
+
this.start = remainderBytes === 0 ? undefined : cursorEnd - remainderBytes;
|
|
303
|
+
return {
|
|
304
|
+
lines: lines.length,
|
|
305
|
+
bytes: completeBytes,
|
|
306
|
+
text: lines.join("\n"),
|
|
307
|
+
cursorStart: savedStart,
|
|
308
|
+
cursorEnd: remainderBytes === 0 ? cursorEnd : cursorEnd - remainderBytes,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Rolling window for overload line-rate / drop-ratio. */
|
|
314
|
+
export const OVERLOAD_WINDOW_MS = 30_000;
|
|
315
|
+
/**
|
|
316
|
+
* Draft / owner-unconfirmed. Calibrated only from one 2026-10-29 incident
|
|
317
|
+
* (events-only; accepted input bytes/lines were unavailable).
|
|
318
|
+
*/
|
|
319
|
+
export const OVERLOAD_SUMMARY_LINES_PER_SEC = 5;
|
|
320
|
+
/** Unverified safety backstop — not calibrated. */
|
|
321
|
+
export const OVERLOAD_STOP_LINES_PER_SEC = 1000;
|
|
322
|
+
export const OVERLOAD_STOP_SUSTAIN_MS = 60_000;
|
|
323
|
+
export const OVERLOAD_EXIT_QUIET_MS = 60_000;
|
|
324
|
+
export const SUMMARY_CADENCE_MS = [30_000, 60_000, 120_000, 300_000];
|
|
325
|
+
export const SUMMARY_MAX_CHARS = 1500;
|
|
326
|
+
export const SUMMARY_MAX_SIGNATURES = 64;
|
|
327
|
+
export const SUMMARY_SIGNATURE_CHARS = 120;
|
|
328
|
+
|
|
329
|
+
export function normalizeSignature(line: string): string {
|
|
330
|
+
let s = line;
|
|
331
|
+
s = s.replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, "");
|
|
332
|
+
s = s.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?/g, "");
|
|
333
|
+
s = s.replace(/\d{2}\/[A-Za-z]{3}\/\d{4}:\d{2}:\d{2}:\d{2} [+-]\d{4}/g, "");
|
|
334
|
+
s = s.replace(/\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?/g, "");
|
|
335
|
+
s = s.replace(/\b[A-Za-z]{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\b/g, "");
|
|
336
|
+
s = stripIpAddresses(s);
|
|
337
|
+
s = s.replace(/\b[0-9a-fA-F]{8,}\b/g, "");
|
|
338
|
+
s = s.replace(/\d{4,}/g, "");
|
|
339
|
+
s = s.replace(/\s+/g, " ").trim();
|
|
340
|
+
return s.length > SUMMARY_SIGNATURE_CHARS ? s.slice(0, SUMMARY_SIGNATURE_CHARS) : s;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Strip IPv4 and IPv6 (full, compressed, bracketed, optional port) without touching HTTP 500/502 or `a:b:c`. */
|
|
344
|
+
function stripIpAddresses(s: string): string {
|
|
345
|
+
s = s.replace(/\[[0-9a-fA-F:]+\](?::\d{1,5})?/gi, "");
|
|
346
|
+
s = s.replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, "");
|
|
347
|
+
s = s.replace(/\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b/gi, "");
|
|
348
|
+
// Compressed forms must contain "::". A hextet immediately before "::" has no
|
|
349
|
+
// trailing colon, so `2001:db8::1` is not parsed as `db8:` + `:1`.
|
|
350
|
+
s = s.replace(
|
|
351
|
+
/(?:^|[\s,;=("'])((?:[0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}::(?:[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4})*)?|::(?:[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4})*)?)/gi,
|
|
352
|
+
(all, addr: string) => all.slice(0, all.length - addr.length),
|
|
353
|
+
);
|
|
354
|
+
return s;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export interface OverloadSummaryOutput {
|
|
358
|
+
firstObservedAt?: number;
|
|
359
|
+
lastObservedAt?: number;
|
|
360
|
+
cursorStart?: number;
|
|
361
|
+
cursorEnd?: number;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export type OverloadEnterReason = "drop-ratio" | "line-rate" | "drop-ratio+line-rate";
|
|
365
|
+
|
|
366
|
+
export interface OverloadControllerOptions {
|
|
367
|
+
clock?: Clock;
|
|
368
|
+
windowMs?: number;
|
|
369
|
+
summaryLinesPerSec?: number;
|
|
370
|
+
dropRatio?: number;
|
|
371
|
+
minimumBatches?: number;
|
|
372
|
+
stopLinesPerSec?: number;
|
|
373
|
+
stopSustainMs?: number;
|
|
374
|
+
exitQuietMs?: number;
|
|
375
|
+
cadenceMs?: number[];
|
|
376
|
+
maxChars?: number;
|
|
377
|
+
maxSignatures?: number;
|
|
378
|
+
onSummary?: (text: string, output: OverloadSummaryOutput) => void;
|
|
379
|
+
onEnter?: (reason: OverloadEnterReason) => void;
|
|
380
|
+
onExit?: () => void;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export interface OverloadInput {
|
|
384
|
+
lines: number;
|
|
385
|
+
bytes: number;
|
|
386
|
+
text?: string;
|
|
387
|
+
cursorStart?: number;
|
|
388
|
+
cursorEnd?: number;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Overload policy: summary on rolling input line-rate or drop-ratio;
|
|
393
|
+
* stop only on unverified extreme sustained line rate.
|
|
394
|
+
*
|
|
395
|
+
* INPUT (line-rate / stop / interval bytes) is complete raw records (`kind:"line"`)
|
|
396
|
+
* or newline-terminated chunks counted in acceptOutput, before the token bucket.
|
|
397
|
+
* Later-deduped lines still count as input; dedup does not consume tokens or the drop budget.
|
|
398
|
+
* Interval signature stats begin at summary-mode entry (line-rate trigger included;
|
|
399
|
+
* drop-ratio entry starts empty), then reset on each emitted summary.
|
|
400
|
+
*/
|
|
401
|
+
export class OverloadController {
|
|
402
|
+
private readonly clock: Clock;
|
|
403
|
+
private readonly windowMs: number;
|
|
404
|
+
private readonly summaryLinesPerSec: number;
|
|
405
|
+
private readonly stopLinesPerSec: number;
|
|
406
|
+
private readonly stopSustainMs: number;
|
|
407
|
+
private readonly exitQuietMs: number;
|
|
408
|
+
private readonly cadenceMs: number[];
|
|
409
|
+
private readonly maxChars: number;
|
|
410
|
+
private readonly maxSignatures: number;
|
|
411
|
+
private readonly onSummary?: OverloadControllerOptions["onSummary"];
|
|
412
|
+
private readonly onEnter?: OverloadControllerOptions["onEnter"];
|
|
413
|
+
private readonly onExit?: OverloadControllerOptions["onExit"];
|
|
414
|
+
private readonly saturation: SaturationWindow;
|
|
415
|
+
private readonly lineBuckets: { sec: number; n: number; firstAt: number }[] = [];
|
|
416
|
+
private signatures = new Map<string, { count: number; extra: number }>();
|
|
417
|
+
private previousSigs = new Set<string>();
|
|
418
|
+
private sigSeq = 0;
|
|
419
|
+
private interval = emptyInterval();
|
|
420
|
+
private firstInputAt: number | undefined;
|
|
421
|
+
private summaryMode = false;
|
|
422
|
+
private cadenceIndex = 0;
|
|
423
|
+
private belowSince: number | undefined;
|
|
424
|
+
private cadenceTimer: ClockTimer | null = null;
|
|
425
|
+
private exitTimer: ClockTimer | null = null;
|
|
426
|
+
private watchTimer: ClockTimer | null = null;
|
|
427
|
+
private disposed = false;
|
|
428
|
+
|
|
429
|
+
constructor(opts: OverloadControllerOptions = {}) {
|
|
430
|
+
this.clock = opts.clock ?? realClock;
|
|
431
|
+
this.windowMs = opts.windowMs ?? OVERLOAD_WINDOW_MS;
|
|
432
|
+
this.summaryLinesPerSec = opts.summaryLinesPerSec ?? OVERLOAD_SUMMARY_LINES_PER_SEC;
|
|
433
|
+
this.stopLinesPerSec = opts.stopLinesPerSec ?? OVERLOAD_STOP_LINES_PER_SEC;
|
|
434
|
+
this.stopSustainMs = opts.stopSustainMs ?? OVERLOAD_STOP_SUSTAIN_MS;
|
|
435
|
+
this.exitQuietMs = opts.exitQuietMs ?? OVERLOAD_EXIT_QUIET_MS;
|
|
436
|
+
this.cadenceMs = opts.cadenceMs ?? [...SUMMARY_CADENCE_MS];
|
|
437
|
+
this.maxChars = opts.maxChars ?? SUMMARY_MAX_CHARS;
|
|
438
|
+
this.maxSignatures = opts.maxSignatures ?? SUMMARY_MAX_SIGNATURES;
|
|
439
|
+
this.onSummary = opts.onSummary;
|
|
440
|
+
this.onEnter = opts.onEnter;
|
|
441
|
+
this.onExit = opts.onExit;
|
|
442
|
+
this.saturation = new SaturationWindow({
|
|
443
|
+
windowMs: this.windowMs,
|
|
444
|
+
dropRatio: opts.dropRatio ?? 0.5,
|
|
445
|
+
minimumBatches: opts.minimumBatches ?? 10,
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
inSummary(): boolean {
|
|
450
|
+
return this.summaryMode;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
shouldStop(): boolean {
|
|
454
|
+
return this.sustainedStop(this.clock.now());
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
stopNotice(): string {
|
|
458
|
+
const secs = Math.round(this.stopSustainMs / 1000);
|
|
459
|
+
return `[Monitor stopped: input exceeded ~${this.stopLinesPerSec} lines/s for ${secs}s (unverified safety backstop).]`;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
recordInput(input: OverloadInput): void {
|
|
463
|
+
if (this.disposed) return;
|
|
464
|
+
const now = this.clock.now();
|
|
465
|
+
const lines = Math.max(0, input.lines);
|
|
466
|
+
if (lines > 0) this.addLineBucket(lines, now);
|
|
467
|
+
const wasSummary = this.summaryMode;
|
|
468
|
+
if (wasSummary) {
|
|
469
|
+
if (lines > 0 || input.bytes > 0) this.addInterval(input, now);
|
|
470
|
+
this.evaluateExit(now);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
this.maybeEnter(now);
|
|
474
|
+
// Line-rate entry includes the triggering input; drop-ratio entry stays empty.
|
|
475
|
+
if (this.summaryMode && this.lineRateHigh(now) && (lines > 0 || input.bytes > 0)) {
|
|
476
|
+
this.addInterval(input, now);
|
|
477
|
+
}
|
|
478
|
+
this.evaluateExit(now);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
recordBatch(dropped: boolean): void {
|
|
482
|
+
if (this.disposed) return;
|
|
483
|
+
const now = this.clock.now();
|
|
484
|
+
this.saturation.record(dropped, now);
|
|
485
|
+
this.maybeEnter(now);
|
|
486
|
+
this.evaluateExit(now);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Emit a non-empty interval immediately (terminal notices), without advancing cadence. */
|
|
490
|
+
flushSummary(): void {
|
|
491
|
+
if (this.disposed || !this.summaryMode || this.interval.lines <= 0) return;
|
|
492
|
+
this.emitSummary();
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
signatureStateForTest(): Map<string, number> {
|
|
496
|
+
return new Map([...this.signatures].map(([k, v]) => [k, v.count]));
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
bucketCountForTest(): number {
|
|
500
|
+
return this.lineBuckets.length;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
dropBucketCountForTest(): number {
|
|
504
|
+
return this.saturation.bucketCountForTest();
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
dispose(): void {
|
|
508
|
+
this.disposed = true;
|
|
509
|
+
this.clearCadence();
|
|
510
|
+
this.clearExit();
|
|
511
|
+
this.clearWatch();
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
private maybeEnter(now: number): void {
|
|
515
|
+
if (this.summaryMode) return;
|
|
516
|
+
const drop = this.saturation.isSaturated(now);
|
|
517
|
+
const rate = this.lineRateHigh(now);
|
|
518
|
+
if (!drop && !rate) return;
|
|
519
|
+
this.summaryMode = true;
|
|
520
|
+
this.cadenceIndex = 0;
|
|
521
|
+
this.belowSince = undefined;
|
|
522
|
+
this.clearExit();
|
|
523
|
+
this.armCadence(this.cadenceMs[0] ?? 30_000);
|
|
524
|
+
this.armWatch();
|
|
525
|
+
const reason: OverloadEnterReason = drop && rate ? "drop-ratio+line-rate" : drop ? "drop-ratio" : "line-rate";
|
|
526
|
+
this.onEnter?.(reason);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
private evaluateExit(now: number): void {
|
|
530
|
+
if (!this.summaryMode) return;
|
|
531
|
+
const busy = this.lineRateHigh(now) || this.saturation.isSaturated(now);
|
|
532
|
+
if (busy) {
|
|
533
|
+
this.belowSince = undefined;
|
|
534
|
+
this.clearExit();
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (this.belowSince === undefined) {
|
|
538
|
+
this.belowSince = now;
|
|
539
|
+
this.armExit(this.exitQuietMs);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
private leaveSummary(): void {
|
|
544
|
+
if (this.interval.lines > 0) this.emitSummary();
|
|
545
|
+
this.onExit?.();
|
|
546
|
+
this.summaryMode = false;
|
|
547
|
+
this.cadenceIndex = 0;
|
|
548
|
+
this.belowSince = undefined;
|
|
549
|
+
this.interval = emptyInterval();
|
|
550
|
+
this.signatures = new Map();
|
|
551
|
+
this.previousSigs = new Set();
|
|
552
|
+
this.clearCadence();
|
|
553
|
+
this.clearExit();
|
|
554
|
+
this.clearWatch();
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
private onCadenceDue(): void {
|
|
558
|
+
this.cadenceTimer = null;
|
|
559
|
+
if (this.disposed || !this.summaryMode) return;
|
|
560
|
+
this.evaluateExit(this.clock.now());
|
|
561
|
+
if (!this.summaryMode) return;
|
|
562
|
+
if (this.interval.lines > 0) {
|
|
563
|
+
this.emitSummary();
|
|
564
|
+
this.cadenceIndex = Math.min(this.cadenceIndex + 1, this.cadenceMs.length - 1);
|
|
565
|
+
this.armCadence(this.cadenceMs[this.cadenceIndex] ?? 300_000);
|
|
566
|
+
} else {
|
|
567
|
+
this.armCadence(this.cadenceMs[this.cadenceIndex] ?? 30_000);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
private emitSummary(): void {
|
|
572
|
+
let newSignatures = 0;
|
|
573
|
+
for (const key of this.signatures.keys()) {
|
|
574
|
+
if (!this.previousSigs.has(key)) newSignatures += 1;
|
|
575
|
+
}
|
|
576
|
+
const text = formatOverloadSummary(this.interval, this.signatures, this.maxChars, newSignatures);
|
|
577
|
+
const output: OverloadSummaryOutput = {
|
|
578
|
+
firstObservedAt: this.interval.firstAt,
|
|
579
|
+
lastObservedAt: this.interval.lastAt,
|
|
580
|
+
cursorStart: this.interval.cursorStart,
|
|
581
|
+
cursorEnd: this.interval.cursorEnd,
|
|
582
|
+
};
|
|
583
|
+
this.previousSigs = new Set(this.signatures.keys());
|
|
584
|
+
this.interval = emptyInterval();
|
|
585
|
+
this.signatures = new Map();
|
|
586
|
+
this.onSummary?.(text, output);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
private addLineBucket(n: number, now: number): void {
|
|
590
|
+
if (this.firstInputAt === undefined) this.firstInputAt = now;
|
|
591
|
+
const sec = Math.floor(now / 1000);
|
|
592
|
+
const last = this.lineBuckets[this.lineBuckets.length - 1];
|
|
593
|
+
if (last && last.sec === sec) {
|
|
594
|
+
const wasBelowStop = last.n < this.stopLinesPerSec;
|
|
595
|
+
last.n += n;
|
|
596
|
+
// Earlier low-rate input in this second is not the start of the flood.
|
|
597
|
+
if (wasBelowStop && last.n >= this.stopLinesPerSec) last.firstAt = now;
|
|
598
|
+
} else {
|
|
599
|
+
this.lineBuckets.push({ sec, n, firstAt: now });
|
|
600
|
+
}
|
|
601
|
+
const cutoffSec = Math.floor((now - Math.max(this.windowMs, this.stopSustainMs)) / 1000) - 1;
|
|
602
|
+
while (this.lineBuckets.length > 0 && this.lineBuckets[0].sec < cutoffSec) this.lineBuckets.shift();
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** Average over the last `window` completed seconds; the current partial second is excluded. */
|
|
606
|
+
private lineRate(now: number): number {
|
|
607
|
+
const windowSecs = Math.max(1, Math.round(this.windowMs / 1000));
|
|
608
|
+
const currentSec = Math.floor(now / 1000);
|
|
609
|
+
const fromSec = currentSec - windowSecs;
|
|
610
|
+
const toSec = currentSec - 1;
|
|
611
|
+
let n = 0;
|
|
612
|
+
for (const b of this.lineBuckets) {
|
|
613
|
+
if (b.sec >= fromSec && b.sec <= toSec) n += b.n;
|
|
614
|
+
}
|
|
615
|
+
return n / windowSecs;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** Rolling average over the nominal window; a single burst does not fill the window. */
|
|
619
|
+
private lineRateHigh(now: number): boolean {
|
|
620
|
+
if (this.firstInputAt === undefined || now - this.firstInputAt < this.windowMs) return false;
|
|
621
|
+
return this.lineRate(now) > this.summaryLinesPerSec;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
private sustainedStop(now: number): boolean {
|
|
625
|
+
const need = Math.max(1, Math.round(this.stopSustainMs / 1000));
|
|
626
|
+
const currentSec = Math.floor(now / 1000);
|
|
627
|
+
const from = currentSec - need;
|
|
628
|
+
const to = currentSec - 1;
|
|
629
|
+
if (to < from) return false;
|
|
630
|
+
let i = 0;
|
|
631
|
+
let runFirstAt: number | undefined;
|
|
632
|
+
for (let sec = from; sec <= to; sec++) {
|
|
633
|
+
while (i < this.lineBuckets.length && this.lineBuckets[i].sec < sec) i++;
|
|
634
|
+
const bucket = this.lineBuckets[i];
|
|
635
|
+
if (!bucket || bucket.sec !== sec || bucket.n < this.stopLinesPerSec) return false;
|
|
636
|
+
if (runFirstAt === undefined) runFirstAt = bucket.firstAt;
|
|
637
|
+
}
|
|
638
|
+
return runFirstAt !== undefined && now - runFirstAt >= this.stopSustainMs;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
private addInterval(input: OverloadInput, now: number): void {
|
|
642
|
+
this.interval.lines += Math.max(0, input.lines);
|
|
643
|
+
this.interval.bytes += Math.max(0, input.bytes);
|
|
644
|
+
if (this.interval.firstAt === undefined) this.interval.firstAt = now;
|
|
645
|
+
this.interval.lastAt = now;
|
|
646
|
+
if (input.cursorStart !== undefined) {
|
|
647
|
+
this.interval.cursorStart = this.interval.cursorStart === undefined
|
|
648
|
+
? input.cursorStart
|
|
649
|
+
: Math.min(this.interval.cursorStart, input.cursorStart);
|
|
650
|
+
}
|
|
651
|
+
if (input.cursorEnd !== undefined) {
|
|
652
|
+
this.interval.cursorEnd = this.interval.cursorEnd === undefined
|
|
653
|
+
? input.cursorEnd
|
|
654
|
+
: Math.max(this.interval.cursorEnd, input.cursorEnd);
|
|
655
|
+
}
|
|
656
|
+
this.addSignatures(input.text ?? "", input.lines);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
private addSignatures(text: string, lines: number): void {
|
|
660
|
+
const parts = text.split("\n").filter((line) => line.length > 0);
|
|
661
|
+
if (parts.length === 0) return;
|
|
662
|
+
// Compact form: one line with no newlines uses `lines` as frequency.
|
|
663
|
+
// Empty lines never add signature frequency; they still count in interval lines/bytes.
|
|
664
|
+
if (!text.includes("\n")) {
|
|
665
|
+
this.addSignature(parts[0], Math.max(1, lines));
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
for (const part of parts) this.addSignature(part, 1);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
private addSignature(line: string, count: number): void {
|
|
672
|
+
const key = normalizeSignature(line);
|
|
673
|
+
if (!key) return;
|
|
674
|
+
const existing = this.signatures.get(key);
|
|
675
|
+
if (existing) {
|
|
676
|
+
existing.count += count;
|
|
677
|
+
existing.extra = ++this.sigSeq;
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
while (this.signatures.size >= this.maxSignatures) this.evictLeastFrequent();
|
|
681
|
+
this.signatures.set(key, { count, extra: ++this.sigSeq });
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
private evictLeastFrequent(): void {
|
|
685
|
+
let worst: string | undefined;
|
|
686
|
+
let worstCount = Infinity;
|
|
687
|
+
let worstSeq = Infinity;
|
|
688
|
+
for (const [key, val] of this.signatures) {
|
|
689
|
+
if (val.count < worstCount || (val.count === worstCount && val.extra < worstSeq)) {
|
|
690
|
+
worst = key;
|
|
691
|
+
worstCount = val.count;
|
|
692
|
+
worstSeq = val.extra;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (worst !== undefined) this.signatures.delete(worst);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
private armCadence(delayMs: number): void {
|
|
699
|
+
this.clearCadence();
|
|
700
|
+
this.cadenceTimer = this.clock.setTimeout(() => this.onCadenceDue(), delayMs);
|
|
701
|
+
this.clock.unref?.(this.cadenceTimer);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
private armExit(delayMs: number): void {
|
|
705
|
+
this.clearExit();
|
|
706
|
+
this.exitTimer = this.clock.setTimeout(() => {
|
|
707
|
+
this.exitTimer = null;
|
|
708
|
+
if (this.disposed || !this.summaryMode) return;
|
|
709
|
+
const now = this.clock.now();
|
|
710
|
+
const busy = this.lineRateHigh(now) || this.saturation.isSaturated(now);
|
|
711
|
+
if (busy) {
|
|
712
|
+
this.belowSince = undefined;
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
this.leaveSummary();
|
|
716
|
+
}, delayMs);
|
|
717
|
+
this.clock.unref?.(this.exitTimer);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
private clearCadence(): void {
|
|
721
|
+
if (this.cadenceTimer !== null) {
|
|
722
|
+
this.clock.clearTimeout(this.cadenceTimer);
|
|
723
|
+
this.cadenceTimer = null;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
private clearExit(): void {
|
|
728
|
+
if (this.exitTimer !== null) {
|
|
729
|
+
this.clock.clearTimeout(this.exitTimer);
|
|
730
|
+
this.exitTimer = null;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
private armWatch(): void {
|
|
735
|
+
this.clearWatch();
|
|
736
|
+
this.watchTimer = this.clock.setInterval(() => {
|
|
737
|
+
if (this.disposed || !this.summaryMode) return;
|
|
738
|
+
this.evaluateExit(this.clock.now());
|
|
739
|
+
}, 1000);
|
|
740
|
+
this.clock.unref?.(this.watchTimer);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
private clearWatch(): void {
|
|
744
|
+
if (this.watchTimer !== null) {
|
|
745
|
+
this.clock.clearInterval(this.watchTimer);
|
|
746
|
+
this.watchTimer = null;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function emptyInterval(): {
|
|
752
|
+
lines: number;
|
|
753
|
+
bytes: number;
|
|
754
|
+
firstAt?: number;
|
|
755
|
+
lastAt?: number;
|
|
756
|
+
cursorStart?: number;
|
|
757
|
+
cursorEnd?: number;
|
|
758
|
+
} {
|
|
759
|
+
return { lines: 0, bytes: 0 };
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function formatOverloadSummary(
|
|
763
|
+
interval: { lines: number; bytes: number; firstAt?: number; lastAt?: number; cursorStart?: number; cursorEnd?: number },
|
|
764
|
+
signatures: Map<string, { count: number; extra: number }>,
|
|
765
|
+
maxChars: number,
|
|
766
|
+
newSignatures: number,
|
|
767
|
+
): string {
|
|
768
|
+
const top = [...signatures.entries()].sort((a, b) => b[1].count - a[1].count || a[1].extra - b[1].extra).slice(0, 3);
|
|
769
|
+
const other = Math.max(0, signatures.size - top.length);
|
|
770
|
+
const header = [
|
|
771
|
+
"[Monitor overload summary]",
|
|
772
|
+
`lines=${interval.lines} bytes=${interval.bytes} from=${interval.firstAt ?? "-"} to=${interval.lastAt ?? "-"} cursor=${interval.cursorStart ?? "-"}-${interval.cursorEnd ?? "-"}`,
|
|
773
|
+
`raw via task_output cursor=${interval.cursorStart ?? "-"}-${interval.cursorEnd ?? "-"}`,
|
|
774
|
+
];
|
|
775
|
+
const rows = top.map(([sig, val]) => `${sig} x${val.count}`);
|
|
776
|
+
if (other > 0) rows.push(`+${other} other signatures`);
|
|
777
|
+
rows.push(`${newSignatures} new since previous`);
|
|
778
|
+
let text = [...header, ...rows].join("\n");
|
|
779
|
+
if (text.length <= maxChars) return text;
|
|
780
|
+
text = header.join("\n");
|
|
781
|
+
for (const row of rows) {
|
|
782
|
+
const next = `${text}\n${row}`;
|
|
783
|
+
if (next.length > maxChars) break;
|
|
784
|
+
text = next;
|
|
785
|
+
}
|
|
786
|
+
if (text.length > maxChars) text = text.slice(0, Math.max(0, maxChars));
|
|
787
|
+
return text;
|
|
788
|
+
}
|