pi-subagent-manager 0.3.2 → 0.4.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
 
@@ -143,7 +143,7 @@ Automatic project discovery requires project trust. Only agent definitions are o
143
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`.
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.4.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
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
  });
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]),
@@ -138,6 +169,12 @@ async function configureAgentsDialog(
138
169
  )
139
170
  throw new Error(field.help);
140
171
  draft[field.id] = number;
172
+ } else if (action === "subagentMode") {
173
+ const mode = await dialogMenu(ctx, "Subagent Mode", [...MODE_OPTIONS], {
174
+ selectedId: draft.subagentMode,
175
+ });
176
+ if (MODE_OPTIONS.some((option) => option.id === mode))
177
+ draft.subagentMode = mode as SubagentMode;
141
178
  } else if (action === "scopedModelFiltering") {
142
179
  draft.scopedModelFiltering = !draft.scopedModelFiltering;
143
180
  } 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;