pi-subagent-manager 0.8.0 → 0.9.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.
@@ -1,28 +1,41 @@
1
1
  import type {
2
2
  ExtensionCommandContext,
3
+ ExtensionContext,
4
+ ExtensionUIContext,
3
5
  Theme,
4
6
  } from "@earendil-works/pi-coding-agent";
5
- import { getKeybindings, Key, matchesKey } from "@earendil-works/pi-tui";
7
+ import {
8
+ getKeybindings,
9
+ setKeybindings,
10
+ Key,
11
+ matchesKey,
12
+ type Keybinding,
13
+ } from "@earendil-works/pi-tui";
6
14
  import {
7
15
  canOpenDialog,
8
16
  DIALOG_OPTIONS,
9
17
  type DialogHost,
18
+ DialogSession,
19
+ scopeDialogContext,
20
+ dialogMenu,
21
+ dialogEditor,
10
22
  dialogHeight,
11
23
  dialogText,
12
24
  frameDialog,
13
- withDialogSession,
14
25
  } from "./dialog.ts";
15
26
  import type { ThreadService } from "../types.ts";
16
27
  import { buildStatusTree, type StatusRow } from "./thread-tree.ts";
17
- import { showThreads, threadMetrics } from "./ui.ts";
28
+ import { agentTypeBadge, showThreads, threadMetrics } from "./ui.ts";
29
+ import { LiveAgentView, fillViewport, type AgentViewportState } from "./live-agent-view.ts";
18
30
 
19
31
  export { buildStatusTree, type StatusRow };
20
32
 
21
33
  const ROOT = "/root";
34
+ const INACTIVE_STATES = new Set(["paused", "stopped", "failed", "completed"]);
22
35
  const TITLE = "Agents status";
23
36
  const TREE_TITLE = "Agents tree";
24
37
  const FOOTER =
25
- "Esc close · ↑↓ select · ←→ fold · PgUp/PgDn · Enter inspect · r refresh";
38
+ "Esc close · ↑↓ select · ←→ fold · PgUp/PgDn · Enter inspect · r refresh · Ctrl+C stop all";
26
39
 
27
40
  function agentCount(threads: readonly { path?: string }[]): number {
28
41
  const paths = new Set<string>();
@@ -47,9 +60,7 @@ function treeParent(rows: StatusRow[], index: number): StatusRow | undefined {
47
60
 
48
61
  function firstChild(rows: StatusRow[], index: number): StatusRow | undefined {
49
62
  const next = rows[index + 1];
50
- return next && next.prefix.length > (rows[index]?.prefix.length ?? 0)
51
- ? next
52
- : undefined;
63
+ return next && next.prefix.length > (rows[index]?.prefix.length ?? 0) ? next : undefined;
53
64
  }
54
65
 
55
66
  function label(row: StatusRow): string {
@@ -62,9 +73,22 @@ function label(row: StatusRow): string {
62
73
  .join(" ");
63
74
  }
64
75
 
76
+ export interface AgentTreeState {
77
+ selectedPath: string;
78
+ collapsed: Set<string>;
79
+ }
80
+
65
81
  export class StatusDialog {
66
- private selectedPath: string;
67
- private collapsed = new Set<string>();
82
+ private state: AgentTreeState;
83
+ private get selectedPath(): string {
84
+ return this.state.selectedPath;
85
+ }
86
+ private set selectedPath(value: string) {
87
+ this.state.selectedPath = value;
88
+ }
89
+ private get collapsed(): Set<string> {
90
+ return this.state.collapsed;
91
+ }
68
92
  private viewport = 1;
69
93
  private timer: ReturnType<typeof setInterval> | undefined;
70
94
 
@@ -75,8 +99,13 @@ export class StatusDialog {
75
99
  private done: (path: string | undefined) => void,
76
100
  selected?: string,
77
101
  private title = TITLE,
102
+ private navigation?: {
103
+ state: AgentTreeState;
104
+ actions(path: string): void;
105
+ fullscreen?: boolean;
106
+ },
78
107
  ) {
79
- this.selectedPath = selected || ROOT;
108
+ this.state = navigation?.state ?? { selectedPath: selected || ROOT, collapsed: new Set() };
80
109
  }
81
110
 
82
111
  invalidate(): void {}
@@ -99,6 +128,22 @@ export class StatusDialog {
99
128
  this.timer = undefined;
100
129
  }
101
130
 
131
+ /** Stop every live agent. Stopping a subtree covers its descendants, so only top-most live paths are sent. */
132
+ private stopAll(): void {
133
+ const live = this.service
134
+ .list()
135
+ .filter((thread) => thread.path !== ROOT && (thread.state === "starting" || thread.state === "running"))
136
+ .map((thread) => thread.path);
137
+ const tops = live.filter((path) => !live.some((other) => path.startsWith(`${other}/`)));
138
+ for (const path of tops) {
139
+ void this.service
140
+ .stop(path)
141
+ .catch(() => {})
142
+ .finally(() => this.host.requestRender());
143
+ }
144
+ this.host.requestRender();
145
+ }
146
+
102
147
  private rows(): StatusRow[] {
103
148
  return buildStatusTree(this.service.list(), this.collapsed);
104
149
  }
@@ -118,6 +163,10 @@ export class StatusDialog {
118
163
 
119
164
  handleInput(data: string): void {
120
165
  const keys = getKeybindings();
166
+ if (matchesKey(data, Key.ctrl("c"))) {
167
+ this.stopAll();
168
+ return;
169
+ }
121
170
  if (keys.matches(data, "tui.select.cancel")) {
122
171
  this.done(undefined);
123
172
  return;
@@ -127,7 +176,16 @@ export class StatusDialog {
127
176
  const row = rows[index];
128
177
  if (row) this.selectedPath = row.path;
129
178
  if (keys.matches(data, "tui.select.confirm")) {
130
- if (row?.thread && row.path !== ROOT) this.done(row.path);
179
+ if (this.navigation && row?.path === ROOT) this.done(undefined);
180
+ else if (row?.thread && row.path !== ROOT) this.done(row.path);
181
+ return;
182
+ }
183
+ if (data === "i" && this.navigation) {
184
+ if (row?.thread && row.path !== ROOT) this.navigation.actions(row.path);
185
+ return;
186
+ }
187
+ if (matchesKey(data, Key.ctrl("q")) && this.navigation) {
188
+ this.done(undefined);
131
189
  return;
132
190
  }
133
191
  if (data === "r") {
@@ -135,15 +193,13 @@ export class StatusDialog {
135
193
  return;
136
194
  }
137
195
  if (matchesKey(data, Key.left)) {
138
- if (row?.hasChildren && !this.collapsed.has(row.path))
139
- this.collapsed.add(row.path);
196
+ if (row?.hasChildren && !this.collapsed.has(row.path)) this.collapsed.add(row.path);
140
197
  else if (row) {
141
198
  const parent = treeParent(rows, index);
142
199
  if (parent) this.selectedPath = parent.path;
143
200
  }
144
201
  } else if (matchesKey(data, Key.right)) {
145
- if (row?.hasChildren && this.collapsed.has(row.path))
146
- this.collapsed.delete(row.path);
202
+ if (row?.hasChildren && this.collapsed.has(row.path)) this.collapsed.delete(row.path);
147
203
  else {
148
204
  const child = row?.hasChildren ? firstChild(rows, index) : undefined;
149
205
  if (child) this.selectedPath = child.path;
@@ -158,41 +214,58 @@ export class StatusDialog {
158
214
  else if (matchesKey(data, Key.end)) next = Math.max(0, rows.length - 1);
159
215
  else return;
160
216
  this.selectedPath =
161
- rows[Math.max(0, Math.min(rows.length - 1, next))]?.path ??
162
- this.selectedPath;
217
+ rows[Math.max(0, Math.min(rows.length - 1, next))]?.path ?? this.selectedPath;
163
218
  }
164
219
  this.host.requestRender();
165
220
  }
166
221
 
167
222
  private line(row: StatusRow, selected: boolean): string {
168
- const marker = row.hasChildren
169
- ? this.collapsed.has(row.path)
170
- ? "▸ "
171
- : "▾ "
172
- : "";
173
- const text = ` ${row.prefix}${selected ? "›" : " "} ${marker}${label(row)}`;
174
- if (selected) return this.theme.fg("accent", text);
175
- if (row.thread?.state === "failed") return this.theme.fg("error", text);
176
- if (row.thread?.state === "paused") return this.theme.fg("warning", text);
177
- return text;
223
+ const marker = row.hasChildren ? (this.collapsed.has(row.path) ? "▸ " : "▾ ") : "";
224
+ const head = ` ${row.prefix}${selected ? "›" : " "} ${marker}`;
225
+ const thread = row.thread;
226
+ if (!thread) {
227
+ const text = `${head}${label(row)}`;
228
+ return selected ? this.theme.fg("accent", text) : text;
229
+ }
230
+ const inactive = INACTIVE_STATES.has(thread.state);
231
+ if (inactive) {
232
+ // Completed fades furthest (dim); the state word keeps a theme hint for done/failed.
233
+ const base = thread.state === "completed" ? "dim" : "muted";
234
+ const hint =
235
+ thread.state === "completed" ? "success" : thread.state === "failed" ? "error" : base;
236
+ const state = dialogText(thread.state);
237
+ const path = dialogText(thread.path);
238
+ const status = dialogText(thread.status);
239
+ return [
240
+ this.theme.fg(selected ? "accent" : base, head),
241
+ this.theme.fg(base, `${dialogText(thread.type)} ${path} `),
242
+ this.theme.fg(hint, state),
243
+ this.theme.fg(base, ` ${status}`),
244
+ ].join("");
245
+ }
246
+ const rest = [thread.path, thread.state, thread.status]
247
+ .map((part) => dialogText(part))
248
+ .join(" ");
249
+ if (selected)
250
+ return `${this.theme.fg("accent", head)}${agentTypeBadge(thread.type, thread.color, this.theme)} ${this.theme.fg("accent", rest)}`;
251
+ return `${head}${agentTypeBadge(thread.type, thread.color, this.theme)} ${rest}`;
178
252
  }
179
253
 
180
254
  private detail(row: StatusRow | undefined): string[] {
181
255
  if (!row?.thread) {
182
256
  return [
183
- ` ${row?.path === ROOT ? "Main Pi session" : "Missing parent"}`,
257
+ ` ${row?.path === ROOT ? (agentCount(this.service.list()) ? "Main Pi session" : "Main Pi session — No agents yet") : "Missing parent"}`,
184
258
  "",
185
259
  ];
186
260
  }
187
- return [
188
- ` task ${dialogText(row.thread.task)}`,
189
- ` ${threadMetrics(row.thread)}`,
190
- ];
261
+ return [` task ${dialogText(row.thread.task)}`, ` ${threadMetrics(row.thread)}`];
191
262
  }
192
263
 
193
264
  render(width: number): string[] {
194
265
  const rows = this.rows();
195
- const height = dialogHeight(this.host);
266
+ const height = this.navigation?.fullscreen
267
+ ? Math.max(1, this.host.terminal?.rows ?? 24)
268
+ : dialogHeight(this.host);
196
269
  const index = this.locate(rows);
197
270
  if (rows[index]) this.selectedPath = rows[index].path;
198
271
  const budget = Math.max(0, height - 4);
@@ -200,10 +273,7 @@ export class StatusDialog {
200
273
  const treeCount = Math.max(0, budget - detail.length);
201
274
  this.viewport = Math.max(1, treeCount);
202
275
  const start = treeCount
203
- ? Math.max(
204
- 0,
205
- Math.min(index - treeCount + 1, Math.max(0, rows.length - treeCount)),
206
- )
276
+ ? Math.max(0, Math.min(index - treeCount + 1, Math.max(0, rows.length - treeCount)))
207
277
  : 0;
208
278
  const body = [
209
279
  ...rows
@@ -217,7 +287,9 @@ export class StatusDialog {
217
287
  height,
218
288
  this.heading(rows, start, treeCount),
219
289
  body,
220
- FOOTER,
290
+ this.navigation
291
+ ? "Esc main · ↑↓ select · ←→ fold · i Actions · Ctrl+C stop all"
292
+ : FOOTER,
221
293
  );
222
294
  }
223
295
 
@@ -273,16 +345,177 @@ export async function showAgentStatus(
273
345
  await showAgentDialog(ctx, service, { inspect });
274
346
  }
275
347
 
348
+ /** Root-owned navigation state. Opening and closing never changes the executing session. */
349
+ export class AgentNavigationController {
350
+ private tree: AgentTreeState = { selectedPath: ROOT, collapsed: new Set() };
351
+ private viewports = new Map<string, AgentViewportState>();
352
+ private session: DialogSession | undefined;
353
+ private opening: Promise<void> | undefined;
354
+ private generation = 0;
355
+
356
+ get isOpen(): boolean {
357
+ return this.opening !== undefined;
358
+ }
359
+
360
+ close(): void {
361
+ ++this.generation;
362
+ this.session?.close();
363
+ this.session = undefined;
364
+ }
365
+
366
+ open(ctx: ExtensionContext, service: ThreadService, selectedPath?: string): Promise<void> {
367
+ if (this.opening) return this.opening;
368
+ if (!canOpenDialog(ctx)) return Promise.resolve();
369
+ if (selectedPath) this.tree.selectedPath = selectedPath;
370
+ const generation = ++this.generation;
371
+ let failure: unknown;
372
+ let failed = false;
373
+ let ownedSession: DialogSession | undefined;
374
+ const task = ctx.ui.custom<void>(
375
+ (host, theme, keys, done) => {
376
+ const session = new DialogSession(host, theme, keys, done);
377
+ ownedSession = session;
378
+ if (generation !== this.generation) {
379
+ void Promise.resolve().then(() => session.close());
380
+ return session;
381
+ }
382
+ this.session = session;
383
+ // The alt-screen renderer's listener runs before extension listeners. Temporarily
384
+ // remove only its search action from the public keybinding lookup, before dispatch.
385
+ const previousKeybindings = getKeybindings();
386
+ const watchingKeybindings = new Proxy(previousKeybindings, {
387
+ get(target, property) {
388
+ if (property === "matches")
389
+ return (data: string, action: Keybinding) =>
390
+ action === "tui.altScreen.search" ? false : target.matches(data, action);
391
+ // Preserve all other public manager methods and their original receiver.
392
+ const value = Reflect.get(target, property, target);
393
+ return typeof value === "function" ? value.bind(target) : value;
394
+ },
395
+ });
396
+ setKeybindings(watchingKeybindings);
397
+ const dispose = session.dispose.bind(session);
398
+ session.dispose = () => {
399
+ // Do not overwrite a newer keybinding owner installed by another extension.
400
+ if (getKeybindings() === watchingKeybindings) setKeybindings(previousKeybindings);
401
+ dispose();
402
+ };
403
+ // One fullscreen surface also covers shorter Actions dialogs without exposing main.
404
+ const render = session.render.bind(session);
405
+ session.render = (width) => fillViewport(render(width), width, host.terminal.rows);
406
+ const scoped = scopeDialogContext(ctx, session);
407
+ // Built-in UI dialogs otherwise stack independently. Mount these actions in our child slot.
408
+ const ui = scoped.ui as ExtensionUIContext;
409
+ ui.select = (title, options) =>
410
+ dialogMenu(
411
+ scoped,
412
+ title,
413
+ options.map((label) => ({ id: label, label })),
414
+ );
415
+ ui.confirm = async (title, message) =>
416
+ (await dialogMenu(
417
+ scoped,
418
+ title,
419
+ [
420
+ { id: "Yes", label: "Yes", help: message },
421
+ { id: "No", label: "No", help: message },
422
+ ],
423
+ { selectedId: "No" },
424
+ )) === "Yes";
425
+ ui.editor = (title, prefill) => dialogEditor(scoped, title, prefill ?? "");
426
+ // Defer until Pi has installed/focused the overlay; suppress opening-key repeats briefly.
427
+ const handoffUntil = Date.now() + 100;
428
+ const handle = session.handleInput.bind(session);
429
+ session.handleInput = (data) => {
430
+ if (Date.now() < handoffUntil && matchesKey(data, Key.down)) return;
431
+ handle(data);
432
+ };
433
+ void Promise.resolve()
434
+ .then(async () => {
435
+ while (generation === this.generation) {
436
+ let treeDialog: StatusDialog | undefined;
437
+ const chosen = await session.mount<
438
+ { kind: "watch" | "actions"; path: string } | undefined
439
+ >((tui, activeTheme, _keys, finish) => {
440
+ treeDialog = new StatusDialog(
441
+ tui,
442
+ activeTheme,
443
+ service,
444
+ (path) => finish(path ? { kind: "watch", path } : undefined),
445
+ undefined,
446
+ TREE_TITLE,
447
+ {
448
+ state: this.tree,
449
+ fullscreen: true,
450
+ actions: (path) => finish({ kind: "actions", path }),
451
+ },
452
+ );
453
+ treeDialog.startRefresh();
454
+ return treeDialog;
455
+ });
456
+ treeDialog?.dispose();
457
+ if (!chosen || generation !== this.generation) break;
458
+ if (chosen.kind === "actions") {
459
+ await showThreads(scoped, service, chosen.path);
460
+ continue;
461
+ }
462
+ let viewport = this.viewports.get(chosen.path);
463
+ if (!viewport) {
464
+ viewport = { scrollTop: 0, follow: true };
465
+ this.viewports.set(chosen.path, viewport);
466
+ }
467
+ const result = await session.mount<"back" | "main">(
468
+ (tui, activeTheme, _keys, finish) =>
469
+ new LiveAgentView(tui, activeTheme, service, chosen.path, viewport!, finish),
470
+ );
471
+ if (result !== "back") break;
472
+ }
473
+ })
474
+ .then(
475
+ () => session.close(),
476
+ (error: unknown) => {
477
+ failed = true;
478
+ failure = error;
479
+ ctx.ui.notify(
480
+ dialogText(error instanceof Error ? error.message : String(error)),
481
+ "error",
482
+ );
483
+ session.close();
484
+ },
485
+ );
486
+ return session;
487
+ },
488
+ {
489
+ overlay: true,
490
+ overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0, margin: 0 },
491
+ },
492
+ );
493
+ this.opening = task
494
+ .then(() => {
495
+ if (failed) throw failure;
496
+ })
497
+ .finally(() => {
498
+ // Also clean up if the host rejects mounting after our factory returned.
499
+ ownedSession?.dispose();
500
+ if (this.opening === result) this.opening = undefined;
501
+ if (generation === this.generation) this.session = undefined;
502
+ });
503
+ const result = this.opening;
504
+ return result;
505
+ }
506
+ }
507
+
508
+ const navigationByService = new WeakMap<ThreadService, AgentNavigationController>();
509
+
276
510
  export async function showAgentTree(
277
- ctx: ExtensionCommandContext,
511
+ ctx: ExtensionContext,
278
512
  service: ThreadService,
279
513
  selectedPath?: string,
280
514
  ): Promise<void> {
281
- if (!canOpenDialog(ctx)) return;
282
- await withDialogSession(ctx, (scoped) =>
283
- showAgentDialog(scoped, service, {
284
- title: TREE_TITLE,
285
- selected: selectedPath,
286
- }),
287
- );
515
+ let navigation = navigationByService.get(service);
516
+ if (!navigation) {
517
+ navigation = new AgentNavigationController();
518
+ navigationByService.set(service, navigation);
519
+ }
520
+ await navigation.open(ctx, service, selectedPath);
288
521
  }
package/src/ui/ui.ts CHANGED
@@ -48,7 +48,7 @@ import {
48
48
 
49
49
  export type ThreadController = Pick<
50
50
  ThreadService,
51
- "list" | "get" | "output" | "transcript" | "steer" | "stop"
51
+ "list" | "get" | "output" | "transcript" | "observeTranscript" | "steer" | "stop"
52
52
  >;
53
53
 
54
54
  /** Plain terminal-safe text: never pass agent-supplied terminal commands through. */
@@ -88,7 +88,7 @@ function contrastPill(
88
88
  });
89
89
  }
90
90
 
91
- function agentTypeBadge(
91
+ export function agentTypeBadge(
92
92
  type: string,
93
93
  color: string | undefined,
94
94
  theme: AgentBadgeTheme,
@@ -217,7 +217,7 @@ export function renderThreads(
217
217
  }
218
218
 
219
219
  const WIDGET_ROOT = "/root";
220
- const MAX_WIDGET_LINES = 10;
220
+ const MAX_WIDGET_LINES = 12;
221
221
  const AGENT_WIDGET_PLACEMENT = { placement: "aboveEditor" as const };
222
222
 
223
223
  function statePriority(state: ThreadView["state"] | undefined): number {
@@ -421,10 +421,13 @@ export function renderAgentTree(
421
421
  theme.fg("muted", `${live} live · ${paused} paused`),
422
422
  columns,
423
423
  );
424
- let visible = takeWidgetRows(rows, MAX_WIDGET_LINES - 1);
424
+ const help = ["Esc: abort main, not subagents"];
425
+ // Reserve help even when every agent fits; overflow must not push it out.
426
+ const rowBudget = MAX_WIDGET_LINES - 1 - help.length;
427
+ let visible = takeWidgetRows(rows, rowBudget);
425
428
  let omitted = agents.length - visible.filter((row) => row.thread).length;
426
429
  if (omitted > 0) {
427
- visible = takeWidgetRows(rows, MAX_WIDGET_LINES - 2);
430
+ visible = takeWidgetRows(rows, rowBudget - 1);
428
431
  omitted = agents.length - visible.filter((row) => row.thread).length;
429
432
  }
430
433
  const lines = [heading];
@@ -439,12 +442,15 @@ export function renderAgentTree(
439
442
  if (omitted > 0) {
440
443
  lines.push(
441
444
  truncateToWidth(
442
- theme.fg("muted", `+${omitted} more agents · /agents tree`),
445
+ theme.fg("muted", `+${omitted} more agents`),
443
446
  columns,
444
447
  "",
445
448
  ),
446
449
  );
447
450
  }
451
+ lines.push(
452
+ ...help.map((line) => truncateToWidth(theme.fg("muted", line), columns, "")),
453
+ );
448
454
  return lines;
449
455
  }
450
456
 
@@ -489,7 +495,7 @@ export function updateWidget(
489
495
  }
490
496
 
491
497
  export async function showThreads(
492
- ctx: ExtensionCommandContext,
498
+ ctx: ExtensionContext,
493
499
  controller: ThreadController,
494
500
  path?: string,
495
501
  ): Promise<void> {