@henryqw/pi-subagent 28.1.0 → 28.2.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/README.md CHANGED
@@ -150,13 +150,27 @@ Staging, validation, and promotion require clean, unchanged Main. After a defini
150
150
 
151
151
  ### Inspect work
152
152
 
153
- Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history.
153
+ Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows have **Direct**, **Isolated**, and **Orphaned · parent checkout removed** group labels. On a wide terminal, each row shows its group beside its reference and status. Group headings are not actions. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history.
154
154
 
155
- In the terminal, the menu replaces the editor and uses at most half the terminal height. It does not overlay the report or the transcript. While the menu waits for your selection, Pi reports that it needs user input. Key hints use Pi's configured bindings.
155
+ In the terminal, Pi's native input and selection list replace the editor and use at most half the terminal height. The menu does not cover the report or the transcript.
156
156
 
157
- Move through rows with the mouse wheel. Click a row to select it. You can also use the keyboard.
157
+ The selected row has an arrow. A detail preview wraps the selected row's context when space permits. Narrow terminals keep the reference and status before the goal. Very short terminals hide the search field, preview, or extra hints. While the menu waits for your selection, Pi reports that it needs user input.
158
158
 
159
- Each row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed. Terminal requests stay hidden until you select **Completed / history**; this filter deletes no records. `/subagent` reports show as transcript entries that the model does not get.
159
+ Type to filter the current menu by reference, record identifier, Role, name, or status. Search includes details that do not fit in a row. The menu shows the number of matching rows and the total row count, including actions. Search changes no records. The menu keeps the filter and selected record when you return from details. Select **Refresh** to load current status; search and navigation use the loaded inventory only.
160
+
161
+ | Default key | Action |
162
+ | --- | --- |
163
+ | `Up` / `Down` | Move to another row. |
164
+ | `PageUp` / `PageDown` | Move one page within the list, not the transcript. |
165
+ | `Enter` | Select a row or toggle it in a multiple-selection menu. |
166
+ | `Ctrl+U` | Clear the filter and show all rows. |
167
+ | `Escape` | Cancel the menu without selecting a row. |
168
+
169
+ Key hints show Pi's configured bindings. In fullscreen mode, move through rows with the mouse wheel and click a row to select it. In regular mode, use the keyboard; the terminal owns mouse input.
170
+
171
+ Each work row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed. Status text stays beside the reference; color is not required. Terminal requests stay hidden until you select **Completed / history**; this filter deletes no records. `/subagent` reports show as transcript entries that the model does not get.
172
+
173
+ **Select multiple…** and prune review keep the filter after each toggle. The title shows the selected count, including selected rows hidden by the filter. Search does not select or clear rows. Clear the filter to reach **Select all**, **Clear**, or **Continue**. **Select all** selects every offered row, not only matches. **Continue** uses the selected rows; cancellation returns no selection.
160
174
 
161
175
  Every isolated request, including an orphaned request, has **Close and delete worktrees (discard work)**. Select it to review owned resources and confirm deletion. **This permanently deletes committed, uncommitted, and ignored content in the listed checkouts.** Cancel makes no change, and agents and tools cannot trigger this action. **Select multiple…** applies one action to many rows, with one confirmation. See [Close and delete isolated worktrees](./docs/orchestration.md#close-and-delete-isolated-worktrees) for guards and partial cleanup.
162
176
 
@@ -1,5 +1,5 @@
1
1
  import { getMarkdownTheme, getSelectListTheme, rawKeyHint, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
- import { Box, Markdown, SelectList, Spacer, Text, truncateToWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
2
+ import { Box, fuzzyFilter, getSelectPageIndex, Input, Markdown, SelectList, Spacer, Text, truncateToWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
3
3
  import type { DiscardPlan } from "../dist/discard.js";
4
4
  import type { PruneItem, PruneProgress } from "../dist/prune.js";
5
5
  import { TERMINAL_RUN_STATUSES } from "../dist/schema.js";
@@ -332,63 +332,121 @@ export function workingReport(direct: readonly DirectTask[], inventory: Isolated
332
332
  }), ...moreSection(fitted.more)] };
333
333
  }
334
334
 
335
- type Choice<T> = { label: string; value: T };
336
- async function choose<T>(ctx: ExtensionContext, title: string, items: readonly Choice<T>[], selectedIndex = 0): Promise<T | undefined> {
335
+ type Choice<T> = { label: string; value: T; description?: string; detail?: string; search?: string; key?: string };
336
+ type MenuState = { index: number; query: string; key?: string };
337
+ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly Choice<T>[], state: MenuState = { index: 0, query: "" }): Promise<T | undefined> {
337
338
  // Numeric suffixes only tell duplicate labels apart. Never parse display text into an identity.
338
339
  const clipped = items.map((item) => clean(item.label, 145));
339
- const labels = clipped.map((label, index) => clipped.indexOf(label) === clipped.lastIndexOf(label) ? label : `${label} [${index + 1}]`);
340
+ const counts = new Map<string, number>();
341
+ for (const label of clipped) counts.set(label, (counts.get(label) ?? 0) + 1);
342
+ const labels = clipped.map((label, index) => counts.get(label) === 1 ? label : `${label} [${index + 1}]`);
340
343
  if (ctx.mode !== "tui") {
341
344
  const selected = await ctx.ui.select(title, labels);
342
345
  const index = labels.indexOf(selected ?? "");
343
346
  return index < 0 ? undefined : items[index]!.value;
344
347
  }
345
348
  return ctx.ui.custom<T | undefined>((tui, theme, keys, done) => {
346
- const keyText = (action: Parameters<typeof keys.getKeys>[0]) => keys.getKeys(action).join("/");
349
+ const keyText = (action: Parameters<typeof keys.getKeys>[0]) => keys.getKeys(action)[0] ?? "unbound";
347
350
  const keyHint = (action: Parameters<typeof keys.getKeys>[0], description: string) => rawKeyHint(keyText(action), description);
348
- const rows = labels.map((label, index) => ({ label, value: String(index) }));
349
- // The menu replaces the editor, not the screen; cap its height to leave room for other content.
351
+ const rows = items.map((item, index) => ({ label: labels[index]!, value: String(index),
352
+ description: clean(item.description ?? "", 4000), detail: clean(item.detail ?? item.label, 4000).trim(),
353
+ search: clean([item.label, item.description, item.detail, item.search].filter(Boolean).join(" "), 8000) }));
354
+ const input = new Input({ prompt: "Find: ", placeholder: "type to filter", placeholderStyle: (text) => theme.fg("dim", text) });
355
+ input.setValue(state.query);
356
+ const previewText = new Text("", 0, 0);
357
+ const hints = new Text("", 0, 0);
358
+ const filter = () => fuzzyFilter(rows, input.getValue(), (row) => row.search);
359
+ let filtered = filter();
360
+ // The menu replaces the editor, not the screen; leave half the terminal for the transcript.
350
361
  const menuHeight = () => Math.max(1, Math.floor(tui.terminal.rows / 2));
351
362
  let height = menuHeight();
363
+ let width = 0;
352
364
  let listHeight = 0;
353
365
  let pressed = false;
354
366
  let cancelClick = false;
367
+ const headerHeight = () => height >= 6 ? 2 : height >= 4 ? 1 : 0;
368
+ const hintHeight = () => height >= 12 && width < 60 ? 3 : height >= 8 ? 2 : height >= 4 ? 1 : 0;
369
+ const detailHeight = () => height >= 12 ? 3 : height >= 10 ? 2 : 0;
370
+ const pageSize = () => Math.max(1, height - headerHeight() - hintHeight() - detailHeight() - 1);
371
+ const remember = (value: string) => { state.index = Number(value); state.key = items[state.index]!.key; };
355
372
  const createList = () => {
356
- // Reserve title, key hints, and the native scroll indicator. Very short menus show only the list.
357
- const list = new SelectList(rows, Math.max(1, height - (height >= 4 ? 3 : 1)), getSelectListTheme());
358
- list.setSelectedIndex(selectedIndex);
359
- list.onSelectionChange = ({ value }) => { selectedIndex = Number(value); };
360
- list.onSelect = ({ value }) => done(items[Number(value)]!.value);
361
- list.onCancel = () => done(undefined);
373
+ const list = new SelectList(filtered, pageSize(), { ...getSelectListTheme(), noMatch: () => theme.fg("warning", " No matches. Clear the filter.") }, { maxPrimaryColumnWidth: 42,
374
+ truncatePrimary: ({ text, maxWidth }) => truncateToWidth(text, maxWidth) });
375
+ const index = filtered.findIndex(({ value }) => state.key ? items[Number(value)]!.key === state.key : Number(value) === state.index);
376
+ list.setSelectedIndex(Math.max(0, index));
377
+ list.onSelectionChange = ({ value }) => remember(value);
378
+ list.onSelect = ({ value }) => { remember(value); done(items[Number(value)]!.value); };
362
379
  return list;
363
380
  };
364
381
  let list = createList();
382
+ const resetPress = () => { if (pressed) cancelClick = true; pressed = false; };
365
383
  return {
366
- render(width) {
367
- // Keep the pressed item across redraws: a press can recenter the visible rows before its click.
368
- if (height !== menuHeight()) {
369
- if (pressed) cancelClick = true;
370
- pressed = false;
371
- height = menuHeight(); list = createList();
384
+ // Native list paging must not scroll the fullscreen transcript instead.
385
+ capturesViewportInput: list.capturesViewportInput,
386
+ get focused() { return input.focused; },
387
+ set focused(value: boolean) { input.focused = value; },
388
+ render(nextWidth) {
389
+ if (height !== menuHeight() || width !== nextWidth) {
390
+ resetPress();
391
+ height = menuHeight(); width = nextWidth; list = createList();
372
392
  }
373
- const lines = list.render(width);
374
- listHeight = Math.min(lines.length, height);
375
- if (height < 4) return lines.slice(0, height);
376
- return [truncateToWidth(theme.fg("accent", title), width), ...lines,
377
- truncateToWidth([rawKeyHint(`${keyText("tui.select.up")}/${keyText("tui.select.down")}`, "scroll"),
378
- keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel")].join(" · "), width)];
393
+ const lines = list.render(width).map((line) => truncateToWidth(line, width));
394
+ listHeight = Math.min(lines.length, height - headerHeight() - hintHeight() - detailHeight());
395
+ const selected = list.getSelectedItem();
396
+ const detail = selected ? rows[Number(selected.value)]!.detail : "No matches. Clear or change the filter.";
397
+ previewText.setText(theme.fg("muted", detail));
398
+ const limit = detailHeight();
399
+ const preview = limit ? previewText.render(width).slice(0, limit + 1) : [];
400
+ if (limit && preview.length > limit) preview[limit - 1] = truncateToWidth(`${preview[limit - 1]}…`, width, "…", true);
401
+ hints.setText([keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel"),
402
+ `${filtered.length}/${rows.length}`, rawKeyHint(`${keyText("tui.select.up")}/${keyText("tui.select.down")}`, "move"),
403
+ rawKeyHint(`${keyText("tui.select.pageUp")}/${keyText("tui.select.pageDown")}`, "page"), keyHint("tui.editor.deleteToLineStart", "clear")].join(" · "));
404
+ return [
405
+ ...(headerHeight() ? [theme.fg("accent", title)] : []),
406
+ ...(headerHeight() === 2 ? input.render(width) : []),
407
+ ...lines.slice(0, listHeight),
408
+ ...preview.slice(0, limit),
409
+ ...hints.render(width).slice(0, hintHeight()),
410
+ ].map((line) => truncateToWidth(line, width));
411
+ },
412
+ handleInput(data) {
413
+ resetPress();
414
+ if (keys.matches(data, "tui.select.cancel")) { done(undefined); return; }
415
+ if (keys.matches(data, "tui.select.confirm")) {
416
+ const selected = list.getSelectedItem();
417
+ if (selected) list.onSelect!(selected);
418
+ return;
419
+ }
420
+ const index = filtered.findIndex(({ value }) => value === list.getSelectedItem()?.value);
421
+ const page = getSelectPageIndex(keys, data, index, filtered.length, pageSize());
422
+ const up = keys.matches(data, "tui.select.up"), down = keys.matches(data, "tui.select.down");
423
+ if (up || down || page !== undefined) {
424
+ if (filtered.length) list.setSelectedIndex(page ?? (index + (up ? -1 : 1) + filtered.length) % filtered.length);
425
+ const selected = list.getSelectedItem();
426
+ if (selected) remember(selected.value);
427
+ } else {
428
+ if (keys.matches(data, "tui.editor.deleteToLineStart")) input.setValue("");
429
+ else input.handleInput(data);
430
+ if (state.query !== input.getValue()) {
431
+ state.query = input.getValue(); filtered = filter(); list = createList();
432
+ const selected = list.getSelectedItem();
433
+ if (selected) remember(selected.value);
434
+ }
435
+ }
436
+ tui.requestRender();
379
437
  },
380
- handleInput(data) { list.handleInput(data); tui.requestRender(); },
381
438
  handleMouse(event: TuiMouseEvent) {
382
439
  if (event.type === "click" && cancelClick) { cancelClick = false; return { handled: true }; }
383
440
  if (event.type === "press") cancelClick = false;
384
- const y = event.y - (height >= 4 ? 1 : 0);
441
+ if (headerHeight() === 2 && event.y === 1) return input.handleMouse({ ...event, y: 0, height: 1 });
442
+ const y = event.y - headerHeight();
385
443
  if (y < 0 || y >= listHeight) return undefined;
386
444
  const result = list.handleMouse({ ...event, y, height: listHeight });
387
445
  if (event.type === "press") pressed = result?.handled === true;
388
446
  if (event.type === "click") pressed = false;
389
447
  return result;
390
448
  },
391
- invalidate() { list.invalidate(); },
449
+ invalidate() { input.invalidate(); list.invalidate(); previewText.invalidate(); hints.invalidate(); },
392
450
  };
393
451
  }, { blocked: { kind: "question", message: title } });
394
452
  }
@@ -399,16 +457,16 @@ async function chooseMany<T>(ctx: ExtensionContext, title: string, items: readon
399
457
  valid: () => boolean): Promise<T[] | undefined> {
400
458
  type Pick = { kind: "toggle"; value: T } | { kind: "all" } | { kind: "clear" } | { kind: "continue" } | { kind: "cancel" };
401
459
  const chosen = new Set(preselected);
402
- let selectedIndex = 0;
460
+ const state: MenuState = { index: 0, query: "" };
403
461
  for (;;) {
404
462
  const choices: Choice<Pick>[] = [
405
- ...items.map((item) => ({ label: `${chosen.has(item.value) ? "[x]" : "[ ]"} ${item.label}`, value: { kind: "toggle" as const, value: item.value } })),
463
+ ...items.map((item) => ({ ...item, label: `${chosen.has(item.value) ? "[x]" : "[ ]"} ${item.label}`, value: { kind: "toggle" as const, value: item.value } })),
406
464
  { label: "Select all", value: { kind: "all" } }, { label: "Clear", value: { kind: "clear" } },
407
465
  { label: `Continue (${chosen.size} selected)`, value: { kind: "continue" } }, { label: "Cancel", value: { kind: "cancel" } },
408
466
  ];
409
- const picked = await choose(ctx, title, choices, selectedIndex);
467
+ const picked = await choose(ctx, `${chosen.size} selected · ${title}`, choices, state);
410
468
  if (!valid() || !picked || picked.kind === "cancel") return undefined;
411
- selectedIndex = choices.findIndex(({ value }) => value === picked);
469
+ state.index = choices.findIndex(({ value }) => value === picked);
412
470
  if (picked.kind === "continue") return items.map(({ value }) => value).filter((value) => chosen.has(value));
413
471
  if (picked.kind === "all") for (const { value } of items) chosen.add(value);
414
472
  else if (picked.kind === "clear") chosen.clear();
@@ -608,7 +666,8 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
608
666
  const options = reviewed.shown.filter((item) => item.prunable || item.override);
609
667
  if (!options.length) return;
610
668
  // Continue confirms prunable items; each is re-verified first. Blocked items need their own confirmation below.
611
- const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item), value: item })),
669
+ const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item),
670
+ detail: `${item.branch} · ${item.path ?? "no checkout"} · ${item.reason}`, value: item })),
612
671
  options.filter((item) => item.prunable), valid);
613
672
  if (!picked?.length) return;
614
673
  const forceable = picked.filter((item) => item.override === "force");
@@ -674,6 +733,7 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
674
733
  return;
675
734
  }
676
735
  let history = false;
736
+ const menu: MenuState = { index: 0, query: "" };
677
737
  // The working report shows on open and on each Refresh, not after other menu actions.
678
738
  let report = true;
679
739
  for (;;) {
@@ -690,14 +750,27 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
690
750
  if (unavailable) ctx.ui.notify(`Isolated inventory unavailable (${unavailable}). Direct branch recovery remains available; check the canonical Git checkout/configuration.`, "warning");
691
751
  if (inventory?.invalidIds.length) for (const id of inventory.invalidIds) ctx.ui.notify(`Unreadable isolated state ID: ${JSON.stringify(id)}. Preserve this file; inspect the state store before making changes.`, "warning");
692
752
  type Selection = { kind: "direct"; task: DirectTask } | { kind: "isolated"; request: IsolatedRequest; root: string } | { kind: "refresh" } | { kind: "history" } | { kind: "many" } | { kind: "close" };
693
- // A header row selects Refresh; rows sort by status priority within their group.
753
+ // Terminal rows carry their group, so headings cannot be mistaken for actions.
694
754
  const group = <T extends { status: string }>(title: string, items: readonly T[], choice: (item: T) => Choice<Selection>): Choice<Selection>[] =>
695
- items.length ? [{ label: `── ${title} (${items.length}) ──`, value: { kind: "refresh" } },
755
+ items.length ? [...(ctx.mode === "tui" ? [] : [{ label: `── ${title} (${items.length}) ──`, value: { kind: "refresh" as const } }]),
696
756
  ...[...items].sort((a, b) => priority(a.status) - priority(b.status)).map(choice)] : [];
697
757
  const requests = (inventory?.requests ?? []).filter((request) => history || !completed(request.status) || /retained/i.test(request.status));
698
- const isolatedChoice = (request: IsolatedRequest): Choice<Selection> => ({ label: ` ${glyph(request.status)} ${isolatedLabel(request)}`, value: { kind: "isolated", request, root: inventory!.root } });
699
- // One row per workflow; new records keep opaque IDs in details. Status is last so clipping preserves the reference.
700
- const directChoice = (task: DirectTask): Choice<Selection> => ({ label: ` ${glyph(task.status)} ${directLabel(task)} · ${task.status}${costSuffix(task.cost)}${task.workers.length || task.name === task.id ? "" : ` · ${task.id}`}`, value: { kind: "direct", task } });
758
+ const isolatedChoice = (request: IsolatedRequest): Choice<Selection> => {
759
+ const group = request.orphaned ? "Orphaned · parent checkout removed" : "Isolated";
760
+ return { label: ` ${glyph(request.status)} ${ctx.mode === "tui" ? `${request.id} · ${request.status}` : isolatedLabel(request)}`,
761
+ description: `${group} · ${summary(request.name)}`, detail: `${group} · ${request.status} · ${request.id} · ${request.name}`,
762
+ key: `isolated:${request.directory ?? inventory!.root}:${request.id}`, value: { kind: "isolated", request, root: inventory!.root } };
763
+ };
764
+ // Put identity and status before the goal. Keep full context in the selected-row preview and search.
765
+ const directChoice = (task: DirectTask): Choice<Selection> => {
766
+ const [first] = task.workers;
767
+ const ref = first ? first.workers === 1 ? directRef(first) : `D${first.workflow} · ${first.workers} workers` : task.id;
768
+ return { label: ctx.mode === "tui" ? ` ${glyph(task.status)} ${ref} · ${task.status}${costSuffix(task.cost)}`
769
+ : ` ${glyph(task.status)} ${directLabel(task)} · ${task.status}${costSuffix(task.cost)}${task.workers.length || task.name === task.id ? "" : ` · ${task.id}`}`,
770
+ description: `Direct · ${directLabel(task)}`, detail: `Direct · ${task.status}${costSuffix(task.cost)} · ${task.id} · ${directLabel(task)}`,
771
+ search: [task.name, ...task.workers.map(workerLabel)].join(" "),
772
+ key: `direct:${task.id}`, value: { kind: "direct", task } };
773
+ };
701
774
  const groups = [
702
775
  group("Direct", direct.filter((task) => history || !completed(task.status)), directChoice),
703
776
  group("Isolated", requests.filter((request) => !request.orphaned), isolatedChoice),
@@ -712,12 +785,12 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
712
785
  { label: "Close", value: { kind: "close" } },
713
786
  ];
714
787
  if (!unavailable && !direct.length && !inventory?.requests.length && !inventory?.invalidIds.length) ctx.ui.notify("No direct tasks recorded on this session branch or isolated requests in this checkout. Ask Main to start delegation.", "info");
715
- const selected = await choose(ctx, history ? "Subagent · completed / history" : "Subagent · current work", selections);
788
+ const selected = await choose(ctx, history ? "Subagent · completed / history" : "Subagent · current work", selections, menu);
716
789
  if (!valid() || !selected || selected.kind === "close") return;
717
790
  if (selected.kind === "refresh") { report = true; continue; }
718
791
  if (selected.kind === "history") { history = !history; continue; }
719
792
  if (selected.kind === "many") {
720
- const picked = await chooseMany(ctx, "Subagent · select work", rows.map(({ label, value }) => ({ label: label.trim(), value })), [], valid);
793
+ const picked = await chooseMany(ctx, "Subagent · select work", rows.map((item) => ({ ...item, label: item.label.trim() })), [], valid);
721
794
  if (!picked?.length) { if (!valid()) return; continue; }
722
795
  const isolated = picked.flatMap((item) => item.kind === "isolated" ? [item.request] : []);
723
796
  const closable = picked.flatMap((item) => item.kind === "direct" && item.task.canClose ? [item.task] : []);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "28.1.0",
3
+ "version": "28.2.0",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",