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,547 @@
1
+ import { lstatSync, readdirSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { delimiter, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
4
+ import { parseDocument } from "yaml";
5
+ const EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
6
+ const SKIPPED_DIR_NAMES = new Set([".git", "node_modules"]);
7
+ function isSkillDirectoryName(name) {
8
+ const normalized = name.toLowerCase();
9
+ return normalized === "skills" || normalized === ".skills";
10
+ }
11
+ function isSkillMarkdownName(name) {
12
+ return name.toLowerCase() === "skill.md";
13
+ }
14
+ function isSkillPath(filePath) {
15
+ return normalize(filePath)
16
+ .split(sep)
17
+ .some((segment) => isSkillDirectoryName(segment));
18
+ }
19
+ export function discoverImportCandidates(options) {
20
+ const diagnostics = [];
21
+ const candidates = [];
22
+ try {
23
+ collectCandidates(options, candidates, diagnostics);
24
+ }
25
+ catch (error) {
26
+ diagnostics.push(`Import discovery failed: ${detail(error)}`);
27
+ }
28
+ candidates.sort((left, right) => compare(left.name, right.name) || compare(left.path, right.path));
29
+ return { candidates, diagnostics: unique(diagnostics) };
30
+ }
31
+ function collectCandidates(options, candidates, diagnostics) {
32
+ const cwd = resolve(options.cwd);
33
+ const agentDir = resolve(options.agentDir);
34
+ const homeDir = resolve(options.homeDir ?? homedir());
35
+ const extraRaw = options.extraAgentDirs ?? process.env[EXTRA_AGENT_DIRS_ENV] ?? "";
36
+ const userSettingsPath = resolve(agentDir, "settings.json");
37
+ const userBase = realDirectory(agentDir, [], diagnostics);
38
+ const userSettings = userBase
39
+ ? readScanSettings(userSettingsPath, diagnostics)
40
+ : { scanDirs: [], excludes: [] };
41
+ const userExcludes = userSettings.excludes.map((entry) => resolveLiteral(entry, agentDir, homeDir));
42
+ const managerDirs = [
43
+ resolve(agentDir, "subagent-manager", "agents"),
44
+ resolve(cwd, ".pi", "agent", "subagent-manager", "agents"),
45
+ ];
46
+ const projectRoot = options.includeProject ? findNearestProjectRoot(cwd, homeDir) : undefined;
47
+ const projectSettingsDir = projectRoot
48
+ ? realDirectory(projectRoot, [".pi"], diagnostics)
49
+ : undefined;
50
+ const projectSettingsPath = projectSettingsDir
51
+ ? resolve(projectSettingsDir, "settings.json")
52
+ : undefined;
53
+ const projectSettings = projectSettingsPath
54
+ ? readScanSettings(projectSettingsPath, diagnostics)
55
+ : { scanDirs: [], excludes: [] };
56
+ const projectExcludes = projectSettings.excludes.map((entry) => resolveLiteral(entry, projectSettingsPath ? dirname(projectSettingsPath) : cwd, homeDir));
57
+ const mergedProjectExcludes = [...userExcludes, ...projectExcludes];
58
+ const userSettingsPaths = userBase ? existingFiles([userSettingsPath], diagnostics) : [];
59
+ const projectSettingsPaths = existingFiles([...userSettingsPaths, ...(projectSettingsPath ? [projectSettingsPath] : [])], diagnostics);
60
+ const roots = [];
61
+ const scheduled = new Set();
62
+ const schedule = (directory, scope, permissive) => {
63
+ if (!directory)
64
+ return;
65
+ const resolved = resolve(directory);
66
+ if (isSkillPath(resolved) || scheduled.has(resolved) || isManagerOwned(resolved, managerDirs)) {
67
+ return;
68
+ }
69
+ const excludes = scope === "project" ? mergedProjectExcludes : userExcludes;
70
+ if (isExcluded(resolved, excludes))
71
+ return;
72
+ scheduled.add(resolved);
73
+ roots.push({
74
+ directory: resolved,
75
+ scope,
76
+ permissive,
77
+ settingsPaths: scope === "project" ? projectSettingsPaths : userSettingsPaths,
78
+ });
79
+ };
80
+ schedule(realDirectory(agentDir, ["agents"], diagnostics), "user", "agents");
81
+ schedule(realDirectory(homeDir, [".agents"], diagnostics), "user", "broad");
82
+ if (projectRoot) {
83
+ schedule(realDirectory(projectRoot, [".pi", "agents"], diagnostics), "project", "agents");
84
+ schedule(realDirectory(projectRoot, [".agents"], diagnostics), "project", "broad");
85
+ }
86
+ for (const directory of extraDirectories(extraRaw, cwd, homeDir, diagnostics)) {
87
+ schedule(directory, "user", "strict");
88
+ }
89
+ for (const directory of expandScanDirs(userSettings.scanDirs, agentDir, homeDir, userSettingsPath, diagnostics)) {
90
+ schedule(directory, "user", "strict");
91
+ }
92
+ if (projectRoot && projectSettingsPath) {
93
+ for (const directory of expandScanDirs(projectSettings.scanDirs, dirname(projectSettingsPath), homeDir, projectSettingsPath, diagnostics)) {
94
+ schedule(directory, "project", "strict");
95
+ }
96
+ }
97
+ const seen = new Set();
98
+ for (const root of roots) {
99
+ const excludes = root.scope === "project" ? mergedProjectExcludes : userExcludes;
100
+ walk(root, excludes, managerDirs, seen, candidates, diagnostics);
101
+ }
102
+ }
103
+ function walk(root, excludes, managerDirs, seen, candidates, diagnostics) {
104
+ if (isSkillPath(root.directory))
105
+ return;
106
+ const skipHidden = basenameOf(root.directory) === ".agents";
107
+ const visit = (directory) => {
108
+ if (isSkillPath(directory) ||
109
+ isManagerOwned(directory, managerDirs) ||
110
+ isExcluded(directory, excludes)) {
111
+ return;
112
+ }
113
+ let entries;
114
+ try {
115
+ const stat = lstatSync(directory);
116
+ if (stat.isSymbolicLink())
117
+ return;
118
+ if (!stat.isDirectory()) {
119
+ diagnostics.push(`${directory}: Agent directory must be a directory`);
120
+ return;
121
+ }
122
+ entries = readdirSync(directory, { withFileTypes: true });
123
+ }
124
+ catch (error) {
125
+ if (errorCode(error) === "ENOENT")
126
+ return;
127
+ diagnostics.push(`${directory}: ${detail(error)}`);
128
+ return;
129
+ }
130
+ for (const entry of [...entries].sort((left, right) => compare(left.name, right.name))) {
131
+ if (entry.isSymbolicLink())
132
+ continue;
133
+ const child = join(directory, entry.name);
134
+ if (entry.isDirectory()) {
135
+ if (SKIPPED_DIR_NAMES.has(entry.name) || isSkillDirectoryName(entry.name))
136
+ continue;
137
+ if (skipHidden && entry.name.startsWith("."))
138
+ continue;
139
+ if (isManagerOwned(child, managerDirs) || isExcluded(child, excludes))
140
+ continue;
141
+ visit(child);
142
+ continue;
143
+ }
144
+ if (isSkillMarkdownName(entry.name))
145
+ continue;
146
+ if (!entry.isFile() || !entry.name.endsWith(".md") || entry.name.endsWith(".chain.md")) {
147
+ continue;
148
+ }
149
+ if (isExcluded(child, excludes) || isManagerOwned(child, managerDirs))
150
+ continue;
151
+ considerFile(child, root, seen, candidates, diagnostics);
152
+ }
153
+ };
154
+ visit(root.directory);
155
+ }
156
+ function considerFile(filePath, root, seen, candidates, diagnostics) {
157
+ if (isSkillMarkdownName(basenameOf(filePath)) || isSkillPath(filePath))
158
+ return;
159
+ const resolved = resolve(filePath);
160
+ if (seen.has(resolved))
161
+ return;
162
+ seen.add(resolved);
163
+ let content = "";
164
+ try {
165
+ const stat = lstatSync(resolved);
166
+ if (stat.isSymbolicLink() || !stat.isFile())
167
+ return;
168
+ content = readFileSync(resolved, "utf8");
169
+ }
170
+ catch (error) {
171
+ if (errorCode(error) !== "ENOENT")
172
+ diagnostics.push(`${resolved}: ${detail(error)}`);
173
+ return;
174
+ }
175
+ let fields;
176
+ try {
177
+ fields = readDisplayFields(content);
178
+ }
179
+ catch (error) {
180
+ diagnostics.push(`${resolved}: ${detail(error)}`);
181
+ const display = looseDisplayFields(content);
182
+ if (!display)
183
+ return;
184
+ fields = display;
185
+ }
186
+ const permissive = allowsFilenameFallback(root, resolved);
187
+ const rawName = fields.name?.trim() ?? "";
188
+ const name = rawName || (permissive ? filenameName(resolved) : "");
189
+ const description = fields.description ?? (permissive ? "" : undefined);
190
+ if (!name || description === undefined || (!permissive && !description.trim()))
191
+ return;
192
+ const packageName = fields.packageName?.trim() ?? "";
193
+ candidates.push({
194
+ id: resolved,
195
+ path: resolved,
196
+ name: packageName ? `${packageName}.${name}` : name,
197
+ description,
198
+ scope: root.scope,
199
+ settingsPaths: root.settingsPaths,
200
+ });
201
+ }
202
+ function looseDisplayFields(content) {
203
+ const extracted = frontmatter(content);
204
+ if (!extracted)
205
+ return undefined;
206
+ const fields = {};
207
+ for (const key of ["name", "description", "package"]) {
208
+ const matches = [...extracted.yaml.matchAll(new RegExp(`^${key}:\\s*(.*)$`, "gm"))];
209
+ if (matches.length > 1)
210
+ return undefined;
211
+ if (!matches.length)
212
+ continue;
213
+ const value = matches[0][1].trim();
214
+ if (!value || /^[&*[{>|]/.test(value))
215
+ continue;
216
+ try {
217
+ const scalar = parseDocument(value);
218
+ if (scalar.errors.length)
219
+ continue;
220
+ const parsed = scalar.toJS({ maxAliasCount: 0 });
221
+ if (typeof parsed === "string")
222
+ fields[key] = parsed;
223
+ }
224
+ catch {
225
+ }
226
+ }
227
+ if (!fields.name || !fields.description)
228
+ return undefined;
229
+ return { name: fields.name, description: fields.description, packageName: fields.package };
230
+ }
231
+ function readDisplayFields(content) {
232
+ const extracted = frontmatter(content);
233
+ if (!extracted)
234
+ return {};
235
+ const doc = parseDocument(extracted.yaml);
236
+ if (doc.errors.length) {
237
+ throw new Error(doc.errors.map((error) => error.message).join("; "));
238
+ }
239
+ const data = doc.toJS({ maxAliasCount: 0 });
240
+ if (data === null || data === undefined)
241
+ return {};
242
+ if (typeof data !== "object" || Array.isArray(data)) {
243
+ throw new Error("Frontmatter must be a mapping");
244
+ }
245
+ const record = data;
246
+ return {
247
+ name: typeof record.name === "string" ? record.name : undefined,
248
+ description: typeof record.description === "string" ? record.description : undefined,
249
+ packageName: typeof record.package === "string" ? record.package : undefined,
250
+ };
251
+ }
252
+ function frontmatter(content) {
253
+ const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(content);
254
+ if (!match || match.index !== 0)
255
+ return undefined;
256
+ return { yaml: match[1] };
257
+ }
258
+ function allowsFilenameFallback(root, filePath) {
259
+ if (root.permissive === "agents")
260
+ return true;
261
+ if (root.permissive !== "broad")
262
+ return false;
263
+ const parts = relative(root.directory, filePath).split(sep);
264
+ return parts.length === 2 && parts[0] === "agents" && parts[1].endsWith(".md");
265
+ }
266
+ function filenameName(filePath) {
267
+ const base = basenameOf(filePath);
268
+ return base.endsWith(".md") ? base.slice(0, -3) : base;
269
+ }
270
+ function findNearestProjectRoot(cwd, homeDir) {
271
+ let current = resolve(cwd);
272
+ const home = resolve(homeDir);
273
+ while (current !== home) {
274
+ const stat = listed(current);
275
+ if (stat.kind === "ok" && stat.stat.isDirectory()) {
276
+ if (isRealDirectory(join(current, ".pi")) || isRealDirectory(join(current, ".agents"))) {
277
+ return current;
278
+ }
279
+ }
280
+ const parent = dirname(current);
281
+ if (parent === current)
282
+ return undefined;
283
+ current = parent;
284
+ }
285
+ return undefined;
286
+ }
287
+ function isRealDirectory(path) {
288
+ const stat = listed(path);
289
+ return stat.kind === "ok" && stat.stat.isDirectory();
290
+ }
291
+ function realDirectory(base, segments, diagnostics) {
292
+ let current = resolve(base);
293
+ const accept = (path) => {
294
+ const stat = listed(path);
295
+ if (stat.kind === "absent" || stat.kind === "symlink")
296
+ return false;
297
+ if (stat.kind === "error") {
298
+ diagnostics.push(`${path}: ${stat.message}`);
299
+ return false;
300
+ }
301
+ if (!stat.stat.isDirectory()) {
302
+ diagnostics.push(`${path}: Agent directory must be a directory`);
303
+ return false;
304
+ }
305
+ return true;
306
+ };
307
+ if (!accept(current))
308
+ return undefined;
309
+ for (const segment of segments) {
310
+ current = join(current, segment);
311
+ if (!accept(current))
312
+ return undefined;
313
+ }
314
+ return current;
315
+ }
316
+ function extraDirectories(raw, cwd, homeDir, diagnostics) {
317
+ const directories = [];
318
+ for (const entry of raw.split(delimiter)) {
319
+ const trimmed = entry.trim();
320
+ if (!trimmed)
321
+ continue;
322
+ const target = resolve(cwd, expandTilde(trimmed, homeDir));
323
+ if (isSkillPath(target) || hasSymlinkComponent(cwd, target))
324
+ continue;
325
+ const stat = listed(target);
326
+ if (stat.kind === "absent" || stat.kind === "symlink")
327
+ continue;
328
+ if (stat.kind === "error") {
329
+ diagnostics.push(`${target}: ${stat.message}`);
330
+ continue;
331
+ }
332
+ if (!stat.stat.isDirectory()) {
333
+ diagnostics.push(`${target}: Agent directory must be a directory`);
334
+ continue;
335
+ }
336
+ directories.push(target);
337
+ }
338
+ return directories;
339
+ }
340
+ function expandScanDirs(patterns, baseDir, homeDir, settingsPath, diagnostics) {
341
+ const directories = [];
342
+ for (const pattern of patterns) {
343
+ const expanded = expandTilde(pattern, homeDir).replace(/[\\/]+/g, sep);
344
+ const absolute = isAbsolute(expanded) ? expanded : join(resolve(baseDir), expanded);
345
+ const normalized = normalize(absolute);
346
+ const parts = normalized.split(sep);
347
+ const starCount = [...normalized.matchAll(/\*/g)].length;
348
+ if (starCount === 0) {
349
+ if (isSkillPath(normalized))
350
+ continue;
351
+ const directory = acceptDirectory(normalized, baseDir, diagnostics);
352
+ if (directory)
353
+ directories.push(directory);
354
+ continue;
355
+ }
356
+ const wildcardAt = parts.findIndex((part) => part.includes("*"));
357
+ if (starCount !== 1 || wildcardAt < 0 || parts[wildcardAt] !== "*") {
358
+ diagnostics.push(`${settingsPath}: Invalid agentScanDirs pattern '${pattern}': expected one '*' path segment`);
359
+ continue;
360
+ }
361
+ const wildcardBase = wildcardDirectory(parts.slice(0, wildcardAt));
362
+ if (isSkillPath(wildcardBase) || !acceptDirectory(wildcardBase, baseDir, diagnostics))
363
+ continue;
364
+ let entries;
365
+ try {
366
+ entries = readdirSync(wildcardBase, { withFileTypes: true });
367
+ }
368
+ catch (error) {
369
+ if (errorCode(error) !== "ENOENT")
370
+ diagnostics.push(`${wildcardBase}: ${detail(error)}`);
371
+ continue;
372
+ }
373
+ const rest = parts.slice(wildcardAt + 1);
374
+ for (const entry of [...entries].sort((left, right) => compare(left.name, right.name))) {
375
+ if (entry.isSymbolicLink() || !entry.isDirectory() || isSkillDirectoryName(entry.name)) {
376
+ continue;
377
+ }
378
+ const target = join(wildcardBase, entry.name, ...rest);
379
+ if (isSkillPath(target))
380
+ continue;
381
+ const directory = acceptDirectory(target, wildcardBase, diagnostics);
382
+ if (directory)
383
+ directories.push(directory);
384
+ }
385
+ }
386
+ return directories;
387
+ }
388
+ function wildcardDirectory(parts) {
389
+ if (parts.length === 0)
390
+ return sep;
391
+ const joined = parts.join(sep);
392
+ return joined || sep;
393
+ }
394
+ function acceptDirectory(target, base, diagnostics) {
395
+ const resolved = resolve(target);
396
+ if (hasSymlinkComponent(base, resolved))
397
+ return undefined;
398
+ const stat = listed(resolved);
399
+ if (stat.kind === "absent" || stat.kind === "symlink")
400
+ return undefined;
401
+ if (stat.kind === "error") {
402
+ diagnostics.push(`${resolved}: ${stat.message}`);
403
+ return undefined;
404
+ }
405
+ if (!stat.stat.isDirectory()) {
406
+ diagnostics.push(`${resolved}: Agent directory must be a directory`);
407
+ return undefined;
408
+ }
409
+ return resolved;
410
+ }
411
+ function readScanSettings(filePath, diagnostics) {
412
+ const empty = { scanDirs: [], excludes: [] };
413
+ const stat = listed(filePath);
414
+ if (stat.kind === "absent" || stat.kind === "symlink")
415
+ return empty;
416
+ if (stat.kind === "error") {
417
+ diagnostics.push(`${filePath}: ${stat.message}`);
418
+ return empty;
419
+ }
420
+ if (!stat.stat.isFile()) {
421
+ diagnostics.push(`${filePath}: Settings must be a regular file`);
422
+ return empty;
423
+ }
424
+ let parsed;
425
+ try {
426
+ parsed = JSON.parse(readFileSync(filePath, "utf8"));
427
+ }
428
+ catch (error) {
429
+ diagnostics.push(`${filePath}: ${detail(error)}`);
430
+ return empty;
431
+ }
432
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
433
+ diagnostics.push(`${filePath}: Settings must be a JSON object`);
434
+ return empty;
435
+ }
436
+ const subagents = parsed.subagents;
437
+ if (subagents === undefined)
438
+ return empty;
439
+ if (subagents === null || typeof subagents !== "object" || Array.isArray(subagents)) {
440
+ diagnostics.push(`${filePath}: subagents must be a JSON object`);
441
+ return empty;
442
+ }
443
+ const record = subagents;
444
+ return {
445
+ scanDirs: stringList(record, "agentScanDirs", filePath, diagnostics),
446
+ excludes: stringList(record, "agentExcludeDirs", filePath, diagnostics),
447
+ };
448
+ }
449
+ function stringList(record, key, filePath, diagnostics) {
450
+ if (!Object.hasOwn(record, key))
451
+ return [];
452
+ const value = record[key];
453
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || !item.trim())) {
454
+ diagnostics.push(`${filePath}: subagents.${key} must be an array of non-empty strings`);
455
+ return [];
456
+ }
457
+ return value.map((item) => item.trim());
458
+ }
459
+ function existingFiles(paths, diagnostics) {
460
+ const files = [];
461
+ for (const filePath of paths) {
462
+ const resolved = resolve(filePath);
463
+ const stat = listed(resolved);
464
+ if (stat.kind === "absent" || stat.kind === "symlink")
465
+ continue;
466
+ if (stat.kind === "error") {
467
+ diagnostics.push(`${resolved}: ${stat.message}`);
468
+ continue;
469
+ }
470
+ if (!stat.stat.isFile()) {
471
+ diagnostics.push(`${resolved}: Settings must be a regular file`);
472
+ continue;
473
+ }
474
+ files.push(resolved);
475
+ }
476
+ return files;
477
+ }
478
+ function hasSymlinkComponent(base, target) {
479
+ const resolvedBase = resolve(base);
480
+ const resolvedTarget = resolve(target);
481
+ const rel = relative(resolvedBase, resolvedTarget);
482
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
483
+ return listed(resolvedTarget).kind === "symlink";
484
+ }
485
+ let current = resolvedBase;
486
+ if (listed(current).kind === "symlink")
487
+ return true;
488
+ for (const segment of rel.split(sep)) {
489
+ if (!segment || segment === ".")
490
+ continue;
491
+ current = join(current, segment);
492
+ if (listed(current).kind === "symlink")
493
+ return true;
494
+ }
495
+ return false;
496
+ }
497
+ function isManagerOwned(target, managerDirs) {
498
+ const resolved = resolve(target);
499
+ return managerDirs.some((directory) => isInside(directory, resolved));
500
+ }
501
+ function isExcluded(target, excludes) {
502
+ const resolved = resolve(target);
503
+ return excludes.some((directory) => isInside(directory, resolved));
504
+ }
505
+ function isInside(root, target) {
506
+ const rel = relative(resolve(root), resolve(target));
507
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
508
+ }
509
+ function resolveLiteral(entry, baseDir, homeDir) {
510
+ return resolve(baseDir, expandTilde(entry.trim(), homeDir));
511
+ }
512
+ function expandTilde(value, homeDir) {
513
+ if (value === "~")
514
+ return homeDir;
515
+ if (value.startsWith("~/") || value.startsWith("~\\"))
516
+ return join(homeDir, value.slice(2));
517
+ return value;
518
+ }
519
+ function listed(path) {
520
+ try {
521
+ const stat = lstatSync(path);
522
+ return stat.isSymbolicLink() ? { kind: "symlink" } : { kind: "ok", stat };
523
+ }
524
+ catch (error) {
525
+ if (errorCode(error) === "ENOENT")
526
+ return { kind: "absent" };
527
+ return { kind: "error", message: detail(error) };
528
+ }
529
+ }
530
+ function basenameOf(path) {
531
+ const parts = path.split(sep);
532
+ return parts[parts.length - 1] ?? path;
533
+ }
534
+ function errorCode(error) {
535
+ return typeof error === "object" && error !== null && "code" in error
536
+ ? String(error.code)
537
+ : undefined;
538
+ }
539
+ function detail(error) {
540
+ return error instanceof Error ? error.message : String(error);
541
+ }
542
+ function compare(left, right) {
543
+ return left < right ? -1 : left > right ? 1 : 0;
544
+ }
545
+ function unique(values) {
546
+ return [...new Set(values)];
547
+ }
@@ -1,4 +1,3 @@
1
- /** Semantic migration belongs to the current session model, never a converter. */
2
1
  export const MIGRATION_INSTRUCTIONS = `
3
2
  ## Migration contract
4
3
  You are importing selected external definitions into pi-subagent-manager in THIS conversation.
@@ -0,0 +1,56 @@
1
+ const MODEL_IDENTITY = /^[^\s/]+\/[^\s]+$/;
2
+ function validateModelPreference(value, label) {
3
+ if (typeof value !== "string" || !MODEL_IDENTITY.test(value))
4
+ throw new Error(`${label} must be provider/model-id`);
5
+ return value;
6
+ }
7
+ export function getModelPreferences(type) {
8
+ const hasModels = type.models !== undefined;
9
+ const hasModel = type.model !== undefined;
10
+ if (hasModels && hasModel)
11
+ throw new Error("Specify either models or model, not both");
12
+ if (hasModels) {
13
+ if (!Array.isArray(type.models))
14
+ throw new Error("models must be an array of provider/model-id strings");
15
+ if (type.models.length === 0)
16
+ throw new Error("models must not be empty; omit models to inherit the parent/default model");
17
+ const models = type.models.map((value, index) => validateModelPreference(value, `models[${index}]`));
18
+ if (new Set(models).size !== models.length)
19
+ throw new Error("models contains duplicate entries");
20
+ return [...models];
21
+ }
22
+ if (hasModel)
23
+ return [validateModelPreference(type.model, "model")];
24
+ return undefined;
25
+ }
26
+ export function modelIdentity(model) {
27
+ return `${model.provider}/${model.id}`;
28
+ }
29
+ export class ModelPreferenceError extends Error {
30
+ scopedModelFiltering;
31
+ constructor(message, scopedModelFiltering) {
32
+ super(message);
33
+ this.scopedModelFiltering = scopedModelFiltering;
34
+ }
35
+ get summary() {
36
+ return this.scopedModelFiltering
37
+ ? "No preferred model is available in /scoped-models; update the scope or this type's models."
38
+ : "No preferred model is available; check provider credentials or this type's models.";
39
+ }
40
+ }
41
+ export function selectPreferredModel(type, eligibleModels, scopedModelFiltering = true) {
42
+ const preferences = getModelPreferences(type);
43
+ if (preferences === undefined)
44
+ return undefined;
45
+ const available = eligibleModels.map(({ model }) => modelIdentity(model));
46
+ for (const preference of preferences) {
47
+ if (available.includes(preference))
48
+ return preference;
49
+ }
50
+ const preferenceList = `[${preferences.join(", ")}]`;
51
+ const availableList = available.length === 0 ? "(none)" : `[${available.join(", ")}]`;
52
+ if (!scopedModelFiltering) {
53
+ throw new ModelPreferenceError(`Agent type ${JSON.stringify(type.name)} prefers models ${preferenceList}, but none are available. Available models: ${availableList}. Update this agent type's models list.`, false);
54
+ }
55
+ throw new ModelPreferenceError(`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.`, true);
56
+ }