pi-better-subagents 0.28.2 → 0.29.1

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/timing.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  * the durable `RunMeta.timing` record written at launch (so /reload keeps it);
12
12
  * - `foldProgress` reads the child's own `--mode json` event stream into a
13
13
  * progress state (what counts as progress is defined once, below);
14
- * - `decideTiming` says what is due at `now` (steer, one parent wake, a stop);
14
+ * - `decideTiming` says what is due at `now` (steer, a parent wake, a stop);
15
15
  * - `describeTiming` renders the reason for list/output/result/callbacks.
16
16
  *
17
17
  * The host (index.ts) performs the side effects: writing the steer request the
@@ -28,11 +28,17 @@
28
28
  * possibly hung command can opt into a ceiling.
29
29
  *
30
30
  * Because silence inside a running call is waiting, not being stuck, the
31
- * parent also records the call it last saw open in the durable timing record
32
- * (`inFlight`). A later parent (after `/reload`, or after a log rewrite) that
33
- * can only read a bounded window may not see the call's start; the record is
34
- * the still-alive evidence that keeps a silent build from being reported as
35
- * stuck or stopped mid-call (#620).
31
+ * parent also records the calls it saw open in the durable timing record
32
+ * (`openCalls`, with `inFlight` retained for older records). A later parent
33
+ * (after `/reload`, or after a log rewrite) that can only read a bounded window
34
+ * may not see a call's start; the record is the still-alive evidence that keeps
35
+ * a silent build from being reported as stuck or stopped mid-call (#620).
36
+ *
37
+ * Waiting itself is still reportable: independently of the stuck window, one
38
+ * tool call that remains open for `toolWaitMs` (default 5 minutes) gets one
39
+ * factual parent wake. The once-per-call marker is durable, so a reload does
40
+ * not repeat it, and parallel calls alert independently. The wake never stops,
41
+ * cancels, or restarts the run.
36
42
  */
37
43
 
38
44
  import { createHash } from "node:crypto";
@@ -40,11 +46,20 @@ import { createHash } from "node:crypto";
40
46
  export type TimingStopReason = "deadline" | "ceiling";
41
47
  export type TimingReason = TimingStopReason | "stuck";
42
48
 
49
+ /** One call the parent observed open, persisted so a bounded reload read keeps its wait. */
50
+ export interface OpenCallRecord {
51
+ id: string;
52
+ since: number;
53
+ name?: string;
54
+ command?: string;
55
+ }
56
+
43
57
  /** Built-in defaults, in minutes. `0` disables that control. */
44
58
  export const DEFAULT_TIMING_MINUTES = Object.freeze({
45
59
  deadline: 0,
46
60
  grace: 5,
47
61
  max: 0,
62
+ toolWait: 5,
48
63
  stuck: 10,
49
64
  });
50
65
 
@@ -58,6 +73,8 @@ export interface RunTiming {
58
73
  ceilingAt?: number;
59
74
  /** No-progress window. Absent = stuck detection off. */
60
75
  stuckMs?: number;
76
+ /** Tool-call wait window. Absent = tool-wait alerts off. */
77
+ toolWaitMs?: number;
61
78
  /** When the wrap-up steer was requested from the child. */
62
79
  steerRequestedAt?: number;
63
80
  /** When the steer entered the child's conversation (grace starts here). */
@@ -71,12 +88,16 @@ export interface RunTiming {
71
88
  /** Latest progress seen by the parent (floor for a reload whose log read is bounded). */
72
89
  lastProgressAt?: number;
73
90
  /**
74
- * Tool call the parent last observed open, so a bounded reload read cannot
75
- * turn a child that is waiting on a command into "no progress" (#620).
91
+ * First tool call the parent last observed open. Kept for older records;
92
+ * `openCalls` carries every parallel call.
76
93
  * `since` is when the open set became non-empty, which is also the pause
77
94
  * start used once its result arrives.
78
95
  */
79
96
  inFlight?: { id: string; since: number };
97
+ /** Every tool call the parent last observed open, including parallel calls. */
98
+ openCalls?: OpenCallRecord[];
99
+ /** Call ids whose long-wait alert was handed off (or intentionally suppressed). */
100
+ toolWaitAlerted?: string[];
80
101
  /** Set when the harness stopped the run. */
81
102
  stopReason?: TimingStopReason;
82
103
  stoppedAt?: number;
@@ -86,6 +107,7 @@ export interface TimingParams {
86
107
  deadline_minutes?: number | null;
87
108
  grace_minutes?: number | null;
88
109
  max_minutes?: number | null;
110
+ tool_wait_minutes?: number | null;
89
111
  stuck_minutes?: number | null;
90
112
  }
91
113
 
@@ -93,6 +115,7 @@ export interface TimingSettings {
93
115
  deadlineMinutes?: number | null;
94
116
  graceMinutes?: number | null;
95
117
  maxMinutes?: number | null;
118
+ toolWaitMinutes?: number | null;
96
119
  stuckMinutes?: number | null;
97
120
  }
98
121
 
@@ -100,13 +123,31 @@ export const TIMING_ENV = Object.freeze({
100
123
  deadline: "PI_SUBAGENT_DEADLINE_MINUTES",
101
124
  grace: "PI_SUBAGENT_GRACE_MINUTES",
102
125
  max: "PI_SUBAGENT_MAX_MINUTES",
126
+ toolWait: "PI_SUBAGENT_TOOL_WAIT_MINUTES",
103
127
  stuck: "PI_SUBAGENT_STUCK_MINUTES",
104
128
  });
105
129
 
106
- const PARAM_KEYS = ["deadline_minutes", "grace_minutes", "max_minutes", "stuck_minutes"] as const;
130
+ const PARAM_KEYS = ["deadline_minutes", "grace_minutes", "max_minutes", "tool_wait_minutes", "stuck_minutes"] as const;
107
131
  const MAX_MINUTES = 7 * 24 * 60;
108
132
  const MINUTE = 60_000;
109
133
 
134
+ /** Largest accepted timing value, in minutes. */
135
+ export const MAX_TIMING_MINUTES = MAX_MINUTES;
136
+
137
+ /** Whether a value is a valid setting: finite minutes from 0 through one week. */
138
+ export function isTimingMinutes(value: unknown): value is number {
139
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_MINUTES;
140
+ }
141
+
142
+ /** Validate one explicit setting value. `0` disables; strings are accepted for env input. */
143
+ export function validatedTimingMinutes(value: unknown, label = "minutes"): number {
144
+ const parsed = minutes(value, label);
145
+ if (parsed === undefined) {
146
+ throw new Error(`${label} must be a number of minutes from 0 to ${MAX_MINUTES} (0 disables); got ${JSON.stringify(value)}.`);
147
+ }
148
+ return parsed;
149
+ }
150
+
110
151
  /**
111
152
  * One optional minutes value. `undefined`, `null`, and (for env) an empty
112
153
  * string mean "not set". Anything else must be a finite number from 0 to a
@@ -153,12 +194,15 @@ export function resolveRunTiming(input: {
153
194
  ["grace_minutes", TIMING_ENV.grace, "graceMinutes"]);
154
195
  const max = pick(p.max_minutes, env[TIMING_ENV.max], s.maxMinutes, DEFAULT_TIMING_MINUTES.max,
155
196
  ["max_minutes", TIMING_ENV.max, "maxMinutes"]);
197
+ const toolWait = pick(p.tool_wait_minutes, env[TIMING_ENV.toolWait], s.toolWaitMinutes, DEFAULT_TIMING_MINUTES.toolWait,
198
+ ["tool_wait_minutes", TIMING_ENV.toolWait, "toolWaitMinutes"]);
156
199
  const stuck = pick(p.stuck_minutes, env[TIMING_ENV.stuck], s.stuckMinutes, DEFAULT_TIMING_MINUTES.stuck,
157
200
  ["stuck_minutes", TIMING_ENV.stuck, "stuckMinutes"]);
158
201
  return {
159
202
  ...(deadline > 0 ? { deadlineAt: input.startedAt + Math.round(deadline * MINUTE) } : {}),
160
203
  graceMs: Math.round(grace * MINUTE),
161
204
  ...(max > 0 ? { ceilingAt: input.startedAt + Math.round(max * MINUTE) } : {}),
205
+ ...(toolWait > 0 ? { toolWaitMs: Math.round(toolWait * MINUTE) } : {}),
162
206
  ...(stuck > 0 ? { stuckMs: Math.round(stuck * MINUTE) } : {}),
163
207
  };
164
208
  }
@@ -169,6 +213,7 @@ const TIMING_DESCRIPTIONS = {
169
213
  deadline_minutes: "Optional soft deadline in minutes (default: none; 0 = none; null or omitted = inherit: in a batch job the shared value, otherwise the default). At the deadline the child is told to stop starting new work, commit what is done, and report, and you get one wake. Grace starts when the message reaches the child (after its current tool call); if it has not finished by then, the harness stops it with reason deadline.",
170
214
  grace_minutes: "Minutes after the wrap-up message reaches the child before the run is stopped (default 5; null or omitted = inherit).",
171
215
  max_minutes: "Optional hard ceiling in minutes (default: none; 0 = none; null or omitted = inherit). The run is stopped at once, without grace, with reason ceiling.",
216
+ tool_wait_minutes: "Tool-call wait alert in minutes (default 5; 0 = off; null or omitted = inherit). While a tool call stays open this long you get one factual wake for that call, including a normal long test. Parallel calls alert independently. The alert does not stop or cancel the run.",
172
217
  stuck_minutes: "No-progress window in minutes (default 10; 0 = off; null or omitted = inherit). Progress is any successful tool call that is not an exact repeat of an earlier one (same tool, same arguments); edits, writes, commits, and a success after a failure always count. Time inside a running tool call does not count. Wakes you once per stuck spell; never stops the run.",
173
218
  } as const;
174
219
 
@@ -190,6 +235,7 @@ export function timingParameterSchemas(Type: SchemaBuilder): Record<keyof typeof
190
235
  deadline_minutes: field(TIMING_DESCRIPTIONS.deadline_minutes),
191
236
  grace_minutes: field(TIMING_DESCRIPTIONS.grace_minutes),
192
237
  max_minutes: field(TIMING_DESCRIPTIONS.max_minutes),
238
+ tool_wait_minutes: field(TIMING_DESCRIPTIONS.tool_wait_minutes),
193
239
  stuck_minutes: field(TIMING_DESCRIPTIONS.stuck_minutes),
194
240
  };
195
241
  }
@@ -203,7 +249,7 @@ export interface ProgressState {
203
249
  /** Latest event timestamp seen (message provenance only). */
204
250
  lastEventAt?: number;
205
251
  /** Tool calls started and not yet finished. */
206
- open: Map<string, { name: string; command?: string; novel: boolean; seeded?: boolean }>;
252
+ open: Map<string, { name: string; command?: string; novel: boolean; seeded?: boolean; startedAt: number }>;
207
253
  /** Hashes of tool name + normalized arguments already seen in this run (bounded, oldest evicted). */
208
254
  seen: Set<string>;
209
255
  /** When the open set last went from empty to non-empty. */
@@ -216,15 +262,28 @@ export interface ProgressState {
216
262
  /**
217
263
  * Progress state for a run. `inFlight` seeds the open set from the durable
218
264
  * record: the parent knows the child is waiting on that call even when the
219
- * bounded log read no longer contains its start. A seeded entry carries no
220
- * arguments, so its result is never mistaken for progress; the call's own
221
- * result, or a later call's start, supersedes it.
265
+ * bounded log read no longer contains its start. It accepts either the legacy
266
+ * single-call record or the current list of all open calls. A seeded entry
267
+ * carries no arguments, so its result is never mistaken for progress; the
268
+ * call's own result, or a later call's start, supersedes it.
222
269
  */
223
- export function emptyProgress(startedAt: number, inFlight?: { id?: string; since?: number }): ProgressState {
270
+ export function emptyProgress(startedAt: number,
271
+ inFlight?: { id?: string; since?: number; name?: string; command?: string } | readonly OpenCallRecord[]): ProgressState {
224
272
  const state: ProgressState = { startedAt, open: new Map(), seen: new Set(), pausedMs: 0, lastToolFailed: false };
225
- if (typeof inFlight?.id === "string" && inFlight.id !== "" && typeof inFlight.since === "number" && Number.isFinite(inFlight.since)) {
226
- state.open.set(inFlight.id, { name: "", novel: false, seeded: true });
227
- state.inFlightSince = Math.max(startedAt, inFlight.since);
273
+ const seeds: readonly { id?: string; since?: number; name?: string; command?: string }[] = Array.isArray(inFlight) ? inFlight : [inFlight ?? {}];
274
+ const sinceValues: number[] = [];
275
+ for (const seed of seeds) {
276
+ if (typeof seed?.id !== "string" || seed.id === "" || typeof seed.since !== "number" || !Number.isFinite(seed.since)) continue;
277
+ const since = Math.max(startedAt, seed.since);
278
+ state.open.set(seed.id, {
279
+ name: typeof seed.name === "string" ? seed.name : "",
280
+ ...(typeof seed.command === "string" ? { command: seed.command } : {}),
281
+ novel: false, seeded: true, startedAt: since,
282
+ });
283
+ sinceValues.push(since);
284
+ }
285
+ if (sinceValues.length > 0) {
286
+ state.inFlightSince = Math.min(...sinceValues);
228
287
  }
229
288
  return state;
230
289
  }
@@ -294,13 +353,17 @@ export function foldProgress(state: ProgressState, event: Record<string, unknown
294
353
  if (!id) return;
295
354
  const args = event.args as { command?: unknown } | undefined;
296
355
  const name = String(event.toolName ?? "");
297
- // A different call starting means the seeded call finished while the log window
298
- // was lost: its wait is a pause, not progress. A seed for this same id is
299
- // replaced by the real event below.
356
+ // Pi emits every tool start for one assistant batch before its results,
357
+ // and starts the next batch only after the previous one finished. So a
358
+ // retained assistant/message timestamp after a seed's start proves that
359
+ // seed's batch ended even when its own result fell outside the window.
360
+ // Seeds started in the current retained batch stay open (genuine
361
+ // parallel calls), and a seed for this same id is replaced below.
300
362
  const seedSince = state.inFlightSince;
301
363
  let supersededSeed = false;
364
+ const boundary = state.lastEventAt;
302
365
  for (const [openId, call] of state.open) {
303
- if (call.seeded && openId !== id) {
366
+ if (call.seeded && openId !== id && boundary !== undefined && boundary > call.startedAt) {
304
367
  state.open.delete(openId);
305
368
  supersededSeed = true;
306
369
  }
@@ -310,7 +373,13 @@ export function foldProgress(state: ProgressState, event: Record<string, unknown
310
373
  state.inFlightSince = undefined;
311
374
  }
312
375
  if (state.open.size === 0) state.inFlightSince = state.lastEventAt ?? state.startedAt;
313
- state.open.set(id, { name, command: typeof args?.command === "string" ? args.command : undefined, novel: remember(state, callKey(name, event.args)) });
376
+ const startedAt = state.open.get(id)?.startedAt ?? state.lastEventAt ?? state.startedAt;
377
+ state.open.set(id, {
378
+ name,
379
+ command: typeof args?.command === "string" ? args.command : undefined,
380
+ novel: remember(state, callKey(name, event.args)),
381
+ startedAt,
382
+ });
314
383
  return;
315
384
  }
316
385
  if (type !== "message_end") return;
@@ -359,6 +428,8 @@ export interface TimingActions {
359
428
  steer?: boolean;
360
429
  /** Wake the parent about the deadline (once; retried until handed off). */
361
430
  deadlineWake?: boolean;
431
+ /** Wake the parent about tool calls that have been open long enough (one per call). */
432
+ toolWaitWakes?: { callId: string; startedAt: number; ageMs: number; name?: string; command?: string }[];
362
433
  /** Wake the parent about no progress (once per stuck episode). */
363
434
  stuckWake?: { anchorAt: number; ageMs: number };
364
435
  /** Stop the run now. */
@@ -388,6 +459,20 @@ export function decideTiming(timing: RunTiming | undefined, progress: ProgressSt
388
459
  // Past the deadline the wrap-up flow governs; a stuck wake would only repeat it.
389
460
  return actions;
390
461
  }
462
+ if (timing.toolWaitMs !== undefined && timing.toolWaitMs > 0 && progress) {
463
+ const alerted = new Set(timing.toolWaitAlerted ?? []);
464
+ const due = [...progress.open.entries()]
465
+ .filter(([id]) => !alerted.has(id))
466
+ .map(([callId, call]) => ({
467
+ callId, startedAt: call.startedAt,
468
+ ageMs: Math.max(0, now - call.startedAt),
469
+ ...(call.name ? { name: call.name } : {}),
470
+ ...(call.command !== undefined ? { command: call.command } : {}),
471
+ }))
472
+ .filter((call) => call.ageMs >= timing.toolWaitMs!)
473
+ .sort((a, b) => a.startedAt - b.startedAt || a.callId.localeCompare(b.callId));
474
+ if (due.length > 0) actions.toolWaitWakes = due;
475
+ }
391
476
  if (timing.stuckMs !== undefined && progress) {
392
477
  const age = stuckAge(progress, now, timing.lastProgressAt);
393
478
  const anchorAt = progressAnchor(progress, timing.lastProgressAt);
@@ -404,6 +489,70 @@ function fmtMinutes(ms: number): string {
404
489
  return Number.isInteger(m) ? `${m}m` : m >= 1 ? `${m.toFixed(1)}m` : `${Math.max(1, Math.round(ms / 1000))}s`;
405
490
  }
406
491
 
492
+ function oneLine(value: string, max = 160): string {
493
+ const compact = value.replace(/\s+/g, " ").trim();
494
+ return compact.length <= max ? compact : `${compact.slice(0, Math.max(0, max - 3))}...`;
495
+ }
496
+
497
+ function lastProgressLine(now: number, lastProgressAt?: number): string {
498
+ return lastProgressAt === undefined
499
+ ? "Last progress: none observed since the run started."
500
+ : `Last progress: ${fmtMinutes(Math.max(0, now - lastProgressAt))} ago.`;
501
+ }
502
+
503
+ function evidenceLine(id: string, logPath?: string): string {
504
+ return `Evidence: subagent_output id=${JSON.stringify(id)}${logPath ? `; log ${logPath}` : ""}.`;
505
+ }
506
+
507
+ export interface ToolWaitAlertFacts {
508
+ id: string;
509
+ label: string;
510
+ callId: string;
511
+ toolName: string;
512
+ command?: string;
513
+ openMs: number;
514
+ thresholdMs: number;
515
+ now: number;
516
+ lastProgressAt?: number;
517
+ logPath?: string;
518
+ }
519
+
520
+ /** One factual long-tool alert. It describes the wait; it does not direct a response. */
521
+ export function toolWaitAlertText(facts: ToolWaitAlertFacts): string {
522
+ const operation = facts.toolName
523
+ ? `${facts.toolName}${facts.command ? `: ${oneLine(facts.command)}` : ""}`
524
+ : "unknown tool";
525
+ return [
526
+ `Subagent ${facts.label} · tool wait`,
527
+ `Tool call ${facts.callId} (${operation}) has been open for ${fmtMinutes(facts.openMs)} (threshold ${fmtMinutes(facts.thresholdMs)}).`,
528
+ `Run ${facts.id}. Current operation: ${operation}. ${lastProgressLine(facts.now, facts.lastProgressAt)}`,
529
+ evidenceLine(facts.id, facts.logPath),
530
+ "The run continues; this alert does not stop, cancel, or restart it.",
531
+ ].join("\n");
532
+ }
533
+
534
+ export interface StuckAlertFacts {
535
+ id: string;
536
+ label: string;
537
+ ageMs: number;
538
+ windowMs: number;
539
+ now: number;
540
+ lastProgressAt?: number;
541
+ logPath?: string;
542
+ }
543
+
544
+ /** One factual no-progress alert. It describes the observation; it does not direct a response. */
545
+ export function stuckAlertText(facts: StuckAlertFacts): string {
546
+ return [
547
+ `Subagent ${facts.label} · no progress`,
548
+ `No progress for ${fmtMinutes(facts.ageMs)} (threshold ${fmtMinutes(facts.windowMs)}). Successful tool calls, if any, only repeated earlier calls ` +
549
+ "(same tool, same arguments); time inside running tool calls is not counted.",
550
+ `Run ${facts.id}. Current operation: none (no tool call open). ${lastProgressLine(facts.now, facts.lastProgressAt)}`,
551
+ evidenceLine(facts.id, facts.logPath),
552
+ "The run continues; this alert does not stop, cancel, or restart it.",
553
+ ].join("\n");
554
+ }
555
+
407
556
  /** Wrap-up instruction delivered into the child session at the soft deadline. */
408
557
  export function steerText(timing: RunTiming, startedAt: number): string {
409
558
  const limit = timing.deadlineAt !== undefined ? fmtMinutes(timing.deadlineAt - startedAt) : "the";
@@ -461,6 +610,7 @@ export function formatTimingLimits(timing: RunTiming, startedAt: number): string
461
610
  const parts = [
462
611
  timing.deadlineAt !== undefined ? `soft deadline ${fmtMinutes(timing.deadlineAt - startedAt)} (+${fmtMinutes(timing.graceMs)} grace)` : "no soft deadline",
463
612
  timing.ceilingAt !== undefined ? `ceiling ${fmtMinutes(timing.ceilingAt - startedAt)}` : "no ceiling",
613
+ timing.toolWaitMs !== undefined ? `tool wait after ${fmtMinutes(timing.toolWaitMs)}` : "no tool-wait alert",
464
614
  timing.stuckMs !== undefined ? `stuck wake after ${fmtMinutes(timing.stuckMs)} without progress` : "no stuck wake",
465
615
  ];
466
616
  return `Timing: ${parts.join(", ")}.`;