pi-subagent-manager 0.29.1 → 0.30.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
@@ -8,6 +8,10 @@
8
8
 
9
9
  Let pi hand work to helper agents in parallel. Watch what they're doing, give them more direction, or pick up a finished agent's conversation.
10
10
 
11
+ ![Pi running parallel agents, browsing a nested agent tree, steering a writer, and watching passing tests](docs/assets/subagent-manager-demo.gif)
12
+
13
+ A real Pi session with a customized footer and Nerd Font: parallel work, nested delegation, watching, and steering. [Recording details](docs/demo.md) (37 seconds; pauses shortened).
14
+
11
15
  ## Install
12
16
 
13
17
  Requires pi **0.99.2+**.
@@ -47,7 +51,7 @@ They use your current model until you configure preferences. Open `/agents types
47
51
 
48
52
  ## Settings and safety
49
53
 
50
- Open `/agents` to change delegation mode, limits, and display settings; save with **Ctrl+S**. Experimental options are marked **[labs]** in their help.
54
+ Open `/agents` to change delegation mode, limits, and display settings; save with **Ctrl+S**. Experimental options are marked **[labs]** in their help. **[lab] Subagent extensions** opens a per-extension chooser (Space/Enter toggles, Esc returns); **Save and apply** persists the selection for new subagent sessions. It lists auto-discovered `.ts`/`.js` files and subdirectory entry points in Pi’s agent-dir `extensions/` (honoring `PI_CODING_AGENT_DIR`), trusted project `.pi/extensions/`, and configured/package files—not CLI-only/inline/built-in extensions; see [limitations](docs/subagent-extension-limitations.md).
51
55
 
52
56
  Agents share your working directory and OS permissions: **tool policies are not a sandbox**. Don't run multiple subagent extensions together — they clash on `/agents`.
53
57
 
package/docs/demo.md ADDED
@@ -0,0 +1,63 @@
1
+ # README demo
2
+
3
+ [Watch the GIF](assets/subagent-manager-demo.gif).
4
+
5
+ ## What it shows
6
+
7
+ An actual interactive Pi session: six parallel agent roles, two nested taskers,
8
+ the live Agents widget, the fullscreen tree, watching a thread, steering a completed
9
+ writer back into action, passing API checks, and the final recap. A preparatory
10
+ reader makes nine agents in total.
11
+
12
+ The fictional **Orbit** project lived in a private temporary demo folder, outside
13
+ this repository. Its documents and Python checks were synthetic and local; the
14
+ agents still used live model providers. The deliberately slow checks left time to
15
+ browse live activity. No production code or data was used.
16
+
17
+ ## Recording
18
+
19
+ - Pi **1.3.0**, pi-subagent-manager **0.29.3**.
20
+ - Started **plain `pi`**, with the user's existing configuration and all configured
21
+ extensions. No `-ne`, replacement agent directory, or stripped-down configuration.
22
+ - The colorful footer and checklist come from the author's configured extensions;
23
+ they are not installed by pi-subagent-manager.
24
+ - **Maple Mono NF**, 17 px, 112 × 34 terminal cells. Reused this installed Nerd Font
25
+ rather than installing JetBrains Mono. Chromium confirmed MapleMono-NF-Regular
26
+ for every footer icon; the rendered footer and role glyphs were visually checked.
27
+ - Used the [ttyd-testing skill](../.agents/skills/ttyd-testing/SKILL.md): a real PTY
28
+ in localhost-only authenticated ttyd, rendered by isolated headless Chrome 154
29
+ through Playwright. Reused system Chrome; capture-only Playwright lived in a
30
+ private temporary directory. No project dependencies or Pi settings changed.
31
+ - Sampled actual screenshots at approximately 4 fps. Idle intervals were cut, a
32
+ short tree section runs at 2×, and selected frames are held for readability.
33
+ No UI content was synthesized, redrawn, or overlaid.
34
+ - Encoded with FFmpeg's `palettegen` / `paletteuse` filters, no dithering, variable
35
+ frame timing, and infinite looping: **1150 × 759 px**, **37.28 seconds**,
36
+ **1,332,767 bytes** (about 1.27 MiB).
37
+ - Decoded the finished GIF and inspected representative frames for text, borders,
38
+ glyphs, footer, and transitions. Stopped the recording, Pi, ttyd, and browser.
39
+ Private session logs, control credentials, and raw captures are not committed.
40
+
41
+ To record another session, read the skill first, run its `doctor` with an installed
42
+ Nerd Font, and start a fresh session in a disposable folder:
43
+
44
+ ```sh
45
+ SKILL="$PWD/.agents/skills/ttyd-testing"
46
+ WORK="$(mktemp -d)"
47
+ node "$SKILL/scripts/terminal.mjs" doctor --font 'Maple Mono NF'
48
+ node "$SKILL/scripts/terminal.mjs" start \
49
+ --session readme-demo --cwd "$WORK" --cols 112 --rows 34 \
50
+ --font 'Maple Mono NF' --font-size 17 -- pi
51
+ ```
52
+
53
+ Populate the disposable folder with a small fictional project and task brief before
54
+ submitting a prompt. This recording asked Pi to fan out six named roles and have the
55
+ architect delegate two more, staying offline and inside the demo folder. Open the
56
+ tree with **←**, select a thread and press **Enter**, send a message in **Steer**,
57
+ and use **Ctrl+Q** to return to the main editor. Capture named screenshots after
58
+ meaningful actions and inspect them. For continuous sampling, avoid a long `wait`
59
+ action on the same session: the harness serializes controls, so it blocks captures.
60
+ Always finish with `terminal.mjs stop --session readme-demo`.
61
+
62
+ The GIF is an edited demonstration, not a timing benchmark or a guarantee that
63
+ other fonts, themes, terminal sizes, or agent models render identically.
package/docs/settings.md CHANGED
@@ -106,15 +106,25 @@ Both status modes use the same public Pi status API: third-party footers may als
106
106
 
107
107
  See [Subagent dollar totals in pi-footer](pi-footer.md) for step-by-step setup and copy-paste widget configuration, status-key, and event snippets.
108
108
 
109
- ## [labs] Enable subagent extensions (`subagentExtensions`)
109
+ ## [labs] Subagent extensions (`subagentExtensions`)
110
110
 
111
- Experimental on/off toggle, **off by default**. Enable **[labs] Enable subagent extensions** in `/agents settings` and save, or set `"subagentExtensions": true`.
111
+ Experimental per-extension chooser, **none enabled by default**. Open **[lab] Subagent extensions** in `/agents settings`. Use ↑/↓ or Tab to navigate, Space/Enter to toggle each extension, and Esc/Back to return. Then **Save and apply** (Ctrl+S) in the outer settings dialog; outer Cancel discards edits. Full paths appear in row help so identically named extensions can be distinguished.
112
112
 
113
- When a subagent session opens, it reloads enabled extension files from user configuration and, only when the main project is trusted, project configuration. Pi package resource filters and disabled-extension settings are respected; missing packages are skipped, never installed. This manager is excluded to avoid starting a second subagent manager inside each child. Each factory receives a child-local runtime and its hooks run against that child's session. Reloaded extension tools take precedence over inherited main-session bridges, including tools registered on `session_start`; tool filtering still applies. Other inherited tools keep their existing bridges.
113
+ `subagentExtensions` accepts an array of canonical absolute extension file paths, for example `"subagentExtensions": ["/home/me/.pi/agent/extensions/example.ts"]`. The selected set is persisted in the existing Global/Current Project settings layer. Legacy `true` still means all discoverable extensions and `false` means none; opening and closing the chooser converts that value to an explicit draft selection, persisted only on Save and apply. Newly discovered extensions are not automatically enabled after an explicit selection is saved. Saved paths that are no longer discoverable are shown as **Unavailable**, can be toggled off, and never load.
114
114
 
115
- **This is configured-file discovery, not exact main-session inheritance. Bugs and unintended consequences are possible.** Read [subagent extension limitations](subagent-extension-limitations.md) before enabling it: the guide covers excluded extensions, configuration drift, `input` hook bypasses, shared side effects, non-interactive UI, and main-session tool bridges.
115
+ The chooser includes **auto-discovered files**, not just paths listed in `settings.json` or packages:
116
116
 
117
- Save and apply affects newly opened sessions, including retained sessions reopened after reload. Already-open agents keep their extension runtime until disposed. The main agent's extensions and tool set are not changed. Leave this off unless your extensions are safe to run across separate sessions.
117
+ - `<agentDir>/extensions/*.ts` and `*.js` (normally `~/.pi/agent/extensions/foo.ts`). The existing Pi `getAgentDir()` resolution honors `PI_CODING_AGENT_DIR`; no home-directory path is hard-coded.
118
+ - Immediate subdirectories with `index.ts` or `index.js` entry points (`index.ts` takes precedence), or Pi package-manifest extension entries. This is not an unrestricted recursive scan.
119
+ - The same auto-discovery under `<cwd>/.pi/extensions`, **only for trusted projects**.
120
+
121
+ Discovery uses Pi's own resource resolver, keeping its ignore rules, directory/manifest entry-point precedence and disabled-extension patterns. Standalone files need no package manifest or explicit settings entry. This manager is always excluded, including symlinks to it.
122
+
123
+ When a subagent session opens, it reloads only selected, currently enabled extension files from user auto-discovery/configuration and, only when the main project is trusted, project auto-discovery/configuration. Pi package resource filters and disabled-extension settings are respected; missing packages are skipped, never installed. This manager is excluded to avoid starting a second subagent manager inside each child. Each factory receives a child-local runtime and its hooks run against that child's session. Reloaded extension tools take precedence over inherited main-session bridges, including tools registered on `session_start`; tool filtering still applies. Other inherited tools keep their existing bridges.
124
+
125
+ **This is filesystem/configuration discovery, not exact main-session inheritance. Bugs and unintended consequences are possible.** Read [subagent extension limitations](subagent-extension-limitations.md) before enabling it: the guide covers excluded extensions, configuration drift, `input` hook bypasses, shared side effects, non-interactive UI, and main-session tool bridges.
126
+
127
+ Save and apply affects newly opened sessions, including retained sessions reopened after reload. Already-open agents keep their extension runtime until disposed. The main agent's extensions and tool set are not changed. Leave all extensions unselected unless your extensions are safe to run across separate sessions.
118
128
 
119
129
  ## [labs] Checklist integration (`checklistIntegration`)
120
130
 
@@ -1,15 +1,15 @@
1
1
  # Subagent extension limitations
2
2
 
3
- **[labs] Enable subagent extensions** (`subagentExtensions`) is experimental and **off by default**. It reloads configured extension files into separate subagent sessions. Bugs and unintended consequences are possible; enable it only when your extensions are safe to run in multiple sessions.
3
+ **[lab] Subagent extensions** (`subagentExtensions`) is experimental and **none selected by default**. It reloads selected auto-discovered/configured extension files into separate subagent sessions. Bugs and unintended consequences are possible; enable it only when your extensions are safe to run in multiple sessions.
4
4
 
5
- See [the setting and how to enable it](settings.md#labs-enable-subagent-extensions-subagentextensions).
5
+ See [the setting and how to enable it](settings.md#labs-subagent-extensions-subagentextensions).
6
6
 
7
7
  ## Not an exact copy of the main agent's extensions
8
8
 
9
- - The public Pi extension API does not expose the main session's loaded-extension inventory. Subagents discover enabled extension files from user configuration and, only when the main project is trusted, project configuration.
10
- - **CLI-only, inline, and built-in extensions are not reloaded.** Configured file extensions are supported; this manager is excluded to avoid starting another subagent manager inside each child.
9
+ - The public Pi extension API does not expose the main session's loaded-extension inventory. Subagents discover enabled extension files through Pi’s resource resolver: standalone `.ts`/`.js` files and subdirectory entry points in `<agentDir>/extensions` (honoring `PI_CODING_AGENT_DIR`), plus configured/package paths. The same discovery under `<cwd>/.pi/extensions` and project configuration is included only when the main project is trusted.
10
+ - **CLI-only, inline, and built-in extensions are not reloaded.** Auto-discovered and configured file extensions are supported; this manager is excluded to avoid starting another subagent manager inside each child.
11
11
  - Configuration changed since the main session loaded can produce a different extension set in a newly opened subagent session. Disabled-extension settings and package resource filters are respected. Missing packages are skipped, never installed.
12
- - Saving the toggle affects newly opened sessions, including retained sessions reopened after reload. Already-open agents keep their extension runtime until disposed; the main agent's runtime is unchanged.
12
+ - Saving the selection affects newly opened sessions, including retained sessions reopened after reload. Already-open agents keep their extension runtime until disposed; the main agent's runtime is unchanged.
13
13
 
14
14
  ## Some messages bypass `input` hooks
15
15
 
@@ -27,4 +27,4 @@ Reloaded extension tools take precedence over inherited main-session bridges, in
27
27
 
28
28
  **Bridged calls run through both child hooks and the main session's hooks.** They reuse main-session resources and context, so session-mutating tools are not necessarily isolated to the child, and hook side effects can occur in both sessions. Built-in codemode and tool search remain child-local rather than reusing the main agent's implementations.
29
29
 
30
- Leave the setting off if your extensions require exact main-session inheritance, interactive UI, or an `input` hook for every delivered message.
30
+ Leave all extensions unselected if your extensions require exact main-session inheritance, interactive UI, or an `input` hook for every delivered message.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.29.1",
3
+ "version": "0.30.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
@@ -29,7 +29,7 @@ async function isManagerExtension(file: string, packageRoot?: string): Promise<b
29
29
 
30
30
  /**
31
31
  * The public ExtensionAPI cannot inspect the main session's resource loader. This is
32
- * deliberately configured-file discovery, not exact main-set inheritance: CLI-only,
32
+ * deliberately filesystem/configuration discovery, not exact main-set inheritance: CLI-only,
33
33
  * inline and built-in extensions are not reloaded. Missing packages are never installed.
34
34
  */
35
35
  export async function discoverSubagentExtensions(options: {
@@ -41,6 +41,10 @@ export async function discoverSubagentExtensions(options: {
41
41
  projectTrusted: options.projectTrusted,
42
42
  });
43
43
  const packages = new DefaultPackageManager({ ...options, settingsManager });
44
+ // Pi's resolver includes auto-discovery in <agentDir>/extensions and, when
45
+ // trusted, <cwd>/.pi/extensions: direct .ts/.js files and directory entry points.
46
+ // Reuse it so index/manifest precedence, ignore rules and disabled-resource
47
+ // patterns stay identical to Pi instead of bypassing them with a second scan.
44
48
  const resources = await packages.resolve(async () => "skip");
45
49
  const paths: string[] = [];
46
50
  const seen = new Set<string>();
@@ -50,7 +54,18 @@ export async function discoverSubagentExtensions(options: {
50
54
  const resolved = await canonical(resource.path);
51
55
  if (seen.has(resolved)) continue;
52
56
  seen.add(resolved);
53
- paths.push(resource.path);
57
+ paths.push(resolved);
54
58
  }
55
59
  return paths;
56
60
  }
61
+
62
+ /** Intersect saved selections with current trusted discovery; never load arbitrary saved paths. */
63
+ export function selectSubagentExtensions(
64
+ available: string[],
65
+ selection: boolean | readonly string[],
66
+ ): string[] {
67
+ if (selection === true) return [...available];
68
+ if (selection === false) return [];
69
+ const selected = new Set(selection);
70
+ return available.filter((file) => selected.has(file));
71
+ }
@@ -36,7 +36,7 @@ interface Record {
36
36
  liveInputTokens?: number;
37
37
  liveOutputTokens?: number;
38
38
  liveCostUsd?: number;
39
- /** Detached (spawned with wait:false): completion is reported as an event. */
39
+ /** Detached (spawned with wait:false or resumed): completion is reported as an event. */
40
40
  async?: boolean;
41
41
  timeoutTimer?: ReturnType<typeof setTimeout>;
42
42
  pauseRequested: boolean;
@@ -414,6 +414,8 @@ export class ThreadManager {
414
414
  return rearm();
415
415
  }
416
416
  this.assertCapacity();
417
+ // Resumes return immediately, regardless of the original spawn mode or restored metadata.
418
+ record.async = true;
417
419
  this.start(record, message);
418
420
  return rearm();
419
421
  }
@@ -27,9 +27,9 @@ import {
27
27
  } from "./mailbox.ts";
28
28
  import { selectTools } from "../prefs/config.ts";
29
29
  import { TranscriptChannel } from "./transcript.ts";
30
- import { discoverSubagentExtensions } from "./extensions.ts";
30
+ import { discoverSubagentExtensions, selectSubagentExtensions } from "./extensions.ts";
31
31
  import type { InheritedToolSource } from "./inherited-tools.ts";
32
- import type { ModelSelectionMode, ToolFilteringMode } from "../prefs/settings.ts";
32
+ import type { ModelSelectionMode, SubagentExtensionSelection, ToolFilteringMode } from "../prefs/settings.ts";
33
33
  import {
34
34
  modelIdentity,
35
35
  getModelPreferences,
@@ -176,7 +176,7 @@ export function createDriverFactory(
176
176
  getModelSelection: () => ModelSelectionMode = () => "pick-first-scoped",
177
177
  getToolFiltering: () => ToolFilteringMode = () => "allowed",
178
178
  getInheritedTools: () => InheritedToolSource = () => ({ tools: [], activeNames: [] }),
179
- getSubagentExtensions: () => boolean = () => false,
179
+ getSubagentExtensions: () => SubagentExtensionSelection = () => false,
180
180
  ): DriverFactory & {
181
181
  resolveAgentSettings(type: AgentType, parentPath: string): ResolvedAgentSettings;
182
182
  } {
@@ -274,7 +274,7 @@ export function createDriverFactory(
274
274
  const ctx = getRootContext();
275
275
  // Tool policy is a startup snapshot; retained live sessions keep their selected set.
276
276
  const toolFiltering = getToolFiltering();
277
- const subagentExtensions = getSubagentExtensions();
277
+ const extensionSelection = getSubagentExtensions();
278
278
  const rootId = ctx.sessionManager.getSessionId();
279
279
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(rootId))
280
280
  throw new Error("Unsafe root session id for subagent storage");
@@ -423,9 +423,13 @@ export function createDriverFactory(
423
423
  (options.type.tools?.allow?.includes(name) && toolFiltering === "allowed"),
424
424
  );
425
425
  const projectTrusted = ctx.isProjectTrusted?.() ?? false;
426
- const extensionPaths = subagentExtensions
427
- ? await discoverSubagentExtensions({ cwd: ctx.cwd, agentDir, projectTrusted })
428
- : [];
426
+ const extensionPaths = extensionSelection === false || (Array.isArray(extensionSelection) && !extensionSelection.length)
427
+ ? []
428
+ : selectSubagentExtensions(
429
+ await discoverSubagentExtensions({ cwd: ctx.cwd, agentDir, projectTrusted }),
430
+ extensionSelection,
431
+ );
432
+ const subagentExtensions = extensionPaths.length > 0;
429
433
  // Keep discovery settings OUT of this loader: reload() resolves packages with
430
434
  // auto-install enabled. An empty in-memory package/resource list ensures it
431
435
  // only loads the already-resolved files and cannot install missing packages.
@@ -42,6 +42,13 @@ export const MODEL_SELECTION_MODES = [
42
42
  ] as const;
43
43
  export type ModelSelectionMode = (typeof MODEL_SELECTION_MODES)[number];
44
44
 
45
+ /** Legacy booleans mean all/none; arrays pin the selected canonical file paths. */
46
+ export type SubagentExtensionSelection = boolean | string[];
47
+
48
+ export function settingsValueEqual(a: unknown, b: unknown): boolean {
49
+ return JSON.stringify(a) === JSON.stringify(b);
50
+ }
51
+
45
52
  export interface ManagerSettings {
46
53
  subagentMode: SubagentMode;
47
54
  toolFiltering: ToolFilteringMode;
@@ -52,7 +59,7 @@ export interface ManagerSettings {
52
59
  nerdFontIcons: boolean;
53
60
  loaderStyle: LoaderStyle;
54
61
  finalRecap: boolean;
55
- subagentExtensions: boolean;
62
+ subagentExtensions: SubagentExtensionSelection;
56
63
  checklistIntegration: boolean;
57
64
  /** [labs] One-line agent work summaries written by the housekeeping model. */
58
65
  housekeepingEnabled: boolean;
@@ -128,7 +135,8 @@ function positiveSafeInteger(value: unknown): value is number {
128
135
  }
129
136
 
130
137
  function requirement(key: (typeof KEYS)[number]): string {
131
- if (key === "nerdFontIcons" || key === "finalRecap" || key === "subagentExtensions" || key === "checklistIntegration" || key === "housekeepingEnabled") return `${key} must be a boolean`;
138
+ if (key === "subagentExtensions") return "subagentExtensions must be a boolean or an array of absolute file paths";
139
+ if (key === "nerdFontIcons" || key === "finalRecap" || key === "checklistIntegration" || key === "housekeepingEnabled") return `${key} must be a boolean`;
132
140
  if (key === "housekeepingModel") return "housekeepingModel must be empty or provider/model-id";
133
141
  if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
134
142
  if (key === "widgetMode") return "widgetMode must be full or minimal";
@@ -168,11 +176,18 @@ function parseSettings(content: string): Partial<ManagerSettings> {
168
176
  for (const key of KEYS) {
169
177
  if (!Object.hasOwn(record, key)) continue;
170
178
  const value = record[key];
171
- if (key === "nerdFontIcons" || key === "finalRecap" || key === "subagentExtensions" || key === "checklistIntegration" || key === "housekeepingEnabled") {
179
+ if (key === "nerdFontIcons" || key === "finalRecap" || key === "checklistIntegration" || key === "housekeepingEnabled") {
172
180
  if (typeof value !== "boolean") throw new Error(requirement(key));
173
181
  layer[key] = value;
174
182
  continue;
175
183
  }
184
+ if (key === "subagentExtensions") {
185
+ if (typeof value !== "boolean" && !(Array.isArray(value) && value.every(
186
+ (entry) => typeof entry === "string" && entry.length > 0 && resolve(entry) === entry && !entry.includes("\0"),
187
+ ))) throw new Error(requirement(key));
188
+ layer.subagentExtensions = typeof value === "boolean" ? value : [...new Set(value as string[])].sort();
189
+ continue;
190
+ }
176
191
  if (key === "housekeepingModel") {
177
192
  if (!isHousekeepingModel(value)) throw new Error(requirement(key));
178
193
  layer.housekeepingModel = value;
@@ -331,7 +346,7 @@ function serializedSettings(settings: ManagerSettings): string {
331
346
  const serialized = `${JSON.stringify(parsed, null, 2)}\n`;
332
347
  const confirmed = parseSettings(serialized);
333
348
  for (const key of KEYS) {
334
- if (confirmed[key] !== parsed[key]) throw new Error(requirement(key));
349
+ if (!settingsValueEqual(confirmed[key], parsed[key])) throw new Error(requirement(key));
335
350
  }
336
351
  return serialized;
337
352
  }
@@ -440,8 +455,8 @@ export function saveManagerSettings(options: {
440
455
  function assertExpectedLayers(current: ManagerSettingsLayers, expected: ManagerSettingsLayers): void {
441
456
  if (
442
457
  current.scope !== expected.scope ||
443
- KEYS.some((key) => current.global[key] !== expected.global[key] ||
444
- current.project[key] !== expected.project[key]) ||
458
+ KEYS.some((key) => !settingsValueEqual(current.global[key], expected.global[key]) ||
459
+ !settingsValueEqual(current.project[key], expected.project[key])) ||
445
460
  current.diagnostics.length !== expected.diagnostics.length ||
446
461
  current.diagnostics.some((diagnostic, index) => diagnostic !== expected.diagnostics[index])
447
462
  ) {
@@ -473,7 +488,7 @@ export function saveManagerOverrides(options: ManagerSettingsOptions & {
473
488
  ? DEFAULT_MANAGER_SETTINGS
474
489
  : { ...DEFAULT_MANAGER_SETTINGS, ...current.global };
475
490
  const overrides = Object.fromEntries(
476
- KEYS.filter((key) => parsed[key] !== inherited[key]).map((key) => [key, parsed[key]]),
491
+ KEYS.filter((key) => !settingsValueEqual(parsed[key], inherited[key])).map((key) => [key, parsed[key]]),
477
492
  );
478
493
  const entry = options.scope === "user"
479
494
  ? layer(options.agentDir, ["subagent-manager"])
package/src/ui/dialog.ts CHANGED
@@ -196,6 +196,7 @@ export class DialogMenu {
196
196
  readonly footer = "↑↓ navigate · Enter select · Esc close",
197
197
  private saveId?: string,
198
198
  private renderLegend?: (theme: Theme) => string,
199
+ private spaceSelect = false,
199
200
  ) {
200
201
  const index = rows.findIndex((row) => row.id === selectedId);
201
202
  if (index >= 0) this.selected = index;
@@ -206,7 +207,7 @@ export class DialogMenu {
206
207
  handleInput(data: string): void {
207
208
  const keys = getKeybindings();
208
209
  if (keys.matches(data, "tui.select.cancel")) return this.done(undefined);
209
- if (keys.matches(data, "tui.select.confirm"))
210
+ if (keys.matches(data, "tui.select.confirm") || (this.spaceSelect && matchesKey(data, Key.space)))
210
211
  return this.done(this.getSelectedId());
211
212
  if (this.saveId && matchesKey(data, Key.ctrl("s")))
212
213
  return this.done(this.saveId);
@@ -312,7 +313,7 @@ export async function dialogMenu(
312
313
  ctx: ExtensionContext,
313
314
  title: string,
314
315
  rows: DialogRow[],
315
- options: { selectedId?: string; footer?: string; saveId?: string; renderLegend?: (theme: Theme) => string } = {},
316
+ options: { selectedId?: string; footer?: string; saveId?: string; renderLegend?: (theme: Theme) => string; spaceSelect?: boolean } = {},
316
317
  ): Promise<string | undefined> {
317
318
  return ctx.ui.custom(
318
319
  (host, theme, _keys, done) =>
@@ -326,6 +327,7 @@ export async function dialogMenu(
326
327
  options.footer,
327
328
  options.saveId,
328
329
  options.renderLegend,
330
+ options.spaceSelect,
329
331
  ),
330
332
  DIALOG_OPTIONS,
331
333
  );
@@ -1,4 +1,6 @@
1
1
  import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
2
+ import { basename } from "node:path";
3
+ import { discoverSubagentExtensions } from "../orch/extensions.ts";
2
4
  import type { ConfigStore } from "../prefs/config.ts";
3
5
  import {
4
6
  canOpenDialog,
@@ -9,6 +11,7 @@ import {
9
11
  } from "./dialog.ts";
10
12
  import {
11
13
  DEFAULT_MANAGER_SETTINGS,
14
+ settingsValueEqual,
12
15
  type CostDisplayMode,
13
16
  COST_ICONS,
14
17
  type CostIcon,
@@ -159,9 +162,9 @@ type SettingsLayers = ReturnType<typeof loadManagerSettingsLayers>;
159
162
  /** Persisted changes, not unsaved draft values; theme styling is computed on render. */
160
163
  function withProvenance(row: DialogRow, keys: (keyof ManagerSettings)[], layers: SettingsLayers): DialogRow {
161
164
  const globalChanged = keys.some((key) => layers.global[key] !== undefined &&
162
- layers.global[key] !== DEFAULT_MANAGER_SETTINGS[key]);
165
+ !settingsValueEqual(layers.global[key], DEFAULT_MANAGER_SETTINGS[key]));
163
166
  const projectChanged = keys.some((key) => layers.project[key] !== undefined &&
164
- layers.project[key] !== (layers.global[key] ?? DEFAULT_MANAGER_SETTINGS[key]));
167
+ !settingsValueEqual(layers.project[key], layers.global[key] ?? DEFAULT_MANAGER_SETTINGS[key]));
165
168
  return {
166
169
  ...row,
167
170
  renderIndicators: (theme) =>
@@ -177,6 +180,37 @@ function provenanceLegend(theme: Theme): string {
177
180
  return theme.fg("muted", "Saved: ") + `${global} Global · ${project} Current Project · ${global} ${project} Both`;
178
181
  }
179
182
 
183
+ /** Selection edits stay in the outer draft until Save and apply. */
184
+ async function configureSubagentExtensions(
185
+ ctx: ExtensionCommandContext,
186
+ draft: ManagerSettings,
187
+ agentDir: string,
188
+ ): Promise<void> {
189
+ const available = await discoverSubagentExtensions({ cwd: ctx.cwd, agentDir, projectTrusted: ctx.isProjectTrusted() });
190
+ const selected = new Set(draft.subagentExtensions === true ? available : draft.subagentExtensions || []);
191
+ // Keep stale selections visible and removable; runtime still intersects with discovery.
192
+ const files = [...new Set([...available, ...selected])].sort();
193
+ let selectedId: string | undefined;
194
+ while (true) {
195
+ const action = await dialogMenu(ctx, "[lab] Subagent extensions", [
196
+ ...files.map((file) => ({
197
+ id: file,
198
+ label: `${selected.has(file) ? "[x]" : "[ ]"} ${basename(file)}`,
199
+ value: available.includes(file) ? (selected.has(file) ? "On" : "Off") : "Unavailable",
200
+ help: `${file}\n${available.includes(file) ? "Reload this extension in newly opened subagent sessions." : "Not currently discoverable/trusted; will not load. Toggle Off to remove the saved selection."}\nSpace/Enter toggles. Changes are saved only with outer Save and apply.`,
201
+ })),
202
+ { id: "back", label: "Back", help: files.length ? "Return to settings; selection is not saved yet." : "No extensions available (configured or auto-discovered). CLI-only, inline, built-in extensions and this manager are excluded." },
203
+ ], { selectedId, spaceSelect: true, footer: "↑↓/Tab navigate · Space/Enter toggle · Esc back" });
204
+ if (!action || action === "back") {
205
+ draft.subagentExtensions = [...selected].sort();
206
+ return;
207
+ }
208
+ selectedId = action;
209
+ if (selected.has(action)) selected.delete(action);
210
+ else selected.add(action);
211
+ }
212
+ }
213
+
180
214
  /** Edits the shared draft; only the outer settings screen saves or applies it. */
181
215
  async function configureFooterDisplay(ctx: ExtensionCommandContext, draft: ManagerSettings, layers: SettingsLayers): Promise<void> {
182
216
  let selectedId: string | undefined;
@@ -421,9 +455,9 @@ async function configureAgentsDialog(
421
455
  },
422
456
  {
423
457
  id: "subagentExtensions",
424
- label: "[lab] Enable subagent extensions",
425
- value: draft.subagentExtensions ? "On" : "Off",
426
- help: "Experimental: reload configured user/trusted-project extension hooks in separate subagent sessions (not CLI-only or inline extensions). Bugs and unintended consequences may occur if hooks assume main-session state.\nRead limitations: https://github.com/championswimmer/pi-subagent-manager/blob/main/docs/subagent-extension-limitations.md\nOff by default. Save and apply affects newly opened sessions, not already-open agents.",
458
+ label: "[lab] Subagent extensions",
459
+ value: Array.isArray(draft.subagentExtensions) ? `${draft.subagentExtensions.length} selected` : draft.subagentExtensions ? "All (legacy)" : "None",
460
+ help: "Experimental: reload selected user/trusted-project extension hooks, including auto-discovered .ts/.js files and subdirectory entry points, in separate subagent sessions (not CLI-only or inline extensions). Bugs and unintended consequences may occur if hooks assume main-session state.\nRead limitations: https://github.com/championswimmer/pi-subagent-manager/blob/main/docs/subagent-extension-limitations.md\nSelect individual extensions in the submenu. None by default. Save and apply affects newly opened sessions, not already-open agents.",
427
461
  },
428
462
  checklistRow(draft.checklistIntegration, checklistStatus()),
429
463
  {
@@ -537,7 +571,7 @@ async function configureAgentsDialog(
537
571
  );
538
572
  if (styles.includes(style as LoaderStyle)) draft.loaderStyle = style as LoaderStyle;
539
573
  } else if (action === "subagentExtensions") {
540
- draft.subagentExtensions = !draft.subagentExtensions;
574
+ await configureSubagentExtensions(ctx, draft, options.agentDir);
541
575
  } else if (action === "checklistIntegration") {
542
576
  const status = checklistStatus();
543
577
  // Turning Off is always allowed; turning On requires current eligibility.