brl-subagent 2.6.0 → 2.8.0

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.
@@ -0,0 +1,90 @@
1
+ // Purpose: The pure auto-retry predicate for background runs that settled with a transport-class failure (issue #365).
2
+ import type { SubagentRun } from "./types";
3
+
4
+ /**
5
+ * Conservative transport signatures (issue #365). The four observed failures in
6
+ * the 2026-10 cycle were all externally-caused drops — `"Connection error."`
7
+ * from the SDK — that died before any file work, so a replay with the recorded
8
+ * params is cheap and safe. The list is substring-matched against the settled
9
+ * run's `errorMessage` (case-insensitive) and deliberately narrow: a retry is
10
+ * never armed for a failure whose cause is unknown, because re-running a
11
+ * genuinely broken dispatch just spends twice.
12
+ */
13
+ const TRANSPORT_SIGNATURES = [
14
+ "connection error",
15
+ "econnreset",
16
+ "econnrefused",
17
+ "socket hang up",
18
+ "fetch failed",
19
+ "network error",
20
+ "etimedout",
21
+ "enotfound",
22
+ "eai_again",
23
+ ] as const;
24
+
25
+ /**
26
+ * The user-visible warning surfaced when the auto-retry is scheduled. Lives here
27
+ * so the handler and its tests agree on one literal (the runtime-vocabulary
28
+ * ratchet forbids internal vocabulary — this string is user-facing and stays
29
+ * plain).
30
+ */
31
+ export const TRANSPORT_RETRY_TOAST = "Transport failure — auto-retrying once (attempt 2/2)";
32
+
33
+ /**
34
+ * The CLASS half of the predicate: the run failed as a process-level exit
35
+ * (`exit_error`, with the legacy `originalParams.errorCategory` fallback the
36
+ * rest of the code uses) AND its `errorMessage` carries a transport signature.
37
+ *
38
+ * Extracted for issue #404: the settle path must decide whether to RETAIN the
39
+ * run's session directory from exactly the values the run record is about to
40
+ * receive, and it must do so before that record is written. Keeping the half
41
+ * here (not inlined at the settle site) means the retention decision and the
42
+ * retry decision can never drift apart.
43
+ *
44
+ * Pure: no pi SDK, no state, no I/O.
45
+ */
46
+ export function isTransportFailure(
47
+ run: Pick<SubagentRun, "status" | "errorCategory" | "errorMessage" | "originalParams">,
48
+ ): boolean {
49
+ if (run.status !== "failed") return false;
50
+ // New consumers read the top-level category; the legacy snapshot key is the
51
+ // documented fallback (same rule as buildCompletionMessage).
52
+ const category = run.errorCategory ?? run.originalParams?.errorCategory;
53
+ if (category !== "exit_error") return false;
54
+ const message = (run.errorMessage ?? "").toLowerCase();
55
+ return TRANSPORT_SIGNATURES.some((signature) => message.includes(signature));
56
+ }
57
+
58
+ /**
59
+ * TRUE when a settled run should be re-dispatched ONCE automatically.
60
+ *
61
+ * Every condition must hold (issue #365 spec):
62
+ *
63
+ * 1. `isTransportFailure` — failed as `exit_error` with a transport
64
+ * signature in the message (the class the runner already stamps for an
65
+ * external drop);
66
+ * 2. it is the ORIGINAL dispatch (`attempt ?? 1 === 1`): a user retry, or a
67
+ * previous auto-retry that failed again, surfaces normally. This is what
68
+ * bounds the machinery structurally — one retry per logical dispatch,
69
+ * never a chain, no timer, no queue;
70
+ * 3. it ran in the BACKGROUND — a foreground failure is already visible
71
+ * inline (and `retryOnTimeout` covers the foreground timeout case);
72
+ * 4. the record carries `originalParams`, which is what the retry restores.
73
+ * Fan-out units deliberately omit it (their retry semantics belong to
74
+ * issue #229), so they fall out here by construction.
75
+ *
76
+ * Issue #404: this is ALSO the settle-time retention gate. The resume preamble
77
+ * that points at a retained session is built only by `scheduleTransportRetry`,
78
+ * which fires only when this predicate holds — so exactly this class has a
79
+ * reader. An attempt-2 transport failure (or one of a background-less run)
80
+ * prunes its session as before.
81
+ *
82
+ * Pure: no pi SDK, no state, no I/O — unit-testable as a matrix.
83
+ */
84
+ export function isTransportRetryable(
85
+ run: Pick<SubagentRun, "status" | "errorCategory" | "errorMessage" | "attempt" | "originalParams">,
86
+ ): boolean {
87
+ if (!isTransportFailure(run)) return false;
88
+ if ((run.attempt ?? 1) !== 1) return false;
89
+ return run.originalParams?.background === true;
90
+ }
package/src/tui-format.ts CHANGED
@@ -82,6 +82,73 @@ export interface ProgressStatusInput {
82
82
  modeContext?: ModeContext;
83
83
  /** Epoch ms at which the oldest active run started; absent → no elapsed suffix. */
84
84
  activeSinceMs?: number;
85
+ /**
86
+ * Issue #423: the live map's own clock, when the caller has one. Supersedes
87
+ * `activeSinceMs` for the age (it is the age of the OLDEST still-running
88
+ * agent, not the burst anchor) and adds the nearest deadline.
89
+ */
90
+ times?: ProgressTimes;
91
+ }
92
+
93
+ /** The one live-entry clock {@link computeProgressTimes} needs. */
94
+ export interface LiveBudgetInput {
95
+ startedAt: number;
96
+ deadlineAt?: number;
97
+ }
98
+
99
+ /** The footer's two derived clocks, both already filtered of settled runs. */
100
+ export interface ProgressTimes {
101
+ /** Age of the OLDEST still-running entry (ms), clamped at 0. */
102
+ ranMs?: number;
103
+ /** The soonest deadline: time left, and the fraction of its budget left. */
104
+ next?: { remainingMs: number; fraction: number };
105
+ }
106
+
107
+ /** Clamp a fraction into [0, 1]; a non-positive budget has nothing left. */
108
+ function clampFraction(value: number): number {
109
+ if (!Number.isFinite(value)) return 0;
110
+ return Math.min(1, Math.max(0, value));
111
+ }
112
+
113
+ /**
114
+ * Derive the footer's clocks from the live entries (issue #423). Pure.
115
+ *
116
+ * `ranMs` is the age of the OLDEST still-running agent — `now - min(startedAt)`
117
+ * — not the burst anchor: with a queue, the burst anchor predates the row the
118
+ * human is watching. An EMPTY list yields no `ranMs` so the caller can fall back
119
+ * to `activeSinceMs` (the pre-#423 line).
120
+ *
121
+ * `next` is the SOONEST deadline, and its `fraction` is measured against that
122
+ * entry's own budget, so a long-running agent with a long budget does not read
123
+ * as nearly-exhausted. Remaining time clamps at 0; a backwards clock jump makes
124
+ * the age 0 rather than negative.
125
+ */
126
+ export function computeProgressTimes(
127
+ live: ReadonlyArray<LiveBudgetInput>,
128
+ now: number,
129
+ ): ProgressTimes {
130
+ if (live.length === 0) return {};
131
+
132
+ let oldestStartedAt = Infinity;
133
+ let soonest: LiveBudgetInput | undefined;
134
+ for (const entry of live) {
135
+ oldestStartedAt = Math.min(oldestStartedAt, entry.startedAt);
136
+ if (entry.deadlineAt === undefined) continue;
137
+ if (soonest?.deadlineAt === undefined || entry.deadlineAt < soonest.deadlineAt) {
138
+ soonest = entry;
139
+ }
140
+ }
141
+
142
+ const times: ProgressTimes = { ranMs: Math.max(0, now - oldestStartedAt) };
143
+ if (soonest?.deadlineAt !== undefined) {
144
+ const remainingMs = Math.max(0, soonest.deadlineAt - now);
145
+ const budgetMs = soonest.deadlineAt - soonest.startedAt;
146
+ times.next = {
147
+ remainingMs,
148
+ fraction: budgetMs > 0 ? clampFraction(remainingMs / budgetMs) : 0,
149
+ };
150
+ }
151
+ return times;
85
152
  }
86
153
 
87
154
  /** One coloured run of text on the footer line. */
@@ -95,6 +162,24 @@ const DONE_SYMBOL = "\u2713";
95
162
  const FAILED_SYMBOL = "\u2717";
96
163
  /** Separator before the elapsed suffix — " · ", muted with the duration. */
97
164
  const ELAPSED_SEPARATOR = " \u00b7 ";
165
+ /** Issue #423 — the labels of the two clock segments, in one place. */
166
+ const RAN_LABEL = "ran: ";
167
+ const DEADLINE_LABEL = "deadline in ";
168
+ const DEADLINE_STOPPING = "deadline: stopping";
169
+ /**
170
+ * Issue #423 — the deadline segment's colour bands, by the fraction of budget
171
+ * left. The text always carries the value, so colour is redundant, never
172
+ * load-bearing.
173
+ */
174
+ const DEADLINE_ERROR_FRACTION = 0.05;
175
+ const DEADLINE_WARNING_FRACTION = 0.2;
176
+
177
+ /** The deadline clock's colour: exhausted/almost → error, tight → warning. */
178
+ function deadlineColor(next: { remainingMs: number; fraction: number }): ProgressStatusColor {
179
+ if (next.remainingMs <= 0 || next.fraction <= DEADLINE_ERROR_FRACTION) return "error";
180
+ if (next.fraction <= DEADLINE_WARNING_FRACTION) return "warning";
181
+ return "muted";
182
+ }
98
183
 
99
184
  /** The verdict a run or step settled on — the input to {@link formatOutcomeSymbol}. */
100
185
  export type OutcomeKind = "success" | "failure";
@@ -189,10 +274,29 @@ export function formatProgressSegments(
189
274
  });
190
275
  }
191
276
 
192
- if (active && state.activeSinceMs !== undefined) {
193
- // Clamp at zero: a clock jump backwards must never print a negative age.
194
- const elapsed = formatElapsed(Math.max(0, now - state.activeSinceMs));
195
- segments.push({ color: "muted", text: `${ELAPSED_SEPARATOR}${elapsed}` });
277
+ if (active) {
278
+ const times = state.times;
279
+ if (times?.ranMs !== undefined) {
280
+ // Clamp again here: the formatter is public and may be handed a raw age.
281
+ segments.push({
282
+ color: "muted",
283
+ text: `${ELAPSED_SEPARATOR}${RAN_LABEL}${formatElapsed(Math.max(0, times.ranMs))}`,
284
+ });
285
+ } else if (state.activeSinceMs !== undefined) {
286
+ // Pre-#423 fallback (no live clock known): the burst anchor, unchanged.
287
+ // Clamp at zero: a clock jump backwards must never print a negative age.
288
+ const elapsed = formatElapsed(Math.max(0, now - state.activeSinceMs));
289
+ segments.push({ color: "muted", text: `${ELAPSED_SEPARATOR}${elapsed}` });
290
+ }
291
+ if (times?.next !== undefined) {
292
+ segments.push({
293
+ color: deadlineColor(times.next),
294
+ text:
295
+ times.next.remainingMs <= 0
296
+ ? `${ELAPSED_SEPARATOR}${DEADLINE_STOPPING}`
297
+ : `${ELAPSED_SEPARATOR}${DEADLINE_LABEL}${formatElapsed(times.next.remainingMs)}`,
298
+ });
299
+ }
196
300
  }
197
301
 
198
302
  return segments;
@@ -213,13 +317,77 @@ export function formatProgressStatus(
213
317
  .join("");
214
318
  }
215
319
 
216
- /** Dim section of a live row: short id + token counts + elapsed. */
320
+ /** Dim section of a live row: short id + token counts + elapsed (+ budget). */
217
321
  export function formatLiveRowDim(
218
322
  id: string,
219
323
  usage: { input: number; output: number },
220
324
  elapsedStr: string,
325
+ // Issue #423: the budget segment, when the run has a known deadline.
326
+ budget?: string,
327
+ ): string {
328
+ return ` [${id.slice(0, 8)}] \u2191${formatTokens(usage.input)} \u2193${formatTokens(usage.output)} ${elapsedStr}${budget ? ` \u00b7 ${budget}` : ""}`;
329
+ }
330
+
331
+ // ---------------------------------------------------------------------------
332
+ // Issue #423 — budget display (footer, monitor rows, dashboard)
333
+ // ---------------------------------------------------------------------------
334
+
335
+ /**
336
+ * A budget/used/left duration: a whole number of minutes as `30m` (a budget is
337
+ * read as a round number), otherwise the compact `4m 12s` form. Pure.
338
+ */
339
+ export function formatBudgetDuration(ms: number): string {
340
+ const safe = Math.max(0, ms);
341
+ const minutes = safe / 60_000;
342
+ return Number.isInteger(minutes) && minutes > 0 ? `${minutes}m` : formatElapsed(safe);
343
+ }
344
+
345
+ /** The no-deadline token: the run has no timer, so there is nothing to state. */
346
+ const NO_BUDGET = "\u2014";
347
+
348
+ /**
349
+ * One live row's budget: `4m 12s / 30m (86% left)`. Pure.
350
+ *
351
+ * `startedAt` + `deadlineAt` are the entry's own clocks; a missing deadline
352
+ * renders {@link NO_BUDGET} (a foreground run with no timeout, or an old
353
+ * record) rather than inventing a 30m default the run does not have. An
354
+ * exhausted budget states `0% left` — the remaining time is clamped, never
355
+ * negative.
356
+ */
357
+ export function formatBudget(
358
+ startedAt: number,
359
+ deadlineAt: number | undefined,
360
+ now: number,
221
361
  ): string {
222
- return ` [${id.slice(0, 8)}] \u2191${formatTokens(usage.input)} \u2193${formatTokens(usage.output)} ${elapsedStr}`;
362
+ if (deadlineAt === undefined) return NO_BUDGET;
363
+ const budgetMs = deadlineAt - startedAt;
364
+ const usedMs = Math.max(0, now - startedAt);
365
+ const remainingMs = Math.max(0, deadlineAt - now);
366
+ const percentLeft =
367
+ budgetMs > 0 ? Math.max(0, Math.min(100, Math.floor((remainingMs / budgetMs) * 100))) : 0;
368
+ return `${formatBudgetDuration(usedMs)} / ${formatBudgetDuration(budgetMs)} (${percentLeft}% left)`;
369
+ }
370
+
371
+ /**
372
+ * Order live rows for display: soonest deadline first (undated last), then
373
+ * oldest first, then id for a stable total order. Pure; returns a copy.
374
+ *
375
+ * Ordering by `deadlineAt` IS ordering by remaining time (same `now`), so the
376
+ * list does not reorder between paints as the clock advances — only a
377
+ * registration or a deadline change moves a row.
378
+ */
379
+ export function sortLiveSessions<T extends LiveBudgetInput>(
380
+ entries: ReadonlyArray<readonly [string, T]>,
381
+ ): Array<[string, T]> {
382
+ return entries
383
+ .map(([id, entry]) => [id, entry] as [string, T])
384
+ .sort(([aId, a], [bId, b]) => {
385
+ const aDeadline = a.deadlineAt ?? Number.POSITIVE_INFINITY;
386
+ const bDeadline = b.deadlineAt ?? Number.POSITIVE_INFINITY;
387
+ if (aDeadline !== bDeadline) return aDeadline - bDeadline;
388
+ if (a.startedAt !== b.startedAt) return a.startedAt - b.startedAt;
389
+ return aId < bId ? -1 : aId > bId ? 1 : 0;
390
+ });
223
391
  }
224
392
 
225
393
  /**