pi-subagent-manager 0.3.2 → 0.5.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
@@ -126,7 +126,7 @@ Project types override global types. Malformed definitions and same-scope duplic
126
126
 
127
127
  ### Import existing agents
128
128
 
129
- On the first interactive TUI session, the manager discovers external definitions read-only and offers an import. After accepting, a **checkbox picker** lets you choose individual agents; nothing is selected by default. **↑↓** navigates, **Space** toggles a row, **Ctrl+A** toggles all, **Enter** submits (an empty selection skips), and **Esc** cancels. `/agents import` opens the picker again later, including after declining or cancelling.
129
+ On the first interactive TUI session with subagents enabled, the manager discovers external definitions read-only and offers an import. **Off** mode suppresses this automatic offer. After accepting, a **checkbox picker** lets you choose individual agents; nothing is selected by default. **↑↓** navigates, **Space** toggles a row, **Ctrl+A** toggles all, **Enter** submits (an empty selection skips), and **Esc** cancels. `/agents import` opens the picker again later, including after declining or cancelling.
130
130
 
131
131
  The current session's model receives **only the selected file paths**, applicable source settings paths, the exact destination schema, current scoped models/tools, and detailed field-by-field migration instructions. It reads and writes the definitions itself in the existing conversation—there is **no deterministic conversion code** or separate importer agent/session. Originals remain untouched. Unsupported capabilities, lost security restrictions, unavailable models and collisions must be explained and approved before writing; compatible definitions need no second all-or-nothing selection. Definitions reload after model turns, or explicitly with `/agents reload`.
132
132
 
@@ -140,10 +140,10 @@ Automatic project discovery requires project trust. Only agent definitions are o
140
140
 
141
141
  ### Configuration and thread UI
142
142
 
143
- - `/agents types`: open the bordered agent-definition browser and two-column editor: **field names** on the left, **current values** on the right. **↑↓/Tab** selects fields, **Enter** edits, **Ctrl+S** saves, and **Esc** discards the draft. Multiline field dialogs use **Enter** for a newline and **Ctrl+S** to apply to the draft. Edit the system prompt, models, thinking, tools, color and save scope. Model preferences use an ordered picker: add available models (scoped entries are marked), remove entries, and move them up/down. The YAML editor edits the header together; **External editor** edits the whole Markdown file using `$VISUAL`, `$EDITOR`, or `vi`.
143
+ - `/agents types`: open the bordered agent-definition browser and two-column editor: **field names** on the left, **current values** on the right. **↑↓/Tab** selects fields, **Enter** edits, **Ctrl+S** saves, and **Esc** discards the draft. Multiline field dialogs use **Enter** for a newline and **Ctrl+S** to apply to the draft. Edit the system prompt, models, thinking, tools, color and save scope. Model preferences use an ordered picker: add available models (scoped entries are marked), remove entries, and move them up/down. When adding or replacing a model, [fuzzysort](https://github.com/farzher/fuzzysort) fuzzy-matches the draft's `modelSuggestions` against provider/id and display name: scoped matches first, other matches next (ranked by best match score), then remaining models alphabetically without duplicates. Typing filters these groups; without suggestions the list is alphabetical. Suggestions only aid selection and never change runtime model resolution. The YAML editor edits the header together; **External editor** edits the whole Markdown file using `$VISUAL`, `$EDITOR`, or `vi`.
144
144
  - `/agents import`: select individual external definitions for model-driven migration.
145
145
  - `/agents reload`: reload definitions and show diagnostics.
146
- - `/agents` or `/agents settings`: open a bordered settings dialog. Edit level, concurrency and retained-thread limits, toggle **Scoped model filtering**, choose global or trusted-project scope, and save with **Ctrl+S**. Settings apply immediately without interrupting existing work. **Agent definitions** opens the type editor.
146
+ - `/agents` or `/agents settings`: open a bordered settings dialog. Choose **Subagent Mode** (**Off**, **Opportunistic**, or **Orchestration**), edit level, concurrency and retained-thread limits, toggle **Scoped model filtering**, choose global or trusted-project scope, and save with **Ctrl+S**. The mode field and chooser explain each option. Settings apply immediately without interrupting existing work. **Agent definitions** opens the type editor.
147
147
  - `/agents tree`: open a live, bordered tree of all retained agents, including running and paused sessions. **↑↓** select, **←→** collapse/expand, **PgUp/PgDn** scroll, **Enter** inspects the selected thread, **Esc** close. The dialog refreshes every second and preserves selection. An optional path preselects that agent, for example `/agents tree /root/controller-security-research`.
148
148
  - `/agents status`: alias of `/agents tree`.
149
149
 
@@ -192,11 +192,20 @@ Settings belong to **this extension**, not another subagent package:
192
192
  "maxLevels": 3,
193
193
  "maxConcurrent": 16,
194
194
  "maxThreads": 64,
195
- "scopedModelFiltering": true
195
+ "scopedModelFiltering": true,
196
+ "subagentMode": "opportunistic"
196
197
  }
197
198
  ```
198
199
 
199
- All keys are optional. `maxLevels` includes the main conversation as **L1**: the default permits L2 children and L3 grandchildren, but no L4. An independent root such as `/k` is still L2, so independent paths cannot bypass the limit. `maxLevels: 1` disables new children; supported values are integers from 1 to 32.
200
+ All keys are optional. `subagentMode` controls tool availability and concise system-prompt guidance:
201
+
202
+ - **`off`**: hide subagent tools and inject no subagent guidance. The main model is not told about this plugin; the automatic import offer, thread widget and root notifications are suppressed. `/agents` remains available to change settings or inspect retained threads.
203
+ - **`opportunistic`** (default): expose subagent tools and tell the main model to delegate only parallelizable or very large tasks; otherwise work directly.
204
+ - **`orchestration`**: expose subagent tools and tell `/root` to delegate all task execution. It only coordinates and synthesizes subagent results. This is a prompt policy, not a tool sandbox; the root-only rule is not inherited by workers.
205
+
206
+ Mode changes apply immediately without canceling running work or discarding retained sessions. Agent import requires **opportunistic** mode because migration uses the main thread's file tools; it is not offered automatically in orchestration mode.
207
+
208
+ `maxLevels` includes the main conversation as **L1**: the default permits L2 children and L3 grandchildren, but no L4. An independent root such as `/k` is still L2, so independent paths cannot bypass the limit. `maxLevels: 1` disables new children; supported values are integers from 1 to 32.
200
209
 
201
210
  `maxConcurrent` counts starting/running threads **across the entire tree**, including parents waiting for children; `maxThreads` counts all retained threads. Both require positive safe integers. Capacity exhaustion fails clearly rather than queuing. Omitted settings use the defaults above. Unknown keys, malformed values and symlinked settings paths produce warnings; an invalid file is ignored atomically, preserving the preceding valid layer/defaults.
202
211
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
@@ -45,6 +45,7 @@
45
45
  "format:check": "prettier --check --print-width 100 src tests agents .github docs/default-agents.md README.md"
46
46
  },
47
47
  "dependencies": {
48
+ "fuzzysort": "^4.0.2",
48
49
  "shell-quote": "^1.8.3",
49
50
  "yaml": "^2.8.1"
50
51
  },
package/src/dialog.ts CHANGED
@@ -29,10 +29,10 @@ export interface DialogEditorHost extends DialogHost {
29
29
  export interface DialogRow {
30
30
  id: string;
31
31
  label: string;
32
- labelPrefix?: { text: string; color: Parameters<Theme["fg"]>[0] };
33
32
  /** Trusted formatter receives sanitized text; generated ANSI styling is kept when clipping. */
34
33
  renderLabel?: (label: string, theme: Theme) => string;
35
34
  value?: string;
35
+ valueColor?: Parameters<Theme["fg"]>[0];
36
36
  help?: string;
37
37
  }
38
38
  export const DIALOG_OPTIONS = {
@@ -245,21 +245,19 @@ export class DialogMenu {
245
245
  ...this.rows.slice(start, start + this.viewport).map((row, i) => {
246
246
  const selected = start + i === this.selected;
247
247
  const color = (text: string) => selected ? this.theme.fg("accent", text) : text;
248
- const prefix = row.labelPrefix
249
- ? truncateToWidth(`${dialogText(row.labelPrefix.text)} `, labelWidth, "")
250
- : "";
251
248
  const plainLabel = dialogText(row.label);
252
249
  const label = truncateToWidth(
253
250
  row.renderLabel ? row.renderLabel(plainLabel, this.theme) : plainLabel,
254
- labelWidth - visibleWidth(prefix),
251
+ labelWidth,
255
252
  "",
256
253
  true,
257
254
  );
258
- const padding = " ".repeat(Math.max(0, labelWidth - visibleWidth(prefix) - visibleWidth(label)));
255
+ const padding = " ".repeat(Math.max(0, labelWidth - visibleWidth(label)));
256
+ const value = dialogText(row.value ?? "");
259
257
  return color(`${selected ? "›" : " "} `)
260
- + (row.labelPrefix ? this.theme.fg(row.labelPrefix.color, prefix) : "")
261
258
  + (row.renderLabel ? label : color(label))
262
- + color(`${padding} │ ${dialogText(row.value ?? "")}`);
259
+ + color(`${padding} │ `)
260
+ + (row.valueColor ? this.theme.fg(row.valueColor, value) : color(value));
263
261
  }),
264
262
  "",
265
263
  ...help.map((line) => this.theme.fg("muted", ` ${line}`)),
package/src/index.ts CHANGED
@@ -5,10 +5,11 @@ import { fuzzyFilter } from "@earendil-works/pi-tui";
5
5
  import { ConfigStore } from "./config.ts";
6
6
  import { IMPORT_REQUEST_PREFIX, markImportOffered, offerAgentImport } from "./agent-import.ts";
7
7
  import { ThreadManager } from "./manager.ts";
8
- import { DEFAULT_MANAGER_SETTINGS, loadManagerSettings } from "./settings.ts";
8
+ import { loadManagerSettings } from "./settings.ts";
9
9
  import { configureAgents } from "./settings-ui.ts";
10
10
  import { showAgentStatus, showAgentTree } from "./status-ui.ts";
11
11
  import { createDriverFactory } from "./runtime.ts";
12
+ import { subagentPrompt } from "./prompt.ts";
12
13
  import { agentTools } from "./tools.ts";
13
14
  import { editAgentTypes, updateWidget } from "./ui.ts";
14
15
  import type { SavedThread, ThreadEvent } from "./types.ts";
@@ -29,7 +30,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
29
30
  includeProject: false,
30
31
  });
31
32
  let manager: ThreadManager | undefined;
32
- let limits = { ...DEFAULT_MANAGER_SETTINGS };
33
+ let limits = loadManagerSettings({
34
+ cwd: process.cwd(),
35
+ agentDir: getAgentDir(),
36
+ includeProject: false,
37
+ }).settings;
33
38
  const loadLimits = (ctx: ExtensionContext) => {
34
39
  const loaded = loadManagerSettings({
35
40
  cwd: ctx.cwd,
@@ -44,6 +49,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
44
49
  let migrationRequested = false;
45
50
  let importInProgress = false;
46
51
  const importAgents = async (ctx: ExtensionContext, firstRun: boolean) => {
52
+ // Migration requires the root's file tools and must not delegate source prompts.
53
+ if (limits.subagentMode === "orchestration") {
54
+ if (!firstRun)
55
+ ctx.ui.notify("Agent import requires Opportunistic mode. Change Subagent Mode in /agents settings.", "info");
56
+ return;
57
+ }
47
58
  if (importInProgress) return;
48
59
  importInProgress = true;
49
60
  try {
@@ -59,7 +70,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
59
70
  };
60
71
  // A migration can span clarification turns. Reload after each root turn, without converting files.
61
72
  pi.on("agent_end", async () => {
62
- if (!migrationRequested) return;
73
+ if (limits.subagentMode === "off" || !migrationRequested) return;
63
74
  store.reload();
64
75
  if (store.diagnostics.length) context?.ui.notify(store.diagnostics.join("\n"), "warning");
65
76
  });
@@ -85,10 +96,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
85
96
  }
86
97
  };
87
98
  const warnDelivery = (error: unknown) => {
99
+ if (limits.subagentMode === "off") return;
88
100
  const message = error instanceof Error ? error.message : String(error);
89
101
  context?.ui.notify(`Subagent delivery failed: ${message}`, "warning");
90
102
  };
91
- const sendRootNotification = (notification: RootNotification) =>
103
+ const sendRootNotification = (notification: RootNotification) => {
104
+ if (limits.subagentMode === "off" || context?.isIdle?.() === false) return;
105
+ // Never submit to Pi's streaming queue: off must also suppress pending delivery.
92
106
  pi.sendMessage(
93
107
  {
94
108
  customType: "pi-subagent:update",
@@ -98,7 +112,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
98
112
  },
99
113
  { triggerTurn: false },
100
114
  );
115
+ };
101
116
  const restoreRootMailbox = (ctx: ExtensionContext) => {
117
+ if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
102
118
  const entries = ctx.sessionManager.getBranch();
103
119
  const delivered = new Set(
104
120
  entries.flatMap((entry) => {
@@ -121,6 +137,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
121
137
  }
122
138
  }
123
139
  };
140
+ pi.on("agent_settled", async (_event, ctx) => {
141
+ if (context?.sessionManager === ctx.sessionManager) restoreRootMailbox(ctx);
142
+ });
124
143
  const delivery = (event: ThreadEvent) => {
125
144
  if (event.kind === "change" || event.kind === "metrics") return;
126
145
  const thread = event.thread;
@@ -141,8 +160,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
141
160
  state: thread.state,
142
161
  },
143
162
  };
144
- // Root sendMessage can defer while streaming too. Accept durably before queueing;
145
- // the eventual transcript message carries its ID for branch-local recovery.
163
+ // Persist first; defer delivery until the root is idle and the plugin is enabled.
164
+ // The eventual transcript message carries its ID for branch-local recovery.
146
165
  pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
147
166
  sendRootNotification(notification);
148
167
  } else void requireManager().deliver(event.recipient, message).catch(warnDelivery);
@@ -151,9 +170,34 @@ export default function piSubagent(pi: ExtensionAPI): void {
151
170
  }
152
171
  };
153
172
 
154
- for (const tool of agentTools(requireManager, "/root", () => store.list())) pi.registerTool(tool);
173
+ const rootTools = agentTools(requireManager, "/root", () => store.list());
174
+ let toolsEnabled: boolean | undefined;
175
+ const syncTools = () => {
176
+ const enabled = limits.subagentMode !== "off";
177
+ if (toolsEnabled === enabled) return;
178
+ toolsEnabled = enabled;
179
+ for (const tool of rootTools) {
180
+ pi.registerTool({
181
+ ...tool,
182
+ // Hidden tools are neither model-visible nor discoverable/callable via codemode.
183
+ exposure: enabled ? "direct" : "hidden",
184
+ execute: (...args) => {
185
+ if (limits.subagentMode === "off") throw new Error("Subagent Mode is off");
186
+ return tool.execute(...args);
187
+ },
188
+ });
189
+ }
190
+ };
191
+ const refreshWidget = (ctx: ExtensionContext) => {
192
+ if (limits.subagentMode === "off") {
193
+ if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
194
+ } else updateWidget(ctx, requireManager().list());
195
+ };
196
+ syncTools();
155
197
  pi.on("before_agent_start", async (event, ctx) => {
156
- if (event.prompt.startsWith(IMPORT_REQUEST_PREFIX)) {
198
+ const prompt = subagentPrompt(limits);
199
+ if (!prompt) return;
200
+ if (limits.subagentMode === "opportunistic" && event.prompt.startsWith(IMPORT_REQUEST_PREFIX)) {
157
201
  try {
158
202
  markImportOffered(getAgentDir());
159
203
  } catch (error) {
@@ -161,12 +205,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
161
205
  }
162
206
  }
163
207
  return {
164
- systemPrompt: `${event.systemPrompt}\n\n## pi-subagent\nYou are /root. Thread paths determine context ancestry, independently of agent type. Name children with concise task-based kebab-case paths (e.g. /root/controller-security-research), not their type name. Children can pause WITHOUT handing back an answer; completed and paused sessions can both receive more work via agent_steer. Working child threads appear above the footer. The main conversation is L1; the maximum is ${limits.maxLevels} levels including L1. For independent work, spawn all siblings with wait:false before calling agent_wait; the same pattern applies inside child agents that have delegation tools. Waiting parents count toward the shared ${limits.maxConcurrent}-thread concurrency limit. Available types:\n${store
165
- .list()
166
- .map((type) => `- ${type.name}: ${type.description}`)
167
- .join(
168
- "\n",
169
- )}\nUse agent_status to inspect and agent_wait to wait. Detached notifications do not automatically resume your turn.`,
208
+ systemPrompt: `${event.systemPrompt}\n\n${prompt}`,
170
209
  };
171
210
  });
172
211
 
@@ -182,6 +221,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
182
221
  });
183
222
  persistenceSignature = "";
184
223
  const settingsDiagnostics = loadLimits(ctx);
224
+ syncTools();
185
225
  const instance = new ThreadManager({
186
226
  ...limits,
187
227
  createDriver: createDriverFactory(requireContext, () => limits.scopedModelFiltering),
@@ -190,7 +230,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
190
230
  toolsFor: (path) => agentTools(requireManager, path, () => store.list()),
191
231
  onEvent: (event) => {
192
232
  if (token !== generation) return;
193
- updateWidget(requireContext(), requireManager().list());
233
+ refreshWidget(requireContext());
194
234
  if (event.kind !== "metrics") persist();
195
235
  delivery(event);
196
236
  },
@@ -214,17 +254,19 @@ export default function piSubagent(pi: ExtensionAPI): void {
214
254
  instance.restore(data.threads);
215
255
  else persist();
216
256
  } catch (error) {
217
- ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
257
+ if (limits.subagentMode !== "off")
258
+ ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
218
259
  }
219
260
  }
220
261
  restoreRootMailbox(ctx);
221
- updateWidget(ctx, requireManager().list());
262
+ refreshWidget(ctx);
222
263
  const diagnostics = [...store.diagnostics, ...settingsDiagnostics];
223
- if (diagnostics.length) ctx.ui.notify(diagnostics.join("\n"), "warning");
264
+ if (limits.subagentMode !== "off" && diagnostics.length)
265
+ ctx.ui.notify(diagnostics.join("\n"), "warning");
224
266
  };
225
267
  pi.on("session_start", async (_event, ctx) => {
226
268
  await attachSession(ctx);
227
- await importAgents(ctx, true);
269
+ if (limits.subagentMode !== "off") await importAgents(ctx, true);
228
270
  });
229
271
  pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
230
272
  const stopWorkingThreads = async () => {
@@ -279,6 +321,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
279
321
  store.reload();
280
322
  const diagnostics = [...store.diagnostics, ...loadLimits(ctx)];
281
323
  requireManager().setLimits(limits);
324
+ syncTools();
325
+ refreshWidget(ctx);
326
+ restoreRootMailbox(ctx);
282
327
  ctx.ui.notify(
283
328
  diagnostics.length
284
329
  ? diagnostics.join("\n")
@@ -293,6 +338,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
293
338
  apply: () => {
294
339
  const diagnostics = loadLimits(ctx);
295
340
  requireManager().setLimits(limits);
341
+ syncTools();
342
+ refreshWidget(ctx);
343
+ restoreRootMailbox(ctx);
296
344
  if (diagnostics.length) ctx.ui.notify(diagnostics.join("\n"), "warning");
297
345
  },
298
346
  });
@@ -1,3 +1,4 @@
1
+ import fuzzysort, { type SnapshotKeys } from "fuzzysort";
1
2
  import type { Api, Model } from "@earendil-works/pi-ai";
2
3
  import {
3
4
  getSelectListTheme,
@@ -7,7 +8,6 @@ import {
7
8
  } from "@earendil-works/pi-coding-agent";
8
9
  import {
9
10
  Container,
10
- fuzzyFilter,
11
11
  getKeybindings,
12
12
  Input,
13
13
  SelectList,
@@ -31,6 +31,10 @@ export const MODEL_EDITOR_CANCEL = Symbol("model-editor-cancel");
31
31
 
32
32
  type AvailableModel = Pick<Model<Api>, "provider" | "id" | "name">;
33
33
 
34
+ interface ModelSelectItem extends SelectItem {
35
+ group?: string;
36
+ }
37
+
34
38
  type ModelEditorMode =
35
39
  | { kind: "menu" }
36
40
  | { kind: "actions"; index: number }
@@ -46,6 +50,7 @@ interface OrderedModelEditorComponentOptions {
46
50
  availableModels: readonly AvailableModel[];
47
51
  scopedModels: readonly ScopedModel[];
48
52
  initialModels?: readonly string[];
53
+ modelSuggestions?: readonly string[];
49
54
  onDone(models: string[]): void;
50
55
  onCancel(): void;
51
56
  }
@@ -58,6 +63,13 @@ function renderModelIdentity(identity: string): string {
58
63
  return sanitizeModelText(identity);
59
64
  }
60
65
 
66
+ function modelSearchText(text: string): string {
67
+ // Providers spell the same version differently (sonnet-5.5 vs sonnet-5-5).
68
+ // Strip separators rather than splitting them into repeated numeric terms;
69
+ // raw identities and labels remain untouched.
70
+ return sanitizeModelText(text).replace(/[._:/-]+/g, "");
71
+ }
72
+
61
73
  function sortModels(models: readonly AvailableModel[]): AvailableModel[] {
62
74
  const unique = new Map<string, AvailableModel>();
63
75
  for (const model of models) unique.set(modelIdentity(model), model);
@@ -80,19 +92,6 @@ function describeModel(
80
92
  return [name, annotation].filter(Boolean).join(" · ");
81
93
  }
82
94
 
83
- function buildSearchText(
84
- model: AvailableModel,
85
- scopedIdentities: ReadonlySet<string>,
86
- ): string {
87
- return [
88
- renderModelIdentity(modelIdentity(model)),
89
- sanitizeModelText(model.name),
90
- describeModel(model, scopedIdentities),
91
- ]
92
- .filter(Boolean)
93
- .join(" ");
94
- }
95
-
96
95
  export class OrderedModelEditorComponent extends Container {
97
96
  private readonly tui: {
98
97
  requestRender(force?: boolean): void;
@@ -100,6 +99,8 @@ export class OrderedModelEditorComponent extends Container {
100
99
  };
101
100
  private readonly theme: Theme;
102
101
  private readonly allModels: readonly AvailableModel[];
102
+ private readonly modelSearch: SnapshotKeys<AvailableModel>;
103
+ private readonly suggestedScores: ReadonlyMap<string, number>;
103
104
  private readonly modelsByIdentity = new Map<string, AvailableModel>();
104
105
  private readonly scopedIdentities: ReadonlySet<string>;
105
106
  private readonly onDone: (models: string[]) => void;
@@ -112,7 +113,7 @@ export class OrderedModelEditorComponent extends Container {
112
113
  private mode: ModelEditorMode;
113
114
  private pickerQuery = "";
114
115
  private pickerSelectedValue: string | undefined;
115
- private currentItems: SelectItem[] = [];
116
+ private currentItems: ModelSelectItem[] = [];
116
117
  private selectList = new SelectList(
117
118
  [],
118
119
  1,
@@ -130,6 +131,15 @@ export class OrderedModelEditorComponent extends Container {
130
131
  this.tui = options.tui;
131
132
  this.theme = options.theme;
132
133
  this.allModels = sortModels(options.availableModels);
134
+ // The registry is fixed for this dialog; prepare searchable fields once.
135
+ // Scope annotations deliberately aren't searchable model metadata.
136
+ this.modelSearch = fuzzysort.snapshot(this.allModels, {
137
+ keys: [
138
+ (model) => modelSearchText(modelIdentity(model)),
139
+ (model) => modelSearchText(model.name),
140
+ ],
141
+ });
142
+ this.suggestedScores = this.searchScores(options.modelSuggestions ?? []);
133
143
  this.onDone = options.onDone;
134
144
  this.onCancel = options.onCancel;
135
145
  for (const model of this.allModels)
@@ -192,17 +202,31 @@ export class OrderedModelEditorComponent extends Container {
192
202
  if (this.searchInput) header.push(...this.searchInput.render(inner));
193
203
  const budget = Math.max(1, height - 4 - header.length);
194
204
  const selected = this.selectList.getSelectedItem()?.value;
205
+ // Headings are visual rows only: keyboard navigation selects models, not groups.
206
+ const displayRows: (ModelSelectItem | string)[] = [];
207
+ let previousGroup: string | undefined;
208
+ for (const item of this.currentItems) {
209
+ if (item.group && item.group !== previousGroup) {
210
+ displayRows.push(item.group);
211
+ }
212
+ previousGroup = item.group;
213
+ displayRows.push(item);
214
+ }
195
215
  const index = Math.max(
196
216
  0,
197
- this.currentItems.findIndex((item) => item.value === selected),
217
+ displayRows.findIndex(
218
+ (row) => typeof row !== "string" && row.value === selected,
219
+ ),
198
220
  );
199
221
  const start = Math.max(
200
222
  0,
201
- Math.min(index - budget + 1, this.currentItems.length - budget),
223
+ Math.min(index - budget + 1, displayRows.length - budget),
202
224
  );
203
- const rows = this.currentItems.slice(start, start + budget).map((item) => {
204
- const text = `${item.value === selected ? "›" : " "} ${item.label} ${this.theme.fg("muted", item.description ?? "")}`;
205
- return item.value === selected ? this.theme.fg("accent", text) : text;
225
+ // Only format visible rows; a registry can contain thousands of models.
226
+ const rows = displayRows.slice(start, start + budget).map((row) => {
227
+ if (typeof row === "string") return this.theme.fg("muted", row);
228
+ const text = `${row.value === selected ? "›" : " "} ${row.label} ${this.theme.fg("muted", row.description ?? "")}`;
229
+ return row.value === selected ? this.theme.fg("accent", text) : text;
206
230
  });
207
231
  if (!rows.length) rows.push(this.theme.fg("muted", "No matching models"));
208
232
  return frameDialog(
@@ -440,7 +464,9 @@ export class OrderedModelEditorComponent extends Container {
440
464
  this.theme.fg(
441
465
  "muted",
442
466
  this.withScopeWarning(
443
- "Search by provider/id or model name. Already-selected duplicates are hidden.",
467
+ this.suggestedScores.size
468
+ ? "Suggested matches: scoped first, then other models; the rest A–Z. Type to search."
469
+ : "Search by provider/id or model name. Models A–Z; selected duplicates are hidden.",
444
470
  ),
445
471
  ),
446
472
  );
@@ -544,23 +570,71 @@ export class OrderedModelEditorComponent extends Container {
544
570
  return list;
545
571
  }
546
572
 
547
- private getPickerItems(replaceIndex: number | undefined): SelectItem[] {
573
+ private searchScores(queries: readonly string[]): Map<string, number> {
574
+ const scores = new Map<string, number>();
575
+ const uniqueQueries = new Set(
576
+ queries.map((query) => modelSearchText(query).trim()).filter(Boolean),
577
+ );
578
+ for (const query of uniqueQueries) {
579
+ // Both defaults are restrictive (10 results, score >= .5); collect every
580
+ // fuzzy match so suggestions aren't silently capped or omitted.
581
+ for (const result of fuzzysort.go(query, this.modelSearch, {
582
+ limit: 0,
583
+ threshold: 0,
584
+ })) {
585
+ const identity = modelIdentity(result.obj);
586
+ scores.set(identity, Math.max(scores.get(identity) ?? 0, result.score));
587
+ }
588
+ }
589
+ return scores;
590
+ }
591
+
592
+ private getPickerItems(replaceIndex: number | undefined): ModelSelectItem[] {
548
593
  const excluded = new Set(
549
594
  this.draft.filter((_, index) => index !== replaceIndex),
550
595
  );
551
- const available = this.allModels.filter(
552
- (model) => !excluded.has(modelIdentity(model)),
553
- );
554
- const filtered = this.pickerQuery
555
- ? fuzzyFilter(available, this.pickerQuery, (model) =>
556
- buildSearchText(model, this.scopedIdentities),
557
- )
558
- : available;
559
- return filtered.map((model) => ({
560
- value: modelIdentity(model),
561
- label: renderModelIdentity(modelIdentity(model)),
562
- description: describeModel(model, this.scopedIdentities),
563
- }));
596
+ const query = this.pickerQuery.trim();
597
+ const queryScores = query ? this.searchScores([query]) : undefined;
598
+ const scoped: AvailableModel[] = [];
599
+ const other: AvailableModel[] = [];
600
+ const remaining: AvailableModel[] = [];
601
+ for (const model of this.allModels) {
602
+ const identity = modelIdentity(model);
603
+ if (excluded.has(identity) || (queryScores && !queryScores.has(identity)))
604
+ continue;
605
+ if (this.suggestedScores.has(identity)) {
606
+ (this.scopedIdentities.has(identity) ? scoped : other).push(model);
607
+ } else {
608
+ remaining.push(model);
609
+ }
610
+ }
611
+ const bySuggestionScore = (a: AvailableModel, b: AvailableModel) =>
612
+ this.suggestedScores.get(modelIdentity(b))! -
613
+ this.suggestedScores.get(modelIdentity(a))!;
614
+ // Stable score sorting preserves alphabetical order for ties. The last
615
+ // tier retains the registry's alphabetical order, irrespective of scope.
616
+ scoped.sort(bySuggestionScore);
617
+ other.sort(bySuggestionScore);
618
+ const items = (
619
+ models: AvailableModel[],
620
+ group: string,
621
+ ): ModelSelectItem[] =>
622
+ models.map((model) => ({
623
+ value: modelIdentity(model),
624
+ label: renderModelIdentity(modelIdentity(model)),
625
+ description: describeModel(model, this.scopedIdentities),
626
+ group,
627
+ }));
628
+ return [
629
+ ...items(scoped, "Suggested matches · scoped models"),
630
+ ...items(other, "Suggested matches · other models"),
631
+ ...items(
632
+ remaining,
633
+ scoped.length || other.length
634
+ ? "All other models · A–Z"
635
+ : "All models · A–Z",
636
+ ),
637
+ ];
564
638
  }
565
639
 
566
640
  private describeDraftIdentity(identity: string): string {
@@ -580,6 +654,7 @@ export class OrderedModelEditorComponent extends Container {
580
654
  export async function editModelPreferences(
581
655
  ctx: ExtensionCommandContext,
582
656
  currentModels?: readonly string[],
657
+ modelSuggestions?: readonly string[],
583
658
  ): Promise<readonly string[] | typeof MODEL_EDITOR_CANCEL> {
584
659
  if (ctx.mode !== "tui") {
585
660
  if (ctx.hasUI) {
@@ -603,6 +678,7 @@ export async function editModelPreferences(
603
678
  availableModels,
604
679
  scopedModels: ctx.scopedModels,
605
680
  initialModels: currentModels,
681
+ modelSuggestions,
606
682
  onDone: (models) => done(models),
607
683
  onCancel: () => done(MODEL_EDITOR_CANCEL),
608
684
  }),
package/src/prompt.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { ManagerSettings } from "./settings.ts";
2
+
3
+ /** Root-only guidance: child SDK sessions use their own worker prompt. */
4
+ export function subagentPrompt(settings: ManagerSettings): string | undefined {
5
+ if (settings.subagentMode === "off") return undefined;
6
+ const policy =
7
+ settings.subagentMode === "orchestration"
8
+ ? "Orchestration mode: /root only coordinates. Delegate every user task to subagents, even small or sequential tasks. Do not inspect/edit files, run commands, research, or execute task work yourself. Only plan, assign, monitor, clarify, and synthesize subagent results for the user. This restriction applies only to /root; subagents execute the work."
9
+ : "Opportunistic mode: do ordinary tasks yourself. Delegate only when work can be parallelized or a task is very large; do not spawn agents for small, straightforward tasks.";
10
+ return [
11
+ "## pi-subagent",
12
+ "You are /root, the main conversation (L1).",
13
+ policy,
14
+ "Call agent_types before choosing a type. Name children by task using kebab-case paths (e.g. /root/security-review), not type names. Paths determine context ancestry; independent roots inherit no history.",
15
+ "For independent parallel work, spawn all siblings with wait:false before agent_wait. Use agent_status to inspect, agent_wait to wait, and agent_output for full results. Detached notifications do not resume your turn.",
16
+ "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
17
+ `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
18
+ ].join("\n");
19
+ }
@@ -10,6 +10,7 @@ import {
10
10
  DEFAULT_MANAGER_SETTINGS,
11
11
  saveManagerSettings,
12
12
  type ManagerSettings,
13
+ type SubagentMode,
13
14
  } from "./settings.ts";
14
15
  import { editAgentTypes } from "./ui.ts";
15
16
 
@@ -31,6 +32,30 @@ const FIELDS = [
31
32
  },
32
33
  ] as const;
33
34
 
35
+ const MODE_OPTIONS = [
36
+ {
37
+ id: "off",
38
+ label: "Off",
39
+ value: "No subagent tools or prompt guidance",
40
+ help: "Off: hide subagent tools and inject no subagent guidance into the system prompt. Existing work and retained sessions are kept.",
41
+ },
42
+ {
43
+ id: "opportunistic",
44
+ label: "Opportunistic",
45
+ value: "Parallelizable or very large tasks only",
46
+ help: "Opportunistic: make subagent tools available. Delegate only when tasks can be parallelized or a task is very large; otherwise work directly.",
47
+ },
48
+ {
49
+ id: "orchestration",
50
+ label: "Orchestration",
51
+ value: "/root coordinates; subagents execute",
52
+ help: "Orchestration: tell /root to delegate all task execution to subagents and only coordinate and synthesize results. This rule is not inherited by workers.",
53
+ },
54
+ ] as const;
55
+
56
+ const MODE_HELP =
57
+ "Off: no subagent tools or prompt guidance. Opportunistic: delegate only parallelizable or very large tasks. Orchestration: /root delegates all execution and only coordinates and synthesizes results.";
58
+
34
59
  const SCOPED_MODEL_FILTERING = {
35
60
  id: "scopedModelFiltering",
36
61
  label: "Scoped model filtering",
@@ -70,6 +95,12 @@ async function configureAgentsDialog(
70
95
  ctx,
71
96
  `Agents settings${dirty ? " · unsaved" : ""}`,
72
97
  [
98
+ {
99
+ id: "subagentMode",
100
+ label: "Subagent Mode",
101
+ value: MODE_OPTIONS.find((mode) => mode.id === draft.subagentMode)!.label,
102
+ help: MODE_HELP,
103
+ },
73
104
  ...FIELDS.map((field) => ({
74
105
  ...field,
75
106
  value: String(draft[field.id]),
@@ -102,7 +133,8 @@ async function configureAgentsDialog(
102
133
  {
103
134
  id: "save",
104
135
  label: "Save and apply",
105
- labelPrefix: dirty ? { text: "(changes)", color: "warning" as const } : undefined,
136
+ value: dirty ? "(changes)" : undefined,
137
+ valueColor: dirty ? "warning" as const : undefined,
106
138
  help: "Save all values to the selected scope and reload settings now. Project overrides still take precedence. Running agents and retained sessions are kept.",
107
139
  },
108
140
  {
@@ -138,6 +170,12 @@ async function configureAgentsDialog(
138
170
  )
139
171
  throw new Error(field.help);
140
172
  draft[field.id] = number;
173
+ } else if (action === "subagentMode") {
174
+ const mode = await dialogMenu(ctx, "Subagent Mode", [...MODE_OPTIONS], {
175
+ selectedId: draft.subagentMode,
176
+ });
177
+ if (MODE_OPTIONS.some((option) => option.id === mode))
178
+ draft.subagentMode = mode as SubagentMode;
141
179
  } else if (action === "scopedModelFiltering") {
142
180
  draft.scopedModelFiltering = !draft.scopedModelFiltering;
143
181
  } else if (action === "scope") {
package/src/settings.ts CHANGED
@@ -13,7 +13,11 @@ import {
13
13
  } from "node:fs";
14
14
  import { dirname, join, resolve } from "node:path";
15
15
 
16
+ export const SUBAGENT_MODES = ["off", "opportunistic", "orchestration"] as const;
17
+ export type SubagentMode = (typeof SUBAGENT_MODES)[number];
18
+
16
19
  export interface ManagerSettings {
20
+ subagentMode: SubagentMode;
17
21
  maxLevels: number;
18
22
  maxConcurrent: number;
19
23
  maxThreads: number;
@@ -25,9 +29,12 @@ export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
25
29
  maxConcurrent: 16,
26
30
  maxThreads: 64,
27
31
  scopedModelFiltering: true,
32
+ subagentMode: "opportunistic",
28
33
  };
29
34
 
30
- const KEYS = ["maxLevels", "maxConcurrent", "maxThreads", "scopedModelFiltering"] as const;
35
+ const KEYS = [
36
+ "maxLevels", "maxConcurrent", "maxThreads", "scopedModelFiltering", "subagentMode",
37
+ ] as const;
31
38
  const MAX_LEVELS = 32;
32
39
 
33
40
  function errorCode(error: unknown): string | undefined {
@@ -64,6 +71,7 @@ function positiveSafeInteger(value: unknown): value is number {
64
71
  }
65
72
 
66
73
  function requirement(key: (typeof KEYS)[number]): string {
74
+ if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
67
75
  return key === "scopedModelFiltering"
68
76
  ? "scopedModelFiltering must be a boolean"
69
77
  : `${key} must be a positive safe integer`;
@@ -88,6 +96,11 @@ function parseSettings(content: string): Partial<ManagerSettings> {
88
96
  for (const key of KEYS) {
89
97
  if (!Object.hasOwn(record, key)) continue;
90
98
  const value = record[key];
99
+ if (key === "subagentMode") {
100
+ if (!SUBAGENT_MODES.includes(value as SubagentMode)) throw new Error(requirement(key));
101
+ layer.subagentMode = value as SubagentMode;
102
+ continue;
103
+ }
91
104
  if (key === "scopedModelFiltering") {
92
105
  if (typeof value !== "boolean") throw new Error(requirement(key));
93
106
  layer.scopedModelFiltering = value;
package/src/ui.ts CHANGED
@@ -1062,12 +1062,14 @@ async function editAgentTypesDialog(
1062
1062
  let draft: AgentType = original
1063
1063
  ? structuredClone(original)
1064
1064
  : { name: "new-agent", description: "New agent", systemPrompt: "" };
1065
+ const originalContent = serializeAgentType(draft);
1065
1066
  let selectedId: string | undefined;
1066
1067
  let saveScope: "user" | "project" =
1067
1068
  original?.source === "project" && store.canSaveProject()
1068
1069
  ? "project"
1069
1070
  : "user";
1070
1071
  while (true) {
1072
+ const dirty = !original || serializeAgentType(draft) !== originalContent;
1071
1073
  const field = await dialogMenu(
1072
1074
  ctx,
1073
1075
  `Edit ${sanitizeText(draft.name)} (unsaved)`,
@@ -1077,16 +1079,19 @@ async function editAgentTypesDialog(
1077
1079
  return {
1078
1080
  id: action,
1079
1081
  label: EDIT_FIELD_LABELS[action],
1082
+ valueColor: action === "Save" && dirty ? "warning" as const : undefined,
1080
1083
  value:
1081
- action === "Source"
1082
- ? (original?.source ?? "New draft")
1083
- : action === "Save scope"
1084
- ? saveScope === "user"
1085
- ? "Global"
1086
- : "Trusted project"
1087
- : separator >= 0
1088
- ? decorated.slice(separator + 2)
1089
- : "",
1084
+ action === "Save" && dirty
1085
+ ? "(changes)"
1086
+ : action === "Source"
1087
+ ? (original?.source ?? "New draft")
1088
+ : action === "Save scope"
1089
+ ? saveScope === "user"
1090
+ ? "Global"
1091
+ : "Trusted project"
1092
+ : separator >= 0
1093
+ ? decorated.slice(separator + 2)
1094
+ : "",
1090
1095
  help:
1091
1096
  action === "Source"
1092
1097
  ? (original?.filePath ??
@@ -1165,6 +1170,7 @@ async function editAgentTypesDialog(
1165
1170
  const value = await editModelPreferences(
1166
1171
  ctx,
1167
1172
  getModelPreferences(candidate),
1173
+ candidate.modelSuggestions,
1168
1174
  );
1169
1175
  if (value === MODEL_EDITOR_CANCEL) continue;
1170
1176
  if (value.length === 0) {