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,878 @@
1
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { randomUUID } from "node:crypto";
5
+ import { isMap, isScalar, parseDocument, stringify } from "yaml";
6
+ import { getModelPreferences } from "./models.js";
7
+ import { THINKING_LEVELS } from "../types.js";
8
+ export const AGENT_COLORS = [
9
+ "accent",
10
+ "border",
11
+ "borderAccent",
12
+ "borderMuted",
13
+ "success",
14
+ "error",
15
+ "warning",
16
+ "muted",
17
+ "dim",
18
+ "text",
19
+ "thinkingText",
20
+ "scrollbarTrack",
21
+ "scrollbarThumb",
22
+ "searchMatchText",
23
+ "userMessageText",
24
+ "customMessageText",
25
+ "customMessageLabel",
26
+ "toolTitle",
27
+ "toolOutput",
28
+ "mdHeading",
29
+ "mdLink",
30
+ "mdLinkUrl",
31
+ "mdCode",
32
+ "mdCodeBlock",
33
+ "mdCodeBlockBorder",
34
+ "mdQuote",
35
+ "mdQuoteBorder",
36
+ "mdHr",
37
+ "mdListBullet",
38
+ "toolDiffAdded",
39
+ "toolDiffRemoved",
40
+ "toolDiffContext",
41
+ "syntaxComment",
42
+ "syntaxKeyword",
43
+ "syntaxFunction",
44
+ "syntaxVariable",
45
+ "syntaxString",
46
+ "syntaxNumber",
47
+ "syntaxType",
48
+ "syntaxOperator",
49
+ "syntaxPunctuation",
50
+ "thinkingOff",
51
+ "thinkingMinimal",
52
+ "thinkingLow",
53
+ "thinkingMedium",
54
+ "thinkingHigh",
55
+ "thinkingXhigh",
56
+ "thinkingMax",
57
+ "bashMode",
58
+ ];
59
+ const NAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
60
+ const TOOL = /^[a-zA-Z0-9_-]+$/;
61
+ const FIELDS = new Set([
62
+ "name",
63
+ "description",
64
+ "models",
65
+ "model",
66
+ "modelSuggestions",
67
+ "thinkingLevel",
68
+ "color",
69
+ "icon",
70
+ "tools",
71
+ ]);
72
+ const SUBAGENT_MANAGER_DIR = "subagent-manager";
73
+ const AGENTS_DIR = "agents";
74
+ function errorCode(error) {
75
+ return typeof error === "object" && error !== null && "code" in error
76
+ ? String(error.code)
77
+ : undefined;
78
+ }
79
+ function lstatIfPresent(path) {
80
+ try {
81
+ return lstatSync(path);
82
+ }
83
+ catch (error) {
84
+ if (errorCode(error) === "ENOENT")
85
+ return undefined;
86
+ throw error;
87
+ }
88
+ }
89
+ function assertNotSymlinkPath(path) {
90
+ const stat = lstatIfPresent(path);
91
+ if (stat?.isSymbolicLink())
92
+ throw new Error(`Unsafe symlink path: ${path}`);
93
+ return stat;
94
+ }
95
+ function validatePreservedDestination(filePath, directory, extensions = [".md"]) {
96
+ const resolved = resolve(filePath);
97
+ if (dirname(resolved) !== directory ||
98
+ !extensions.some((extension) => resolved.endsWith(extension)))
99
+ throw new Error(`Unsafe agent destination: ${resolved}`);
100
+ const stat = lstatIfPresent(resolved);
101
+ if (!stat?.isFile())
102
+ throw new Error(`Unsafe agent destination: ${resolved}`);
103
+ return resolved;
104
+ }
105
+ function frontmatter(content) {
106
+ const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(content);
107
+ if (!match || match.index !== 0)
108
+ throw new Error("Expected YAML frontmatter enclosed by --- lines");
109
+ return { yaml: match[1], body: content.slice(match[0].length) };
110
+ }
111
+ function record(value, label) {
112
+ if (value === null || typeof value !== "object" || Array.isArray(value))
113
+ throw new Error(`${label} must be a mapping`);
114
+ return value;
115
+ }
116
+ function modelSuggestionNames(value) {
117
+ if (!Array.isArray(value))
118
+ throw new Error("modelSuggestions must be an array of nonempty display names");
119
+ const suggestions = value.map((entry, index) => {
120
+ if (typeof entry !== "string")
121
+ throw new Error(`modelSuggestions[${index}] must be a nonempty display name`);
122
+ const name = entry.trim();
123
+ if (!name)
124
+ throw new Error(`modelSuggestions[${index}] must be a nonempty display name`);
125
+ return name;
126
+ });
127
+ if (new Set(suggestions).size !== suggestions.length)
128
+ throw new Error("modelSuggestions contains duplicate display names");
129
+ return [...suggestions];
130
+ }
131
+ function toolNames(value, label) {
132
+ if (!Array.isArray(value) || value.some((name) => typeof name !== "string" || !TOOL.test(name))) {
133
+ throw new Error(`${label} must be an array of exact tool names (no wildcards or patterns)`);
134
+ }
135
+ if (new Set(value).size !== value.length)
136
+ throw new Error(`${label} contains duplicate tool names`);
137
+ return [...value];
138
+ }
139
+ function toolPolicy(value) {
140
+ const mapping = record(value, "tools");
141
+ for (const key of Object.keys(mapping))
142
+ if (key !== "allow" && key !== "block")
143
+ throw new Error(`Unknown tools field: ${key}`);
144
+ const result = {};
145
+ if (Object.hasOwn(mapping, "allow"))
146
+ result.allow = toolNames(mapping.allow, "tools.allow");
147
+ if (Object.hasOwn(mapping, "block"))
148
+ result.block = toolNames(mapping.block, "tools.block");
149
+ return result;
150
+ }
151
+ function overrideToolPolicy(value) {
152
+ const mapping = record(value, "tools");
153
+ const result = {};
154
+ for (const key of Object.keys(mapping)) {
155
+ if (key !== "allow" && key !== "block")
156
+ throw new Error(`Unknown tools field: ${key}`);
157
+ result[key] = mapping[key] === null ? null : toolNames(mapping[key], `tools.${key}`);
158
+ }
159
+ return result;
160
+ }
161
+ export function parseAgentType(content, filePath) {
162
+ try {
163
+ const { yaml, body } = frontmatter(content);
164
+ const doc = parseDocument(yaml, { uniqueKeys: true });
165
+ if (doc.errors.length)
166
+ throw new Error(doc.errors.map((error) => error.message).join("; "));
167
+ const data = record(doc.toJS({ maxAliasCount: 0 }), "Frontmatter");
168
+ for (const key of Object.keys(data))
169
+ if (!FIELDS.has(key))
170
+ throw new Error(`Unknown frontmatter field: ${key}`);
171
+ if (typeof data.name !== "string" || !NAME.test(data.name))
172
+ throw new Error("name must be a safe identifier using letters, numbers, underscores or hyphens");
173
+ if (typeof data.description !== "string" || !data.description.trim())
174
+ throw new Error("description must be a nonempty string");
175
+ const result = {
176
+ name: data.name,
177
+ description: data.description,
178
+ systemPrompt: body,
179
+ };
180
+ const models = getModelPreferences({
181
+ models: data.models,
182
+ model: data.model,
183
+ });
184
+ if (models !== undefined)
185
+ result.models = models;
186
+ if (Object.hasOwn(data, "modelSuggestions"))
187
+ result.modelSuggestions = modelSuggestionNames(data.modelSuggestions);
188
+ if (Object.hasOwn(data, "thinkingLevel")) {
189
+ if (!THINKING_LEVELS.includes(data.thinkingLevel))
190
+ throw new Error(`thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`);
191
+ result.thinkingLevel = data.thinkingLevel;
192
+ }
193
+ if (Object.hasOwn(data, "color")) {
194
+ if (!AGENT_COLORS.includes(data.color))
195
+ throw new Error(`color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`);
196
+ result.color = data.color;
197
+ }
198
+ if (Object.hasOwn(data, "icon")) {
199
+ if (typeof data.icon !== "string" || !/^\p{Co}$/u.test(data.icon))
200
+ throw new Error("icon must be a single literal Nerd Font glyph (Unicode private-use character)");
201
+ result.icon = data.icon;
202
+ }
203
+ if (Object.hasOwn(data, "tools"))
204
+ result.tools = toolPolicy(data.tools);
205
+ if (filePath !== undefined)
206
+ result.filePath = filePath;
207
+ return result;
208
+ }
209
+ catch (error) {
210
+ throw new Error(`${filePath ?? "Agent definition"}: ${error instanceof Error ? error.message : String(error)}`);
211
+ }
212
+ }
213
+ export function serializeAgentType(type) {
214
+ if (typeof type.systemPrompt !== "string")
215
+ throw new Error("systemPrompt must be a string");
216
+ const data = {
217
+ name: type.name,
218
+ description: type.description,
219
+ };
220
+ const models = getModelPreferences(type);
221
+ if (models !== undefined)
222
+ data.models = models;
223
+ if (type.modelSuggestions !== undefined)
224
+ data.modelSuggestions = modelSuggestionNames(type.modelSuggestions);
225
+ for (const key of ["thinkingLevel", "color", "icon", "tools"])
226
+ if (type[key] !== undefined)
227
+ data[key] = type[key];
228
+ const content = `---\n${stringify(data)}---\n${type.systemPrompt}`;
229
+ parseAgentType(content);
230
+ return content;
231
+ }
232
+ const AGENT_OVERRIDE_EXTENSIONS = [".yml", ".yaml"];
233
+ function overrideBaseName(file) {
234
+ for (const extension of AGENT_OVERRIDE_EXTENSIONS)
235
+ if (file.endsWith(extension))
236
+ return file.slice(0, -extension.length);
237
+ return undefined;
238
+ }
239
+ function isAgentOverrideFile(file) {
240
+ return overrideBaseName(file) !== undefined;
241
+ }
242
+ function nullableField(value, validate) {
243
+ if (value === null)
244
+ return null;
245
+ return validate(value);
246
+ }
247
+ export function parseAgentSettings(content, filePath, expectedName) {
248
+ const label = filePath ?? "Agent settings override";
249
+ try {
250
+ if (/^\uFEFF?---[ \t]*\r?\n/m.test(content) || content.includes("\n---"))
251
+ throw new Error("Settings overrides are plain YAML with no frontmatter and no Markdown body");
252
+ const doc = parseDocument(content, { uniqueKeys: true });
253
+ if (doc.errors.length)
254
+ throw new Error(doc.errors.map((error) => error.message).join("; "));
255
+ const data = record(doc.toJS({ maxAliasCount: 0 }) ?? {}, "Settings override");
256
+ for (const key of Object.keys(data)) {
257
+ if (key === "systemPrompt" || key === "prompt" || key === "body")
258
+ throw new Error(`Settings overrides carry no prompt body; "${key}" belongs in a <name>.md fork`);
259
+ if (!FIELDS.has(key))
260
+ throw new Error(`Unknown settings field: ${key}`);
261
+ }
262
+ const result = {};
263
+ if (Object.hasOwn(data, "name")) {
264
+ if (typeof data.name !== "string" || !NAME.test(data.name))
265
+ throw new Error("name must be a safe identifier using letters, numbers, underscores or hyphens");
266
+ if (expectedName !== undefined && data.name !== expectedName)
267
+ throw new Error(`name ${JSON.stringify(data.name)} does not match override file ${JSON.stringify(expectedName)}`);
268
+ result.name = data.name;
269
+ }
270
+ if (Object.hasOwn(data, "description")) {
271
+ if (typeof data.description !== "string" || !data.description.trim())
272
+ throw new Error("description must be a nonempty string");
273
+ result.description = data.description;
274
+ }
275
+ const hasModels = Object.hasOwn(data, "models");
276
+ const hasModel = Object.hasOwn(data, "model");
277
+ if (hasModels && hasModel)
278
+ throw new Error("Specify either models or model, not both");
279
+ if (hasModels)
280
+ result.models = nullableField(data.models, (value) => getModelPreferences({ models: value }));
281
+ if (hasModel) {
282
+ if (data.model === null)
283
+ result.model = null;
284
+ else
285
+ result.models = getModelPreferences({ model: data.model });
286
+ }
287
+ if (Object.hasOwn(data, "modelSuggestions"))
288
+ result.modelSuggestions = nullableField(data.modelSuggestions, (value) => modelSuggestionNames(value));
289
+ if (Object.hasOwn(data, "thinkingLevel"))
290
+ result.thinkingLevel = nullableField(data.thinkingLevel, (value) => {
291
+ if (!THINKING_LEVELS.includes(value))
292
+ throw new Error(`thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`);
293
+ return value;
294
+ });
295
+ if (Object.hasOwn(data, "color"))
296
+ result.color = nullableField(data.color, (value) => {
297
+ if (!AGENT_COLORS.includes(value))
298
+ throw new Error(`color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`);
299
+ return value;
300
+ });
301
+ if (Object.hasOwn(data, "icon"))
302
+ result.icon = nullableField(data.icon, (value) => {
303
+ if (typeof value !== "string" || !/^\p{Co}$/u.test(value))
304
+ throw new Error("icon must be a single literal Nerd Font glyph (Unicode private-use character)");
305
+ return value;
306
+ });
307
+ if (Object.hasOwn(data, "tools"))
308
+ result.tools = data.tools === null ? null : overrideToolPolicy(data.tools);
309
+ return result;
310
+ }
311
+ catch (error) {
312
+ throw new Error(`${label}: ${error instanceof Error ? error.message : String(error)}`);
313
+ }
314
+ }
315
+ export function serializeAgentSettings(override) {
316
+ const data = {};
317
+ if (override.name !== undefined)
318
+ data.name = override.name;
319
+ if (override.description !== undefined)
320
+ data.description = override.description;
321
+ const models = getModelPreferences({
322
+ models: override.models ?? undefined,
323
+ model: override.model ?? undefined,
324
+ });
325
+ if (override.models === null || override.model === null)
326
+ data.models = null;
327
+ else if (models !== undefined)
328
+ data.models = models;
329
+ if (override.modelSuggestions !== undefined)
330
+ data.modelSuggestions =
331
+ override.modelSuggestions === null ? null : modelSuggestionNames(override.modelSuggestions);
332
+ for (const key of ["thinkingLevel", "color", "icon", "tools"])
333
+ if (override[key] !== undefined)
334
+ data[key] = override[key];
335
+ const content = `${stringify(data)}`;
336
+ parseAgentSettings(content);
337
+ return content;
338
+ }
339
+ export function mergeAgentSettings(base, override) {
340
+ const merged = structuredClone(base);
341
+ if (override.description !== undefined)
342
+ merged.description = override.description;
343
+ const models = getModelPreferences({
344
+ models: override.models ?? undefined,
345
+ model: override.model ?? undefined,
346
+ });
347
+ if (override.models === null || override.model === null) {
348
+ delete merged.models;
349
+ delete merged.model;
350
+ }
351
+ else if (models !== undefined) {
352
+ merged.models = [...models];
353
+ delete merged.model;
354
+ }
355
+ for (const key of ["modelSuggestions", "thinkingLevel", "color", "icon"]) {
356
+ const value = override[key];
357
+ if (value === undefined)
358
+ continue;
359
+ if (value === null)
360
+ delete merged[key];
361
+ else
362
+ merged[key] = structuredClone(value);
363
+ }
364
+ if (override.tools === null)
365
+ delete merged.tools;
366
+ else if (override.tools !== undefined) {
367
+ merged.tools ??= {};
368
+ for (const key of ["allow", "block"]) {
369
+ const value = override.tools[key];
370
+ if (value === null)
371
+ delete merged.tools[key];
372
+ else if (value !== undefined)
373
+ merged.tools[key] = [...value];
374
+ }
375
+ if (!Object.keys(merged.tools).length)
376
+ delete merged.tools;
377
+ }
378
+ merged.systemPrompt = base.systemPrompt;
379
+ return merged;
380
+ }
381
+ export function diffAgentSettings(base, draft) {
382
+ const override = {};
383
+ if (draft.description !== base.description)
384
+ override.description = draft.description;
385
+ const baseModels = getModelPreferences(base);
386
+ const draftModels = getModelPreferences(draft);
387
+ const sameModels = (baseModels === undefined && draftModels === undefined) ||
388
+ (baseModels !== undefined &&
389
+ draftModels !== undefined &&
390
+ baseModels.length === draftModels.length &&
391
+ baseModels.every((model, index) => model === draftModels[index]));
392
+ if (!sameModels) {
393
+ if (draftModels === undefined)
394
+ override.models = null;
395
+ else
396
+ override.models = [...draftModels];
397
+ }
398
+ for (const key of ["modelSuggestions", "thinkingLevel", "color", "icon"]) {
399
+ const before = base[key];
400
+ const after = draft[key];
401
+ if (sameSetting(before, after))
402
+ continue;
403
+ if (after === undefined)
404
+ override[key] = null;
405
+ else
406
+ override[key] = structuredClone(after);
407
+ }
408
+ for (const key of ["allow", "block"]) {
409
+ if (sameSetting(base.tools?.[key], draft.tools?.[key]))
410
+ continue;
411
+ override.tools ??= {};
412
+ override.tools[key] = draft.tools?.[key] === undefined ? null : [...draft.tools[key]];
413
+ }
414
+ return override;
415
+ }
416
+ function sameSetting(before, after) {
417
+ return JSON.stringify(before ?? null) === JSON.stringify(after ?? null);
418
+ }
419
+ function updateAgentSettings(base, before, draft, existing) {
420
+ const result = structuredClone(existing);
421
+ const edits = diffAgentSettings(before, draft);
422
+ const desired = diffAgentSettings(base, draft);
423
+ for (const key of [
424
+ "description",
425
+ "models",
426
+ "modelSuggestions",
427
+ "thinkingLevel",
428
+ "color",
429
+ "icon",
430
+ ]) {
431
+ if (!Object.hasOwn(edits, key))
432
+ continue;
433
+ if (desired[key] === undefined)
434
+ delete result[key];
435
+ else
436
+ result[key] = desired[key];
437
+ if (key === "models")
438
+ delete result.model;
439
+ }
440
+ if (edits.tools) {
441
+ if (result.tools === null)
442
+ result.tools = { allow: null, block: null };
443
+ const tools = result.tools ?? {};
444
+ for (const key of ["allow", "block"]) {
445
+ if (!Object.hasOwn(edits.tools, key))
446
+ continue;
447
+ const value = desired.tools?.[key];
448
+ if (value === undefined)
449
+ delete tools[key];
450
+ else
451
+ tools[key] = value;
452
+ }
453
+ if (Object.keys(tools).length)
454
+ result.tools = tools;
455
+ else
456
+ delete result.tools;
457
+ }
458
+ return result;
459
+ }
460
+ export function selectTools(policy, available, mode = "allowed") {
461
+ const names = new Set(available);
462
+ if (mode === "all")
463
+ return [...names];
464
+ const relevantPolicy = mode === "all-except-blocked"
465
+ ? policy?.block === undefined
466
+ ? {}
467
+ : { block: policy.block }
468
+ : policy;
469
+ const validated = relevantPolicy === undefined ? {} : toolPolicy(relevantPolicy);
470
+ for (const name of [...(validated.allow ?? []), ...(validated.block ?? [])]) {
471
+ if (!names.has(name))
472
+ throw new Error(`Unavailable tool name: ${name}`);
473
+ }
474
+ const allow = mode === "all-except-blocked" ? names : new Set(validated.allow ?? []);
475
+ const block = new Set(validated.block ?? []);
476
+ return [...names].filter((name) => allow.has(name) && !block.has(name));
477
+ }
478
+ export class ConfigStore {
479
+ diagnostics = [];
480
+ types = new Map();
481
+ bases = new Map();
482
+ scopeBases = new Map();
483
+ scopeOverrides = new Map();
484
+ options;
485
+ constructor(options) {
486
+ this.options = { ...options };
487
+ this.reload();
488
+ }
489
+ reload() {
490
+ this.types.clear();
491
+ this.bases.clear();
492
+ this.scopeBases.clear();
493
+ this.scopeOverrides.clear();
494
+ this.diagnostics = [];
495
+ const layers = [
496
+ [
497
+ this.options.bundledDir ?? fileURLToPath(new URL("../../agents/", import.meta.url)),
498
+ "bundled",
499
+ ],
500
+ ...this.scopeDirectories("user").map((directory) => [directory, "user"]),
501
+ ];
502
+ if (this.options.includeProject)
503
+ layers.push(...this.scopeDirectories("project").map((directory) => [directory, "project"]));
504
+ for (const [directory, source] of layers) {
505
+ if (source !== "bundled") {
506
+ this.scopeBases.set(source, structuredClone(this.types));
507
+ this.scopeOverrides.set(source, new Map());
508
+ }
509
+ let files;
510
+ try {
511
+ const stat = assertNotSymlinkPath(directory);
512
+ if (!stat)
513
+ continue;
514
+ if (!stat.isDirectory())
515
+ throw new Error(`Agent directory must be a directory: ${directory}`);
516
+ files = readdirSync(directory)
517
+ .filter((file) => file.endsWith(".md") || isAgentOverrideFile(file))
518
+ .sort();
519
+ }
520
+ catch (error) {
521
+ this.diagnostics.push(`${directory}: ${String(error)}`);
522
+ this.types.clear();
523
+ this.bases.clear();
524
+ continue;
525
+ }
526
+ if (source === "bundled") {
527
+ this.loadBundledLayer(directory, files);
528
+ continue;
529
+ }
530
+ this.applyScopeLayer(directory, source, files);
531
+ }
532
+ }
533
+ loadBundledLayer(directory, files) {
534
+ const blocked = new Set();
535
+ const seenNames = new Set();
536
+ for (const file of files) {
537
+ const filePath = join(directory, file);
538
+ if (isAgentOverrideFile(file)) {
539
+ blocked.add(overrideBaseName(file));
540
+ this.diagnostics.push(`${filePath}: Settings overrides (<name>.yml) are not allowed in the bundled layer`);
541
+ continue;
542
+ }
543
+ let content = "";
544
+ try {
545
+ if (!lstatSync(filePath).isFile())
546
+ throw new Error("Agent definition must be a regular file, not a symlink");
547
+ content = readFileSync(filePath, "utf8");
548
+ const type = parseAgentType(content, filePath);
549
+ if (seenNames.has(type.name)) {
550
+ blocked.add(type.name);
551
+ this.diagnostics.push(`${filePath}: Duplicate agent name in bundled layer: ${type.name}`);
552
+ continue;
553
+ }
554
+ seenNames.add(type.name);
555
+ this.types.set(type.name, { ...type, source: "bundled" });
556
+ }
557
+ catch (error) {
558
+ blocked.add(file.slice(0, -3));
559
+ try {
560
+ const doc = parseDocument(frontmatter(content).yaml);
561
+ if (isMap(doc.contents))
562
+ for (const pair of doc.contents.items) {
563
+ if (isScalar(pair.key) &&
564
+ pair.key.value === "name" &&
565
+ isScalar(pair.value) &&
566
+ typeof pair.value.value === "string")
567
+ blocked.add(pair.value.value);
568
+ }
569
+ }
570
+ catch {
571
+ }
572
+ this.diagnostics.push(`${filePath}: ${String(error)}`);
573
+ }
574
+ }
575
+ for (const name of blocked) {
576
+ this.types.delete(name);
577
+ this.bases.delete(name);
578
+ }
579
+ }
580
+ applyScopeLayer(directory, scope, files) {
581
+ const blocked = new Set();
582
+ const forks = new Map();
583
+ const overrides = new Map();
584
+ const forkNames = new Set();
585
+ const declareBlocked = (name) => {
586
+ blocked.add(name);
587
+ };
588
+ for (const file of files) {
589
+ const filePath = join(directory, file);
590
+ const overrideName = overrideBaseName(file);
591
+ if (overrideName !== undefined) {
592
+ if (!NAME.test(overrideName)) {
593
+ declareBlocked(overrideName);
594
+ this.diagnostics.push(`${filePath}: Invalid agent name in override filename`);
595
+ continue;
596
+ }
597
+ let content = "";
598
+ try {
599
+ if (!lstatSync(filePath).isFile())
600
+ throw new Error("Agent settings override must be a regular file, not a symlink");
601
+ content = readFileSync(filePath, "utf8");
602
+ const override = parseAgentSettings(content, filePath, overrideName);
603
+ const key = override.name ?? overrideName;
604
+ if (forkNames.has(key)) {
605
+ declareBlocked(key);
606
+ this.diagnostics.push(`${filePath}: Use either ${key}.md (full fork) or ${key}.yml (settings override), not both`);
607
+ continue;
608
+ }
609
+ if (overrides.has(key)) {
610
+ declareBlocked(key);
611
+ this.diagnostics.push(`${filePath}: Duplicate agent override in ${scope} layer: ${key}`);
612
+ continue;
613
+ }
614
+ overrides.set(key, { override, file });
615
+ }
616
+ catch (error) {
617
+ declareBlocked(overrideName);
618
+ try {
619
+ const doc = parseDocument(content);
620
+ if (isMap(doc.contents))
621
+ for (const pair of doc.contents.items) {
622
+ if (isScalar(pair.key) &&
623
+ pair.key.value === "name" &&
624
+ isScalar(pair.value) &&
625
+ typeof pair.value.value === "string")
626
+ declareBlocked(pair.value.value);
627
+ }
628
+ }
629
+ catch {
630
+ }
631
+ this.diagnostics.push(`${filePath}: ${String(error)}`);
632
+ }
633
+ continue;
634
+ }
635
+ let content = "";
636
+ try {
637
+ if (!lstatSync(filePath).isFile())
638
+ throw new Error("Agent definition must be a regular file, not a symlink");
639
+ content = readFileSync(filePath, "utf8");
640
+ const type = parseAgentType(content, filePath);
641
+ if (overrides.has(type.name)) {
642
+ declareBlocked(type.name);
643
+ this.diagnostics.push(`${filePath}: Use either ${type.name}.md (full fork) or ${type.name}.yml (settings override), not both`);
644
+ continue;
645
+ }
646
+ if (forkNames.has(type.name)) {
647
+ declareBlocked(type.name);
648
+ this.diagnostics.push(`${filePath}: Duplicate agent name in ${scope} layer: ${type.name}`);
649
+ continue;
650
+ }
651
+ forkNames.add(type.name);
652
+ forks.set(type.name, { type, file });
653
+ }
654
+ catch (error) {
655
+ declareBlocked(file.slice(0, -3));
656
+ try {
657
+ const doc = parseDocument(frontmatter(content).yaml);
658
+ if (isMap(doc.contents))
659
+ for (const pair of doc.contents.items) {
660
+ if (isScalar(pair.key) &&
661
+ pair.key.value === "name" &&
662
+ isScalar(pair.value) &&
663
+ typeof pair.value.value === "string")
664
+ declareBlocked(pair.value.value);
665
+ }
666
+ }
667
+ catch {
668
+ }
669
+ this.diagnostics.push(`${filePath}: ${String(error)}`);
670
+ }
671
+ }
672
+ for (const name of [...forks.keys()].filter((name) => overrides.has(name))) {
673
+ declareBlocked(name);
674
+ this.diagnostics.push(`${join(directory, forks.get(name).file)} and ${join(directory, overrides.get(name).file)}: ` +
675
+ `Use either ${name}.md (full fork) or ${name}.yml (settings override), not both`);
676
+ }
677
+ for (const [name, { type, file }] of forks) {
678
+ if (blocked.has(name))
679
+ continue;
680
+ const filePath = join(directory, file);
681
+ const base = this.types.get(name);
682
+ const fork = {
683
+ ...type,
684
+ source: scope,
685
+ filePath,
686
+ customization: { kind: "fork", scope, filePath },
687
+ baseSource: base?.source,
688
+ baseFilePath: base?.filePath,
689
+ };
690
+ this.bases.set(name, base ? structuredClone(base) : structuredClone(fork));
691
+ this.types.set(name, fork);
692
+ }
693
+ for (const [name, { override, file }] of overrides) {
694
+ if (blocked.has(name))
695
+ continue;
696
+ const filePath = join(directory, file);
697
+ const base = this.types.get(name);
698
+ if (!base) {
699
+ declareBlocked(name);
700
+ this.diagnostics.push(`${filePath}: Settings override has no base agent named ${JSON.stringify(name)}; ` +
701
+ `create ${name}.md first or remove the override`);
702
+ continue;
703
+ }
704
+ try {
705
+ const merged = mergeAgentSettings(base, { ...override, name });
706
+ this.bases.set(name, structuredClone(base));
707
+ this.scopeOverrides.get(scope).set(name, structuredClone(override));
708
+ this.types.set(name, {
709
+ ...merged,
710
+ name,
711
+ source: scope,
712
+ filePath,
713
+ customization: { kind: "override", scope, filePath },
714
+ baseSource: base.source,
715
+ baseFilePath: base.filePath,
716
+ });
717
+ }
718
+ catch (error) {
719
+ declareBlocked(name);
720
+ this.diagnostics.push(`${filePath}: ${String(error)}`);
721
+ }
722
+ }
723
+ for (const name of blocked) {
724
+ this.types.delete(name);
725
+ this.bases.delete(name);
726
+ }
727
+ }
728
+ list() {
729
+ return structuredClone([...this.types.values()].sort((a, b) => a.name.localeCompare(b.name)));
730
+ }
731
+ get(name) {
732
+ const type = this.types.get(name);
733
+ if (!type)
734
+ throw new Error(`Unknown or invalid agent type: ${name}`);
735
+ return structuredClone(type);
736
+ }
737
+ canSaveProject() {
738
+ return this.options.includeProject;
739
+ }
740
+ preferredScopeDirectory(scope) {
741
+ if (scope !== "user" && scope !== "project")
742
+ throw new Error("Invalid agent scope");
743
+ if (scope === "project" && !this.options.includeProject)
744
+ throw new Error("Project agents are not enabled/trusted");
745
+ return scope === "user"
746
+ ? resolve(this.options.agentDir, SUBAGENT_MANAGER_DIR, AGENTS_DIR)
747
+ : resolve(this.options.cwd, ".pi", "agent", SUBAGENT_MANAGER_DIR, AGENTS_DIR);
748
+ }
749
+ scopeDirectories(scope) {
750
+ return [this.preferredScopeDirectory(scope)];
751
+ }
752
+ destinationBasePaths(scope, directory) {
753
+ if (scope === "user") {
754
+ const base = resolve(this.options.agentDir);
755
+ return [base, join(base, SUBAGENT_MANAGER_DIR), directory];
756
+ }
757
+ const base = resolve(this.options.cwd);
758
+ const projectPi = join(base, ".pi");
759
+ const projectAgent = join(projectPi, "agent");
760
+ return [base, projectPi, projectAgent, join(projectAgent, SUBAGENT_MANAGER_DIR), directory];
761
+ }
762
+ getBase(name) {
763
+ const base = this.bases.get(name);
764
+ return base ? structuredClone(base) : undefined;
765
+ }
766
+ getLayers(name) {
767
+ const current = this.get(name);
768
+ const layers = new Map();
769
+ for (const type of [
770
+ this.scopeBases.get("user")?.get(name),
771
+ this.scopeBases.get("project")?.get(name),
772
+ current,
773
+ ]) {
774
+ if (type)
775
+ layers.set(type.source, type);
776
+ }
777
+ return structuredClone([...layers.values()]);
778
+ }
779
+ getSettingsOverride(name, scope) {
780
+ const layer = this.getLayers(name).find((type) => type.source === scope);
781
+ if (layer?.customization?.kind !== "override")
782
+ return undefined;
783
+ const override = this.scopeOverrides.get(scope)?.get(name);
784
+ return override ? structuredClone(override) : undefined;
785
+ }
786
+ getScopeBase(name, scope) {
787
+ const base = this.scopeBases.get(scope)?.get(name);
788
+ return base ? structuredClone(base) : undefined;
789
+ }
790
+ canPreserveDestination(name, scope, original, kind) {
791
+ if (original?.name !== name ||
792
+ original.source !== scope ||
793
+ typeof original.filePath !== "string" ||
794
+ dirname(resolve(original.filePath)) !== this.preferredScopeDirectory(scope))
795
+ return false;
796
+ const preserved = resolve(original.filePath);
797
+ if (kind === "fork")
798
+ return preserved.endsWith(".md");
799
+ return AGENT_OVERRIDE_EXTENSIONS.some((extension) => preserved.endsWith(extension));
800
+ }
801
+ destination(name, scope, original, kind = "fork") {
802
+ if (!NAME.test(name))
803
+ throw new Error("Unsafe agent name");
804
+ const directory = this.preferredScopeDirectory(scope);
805
+ if (this.canPreserveDestination(name, scope, original, kind) &&
806
+ typeof original?.filePath === "string") {
807
+ return validatePreservedDestination(original.filePath, directory, kind === "fork" ? [".md"] : [...AGENT_OVERRIDE_EXTENSIONS]);
808
+ }
809
+ return resolve(directory, `${name}${kind === "fork" ? ".md" : ".yml"}`);
810
+ }
811
+ writeContent(filePath, name, content) {
812
+ const directory = dirname(filePath);
813
+ mkdirSync(directory, { recursive: true });
814
+ const temporary = join(dirname(filePath), `.${name}.${randomUUID()}.tmp`);
815
+ try {
816
+ writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
817
+ renameSync(temporary, filePath);
818
+ }
819
+ finally {
820
+ if (lstatIfPresent(temporary))
821
+ unlinkSync(temporary);
822
+ }
823
+ }
824
+ assertWritableDestination(filePath, scope) {
825
+ const directory = dirname(filePath);
826
+ for (const path of [...this.destinationBasePaths(scope, directory), filePath]) {
827
+ const stat = assertNotSymlinkPath(path);
828
+ if (path === filePath && stat && !stat.isFile())
829
+ throw new Error(`Unsafe agent destination: ${filePath}`);
830
+ }
831
+ }
832
+ save(type, scope, original) {
833
+ const content = serializeAgentType(type);
834
+ const validated = parseAgentType(content);
835
+ const filePath = this.destination(validated.name, scope, original, "fork");
836
+ this.assertWritableDestination(filePath, scope);
837
+ this.writeContent(filePath, validated.name, content);
838
+ this.reload();
839
+ return this.get(validated.name);
840
+ }
841
+ saveOverride(name, draft, scope, original) {
842
+ if (!NAME.test(name))
843
+ throw new Error("Unsafe agent name");
844
+ if (draft.name !== name)
845
+ throw new Error("Settings overrides cannot rename the agent; fork it instead");
846
+ const base = this.getScopeBase(name, scope);
847
+ if (!base)
848
+ throw new Error(`Settings override has no base agent named ${JSON.stringify(name)}`);
849
+ const before = original ?? this.get(name);
850
+ const existing = this.scopeOverrides.get(scope)?.get(name) ?? {};
851
+ const override = before.customization?.kind === "fork"
852
+ ? diffAgentSettings(base, draft)
853
+ : updateAgentSettings(base, before, draft, existing);
854
+ const content = serializeAgentSettings(override);
855
+ parseAgentSettings(content, undefined, name);
856
+ const filePath = this.destination(name, scope, original, "override");
857
+ this.assertWritableDestination(filePath, scope);
858
+ this.writeContent(filePath, name, content);
859
+ this.reload();
860
+ return this.get(name);
861
+ }
862
+ removeCustomization(name, scope) {
863
+ const current = this.types.get(name);
864
+ const customization = current?.customization;
865
+ if (!customization || customization.scope !== scope)
866
+ throw new Error(`No ${scope} customization found for ${JSON.stringify(name)}`);
867
+ const resolved = resolve(customization.filePath);
868
+ if (dirname(resolved) !== this.preferredScopeDirectory(scope) ||
869
+ (!resolved.endsWith(".md") &&
870
+ !AGENT_OVERRIDE_EXTENSIONS.some((extension) => resolved.endsWith(extension))))
871
+ throw new Error(`Unsafe agent destination: ${resolved}`);
872
+ const stat = lstatIfPresent(resolved);
873
+ if (!stat?.isFile())
874
+ throw new Error(`Unsafe agent destination: ${resolved}`);
875
+ unlinkSync(resolved);
876
+ this.reload();
877
+ }
878
+ }