pi-subagent-manager 1.10.0 → 1.12.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.
Files changed (95) hide show
  1. package/README.md +9 -9
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.js +790 -0
  4. package/dist/orch/checklist-integration.js +176 -0
  5. package/dist/orch/context-entries.js +6 -0
  6. package/dist/orch/cost-ledger.js +38 -0
  7. package/dist/orch/diagnostics.js +86 -0
  8. package/dist/orch/extensions.js +66 -0
  9. package/dist/orch/housekeeping-usage.js +22 -0
  10. package/dist/orch/housekeeping.js +248 -0
  11. package/dist/orch/inherited-tools.js +57 -0
  12. package/dist/orch/mailbox.js +195 -0
  13. package/dist/orch/manager.js +970 -0
  14. package/dist/orch/paths.js +69 -0
  15. package/dist/orch/prompt.js +30 -0
  16. package/dist/orch/registry.js +115 -0
  17. package/dist/orch/runtime.js +835 -0
  18. package/dist/orch/tools.js +112 -0
  19. package/dist/orch/transcript.js +165 -0
  20. package/dist/prefs/agent-import.js +188 -0
  21. package/dist/prefs/config.js +878 -0
  22. package/dist/prefs/import-discovery.js +547 -0
  23. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +0 -1
  24. package/dist/prefs/models.js +56 -0
  25. package/dist/prefs/settings.js +491 -0
  26. package/dist/types.js +1 -0
  27. package/dist/ui/agent-loader.js +63 -0
  28. package/dist/ui/agent-navigation-editor.js +168 -0
  29. package/dist/ui/cost-footer.js +209 -0
  30. package/dist/ui/dialog.js +505 -0
  31. package/dist/ui/import-picker.js +191 -0
  32. package/dist/ui/live-agent-view.js +527 -0
  33. package/dist/ui/model-picker.js +529 -0
  34. package/dist/ui/settings-ui.js +671 -0
  35. package/dist/ui/status-ui.js +470 -0
  36. package/dist/ui/thread-tree.js +142 -0
  37. package/dist/ui/tool-picker.js +331 -0
  38. package/dist/ui/transcript-tool.js +91 -0
  39. package/dist/ui/ui.js +1019 -0
  40. package/package.json +17 -5
  41. package/docs/assets/subagent-manager-demo.gif +0 -0
  42. package/docs/async-lifecycle.md +0 -153
  43. package/docs/custom-agents.md +0 -154
  44. package/docs/default-agents.md +0 -95
  45. package/docs/demo.md +0 -63
  46. package/docs/development.md +0 -74
  47. package/docs/importing-agents.md +0 -41
  48. package/docs/pi-footer.md +0 -128
  49. package/docs/research-claude.md +0 -258
  50. package/docs/research-codex.md +0 -143
  51. package/docs/research-default-agent-models.md +0 -121
  52. package/docs/research-model-audit-2026-10.md +0 -154
  53. package/docs/research-model-roles-coding.md +0 -99
  54. package/docs/research-model-roles-writing.md +0 -78
  55. package/docs/research-researcher-workflow.md +0 -97
  56. package/docs/settings.md +0 -293
  57. package/docs/subagent-extension-limitations.md +0 -98
  58. package/docs/threads.md +0 -73
  59. package/docs/tools-and-ui.md +0 -129
  60. package/src/index.ts +0 -920
  61. package/src/orch/checklist-integration.ts +0 -230
  62. package/src/orch/context-entries.ts +0 -15
  63. package/src/orch/cost-ledger.ts +0 -56
  64. package/src/orch/diagnostics.ts +0 -95
  65. package/src/orch/extensions.ts +0 -83
  66. package/src/orch/housekeeping-usage.ts +0 -47
  67. package/src/orch/housekeeping.ts +0 -348
  68. package/src/orch/inherited-tools.ts +0 -84
  69. package/src/orch/mailbox.ts +0 -261
  70. package/src/orch/manager.ts +0 -1084
  71. package/src/orch/paths.ts +0 -73
  72. package/src/orch/prompt.ts +0 -39
  73. package/src/orch/registry.ts +0 -168
  74. package/src/orch/runtime.ts +0 -1041
  75. package/src/orch/tools.ts +0 -190
  76. package/src/orch/transcript.ts +0 -186
  77. package/src/prefs/agent-import.ts +0 -245
  78. package/src/prefs/config.ts +0 -1017
  79. package/src/prefs/import-discovery.ts +0 -643
  80. package/src/prefs/models.ts +0 -74
  81. package/src/prefs/settings.ts +0 -614
  82. package/src/types.ts +0 -271
  83. package/src/ui/agent-loader.ts +0 -98
  84. package/src/ui/agent-navigation-editor.ts +0 -233
  85. package/src/ui/cost-footer.ts +0 -230
  86. package/src/ui/dialog.ts +0 -678
  87. package/src/ui/import-picker.ts +0 -231
  88. package/src/ui/live-agent-view.ts +0 -600
  89. package/src/ui/model-picker.ts +0 -701
  90. package/src/ui/settings-ui.ts +0 -830
  91. package/src/ui/status-ui.ts +0 -628
  92. package/src/ui/thread-tree.ts +0 -173
  93. package/src/ui/tool-picker.ts +0 -398
  94. package/src/ui/transcript-tool.ts +0 -142
  95. package/src/ui/ui.ts +0 -1407
@@ -0,0 +1,470 @@
1
+ import { getKeybindings, setKeybindings, Key, matchesKey, } from "@earendil-works/pi-tui";
2
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { canOpenDialog, DIALOG_OPTIONS, DialogSession, scopeDialogContext, dialogMenu, dialogEditor, dialogHeight, dialogText, frameDialog, } from "./dialog.js";
4
+ import { buildStatusTree, threadActivity } from "./thread-tree.js";
5
+ import { AGENT_PROGRESS_INTERVAL, agentProgressIcon, agentTypeBadge, agentTypeLabel, showThreads, threadMetrics, } from "./ui.js";
6
+ import { LiveAgentView, fillViewport } from "./live-agent-view.js";
7
+ export { buildStatusTree };
8
+ const ROOT = "/root";
9
+ const INACTIVE_STATES = new Set(["paused", "stopped", "failed", "completed"]);
10
+ const TITLE = "Agents status";
11
+ const TREE_TITLE = "Agents tree";
12
+ const FOOTER = "Esc close · ↑↓ select · ←→ fold · PgUp/PgDn · Enter inspect · r refresh · Ctrl+C stop all";
13
+ function agentCount(threads) {
14
+ const paths = new Set();
15
+ for (const thread of threads) {
16
+ if (thread?.path && thread.path !== ROOT)
17
+ paths.add(thread.path);
18
+ }
19
+ return paths.size;
20
+ }
21
+ function lexicalParent(path) {
22
+ const index = path.lastIndexOf("/");
23
+ return index > 0 ? path.slice(0, index) : null;
24
+ }
25
+ function treeParent(rows, index) {
26
+ const depth = rows[index]?.prefix.length ?? 0;
27
+ for (let cursor = index - 1; cursor >= 0; cursor--) {
28
+ if (rows[cursor].prefix.length < depth)
29
+ return rows[cursor];
30
+ }
31
+ return undefined;
32
+ }
33
+ function firstChild(rows, index) {
34
+ const next = rows[index + 1];
35
+ return next && next.prefix.length > (rows[index]?.prefix.length ?? 0) ? next : undefined;
36
+ }
37
+ function label(row) {
38
+ if (!row.thread)
39
+ return row.path === ROOT
40
+ ? `${dialogText(row.path)} main running main`
41
+ : `${dialogText(row.path)} missing parent`;
42
+ return [row.path, row.thread.type, row.thread.state, row.thread.status]
43
+ .map((part) => dialogText(part))
44
+ .join(" ");
45
+ }
46
+ export class StatusDialog {
47
+ host;
48
+ theme;
49
+ service;
50
+ done;
51
+ title;
52
+ navigation;
53
+ nerdFontIcons;
54
+ loaderStyle;
55
+ state;
56
+ get selectedPath() {
57
+ return this.state.selectedPath;
58
+ }
59
+ set selectedPath(value) {
60
+ this.state.selectedPath = value;
61
+ }
62
+ get collapsed() {
63
+ return this.state.collapsed;
64
+ }
65
+ viewport = 1;
66
+ timer;
67
+ refreshDelay = 0;
68
+ refreshing = false;
69
+ constructor(host, theme, service, done, selected, title = TITLE, navigation, nerdFontIcons = false, loaderStyle = "circle") {
70
+ this.host = host;
71
+ this.theme = theme;
72
+ this.service = service;
73
+ this.done = done;
74
+ this.title = title;
75
+ this.navigation = navigation;
76
+ this.nerdFontIcons = nerdFontIcons;
77
+ this.loaderStyle = loaderStyle;
78
+ this.state = navigation?.state ?? { selectedPath: selected || ROOT, collapsed: new Set() };
79
+ }
80
+ invalidate() { }
81
+ startRefresh() {
82
+ this.stopRefresh();
83
+ this.refreshing = true;
84
+ this.syncRefresh();
85
+ }
86
+ dispose() {
87
+ this.refreshing = false;
88
+ this.stopRefresh();
89
+ }
90
+ syncRefresh() {
91
+ if (!this.refreshing)
92
+ return;
93
+ const delay = this.service
94
+ .list()
95
+ .some((thread) => thread.path !== ROOT && (thread.state === "starting" || thread.state === "running"))
96
+ ? AGENT_PROGRESS_INTERVAL
97
+ : 1000;
98
+ if (this.timer !== undefined && this.refreshDelay === delay)
99
+ return;
100
+ this.stopRefresh();
101
+ this.refreshDelay = delay;
102
+ this.timer = setInterval(() => {
103
+ this.syncRefresh();
104
+ this.host.requestRender();
105
+ }, delay);
106
+ if (typeof this.timer.unref === "function")
107
+ this.timer.unref();
108
+ }
109
+ stopRefresh() {
110
+ if (this.timer === undefined)
111
+ return;
112
+ clearInterval(this.timer);
113
+ this.timer = undefined;
114
+ this.refreshDelay = 0;
115
+ }
116
+ stopAll() {
117
+ const live = this.service
118
+ .list()
119
+ .filter((thread) => thread.path !== ROOT && (thread.state === "starting" || thread.state === "running"))
120
+ .map((thread) => thread.path);
121
+ const tops = live.filter((path) => !live.some((other) => path.startsWith(`${other}/`)));
122
+ for (const path of tops) {
123
+ void this.service
124
+ .stop(path)
125
+ .catch(() => { })
126
+ .finally(() => this.host.requestRender());
127
+ }
128
+ this.host.requestRender();
129
+ }
130
+ rows() {
131
+ return buildStatusTree(this.service.list(), this.collapsed);
132
+ }
133
+ locate(rows) {
134
+ const exact = rows.findIndex((row) => row.path === this.selectedPath);
135
+ if (exact >= 0)
136
+ return exact;
137
+ let parent = lexicalParent(this.selectedPath);
138
+ while (parent) {
139
+ const index = rows.findIndex((row) => row.path === parent);
140
+ if (index >= 0)
141
+ return index;
142
+ parent = lexicalParent(parent);
143
+ }
144
+ const root = rows.findIndex((row) => row.path === ROOT);
145
+ return root >= 0 ? root : 0;
146
+ }
147
+ handleInput(data) {
148
+ const keys = getKeybindings();
149
+ if (matchesKey(data, Key.ctrl("c"))) {
150
+ this.stopAll();
151
+ return;
152
+ }
153
+ if (keys.matches(data, "tui.select.cancel")) {
154
+ this.done(undefined);
155
+ return;
156
+ }
157
+ const rows = this.rows();
158
+ const index = this.locate(rows);
159
+ const row = rows[index];
160
+ if (row)
161
+ this.selectedPath = row.path;
162
+ if (keys.matches(data, "tui.select.confirm")) {
163
+ if (this.navigation && row?.path === ROOT)
164
+ this.done(undefined);
165
+ else if (row?.thread && row.path !== ROOT)
166
+ this.done(row.path);
167
+ return;
168
+ }
169
+ if (data === "i" && this.navigation) {
170
+ if (row?.thread && row.path !== ROOT)
171
+ this.navigation.actions(row.path);
172
+ return;
173
+ }
174
+ if (matchesKey(data, Key.ctrl("q")) && this.navigation) {
175
+ this.done(undefined);
176
+ return;
177
+ }
178
+ if (data === "r") {
179
+ this.host.requestRender();
180
+ return;
181
+ }
182
+ if (matchesKey(data, Key.left)) {
183
+ if (row?.hasChildren && !this.collapsed.has(row.path))
184
+ this.collapsed.add(row.path);
185
+ else if (row) {
186
+ const parent = treeParent(rows, index);
187
+ if (parent)
188
+ this.selectedPath = parent.path;
189
+ }
190
+ }
191
+ else if (matchesKey(data, Key.right)) {
192
+ if (row?.hasChildren && this.collapsed.has(row.path))
193
+ this.collapsed.delete(row.path);
194
+ else {
195
+ const child = row?.hasChildren ? firstChild(rows, index) : undefined;
196
+ if (child)
197
+ this.selectedPath = child.path;
198
+ else if (this.navigation?.fullscreen) {
199
+ this.navigation.returnToWidget?.();
200
+ this.done(undefined);
201
+ return;
202
+ }
203
+ }
204
+ }
205
+ else {
206
+ let next = index;
207
+ if (keys.matches(data, "tui.select.up"))
208
+ next -= 1;
209
+ else if (keys.matches(data, "tui.select.down"))
210
+ next += 1;
211
+ else if (matchesKey(data, Key.pageUp))
212
+ next -= this.viewport;
213
+ else if (matchesKey(data, Key.pageDown))
214
+ next += this.viewport;
215
+ else if (matchesKey(data, Key.home))
216
+ next = 0;
217
+ else if (matchesKey(data, Key.end))
218
+ next = Math.max(0, rows.length - 1);
219
+ else
220
+ return;
221
+ this.selectedPath =
222
+ rows[Math.max(0, Math.min(rows.length - 1, next))]?.path ?? this.selectedPath;
223
+ }
224
+ this.host.requestRender();
225
+ }
226
+ line(row, selected, width) {
227
+ const marker = row.hasChildren ? (this.collapsed.has(row.path) ? "▸ " : "▾ ") : "";
228
+ const head = ` ${row.prefix}${selected ? "›" : " "} ${marker}`;
229
+ const thread = row.thread;
230
+ if (!thread) {
231
+ const text = `${head}${label(row)}`;
232
+ return [selected ? this.theme.fg("accent", text) : text, ""];
233
+ }
234
+ const inactive = INACTIVE_STATES.has(thread.state);
235
+ const base = thread.state === "completed" ? "dim" : "muted";
236
+ const hint = thread.state === "completed" ? "success" : thread.state === "failed" ? "error" : base;
237
+ const progress = agentProgressIcon(thread, this.nerdFontIcons, Date.now(), true, this.loaderStyle);
238
+ const badge = inactive
239
+ ? this.theme.fg(base, agentTypeLabel(thread.type, thread.icon, this.nerdFontIcons, progress))
240
+ : agentTypeBadge(thread.type, thread.color, this.theme, thread.icon, this.nerdFontIcons, progress);
241
+ const identity = [
242
+ thread.path,
243
+ `${thread.model ?? "model pending"}${thread.thinkingLevel ? `:${thread.thinkingLevel}` : ""}`,
244
+ ]
245
+ .map((part) => dialogText(part))
246
+ .join(" ");
247
+ const identityLine = [
248
+ selected ? this.theme.fg("accent", head) : head,
249
+ badge,
250
+ this.theme.fg(inactive ? base : selected ? "accent" : "text", ` ${identity} `),
251
+ this.theme.fg(inactive ? hint : "muted", dialogText(thread.state)),
252
+ ].join("");
253
+ const stem = row.prefix.replace("├ ", "│ ").replace("└ ", " ");
254
+ const activity = ` ${stem} ${dialogText(threadActivity(thread))}`;
255
+ const metrics = this.theme.fg(base, threadMetrics(thread));
256
+ const metricWidth = visibleWidth(metrics);
257
+ const first = metricWidth >= width
258
+ ? truncateToWidth(metrics, width, "")
259
+ : (() => {
260
+ const left = truncateToWidth(identityLine, width - metricWidth - 1);
261
+ return (left + " ".repeat(Math.max(1, width - visibleWidth(left) - metricWidth)) + metrics);
262
+ })();
263
+ const second = truncateToWidth(this.theme.fg(inactive ? base : selected ? "accent" : "muted", activity), width);
264
+ return [first, second];
265
+ }
266
+ detail(row) {
267
+ if (!row?.thread) {
268
+ return [
269
+ ` ${row?.path === ROOT ? (agentCount(this.service.list()) ? "Main Pi session" : "Main Pi session — No agents yet") : "Missing parent"}`,
270
+ "",
271
+ ];
272
+ }
273
+ return [` task ${dialogText(row.thread.task)}`, ` ${threadMetrics(row.thread)}`];
274
+ }
275
+ render(width) {
276
+ this.syncRefresh();
277
+ const rows = this.rows();
278
+ const height = this.navigation?.fullscreen
279
+ ? Math.max(1, this.host.terminal?.rows ?? 24)
280
+ : dialogHeight(this.host);
281
+ const index = this.locate(rows);
282
+ if (rows[index])
283
+ this.selectedPath = rows[index].path;
284
+ const budget = Math.max(0, height - 4);
285
+ const detail = budget > 2 ? this.detail(rows[index]) : [];
286
+ const treeCount = Math.max(0, Math.floor((budget - detail.length) / 2));
287
+ this.viewport = Math.max(1, treeCount);
288
+ const start = treeCount
289
+ ? Math.max(0, Math.min(index - treeCount + 1, Math.max(0, rows.length - treeCount)))
290
+ : 0;
291
+ const body = [
292
+ ...rows
293
+ .slice(start, start + treeCount)
294
+ .flatMap((row) => this.line(row, row.path === this.selectedPath, Math.max(0, width - 2))),
295
+ ...detail,
296
+ ];
297
+ return frameDialog(this.theme, width, height, this.heading(rows, start, treeCount), body, this.navigation
298
+ ? "Esc main · ↑↓ select · ←→ fold · → widget · i Actions · Ctrl+C stop all"
299
+ : FOOTER);
300
+ }
301
+ heading(rows, start, treeCount) {
302
+ if (this.title !== TREE_TITLE)
303
+ return this.title;
304
+ const agents = agentCount(this.service.list());
305
+ const noun = agents === 1 ? "agent" : "agents";
306
+ const total = rows.length;
307
+ const shown = Math.max(0, Math.min(treeCount, total - start));
308
+ if (shown <= 0)
309
+ return `${TREE_TITLE} ${agents} ${noun}`;
310
+ return `${TREE_TITLE} ${agents} ${noun} ${start + 1}-${start + shown}/${total}`;
311
+ }
312
+ }
313
+ async function showAgentDialog(ctx, service, options = {}) {
314
+ const open = options.inspect ?? ((path) => showThreads(ctx, service, path));
315
+ let selected = options.selected;
316
+ for (;;) {
317
+ let dialog;
318
+ try {
319
+ const chosen = await ctx.ui.custom((host, theme, _keys, done) => {
320
+ dialog = new StatusDialog(host, theme, service, done, selected, options.title, undefined, options.nerdFontIcons, options.loaderStyle);
321
+ dialog.startRefresh();
322
+ return dialog;
323
+ }, DIALOG_OPTIONS);
324
+ dialog?.dispose();
325
+ dialog = undefined;
326
+ if (!chosen)
327
+ return;
328
+ selected = chosen;
329
+ await open(chosen);
330
+ }
331
+ finally {
332
+ dialog?.dispose();
333
+ }
334
+ }
335
+ }
336
+ export async function showAgentStatus(ctx, service, inspect, nerdFontIcons = false, loaderStyle = "circle") {
337
+ if (!canOpenDialog(ctx))
338
+ return;
339
+ await showAgentDialog(ctx, service, { inspect, nerdFontIcons, loaderStyle });
340
+ }
341
+ export class AgentNavigationController {
342
+ returnToWidget;
343
+ tree = { selectedPath: ROOT, collapsed: new Set() };
344
+ viewports = new Map();
345
+ session;
346
+ opening;
347
+ generation = 0;
348
+ constructor(returnToWidget) {
349
+ this.returnToWidget = returnToWidget;
350
+ }
351
+ get isOpen() {
352
+ return this.opening !== undefined;
353
+ }
354
+ close() {
355
+ ++this.generation;
356
+ this.session?.close();
357
+ this.session = undefined;
358
+ }
359
+ open(ctx, service, selectedPath, nerdFontIcons = false, loaderStyle = "circle") {
360
+ if (this.opening)
361
+ return this.opening;
362
+ if (!canOpenDialog(ctx))
363
+ return Promise.resolve();
364
+ if (selectedPath)
365
+ this.tree.selectedPath = selectedPath;
366
+ const generation = ++this.generation;
367
+ let failure;
368
+ let failed = false;
369
+ let ownedSession;
370
+ const task = ctx.ui.custom((host, theme, keys, done) => {
371
+ const session = new DialogSession(host, theme, keys, done);
372
+ ownedSession = session;
373
+ if (generation !== this.generation) {
374
+ void Promise.resolve().then(() => session.close());
375
+ return session;
376
+ }
377
+ this.session = session;
378
+ const previousKeybindings = getKeybindings();
379
+ const watchingKeybindings = new Proxy(previousKeybindings, {
380
+ get(target, property) {
381
+ if (property === "matches")
382
+ return (data, action) => action === "tui.altScreen.search" ? false : target.matches(data, action);
383
+ const value = Reflect.get(target, property, target);
384
+ return typeof value === "function" ? value.bind(target) : value;
385
+ },
386
+ });
387
+ setKeybindings(watchingKeybindings);
388
+ const dispose = session.dispose.bind(session);
389
+ session.dispose = () => {
390
+ if (getKeybindings() === watchingKeybindings)
391
+ setKeybindings(previousKeybindings);
392
+ dispose();
393
+ };
394
+ const render = session.render.bind(session);
395
+ session.render = (width) => fillViewport(render(width), width, host.terminal.rows);
396
+ const scoped = scopeDialogContext(ctx, session);
397
+ const ui = scoped.ui;
398
+ ui.select = (title, options) => dialogMenu(scoped, title, options.map((label) => ({ id: label, label })));
399
+ ui.confirm = async (title, message) => (await dialogMenu(scoped, title, [
400
+ { id: "Yes", label: "Yes", help: message },
401
+ { id: "No", label: "No", help: message },
402
+ ], { selectedId: "No" })) === "Yes";
403
+ ui.editor = (title, prefill) => dialogEditor(scoped, title, prefill ?? "");
404
+ void Promise.resolve()
405
+ .then(async () => {
406
+ while (generation === this.generation) {
407
+ let treeDialog;
408
+ const chosen = await session.mount((tui, activeTheme, _keys, finish) => {
409
+ treeDialog = new StatusDialog(tui, activeTheme, service, (path) => finish(path ? { kind: "watch", path } : undefined), undefined, TREE_TITLE, {
410
+ state: this.tree,
411
+ fullscreen: true,
412
+ returnToWidget: this.returnToWidget,
413
+ actions: (path) => finish({ kind: "actions", path }),
414
+ }, nerdFontIcons, loaderStyle);
415
+ treeDialog.startRefresh();
416
+ return treeDialog;
417
+ });
418
+ treeDialog?.dispose();
419
+ if (!chosen || generation !== this.generation)
420
+ break;
421
+ if (chosen.kind === "actions") {
422
+ await showThreads(scoped, service, chosen.path);
423
+ continue;
424
+ }
425
+ let viewport = this.viewports.get(chosen.path);
426
+ if (!viewport) {
427
+ viewport = { scrollTop: 0, follow: true };
428
+ this.viewports.set(chosen.path, viewport);
429
+ }
430
+ const result = await session.mount((tui, activeTheme, _keys, finish) => new LiveAgentView(tui, activeTheme, service, chosen.path, viewport, finish, nerdFontIcons, loaderStyle));
431
+ if (result !== "back")
432
+ break;
433
+ }
434
+ })
435
+ .then(() => session.close(), (error) => {
436
+ failed = true;
437
+ failure = error;
438
+ ctx.ui.notify(dialogText(error instanceof Error ? error.message : String(error)), "error");
439
+ session.close();
440
+ });
441
+ return session;
442
+ }, {
443
+ overlay: true,
444
+ overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0, margin: 0 },
445
+ });
446
+ this.opening = task
447
+ .then(() => {
448
+ if (failed)
449
+ throw failure;
450
+ })
451
+ .finally(() => {
452
+ ownedSession?.dispose();
453
+ if (this.opening === result)
454
+ this.opening = undefined;
455
+ if (generation === this.generation)
456
+ this.session = undefined;
457
+ });
458
+ const result = this.opening;
459
+ return result;
460
+ }
461
+ }
462
+ const navigationByService = new WeakMap();
463
+ export async function showAgentTree(ctx, service, selectedPath, nerdFontIcons = false, loaderStyle = "circle") {
464
+ let navigation = navigationByService.get(service);
465
+ if (!navigation) {
466
+ navigation = new AgentNavigationController();
467
+ navigationByService.set(service, navigation);
468
+ }
469
+ await navigation.open(ctx, service, selectedPath, nerdFontIcons, loaderStyle);
470
+ }
@@ -0,0 +1,142 @@
1
+ const ROOT = "/root";
2
+ export function threadActivity(thread, fallback = thread.status || thread.task) {
3
+ const active = thread.state === "starting" || thread.state === "running";
4
+ const summary = typeof thread.summary === "string" ? thread.summary.trim() : "";
5
+ return (active && summary) || fallback;
6
+ }
7
+ function lexicalParent(path) {
8
+ const index = path.lastIndexOf("/");
9
+ return index > 0 ? path.slice(0, index) : null;
10
+ }
11
+ function comparePath(a, b) {
12
+ return a < b ? -1 : a > b ? 1 : 0;
13
+ }
14
+ function chainHas(parentOf, start, target) {
15
+ const seen = new Set();
16
+ let current = start;
17
+ while (current) {
18
+ if (current === target || seen.has(current))
19
+ return true;
20
+ seen.add(current);
21
+ current = parentOf.get(current) ?? null;
22
+ }
23
+ return false;
24
+ }
25
+ export function lastStarted(thread) {
26
+ const value = thread?.lastStartedAt ?? thread?.createdAt;
27
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
28
+ }
29
+ function recencyComparator(threads) {
30
+ const byPath = new Map();
31
+ for (const thread of threads) {
32
+ if (thread?.path && !byPath.has(thread.path))
33
+ byPath.set(thread.path, thread);
34
+ }
35
+ const latest = new Map();
36
+ for (const thread of byPath.values()) {
37
+ const time = lastStarted(thread);
38
+ const seen = new Set();
39
+ let current = thread.path;
40
+ while (current && !seen.has(current)) {
41
+ seen.add(current);
42
+ latest.set(current, Math.max(latest.get(current) ?? 0, time));
43
+ const view = byPath.get(current);
44
+ current = view
45
+ ? view.parent && view.parent !== current
46
+ ? view.parent
47
+ : null
48
+ : lexicalParent(current);
49
+ }
50
+ }
51
+ return (a, b) => (latest.get(b) ?? 0) - (latest.get(a) ?? 0) || comparePath(a, b);
52
+ }
53
+ export function buildStatusTree(threads, collapsed, comparePaths = recencyComparator(threads)) {
54
+ const threadsByPath = new Map();
55
+ for (const thread of threads) {
56
+ if (thread?.path && !threadsByPath.has(thread.path))
57
+ threadsByPath.set(thread.path, thread);
58
+ }
59
+ const nodes = new Map();
60
+ const parentOf = new Map();
61
+ const nodeFor = (path) => {
62
+ let node = nodes.get(path);
63
+ if (!node) {
64
+ node = { path, thread: threadsByPath.get(path), children: [] };
65
+ nodes.set(path, node);
66
+ }
67
+ return node;
68
+ };
69
+ const declaredParent = (path) => {
70
+ if (path === ROOT)
71
+ return null;
72
+ const thread = threadsByPath.get(path);
73
+ if (thread)
74
+ return thread.parent && thread.parent !== path ? thread.parent : null;
75
+ return lexicalParent(path);
76
+ };
77
+ const ensure = (path, seen = new Set()) => {
78
+ if (!path || seen.has(path))
79
+ return;
80
+ seen.add(path);
81
+ nodeFor(path);
82
+ if (parentOf.has(path))
83
+ return;
84
+ const parent = declaredParent(path);
85
+ parentOf.set(path, parent);
86
+ if (parent)
87
+ ensure(parent, seen);
88
+ };
89
+ ensure(ROOT);
90
+ for (const path of threadsByPath.keys())
91
+ ensure(path);
92
+ const linked = new Set();
93
+ for (const path of [...parentOf.keys()].sort(comparePath)) {
94
+ const parent = parentOf.get(path);
95
+ if (!parent || parent === path)
96
+ continue;
97
+ if (chainHas(parentOf, parent, path)) {
98
+ parentOf.set(path, null);
99
+ continue;
100
+ }
101
+ const parentNode = nodeFor(parent);
102
+ const child = nodeFor(path);
103
+ if (!parentNode.children.includes(child))
104
+ parentNode.children.push(child);
105
+ linked.add(path);
106
+ }
107
+ const rows = [];
108
+ const visited = new Set();
109
+ const conceal = (node) => {
110
+ for (const child of node.children) {
111
+ if (visited.has(child.path))
112
+ continue;
113
+ visited.add(child.path);
114
+ conceal(child);
115
+ }
116
+ };
117
+ const walk = (list, ancestors, top) => {
118
+ const ordered = [...list]
119
+ .filter((node) => !visited.has(node.path))
120
+ .sort((a, b) => comparePaths(a.path, b.path));
121
+ for (const [index, node] of ordered.entries()) {
122
+ visited.add(node.path);
123
+ const last = index === ordered.length - 1;
124
+ const stem = ancestors.map((isLast) => (isLast ? " " : "│ ")).join("");
125
+ rows.push({
126
+ path: node.path,
127
+ prefix: stem + (top ? "" : last ? "└ " : "├ "),
128
+ hasChildren: node.children.length > 0,
129
+ ...(node.thread ? { thread: node.thread } : {}),
130
+ });
131
+ if (collapsed.has(node.path))
132
+ conceal(node);
133
+ else if (node.children.length > 0)
134
+ walk(node.children, top ? [] : [...ancestors, last], false);
135
+ }
136
+ };
137
+ walk([...nodes.values()].filter((node) => !linked.has(node.path)), [], true);
138
+ const missed = [...nodes.values()].filter((node) => !visited.has(node.path));
139
+ if (missed.length)
140
+ walk(missed, [], true);
141
+ return rows;
142
+ }