pi-subagent-manager 1.9.0 → 1.11.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 (191) hide show
  1. package/agents/architect.md +4 -4
  2. package/agents/coder.md +3 -4
  3. package/agents/researcher.md +2 -2
  4. package/agents/writer.md +2 -5
  5. package/dist/index.d.ts +3 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +836 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/orch/checklist-integration.d.ts +48 -0
  10. package/dist/orch/checklist-integration.d.ts.map +1 -0
  11. package/dist/orch/checklist-integration.js +204 -0
  12. package/dist/orch/checklist-integration.js.map +1 -0
  13. package/dist/orch/context-entries.d.ts +8 -0
  14. package/dist/orch/context-entries.d.ts.map +1 -0
  15. package/dist/orch/context-entries.js +8 -0
  16. package/dist/orch/context-entries.js.map +1 -0
  17. package/dist/orch/cost-ledger.d.ts +16 -0
  18. package/dist/orch/cost-ledger.d.ts.map +1 -0
  19. package/dist/orch/cost-ledger.js +43 -0
  20. package/dist/orch/cost-ledger.js.map +1 -0
  21. package/dist/orch/diagnostics.d.ts +13 -0
  22. package/dist/orch/diagnostics.d.ts.map +1 -0
  23. package/dist/orch/diagnostics.js +95 -0
  24. package/dist/orch/diagnostics.js.map +1 -0
  25. package/dist/orch/extensions.d.ts +15 -0
  26. package/dist/orch/extensions.d.ts.map +1 -0
  27. package/dist/orch/extensions.js +80 -0
  28. package/dist/orch/extensions.js.map +1 -0
  29. package/dist/orch/housekeeping-usage.d.ts +14 -0
  30. package/dist/orch/housekeeping-usage.d.ts.map +1 -0
  31. package/dist/orch/housekeeping-usage.js +27 -0
  32. package/dist/orch/housekeeping-usage.js.map +1 -0
  33. package/dist/orch/housekeeping.d.ts +89 -0
  34. package/dist/orch/housekeeping.d.ts.map +1 -0
  35. package/dist/orch/housekeeping.js +281 -0
  36. package/dist/orch/housekeeping.js.map +1 -0
  37. package/dist/orch/inherited-tools.d.ts +18 -0
  38. package/dist/orch/inherited-tools.d.ts.map +1 -0
  39. package/dist/orch/inherited-tools.js +71 -0
  40. package/dist/orch/inherited-tools.js.map +1 -0
  41. package/dist/orch/mailbox.d.ts +59 -0
  42. package/dist/orch/mailbox.d.ts.map +1 -0
  43. package/dist/orch/mailbox.js +196 -0
  44. package/dist/orch/mailbox.js.map +1 -0
  45. package/dist/orch/manager.d.ts +82 -0
  46. package/dist/orch/manager.d.ts.map +1 -0
  47. package/dist/orch/manager.js +1010 -0
  48. package/dist/orch/manager.js.map +1 -0
  49. package/dist/orch/paths.d.ts +7 -0
  50. package/dist/orch/paths.d.ts.map +1 -0
  51. package/dist/orch/paths.js +73 -0
  52. package/dist/orch/paths.js.map +1 -0
  53. package/dist/orch/prompt.d.ts +7 -0
  54. package/dist/orch/prompt.d.ts.map +1 -0
  55. package/dist/orch/prompt.js +34 -0
  56. package/dist/orch/prompt.js.map +1 -0
  57. package/dist/orch/registry.d.ts +49 -0
  58. package/dist/orch/registry.d.ts.map +1 -0
  59. package/dist/orch/registry.js +134 -0
  60. package/dist/orch/registry.js.map +1 -0
  61. package/dist/orch/runtime.d.ts +11 -0
  62. package/dist/orch/runtime.d.ts.map +1 -0
  63. package/dist/orch/runtime.js +882 -0
  64. package/dist/orch/runtime.js.map +1 -0
  65. package/dist/orch/tools.d.ts +6 -0
  66. package/dist/orch/tools.d.ts.map +1 -0
  67. package/dist/orch/tools.js +114 -0
  68. package/dist/orch/tools.js.map +1 -0
  69. package/dist/orch/transcript.d.ts +28 -0
  70. package/dist/orch/transcript.d.ts.map +1 -0
  71. package/dist/orch/transcript.js +176 -0
  72. package/dist/orch/transcript.js.map +1 -0
  73. package/dist/prefs/agent-import.d.ts +37 -0
  74. package/dist/prefs/agent-import.d.ts.map +1 -0
  75. package/dist/prefs/agent-import.js +196 -0
  76. package/dist/prefs/agent-import.js.map +1 -0
  77. package/dist/prefs/config.d.ts +108 -0
  78. package/dist/prefs/config.d.ts.map +1 -0
  79. package/dist/prefs/config.js +926 -0
  80. package/dist/prefs/config.js.map +1 -0
  81. package/dist/prefs/import-discovery.d.ts +28 -0
  82. package/dist/prefs/import-discovery.d.ts.map +1 -0
  83. package/dist/prefs/import-discovery.js +562 -0
  84. package/dist/prefs/import-discovery.js.map +1 -0
  85. package/dist/prefs/import-instructions.d.ts +3 -0
  86. package/dist/prefs/import-instructions.d.ts.map +1 -0
  87. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +1 -0
  88. package/dist/prefs/import-instructions.js.map +1 -0
  89. package/dist/prefs/models.d.ts +24 -0
  90. package/dist/prefs/models.d.ts.map +1 -0
  91. package/dist/prefs/models.js +57 -0
  92. package/dist/prefs/models.js.map +1 -0
  93. package/dist/prefs/settings.d.ts +89 -0
  94. package/dist/prefs/settings.d.ts.map +1 -0
  95. package/dist/prefs/settings.js +505 -0
  96. package/dist/prefs/settings.js.map +1 -0
  97. package/dist/types.d.ts +293 -0
  98. package/dist/types.d.ts.map +1 -0
  99. package/dist/types.js +2 -0
  100. package/dist/types.js.map +1 -0
  101. package/dist/ui/agent-loader.d.ts +21 -0
  102. package/dist/ui/agent-loader.d.ts.map +1 -0
  103. package/dist/ui/agent-loader.js +73 -0
  104. package/dist/ui/agent-loader.js.map +1 -0
  105. package/dist/ui/agent-navigation-editor.d.ts +46 -0
  106. package/dist/ui/agent-navigation-editor.d.ts.map +1 -0
  107. package/dist/ui/agent-navigation-editor.js +189 -0
  108. package/dist/ui/agent-navigation-editor.js.map +1 -0
  109. package/dist/ui/cost-footer.d.ts +37 -0
  110. package/dist/ui/cost-footer.d.ts.map +1 -0
  111. package/dist/ui/cost-footer.js +215 -0
  112. package/dist/ui/cost-footer.js.map +1 -0
  113. package/dist/ui/dialog.d.ts +135 -0
  114. package/dist/ui/dialog.d.ts.map +1 -0
  115. package/dist/ui/dialog.js +533 -0
  116. package/dist/ui/dialog.js.map +1 -0
  117. package/dist/ui/import-picker.d.ts +38 -0
  118. package/dist/ui/import-picker.d.ts.map +1 -0
  119. package/dist/ui/import-picker.js +211 -0
  120. package/dist/ui/import-picker.js.map +1 -0
  121. package/dist/ui/live-agent-view.d.ts +82 -0
  122. package/dist/ui/live-agent-view.d.ts.map +1 -0
  123. package/dist/ui/live-agent-view.js +546 -0
  124. package/dist/ui/live-agent-view.js.map +1 -0
  125. package/dist/ui/model-picker.d.ts +109 -0
  126. package/dist/ui/model-picker.d.ts.map +1 -0
  127. package/dist/ui/model-picker.js +549 -0
  128. package/dist/ui/model-picker.js.map +1 -0
  129. package/dist/ui/settings-ui.d.ts +17 -0
  130. package/dist/ui/settings-ui.d.ts.map +1 -0
  131. package/dist/ui/settings-ui.js +679 -0
  132. package/dist/ui/settings-ui.js.map +1 -0
  133. package/dist/ui/status-ui.d.ts +67 -0
  134. package/dist/ui/status-ui.d.ts.map +1 -0
  135. package/dist/ui/status-ui.js +487 -0
  136. package/dist/ui/status-ui.js.map +1 -0
  137. package/dist/ui/thread-tree.d.ts +22 -0
  138. package/dist/ui/thread-tree.d.ts.map +1 -0
  139. package/dist/ui/thread-tree.js +153 -0
  140. package/dist/ui/thread-tree.js.map +1 -0
  141. package/dist/ui/tool-picker.d.ts +46 -0
  142. package/dist/ui/tool-picker.d.ts.map +1 -0
  143. package/dist/ui/tool-picker.js +334 -0
  144. package/dist/ui/tool-picker.js.map +1 -0
  145. package/dist/ui/transcript-tool.d.ts +2 -0
  146. package/dist/ui/transcript-tool.d.ts.map +1 -0
  147. package/dist/ui/transcript-tool.js +100 -0
  148. package/dist/ui/transcript-tool.js.map +1 -0
  149. package/dist/ui/ui.d.ts +41 -0
  150. package/dist/ui/ui.d.ts.map +1 -0
  151. package/dist/ui/ui.js +1047 -0
  152. package/dist/ui/ui.js.map +1 -0
  153. package/docs/default-agents.md +11 -13
  154. package/docs/development.md +2 -1
  155. package/package.json +16 -4
  156. package/src/index.ts +0 -920
  157. package/src/orch/checklist-integration.ts +0 -230
  158. package/src/orch/context-entries.ts +0 -15
  159. package/src/orch/cost-ledger.ts +0 -56
  160. package/src/orch/diagnostics.ts +0 -95
  161. package/src/orch/extensions.ts +0 -83
  162. package/src/orch/housekeeping-usage.ts +0 -47
  163. package/src/orch/housekeeping.ts +0 -348
  164. package/src/orch/inherited-tools.ts +0 -84
  165. package/src/orch/mailbox.ts +0 -261
  166. package/src/orch/manager.ts +0 -1084
  167. package/src/orch/paths.ts +0 -73
  168. package/src/orch/prompt.ts +0 -39
  169. package/src/orch/registry.ts +0 -168
  170. package/src/orch/runtime.ts +0 -1041
  171. package/src/orch/tools.ts +0 -190
  172. package/src/orch/transcript.ts +0 -186
  173. package/src/prefs/agent-import.ts +0 -245
  174. package/src/prefs/config.ts +0 -1017
  175. package/src/prefs/import-discovery.ts +0 -643
  176. package/src/prefs/models.ts +0 -74
  177. package/src/prefs/settings.ts +0 -614
  178. package/src/types.ts +0 -271
  179. package/src/ui/agent-loader.ts +0 -98
  180. package/src/ui/agent-navigation-editor.ts +0 -233
  181. package/src/ui/cost-footer.ts +0 -230
  182. package/src/ui/dialog.ts +0 -678
  183. package/src/ui/import-picker.ts +0 -231
  184. package/src/ui/live-agent-view.ts +0 -600
  185. package/src/ui/model-picker.ts +0 -701
  186. package/src/ui/settings-ui.ts +0 -830
  187. package/src/ui/status-ui.ts +0 -628
  188. package/src/ui/thread-tree.ts +0 -173
  189. package/src/ui/tool-picker.ts +0 -398
  190. package/src/ui/transcript-tool.ts +0 -142
  191. 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
- }