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
@@ -1,74 +0,0 @@
1
- const MODEL_IDENTITY = /^[^\s/]+\/[^\s]+$/;
2
-
3
- function validateModelPreference(value: unknown, label: string): string {
4
- if (typeof value !== "string" || !MODEL_IDENTITY.test(value))
5
- throw new Error(`${label} must be provider/model-id`);
6
- return value;
7
- }
8
-
9
- export function getModelPreferences(type: {
10
- models?: unknown;
11
- model?: unknown;
12
- }): string[] | undefined {
13
- const hasModels = type.models !== undefined;
14
- const hasModel = type.model !== undefined;
15
- if (hasModels && hasModel) throw new Error("Specify either models or model, not both");
16
- if (hasModels) {
17
- if (!Array.isArray(type.models))
18
- throw new Error("models must be an array of provider/model-id strings");
19
- if (type.models.length === 0)
20
- throw new Error("models must not be empty; omit models to inherit the parent/default model");
21
- const models = type.models.map((value, index) =>
22
- validateModelPreference(value, `models[${index}]`),
23
- );
24
- if (new Set(models).size !== models.length)
25
- throw new Error("models contains duplicate entries");
26
- return [...models];
27
- }
28
- if (hasModel) return [validateModelPreference(type.model, "model")];
29
- return undefined;
30
- }
31
-
32
- export function modelIdentity(model: { provider: string; id: string }): string {
33
- return `${model.provider}/${model.id}`;
34
- }
35
-
36
- export class ModelPreferenceError extends Error {
37
- constructor(
38
- message: string,
39
- readonly scopedModelFiltering: boolean,
40
- ) {
41
- super(message);
42
- }
43
-
44
- get summary(): string {
45
- return this.scopedModelFiltering
46
- ? "No preferred model is available in /scoped-models; update the scope or this type's models."
47
- : "No preferred model is available; check provider credentials or this type's models.";
48
- }
49
- }
50
-
51
- export function selectPreferredModel(
52
- type: { name: string; models?: unknown; model?: unknown },
53
- eligibleModels: readonly { model: { provider: string; id: string } }[],
54
- scopedModelFiltering = true,
55
- ): string | undefined {
56
- const preferences = getModelPreferences(type);
57
- if (preferences === undefined) return undefined;
58
- const available = eligibleModels.map(({ model }) => modelIdentity(model));
59
- for (const preference of preferences) {
60
- if (available.includes(preference)) return preference;
61
- }
62
- const preferenceList = `[${preferences.join(", ")}]`;
63
- const availableList = available.length === 0 ? "(none)" : `[${available.join(", ")}]`;
64
- if (!scopedModelFiltering) {
65
- throw new ModelPreferenceError(
66
- `Agent type ${JSON.stringify(type.name)} prefers models ${preferenceList}, but none are available. Available models: ${availableList}. Update this agent type's models list.`,
67
- false,
68
- );
69
- }
70
- throw new ModelPreferenceError(
71
- `Agent type ${JSON.stringify(type.name)} prefers scoped models ${preferenceList}, but none are available in /scoped-models. Available scoped models: ${availableList}. Update /scoped-models or this agent type's models list.`,
72
- true,
73
- );
74
- }
@@ -1,614 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import {
3
- closeSync,
4
- constants,
5
- fchmodSync,
6
- linkSync,
7
- lstatSync,
8
- mkdirSync,
9
- openSync,
10
- readFileSync,
11
- renameSync,
12
- unlinkSync,
13
- writeFileSync,
14
- } from "node:fs";
15
- import { dirname, join, resolve } from "node:path";
16
-
17
- export const SUBAGENT_MODES = ["off", "opportunistic", "orchestration"] as const;
18
- export type SubagentMode = (typeof SUBAGENT_MODES)[number];
19
-
20
- export const WIDGET_MODES = ["full", "minimal"] as const;
21
- export type WidgetMode = (typeof WIDGET_MODES)[number];
22
-
23
- export const COST_DISPLAY_MODES = ["pi-footer-event", "pi-footer-status", "pi-status"] as const;
24
- export type CostDisplayMode = (typeof COST_DISPLAY_MODES)[number];
25
-
26
- export const COST_VALUES = ["subagents", "total"] as const;
27
- export type CostValue = (typeof COST_VALUES)[number];
28
-
29
- export const COST_ICONS = ["money", "coins", "wallet"] as const;
30
- export type CostIcon = (typeof COST_ICONS)[number];
31
-
32
- export const LOADER_STYLES = [
33
- "circle",
34
- "braille",
35
- "hourglass",
36
- "ascii",
37
- "ascii-star",
38
- "ascii-pulse",
39
- ] as const;
40
- export type LoaderStyle = (typeof LOADER_STYLES)[number];
41
-
42
- export const TOOL_FILTERING_MODES = ["allowed", "all-except-blocked", "all"] as const;
43
- export type ToolFilteringMode = (typeof TOOL_FILTERING_MODES)[number];
44
-
45
- export const MODEL_SELECTION_MODES = [
46
- "pick-first-available",
47
- "pick-first-scoped",
48
- "use-current",
49
- ] as const;
50
- export type ModelSelectionMode = (typeof MODEL_SELECTION_MODES)[number];
51
-
52
- /** Legacy booleans mean all/none; arrays pin the selected canonical file paths. */
53
- export type SubagentExtensionSelection = boolean | string[];
54
-
55
- export function settingsValueEqual(a: unknown, b: unknown): boolean {
56
- return JSON.stringify(a) === JSON.stringify(b);
57
- }
58
-
59
- export interface ManagerSettings {
60
- subagentMode: SubagentMode;
61
- toolFiltering: ToolFilteringMode;
62
- widgetMode: WidgetMode;
63
- costDisplay: CostDisplayMode;
64
- costValue: CostValue;
65
- costIcon: CostIcon;
66
- nerdFontIcons: boolean;
67
- loaderStyle: LoaderStyle;
68
- finalRecap: boolean;
69
- subagentExtensions: SubagentExtensionSelection;
70
- checklistIntegration: boolean;
71
- /** [labs] One-line agent work summaries written by the housekeeping model. */
72
- housekeepingEnabled: boolean;
73
- /** `provider/model-id` of the housekeeping model; empty means none selected. */
74
- housekeepingModel: string;
75
- maxLevels: number;
76
- maxConcurrent: number;
77
- maxThreads: number;
78
- modelSelection: ModelSelectionMode;
79
- }
80
-
81
- export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
82
- maxLevels: 3,
83
- maxConcurrent: 16,
84
- maxThreads: 64,
85
- modelSelection: "pick-first-scoped",
86
- subagentMode: "opportunistic",
87
- toolFiltering: "all-except-blocked",
88
- widgetMode: "full",
89
- costDisplay: "pi-footer-status",
90
- costValue: "subagents",
91
- costIcon: "money",
92
- nerdFontIcons: false,
93
- loaderStyle: "circle",
94
- finalRecap: false,
95
- subagentExtensions: false,
96
- checklistIntegration: false,
97
- housekeepingEnabled: false,
98
- housekeepingModel: "",
99
- };
100
-
101
- /** Same `provider/model-id` shape as agent model preferences. */
102
- const HOUSEKEEPING_MODEL = /^[^\s/]+\/[^\s]+$/;
103
- export const isHousekeepingModel = (value: unknown): value is string =>
104
- typeof value === "string" && (value === "" || HOUSEKEEPING_MODEL.test(value));
105
-
106
- const KEYS = [
107
- "maxLevels",
108
- "maxConcurrent",
109
- "maxThreads",
110
- "modelSelection",
111
- "subagentMode",
112
- "toolFiltering",
113
- "widgetMode",
114
- "costDisplay",
115
- "costValue",
116
- "costIcon",
117
- "nerdFontIcons",
118
- "loaderStyle",
119
- "finalRecap",
120
- "subagentExtensions",
121
- "checklistIntegration",
122
- "housekeepingEnabled",
123
- "housekeepingModel",
124
- ] as const;
125
- const MAX_LEVELS = 32;
126
-
127
- function errorCode(error: unknown): string | undefined {
128
- return typeof error === "object" && error !== null && "code" in error
129
- ? String((error as { code?: unknown }).code)
130
- : undefined;
131
- }
132
-
133
- function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined {
134
- try {
135
- return lstatSync(path);
136
- } catch (error) {
137
- if (errorCode(error) === "ENOENT") return undefined;
138
- throw error;
139
- }
140
- }
141
-
142
- function assertNotSymlinkPath(path: string): ReturnType<typeof lstatSync> | undefined {
143
- const stat = lstatIfPresent(path);
144
- if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
145
- return stat;
146
- }
147
-
148
- function isSupportedKey(key: string): key is (typeof KEYS)[number] {
149
- return KEYS.includes(key as (typeof KEYS)[number]);
150
- }
151
-
152
- function positiveSafeInteger(value: unknown): value is number {
153
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
154
- }
155
-
156
- function requirement(key: (typeof KEYS)[number]): string {
157
- if (key === "subagentExtensions")
158
- return "subagentExtensions must be a boolean or an array of absolute file paths";
159
- if (
160
- key === "nerdFontIcons" ||
161
- key === "finalRecap" ||
162
- key === "checklistIntegration" ||
163
- key === "housekeepingEnabled"
164
- )
165
- return `${key} must be a boolean`;
166
- if (key === "housekeepingModel") return "housekeepingModel must be empty or provider/model-id";
167
- if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
168
- if (key === "widgetMode") return "widgetMode must be full or minimal";
169
- if (key === "costDisplay")
170
- return "costDisplay must be pi-footer-event, pi-footer-status or pi-status";
171
- if (key === "costValue") return "costValue must be subagents or total";
172
- if (key === "costIcon") return "costIcon must be money, coins or wallet";
173
- if (key === "loaderStyle") return `loaderStyle must be one of: ${LOADER_STYLES.join(", ")}`;
174
- if (key === "toolFiltering") return "toolFiltering must be allowed, all-except-blocked or all";
175
- if (key === "modelSelection")
176
- return "modelSelection must be pick-first-available, pick-first-scoped or use-current";
177
- return `${key} must be a positive safe integer`;
178
- }
179
-
180
- function parseSettings(content: string): Partial<ManagerSettings> {
181
- let parsed: unknown;
182
- try {
183
- parsed = JSON.parse(content);
184
- } catch (error) {
185
- const detail = error instanceof Error ? error.message : String(error);
186
- throw new Error(`Invalid JSON: ${detail}`);
187
- }
188
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
189
- throw new Error("Settings must be a JSON object");
190
- }
191
- const record = parsed as Record<string, unknown>;
192
- for (const key of Object.keys(record)) {
193
- if (!isSupportedKey(key) && key !== "scopedModelFiltering")
194
- throw new Error(`Unknown settings key: ${key}`);
195
- }
196
- const layer: Partial<ManagerSettings> = {};
197
- if (Object.hasOwn(record, "scopedModelFiltering")) {
198
- if (typeof record.scopedModelFiltering !== "boolean")
199
- throw new Error("scopedModelFiltering must be a boolean");
200
- if (!Object.hasOwn(record, "modelSelection"))
201
- layer.modelSelection = record.scopedModelFiltering
202
- ? "pick-first-scoped"
203
- : "pick-first-available";
204
- }
205
- for (const key of KEYS) {
206
- if (!Object.hasOwn(record, key)) continue;
207
- const value = record[key];
208
- if (
209
- key === "nerdFontIcons" ||
210
- key === "finalRecap" ||
211
- key === "checklistIntegration" ||
212
- key === "housekeepingEnabled"
213
- ) {
214
- if (typeof value !== "boolean") throw new Error(requirement(key));
215
- layer[key] = value;
216
- continue;
217
- }
218
- if (key === "subagentExtensions") {
219
- if (
220
- typeof value !== "boolean" &&
221
- !(
222
- Array.isArray(value) &&
223
- value.every(
224
- (entry) =>
225
- typeof entry === "string" &&
226
- entry.length > 0 &&
227
- resolve(entry) === entry &&
228
- !entry.includes("\0"),
229
- )
230
- )
231
- )
232
- throw new Error(requirement(key));
233
- layer.subagentExtensions =
234
- typeof value === "boolean" ? value : [...new Set(value as string[])].sort();
235
- continue;
236
- }
237
- if (key === "housekeepingModel") {
238
- if (!isHousekeepingModel(value)) throw new Error(requirement(key));
239
- layer.housekeepingModel = value;
240
- continue;
241
- }
242
- if (key === "subagentMode") {
243
- if (!SUBAGENT_MODES.includes(value as SubagentMode)) throw new Error(requirement(key));
244
- layer.subagentMode = value as SubagentMode;
245
- continue;
246
- }
247
- if (key === "toolFiltering") {
248
- if (!TOOL_FILTERING_MODES.includes(value as ToolFilteringMode))
249
- throw new Error(requirement(key));
250
- layer.toolFiltering = value as ToolFilteringMode;
251
- continue;
252
- }
253
- if (key === "widgetMode") {
254
- if (!WIDGET_MODES.includes(value as WidgetMode)) throw new Error(requirement(key));
255
- layer.widgetMode = value as WidgetMode;
256
- continue;
257
- }
258
- if (key === "costDisplay") {
259
- if (!COST_DISPLAY_MODES.includes(value as CostDisplayMode)) throw new Error(requirement(key));
260
- layer.costDisplay = value as CostDisplayMode;
261
- continue;
262
- }
263
- if (key === "costValue") {
264
- if (!COST_VALUES.includes(value as CostValue)) throw new Error(requirement(key));
265
- layer.costValue = value as CostValue;
266
- continue;
267
- }
268
- if (key === "costIcon") {
269
- if (!COST_ICONS.includes(value as CostIcon)) throw new Error(requirement(key));
270
- layer.costIcon = value as CostIcon;
271
- continue;
272
- }
273
- if (key === "loaderStyle") {
274
- if (!LOADER_STYLES.includes(value as LoaderStyle)) throw new Error(requirement(key));
275
- layer.loaderStyle = value as LoaderStyle;
276
- continue;
277
- }
278
- if (key === "modelSelection") {
279
- if (!MODEL_SELECTION_MODES.includes(value as ModelSelectionMode))
280
- throw new Error(requirement(key));
281
- layer.modelSelection = value as ModelSelectionMode;
282
- continue;
283
- }
284
- if (!positiveSafeInteger(value)) throw new Error(requirement(key));
285
- if (key === "maxLevels" && value > MAX_LEVELS) throw new Error("maxLevels must be <= 32");
286
- layer[key] = value;
287
- }
288
- return layer;
289
- }
290
-
291
- interface SettingsLayer {
292
- filePath: string;
293
- directories: string[];
294
- }
295
-
296
- function layer(base: string, segments: string[]): SettingsLayer {
297
- let current = resolve(base);
298
- const directories = [current];
299
- for (const segment of segments) {
300
- current = join(current, segment);
301
- directories.push(current);
302
- }
303
- return { filePath: join(current, "settings.json"), directories };
304
- }
305
-
306
- function settingsFileExists(entry: SettingsLayer): boolean {
307
- for (const directory of entry.directories) {
308
- const stat = assertNotSymlinkPath(directory);
309
- if (!stat) return false;
310
- if (!stat.isDirectory())
311
- throw new Error(`Settings directory must be a directory: ${directory}`);
312
- }
313
- const stat = assertNotSymlinkPath(entry.filePath);
314
- if (!stat) return false;
315
- if (!stat.isFile()) throw new Error(`Settings must be a regular file: ${entry.filePath}`);
316
- return true;
317
- }
318
-
319
- export type ManagerSaveScope = "user" | "project";
320
-
321
- function detail(error: unknown): string {
322
- return error instanceof Error ? error.message : String(error);
323
- }
324
-
325
- export interface ManagerSettingsOptions {
326
- cwd: string;
327
- agentDir: string;
328
- includeProject: boolean;
329
- }
330
-
331
- export interface ManagerSettingsLayers {
332
- settings: ManagerSettings;
333
- diagnostics: string[];
334
- global: Partial<ManagerSettings>;
335
- project: Partial<ManagerSettings>;
336
- scope: ManagerSaveScope;
337
- }
338
-
339
- /** Validated layers retain provenance; save scope belongs to the current project. */
340
- export function loadManagerSettingsLayers(options: ManagerSettingsOptions): ManagerSettingsLayers {
341
- const result: ManagerSettingsLayers = {
342
- settings: { ...DEFAULT_MANAGER_SETTINGS },
343
- diagnostics: [],
344
- global: {},
345
- project: {},
346
- scope: "user",
347
- };
348
- const layers: ["global" | "project", SettingsLayer][] = [
349
- ["global", layer(options.agentDir, ["subagent-manager"])],
350
- ];
351
- if (options.includeProject)
352
- layers.push(["project", layer(options.cwd, [".pi", "agent", "subagent-manager"])]);
353
- for (const [scope, entry] of layers) {
354
- try {
355
- if (!settingsFileExists(entry)) continue;
356
- // Malformed/unreadable regular project files still represent a save destination.
357
- if (scope === "project") result.scope = "project";
358
- const parsed = parseSettings(readFileSync(entry.filePath, "utf8"));
359
- result[scope] = parsed;
360
- Object.assign(result.settings, parsed);
361
- } catch (error) {
362
- result.diagnostics.push(`${entry.filePath}: ${detail(error)}`);
363
- }
364
- }
365
- return result;
366
- }
367
-
368
- export function loadManagerSettings(options: ManagerSettingsOptions): {
369
- settings: ManagerSettings;
370
- diagnostics: string[];
371
- } {
372
- const { settings, diagnostics } = loadManagerSettingsLayers(options);
373
- return { settings, diagnostics };
374
- }
375
-
376
- function serializedSettings(settings: ManagerSettings): string {
377
- if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
378
- throw new Error("Settings must be a JSON object");
379
- }
380
- for (const key of Object.keys(settings)) {
381
- if (!isSupportedKey(key)) throw new Error(`Unknown settings key: ${key}`);
382
- }
383
- const parsed = parseSettings(JSON.stringify(settings));
384
- for (const key of KEYS) {
385
- if (!Object.hasOwn(parsed, key)) throw new Error(requirement(key));
386
- }
387
- const serialized = `${JSON.stringify(parsed, null, 2)}\n`;
388
- const confirmed = parseSettings(serialized);
389
- for (const key of KEYS) {
390
- if (!settingsValueEqual(confirmed[key], parsed[key])) throw new Error(requirement(key));
391
- }
392
- return serialized;
393
- }
394
-
395
- function assertExistingDirectory(directory: string): void {
396
- const stat = assertNotSymlinkPath(directory);
397
- if (!stat?.isDirectory()) throw new Error(`Settings directory must be a directory: ${directory}`);
398
- }
399
-
400
- function ensureOwnedDirectory(directory: string): void {
401
- let stat = assertNotSymlinkPath(directory);
402
- if (!stat) {
403
- try {
404
- mkdirSync(directory);
405
- } catch (error) {
406
- if (errorCode(error) !== "EEXIST") throw error;
407
- }
408
- stat = assertNotSymlinkPath(directory);
409
- }
410
- if (!stat?.isDirectory()) throw new Error(`Settings directory must be a directory: ${directory}`);
411
- }
412
-
413
- function ensureScopeDirectories(directories: string[]): void {
414
- assertExistingDirectory(directories[0]);
415
- for (let index = 1; index < directories.length; index++) {
416
- assertExistingDirectory(directories[index - 1]);
417
- ensureOwnedDirectory(directories[index]);
418
- }
419
- }
420
-
421
- function assertRegularFileOrAbsent(filePath: string): void {
422
- const stat = assertNotSymlinkPath(filePath);
423
- if (stat && !stat.isFile()) throw new Error(`Settings must be a regular file: ${filePath}`);
424
- }
425
-
426
- function exclusiveCreateFlags(): number {
427
- return constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0);
428
- }
429
-
430
- function writeAtomically(entry: SettingsLayer, content: string, overwrite = true): void {
431
- const filePath = entry.filePath;
432
- const temporary = join(dirname(filePath), `.settings.${randomUUID()}.tmp`);
433
- let created = false;
434
- try {
435
- for (const directory of entry.directories) assertExistingDirectory(directory);
436
- assertRegularFileOrAbsent(filePath);
437
- const fd = openSync(temporary, exclusiveCreateFlags(), 0o600);
438
- created = true;
439
- try {
440
- fchmodSync(fd, 0o600);
441
- writeFileSync(fd, content);
442
- } finally {
443
- closeSync(fd);
444
- }
445
- for (const directory of entry.directories) assertExistingDirectory(directory);
446
- assertRegularFileOrAbsent(filePath);
447
- const tempStat = assertNotSymlinkPath(temporary);
448
- if (!tempStat?.isFile()) throw new Error(`Settings must be a regular file: ${temporary}`);
449
- if (overwrite) renameSync(temporary, filePath);
450
- else {
451
- try {
452
- // Linking a completed temporary file creates the destination without clobbering
453
- // a settings file that appeared after the initial absence check.
454
- linkSync(temporary, filePath);
455
- } catch (error) {
456
- if (errorCode(error) !== "EEXIST") throw error;
457
- assertRegularFileOrAbsent(filePath);
458
- }
459
- }
460
- } finally {
461
- if (created) {
462
- try {
463
- if (lstatIfPresent(temporary)) unlinkSync(temporary);
464
- } catch {
465
- // Keep the original save error if cleanup fails.
466
- }
467
- }
468
- }
469
- }
470
-
471
- export function saveManagerSettings(options: {
472
- cwd: string;
473
- agentDir: string;
474
- includeProject: boolean;
475
- scope: "user" | "project";
476
- settings: ManagerSettings;
477
- }): string {
478
- if (options.scope !== "user" && options.scope !== "project") {
479
- throw new Error("Invalid settings scope");
480
- }
481
- if (options.scope === "project" && !options.includeProject) {
482
- throw new Error("Project settings are not enabled/trusted");
483
- }
484
- const content = serializedSettings(options.settings);
485
- const entry =
486
- options.scope === "user"
487
- ? layer(options.agentDir, ["subagent-manager"])
488
- : layer(options.cwd, [".pi", "agent", "subagent-manager"]);
489
- ensureScopeDirectories(entry.directories);
490
- writeAtomically(entry, content);
491
- return entry.filePath;
492
- }
493
-
494
- function assertExpectedLayers(
495
- current: ManagerSettingsLayers,
496
- expected: ManagerSettingsLayers,
497
- ): void {
498
- if (
499
- current.scope !== expected.scope ||
500
- KEYS.some(
501
- (key) =>
502
- !settingsValueEqual(current.global[key], expected.global[key]) ||
503
- !settingsValueEqual(current.project[key], expected.project[key]),
504
- ) ||
505
- current.diagnostics.length !== expected.diagnostics.length ||
506
- current.diagnostics.some((diagnostic, index) => diagnostic !== expected.diagnostics[index])
507
- ) {
508
- throw new Error(
509
- "Settings changed on disk. Reopen settings before saving or switching scope to avoid stale inherited values.",
510
- );
511
- }
512
- }
513
-
514
- /** Persist only values that change the selected scope's inherited settings. */
515
- export function saveManagerOverrides(
516
- options: ManagerSettingsOptions & {
517
- scope: ManagerSaveScope;
518
- settings: ManagerSettings;
519
- expectedLayers?: ManagerSettingsLayers;
520
- },
521
- ): string {
522
- if (options.scope !== "user" && options.scope !== "project")
523
- throw new Error("Invalid settings scope");
524
- if (options.scope === "project" && !options.includeProject)
525
- throw new Error("Project settings are not enabled/trusted");
526
- // Validate the complete draft before creating directories or modifying files.
527
- const parsed = parseSettings(serializedSettings(options.settings));
528
- const current = loadManagerSettingsLayers(options);
529
- if (options.expectedLayers) assertExpectedLayers(current, options.expectedLayers);
530
- if (options.scope === "project") {
531
- const globalPath = layer(options.agentDir, ["subagent-manager"]).filePath;
532
- const globalDiagnostics = current.diagnostics.filter((diagnostic) =>
533
- diagnostic.startsWith(`${globalPath}:`),
534
- );
535
- if (globalDiagnostics.length > 0)
536
- throw new Error(
537
- `Cannot save project overrides while global settings are invalid. Fix global settings and reopen settings. ${globalDiagnostics.join("; ")}`,
538
- );
539
- }
540
- const inherited =
541
- options.scope === "user"
542
- ? DEFAULT_MANAGER_SETTINGS
543
- : { ...DEFAULT_MANAGER_SETTINGS, ...current.global };
544
- const overrides = Object.fromEntries(
545
- KEYS.filter((key) => !settingsValueEqual(parsed[key], inherited[key])).map((key) => [
546
- key,
547
- parsed[key],
548
- ]),
549
- );
550
- const entry =
551
- options.scope === "user"
552
- ? layer(options.agentDir, ["subagent-manager"])
553
- : layer(options.cwd, [".pi", "agent", "subagent-manager"]);
554
- ensureScopeDirectories(entry.directories);
555
- writeAtomically(entry, `${JSON.stringify(overrides, null, 2)}\n`);
556
- return entry.filePath;
557
- }
558
-
559
- /** Confirmed scope transition: create an empty project layer or remove only its file. */
560
- export function setManagerProjectSettings(
561
- options: ManagerSettingsOptions & {
562
- enabled: boolean;
563
- expectedLayers?: ManagerSettingsLayers;
564
- },
565
- ): string {
566
- if (!options.includeProject) throw new Error("Project settings are not enabled/trusted");
567
- if (typeof options.enabled !== "boolean") throw new Error("Invalid project settings state");
568
- if (options.expectedLayers)
569
- assertExpectedLayers(loadManagerSettingsLayers(options), options.expectedLayers);
570
- const entry = layer(options.cwd, [".pi", "agent", "subagent-manager"]);
571
- const present = settingsFileExists(entry);
572
- if (options.enabled) {
573
- if (!present) {
574
- ensureScopeDirectories(entry.directories);
575
- writeAtomically(entry, "{}\n", false);
576
- }
577
- } else if (present) {
578
- // Recheck owned paths immediately before deletion; malformed JSON is removable.
579
- if (settingsFileExists(entry)) unlinkSync(entry.filePath);
580
- }
581
- return entry.filePath;
582
- }
583
-
584
- /** Resolved settings.json path for a scope; the file may not exist. */
585
- export function managerSettingsPath(
586
- options: ManagerSettingsOptions,
587
- scope: ManagerSaveScope,
588
- ): string {
589
- if (scope === "project") {
590
- if (!options.includeProject) throw new Error("Project settings are not enabled/trusted");
591
- return layer(options.cwd, [".pi", "agent", "subagent-manager"]).filePath;
592
- }
593
- return layer(options.agentDir, ["subagent-manager"]).filePath;
594
- }
595
-
596
- /** Restore a scope's defaults by deleting its settings file (nothing is written). A missing file is not an error. */
597
- export function deleteManagerSettings(
598
- options: ManagerSettingsOptions & { scope: ManagerSaveScope },
599
- ): {
600
- filePath: string;
601
- deleted: boolean;
602
- } {
603
- if (options.scope !== "user" && options.scope !== "project")
604
- throw new Error("Invalid settings scope");
605
- const filePath = managerSettingsPath(options, options.scope);
606
- const entry =
607
- options.scope === "project"
608
- ? layer(options.cwd, [".pi", "agent", "subagent-manager"])
609
- : layer(options.agentDir, ["subagent-manager"]);
610
- // Malformed JSON is removable; symlinks and non-files are refused by settingsFileExists.
611
- if (!settingsFileExists(entry)) return { filePath, deleted: false };
612
- unlinkSync(entry.filePath);
613
- return { filePath, deleted: true };
614
- }