pi-famulus 0.2.3 → 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 +2 -2
- package/package.json +7 -7
- package/src/config.ts +4 -0
- package/src/format.ts +33 -5
- package/src/idle-turn-guard.ts +118 -0
- package/src/index.ts +7 -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 +175 -16
- package/src/notify.ts +42 -5
- package/src/prompts.generated.ts +25 -10
- package/src/task-tools.ts +34 -15
- package/src/tui/message-renderers.ts +3 -3
- package/src/wake.ts +14 -3
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();
|
|
@@ -178,6 +196,26 @@ export class MonitorRegistry {
|
|
|
178
196
|
throw new RangeError("fingerprint_mode must be exact or ignore-timestamps");
|
|
179
197
|
}
|
|
180
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
|
+
}
|
|
181
219
|
let timeoutMs: number | null = null;
|
|
182
220
|
if (!persistent) {
|
|
183
221
|
const requested = params.timeout_ms ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -216,6 +254,11 @@ export class MonitorRegistry {
|
|
|
216
254
|
cursor: 0,
|
|
217
255
|
recovering: false,
|
|
218
256
|
queuedOutput: [],
|
|
257
|
+
wakeOn,
|
|
258
|
+
stallAfterMs: params.stall_after_ms ?? null,
|
|
259
|
+
stallTimer: null,
|
|
260
|
+
lastActivityAt: now,
|
|
261
|
+
stallNotified: false,
|
|
219
262
|
};
|
|
220
263
|
entry.overload = new OverloadController({
|
|
221
264
|
clock: this.clock,
|
|
@@ -245,6 +288,7 @@ export class MonitorRegistry {
|
|
|
245
288
|
}, timeoutMs);
|
|
246
289
|
this.clock.unref?.(entry.timeoutTimer);
|
|
247
290
|
}
|
|
291
|
+
if (entry.stallAfterMs !== null) this.armStall(entry, entry.stallAfterMs);
|
|
248
292
|
this.entries.set(task_id, entry);
|
|
249
293
|
this.emitChange();
|
|
250
294
|
// Replay what arrived before we knew the id: lines first, then the exit.
|
|
@@ -297,6 +341,7 @@ export class MonitorRegistry {
|
|
|
297
341
|
// Empty metadata arrays deliberately hold raw fragments for Rust framing.
|
|
298
342
|
entry.batcher.flush();
|
|
299
343
|
const accepted: MonitorOutputRecord[] = [];
|
|
344
|
+
let filteredLines = 0;
|
|
300
345
|
let metadataTookOver = false;
|
|
301
346
|
for (const record of records) {
|
|
302
347
|
if (!validRecord(record, entry.cursor)) continue;
|
|
@@ -305,10 +350,18 @@ export class MonitorRegistry {
|
|
|
305
350
|
entry.recordCursor = record.cursor_end;
|
|
306
351
|
entry.lastRecordKind = record.kind;
|
|
307
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
|
+
}
|
|
308
360
|
entry.output.push(record);
|
|
309
361
|
if (record.kind === "line") accepted.push(record);
|
|
310
362
|
}
|
|
311
363
|
if (metadataTookOver) entry.legacyLines.reset();
|
|
364
|
+
this.noteFilteredLines(entry, filteredLines);
|
|
312
365
|
if (accepted.length > 0) {
|
|
313
366
|
this.noteInput(entry, {
|
|
314
367
|
lines: accepted.length,
|
|
@@ -323,12 +376,21 @@ export class MonitorRegistry {
|
|
|
323
376
|
entry.output.flush();
|
|
324
377
|
const cursorStart = Math.max(previousCursor, entry.cursor - deliver.byteLength);
|
|
325
378
|
const text = deliver.toString("utf8");
|
|
326
|
-
if (text.includes("\n"))
|
|
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
|
+
}
|
|
327
390
|
entry.legacyOutput = mergeOutputInfo(entry.legacyOutput, {
|
|
328
391
|
firstObservedAt: this.clock.now(), lastObservedAt: this.clock.now(),
|
|
329
392
|
cursorStart, cursorEnd: entry.cursor,
|
|
330
393
|
});
|
|
331
|
-
const assembled = entry.legacyLines.push(text, deliver.byteLength, cursorStart, entry.cursor);
|
|
332
394
|
if (assembled) {
|
|
333
395
|
this.noteInput(entry, {
|
|
334
396
|
lines: assembled.lines,
|
|
@@ -342,6 +404,68 @@ export class MonitorRegistry {
|
|
|
342
404
|
}
|
|
343
405
|
}
|
|
344
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;
|
|
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
|
+
|
|
345
469
|
/** Count complete raw lines/chunks before limiter (includes later-deduped lines). */
|
|
346
470
|
private noteInput(entry: MonitorEntry, input: { lines: number; bytes: number; text: string; cursorStart: number; cursorEnd: number }): void {
|
|
347
471
|
entry.overload.recordInput(input);
|
|
@@ -373,7 +497,12 @@ export class MonitorRegistry {
|
|
|
373
497
|
this.earlyFor(taskId).exit = event;
|
|
374
498
|
return false;
|
|
375
499
|
}
|
|
376
|
-
// 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
|
+
}
|
|
377
506
|
entry.batcher.flush();
|
|
378
507
|
entry.output.flush();
|
|
379
508
|
const alreadyStopped = entry.stopped;
|
|
@@ -393,19 +522,27 @@ export class MonitorRegistry {
|
|
|
393
522
|
this.clock.now() - entry.lastEventAt <= EXIT_AFTER_EVENT_MS;
|
|
394
523
|
const duration =
|
|
395
524
|
typeof event.duration_ms === "number" ? `${(event.duration_ms / 1000).toFixed(1)}s` : "unknown duration";
|
|
396
|
-
|
|
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" });
|
|
397
534
|
this.deps.getNotifyCenter()?.notify(
|
|
398
535
|
formatMonitorEvent(
|
|
399
536
|
entry.description,
|
|
400
537
|
entry.taskId,
|
|
401
|
-
|
|
538
|
+
detail,
|
|
402
539
|
"exited",
|
|
403
|
-
{ droppedLines: entry.droppedLinesPending, ...(summary.suppressedCount ? { output: summary } : {}) },
|
|
540
|
+
{ droppedLines: entry.droppedLinesPending, exitFacts: facts, exitContext, ...(summary.suppressedCount ? { output: summary } : {}) },
|
|
404
541
|
),
|
|
405
542
|
{ passive: causedByEvent || entry.stopRequested === true, quietEvents: entry.stopRequested === true },
|
|
406
543
|
);
|
|
407
544
|
this.deps.toast?.(
|
|
408
|
-
`Monitor "${entry.description}"
|
|
545
|
+
`Monitor "${entry.description}": ${detail}`,
|
|
409
546
|
exitCode === 0 || exitCode === null ? "info" : "warning",
|
|
410
547
|
);
|
|
411
548
|
return true;
|
|
@@ -525,17 +662,20 @@ export class MonitorRegistry {
|
|
|
525
662
|
entry.stopped = true;
|
|
526
663
|
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "timeout" });
|
|
527
664
|
const client = this.deps.getClient();
|
|
528
|
-
|
|
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.";
|
|
529
669
|
this.deps.getNotifyCenter()?.notify(
|
|
530
670
|
formatMonitorEvent(
|
|
531
671
|
entry.description,
|
|
532
672
|
entry.taskId,
|
|
533
|
-
|
|
673
|
+
`Timeout elapsed. ${stopDetail}`,
|
|
534
674
|
"timeout",
|
|
535
675
|
{ droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
|
|
536
676
|
),
|
|
537
677
|
);
|
|
538
|
-
this.deps.toast?.(`Monitor "${entry.description}"
|
|
678
|
+
this.deps.toast?.(`Monitor "${entry.description}": timeout elapsed. ${stopDetail}`, "warning");
|
|
539
679
|
this.cleanup(entry);
|
|
540
680
|
this.deps.afterStop?.();
|
|
541
681
|
}
|
|
@@ -551,18 +691,21 @@ export class MonitorRegistry {
|
|
|
551
691
|
entry.stopped = true;
|
|
552
692
|
this.deps.logEvent?.("monitor.stop", { id: entry.taskId, reason: "rate-limit" });
|
|
553
693
|
const client = this.deps.getClient();
|
|
554
|
-
|
|
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.";
|
|
555
698
|
this.deps.getNotifyCenter()?.notify(
|
|
556
699
|
formatMonitorEvent(
|
|
557
700
|
entry.description,
|
|
558
701
|
entry.taskId,
|
|
559
|
-
entry.overload.stopNotice()
|
|
702
|
+
`${entry.overload.stopNotice()} ${stopDetail}`,
|
|
560
703
|
"stopped",
|
|
561
704
|
{ droppedLines: entry.droppedLinesPending, output: entry.output.takeSummary() },
|
|
562
705
|
),
|
|
563
706
|
);
|
|
564
707
|
this.deps.toast?.(
|
|
565
|
-
`Monitor "${entry.description}"
|
|
708
|
+
`Monitor "${entry.description}": input rate safety backstop. ${stopDetail}`,
|
|
566
709
|
"warning",
|
|
567
710
|
);
|
|
568
711
|
this.cleanup(entry);
|
|
@@ -579,11 +722,19 @@ export class MonitorRegistry {
|
|
|
579
722
|
this.clock.clearTimeout(entry.timeoutTimer);
|
|
580
723
|
entry.timeoutTimer = null;
|
|
581
724
|
}
|
|
725
|
+
if (entry.stallTimer !== null) {
|
|
726
|
+
this.clock.clearTimeout(entry.stallTimer);
|
|
727
|
+
entry.stallTimer = null;
|
|
728
|
+
}
|
|
582
729
|
this.entries.delete(entry.taskId);
|
|
583
730
|
this.emitChange();
|
|
584
731
|
}
|
|
585
732
|
}
|
|
586
733
|
|
|
734
|
+
function admits(entry: MonitorEntry, line: string): boolean {
|
|
735
|
+
return entry.wakeOn === null || entry.wakeOn.test(line);
|
|
736
|
+
}
|
|
737
|
+
|
|
587
738
|
function validRecord(record: MonitorOutputRecord, cursor: number): boolean {
|
|
588
739
|
return record?.version === 1 && (record.kind === "line" || record.kind === "progress") &&
|
|
589
740
|
typeof record.preview === "string" && record.preview.length <= 2000 &&
|
|
@@ -629,6 +780,14 @@ const monitorParameters = Type.Object({
|
|
|
629
780
|
persistent: Type.Optional(Type.Boolean({ description: PROMPTS["tools.monitor.param.persistent"] })),
|
|
630
781
|
dedup_window_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 3_600_000, description: PROMPTS["tools.monitor.param.dedup_window_ms"] })),
|
|
631
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
|
+
),
|
|
632
791
|
});
|
|
633
792
|
|
|
634
793
|
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;
|
package/src/prompts.generated.ts
CHANGED
|
@@ -5,6 +5,8 @@ export const PROMPTS = {
|
|
|
5
5
|
"agents.explorer.system-prompt": "You are an explorer agent. Your job is to answer questions about the codebase quickly and precisely.\n\nRules:\n- Return findings, never change code. You are strictly read-only: do not edit, write, or create files.\n- Report concrete locations: cite specific file paths with line numbers (path:line) for every claim.\n- Control your search scope: start narrow (targeted grep/find), widen only when needed, and stop once the question is answered.\n- Prefer a short, factual summary over exhaustive dumps. List what you found and where.",
|
|
6
6
|
"agents.worker.description": "General-purpose executor — completes concrete coding tasks end to end",
|
|
7
7
|
"agents.worker.system-prompt": "You are a worker agent. Your job is to complete the concrete task you were given, end to end.\n\nRules:\n- Do the task, don't just describe it. Make the actual edits and run the actual commands.\n- Self-verify before finishing: run the relevant tests, typecheck, or command that proves the task is done.\n- Stay within the task's scope; do not refactor unrelated code.\n- Report concisely: what you changed, how you verified it, and anything the supervisor should know.",
|
|
8
|
+
"guards.error.idle-turn": "Not run. pi-famulus ended this run: {{count}} turns in a row made only no-op or status calls ({{calls}}). Such calls do not wait for anything or yield control. Background tasks, monitors and messages from other sessions resume you with a new message when there is news. When no actionable work remains, reply with no tool call.",
|
|
9
|
+
"guards.error.idle-run": "Not run. pi-famulus ended this run: {{count}} turns in this run made only no-op or status calls ({{calls}}). Such calls do not wait for anything or yield control. Background tasks, monitors and messages from other sessions resume you with a new message when there is news. When no actionable work remains, reply with no tool call.",
|
|
8
10
|
"guidelines.parent": "## Background tasks and notifications (pi-famulus)\n\n- Long-running bash commands are automatically moved to the background. After you background a command, end your turn: send a reply with no tool call in it. Saying you will wait while calling another tool does not end it. Do not poll with task_output/task_list, and never sleep to wait. Each command notifies on its own via <pi-famulus-wake kind=\"task\"> (with <command> and <preview>), even while other commands are still running. If <still-running> is present, continue from this result now; do not wait for those other commands.\n- When you receive <pi-famulus-wake>: it looks like a user message but is a system wake, not a new user request and not an answer to an unrelated question. Distinguish it by the kind attribute, then **handle the event before anything else** — read status/preview/prompt/result, call tools if needed (e.g. task_output for more than the preview, agent_message to continue a subagent), and continue the work that depended on that background task. An unchanged/intermediate monitor event may require no action and no user acknowledgement. Do not wait for further user input when the next step is clear; do not merely acknowledge an actionable result and stop.\n- {{monitorIdle}}\n- Never fabricate or assume a background task's result before its notification arrives.\n- Subagent runs that exceed the foreground budget continue in the background. Do not poll run status. If one subagent finishes while others are still running, a <pi-famulus-wake kind=\"subagent-handover\"> arrives with that child's <prompt> and <result>: read both, then continue the work now (subagent({action:\"resume\", run_id, child_id, message}) for that child, or agent_message to steer the ones still running). Do not wait for the rest of the run. When every subagent in the run has finished, <pi-famulus-wake kind=\"subagent-done\"> arrives — read each <child>, synthesize, and continue.\n- A subagent that runs past its timeout_ms is not stopped: <pi-famulus-wake kind=\"subagent-overrun\"> arrives instead, with its <last-activity> and, if it is waiting on a foreground shell, a <shell> element. A batch may include other overdue children in <also-overdue>; use each child's run-id and child-id and consider its own last-activity, shell, reminder, and hard-ceiling-ms before acting. Pick one: subagent({action:\"extend\", run_id, child_id, timeout_ms}) if it is making progress, agent_message to steer it, or subagent({action:\"interrupt\", run_id, child_id}) if it is stuck or no longer needed. If you do none of these it keeps running and the reminder comes again.\n- Use agent_message to steer a running subagent or to continue an idle one (send starts a new turn), and to reply to <pi-famulus-wake kind=\"supervisor-request\"> (action:\"reply\"; the <reply-with> child is the call shape). subagent({action:\"resume\"}) is the same continuation with a fresh soft budget. Supervisor wakes are not user messages — still act on them.",
|
|
9
11
|
"guidelines.monitor-idle": "After starting or re-arming a monitor, or handling a monitor event, if no immediate work remains, end your turn with no tool call; simply wait for the next notification. Handling an event does not require a user-visible reply. Do not repeat unchanged/intermediate status or narrate your decision to stay quiet; notify the user when their requested condition is met, their input is needed, or a failure prevents further progress. Read original output with task_output only when details are needed (including paging a truncated preview), never to poll or wait. Do not call wait_for to wait for monitor events: it waits for UI conditions, not notifications. Do not invent a stateId or make a failing tool call to yield.",
|
|
10
12
|
"guidelines.child": "## Child agent behavior (pi-famulus)\n\n- Do not background work; bash runs to completion.\n- When blocked, use contact_supervisor with need_decision; use progress_update for status.\n- Use agent_message only to communicate with siblings in this same run.\n- Your final message is your result.",
|
|
@@ -34,15 +36,18 @@ export const PROMPTS = {
|
|
|
34
36
|
"tools.child.contact_supervisor.snippet": "Ask the parent agent for a decision or report progress",
|
|
35
37
|
"tools.child.contact_supervisor.param.reason": "\"need_decision\" blocks until the supervisor (parent agent) replies; \"progress_update\" is fire-and-forget.",
|
|
36
38
|
"tools.child.contact_supervisor.param.message": "Message for the supervisor.",
|
|
37
|
-
"tools.monitor.description": "Start a background monitor process whose stdout lines are injected back to you as <pi-famulus-wake kind=\"monitor\"> messages (batched over 200ms, rate-limited). The command must be line-buffered: each event must be a single line. It must keep running and follow its source,
|
|
39
|
+
"tools.monitor.description": "Start a background monitor process whose stdout lines are injected back to you as <pi-famulus-wake kind=\"monitor\"> messages (batched over 200ms, rate-limited). The command must be line-buffered: each event must be a single line. It must keep running and follow its source. When you start the producer yourself, make it the command (`node app.js | grep --line-buffered ALERT`); do not start it in bash and tail its output. Use `tail -n +1 -F file | grep --line-buffered PATTERN` or `journalctl -f` for a source you did not start. A command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep only when the first match should end the watch. Silence is not success: print explicit success and terminal failures of what you watch. Routine unchanged retries may stay silent; without wake_on, do not print a heartbeat on every check. The monitor's own exit or timeout is reported to you; do not add end-of-watch lines. Status lines may stay when you set wake_on to the problem pattern: only matching lines wake you, and task_output keeps every line. Use stall_after_ms instead of heartbeats to learn that the source went silent. Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll. Repeated Rust-framed lines are suppressed within dedup_window_ms (default 60000); exact matching is the default. Enable ignore-timestamps only when edge ISO timestamps are incidental. Wakes contain bounded head/tail previews and original-byte references; use task_output for missing details, not polling. Pick one lifetime. timeout_ms (default 5 minutes, max 1 hour) is for a watch that ends at a known time within an hour; expiry stops the monitor and the notice can arrive late while you are busy. Use persistent:true when the watch is open-ended or longer than an hour (\"rest of the day\", \"until I say\"); do not re-arm timed monitors instead. Never set both, and never put the lifetime inside the command (`timeout 3600`, your own timer). If you use timeouts for several monitors, stagger them. Without wake_on, write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. {{monitorIdle}}",
|
|
38
40
|
"tools.monitor.snippet": "Watch a command's line stream and get injected events",
|
|
39
|
-
"tools.monitor.rules": ["Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash.","{{monitorIdle}}","When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation.","
|
|
41
|
+
"tools.monitor.rules": ["Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash.","{{monitorIdle}}","When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation. Report from the <event> itself; do not re-read the source, task_output or task_list to confirm it.","For a watch that is open-ended or longer than an hour, use persistent:true rather than timeout_ms.","For a persistent monitor, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."],
|
|
40
42
|
"tools.monitor.param.command": "Command producing one event per line on stdout. Must be line-buffered (e.g. use `stdbuf -oL` / `grep --line-buffered` where needed).",
|
|
41
43
|
"tools.monitor.param.description": "Short human-readable description of what is being watched",
|
|
42
|
-
"tools.monitor.param.timeout_ms": "Stop the monitor after this many milliseconds (default {{defaultMs}} / 5 minutes, min {{minMs}}, max {{maxMs}} / 1 hour).",
|
|
43
|
-
"tools.monitor.param.persistent": "
|
|
44
|
+
"tools.monitor.param.timeout_ms": "Stop the monitor after this many milliseconds (default {{defaultMs}} / 5 minutes, min {{minMs}}, max {{maxMs}} / 1 hour). Exclusive with persistent; for longer watches use persistent:true instead of re-arming.",
|
|
45
|
+
"tools.monitor.param.persistent": "No timeout: runs until stopped or the session ends. Default false. Use for open-ended watches or any horizon over 1 hour. Exclusive with timeout_ms.",
|
|
44
46
|
"tools.monitor.param.dedup_window_ms": "Deduplication window for Rust-framed complete lines (default 60000ms; 0 disables dedup; maximum 3600000). Starts when a surviving preview is delivered; repeats do not extend it. Missing metadata, capacity eviction, and omitted representatives fail open rather than hiding unseen output.",
|
|
47
|
+
"tools.monitor.param.wake_on": "JavaScript RegExp source tested against each output line. When set, only matching lines wake you (and only they count for dedup and overload); every line is still recorded for task_output. Exit, timeout and stall notices still arrive. Strongly recommended for persistent monitors: match the problem, e.g. `ERROR|unacked=[1-9]`.",
|
|
48
|
+
"tools.monitor.param.stall_after_ms": "Send one notice when the command prints nothing at all (matching wake_on or not) for this many milliseconds while still running (min {{minMs}}, max {{maxMs}}). The next output re-arms it. Use it instead of heartbeat lines.",
|
|
45
49
|
"tools.monitor.param.fingerprint_mode": "Default exact. Explicit ignore-timestamps mode ignores only supported leading/trailing ISO timestamps when comparing Rust-framed lines; original output is unchanged. Numbers, paths, resource identities, and interior timestamps remain significant.",
|
|
50
|
+
"tools.monitor.event.stalled": "[No output for {{idle}}; the monitor is still running. No further stall notice until output resumes.]",
|
|
46
51
|
"tools.monitor.result.started": "You will get <pi-famulus-wake kind=\"monitor\"> notifications for admitted output and a notice when it exits or times out. Repeated lines may be suppressed and previews may be truncated; original output remains available through task_output byte ranges while the task log is retained. Read details only when needed; do not repeatedly poll task_list, task_output, or the watched source, and do not sleep to wait. {{monitorIdle}}",
|
|
47
52
|
"tools.subagent.description": "Run subagents in parallel (tasks) or sequentially (chain with {previous}/{outputs.<label>} interpolation). By default the call waits up to a foreground budget (default 45s); longer runs continue in the background. Each child that finishes while others are still running wakes you with <pi-famulus-wake kind=\"subagent-handover\"> (its prompt and result). The whole run wakes you with <pi-famulus-wake kind=\"subagent-done\">. Never poll or sleep to wait. A subagent still running past its timeout_ms is not stopped; it wakes you with <pi-famulus-wake kind=\"subagent-overrun\"> so you can extend, steer, or interrupt it. Use action=list/get/status/interrupt/resume/steer/extend to manage existing runs.",
|
|
48
53
|
"tools.subagent.snippet": "Fan out subagents in parallel or sequence them in a chain",
|
|
@@ -84,6 +89,8 @@ export const PROMPTS = {
|
|
|
84
89
|
"tools.task_stop.description": "Stop a running background task (SIGTERM to the process group, SIGKILL after a 2s grace).",
|
|
85
90
|
"tools.task_stop.snippet": "Stop a background task",
|
|
86
91
|
"tools.task_stop.param.task_id": "Task id to stop, e.g. sh_a1b2c3d4",
|
|
92
|
+
"tools.task_stop.result.stopped": "Task {{taskId}} stopped (SIGTERM; SIGKILL after 2s grace if needed).",
|
|
93
|
+
"tools.task_stop.result.already-ended": "Task {{taskId}} had already ended ({{outcome}}); nothing was stopped.",
|
|
87
94
|
"wakes.lead-in": "System wake — not a new user message. Handle this <pi-famulus-wake> before other work.",
|
|
88
95
|
"wakes.monitor.output-hint": "Read original bytes with task_output using this monitor id and cursor-start, with a bounded max_bytes (for example 8192); next_cursor continues the read. The range may include interleaved events. A preview is not the full log.",
|
|
89
96
|
"wakes.running-monitors.guidance": "This is an informational list of monitors still running after compaction, not an event. No response is needed; do not use it to poll.",
|
|
@@ -103,6 +110,8 @@ export type PromptId = keyof typeof PROMPTS;
|
|
|
103
110
|
|
|
104
111
|
/** Placeholder names of each template prompt. */
|
|
105
112
|
export interface PromptVars {
|
|
113
|
+
"guards.error.idle-turn": "count" | "calls";
|
|
114
|
+
"guards.error.idle-run": "count" | "calls";
|
|
106
115
|
"guidelines.parent": "monitorIdle";
|
|
107
116
|
"tools.agent_message.error.finished-child": "childId" | "name" | "status" | "runId";
|
|
108
117
|
"tools.bash.description": "maxLines" | "maxKb";
|
|
@@ -113,6 +122,8 @@ export interface PromptVars {
|
|
|
113
122
|
"tools.monitor.description": "monitorIdle";
|
|
114
123
|
"tools.monitor.rules": "monitorIdle";
|
|
115
124
|
"tools.monitor.param.timeout_ms": "defaultMs" | "minMs" | "maxMs";
|
|
125
|
+
"tools.monitor.param.stall_after_ms": "minMs" | "maxMs";
|
|
126
|
+
"tools.monitor.event.stalled": "idle";
|
|
116
127
|
"tools.monitor.result.started": "monitorIdle";
|
|
117
128
|
"tools.subagent.param.model": "thinkingLevels";
|
|
118
129
|
"tools.subagent.param.timeout_ms": "maxMs";
|
|
@@ -122,6 +133,8 @@ export interface PromptVars {
|
|
|
122
133
|
"tools.subagent.result.resumed": "name" | "childId" | "runId" | "queued";
|
|
123
134
|
"tools.subagent.error.resume-queued": "name" | "childId";
|
|
124
135
|
"tools.task_output.error.no-new-output": "taskId" | "hint";
|
|
136
|
+
"tools.task_stop.result.stopped": "taskId";
|
|
137
|
+
"tools.task_stop.result.already-ended": "taskId" | "outcome";
|
|
125
138
|
"wakes.overrun.summary": "name" | "elapsed" | "budget" | "shell";
|
|
126
139
|
"wakes.overrun.summary-shell": "elapsed";
|
|
127
140
|
"wakes.overrun.actions": "runId" | "childId";
|
|
@@ -168,16 +181,18 @@ export const PROMPT_SEGMENTS: Record<string, { prompt: PromptId; text?: string;
|
|
|
168
181
|
"rules.bash-no-poll": {"prompt":"tools.bash.rules","text":"Long-running bash commands are moved to the background automatically; do not poll or sleep to wait for them."},
|
|
169
182
|
"result.bash-bg-instruction": {"prompt":"tools.bash.result.backgrounded","text":"\nYou will be notified when it completes, even if other commands are still running. Do not poll or sleep: reply to the user now with no tool call, and continue from the <pi-famulus-wake kind=\"task\"> when it arrives."},
|
|
170
183
|
"result.sleep-block-advice": {"prompt":"tools.bash.error.bare-sleep","text":" Do not sleep to wait for background work; completion is delivered via notification. Use the monitor tool to watch for a condition, or run_in_background for long commands."},
|
|
171
|
-
"tooldesc.monitor-follow": {"prompt":"tools.monitor.description","text":"It must keep running and follow its source,
|
|
172
|
-
"tooldesc.monitor-silence": {"prompt":"tools.monitor.description","text":"Silence is not success: print explicit success and terminal failures. Routine unchanged retries may stay silent; do not print a heartbeat on every check. "},
|
|
184
|
+
"tooldesc.monitor-follow": {"prompt":"tools.monitor.description","text":"It must keep running and follow its source. When you start the producer yourself, make it the command (`node app.js | grep --line-buffered ALERT`); do not start it in bash and tail its output. Use `tail -n +1 -F file | grep --line-buffered PATTERN` or `journalctl -f` for a source you did not start. A command that reads once and exits (a plain grep or cat) only reports what is there now. Add `-m1` to grep only when the first match should end the watch. "},
|
|
185
|
+
"tooldesc.monitor-silence": {"prompt":"tools.monitor.description","text":"Silence is not success: print explicit success and terminal failures of what you watch. Routine unchanged retries may stay silent; without wake_on, do not print a heartbeat on every check. The monitor's own exit or timeout is reported to you; do not add end-of-watch lines. "},
|
|
186
|
+
"tooldesc.monitor-wake-on": {"prompt":"tools.monitor.description","text":"Status lines may stay when you set wake_on to the problem pattern: only matching lines wake you, and task_output keeps every line. Use stall_after_ms instead of heartbeats to learn that the source went silent. "},
|
|
173
187
|
"tooldesc.monitor-wake": {"prompt":"tools.monitor.description","text":"Events arrive as system wakes (not new user messages). Handle each <pi-famulus-wake kind=\"monitor\"> before other work. Do not poll."},
|
|
174
|
-
"tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"timeout_ms
|
|
175
|
-
"tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"Use persistent:true
|
|
188
|
+
"tooldesc.monitor-timeout": {"prompt":"tools.monitor.description","text":"Pick one lifetime. timeout_ms (default 5 minutes, max 1 hour) is for a watch that ends at a known time within an hour; expiry stops the monitor and the notice can arrive late while you are busy. "},
|
|
189
|
+
"tooldesc.monitor-persistent": {"prompt":"tools.monitor.description","text":"Use persistent:true when the watch is open-ended or longer than an hour (\"rest of the day\", \"until I say\"); do not re-arm timed monitors instead. Never set both, and never put the lifetime inside the command (`timeout 3600`, your own timer). "},
|
|
176
190
|
"tooldesc.monitor-stagger": {"prompt":"tools.monitor.description","text":"If you use timeouts for several monitors, stagger them. "},
|
|
177
|
-
"tooldesc.monitor-edge": {"prompt":"tools.monitor.description","text":"
|
|
191
|
+
"tooldesc.monitor-edge": {"prompt":"tools.monitor.description","text":"Without wake_on, write edge-triggered commands: normally zero output, one line only for a new problem signature, and one recovery line. "},
|
|
178
192
|
"tooldesc.monitor-sampling": {"prompt":"tools.monitor.description","text":"Sampling windows must not overlap and must not leave gaps (window = interval), or keep a cursor/last-seen state in the script and report only new items. "},
|
|
179
193
|
"rules.monitor-use": {"prompt":"tools.monitor.rules","text":"Use the monitor tool to watch for conditions instead of running sleep/poll loops in bash."},
|
|
180
|
-
"rules.monitor-wake": {"prompt":"tools.monitor.rules","text":"When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation."},
|
|
194
|
+
"rules.monitor-wake": {"prompt":"tools.monitor.rules","text":"When woken by a <pi-famulus-wake kind=\"monitor\">, handle the <event> before doing anything else — it is not a new user request and not user confirmation. Report from the <event> itself; do not re-read the source, task_output or task_list to confirm it."},
|
|
195
|
+
"rules.monitor-wake-on": {"prompt":"tools.monitor.rules","text":"For a persistent monitor, set wake_on to the problem pattern so only problems wake you, and stall_after_ms instead of heartbeats."},
|
|
181
196
|
"result.monitor-started-instruction": {"prompt":"tools.monitor.result.started","text":"You will get <pi-famulus-wake kind=\"monitor\"> notifications for admitted output and a notice when it exits or times out. Repeated lines may be suppressed and previews may be truncated; original output remains available through task_output byte ranges while the task log is retained. Read details only when needed; do not repeatedly poll task_list, task_output, or the watched source, and do not sleep to wait."},
|
|
182
197
|
"tooldesc.subagent-wakes": {"prompt":"tools.subagent.description","text":"Each child that finishes while others are still running wakes you with <pi-famulus-wake kind=\"subagent-handover\"> (its prompt and result). The whole run wakes you with <pi-famulus-wake kind=\"subagent-done\">. Never poll or sleep to wait. "},
|
|
183
198
|
"tooldesc.subagent-overrun": {"prompt":"tools.subagent.description","text":"A subagent still running past its timeout_ms is not stopped; it wakes you with <pi-famulus-wake kind=\"subagent-overrun\"> so you can extend, steer, or interrupt it. "},
|