brl-subagent 2.5.1 → 2.6.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.
package/src/tui-format.ts CHANGED
@@ -7,10 +7,18 @@
7
7
  * without a TUI harness.
8
8
  */
9
9
 
10
- import { formatTokens, isInterruptedRun } from "./types";
11
- import type { SubagentRun } from "./types";
10
+ import {
11
+ DEFAULT_SLA_WINDOW_SIZE,
12
+ TEMPLATE_PARAM_RE,
13
+ formatTokens,
14
+ isInterruptedRun,
15
+ } from "./types";
16
+ import type { ModeContext, SubagentRun, TaskTemplate } from "./types";
12
17
 
13
- /** Braille spinner frames, indexed by Math.floor(now / 150) % 10. */
18
+ /** Frame duration of the braille spinners (10 frames → a 1.5 s cycle). */
19
+ export const LIVE_SPINNER_FRAME_MS = 150;
20
+
21
+ /** Braille spinner frames, indexed by Math.floor(now / LIVE_SPINNER_FRAME_MS) % 10. */
14
22
  export const LIVE_SPINNER_FRAMES: readonly string[] = [
15
23
  "\u280B",
16
24
  "\u2819",
@@ -40,7 +48,169 @@ export function liveRowName(label: string | undefined, task: string): string {
40
48
 
41
49
  /** Spinner frame at a given timestamp (ms since epoch). */
42
50
  export function liveSpinner(now: number): string {
43
- return LIVE_SPINNER_FRAMES[Math.floor(now / 150) % 10];
51
+ return LIVE_SPINNER_FRAMES[Math.floor(now / LIVE_SPINNER_FRAME_MS) % LIVE_SPINNER_FRAMES.length];
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Footer activity indicator (issue #354)
56
+ // ---------------------------------------------------------------------------
57
+
58
+ /**
59
+ * The footer line's colour vocabulary — the subset of pi's `ThemeColor` the
60
+ * status line uses, declared locally so this module keeps importing only
61
+ * `./types`. `ctx.ui.theme` satisfies {@link ProgressStatusTheme} structurally,
62
+ * which keeps the formatter free of any TUI import.
63
+ */
64
+ export type ProgressStatusColor = "accent" | "success" | "warning" | "error" | "muted";
65
+
66
+ /** The one theme capability the footer needs. */
67
+ export interface ProgressStatusTheme {
68
+ fg(color: ProgressStatusColor, text: string): string;
69
+ }
70
+
71
+ /**
72
+ * The footer's input: the counter slice of `SessionState` plus the elapsed
73
+ * anchor. Structural rather than `SessionState` so the formatter has no
74
+ * dependency on session state and every case is unit-testable.
75
+ */
76
+ export interface ProgressStatusInput {
77
+ activeSubagents: number;
78
+ completedSubagents: number;
79
+ failedSubagents: number;
80
+ unseenSubagents: number;
81
+ /** Issue #133 multi-unit breakdown, present only while a dispatch is in flight. */
82
+ modeContext?: ModeContext;
83
+ /** Epoch ms at which the oldest active run started; absent → no elapsed suffix. */
84
+ activeSinceMs?: number;
85
+ }
86
+
87
+ /** One coloured run of text on the footer line. */
88
+ export interface ProgressStatusSegment {
89
+ color: ProgressStatusColor;
90
+ text: string;
91
+ }
92
+
93
+ const STATUS_PREFIX = "brl:";
94
+ const DONE_SYMBOL = "\u2713";
95
+ const FAILED_SYMBOL = "\u2717";
96
+ /** Separator before the elapsed suffix — " · ", muted with the duration. */
97
+ const ELAPSED_SEPARATOR = " \u00b7 ";
98
+
99
+ /** The verdict a run or step settled on — the input to {@link formatOutcomeSymbol}. */
100
+ export type OutcomeKind = "success" | "failure";
101
+
102
+ /**
103
+ * The one success/failure symbol pair: `✓` in `success`, `✗` in `error`. Every
104
+ * surface that paints a verdict icon (result renderers, history rows, graph and
105
+ * chain summaries, the footer) routes through here, so the glyph-to-colour
106
+ * pairing cannot drift between them. Theme is injected, like
107
+ * {@link formatProgressStatus}, to keep this module free of TUI imports.
108
+ */
109
+ export function formatOutcomeSymbol(outcome: OutcomeKind, theme: ProgressStatusTheme): string {
110
+ return outcome === "success"
111
+ ? theme.fg("success", DONE_SYMBOL)
112
+ : theme.fg("error", FAILED_SYMBOL);
113
+ }
114
+
115
+ /**
116
+ * The completion segment's colour, decided by outcome: all success → success,
117
+ * mixed → warning, failure-only → error (issue #354).
118
+ */
119
+ export function progressCompletionColor(
120
+ completed: number,
121
+ failed: number,
122
+ ): ProgressStatusColor {
123
+ if (failed === 0) return "success";
124
+ return completed > 0 ? "warning" : "error";
125
+ }
126
+
127
+ /** The #133 breakdown that qualifies the active count. */
128
+ function modeBreakdown(mc: ModeContext): string {
129
+ return mc.kind === "graph"
130
+ ? `graph wave ${mc.wave}/${mc.totalWaves} \u00b7 node ${mc.node}/${mc.totalNodes}`
131
+ : `chain step ${mc.step}/${mc.totalSteps}`;
132
+ }
133
+
134
+ /**
135
+ * The footer as coloured segments, so the completion group can be painted as
136
+ * one unit (symbols included) while the active segment and elapsed suffix take
137
+ * their own colours. Pure: frame, counts and elapsed are all derived from
138
+ * `now` and the counters.
139
+ *
140
+ * Shapes (issue #354):
141
+ * - active: `⠋ brl: 2 running, ✓ 1 done, ✗ 1 failed · 1m 14s`
142
+ * - linger: `✓ brl: 3 done (1 unseen), ✗ 1 failed` (no spinner, no elapsed)
143
+ */
144
+ export function formatProgressSegments(
145
+ state: ProgressStatusInput,
146
+ now: number,
147
+ ): ProgressStatusSegment[] {
148
+ const active = state.activeSubagents > 0;
149
+ const segments: ProgressStatusSegment[] = [];
150
+
151
+ // Completion labels, kept separate from their symbols so the prefix can be
152
+ // inserted after the first symbol on the linger line.
153
+ const completion: Array<{ symbol: string; label: string }> = [];
154
+ if (state.completedSubagents > 0) {
155
+ const unseen = state.unseenSubagents > 0 ? ` (${state.unseenSubagents} unseen)` : "";
156
+ completion.push({
157
+ symbol: DONE_SYMBOL,
158
+ label: `${state.completedSubagents} done${unseen}`,
159
+ });
160
+ }
161
+ if (state.failedSubagents > 0) {
162
+ completion.push({ symbol: FAILED_SYMBOL, label: `${state.failedSubagents} failed` });
163
+ }
164
+
165
+ if (active) {
166
+ const detail: string[] = [];
167
+ if (state.modeContext) detail.push(modeBreakdown(state.modeContext));
168
+ detail.push(`${state.activeSubagents} running`);
169
+ // The separator trailing the active segment stays with it, so the
170
+ // completion segment is contiguous and can be coloured as a unit.
171
+ segments.push({
172
+ color: "accent",
173
+ text: `${liveSpinner(now)} ${STATUS_PREFIX} ${detail.join(", ")}${completion.length > 0 ? ", " : ""}`,
174
+ });
175
+ }
176
+
177
+ if (completion.length > 0) {
178
+ // With no active run the segment carries the prefix itself:
179
+ // `✓ brl: 3 done (1 unseen)`.
180
+ const prefix = active ? "" : `${STATUS_PREFIX} `;
181
+ const [first, ...rest] = completion;
182
+ const text = [
183
+ `${first.symbol} ${prefix}${first.label}`,
184
+ ...rest.map((part) => `${part.symbol} ${part.label}`),
185
+ ].join(", ");
186
+ segments.push({
187
+ color: progressCompletionColor(state.completedSubagents, state.failedSubagents),
188
+ text,
189
+ });
190
+ }
191
+
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}` });
196
+ }
197
+
198
+ return segments;
199
+ }
200
+
201
+ /**
202
+ * The footer line as one themed string — the coloured form of
203
+ * {@link formatProgressSegments}. Pure: every byte is a function of the
204
+ * counters, `now` and the injected theme.
205
+ */
206
+ export function formatProgressStatus(
207
+ state: ProgressStatusInput,
208
+ now: number,
209
+ theme: ProgressStatusTheme,
210
+ ): string {
211
+ return formatProgressSegments(state, now)
212
+ .map((segment) => theme.fg(segment.color, segment.text))
213
+ .join("");
44
214
  }
45
215
 
46
216
  /** Dim section of a live row: short id + token counts + elapsed. */
@@ -106,3 +276,211 @@ export function buildRetryOfferMessage(run: SubagentRun): string {
106
276
  `to retry the ${statusWord} run ${run.id.slice(0, 8)} with its recorded params."`
107
277
  );
108
278
  }
279
+
280
+ // ---------------------------------------------------------------------------
281
+ // Menu polish U1: canonical menu value vocabulary + divider factory (umbrella #345)
282
+ // ---------------------------------------------------------------------------
283
+
284
+ /**
285
+ * Every menu row kind whose displayed value has a canonical spelling. The
286
+ * strings are the contract: later units consume these tokens instead of
287
+ * hand-rolling prose per call site (and the tests assert the tokens, not prose).
288
+ */
289
+ export type MenuValueKind =
290
+ | "model"
291
+ | "thinking"
292
+ | "parallel"
293
+ | "depth"
294
+ | "approval"
295
+ | "completionnotify"
296
+ | "recovery"
297
+ | "historyentries"
298
+ | "costlimit"
299
+ | "sla"
300
+ | "presetCounts"
301
+ | "templateCounts";
302
+
303
+ /**
304
+ * One kind's canonical tokens. `unset` is the spelling for a missing value (and
305
+ * for numeric zero when the kind folds zero into unset); `values` maps a stored
306
+ * enum value to its display token. Kinds whose normal form is templated
307
+ * (`N levels`, `$N.NN`) carry only the tokens that are fixed.
308
+ */
309
+ export interface MenuValueTokenSet {
310
+ readonly unset?: string;
311
+ readonly values?: Readonly<Record<string, string>>;
312
+ }
313
+
314
+ /** The single source of the menu value vocabulary (U1). */
315
+ export const MENU_VALUE_TOKENS = {
316
+ model: { unset: "Not set" },
317
+ thinking: {},
318
+ parallel: { unset: "Unlimited" },
319
+ depth: { unset: "Off" },
320
+ approval: {
321
+ values: { auto: "Never ask", writes: "Ask on writes", always: "Ask every time" },
322
+ },
323
+ completionnotify: {
324
+ values: { all: "Every run", failed: "Failed only", off: "Off" },
325
+ },
326
+ recovery: { values: { offer: "On", off: "Off" } },
327
+ historyentries: { unset: "Unlimited" },
328
+ costlimit: { unset: "Unlimited" },
329
+ sla: { values: { off: "Off" } },
330
+ presetCounts: {},
331
+ templateCounts: {},
332
+ } as const satisfies Record<MenuValueKind, MenuValueTokenSet>;
333
+
334
+ /** Canonical fallback when a kind has no value or no specific unset token. */
335
+ const DEFAULT_UNSET_TOKEN = "Not set";
336
+
337
+ /**
338
+ * Structural input for {@link formatMenuValue}. Deliberately not `SessionState`
339
+ * (this module's architecture ratchet permits `./types` only, and a structural
340
+ * shape keeps every kind independently testable). Every field is optional: an
341
+ * absent field degrades to the kind's canonical unset token.
342
+ */
343
+ export interface MenuValueInput {
344
+ model?: { provider: string; id: string };
345
+ maxThinkingLevel?: string;
346
+ maxParallel?: number;
347
+ maxSubagentDepth?: number;
348
+ approvalMode?: string;
349
+ completionNotify?: string;
350
+ recovery?: string;
351
+ maxHistoryEntries?: number;
352
+ sessionCostLimit?: number;
353
+ slaTrackingEnabled?: boolean;
354
+ slaWindowSize?: number;
355
+ builtinCount?: number;
356
+ customCount?: number;
357
+ }
358
+
359
+ /** Widened view of one kind's token set (the literal table keeps per-key types). */
360
+ function tokensFor(kind: MenuValueKind): MenuValueTokenSet {
361
+ return MENU_VALUE_TOKENS[kind] as MenuValueTokenSet;
362
+ }
363
+
364
+ /** Look up an enum token, falling back to the kind's canonical unset token. */
365
+ function enumToken(kind: MenuValueKind, value: string | undefined): string {
366
+ const values = tokensFor(kind).values;
367
+ const token = value === undefined ? undefined : values?.[value];
368
+ return token ?? formatUnset(kind);
369
+ }
370
+
371
+ /** The canonical unset/zero token for a kind (default `Not set`). */
372
+ export function formatUnset(kind?: MenuValueKind): string {
373
+ if (!kind) return DEFAULT_UNSET_TOKEN;
374
+ return tokensFor(kind).unset ?? DEFAULT_UNSET_TOKEN;
375
+ }
376
+
377
+ /**
378
+ * Format a menu row's value using the canonical vocabulary. Pure. Numeric zero
379
+ * is the kind's unset token where the spec folds unlimited/off into zero
380
+ * (`parallel`, `depth`, `historyentries`, `costlimit`).
381
+ */
382
+ export function formatMenuValue(kind: MenuValueKind, input: MenuValueInput = {}): string {
383
+ switch (kind) {
384
+ case "model":
385
+ return input.model ? `${input.model.provider}/${input.model.id}` : formatUnset(kind);
386
+ case "thinking":
387
+ return input.maxThinkingLevel ?? formatUnset(kind);
388
+ case "parallel":
389
+ if (input.maxParallel === undefined) return formatUnset(kind);
390
+ return input.maxParallel === 0 ? formatUnset(kind) : String(input.maxParallel);
391
+ case "depth": {
392
+ const depth = input.maxSubagentDepth;
393
+ if (depth === undefined) return formatUnset(kind);
394
+ if (depth === 0) return formatUnset(kind);
395
+ return depth === 1 ? "1 level" : `${depth} levels`;
396
+ }
397
+ case "approval":
398
+ return enumToken(kind, input.approvalMode);
399
+ case "completionnotify":
400
+ return enumToken(kind, input.completionNotify);
401
+ case "recovery":
402
+ return enumToken(kind, input.recovery);
403
+ case "historyentries": {
404
+ const entries = input.maxHistoryEntries;
405
+ if (entries === undefined) return formatUnset(kind);
406
+ if (entries === 0) return formatUnset(kind);
407
+ return entries === 1 ? "1 entry" : `${entries} entries`;
408
+ }
409
+ case "costlimit":
410
+ if (input.sessionCostLimit === undefined) return formatUnset(kind);
411
+ return input.sessionCostLimit === 0
412
+ ? formatUnset(kind)
413
+ : `$${input.sessionCostLimit.toFixed(2)}`;
414
+ case "sla":
415
+ if (input.slaTrackingEnabled === undefined) return formatUnset(kind);
416
+ if (!input.slaTrackingEnabled) return tokensFor(kind).values?.off ?? "Off";
417
+ return `On (window ${input.slaWindowSize ?? DEFAULT_SLA_WINDOW_SIZE})`;
418
+ case "presetCounts":
419
+ case "templateCounts":
420
+ if (input.builtinCount === undefined && input.customCount === undefined) {
421
+ return formatUnset(kind);
422
+ }
423
+ return `${input.builtinCount ?? 0} built-in, ${input.customCount ?? 0} custom`;
424
+ }
425
+ }
426
+
427
+ /**
428
+ * A select-list divider row. Structurally compatible with pi-tui's
429
+ * `SelectItem`; declared locally so this module keeps importing only `./types`.
430
+ */
431
+ export interface MenuSectionItem {
432
+ value: string;
433
+ label: string;
434
+ description: string;
435
+ }
436
+
437
+ /** Kebab-case slug: lowercase, non-alphanumeric runs collapsed to `-`, trimmed. */
438
+ function slugify(label: string): string {
439
+ return label
440
+ .toLowerCase()
441
+ .replace(/[^a-z0-9]+/g, "-")
442
+ .replace(/^-+|-+$/g, "");
443
+ }
444
+
445
+ // ---------------------------------------------------------------------------
446
+ // Menu polish U5: template manager row summary (umbrella #345)
447
+ // ---------------------------------------------------------------------------
448
+
449
+ /**
450
+ * `${param}` slot names declared by a template, sorted and deduped. Mirrors
451
+ * `templates.ts:extractParamNames` over the same `task + outputFile` text; the
452
+ * loop is local because this module's architecture ratchet permits `./types`
453
+ * only (the shared pattern lives there).
454
+ */
455
+ function templateSlotNames(t: TaskTemplate): string[] {
456
+ const names = new Set<string>();
457
+ for (const match of (t.task + (t.outputFile ?? "")).matchAll(TEMPLATE_PARAM_RE)) {
458
+ names.add(match[1]);
459
+ }
460
+ return [...names].sort();
461
+ }
462
+
463
+ /**
464
+ * One-line summary of what a template WILL run with, used as the manager row's
465
+ * description when the template declares no `description`:
466
+ * `preset:<name> · thinking:<level> · slots <a>, <b>` — absent parts omitted.
467
+ * A template declaring none of these falls back to the first 60 characters of
468
+ * its task, which is what every row showed before U5.
469
+ */
470
+ export function formatTemplateSummary(t: TaskTemplate): string {
471
+ const parts: string[] = [];
472
+ if (t.preset) parts.push(`preset:${t.preset}`);
473
+ if (t.thinkingLevel) parts.push(`thinking:${t.thinkingLevel}`);
474
+ const slots = templateSlotNames(t);
475
+ if (slots.length > 0) parts.push(`slots ${slots.join(", ")}`);
476
+ return parts.join(" \u00b7 ") || t.task.slice(0, 60);
477
+ }
478
+
479
+ /** Build a select-list section divider, e.g. `─── Model ───`. Pure. */
480
+ export function menuSection(label: string): MenuSectionItem {
481
+ return {
482
+ value: `__divider__:${slugify(label)}`,
483
+ label: `\u2500\u2500\u2500 ${label} \u2500\u2500\u2500`,
484
+ description: "",
485
+ };
486
+ }