pi-subagent-manager 0.13.0 → 0.15.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.
@@ -24,11 +24,7 @@ function comparePath(a: string, b: string): number {
24
24
  return a < b ? -1 : a > b ? 1 : 0;
25
25
  }
26
26
 
27
- function chainHas(
28
- parentOf: Map<string, string | null>,
29
- start: string,
30
- target: string,
31
- ): boolean {
27
+ function chainHas(parentOf: Map<string, string | null>, start: string, target: string): boolean {
32
28
  const seen = new Set<string>();
33
29
  let current: string | null = start;
34
30
  while (current) {
@@ -39,18 +35,49 @@ function chainHas(
39
35
  return false;
40
36
  }
41
37
 
38
+ /** When an agent last (re)started; older saves fall back to creation time. */
39
+ export function lastStarted(thread: ThreadView | undefined): number {
40
+ const value = thread?.lastStartedAt ?? thread?.createdAt;
41
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
42
+ }
43
+
44
+ /** Newest branch first: a branch ranks by its most recently started agent. Cycles are guarded. */
45
+ export function recencyComparator(threads: ThreadView[]): (a: string, b: string) => number {
46
+ const byPath = new Map<string, ThreadView>();
47
+ for (const thread of threads) {
48
+ if (thread?.path && !byPath.has(thread.path)) byPath.set(thread.path, thread);
49
+ }
50
+ const latest = new Map<string, number>();
51
+ for (const thread of byPath.values()) {
52
+ const time = lastStarted(thread);
53
+ const seen = new Set<string>();
54
+ let current: string | null = thread.path;
55
+ while (current && !seen.has(current)) {
56
+ seen.add(current);
57
+ latest.set(current, Math.max(latest.get(current) ?? 0, time));
58
+ const view = byPath.get(current);
59
+ current = view
60
+ ? view.parent && view.parent !== current
61
+ ? view.parent
62
+ : null
63
+ : lexicalParent(current);
64
+ }
65
+ }
66
+ return (a, b) => (latest.get(b) ?? 0) - (latest.get(a) ?? 0) || comparePath(a, b);
67
+ }
68
+
42
69
  /** Flatten retained agents. Parent links win over path shape; /root is always present.
43
- * `comparePaths` orders siblings and roots only. Cycle repair stays lexical.
70
+ * `comparePaths` orders siblings and roots only (default: most recently started branch first).
71
+ * Cycle repair stays lexical.
44
72
  */
45
73
  export function buildStatusTree(
46
74
  threads: ThreadView[],
47
75
  collapsed: Set<string>,
48
- comparePaths: (a: string, b: string) => number = comparePath,
76
+ comparePaths: (a: string, b: string) => number = recencyComparator(threads),
49
77
  ): StatusRow[] {
50
78
  const threadsByPath = new Map<string, ThreadView>();
51
79
  for (const thread of threads) {
52
- if (thread?.path && !threadsByPath.has(thread.path))
53
- threadsByPath.set(thread.path, thread);
80
+ if (thread?.path && !threadsByPath.has(thread.path)) threadsByPath.set(thread.path, thread);
54
81
  }
55
82
  const nodes = new Map<string, StatusNode>();
56
83
  const parentOf = new Map<string, string | null>();
@@ -65,8 +92,7 @@ export function buildStatusTree(
65
92
  const declaredParent = (path: string): string | null => {
66
93
  if (path === ROOT) return null;
67
94
  const thread = threadsByPath.get(path);
68
- if (thread)
69
- return thread.parent && thread.parent !== path ? thread.parent : null;
95
+ if (thread) return thread.parent && thread.parent !== path ? thread.parent : null;
70
96
  return lexicalParent(path);
71
97
  };
72
98
  const ensure = (path: string, seen = new Set<string>()): void => {
package/src/ui/ui.ts CHANGED
@@ -39,8 +39,10 @@ import {
39
39
  withDialogSession,
40
40
  } from "./dialog.ts";
41
41
  import { getModelPreferences } from "../prefs/models.ts";
42
- import type { WidgetMode } from "../prefs/settings.ts";
43
- import { buildStatusTree, type StatusRow } from "./thread-tree.ts";
42
+ import type { LoaderStyle, WidgetMode } from "../prefs/settings.ts";
43
+ import { AGENT_PROGRESS_INTERVAL, agentProgressIcon, isAgentLoaderGlyph } from "./agent-loader.ts";
44
+ export { AGENT_PROGRESS_INTERVAL, agentProgressIcon } from "./agent-loader.ts";
45
+ import { buildStatusTree, lastStarted, type StatusRow } from "./thread-tree.ts";
44
46
  import {
45
47
  THINKING_LEVELS,
46
48
  type AgentType,
@@ -91,33 +93,11 @@ function contrastPill(
91
93
  }
92
94
 
93
95
  /** Invalid/untrusted saved icons never reach the terminal. Names remain readable. */
94
- export function agentTypeLabel(type: string, icon?: string, nerdFontIcons = false): string {
95
- const prefix = nerdFontIcons && typeof icon === "string" && /^\p{Co}$/u.test(icon)
96
+ export function agentTypeLabel(type: string, icon?: string, nerdFontIcons = false, loaderIcon?: string): string {
97
+ const role = nerdFontIcons && typeof icon === "string" && /^\p{Co}$/u.test(icon)
96
98
  ? `${icon} ` : "";
97
- return `${prefix}${sanitizeText(type)}`;
98
- }
99
-
100
- /** Nerd Fonts md-circle-slice-1..8: an equal-width, shape-changing progress cycle.
101
- * Verified against https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/glyphnames.json.
102
- */
103
- export const AGENT_PROGRESS_INTERVAL = 180;
104
- const AGENT_PROGRESS_FRAMES = Array.from({ length: 8 }, (_, index) =>
105
- String.fromCodePoint(0xf0a9e + index),
106
- );
107
-
108
- /** Keep the configured role icon for settled threads and non-animated/RPC output. */
109
- export function agentProgressIcon(
110
- thread: Pick<ThreadView, "state" | "icon">,
111
- nerdFontIcons: boolean,
112
- now = Date.now(),
113
- animate = true,
114
- ): string | undefined {
115
- if (!nerdFontIcons) return undefined;
116
- if (animate && (thread.state === "starting" || thread.state === "running")) {
117
- const frame = Math.floor(Math.max(0, now) / AGENT_PROGRESS_INTERVAL) % AGENT_PROGRESS_FRAMES.length;
118
- return AGENT_PROGRESS_FRAMES[frame];
119
- }
120
- return thread.icon;
99
+ const progress = nerdFontIcons && loaderIcon && isAgentLoaderGlyph(loaderIcon) ? `${loaderIcon} ` : "";
100
+ return `${progress}${role}${sanitizeText(type)}`;
121
101
  }
122
102
 
123
103
  export function agentTypeBadge(
@@ -126,8 +106,9 @@ export function agentTypeBadge(
126
106
  theme: AgentBadgeTheme,
127
107
  icon?: string,
128
108
  nerdFontIcons = false,
109
+ loaderIcon?: string,
129
110
  ): string {
130
- return contrastPill(agentTypeLabel(type, icon, nerdFontIcons), color, theme);
111
+ return contrastPill(agentTypeLabel(type, icon, nerdFontIcons, loaderIcon), color, theme);
131
112
  }
132
113
 
133
114
  function agentPath(
@@ -204,6 +185,7 @@ export function renderThreads(
204
185
  width: number,
205
186
  theme: AgentBadgeTheme,
206
187
  nerdFontIcons = false,
188
+ loaderStyle: LoaderStyle = "circle",
207
189
  ): string[] {
208
190
  const priority = (thread: ThreadView) =>
209
191
  thread.state === "starting" || thread.state === "running"
@@ -228,7 +210,8 @@ export function renderThreads(
228
210
  ? "warning"
229
211
  : "accent";
230
212
  const badge = agentTypeBadge(
231
- thread.type, thread.color, theme, agentProgressIcon(thread, nerdFontIcons), nerdFontIcons,
213
+ thread.type, thread.color, theme, thread.icon, nerdFontIcons,
214
+ agentProgressIcon(thread, nerdFontIcons, Date.now(), true, loaderStyle),
232
215
  );
233
216
  const path = agentPath(thread.path, thread.color, theme);
234
217
  const state = theme.fg(stateColor, `[${sanitizeText(thread.state)}]`);
@@ -262,7 +245,8 @@ interface AgentWidgetRenderOptions {
262
245
  /** RPC widgets cannot open a terminal browser. */
263
246
  showBrowserHint?: boolean;
264
247
  nerdFontIcons?: boolean;
265
- /** RPC snapshots use static role icons and never start an animation. */
248
+ loaderStyle?: LoaderStyle;
249
+ /** RPC snapshots use a static running frame and never start an animation. */
266
250
  animate?: boolean;
267
251
  }
268
252
 
@@ -292,76 +276,6 @@ function statePriority(state: ThreadView["state"] | undefined): number {
292
276
  return 2;
293
277
  }
294
278
 
295
- function explicitParent(
296
- path: string,
297
- threadsByPath: Map<string, ThreadView>,
298
- ): string | null {
299
- if (path === WIDGET_ROOT) return null;
300
- const thread = threadsByPath.get(path);
301
- if (thread)
302
- return thread.parent && thread.parent !== path ? thread.parent : null;
303
- const index = path.lastIndexOf("/");
304
- return index > 0 ? path.slice(0, index) : null;
305
- }
306
-
307
- /** Lowest state in the branch. Parent links define ancestry; cycles are guarded. */
308
- function branchPriorityComparator(
309
- threads: ThreadView[],
310
- ): (a: string, b: string) => number {
311
- const threadsByPath = new Map<string, ThreadView>();
312
- for (const thread of threads) {
313
- if (thread?.path && !threadsByPath.has(thread.path))
314
- threadsByPath.set(thread.path, thread);
315
- }
316
- const children = new Map<string, string[]>();
317
- const link = (path: string, seen: Set<string>) => {
318
- if (!path || seen.has(path)) return;
319
- seen.add(path);
320
- const parent = explicitParent(path, threadsByPath);
321
- if (!parent || parent === path) return;
322
- const list = children.get(parent) ?? [];
323
- if (!list.includes(path)) list.push(path);
324
- children.set(parent, list);
325
- link(parent, seen);
326
- };
327
- link(WIDGET_ROOT, new Set());
328
- for (const path of threadsByPath.keys()) link(path, new Set());
329
-
330
- const subtree = new Map<string, number>();
331
- const ancestors = new Map<string, number>();
332
- const subtreeOf = (path: string, stack: Set<string>): number => {
333
- const cached = subtree.get(path);
334
- if (cached !== undefined) return cached;
335
- const own = statePriority(threadsByPath.get(path)?.state);
336
- if (stack.has(path)) return own;
337
- stack.add(path);
338
- let best = own;
339
- for (const child of children.get(path) ?? [])
340
- best = Math.min(best, subtreeOf(child, stack));
341
- stack.delete(path);
342
- subtree.set(path, best);
343
- return best;
344
- };
345
- const ancestorOf = (path: string): number => {
346
- const cached = ancestors.get(path);
347
- if (cached !== undefined) return cached;
348
- let best = 2;
349
- const seen = new Set<string>();
350
- let current: string | null = path;
351
- while (current && !seen.has(current)) {
352
- seen.add(current);
353
- best = Math.min(best, statePriority(threadsByPath.get(current)?.state));
354
- current = explicitParent(current, threadsByPath);
355
- }
356
- ancestors.set(path, best);
357
- return best;
358
- };
359
- return (a, b) =>
360
- subtreeOf(a, new Set()) - subtreeOf(b, new Set()) ||
361
- ancestorOf(a) - ancestorOf(b) ||
362
- (a < b ? -1 : a > b ? 1 : 0);
363
- }
364
-
365
279
  function agentStateColor(
366
280
  state: ThreadView["state"],
367
281
  ): "error" | "warning" | "accent" {
@@ -378,11 +292,12 @@ function agentLine(
378
292
  theme: AgentBadgeTheme,
379
293
  nerdFontIcons: boolean,
380
294
  animate: boolean,
295
+ loaderStyle: LoaderStyle,
381
296
  ): string {
382
297
  const thread = row.thread!;
383
298
  const badge = agentTypeBadge(
384
- thread.type, thread.color, theme,
385
- agentProgressIcon(thread, nerdFontIcons, Date.now(), animate), nerdFontIcons,
299
+ thread.type, thread.color, theme, thread.icon, nerdFontIcons,
300
+ agentProgressIcon(thread, nerdFontIcons, Date.now(), animate, loaderStyle),
386
301
  );
387
302
  const left = `${row.prefix}${badge} ${agentPath(thread.path, thread.color, theme)} ${theme.fg(agentStateColor(thread.state), `[${sanitizeText(thread.state)}]`)} ${sanitizeText(thread.task)}`;
388
303
  return fitLine(left, theme.fg("muted", threadMetrics(thread)), width);
@@ -421,7 +336,7 @@ function takeWidgetRows(rows: StatusRow[], budget: number): StatusRow[] {
421
336
  (a, b) =>
422
337
  statePriority(a.row.thread!.state) -
423
338
  statePriority(b.row.thread!.state) ||
424
- b.row.thread!.createdAt - a.row.thread!.createdAt || a.index - b.index,
339
+ lastStarted(b.row.thread) - lastStarted(a.row.thread) || a.index - b.index,
425
340
  );
426
341
  const chosen = new Set<number>();
427
342
  let used = 0;
@@ -456,14 +371,10 @@ export function renderAgentTree(
456
371
  threads: ThreadView[],
457
372
  width: number,
458
373
  theme: AgentBadgeTheme,
459
- { showBrowserHint = true, nerdFontIcons = false, animate = true }: AgentWidgetRenderOptions = {},
374
+ { showBrowserHint = true, nerdFontIcons = false, animate = true, loaderStyle = "circle" }: AgentWidgetRenderOptions = {},
460
375
  ): string[] {
461
376
  const columns = Math.max(0, width);
462
- const rows = buildStatusTree(
463
- threads,
464
- new Set(),
465
- branchPriorityComparator(threads),
466
- );
377
+ const rows = buildStatusTree(threads, new Set());
467
378
  const agents = rows.filter((row) => row.thread && row.path !== WIDGET_ROOT);
468
379
  if (!agents.length) return [];
469
380
  const live = agents.filter(
@@ -485,7 +396,7 @@ export function renderAgentTree(
485
396
  lines.push(placeholderLine(row, columns, theme));
486
397
  continue;
487
398
  }
488
- lines.push(agentLine(row, columns, theme, nerdFontIcons, animate));
399
+ lines.push(agentLine(row, columns, theme, nerdFontIcons, animate, loaderStyle));
489
400
  }
490
401
  lines.push(agentWidgetStatus(live, omitted, columns, theme, showBrowserHint));
491
402
  return lines;
@@ -496,7 +407,7 @@ export function renderAgentSummary(
496
407
  threads: ThreadView[],
497
408
  width: number,
498
409
  theme: Pick<Theme, "fg">,
499
- { showBrowserHint = true, nerdFontIcons = false, animate = true }: AgentWidgetRenderOptions = {},
410
+ { showBrowserHint = true, nerdFontIcons = false, animate = true, loaderStyle = "circle" }: AgentWidgetRenderOptions = {},
500
411
  ): string[] {
501
412
  const agents = new Map<string, ThreadView>();
502
413
  for (const thread of threads) {
@@ -528,13 +439,14 @@ export function renderAgentSummary(
528
439
  ["paused", "warning"],
529
440
  ["completed", "success"],
530
441
  ];
531
- const progress = counts.running > 0
532
- ? agentProgressIcon({ state: "running" }, nerdFontIcons, Date.now(), animate)
533
- : undefined;
534
442
  const left = statuses
535
443
  .filter(([state]) => state === "running" || counts[state] > 0)
536
- .map(([state, color]) => theme.fg(color,
537
- `${state === "running" && progress ? `${progress} ` : ""}${counts[state]} ${state}`))
444
+ .map(([state, color]) => {
445
+ const progress = counts[state] > 0
446
+ ? agentProgressIcon({ state }, nerdFontIcons, Date.now(), animate, loaderStyle)
447
+ : undefined;
448
+ return theme.fg(color, `${progress ? `${progress} ` : ""}${counts[state]} ${state}`);
449
+ })
538
450
  .join(theme.fg("muted", ", ")) +
539
451
  (showBrowserHint && counts.running > 0 ? theme.fg("muted", " · ← browser") : "");
540
452
  const right = theme.fg("muted", `↑${formatCount(input)} ↓${formatCount(output)}`);
@@ -547,6 +459,7 @@ export function updateWidget(
547
459
  mode: WidgetMode = "full",
548
460
  nerdFontIcons = false,
549
461
  rootTurnEnded = false,
462
+ loaderStyle: LoaderStyle = "circle",
550
463
  ): void {
551
464
  if (!ctx.hasUI) return;
552
465
  if (!threads.some((thread) => thread.path !== "/root")) {
@@ -560,7 +473,7 @@ export function updateWidget(
560
473
  if (ctx.mode === "rpc") {
561
474
  ctx.ui.setWidget(
562
475
  "pi-subagent",
563
- render(threads, 80, ctx.ui.theme, { showBrowserHint: false, nerdFontIcons, animate: false }),
476
+ render(threads, 80, ctx.ui.theme, { showBrowserHint: false, nerdFontIcons, loaderStyle, animate: false }),
564
477
  AGENT_WIDGET_PLACEMENT,
565
478
  );
566
479
  return;
@@ -578,6 +491,7 @@ export function updateWidget(
578
491
  render: (width) => render(snapshot, width, ctx.ui.theme, {
579
492
  showBrowserHint: !settled,
580
493
  nerdFontIcons,
494
+ loaderStyle,
581
495
  }),
582
496
  invalidate: () => {},
583
497
  dispose: () => {
@@ -1042,6 +956,7 @@ const EDIT_MENU_ACTIONS = [
1042
956
  "Edit frontmatter YAML",
1043
957
  "External editor (entire Markdown)",
1044
958
  "Save",
959
+ "Reset to bundled",
1045
960
  "Cancel",
1046
961
  ] as const;
1047
962
 
@@ -1066,6 +981,7 @@ const EDIT_FIELD_LABELS: Record<EditMenuAction, string> = {
1066
981
  "Edit frontmatter YAML": "Frontmatter YAML",
1067
982
  "External editor (entire Markdown)": "External editor",
1068
983
  Save: "Save",
984
+ "Reset to bundled": "Reset to bundled",
1069
985
  Cancel: "Cancel",
1070
986
  };
1071
987
 
@@ -1093,6 +1009,8 @@ const EDIT_FIELD_HELP: Record<EditMenuAction, string> = {
1093
1009
  "External editor (entire Markdown)":
1094
1010
  "Edit the complete definition using $VISUAL / $EDITOR.",
1095
1011
  Save: "Validate and save. Existing sessions keep their original configuration.",
1012
+ "Reset to bundled":
1013
+ "Delete this fork/override file and go back to the definition shipped with the extension. Unsaved edits are discarded.",
1096
1014
  Cancel: "Close without saving any edits.",
1097
1015
  };
1098
1016
 
@@ -1266,7 +1184,11 @@ async function editAgentTypesDialog(
1266
1184
  const field = await dialogMenu(
1267
1185
  ctx,
1268
1186
  `Edit ${sanitizeText(draft.name)} (unsaved)`,
1269
- EDIT_MENU_ACTIONS.map((action) => {
1187
+ EDIT_MENU_ACTIONS.filter(
1188
+ (action) =>
1189
+ action !== "Reset to bundled" ||
1190
+ (!isNew && !!original?.customization && !!original.baseSource),
1191
+ ).map((action) => {
1270
1192
  const decorated = editMenuLabel(action, draft);
1271
1193
  const separator = decorated.indexOf(": ");
1272
1194
  return {
@@ -1384,6 +1306,30 @@ async function editAgentTypesDialog(
1384
1306
  );
1385
1307
  break;
1386
1308
  }
1309
+ if (field === "Reset to bundled") {
1310
+ if (!original?.customization || !original.baseSource) continue;
1311
+ const { scope, filePath } = original.customization;
1312
+ const confirmed = await dialogMenu(
1313
+ ctx,
1314
+ `Reset ${sanitizeText(original.name)}?`,
1315
+ [
1316
+ {
1317
+ id: "reset",
1318
+ label: "Reset",
1319
+ help: `Deletes ${filePath} and restores the ${original.baseSource ?? "bundled"} definition.`,
1320
+ },
1321
+ { id: "keep", label: "Keep" },
1322
+ ],
1323
+ { selectedId: "keep" },
1324
+ );
1325
+ if (confirmed !== "reset") continue;
1326
+ store.removeCustomization(original.name, scope);
1327
+ ctx.ui.notify(
1328
+ `Reset ${sanitizeText(original.name)}: deleted ${sanitizeText(filePath)}; using the ${original.baseSource ?? "bundled"} definition.`,
1329
+ "info",
1330
+ );
1331
+ break;
1332
+ }
1387
1333
  if (field === "Save scope") {
1388
1334
  const scope = await chooseSaveScope(ctx, store, saveScope);
1389
1335
  if (scope) saveScope = scope;