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/notify.ts
CHANGED
|
@@ -13,13 +13,92 @@
|
|
|
13
13
|
* <pi-famulus-wake kind="task"> payload, and the same task/event pair is only
|
|
14
14
|
* ever delivered once.
|
|
15
15
|
*/
|
|
16
|
-
import { formatMonitorEvent, formatTaskNotification, type TaskExitInfo } from "./format";
|
|
16
|
+
import { 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
|
|
|
20
|
+
/**
|
|
21
|
+
* Fixed, non-resetting window that coalesces timeout/exited/stopped monitor notices.
|
|
22
|
+
* Nearby expiries share one wake for completeness. A busy agent is already turn-bound,
|
|
23
|
+
* so this adds no extra delay before the next turn. An idle agent with a single exit
|
|
24
|
+
* may wake up to 10s later. The window starts on the first notice and does not reset;
|
|
25
|
+
* NotifyCenter.flush() and session teardown release pending terminals immediately.
|
|
26
|
+
*/
|
|
27
|
+
export const MONITOR_TERMINAL_BATCH_MS = 10_000;
|
|
28
|
+
|
|
29
|
+
const TERMINAL_STATUS_RANK: Record<MonitorTerminalStatus, number> = {
|
|
30
|
+
exited: 1,
|
|
31
|
+
stopped: 2,
|
|
32
|
+
timeout: 3,
|
|
33
|
+
};
|
|
34
|
+
|
|
20
35
|
|
|
21
36
|
type MonitorDeliveryAck = (visiblePreview?: string) => void;
|
|
22
37
|
|
|
38
|
+
const MONITOR_TERMINAL_STATUSES = new Set<string>(["timeout", "exited", "stopped"]);
|
|
39
|
+
|
|
40
|
+
function isMonitorTerminalStatus(status: string | undefined): status is MonitorTerminalStatus {
|
|
41
|
+
return status !== undefined && MONITOR_TERMINAL_STATUSES.has(status);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface PendingMonitorTerminal {
|
|
45
|
+
id: string;
|
|
46
|
+
description: string;
|
|
47
|
+
status: MonitorTerminalStatus;
|
|
48
|
+
event: string;
|
|
49
|
+
droppedLines?: number;
|
|
50
|
+
output?: MonitorOutputInfo;
|
|
51
|
+
exitFacts?: import("./wake").MonitorExitFacts;
|
|
52
|
+
exitContext?: string;
|
|
53
|
+
passive: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function mergeTerminal(previous: PendingMonitorTerminal, next: PendingMonitorTerminal, onConflict: (fields: string[]) => void): PendingMonitorTerminal {
|
|
57
|
+
const status =
|
|
58
|
+
TERMINAL_STATUS_RANK[next.status] > TERMINAL_STATUS_RANK[previous.status] ? next.status : previous.status;
|
|
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;
|
|
87
|
+
const description = next.description.length > previous.description.length ? next.description : previous.description;
|
|
88
|
+
const droppedLines = Math.max(previous.droppedLines ?? 0, next.droppedLines ?? 0);
|
|
89
|
+
return {
|
|
90
|
+
id: previous.id,
|
|
91
|
+
description,
|
|
92
|
+
status,
|
|
93
|
+
event,
|
|
94
|
+
...(droppedLines > 0 ? { droppedLines } : {}),
|
|
95
|
+
output: mergeMonitorOutput(previous.output, next.output),
|
|
96
|
+
exitFacts,
|
|
97
|
+
exitContext,
|
|
98
|
+
passive: previous.passive && next.passive,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
23
102
|
export interface NotifyMessage {
|
|
24
103
|
customType: string;
|
|
25
104
|
content: string;
|
|
@@ -113,10 +192,15 @@ export class NotifyCenter {
|
|
|
113
192
|
>();
|
|
114
193
|
private readonly seen = new Set<string>();
|
|
115
194
|
private timer: ClockTimer | null = null;
|
|
195
|
+
private pendingTerminals: PendingMonitorTerminal[] = [];
|
|
196
|
+
private terminalTimer: ClockTimer | null = null;
|
|
197
|
+
/** Ids already delivered in a monitor-terminal wake; late duplicates do not open another window. */
|
|
198
|
+
private readonly seenTerminalIds = new Set<string>();
|
|
116
199
|
private disposed = false;
|
|
117
200
|
/** A wake started or steered a run that has not settled yet. */
|
|
118
201
|
private runPending = false;
|
|
119
|
-
private
|
|
202
|
+
private holdAll = false;
|
|
203
|
+
private held: { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean }[] = [];
|
|
120
204
|
|
|
121
205
|
constructor(deps: NotifyCenterDeps) {
|
|
122
206
|
this.deps = deps;
|
|
@@ -144,14 +228,41 @@ export class NotifyCenter {
|
|
|
144
228
|
* Send a notification immediately, routed by idle/busy state. A monitor's
|
|
145
229
|
* own notice (exit, timeout, stop) first delivers that monitor's coalesced
|
|
146
230
|
* events: they happened before it, and the model must not hear "exited"
|
|
147
|
-
* ahead of the lines the command printed.
|
|
231
|
+
* ahead of the lines the command printed. timeout/exited/stopped notices then
|
|
232
|
+
* join one fixed 10s window rather than each starting a turn.
|
|
148
233
|
*/
|
|
149
234
|
notify(message: NotifyMessage, opts: { passive?: boolean; quietEvents?: boolean } = {}): void {
|
|
150
235
|
if (this.disposed) return;
|
|
236
|
+
const wake = message.details as {
|
|
237
|
+
kind?: string;
|
|
238
|
+
id?: string;
|
|
239
|
+
description?: string;
|
|
240
|
+
status?: string;
|
|
241
|
+
event?: string;
|
|
242
|
+
droppedLines?: number;
|
|
243
|
+
output?: MonitorOutputInfo;
|
|
244
|
+
exitFacts?: import("./wake").MonitorExitFacts;
|
|
245
|
+
exitContext?: string;
|
|
246
|
+
} | undefined;
|
|
247
|
+
if (wake?.kind === "monitor" && typeof wake.id === "string") {
|
|
248
|
+
this.flushMonitor(wake.id, opts.quietEvents);
|
|
249
|
+
if (isMonitorTerminalStatus(wake.status)) {
|
|
250
|
+
this.queueTerminal({
|
|
251
|
+
id: wake.id,
|
|
252
|
+
description: wake.description ?? wake.id,
|
|
253
|
+
status: wake.status,
|
|
254
|
+
event: wake.event ?? "",
|
|
255
|
+
droppedLines: wake.droppedLines,
|
|
256
|
+
output: wake.output,
|
|
257
|
+
exitFacts: wake.exitFacts,
|
|
258
|
+
exitContext: wake.exitContext,
|
|
259
|
+
passive: opts.passive === true,
|
|
260
|
+
});
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
151
264
|
// Stamped on arrival: a held passive notice keeps the time it was built.
|
|
152
265
|
message = stampWakeAsOf(message, this.clock.now());
|
|
153
|
-
const wake = message.details as { kind?: string; id?: string } | undefined;
|
|
154
|
-
if (wake?.kind === "monitor" && typeof wake.id === "string") this.flushMonitor(wake.id, opts.quietEvents);
|
|
155
266
|
if (!opts.passive) {
|
|
156
267
|
this.deliver(message);
|
|
157
268
|
} else {
|
|
@@ -161,7 +272,7 @@ export class NotifyCenter {
|
|
|
161
272
|
|
|
162
273
|
private deliverPassive(message: NotifyMessage, onDelivered?: MonitorDeliveryAck, sourcePreview?: string): void {
|
|
163
274
|
message = stampWakeAsOf(message, this.clock.now());
|
|
164
|
-
if (this.runPending || !this.deps.isIdle()) this.held.push({ message, onDelivered, sourcePreview });
|
|
275
|
+
if (this.holdAll || this.runPending || !this.deps.isIdle()) this.held.push({ message, onDelivered, sourcePreview, passive: true });
|
|
165
276
|
else this.deliver(message, true, onDelivered, sourcePreview);
|
|
166
277
|
}
|
|
167
278
|
|
|
@@ -175,7 +286,58 @@ export class NotifyCenter {
|
|
|
175
286
|
this.runPending = false;
|
|
176
287
|
this.flushMonitorEvents();
|
|
177
288
|
if (this.runPending) return;
|
|
178
|
-
for (const
|
|
289
|
+
for (const item of this.held.splice(0)) {
|
|
290
|
+
this.deliver(item.message, item.passive === true, item.onDelivered, item.sourcePreview);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Compaction is in progress: do not send; coalesced/held wakes wait for {@link settledAfterCompact}. */
|
|
295
|
+
beginHold(): void {
|
|
296
|
+
if (this.disposed) return;
|
|
297
|
+
this.holdAll = true;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
endHold(): void {
|
|
301
|
+
this.holdAll = false;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* After compaction has actually gone idle: drain held/pending wakes and an
|
|
306
|
+
* optional passive running-monitor list. If any active wake exists, append
|
|
307
|
+
* the entire batch before the final message starts one turn.
|
|
308
|
+
*/
|
|
309
|
+
settledAfterCompact(extra?: NotifyMessage): void {
|
|
310
|
+
if (this.disposed) return;
|
|
311
|
+
this.holdAll = false;
|
|
312
|
+
this.runPending = false;
|
|
313
|
+
const batch: { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean }[] = [];
|
|
314
|
+
for (const taskId of [...this.pendingMonitors.keys()]) {
|
|
315
|
+
const item = this.takeMonitor(taskId);
|
|
316
|
+
if (item) batch.push(item);
|
|
317
|
+
}
|
|
318
|
+
const terminals = this.takePendingTerminals();
|
|
319
|
+
if (terminals.length > 0) {
|
|
320
|
+
const ids = new Set(terminals.map((item) => item.id));
|
|
321
|
+
batch.push(...this.takeHeldMonitorEvents(ids));
|
|
322
|
+
const wake = formatMonitorTerminal(terminals);
|
|
323
|
+
batch.push({
|
|
324
|
+
message: { customType: wake.customType, content: wake.content, details: wake.details },
|
|
325
|
+
passive: terminals.every((item) => item.passive),
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
batch.push(...this.held.splice(0));
|
|
329
|
+
if (extra) batch.push({ message: extra, passive: true });
|
|
330
|
+
if (batch.length === 0) return;
|
|
331
|
+
const anyActive = batch.some((item) => !item.passive);
|
|
332
|
+
if (extra && anyActive) {
|
|
333
|
+
const list = batch.pop()!;
|
|
334
|
+
let lastActive = batch.length - 1;
|
|
335
|
+
while (lastActive >= 0 && batch[lastActive].passive) lastActive--;
|
|
336
|
+
batch.splice(lastActive, 0, list);
|
|
337
|
+
}
|
|
338
|
+
for (let i = 0; i < batch.length; i++) {
|
|
339
|
+
this.sendCompactFlush(batch[i], anyActive && i === batch.length - 1);
|
|
340
|
+
}
|
|
179
341
|
}
|
|
180
342
|
|
|
181
343
|
/**
|
|
@@ -194,7 +356,7 @@ export class NotifyCenter {
|
|
|
194
356
|
if (pending?.onDelivered && opts.onDelivered && pending.onDelivered !== opts.onDelivered) {
|
|
195
357
|
throw new Error(`Monitor ${taskId} requires a stable onDelivered callback while pending`);
|
|
196
358
|
}
|
|
197
|
-
if (this.deps.isIdle() && !pending && !opts.quiet) {
|
|
359
|
+
if (this.deps.isIdle() && !this.holdAll && !pending && !opts.quiet) {
|
|
198
360
|
const wake = formatMonitorEvent(description, taskId, event, undefined, { droppedLines, output: opts.output });
|
|
199
361
|
this.deliver({ customType: wake.customType, content: wake.content, details: wake.details }, false, opts.onDelivered);
|
|
200
362
|
return;
|
|
@@ -219,8 +381,15 @@ export class NotifyCenter {
|
|
|
219
381
|
|
|
220
382
|
/** Deliver one monitor's coalesced events, if any, in the current mode. */
|
|
221
383
|
private flushMonitor(taskId: string, quiet = false): void {
|
|
222
|
-
const item = this.
|
|
384
|
+
const item = this.takeMonitor(taskId, quiet);
|
|
223
385
|
if (!item) return;
|
|
386
|
+
if (item.passive) this.deliverPassive(item.message, item.onDelivered, item.sourcePreview);
|
|
387
|
+
else this.deliver(item.message, false, item.onDelivered, item.sourcePreview);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private takeMonitor(taskId: string, quiet = false): { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean } | undefined {
|
|
391
|
+
const item = this.pendingMonitors.get(taskId);
|
|
392
|
+
if (!item) return undefined;
|
|
224
393
|
this.pendingMonitors.delete(taskId);
|
|
225
394
|
const { head, tail, omittedChars } = item.preview;
|
|
226
395
|
const preview = omittedChars > 0 ? `${head}\n[... ${omittedChars} characters omitted ...]\n${tail}` : head;
|
|
@@ -239,23 +408,135 @@ export class NotifyCenter {
|
|
|
239
408
|
tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : "",
|
|
240
409
|
].filter(Boolean).join("\n")
|
|
241
410
|
: head;
|
|
242
|
-
|
|
243
|
-
else this.deliver(message, false, item.onDelivered, sourcePreview);
|
|
411
|
+
return { message, onDelivered: item.onDelivered, sourcePreview, passive: quiet || item.quiet };
|
|
244
412
|
}
|
|
245
413
|
|
|
246
|
-
/** Flush any pending task exit notifications now. */
|
|
414
|
+
/** Flush any pending task exit notifications and monitor-terminal notices now. */
|
|
247
415
|
flush(): void {
|
|
248
416
|
this.clearTimer();
|
|
249
417
|
this.flushExits();
|
|
418
|
+
this.flushAllTerminals();
|
|
250
419
|
this.flushMonitorEvents();
|
|
251
420
|
}
|
|
252
421
|
|
|
422
|
+
/**
|
|
423
|
+
* Take pending monitor-terminal items without sending through pi.
|
|
424
|
+
* File teardown appends each returned message to the old session file instead.
|
|
425
|
+
* Held output for those terminal ids comes first, in held order; the terminal wake is last.
|
|
426
|
+
* Taking a held output message counts as delivery for its acknowledgement.
|
|
427
|
+
*/
|
|
428
|
+
drainPendingMonitorTerminals(): NotifyMessage[] {
|
|
429
|
+
const items = this.takePendingTerminals();
|
|
430
|
+
const ids = new Set(items.map((item) => item.id));
|
|
431
|
+
for (const item of this.held) {
|
|
432
|
+
const details = item.message.details as { kind?: string } | undefined;
|
|
433
|
+
if (details?.kind === "monitor-terminal") {
|
|
434
|
+
for (const id of wakeIds(details)) ids.add(id);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (items.length === 0 && ids.size === 0) return [];
|
|
438
|
+
const held = this.takeHeldMonitorEvents(ids, true);
|
|
439
|
+
const messages: NotifyMessage[] = [];
|
|
440
|
+
for (const item of held) {
|
|
441
|
+
messages.push(item.message);
|
|
442
|
+
this.acknowledgeHeld(item);
|
|
443
|
+
}
|
|
444
|
+
if (items.length > 0) {
|
|
445
|
+
const wake = formatMonitorTerminal(items);
|
|
446
|
+
messages.push({ customType: wake.customType, content: wake.content, details: wake.details });
|
|
447
|
+
}
|
|
448
|
+
return messages;
|
|
449
|
+
}
|
|
450
|
+
|
|
253
451
|
dispose(): void {
|
|
254
|
-
this.disposed
|
|
452
|
+
if (this.disposed) return;
|
|
255
453
|
this.clearTimer();
|
|
454
|
+
this.flushAllTerminals();
|
|
455
|
+
const leftover = this.held.splice(0);
|
|
456
|
+
this.disposed = true;
|
|
457
|
+
this.clearTerminalTimer();
|
|
256
458
|
this.pendingExits = [];
|
|
257
459
|
this.pendingMonitors.clear();
|
|
258
|
-
this.
|
|
460
|
+
this.pendingTerminals = [];
|
|
461
|
+
for (const { message, onDelivered, sourcePreview } of leftover) {
|
|
462
|
+
this.deliver(message, true, onDelivered, sourcePreview);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private queueTerminal(item: PendingMonitorTerminal): void {
|
|
467
|
+
if (this.seenTerminalIds.has(item.id)) return;
|
|
468
|
+
const existing = this.pendingTerminals.findIndex((pending) => pending.id === item.id);
|
|
469
|
+
if (existing >= 0) {
|
|
470
|
+
this.pendingTerminals[existing] = mergeTerminal(this.pendingTerminals[existing], item, (fields) => {
|
|
471
|
+
this.deps.logEvent?.("monitor.exit-facts-conflict", { id: item.id, fields });
|
|
472
|
+
});
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
this.pendingTerminals.push(item);
|
|
476
|
+
if (this.terminalTimer !== null) return;
|
|
477
|
+
this.terminalTimer = this.clock.setTimeout(() => {
|
|
478
|
+
this.terminalTimer = null;
|
|
479
|
+
this.flushAllTerminals();
|
|
480
|
+
}, MONITOR_TERMINAL_BATCH_MS);
|
|
481
|
+
this.clock.unref?.(this.terminalTimer);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
private takePendingTerminals(): PendingMonitorTerminal[] {
|
|
485
|
+
this.clearTerminalTimer();
|
|
486
|
+
const items = this.pendingTerminals;
|
|
487
|
+
this.pendingTerminals = [];
|
|
488
|
+
for (const item of items) this.seenTerminalIds.add(item.id);
|
|
489
|
+
return items;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
private takeHeldMonitorEvents(ids: Set<string>, includeTerminals = false): typeof this.held {
|
|
493
|
+
if (this.held.length === 0) return [];
|
|
494
|
+
if (ids.size === 0 && !includeTerminals) return [];
|
|
495
|
+
const rest: typeof this.held = [];
|
|
496
|
+
const drain: typeof this.held = [];
|
|
497
|
+
for (const item of this.held) {
|
|
498
|
+
const details = item.message.details as { kind?: string; id?: string } | undefined;
|
|
499
|
+
if (details?.kind === "monitor" && typeof details.id === "string" && ids.has(details.id)) drain.push(item);
|
|
500
|
+
else if (includeTerminals && details?.kind === "monitor-terminal" && wakeIds(details).some((id) => ids.has(id))) drain.push(item);
|
|
501
|
+
else rest.push(item);
|
|
502
|
+
}
|
|
503
|
+
this.held = rest;
|
|
504
|
+
return drain;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
private acknowledgeHeld(item: (typeof this.held)[number]): void {
|
|
508
|
+
const details = item.message.details as { kind?: string; event?: string } | undefined;
|
|
509
|
+
item.onDelivered?.(item.sourcePreview ?? (details?.kind === "monitor" ? details.event : undefined));
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
private drainHeldMonitorEvents(ids: Set<string>): void {
|
|
513
|
+
for (const { message, onDelivered, sourcePreview } of this.takeHeldMonitorEvents(ids)) {
|
|
514
|
+
this.deliver(message, true, onDelivered, sourcePreview);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
private flushAllTerminals(): void {
|
|
519
|
+
const items = this.takePendingTerminals();
|
|
520
|
+
if (items.length === 0) return;
|
|
521
|
+
const ids = new Set(items.map((item) => item.id));
|
|
522
|
+
const allPassive = items.every((item) => item.passive);
|
|
523
|
+
const hold = this.runPending || !this.deps.isIdle();
|
|
524
|
+
const wake = formatMonitorTerminal(items);
|
|
525
|
+
const message = { customType: wake.customType, content: wake.content, details: wake.details };
|
|
526
|
+
if (allPassive && hold) {
|
|
527
|
+
this.deliverPassive(message);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
this.drainHeldMonitorEvents(ids);
|
|
531
|
+
if (allPassive) this.deliverPassive(message);
|
|
532
|
+
else this.deliver(message);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private clearTerminalTimer(): void {
|
|
536
|
+
if (this.terminalTimer !== null) {
|
|
537
|
+
this.clock.clearTimeout(this.terminalTimer);
|
|
538
|
+
this.terminalTimer = null;
|
|
539
|
+
}
|
|
259
540
|
}
|
|
260
541
|
|
|
261
542
|
private scheduleFlush(): void {
|
|
@@ -286,9 +567,35 @@ export class NotifyCenter {
|
|
|
286
567
|
});
|
|
287
568
|
}
|
|
288
569
|
|
|
570
|
+
private sendCompactFlush(
|
|
571
|
+
item: { message: NotifyMessage; onDelivered?: MonitorDeliveryAck; sourcePreview?: string; passive?: boolean },
|
|
572
|
+
triggerTurn: boolean,
|
|
573
|
+
): void {
|
|
574
|
+
const message = stampWakeAsOf(item.message, this.clock.now());
|
|
575
|
+
const msg = { ...message, display: true };
|
|
576
|
+
const details = message.details as { kind?: string; eventCount?: number; event?: string } | undefined;
|
|
577
|
+
if (details?.kind) {
|
|
578
|
+
const ids = wakeIds(details);
|
|
579
|
+
this.deps.logEvent?.("wake.emit", {
|
|
580
|
+
kind: details.kind,
|
|
581
|
+
ids,
|
|
582
|
+
batch: ids.length > 1 || (details.kind === "monitor" && (details.eventCount ?? 0) > 1),
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
const mode = triggerTurn ? "trigger" : item.passive ? "passive" : "append";
|
|
586
|
+
this.deps.logEvent?.("wake.deliver", { kind: details?.kind ?? "unknown", mode });
|
|
587
|
+
if (triggerTurn) this.runPending = true;
|
|
588
|
+
this.deps.sendMessage(msg, { triggerTurn });
|
|
589
|
+
item.onDelivered?.(item.sourcePreview ?? (details?.kind === "monitor" ? details.event : undefined));
|
|
590
|
+
}
|
|
591
|
+
|
|
289
592
|
private deliver(message: NotifyMessage, passive = false, onDelivered?: MonitorDeliveryAck, sourcePreview?: string): void {
|
|
290
593
|
// Wakes built here (task batches, monitor events) are stamped now.
|
|
291
594
|
message = stampWakeAsOf(message, this.clock.now());
|
|
595
|
+
if (this.holdAll) {
|
|
596
|
+
this.held.push({ message, onDelivered, sourcePreview, passive });
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
292
599
|
const msg = { ...message, display: true };
|
|
293
600
|
const details = message.details as { kind?: string; eventCount?: number } | undefined;
|
|
294
601
|
if (details?.kind) {
|
|
@@ -313,3 +620,147 @@ export class NotifyCenter {
|
|
|
313
620
|
}
|
|
314
621
|
|
|
315
622
|
}
|
|
623
|
+
|
|
624
|
+
/** Next-tick idle check with 25ms retry; new run/compaction callers cancel. */
|
|
625
|
+
export function scheduleIdleCheck(opts: {
|
|
626
|
+
isReady: () => boolean;
|
|
627
|
+
onReady: () => void;
|
|
628
|
+
setTimeout?: typeof setTimeout;
|
|
629
|
+
clearTimeout?: typeof clearTimeout;
|
|
630
|
+
}): { cancel: () => void } {
|
|
631
|
+
const start = opts.setTimeout ?? setTimeout;
|
|
632
|
+
const stop = opts.clearTimeout ?? clearTimeout;
|
|
633
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
634
|
+
let cancelled = false;
|
|
635
|
+
const tick = (delayMs: number) => {
|
|
636
|
+
timer = start(() => {
|
|
637
|
+
timer = undefined;
|
|
638
|
+
if (cancelled) return;
|
|
639
|
+
if (!opts.isReady()) {
|
|
640
|
+
tick(25);
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
opts.onReady();
|
|
644
|
+
}, delayMs);
|
|
645
|
+
timer.unref?.();
|
|
646
|
+
};
|
|
647
|
+
tick(0);
|
|
648
|
+
return {
|
|
649
|
+
cancel() {
|
|
650
|
+
cancelled = true;
|
|
651
|
+
if (timer !== undefined) stop(timer);
|
|
652
|
+
timer = undefined;
|
|
653
|
+
},
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
export function attachCompactRecovery(
|
|
658
|
+
pi: { on(event: string, handler: (event: unknown, ctx: { isIdle(): boolean; hasPendingMessages?: () => boolean }) => unknown): unknown },
|
|
659
|
+
deps: {
|
|
660
|
+
getCenter: () => NotifyCenter | null;
|
|
661
|
+
getCtx: () => { isIdle(): boolean; hasPendingMessages?: () => boolean } | null;
|
|
662
|
+
listRunningMonitors: () => { id: string; description: string; remaining: string; wakeOn?: string }[];
|
|
663
|
+
now?: () => number;
|
|
664
|
+
setTimeout?: typeof setTimeout;
|
|
665
|
+
clearTimeout?: typeof clearTimeout;
|
|
666
|
+
idleHoldMs?: number;
|
|
667
|
+
maxHoldMs?: number;
|
|
668
|
+
},
|
|
669
|
+
): { dispose: () => void } {
|
|
670
|
+
const idleHoldMs = deps.idleHoldMs ?? 1_000;
|
|
671
|
+
const maxHoldMs = deps.maxHoldMs ?? 600_000;
|
|
672
|
+
const now = deps.now ?? Date.now;
|
|
673
|
+
const startTimer = deps.setTimeout ?? setTimeout;
|
|
674
|
+
const stopTimer = deps.clearTimeout ?? clearTimeout;
|
|
675
|
+
let handle: { cancel: () => void } | undefined;
|
|
676
|
+
let watchdog: { cancel: () => void } | undefined;
|
|
677
|
+
const cancel = () => {
|
|
678
|
+
handle?.cancel();
|
|
679
|
+
handle = undefined;
|
|
680
|
+
watchdog?.cancel();
|
|
681
|
+
watchdog = undefined;
|
|
682
|
+
};
|
|
683
|
+
const flushHeld = () => {
|
|
684
|
+
cancel();
|
|
685
|
+
const center = deps.getCenter();
|
|
686
|
+
if (!center) return;
|
|
687
|
+
const running = deps.listRunningMonitors();
|
|
688
|
+
const extra = running.length > 0 ? formatRunningMonitorList(running) : undefined;
|
|
689
|
+
center.settledAfterCompact(extra);
|
|
690
|
+
};
|
|
691
|
+
const startWatchdog = () => {
|
|
692
|
+
watchdog?.cancel();
|
|
693
|
+
const holdStarted = now();
|
|
694
|
+
let idleSince: number | undefined;
|
|
695
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
696
|
+
let cancelled = false;
|
|
697
|
+
const tick = () => {
|
|
698
|
+
timer = startTimer(() => {
|
|
699
|
+
timer = undefined;
|
|
700
|
+
if (cancelled) return;
|
|
701
|
+
const t = now();
|
|
702
|
+
if (t - holdStarted >= maxHoldMs) {
|
|
703
|
+
flushHeld();
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
const ctx = deps.getCtx();
|
|
707
|
+
const idle = !!ctx && ctx.isIdle() && ctx.hasPendingMessages?.() !== true;
|
|
708
|
+
if (idle) {
|
|
709
|
+
idleSince ??= t;
|
|
710
|
+
if (t - idleSince >= idleHoldMs) {
|
|
711
|
+
flushHeld();
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
} else {
|
|
715
|
+
idleSince = undefined;
|
|
716
|
+
}
|
|
717
|
+
tick();
|
|
718
|
+
}, 25);
|
|
719
|
+
timer.unref?.();
|
|
720
|
+
};
|
|
721
|
+
tick();
|
|
722
|
+
watchdog = {
|
|
723
|
+
cancel() {
|
|
724
|
+
cancelled = true;
|
|
725
|
+
if (timer !== undefined) stopTimer(timer);
|
|
726
|
+
timer = undefined;
|
|
727
|
+
},
|
|
728
|
+
};
|
|
729
|
+
};
|
|
730
|
+
const afterCompact = () => {
|
|
731
|
+
cancel();
|
|
732
|
+
handle = scheduleIdleCheck({
|
|
733
|
+
isReady: () => {
|
|
734
|
+
const ctx = deps.getCtx();
|
|
735
|
+
return !!ctx && ctx.isIdle() && ctx.hasPendingMessages?.() !== true;
|
|
736
|
+
},
|
|
737
|
+
onReady: () => {
|
|
738
|
+
handle = undefined;
|
|
739
|
+
flushHeld();
|
|
740
|
+
},
|
|
741
|
+
setTimeout: startTimer,
|
|
742
|
+
clearTimeout: stopTimer,
|
|
743
|
+
});
|
|
744
|
+
};
|
|
745
|
+
pi.on("session_before_compact", () => {
|
|
746
|
+
cancel();
|
|
747
|
+
deps.getCenter()?.beginHold();
|
|
748
|
+
startWatchdog();
|
|
749
|
+
});
|
|
750
|
+
pi.on("session_compact", afterCompact);
|
|
751
|
+
pi.on("session_compact_failed", afterCompact);
|
|
752
|
+
pi.on("before_agent_start", () => {
|
|
753
|
+
cancel();
|
|
754
|
+
deps.getCenter()?.endHold();
|
|
755
|
+
});
|
|
756
|
+
pi.on("agent_start", () => {
|
|
757
|
+
cancel();
|
|
758
|
+
deps.getCenter()?.endHold();
|
|
759
|
+
});
|
|
760
|
+
return {
|
|
761
|
+
dispose() {
|
|
762
|
+
cancel();
|
|
763
|
+
deps.getCenter()?.endHold();
|
|
764
|
+
},
|
|
765
|
+
};
|
|
766
|
+
}
|