pi-subagent-manager 1.10.0 → 1.12.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.
Files changed (95) hide show
  1. package/README.md +9 -9
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.js +790 -0
  4. package/dist/orch/checklist-integration.js +176 -0
  5. package/dist/orch/context-entries.js +6 -0
  6. package/dist/orch/cost-ledger.js +38 -0
  7. package/dist/orch/diagnostics.js +86 -0
  8. package/dist/orch/extensions.js +66 -0
  9. package/dist/orch/housekeeping-usage.js +22 -0
  10. package/dist/orch/housekeeping.js +248 -0
  11. package/dist/orch/inherited-tools.js +57 -0
  12. package/dist/orch/mailbox.js +195 -0
  13. package/dist/orch/manager.js +970 -0
  14. package/dist/orch/paths.js +69 -0
  15. package/dist/orch/prompt.js +30 -0
  16. package/dist/orch/registry.js +115 -0
  17. package/dist/orch/runtime.js +835 -0
  18. package/dist/orch/tools.js +112 -0
  19. package/dist/orch/transcript.js +165 -0
  20. package/dist/prefs/agent-import.js +188 -0
  21. package/dist/prefs/config.js +878 -0
  22. package/dist/prefs/import-discovery.js +547 -0
  23. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +0 -1
  24. package/dist/prefs/models.js +56 -0
  25. package/dist/prefs/settings.js +491 -0
  26. package/dist/types.js +1 -0
  27. package/dist/ui/agent-loader.js +63 -0
  28. package/dist/ui/agent-navigation-editor.js +168 -0
  29. package/dist/ui/cost-footer.js +209 -0
  30. package/dist/ui/dialog.js +505 -0
  31. package/dist/ui/import-picker.js +191 -0
  32. package/dist/ui/live-agent-view.js +527 -0
  33. package/dist/ui/model-picker.js +529 -0
  34. package/dist/ui/settings-ui.js +671 -0
  35. package/dist/ui/status-ui.js +470 -0
  36. package/dist/ui/thread-tree.js +142 -0
  37. package/dist/ui/tool-picker.js +331 -0
  38. package/dist/ui/transcript-tool.js +91 -0
  39. package/dist/ui/ui.js +1019 -0
  40. package/package.json +17 -5
  41. package/docs/assets/subagent-manager-demo.gif +0 -0
  42. package/docs/async-lifecycle.md +0 -153
  43. package/docs/custom-agents.md +0 -154
  44. package/docs/default-agents.md +0 -95
  45. package/docs/demo.md +0 -63
  46. package/docs/development.md +0 -74
  47. package/docs/importing-agents.md +0 -41
  48. package/docs/pi-footer.md +0 -128
  49. package/docs/research-claude.md +0 -258
  50. package/docs/research-codex.md +0 -143
  51. package/docs/research-default-agent-models.md +0 -121
  52. package/docs/research-model-audit-2026-10.md +0 -154
  53. package/docs/research-model-roles-coding.md +0 -99
  54. package/docs/research-model-roles-writing.md +0 -78
  55. package/docs/research-researcher-workflow.md +0 -97
  56. package/docs/settings.md +0 -293
  57. package/docs/subagent-extension-limitations.md +0 -98
  58. package/docs/threads.md +0 -73
  59. package/docs/tools-and-ui.md +0 -129
  60. package/src/index.ts +0 -920
  61. package/src/orch/checklist-integration.ts +0 -230
  62. package/src/orch/context-entries.ts +0 -15
  63. package/src/orch/cost-ledger.ts +0 -56
  64. package/src/orch/diagnostics.ts +0 -95
  65. package/src/orch/extensions.ts +0 -83
  66. package/src/orch/housekeeping-usage.ts +0 -47
  67. package/src/orch/housekeeping.ts +0 -348
  68. package/src/orch/inherited-tools.ts +0 -84
  69. package/src/orch/mailbox.ts +0 -261
  70. package/src/orch/manager.ts +0 -1084
  71. package/src/orch/paths.ts +0 -73
  72. package/src/orch/prompt.ts +0 -39
  73. package/src/orch/registry.ts +0 -168
  74. package/src/orch/runtime.ts +0 -1041
  75. package/src/orch/tools.ts +0 -190
  76. package/src/orch/transcript.ts +0 -186
  77. package/src/prefs/agent-import.ts +0 -245
  78. package/src/prefs/config.ts +0 -1017
  79. package/src/prefs/import-discovery.ts +0 -643
  80. package/src/prefs/models.ts +0 -74
  81. package/src/prefs/settings.ts +0 -614
  82. package/src/types.ts +0 -271
  83. package/src/ui/agent-loader.ts +0 -98
  84. package/src/ui/agent-navigation-editor.ts +0 -233
  85. package/src/ui/cost-footer.ts +0 -230
  86. package/src/ui/dialog.ts +0 -678
  87. package/src/ui/import-picker.ts +0 -231
  88. package/src/ui/live-agent-view.ts +0 -600
  89. package/src/ui/model-picker.ts +0 -701
  90. package/src/ui/settings-ui.ts +0 -830
  91. package/src/ui/status-ui.ts +0 -628
  92. package/src/ui/thread-tree.ts +0 -173
  93. package/src/ui/tool-picker.ts +0 -398
  94. package/src/ui/transcript-tool.ts +0 -142
  95. package/src/ui/ui.ts +0 -1407
@@ -0,0 +1,671 @@
1
+ import { discoverSubagentExtensions, extensionDisplayName } from "../orch/extensions.js";
2
+ import { canOpenDialog, dialogInput, dialogMenu, withDialogSession, } from "./dialog.js";
3
+ import { DEFAULT_MANAGER_SETTINGS, settingsValueEqual, COST_ICONS, LOADER_STYLES, deleteManagerSettings, loadManagerSettingsLayers, managerSettingsPath, saveManagerOverrides, setManagerProjectSettings, } from "../prefs/settings.js";
4
+ import { editAgentTypes } from "./ui.js";
5
+ import { HOUSEKEEPING_PICKER_CANCEL, pickHousekeepingModel } from "./model-picker.js";
6
+ import { AGENT_LOADERS, availableLoaderStyles, effectiveLoaderStyle } from "./agent-loader.js";
7
+ import { costIconGlyph } from "./cost-footer.js";
8
+ import { CHECKLIST_REQUIREMENTS } from "../orch/checklist-integration.js";
9
+ const LOADER_OPTIONS = LOADER_STYLES.map((id) => {
10
+ const loader = AGENT_LOADERS[id];
11
+ return {
12
+ id,
13
+ label: loader.label,
14
+ value: `${loader.frames.join(" ")} · ${Object.values(loader.states).join(" ")}`,
15
+ help: `Each row: all starting/running frames · completed, paused, failed, stopped.\nStarting/running: ${loader.frames.join(" ")}\nCompleted: ${loader.states.completed} · Paused: ${loader.states.paused}\nFailed: ${loader.states.failed} · Stopped: ${loader.states.stopped}\n${loader.requiresNerdFont ? "Requires [lab] Nerd Font icons On." : id === "braille" ? "Standard Unicode Braille; no Nerd Font needed." : "ASCII only; no special font needed."} The loader appears before the role icon when enabled.`,
16
+ };
17
+ });
18
+ const FIELDS = [
19
+ {
20
+ id: "maxLevels",
21
+ label: "Maximum levels",
22
+ help: "How deep agents can delegate.\nYour main conversation is level 1; 3 allows an agent and its child.\nPositive integer, at most 32.",
23
+ },
24
+ {
25
+ id: "maxConcurrent",
26
+ label: "Concurrent agents",
27
+ help: "How many agents can be active at once across all levels.\nParents waiting for children also count.\nPositive safe integer.",
28
+ },
29
+ {
30
+ id: "maxThreads",
31
+ label: "Retained threads",
32
+ help: "How many agent sessions can be kept for follow-up work, including completed and paused agents.\nAt the limit, new agents cannot start.\nPositive safe integer.",
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.\nExisting 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.\nDelegate 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.\nThis rule is not inherited by workers.",
53
+ },
54
+ ];
55
+ const MODE_HELP = "Off: no subagent tools or prompt guidance.\nOpportunistic: delegate only parallelizable or very large tasks.\nOrchestration: /root delegates all execution and only coordinates and synthesizes results.";
56
+ const TOOL_FILTERING_OPTIONS = [
57
+ {
58
+ id: "allowed",
59
+ label: "Allowed (except blocked)",
60
+ value: "Allow list minus block list",
61
+ help: "Only tools in the agent YAML allow list are available, minus its block list.\nBlocked tools take precedence. A missing or empty allow list means no tools.",
62
+ },
63
+ {
64
+ id: "all-except-blocked",
65
+ label: "All except blocked",
66
+ value: "Ignore allow list",
67
+ help: "All available tools except those in the agent YAML block list.\nThe allow list is completely ignored.",
68
+ },
69
+ {
70
+ id: "all",
71
+ label: "All",
72
+ value: "Ignore both lists",
73
+ help: "All available tools.\nThe agent YAML allow and block lists are completely ignored.",
74
+ },
75
+ ];
76
+ const TOOL_FILTERING_HELP = "Allowed (except blocked): only allow-listed tools, minus blocked tools; a missing or empty allow list means no tools.\nAll except blocked: ignore the allow list; block-listed tools remain blocked.\nAll: ignore both lists.\nSave and apply to affect agents when their sessions start.";
77
+ const WIDGET_MODE_OPTIONS = [
78
+ {
79
+ id: "full",
80
+ label: "Full",
81
+ value: "Detailed agent status rows",
82
+ help: "Full: show the existing agent status widget above the input box, with per-agent details.",
83
+ },
84
+ {
85
+ id: "minimal",
86
+ label: "Minimal",
87
+ value: "One-line counts and running-agent tokens",
88
+ help: "Minimal: show status counts in one line above the input box.\nStarting agents count as running. Token totals include only active (starting/running) agents.",
89
+ },
90
+ ];
91
+ const WIDGET_MODE_HELP = "Full: detailed agent status rows above the input box.\nMinimal: one-line status counts and cumulative input/output tokens for active (starting/running) agents.\nSave and apply to update the widget immediately.";
92
+ const COST_DISPLAY_OPTIONS = [
93
+ {
94
+ id: "pi-status",
95
+ label: "Replace Pi status",
96
+ help: "Show the selected cost in Pi’s status area, without replacing the whole footer. Third-party footers may also consume this status.",
97
+ },
98
+ {
99
+ id: "pi-footer-status",
100
+ label: "pi-footer status widget",
101
+ value: "subagent_cost",
102
+ help: "Status key: subagent_cost\nSelect subagent_cost in pi-footer’s Extension Status widget. Does not replace your footer.",
103
+ },
104
+ {
105
+ id: "pi-footer-event",
106
+ label: "pi-footer event",
107
+ value: "subagent_cost",
108
+ help: "Event: pi-footer:update-widget\nWidget ID: subagent_cost\nAdd a Pi Event Value widget and enable Raw value only. Without an external /footer, retain the cost fallback.",
109
+ },
110
+ ];
111
+ const COST_VALUE_OPTIONS = [
112
+ {
113
+ id: "subagents",
114
+ label: "Only subagent cost",
115
+ help: "Settled USD cost of all subagents; excludes the main session.",
116
+ },
117
+ {
118
+ id: "total",
119
+ label: "Total cost",
120
+ help: "Main session USD cost plus all settled subagent costs.",
121
+ },
122
+ ];
123
+ const COST_ICON_LABELS = { money: "Money", coins: "Coins", wallet: "Wallet" };
124
+ function withProvenance(row, keys, layers) {
125
+ const globalChanged = keys.some((key) => layers.global[key] !== undefined &&
126
+ !settingsValueEqual(layers.global[key], DEFAULT_MANAGER_SETTINGS[key]));
127
+ const projectChanged = keys.some((key) => layers.project[key] !== undefined &&
128
+ !settingsValueEqual(layers.project[key], layers.global[key] ?? DEFAULT_MANAGER_SETTINGS[key]));
129
+ return {
130
+ ...row,
131
+ renderIndicators: (theme) => (globalChanged ? theme.fg("accent", "●") : " ") +
132
+ " " +
133
+ (projectChanged ? theme.fg("warning", "●") : " "),
134
+ help: `${row.label}\n${row.help ?? ""}`,
135
+ };
136
+ }
137
+ function provenanceLegend(theme) {
138
+ const global = theme.fg("accent", "●");
139
+ const project = theme.fg("warning", "●");
140
+ return (theme.fg("muted", "Saved: ") +
141
+ `${global} Global · ${project} Current Project · ${global} ${project} Both`);
142
+ }
143
+ async function configureSubagentExtensions(ctx, draft, agentDir) {
144
+ const available = await discoverSubagentExtensions({
145
+ cwd: ctx.cwd,
146
+ agentDir,
147
+ projectTrusted: ctx.isProjectTrusted(),
148
+ });
149
+ const selected = new Set(draft.subagentExtensions === true ? available : draft.subagentExtensions || []);
150
+ const files = [...new Set([...available, ...selected])].sort();
151
+ let selectedId;
152
+ while (true) {
153
+ const action = await dialogMenu(ctx, "[lab] Subagent extensions", [
154
+ ...files.map((file) => ({
155
+ id: file,
156
+ label: `${selected.has(file) ? "[x]" : "[ ]"} ${extensionDisplayName(file)}`,
157
+ value: available.includes(file) ? (selected.has(file) ? "On" : "Off") : "Unavailable",
158
+ 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.`,
159
+ })),
160
+ {
161
+ id: "back",
162
+ label: "Back",
163
+ help: files.length
164
+ ? "Return to settings; selection is not saved yet."
165
+ : "No extensions available (configured or auto-discovered). CLI-only, inline, built-in extensions and this manager are excluded.",
166
+ },
167
+ ], { selectedId, spaceSelect: true, footer: "↑↓/Tab navigate · Space/Enter toggle · Esc back" });
168
+ if (!action || action === "back") {
169
+ draft.subagentExtensions = [...selected].sort();
170
+ return;
171
+ }
172
+ selectedId = action;
173
+ if (selected.has(action))
174
+ selected.delete(action);
175
+ else
176
+ selected.add(action);
177
+ }
178
+ }
179
+ async function configureFooterDisplay(ctx, draft, layers) {
180
+ let selectedId;
181
+ while (true) {
182
+ const action = await dialogMenu(ctx, "Footer display", [
183
+ {
184
+ id: "location",
185
+ label: "Location",
186
+ value: COST_DISPLAY_OPTIONS.find((option) => option.id === draft.costDisplay).label,
187
+ help: "Choose Pi status, a pi-footer status widget, or a pi-footer event. Integration IDs are shown in the location picker.",
188
+ },
189
+ {
190
+ id: "value",
191
+ label: "Display value",
192
+ value: COST_VALUE_OPTIONS.find((option) => option.id === draft.costValue).label,
193
+ help: "Show only settled subagent cost, or main session plus settled subagents. Applies to every location.",
194
+ },
195
+ {
196
+ id: "icon",
197
+ label: "Icon",
198
+ value: `${costIconGlyph(draft.costIcon, draft.nerdFontIcons)} ${COST_ICON_LABELS[draft.costIcon]}`,
199
+ help: `Choose a money-related ${draft.nerdFontIcons ? "Nerd Font" : "emoji"} icon. The family follows [lab] Nerd Font icons.`,
200
+ },
201
+ {
202
+ id: "back",
203
+ label: "Back",
204
+ help: "Return to settings. Save and apply there to commit these changes.",
205
+ },
206
+ ].map((row) => {
207
+ const key = { location: "costDisplay", value: "costValue", icon: "costIcon" }[row.id];
208
+ return key ? withProvenance(row, [key], layers) : row;
209
+ }), {
210
+ selectedId,
211
+ renderLegend: provenanceLegend,
212
+ footer: "↑↓/Tab navigate · Enter edit · Esc back",
213
+ });
214
+ if (!action || action === "back")
215
+ return;
216
+ selectedId = action;
217
+ if (action === "location") {
218
+ const mode = await dialogMenu(ctx, "Footer location", [...COST_DISPLAY_OPTIONS], {
219
+ selectedId: draft.costDisplay,
220
+ });
221
+ if (COST_DISPLAY_OPTIONS.some((option) => option.id === mode))
222
+ draft.costDisplay = mode;
223
+ }
224
+ else if (action === "value") {
225
+ const value = await dialogMenu(ctx, "Footer display value", [...COST_VALUE_OPTIONS], {
226
+ selectedId: draft.costValue,
227
+ });
228
+ if (COST_VALUE_OPTIONS.some((option) => option.id === value))
229
+ draft.costValue = value;
230
+ }
231
+ else if (action === "icon") {
232
+ const icon = await dialogMenu(ctx, `Footer icon · ${draft.nerdFontIcons ? "Nerd Font" : "Emoji"}`, COST_ICONS.map((id) => ({
233
+ id,
234
+ label: COST_ICON_LABELS[id],
235
+ value: costIconGlyph(id, draft.nerdFontIcons),
236
+ help: `${costIconGlyph(id, draft.nerdFontIcons)} ${COST_ICON_LABELS[id]} · ${draft.nerdFontIcons ? "Requires a Nerd Font in your terminal." : "Emoji icon."}`,
237
+ })), { selectedId: draft.costIcon });
238
+ if (COST_ICONS.includes(icon))
239
+ draft.costIcon = icon;
240
+ }
241
+ }
242
+ }
243
+ function housekeepingValue(draft) {
244
+ if (!draft.housekeepingEnabled)
245
+ return "Off";
246
+ return draft.housekeepingModel ? `On · ${draft.housekeepingModel}` : "On · no model selected";
247
+ }
248
+ const HOUSEKEEPING_HELP = "Experimental: a model you choose writes a one-line summary of each running agent's current work, shown in the tree and widget instead of raw tool-call status.\nSends the agent's task and recent tool names/arguments/text to the selected model, uses extra tokens, and is not included in subagent cost totals.\nOff by default. Any failure keeps the original status. Choose from available and scoped models.";
249
+ async function configureHousekeeping(ctx, draft, layers) {
250
+ let selectedId;
251
+ while (true) {
252
+ const action = await dialogMenu(ctx, "[lab] Housekeeping model", [
253
+ {
254
+ id: "enabled",
255
+ label: "Summaries",
256
+ value: draft.housekeepingEnabled ? "On" : "Off",
257
+ help: "Name each running agent's work in one line using the housekeeping model, replacing raw tool-call status in the tree and widget.\nInactive until a model is selected. Off by default.",
258
+ },
259
+ {
260
+ id: "model",
261
+ label: "Model",
262
+ value: draft.housekeepingModel || "Not selected",
263
+ valueColor: draft.housekeepingModel ? undefined : "muted",
264
+ help: "Pick any available model; scoped models are listed first. A small, fast, inexpensive model is usually enough.\nIf the model later becomes unavailable (no credentials, removed), summaries stay inactive and normal status shows.",
265
+ },
266
+ {
267
+ id: "back",
268
+ label: "Back",
269
+ help: "Return to settings. Save and apply there to commit these changes.",
270
+ },
271
+ ].map((row) => {
272
+ const key = { enabled: "housekeepingEnabled", model: "housekeepingModel" }[row.id];
273
+ return key ? withProvenance(row, [key], layers) : row;
274
+ }), {
275
+ selectedId,
276
+ renderLegend: provenanceLegend,
277
+ footer: "↑↓/Tab navigate · Enter edit · Esc back",
278
+ });
279
+ if (!action || action === "back")
280
+ return;
281
+ selectedId = action;
282
+ if (action === "enabled")
283
+ draft.housekeepingEnabled = !draft.housekeepingEnabled;
284
+ else if (action === "model") {
285
+ const picked = await pickHousekeepingModel(ctx, draft.housekeepingModel);
286
+ if (picked !== HOUSEKEEPING_PICKER_CANCEL)
287
+ draft.housekeepingModel = picked;
288
+ }
289
+ }
290
+ }
291
+ const MODEL_SELECTION_OPTIONS = [
292
+ {
293
+ id: "pick-first-available",
294
+ label: "Pick First (available)",
295
+ value: "First available model in the agent's list",
296
+ help: "Pick First (available):\nPick the first model in the agent's models list available in Pi with an enabled, authenticated provider.\nSkip missing models and providers without credentials; try the next preference.",
297
+ },
298
+ {
299
+ id: "pick-first-scoped",
300
+ label: "Pick First (scoped)",
301
+ value: "First available preference in the session scope",
302
+ help: "Pick First (scoped):\nPick the first available model in the agent's models list that is also selected in the current session's /scoped-models. An empty scope allows all available models.\nSkip unavailable models and providers without credentials.",
303
+ },
304
+ {
305
+ id: "use-current",
306
+ label: "Use Current",
307
+ value: "Use the main session's current model",
308
+ help: "Use Current:\nIgnore the agent's models list and use the main session's current model.\nKeep each agent's configured thinking level, not the main session's thinking level.",
309
+ },
310
+ ];
311
+ const MODEL_SELECTION_HELP = "Pick First (available): first preference with an enabled, authenticated provider in Pi.\nPick First (scoped): same, limited to the current session's /scoped-models when non-empty.\nUse Current: ignore models and use the main session's current model; keep the agent's thinking level.\nOnly the models list affects runtime picking; modelSuggestions are search hints.\nSave and apply to affect agents when their sessions start.";
312
+ export async function configureAgents(ctx, options) {
313
+ if (!canOpenDialog(ctx))
314
+ return;
315
+ await withDialogSession(ctx, (scoped) => configureAgentsDialog(scoped, options));
316
+ }
317
+ function checklistRow(enabled, status) {
318
+ const requirements = `${CHECKLIST_REQUIREMENTS}\nWhen On and eligible, adds prompt guidance to tag which agent works on each checklist task via meta.agent; in Orchestration mode /root must use the checklist. Off by default.`;
319
+ if (status.eligible)
320
+ return {
321
+ id: "checklistIntegration",
322
+ label: "[lab] Checklist integration",
323
+ value: enabled ? "On" : "Off",
324
+ help: `Experimental: integrate with pi-checklist.\n${requirements}\nAvailable now: pi-checklist ≥3.0.0 is loaded with task meta enabled.`,
325
+ };
326
+ return {
327
+ id: "checklistIntegration",
328
+ label: "[lab] Checklist integration",
329
+ value: enabled ? "On · inactive (unavailable)" : "Off · unavailable",
330
+ valueColor: "muted",
331
+ help: `Experimental: integrate with pi-checklist.\nUnavailable: ${status.reason ?? "requirements not met"}.\n${requirements}\n${enabled ? "Saved On but inactive until requirements are met; Enter turns it Off." : "Cannot be turned On until requirements are met."}`,
332
+ };
333
+ }
334
+ async function configureAgentsDialog(ctx, options) {
335
+ const checklistStatus = () => {
336
+ try {
337
+ return (options.checklistStatus?.() ?? {
338
+ eligible: false,
339
+ reason: "pi-checklist status is unavailable",
340
+ });
341
+ }
342
+ catch (error) {
343
+ return {
344
+ eligible: false,
345
+ reason: `could not verify pi-checklist: ${error instanceof Error ? error.message : String(error)}`,
346
+ };
347
+ }
348
+ };
349
+ const readLayers = () => loadManagerSettingsLayers({
350
+ cwd: ctx.cwd,
351
+ agentDir: options.agentDir,
352
+ includeProject: ctx.isProjectTrusted(),
353
+ });
354
+ let layers = readLayers();
355
+ const reportDiagnostics = () => {
356
+ for (const diagnostic of layers.diagnostics)
357
+ ctx.ui.notify(diagnostic, "warning");
358
+ };
359
+ reportDiagnostics();
360
+ let baseline = { ...layers.settings };
361
+ let draft = { ...baseline };
362
+ let scope = layers.scope;
363
+ let selectedId;
364
+ while (true) {
365
+ const dirty = JSON.stringify(draft) !== JSON.stringify(baseline);
366
+ const action = await dialogMenu(ctx, `Agents settings${dirty ? " · unsaved" : ""}`, [
367
+ {
368
+ id: "subagentMode",
369
+ label: "Subagent Mode",
370
+ value: MODE_OPTIONS.find((mode) => mode.id === draft.subagentMode).label,
371
+ help: MODE_HELP,
372
+ },
373
+ {
374
+ id: "toolFiltering",
375
+ label: "Tool Filtering",
376
+ value: TOOL_FILTERING_OPTIONS.find((mode) => mode.id === draft.toolFiltering).label,
377
+ help: TOOL_FILTERING_HELP,
378
+ },
379
+ ...FIELDS.map((field) => ({
380
+ ...field,
381
+ value: String(draft[field.id]),
382
+ })),
383
+ {
384
+ id: "modelSelection",
385
+ label: "Model Picking",
386
+ value: MODEL_SELECTION_OPTIONS.find((mode) => mode.id === draft.modelSelection).label,
387
+ help: MODEL_SELECTION_HELP,
388
+ },
389
+ {
390
+ id: "widgetMode",
391
+ label: "Status Widget",
392
+ value: WIDGET_MODE_OPTIONS.find((mode) => mode.id === draft.widgetMode).label,
393
+ help: WIDGET_MODE_HELP,
394
+ },
395
+ {
396
+ id: "costDisplay",
397
+ label: "Footer display",
398
+ value: COST_DISPLAY_OPTIONS.find((mode) => mode.id === draft.costDisplay).label,
399
+ help: "Configure footer location, displayed cost, and money icon in a submenu. Save and apply to update immediately.",
400
+ },
401
+ {
402
+ id: "loaderStyle",
403
+ label: "Loader style",
404
+ value: AGENT_LOADERS[effectiveLoaderStyle(draft.loaderStyle, draft.nerdFontIcons)].label,
405
+ help: "Preview every animation frame and settled state.\nNerd Fonts Off: Braille (standard Unicode), ASCII, ASCII Star and ASCII Pulse. On: all palettes, including Circle and Hourglass.\nNerd-only saved styles fall back to ASCII while Nerd Fonts are off. Save and apply to update immediately.",
406
+ },
407
+ {
408
+ id: "housekeeping",
409
+ label: "[lab] Housekeeping model",
410
+ value: housekeepingValue(draft),
411
+ valueColor: draft.housekeepingEnabled && !draft.housekeepingModel
412
+ ? "warning"
413
+ : undefined,
414
+ help: HOUSEKEEPING_HELP,
415
+ },
416
+ {
417
+ id: "nerdFontIcons",
418
+ label: "[lab] Nerd Font icons",
419
+ value: draft.nerdFontIcons ? "On" : "Off",
420
+ help: "Experimental: display each agent type’s optional Nerd Font icon and unlock Nerd Font loader palettes.\nRequires a Nerd Font configured in your terminal; otherwise glyphs may appear as boxes.\nOff by default. Braille and ASCII loaders work with this Off. Save and apply to update immediately.",
421
+ },
422
+ {
423
+ id: "subagentExtensions",
424
+ label: "[lab] Subagent extensions",
425
+ value: Array.isArray(draft.subagentExtensions)
426
+ ? `${draft.subagentExtensions.length} selected`
427
+ : draft.subagentExtensions
428
+ ? "All (legacy)"
429
+ : "None",
430
+ 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.",
431
+ },
432
+ checklistRow(draft.checklistIntegration, checklistStatus()),
433
+ {
434
+ id: "finalRecap",
435
+ label: "[lab] Final Recap",
436
+ value: draft.finalRecap ? "On" : "Off",
437
+ help: "Experimental: when detached agents finish or fail and the main agent is idle, automatically ask the main agent to summarize their results.\nEnabling this may cause extra model turns and uses more tokens and context.\nOff by default. Subagent Mode Off suppresses automatic summaries.",
438
+ },
439
+ {
440
+ id: "scope",
441
+ label: "Save scope",
442
+ value: scope === "user" ? "Global" : "Current Project",
443
+ help: "Global: save overrides of built-in defaults for all projects.\nCurrent Project: save overrides of global settings for this trusted project.\nSwitching requires confirmation: enabling Project creates its settings file; switching to Global deletes it and discards unsaved edits. Confirmed scope changes happen immediately, even if you later cancel.",
444
+ },
445
+ {
446
+ id: "types",
447
+ label: "Agent definitions",
448
+ value: `${options.store.list().length} types`,
449
+ help: "Create or edit agent definitions.\nConfigure model preferences and tool policy for each agent type.",
450
+ },
451
+ {
452
+ id: "defaults",
453
+ label: "Restore defaults",
454
+ help: "Pick Global or Project, then delete that scope's settings.json so its defaults apply again.\nThe file is removed, not rewritten; unsaved edits are discarded. This cannot be undone.",
455
+ },
456
+ {
457
+ id: "save",
458
+ label: "Save and apply",
459
+ value: dirty ? "(changes)" : undefined,
460
+ valueColor: dirty ? "warning" : undefined,
461
+ help: "Save only overrides to the selected scope and reload settings now.\nUnchanged values inherit from the lower layer.\nRunning agents and retained sessions are kept.",
462
+ },
463
+ {
464
+ id: "cancel",
465
+ label: "Cancel",
466
+ help: "Close without saving manager settings.",
467
+ },
468
+ ].map((row) => {
469
+ const keys = row.id === "costDisplay"
470
+ ? ["costDisplay", "costValue", "costIcon"]
471
+ : row.id === "housekeeping"
472
+ ? ["housekeepingEnabled", "housekeepingModel"]
473
+ : row.id in DEFAULT_MANAGER_SETTINGS
474
+ ? [row.id]
475
+ : [];
476
+ return keys.length ? withProvenance(row, keys, layers) : row;
477
+ }), {
478
+ selectedId,
479
+ saveId: "save",
480
+ renderLegend: provenanceLegend,
481
+ footer: "↑↓/Tab navigate · Enter edit · Ctrl+S save · Esc cancel",
482
+ });
483
+ if (!action || action === "cancel")
484
+ return;
485
+ selectedId = action;
486
+ try {
487
+ const field = FIELDS.find((field) => field.id === action);
488
+ if (field) {
489
+ const value = await dialogInput(ctx, field.label, String(draft[field.id]), field.help);
490
+ if (value === undefined)
491
+ continue;
492
+ const number = Number(value.trim());
493
+ if (!/^\d+$/.test(value.trim()) ||
494
+ !Number.isSafeInteger(number) ||
495
+ number < 1 ||
496
+ (field.id === "maxLevels" && number > 32))
497
+ throw new Error(field.help);
498
+ draft[field.id] = number;
499
+ }
500
+ else if (action === "subagentMode") {
501
+ const mode = await dialogMenu(ctx, "Subagent Mode", [...MODE_OPTIONS], {
502
+ selectedId: draft.subagentMode,
503
+ });
504
+ if (MODE_OPTIONS.some((option) => option.id === mode))
505
+ draft.subagentMode = mode;
506
+ }
507
+ else if (action === "toolFiltering") {
508
+ const mode = await dialogMenu(ctx, "Tool Filtering", [...TOOL_FILTERING_OPTIONS], {
509
+ selectedId: draft.toolFiltering,
510
+ });
511
+ if (TOOL_FILTERING_OPTIONS.some((option) => option.id === mode))
512
+ draft.toolFiltering = mode;
513
+ }
514
+ else if (action === "modelSelection") {
515
+ const mode = await dialogMenu(ctx, "Model Picking", [...MODEL_SELECTION_OPTIONS], {
516
+ selectedId: draft.modelSelection,
517
+ });
518
+ if (MODEL_SELECTION_OPTIONS.some((option) => option.id === mode))
519
+ draft.modelSelection = mode;
520
+ }
521
+ else if (action === "widgetMode") {
522
+ const mode = await dialogMenu(ctx, "Status Widget", [...WIDGET_MODE_OPTIONS], {
523
+ selectedId: draft.widgetMode,
524
+ });
525
+ if (WIDGET_MODE_OPTIONS.some((option) => option.id === mode))
526
+ draft.widgetMode = mode;
527
+ }
528
+ else if (action === "costDisplay") {
529
+ await configureFooterDisplay(ctx, draft, layers);
530
+ }
531
+ else if (action === "housekeeping") {
532
+ await configureHousekeeping(ctx, draft, layers);
533
+ }
534
+ else if (action === "nerdFontIcons") {
535
+ draft.nerdFontIcons = !draft.nerdFontIcons;
536
+ }
537
+ else if (action === "loaderStyle") {
538
+ const styles = availableLoaderStyles(draft.nerdFontIcons);
539
+ const style = await dialogMenu(ctx, "Loader style", LOADER_OPTIONS.filter((option) => styles.includes(option.id)), { selectedId: effectiveLoaderStyle(draft.loaderStyle, draft.nerdFontIcons) });
540
+ if (styles.includes(style))
541
+ draft.loaderStyle = style;
542
+ }
543
+ else if (action === "subagentExtensions") {
544
+ await configureSubagentExtensions(ctx, draft, options.agentDir);
545
+ }
546
+ else if (action === "checklistIntegration") {
547
+ const status = checklistStatus();
548
+ if (!draft.checklistIntegration && !status.eligible)
549
+ ctx.ui.notify(`Checklist integration cannot be enabled: ${status.reason ?? "requirements not met"}. ${CHECKLIST_REQUIREMENTS}`, "warning");
550
+ else
551
+ draft.checklistIntegration = !draft.checklistIntegration;
552
+ }
553
+ else if (action === "finalRecap") {
554
+ draft.finalRecap = !draft.finalRecap;
555
+ }
556
+ else if (action === "scope") {
557
+ if (!ctx.isProjectTrusted())
558
+ ctx.ui.notify("Project settings require a trusted project; saving globally.", "warning");
559
+ else {
560
+ const nextScope = scope === "user" ? "project" : "user";
561
+ const message = nextScope === "project"
562
+ ? "Create project file now; outer Cancel cannot undo.\nThis will create this project's settings.json. Further changes will be saved there. Unsaved edits are kept until Save and apply."
563
+ : "Delete project file now. Discard edits. No undo.\nUnsaved edits will be discarded. Outer Cancel cannot undo. We reload global settings; further changes are saved globally.";
564
+ const confirmation = await dialogMenu(ctx, nextScope === "project"
565
+ ? "Enable project settings?"
566
+ : "Clear project settings and use Global?", [
567
+ { id: "confirm", label: "Confirm", help: message },
568
+ {
569
+ id: "cancel",
570
+ label: "Cancel",
571
+ help: message + "\nCancel leaves files, scope and unsaved edits unchanged.",
572
+ },
573
+ ], { selectedId: "cancel", footer: "↑↓/Tab choose · Enter select · Esc cancel" });
574
+ if (confirmation !== "confirm")
575
+ continue;
576
+ setManagerProjectSettings({
577
+ cwd: ctx.cwd,
578
+ agentDir: options.agentDir,
579
+ includeProject: ctx.isProjectTrusted(),
580
+ enabled: nextScope === "project",
581
+ expectedLayers: layers,
582
+ });
583
+ layers = readLayers();
584
+ reportDiagnostics();
585
+ scope = nextScope;
586
+ if (scope === "user") {
587
+ baseline = { ...layers.settings };
588
+ draft = { ...baseline };
589
+ options.apply();
590
+ }
591
+ }
592
+ }
593
+ else if (action === "defaults") {
594
+ const target = {
595
+ cwd: ctx.cwd,
596
+ agentDir: options.agentDir,
597
+ includeProject: ctx.isProjectTrusted(),
598
+ };
599
+ const globalPath = managerSettingsPath(target, "user");
600
+ const projectPath = target.includeProject
601
+ ? managerSettingsPath(target, "project")
602
+ : undefined;
603
+ const explain = (path) => `Deletes this file now (nothing is written):\n${path}\nIf it does not exist, nothing happens. Unsaved edits are discarded. No undo.`;
604
+ const rows = [
605
+ {
606
+ id: "user",
607
+ label: "Global",
608
+ value: "Restore global defaults",
609
+ help: explain(globalPath),
610
+ },
611
+ ...(projectPath
612
+ ? [
613
+ {
614
+ id: "project",
615
+ label: "Project",
616
+ value: "Restore project defaults",
617
+ help: explain(projectPath),
618
+ },
619
+ ]
620
+ : []),
621
+ { id: "cancel", label: "Cancel", help: "Delete nothing." },
622
+ ];
623
+ const choice = await dialogMenu(ctx, "Restore defaults: delete which settings file?", rows, {
624
+ selectedId: "cancel",
625
+ footer: "↑↓/Tab choose · Enter delete file · Esc cancel",
626
+ });
627
+ if (choice === "user" || choice === "project") {
628
+ const { filePath, deleted } = deleteManagerSettings({ ...target, scope: choice });
629
+ layers = readLayers();
630
+ reportDiagnostics();
631
+ baseline = { ...layers.settings };
632
+ draft = { ...baseline };
633
+ scope = layers.scope;
634
+ options.apply();
635
+ ctx.ui.notify(deleted
636
+ ? `Deleted ${filePath}. Defaults restored.`
637
+ : `No settings file at ${filePath}; nothing to delete.`, "info");
638
+ }
639
+ }
640
+ else if (action === "types") {
641
+ await editAgentTypes(ctx, options.store, draft.nerdFontIcons, {
642
+ getAllTools: options.getAllTools ?? (() => []),
643
+ toolFiltering: draft.toolFiltering,
644
+ resolveAgentSettings: options.resolveAgentSettings,
645
+ });
646
+ options.store.reload();
647
+ }
648
+ else if (action === "save") {
649
+ if (draft.checklistIntegration && !baseline.checklistIntegration) {
650
+ const status = checklistStatus();
651
+ if (!status.eligible)
652
+ throw new Error(`Checklist integration cannot be enabled: ${status.reason ?? "requirements not met"}. Turn it Off or satisfy: ${CHECKLIST_REQUIREMENTS}`);
653
+ }
654
+ const file = saveManagerOverrides({
655
+ cwd: ctx.cwd,
656
+ agentDir: options.agentDir,
657
+ includeProject: ctx.isProjectTrusted(),
658
+ scope,
659
+ settings: draft,
660
+ expectedLayers: layers,
661
+ });
662
+ options.apply();
663
+ ctx.ui.notify(`Saved ${file}. Settings reloaded; unchanged values inherit from the lower layer.`, "info");
664
+ return;
665
+ }
666
+ }
667
+ catch (error) {
668
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
669
+ }
670
+ }
671
+ }