pi-subagent-manager 0.16.0 → 0.18.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/ui/ui.ts CHANGED
@@ -44,12 +44,7 @@ import type { LoaderStyle, WidgetMode } from "../prefs/settings.ts";
44
44
  import { AGENT_PROGRESS_INTERVAL, agentProgressIcon, isAgentLoaderGlyph } from "./agent-loader.ts";
45
45
  export { AGENT_PROGRESS_INTERVAL, agentProgressIcon } from "./agent-loader.ts";
46
46
  import { buildStatusTree, lastStarted, type StatusRow } from "./thread-tree.ts";
47
- import {
48
- THINKING_LEVELS,
49
- type AgentType,
50
- type ThreadService,
51
- type ThreadView,
52
- } from "../types.ts";
47
+ import { THINKING_LEVELS, type AgentType, type ThreadService, type ThreadView } from "../types.ts";
53
48
 
54
49
  export type ThreadController = Pick<
55
50
  ThreadService,
@@ -71,19 +66,14 @@ function agentColorToken(color: string | undefined): ThemeColor {
71
66
  }
72
67
 
73
68
  /** Background pill with bold contrasting text and padding. Label is sanitized. */
74
- function contrastPill(
75
- label: string,
76
- color: string | undefined,
77
- theme: AgentBadgeTheme,
78
- ): string {
69
+ function contrastPill(label: string, color: string | undefined, theme: AgentBadgeTheme): string {
79
70
  const background = theme.colors[agentColorToken(color)];
80
71
  const { r, g, b } = colorToRgb(background);
81
72
  const linear = (channel: number) => {
82
73
  const value = channel / 255;
83
74
  return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
84
75
  };
85
- const luminance =
86
- 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
76
+ const luminance = 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
87
77
  // Pick whichever of black/white has the higher WCAG contrast ratio.
88
78
  const foreground = luminance > Math.sqrt(0.0525) - 0.05 ? 0 : 255;
89
79
  return theme.style(` ${sanitizeText(label)} `, {
@@ -94,10 +84,16 @@ function contrastPill(
94
84
  }
95
85
 
96
86
  /** Invalid/untrusted saved icons never reach the terminal. Names remain readable. */
97
- export function agentTypeLabel(type: string, icon?: string, nerdFontIcons = false, loaderIcon?: string): string {
98
- const role = nerdFontIcons && typeof icon === "string" && /^\p{Co}$/u.test(icon)
99
- ? `${icon} ` : "";
100
- const progress = nerdFontIcons && loaderIcon && isAgentLoaderGlyph(loaderIcon) ? `${loaderIcon} ` : "";
87
+ export function agentTypeLabel(
88
+ type: string,
89
+ icon?: string,
90
+ nerdFontIcons = false,
91
+ loaderIcon?: string,
92
+ ): string {
93
+ const role =
94
+ nerdFontIcons && typeof icon === "string" && /^\p{Co}$/u.test(icon) ? `${icon} ` : "";
95
+ const progress =
96
+ nerdFontIcons && loaderIcon && isAgentLoaderGlyph(loaderIcon) ? `${loaderIcon} ` : "";
101
97
  return `${progress}${role}${sanitizeText(type)}`;
102
98
  }
103
99
 
@@ -112,18 +108,12 @@ export function agentTypeBadge(
112
108
  return contrastPill(agentTypeLabel(type, icon, nerdFontIcons, loaderIcon), color, theme);
113
109
  }
114
110
 
115
- function agentPath(
116
- path: string,
117
- color: string | undefined,
118
- theme: AgentBadgeTheme,
119
- ): string {
111
+ function agentPath(path: string, color: string | undefined, theme: AgentBadgeTheme): string {
120
112
  return theme.fg(agentColorToken(color), sanitizeText(path));
121
113
  }
122
114
 
123
115
  function metricCount(value: number | undefined): number {
124
- return typeof value === "number" && Number.isFinite(value)
125
- ? Math.max(0, Math.floor(value))
126
- : 0;
116
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
127
117
  }
128
118
 
129
119
  /** Settled active time plus the current live run, only while starting or running. */
@@ -161,7 +151,8 @@ function formatCount(value: number | undefined): string {
161
151
  }
162
152
 
163
153
  export function threadMetrics(thread: ThreadView, now = Date.now()): string {
164
- return `${formatDuration(elapsedTotal(thread, now))} ↑${formatCount(thread.inputTokens)} ↓${formatCount(thread.outputTokens)}`;
154
+ const cost = thread.costUsd === undefined ? "" : ` $${thread.costUsd.toFixed(4)}`;
155
+ return `${formatDuration(elapsedTotal(thread, now))} ↑${formatCount(thread.inputTokens)} ↓${formatCount(thread.outputTokens)}${cost}`;
165
156
  }
166
157
 
167
158
  /** Keep the right-hand counters intact; truncate the left side to the remaining columns. */
@@ -175,10 +166,7 @@ function fitLine(left: string, right: string, width: number): string {
175
166
  }
176
167
 
177
168
  function isLive(thread: ThreadView): boolean {
178
- return (
179
- thread.path !== "/root" &&
180
- (thread.state === "starting" || thread.state === "running")
181
- );
169
+ return thread.path !== "/root" && (thread.state === "starting" || thread.state === "running");
182
170
  }
183
171
 
184
172
  export function renderThreads(
@@ -197,39 +185,29 @@ export function renderThreads(
197
185
  const visible = threads
198
186
  .filter((thread) => thread.path !== "/root")
199
187
  .sort(
200
- (a, b) =>
201
- priority(a) - priority(b) ||
202
- b.updatedAt - a.updatedAt ||
203
- b.createdAt - a.createdAt,
188
+ (a, b) => priority(a) - priority(b) || b.updatedAt - a.updatedAt || b.createdAt - a.createdAt,
204
189
  );
205
190
  const limit = visible.length > 8 ? 7 : 8;
206
191
  const lines = visible.slice(0, limit).map((thread) => {
207
192
  const stateColor =
208
- thread.state === "failed"
209
- ? "error"
210
- : thread.state === "paused"
211
- ? "warning"
212
- : "accent";
193
+ thread.state === "failed" ? "error" : thread.state === "paused" ? "warning" : "accent";
213
194
  const badge = agentTypeBadge(
214
- thread.type, thread.color, theme, thread.icon, nerdFontIcons,
195
+ thread.type,
196
+ thread.color,
197
+ theme,
198
+ thread.icon,
199
+ nerdFontIcons,
215
200
  agentProgressIcon(thread, nerdFontIcons, Date.now(), true, loaderStyle),
216
201
  );
217
202
  const path = agentPath(thread.path, thread.color, theme);
218
203
  const state = theme.fg(stateColor, `[${sanitizeText(thread.state)}]`);
219
204
  const left = `${badge} ${path} ${state} ${sanitizeText(thread.status || thread.task)}`;
220
- return fitLine(
221
- left,
222
- theme.fg("muted", threadMetrics(thread)),
223
- Math.max(0, width),
224
- );
205
+ return fitLine(left, theme.fg("muted", threadMetrics(thread)), Math.max(0, width));
225
206
  });
226
207
  if (visible.length > limit) {
227
208
  lines.push(
228
209
  truncateToWidth(
229
- theme.fg(
230
- "muted",
231
- `+${visible.length - limit} more threads · /agents tree`,
232
- ),
210
+ theme.fg("muted", `+${visible.length - limit} more threads · /agents tree`),
233
211
  Math.max(0, width),
234
212
  ),
235
213
  );
@@ -277,14 +255,8 @@ function statePriority(state: ThreadView["state"] | undefined): number {
277
255
  return 2;
278
256
  }
279
257
 
280
- function agentStateColor(
281
- state: ThreadView["state"],
282
- ): "error" | "warning" | "accent" {
283
- return state === "failed"
284
- ? "error"
285
- : state === "paused"
286
- ? "warning"
287
- : "accent";
258
+ function agentStateColor(state: ThreadView["state"]): "error" | "warning" | "accent" {
259
+ return state === "failed" ? "error" : state === "paused" ? "warning" : "accent";
288
260
  }
289
261
 
290
262
  function agentLine(
@@ -297,18 +269,18 @@ function agentLine(
297
269
  ): string {
298
270
  const thread = row.thread!;
299
271
  const badge = agentTypeBadge(
300
- thread.type, thread.color, theme, thread.icon, nerdFontIcons,
272
+ thread.type,
273
+ thread.color,
274
+ theme,
275
+ thread.icon,
276
+ nerdFontIcons,
301
277
  agentProgressIcon(thread, nerdFontIcons, Date.now(), animate, loaderStyle),
302
278
  );
303
279
  const left = `${row.prefix}${badge} ${agentPath(thread.path, thread.color, theme)} ${theme.fg(agentStateColor(thread.state), `[${sanitizeText(thread.state)}]`)} ${sanitizeText(thread.task)}`;
304
280
  return fitLine(left, theme.fg("muted", threadMetrics(thread)), width);
305
281
  }
306
282
 
307
- function placeholderLine(
308
- row: StatusRow,
309
- width: number,
310
- theme: AgentBadgeTheme,
311
- ): string {
283
+ function placeholderLine(row: StatusRow, width: number, theme: AgentBadgeTheme): string {
312
284
  return truncateToWidth(
313
285
  `${row.prefix}${theme.fg("muted", `${sanitizeText(row.path)} missing parent`)}`,
314
286
  width,
@@ -320,35 +292,26 @@ function takeWidgetRows(rows: StatusRow[], budget: number): StatusRow[] {
320
292
  const parents = new Map<number, number[]>();
321
293
  const stack: number[] = [];
322
294
  for (const [index, row] of rows.entries()) {
323
- while (
324
- stack.length &&
325
- rows[stack[stack.length - 1]!]!.prefix.length >= row.prefix.length
326
- )
295
+ while (stack.length && rows[stack[stack.length - 1]!]!.prefix.length >= row.prefix.length)
327
296
  stack.pop();
328
297
  parents.set(index, [...stack]);
329
298
  stack.push(index);
330
299
  }
331
- const rowCost = (row: StatusRow) =>
332
- row.path === WIDGET_ROOT ? 0 : 1;
300
+ const rowCost = (row: StatusRow) => (row.path === WIDGET_ROOT ? 0 : 1);
333
301
  const candidates = rows
334
302
  .map((row, index) => ({ row, index }))
335
303
  .filter(({ row }) => row.thread && row.path !== WIDGET_ROOT)
336
304
  .sort(
337
305
  (a, b) =>
338
- statePriority(a.row.thread!.state) -
339
- statePriority(b.row.thread!.state) ||
340
- lastStarted(b.row.thread) - lastStarted(a.row.thread) || a.index - b.index,
306
+ statePriority(a.row.thread!.state) - statePriority(b.row.thread!.state) ||
307
+ lastStarted(b.row.thread) - lastStarted(a.row.thread) ||
308
+ a.index - b.index,
341
309
  );
342
310
  const chosen = new Set<number>();
343
311
  let used = 0;
344
312
  for (const { index } of candidates) {
345
- const needed = [...parents.get(index)!, index].filter(
346
- (ancestor) => !chosen.has(ancestor),
347
- );
348
- const cost = needed.reduce(
349
- (total, ancestor) => total + rowCost(rows[ancestor]!),
350
- 0,
351
- );
313
+ const needed = [...parents.get(index)!, index].filter((ancestor) => !chosen.has(ancestor));
314
+ const cost = needed.reduce((total, ancestor) => total + rowCost(rows[ancestor]!), 0);
352
315
  if (used + cost > budget) continue;
353
316
  for (const ancestor of needed) chosen.add(ancestor);
354
317
  used += cost;
@@ -362,9 +325,7 @@ function takeWidgetRows(rows: StatusRow[], budget: number): StatusRow[] {
362
325
  used += cost;
363
326
  }
364
327
  }
365
- return rows.filter(
366
- (row, index) => row.path !== WIDGET_ROOT && chosen.has(index),
367
- );
328
+ return rows.filter((row, index) => row.path !== WIDGET_ROOT && chosen.has(index));
368
329
  }
369
330
 
370
331
  /** Themed agent tree above the editor. Synthetic /root is the main conversation and is omitted. */
@@ -372,15 +333,19 @@ export function renderAgentTree(
372
333
  threads: ThreadView[],
373
334
  width: number,
374
335
  theme: AgentBadgeTheme,
375
- { showBrowserHint = true, nerdFontIcons = false, animate = true, loaderStyle = "circle" }: AgentWidgetRenderOptions = {},
336
+ {
337
+ showBrowserHint = true,
338
+ nerdFontIcons = false,
339
+ animate = true,
340
+ loaderStyle = "circle",
341
+ }: AgentWidgetRenderOptions = {},
376
342
  ): string[] {
377
343
  const columns = Math.max(0, width);
378
344
  const rows = buildStatusTree(threads, new Set());
379
345
  const agents = rows.filter((row) => row.thread && row.path !== WIDGET_ROOT);
380
346
  if (!agents.length) return [];
381
347
  const live = agents.filter(
382
- (row) =>
383
- row.thread!.state === "starting" || row.thread!.state === "running",
348
+ (row) => row.thread!.state === "starting" || row.thread!.state === "running",
384
349
  ).length;
385
350
  const paused = agents.filter((row) => row.thread!.state === "paused").length;
386
351
  const heading = fitLine(
@@ -408,7 +373,12 @@ export function renderAgentSummary(
408
373
  threads: ThreadView[],
409
374
  width: number,
410
375
  theme: Pick<Theme, "fg">,
411
- { showBrowserHint = true, nerdFontIcons = false, animate = true, loaderStyle = "circle" }: AgentWidgetRenderOptions = {},
376
+ {
377
+ showBrowserHint = true,
378
+ nerdFontIcons = false,
379
+ animate = true,
380
+ loaderStyle = "circle",
381
+ }: AgentWidgetRenderOptions = {},
412
382
  ): string[] {
413
383
  const agents = new Map<string, ThreadView>();
414
384
  for (const thread of threads) {
@@ -440,15 +410,17 @@ export function renderAgentSummary(
440
410
  ["paused", "warning"],
441
411
  ["completed", "success"],
442
412
  ];
443
- const left = statuses
444
- .filter(([state]) => state === "running" || counts[state] > 0)
445
- .map(([state, color]) => {
446
- const progress = counts[state] > 0
447
- ? agentProgressIcon({ state }, nerdFontIcons, Date.now(), animate, loaderStyle)
448
- : undefined;
449
- return theme.fg(color, `${progress ? `${progress} ` : ""}${counts[state]} ${state}`);
450
- })
451
- .join(theme.fg("muted", ", ")) +
413
+ const left =
414
+ statuses
415
+ .filter(([state]) => state === "running" || counts[state] > 0)
416
+ .map(([state, color]) => {
417
+ const progress =
418
+ counts[state] > 0
419
+ ? agentProgressIcon({ state }, nerdFontIcons, Date.now(), animate, loaderStyle)
420
+ : undefined;
421
+ return theme.fg(color, `${progress ? `${progress} ` : ""}${counts[state]} ${state}`);
422
+ })
423
+ .join(theme.fg("muted", ", ")) +
452
424
  (showBrowserHint && counts.running > 0 ? theme.fg("muted", " · ← browser") : "");
453
425
  const right = theme.fg("muted", `↑${formatCount(input)} ↓${formatCount(output)}`);
454
426
  return [fitLine(left, right, Math.max(0, width))];
@@ -474,7 +446,12 @@ export function updateWidget(
474
446
  if (ctx.mode === "rpc") {
475
447
  ctx.ui.setWidget(
476
448
  "pi-subagent",
477
- render(threads, 80, ctx.ui.theme, { showBrowserHint: false, nerdFontIcons, loaderStyle, animate: false }),
449
+ render(threads, 80, ctx.ui.theme, {
450
+ showBrowserHint: false,
451
+ nerdFontIcons,
452
+ loaderStyle,
453
+ animate: false,
454
+ }),
478
455
  AGENT_WIDGET_PLACEMENT,
479
456
  );
480
457
  return;
@@ -485,15 +462,19 @@ export function updateWidget(
485
462
  (tui) => {
486
463
  let timer: ReturnType<typeof setInterval> | undefined;
487
464
  if (snapshot.some(isLive) && (mode === "full" || nerdFontIcons)) {
488
- timer = setInterval(() => tui.requestRender(), nerdFontIcons ? AGENT_PROGRESS_INTERVAL : 1000);
465
+ timer = setInterval(
466
+ () => tui.requestRender(),
467
+ nerdFontIcons ? AGENT_PROGRESS_INTERVAL : 1000,
468
+ );
489
469
  timer.unref();
490
470
  }
491
471
  return {
492
- render: (width) => render(snapshot, width, ctx.ui.theme, {
493
- showBrowserHint: !settled,
494
- nerdFontIcons,
495
- loaderStyle,
496
- }),
472
+ render: (width) =>
473
+ render(snapshot, width, ctx.ui.theme, {
474
+ showBrowserHint: !settled,
475
+ nerdFontIcons,
476
+ loaderStyle,
477
+ }),
497
478
  invalidate: () => {},
498
479
  dispose: () => {
499
480
  if (timer) clearInterval(timer);
@@ -515,9 +496,7 @@ export async function showThreads(
515
496
  while (true) {
516
497
  try {
517
498
  if (!selectedPath) {
518
- const threads = controller
519
- .list()
520
- .filter((thread) => thread.path !== "/root");
499
+ const threads = controller.list().filter((thread) => thread.path !== "/root");
521
500
  if (!threads.length) {
522
501
  ctx.ui.notify("No subagent threads.", "info");
523
502
  return;
@@ -534,9 +513,7 @@ export async function showThreads(
534
513
  if (selectedPath === "/root")
535
514
  throw new Error("/root is the current Pi thread, not a subagent.");
536
515
  const thread = controller.get(selectedPath);
537
- const children = controller
538
- .list()
539
- .filter((child) => child.parent === selectedPath);
516
+ const children = controller.list().filter((child) => child.parent === selectedPath);
540
517
  const title = `${sanitizeText(thread.path)} [${sanitizeText(thread.state)}] ${sanitizeText(thread.status)}`;
541
518
  const action = await ctx.ui.select(title, [
542
519
  "View output",
@@ -562,10 +539,7 @@ export async function showThreads(
562
539
  text.split("\n").map(sanitizeText).join("\n"),
563
540
  );
564
541
  } else if (action === "Send input / resume") {
565
- const message = await ctx.ui.editor(
566
- "Send input / resume retained session",
567
- "",
568
- );
542
+ const message = await ctx.ui.editor("Send input / resume retained session", "");
569
543
  if (message?.trim()) await controller.steer(selectedPath, message);
570
544
  } else if (action === "Stop") {
571
545
  if (
@@ -582,14 +556,10 @@ export async function showThreads(
582
556
  );
583
557
  const selected = await ctx.ui.select("Children", labels);
584
558
  if (selected !== undefined)
585
- selectedPath =
586
- children[labels.indexOf(selected)]?.path ?? selectedPath;
559
+ selectedPath = children[labels.indexOf(selected)]?.path ?? selectedPath;
587
560
  }
588
561
  } catch (error) {
589
- ctx.ui.notify(
590
- sanitizeText(error instanceof Error ? error.message : String(error)),
591
- "error",
592
- );
562
+ ctx.ui.notify(sanitizeText(error instanceof Error ? error.message : String(error)), "error");
593
563
  return;
594
564
  }
595
565
  }
@@ -606,15 +576,9 @@ export function editorArguments(command: string): string[] {
606
576
  return args as string[];
607
577
  }
608
578
 
609
- async function externalEdit(
610
- ctx: ExtensionCommandContext,
611
- text: string,
612
- ): Promise<string> {
613
- if (ctx.mode !== "tui")
614
- throw new Error("External editing requires interactive TUI mode.");
615
- const [command, ...args] = editorArguments(
616
- process.env.VISUAL || process.env.EDITOR || "vi",
617
- );
579
+ async function externalEdit(ctx: ExtensionCommandContext, text: string): Promise<string> {
580
+ if (ctx.mode !== "tui") throw new Error("External editing requires interactive TUI mode.");
581
+ const [command, ...args] = editorArguments(process.env.VISUAL || process.env.EDITOR || "vi");
618
582
  const directory = await mkdtemp(join(tmpdir(), "pi-subagent-"));
619
583
  const file = join(directory, "agent.md");
620
584
  try {
@@ -628,9 +592,7 @@ async function externalEdit(
628
592
  });
629
593
  if (result.error) throw result.error;
630
594
  if (result.status !== 0)
631
- throw new Error(
632
- `Editor exited with status ${result.status ?? result.signal}.`,
633
- );
595
+ throw new Error(`Editor exited with status ${result.status ?? result.signal}.`);
634
596
  } finally {
635
597
  tui.start();
636
598
  tui.requestRender(true);
@@ -712,17 +674,10 @@ class AgentColorPickerComponent extends Container {
712
674
  this.updatePreview(tui, item.value);
713
675
  };
714
676
  this.selectList.onSelect = (item) => {
715
- onSelect(
716
- item.value === AGENT_COLOR_DEFAULT
717
- ? undefined
718
- : (item.value as AgentType["color"]),
719
- );
677
+ onSelect(item.value === AGENT_COLOR_DEFAULT ? undefined : (item.value as AgentType["color"]));
720
678
  };
721
679
  this.selectList.onCancel = onCancel;
722
- this.updatePreview(
723
- tui,
724
- this.items[selectedIndex >= 0 ? selectedIndex : 0]!.value,
725
- );
680
+ this.updatePreview(tui, this.items[selectedIndex >= 0 ? selectedIndex : 0]!.value);
726
681
  }
727
682
 
728
683
  getItems(): readonly {
@@ -739,10 +694,7 @@ class AgentColorPickerComponent extends Container {
739
694
  const selected = this.items.findIndex(
740
695
  (item) => item.value === this.selectList.getSelectedItem()?.value,
741
696
  );
742
- const start = Math.max(
743
- 0,
744
- Math.min(selected - budget + 1, this.items.length - budget),
745
- );
697
+ const start = Math.max(0, Math.min(selected - budget + 1, this.items.length - budget));
746
698
  const body = [
747
699
  ` ${truncateToWidth(
748
700
  this.preview
@@ -783,10 +735,7 @@ class AgentColorPickerComponent extends Container {
783
735
  this.selectList.handleInput(keyData);
784
736
  }
785
737
 
786
- private updatePreview(
787
- tui: { requestRender(force?: boolean): void },
788
- value: string,
789
- ): void {
738
+ private updatePreview(tui: { requestRender(force?: boolean): void }, value: string): void {
790
739
  const color = value === AGENT_COLOR_DEFAULT ? undefined : value;
791
740
  const badge = agentTypeBadge(this.agentName, color, this.theme);
792
741
  const path = agentPath("/root/example-task", color, this.theme);
@@ -841,13 +790,8 @@ async function editDocument(
841
790
  source: type.source,
842
791
  };
843
792
  } catch (error) {
844
- const diagnostic = sanitizeText(
845
- error instanceof Error ? error.message : String(error),
846
- );
847
- ctx.ui.notify(
848
- `Edit not accepted: ${diagnostic}. Original definition is unchanged.`,
849
- "error",
850
- );
793
+ const diagnostic = sanitizeText(error instanceof Error ? error.message : String(error));
794
+ ctx.ui.notify(`Edit not accepted: ${diagnostic}. Original definition is unchanged.`, "error");
851
795
  const action = await dialogMenu(ctx, "Invalid edit — retry?", [
852
796
  {
853
797
  id: "Retry",
@@ -876,16 +820,12 @@ function assertSaveDestination(
876
820
  kind: AgentEditMode = "fork",
877
821
  ): void {
878
822
  if (kind === "override" && original && type.name !== original.name) {
879
- throw new Error(
880
- "Settings overrides cannot rename the agent; fork it instead.",
881
- );
823
+ throw new Error("Settings overrides cannot rename the agent; fork it instead.");
882
824
  }
883
825
  const entries = store.list();
884
826
  const sameName = entries.find((entry) => entry.name === type.name);
885
827
  if (sameName && (!original || type.name !== original.name)) {
886
- throw new Error(
887
- `Agent type ${type.name} already exists; choose a different name.`,
888
- );
828
+ throw new Error(`Agent type ${type.name} already exists; choose a different name.`);
889
829
  }
890
830
  const destination = store.destination(type.name, scope, original, kind);
891
831
  if (
@@ -969,17 +909,15 @@ const EDIT_FIELD_HELP: Record<EditMenuAction, string> = {
969
909
  thinkingLevel: "Reasoning effort. Default follows the parent session.",
970
910
  "tools.allow":
971
911
  "Pick session tools with checkboxes. Under Allowed (except blocked), an unset or empty allow list allows no tools.",
972
- "tools.block": "Pick session tools to block. Blocked tools take precedence when the policy uses this list.",
912
+ "tools.block":
913
+ "Pick session tools to block. Blocked tools take precedence when the policy uses this list.",
973
914
  color: "Thread widget color with live preview.",
974
915
  icon: "Paste a single Nerd Font glyph from nerdfonts.com/cheat-sheet (not its name or codepoint).\nLeave blank to remove. Display requires [labs] Nerd Font icons in settings and a Nerd Font in your terminal.",
975
916
  systemPrompt: "Edit the Markdown prompt body in a multiline dialog.",
976
- "Save scope":
977
- "Project definitions override global definitions with the same name.",
978
- Source:
979
- "Read-only source. Bundled definitions are copied, never overwritten.",
917
+ "Save scope": "Project definitions override global definitions with the same name.",
918
+ Source: "Read-only source. Bundled definitions are copied, never overwritten.",
980
919
  "Edit frontmatter YAML": "Edit metadata as YAML, preserving the prompt body.",
981
- "External editor (entire Markdown)":
982
- "Edit the complete definition using $VISUAL / $EDITOR.",
920
+ "External editor (entire Markdown)": "Edit the complete definition using $VISUAL / $EDITOR.",
983
921
  Save: "Validate and save. Existing sessions keep their original configuration.",
984
922
  "Reset to bundled":
985
923
  "Delete this fork/override file and go back to the definition shipped with the extension. Unsaved edits are discarded.",
@@ -991,10 +929,7 @@ async function chooseSaveScope(
991
929
  store: ConfigStore,
992
930
  current: "user" | "project",
993
931
  ): Promise<"user" | "project" | undefined> {
994
- const choices = [
995
- "Global",
996
- ...(store.canSaveProject() ? ["Trusted project"] : []),
997
- ];
932
+ const choices = ["Global", ...(store.canSaveProject() ? ["Trusted project"] : [])];
998
933
  const value = await dialogMenu(
999
934
  ctx,
1000
935
  "Save scope",
@@ -1020,10 +955,7 @@ function modelSuggestionPrefill(suggestions: string[] | undefined): string {
1020
955
  return (suggestions ?? []).map((name) => sanitizeText(name)).join("\n");
1021
956
  }
1022
957
 
1023
- function customizationMenuValue(
1024
- editMode: AgentEditMode | undefined,
1025
- isNew: boolean,
1026
- ): string {
958
+ function customizationMenuValue(editMode: AgentEditMode | undefined, isNew: boolean): string {
1027
959
  if (isNew) return "New full definition (.md)";
1028
960
  if (editMode === "override") return "Settings override (.yml)";
1029
961
  if (editMode === "fork") return "Full copy (.md)";
@@ -1098,7 +1030,9 @@ export async function editAgentTypes(
1098
1030
  toolEditor: ToolEditorOptions = { getAllTools: () => [], toolFiltering: "allowed" },
1099
1031
  ): Promise<void> {
1100
1032
  if (!canOpenDialog(ctx)) return;
1101
- await withDialogSession(ctx, (scoped) => editAgentTypesDialog(scoped, store, nerdFontIcons, toolEditor));
1033
+ await withDialogSession(ctx, (scoped) =>
1034
+ editAgentTypesDialog(scoped, store, nerdFontIcons, toolEditor),
1035
+ );
1102
1036
  }
1103
1037
 
1104
1038
  async function editAgentTypesDialog(
@@ -1119,14 +1053,14 @@ async function editAgentTypesDialog(
1119
1053
  ...types.map((type) => ({
1120
1054
  id: type.name,
1121
1055
  label: type.name,
1122
- renderLabel: (label: string, theme: Theme) => agentTypeBadge(label, type.color, theme, type.icon, nerdFontIcons),
1056
+ renderLabel: (label: string, theme: Theme) =>
1057
+ agentTypeBadge(label, type.color, theme, type.icon, nerdFontIcons),
1123
1058
  value: type.description,
1124
1059
  help: `${type.source ?? "user"} · ${type.filePath ?? ""}`,
1125
1060
  })),
1126
1061
  ]);
1127
1062
  if (selection === undefined) return;
1128
- const original =
1129
- selection === "Create new type" ? undefined : store.get(selection);
1063
+ const original = selection === "Create new type" ? undefined : store.get(selection);
1130
1064
  const isNew = !original;
1131
1065
  let draft: AgentType = original
1132
1066
  ? structuredClone(original)
@@ -1134,9 +1068,7 @@ async function editAgentTypesDialog(
1134
1068
  const originalContent = serializeAgentType(draft);
1135
1069
  let selectedId: string | undefined;
1136
1070
  let saveScope: "user" | "project" =
1137
- original?.source === "project" && store.canSaveProject()
1138
- ? "project"
1139
- : "user";
1071
+ original?.source === "project" && store.canSaveProject() ? "project" : "user";
1140
1072
  // Bundled definitions stay read-only until the user picks how to own them.
1141
1073
  let editMode: AgentEditMode | undefined = isNew
1142
1074
  ? "fork"
@@ -1168,16 +1100,16 @@ async function editAgentTypesDialog(
1168
1100
  return {
1169
1101
  id: action,
1170
1102
  label: EDIT_FIELD_LABELS[action],
1171
- valueColor: action === "Save" && dirty ? "warning" as const : undefined,
1103
+ valueColor: action === "Save" && dirty ? ("warning" as const) : undefined,
1172
1104
  value:
1173
1105
  action === "Customization"
1174
1106
  ? customizationMenuValue(editMode, isNew)
1175
1107
  : action === "Save" && dirty
1176
1108
  ? "(changes)"
1177
1109
  : action === "Source"
1178
- ? (original?.customization
1110
+ ? original?.customization
1179
1111
  ? `${original.customization.scope} ${original.customization.kind} over ${original.baseSource ?? "bundled"}`
1180
- : (original?.source ?? "New draft"))
1112
+ : (original?.source ?? "New draft")
1181
1113
  : action === "Save scope"
1182
1114
  ? saveScope === "user"
1183
1115
  ? "Global"
@@ -1189,10 +1121,10 @@ async function editAgentTypesDialog(
1189
1121
  : "",
1190
1122
  help:
1191
1123
  action === "Source"
1192
- ? (original?.customization
1124
+ ? original?.customization
1193
1125
  ? `Settings file: ${original.customization.filePath}. Base prompt: ${original.baseFilePath ?? "(bundled)"}.`
1194
1126
  : (original?.filePath ??
1195
- "Not saved yet. Bundled definitions are copied, never overwritten."))
1127
+ "Not saved yet. Bundled definitions are copied, never overwritten.")
1196
1128
  : EDIT_FIELD_HELP[action],
1197
1129
  };
1198
1130
  }),
@@ -1310,16 +1242,10 @@ async function editAgentTypesDialog(
1310
1242
  continue;
1311
1243
  }
1312
1244
  if (field === "Source") {
1313
- ctx.ui.notify(
1314
- original?.filePath ?? "This definition has not been saved yet.",
1315
- "info",
1316
- );
1245
+ ctx.ui.notify(original?.filePath ?? "This definition has not been saved yet.", "info");
1317
1246
  continue;
1318
1247
  }
1319
- if (
1320
- field === "External editor (entire Markdown)" ||
1321
- field === "Edit frontmatter YAML"
1322
- ) {
1248
+ if (field === "External editor (entire Markdown)" || field === "Edit frontmatter YAML") {
1323
1249
  const edited = await editDocument(
1324
1250
  ctx,
1325
1251
  draft,
@@ -1329,11 +1255,7 @@ async function editAgentTypesDialog(
1329
1255
  continue;
1330
1256
  }
1331
1257
  const candidate = structuredClone(draft);
1332
- if (
1333
- field === "name" ||
1334
- field === "description" ||
1335
- field === "systemPrompt"
1336
- ) {
1258
+ if (field === "name" || field === "description" || field === "systemPrompt") {
1337
1259
  const originalValue = candidate[field] ?? "";
1338
1260
  // Editor prefill must not carry terminal controls. An unmodified or
1339
1261
  // SDK-trimmed submit keeps the original, including whitespace and CRLF.
@@ -1345,12 +1267,13 @@ async function editAgentTypesDialog(
1345
1267
  .join("\n");
1346
1268
  const value = await dialogEditor(ctx, `Agent ${field}`, prefill);
1347
1269
  if (value === undefined) continue;
1348
- candidate[field] =
1349
- value === prefill || value === prefill.trim()
1350
- ? originalValue
1351
- : value;
1270
+ candidate[field] = value === prefill || value === prefill.trim() ? originalValue : value;
1352
1271
  } else if (field === "icon") {
1353
- const value = await dialogEditor(ctx, "Agent icon (Nerd Font glyph; blank to remove)", candidate.icon ?? "");
1272
+ const value = await dialogEditor(
1273
+ ctx,
1274
+ "Agent icon (Nerd Font glyph; blank to remove)",
1275
+ candidate.icon ?? "",
1276
+ );
1354
1277
  if (value === undefined) continue;
1355
1278
  const icon = value.trim();
1356
1279
  if (!icon) delete candidate.icon;
@@ -1398,11 +1321,7 @@ async function editAgentTypesDialog(
1398
1321
  if (value === "Default (inherit)") delete candidate.thinkingLevel;
1399
1322
  else candidate.thinkingLevel = value as AgentType["thinkingLevel"];
1400
1323
  } else if (field === "color") {
1401
- const value = await selectAgentColor(
1402
- ctx,
1403
- candidate.color,
1404
- candidate.name,
1405
- );
1324
+ const value = await selectAgentColor(ctx, candidate.color, candidate.name);
1406
1325
  if (value === AGENT_COLOR_CANCEL) continue;
1407
1326
  if (value === undefined) delete candidate.color;
1408
1327
  else candidate.color = value;