pi-subagent-manager 0.1.1 → 0.3.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.
package/src/config.ts CHANGED
@@ -11,9 +11,10 @@ import { dirname, join, resolve } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { randomUUID } from "node:crypto";
13
13
  import { isMap, isScalar, parseDocument, stringify } from "yaml";
14
+ import { getModelPreferences } from "./models.js";
14
15
  import { THINKING_LEVELS, type AgentType } from "./types.js";
15
16
 
16
- // Pi semantic foreground tokens (background tokens are intentionally excluded).
17
+ // Pi semantic color tokens, resolved as concrete colors for agent name backgrounds.
17
18
  export const AGENT_COLORS = [
18
19
  "accent",
19
20
  "border",
@@ -68,7 +69,18 @@ export const AGENT_COLORS = [
68
69
 
69
70
  const NAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
70
71
  const TOOL = /^[a-zA-Z0-9_-]+$/;
71
- const FIELDS = new Set(["name", "description", "model", "thinkingLevel", "color", "tools"]);
72
+ const FIELDS = new Set([
73
+ "name",
74
+ "description",
75
+ "models",
76
+ "model",
77
+ "modelSuggestions",
78
+ "thinkingLevel",
79
+ "color",
80
+ "tools",
81
+ ]);
82
+ const SUBAGENT_MANAGER_DIR = "subagent-manager";
83
+ const AGENTS_DIR = "agents";
72
84
 
73
85
  type AgentScope = "user" | "project";
74
86
  type SaveOrigin = Pick<AgentType, "name" | "source" | "filePath">;
@@ -79,7 +91,9 @@ function errorCode(error: unknown): string | undefined {
79
91
  : undefined;
80
92
  }
81
93
 
82
- function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined {
94
+ function lstatIfPresent(
95
+ path: string,
96
+ ): ReturnType<typeof lstatSync> | undefined {
83
97
  try {
84
98
  return lstatSync(path);
85
99
  } catch (error) {
@@ -88,13 +102,18 @@ function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined
88
102
  }
89
103
  }
90
104
 
91
- function assertNotSymlinkPath(path: string): ReturnType<typeof lstatSync> | undefined {
105
+ function assertNotSymlinkPath(
106
+ path: string,
107
+ ): ReturnType<typeof lstatSync> | undefined {
92
108
  const stat = lstatIfPresent(path);
93
109
  if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
94
110
  return stat;
95
111
  }
96
112
 
97
- function validatePreservedDestination(filePath: string, directory: string): string {
113
+ function validatePreservedDestination(
114
+ filePath: string,
115
+ directory: string,
116
+ ): string {
98
117
  const resolved = resolve(filePath);
99
118
  if (dirname(resolved) !== directory || !resolved.endsWith(".md"))
100
119
  throw new Error(`Unsafe agent destination: ${resolved}`);
@@ -104,7 +123,9 @@ function validatePreservedDestination(filePath: string, directory: string): stri
104
123
  }
105
124
 
106
125
  function frontmatter(content: string): { yaml: string; body: string } {
107
- const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(content);
126
+ const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(
127
+ content,
128
+ );
108
129
  if (!match || match.index !== 0)
109
130
  throw new Error("Expected YAML frontmatter enclosed by --- lines");
110
131
  return { yaml: match[1], body: content.slice(match[0].length) };
@@ -116,9 +137,30 @@ function record(value: unknown, label: string): Record<string, unknown> {
116
137
  return value as Record<string, unknown>;
117
138
  }
118
139
 
140
+ /** Advisory display names only. Empty means no suggestions; never a model pin. */
141
+ function modelSuggestionNames(value: unknown): string[] {
142
+ if (!Array.isArray(value))
143
+ throw new Error("modelSuggestions must be an array of nonempty display names");
144
+ const suggestions = value.map((entry, index) => {
145
+ if (typeof entry !== "string")
146
+ throw new Error(`modelSuggestions[${index}] must be a nonempty display name`);
147
+ const name = entry.trim();
148
+ if (!name) throw new Error(`modelSuggestions[${index}] must be a nonempty display name`);
149
+ return name;
150
+ });
151
+ if (new Set(suggestions).size !== suggestions.length)
152
+ throw new Error("modelSuggestions contains duplicate display names");
153
+ return [...suggestions];
154
+ }
155
+
119
156
  function toolNames(value: unknown, label: string): string[] {
120
- if (!Array.isArray(value) || value.some((name) => typeof name !== "string" || !TOOL.test(name))) {
121
- throw new Error(`${label} must be an array of exact tool names (no wildcards or patterns)`);
157
+ if (
158
+ !Array.isArray(value) ||
159
+ value.some((name) => typeof name !== "string" || !TOOL.test(name))
160
+ ) {
161
+ throw new Error(
162
+ `${label} must be an array of exact tool names (no wildcards or patterns)`,
163
+ );
122
164
  }
123
165
  if (new Set(value).size !== value.length)
124
166
  throw new Error(`${label} contains duplicate tool names`);
@@ -128,10 +170,13 @@ function toolNames(value: unknown, label: string): string[] {
128
170
  function toolPolicy(value: unknown): NonNullable<AgentType["tools"]> {
129
171
  const mapping = record(value, "tools");
130
172
  for (const key of Object.keys(mapping))
131
- if (key !== "allow" && key !== "block") throw new Error(`Unknown tools field: ${key}`);
173
+ if (key !== "allow" && key !== "block")
174
+ throw new Error(`Unknown tools field: ${key}`);
132
175
  const result: NonNullable<AgentType["tools"]> = {};
133
- if (Object.hasOwn(mapping, "allow")) result.allow = toolNames(mapping.allow, "tools.allow");
134
- if (Object.hasOwn(mapping, "block")) result.block = toolNames(mapping.block, "tools.block");
176
+ if (Object.hasOwn(mapping, "allow"))
177
+ result.allow = toolNames(mapping.allow, "tools.allow");
178
+ if (Object.hasOwn(mapping, "block"))
179
+ result.block = toolNames(mapping.block, "tools.block");
135
180
  return result;
136
181
  }
137
182
 
@@ -139,10 +184,12 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
139
184
  try {
140
185
  const { yaml, body } = frontmatter(content);
141
186
  const doc = parseDocument(yaml, { uniqueKeys: true });
142
- if (doc.errors.length) throw new Error(doc.errors.map((error) => error.message).join("; "));
187
+ if (doc.errors.length)
188
+ throw new Error(doc.errors.map((error) => error.message).join("; "));
143
189
  const data = record(doc.toJS({ maxAliasCount: 0 }), "Frontmatter");
144
190
  for (const key of Object.keys(data))
145
- if (!FIELDS.has(key)) throw new Error(`Unknown frontmatter field: ${key}`);
191
+ if (!FIELDS.has(key))
192
+ throw new Error(`Unknown frontmatter field: ${key}`);
146
193
  if (typeof data.name !== "string" || !NAME.test(data.name))
147
194
  throw new Error(
148
195
  "name must be a safe identifier using letters, numbers, underscores or hyphens",
@@ -154,19 +201,29 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
154
201
  description: data.description,
155
202
  systemPrompt: body,
156
203
  };
157
- if (Object.hasOwn(data, "model")) {
158
- if (typeof data.model !== "string" || !/^[^\s/]+\/[^\s]+$/.test(data.model))
159
- throw new Error("model must be provider/model-id");
160
- result.model = data.model;
161
- }
204
+ const models = getModelPreferences({
205
+ models: data.models,
206
+ model: data.model,
207
+ });
208
+ if (models !== undefined) result.models = models;
209
+ if (Object.hasOwn(data, "modelSuggestions"))
210
+ result.modelSuggestions = modelSuggestionNames(data.modelSuggestions);
162
211
  if (Object.hasOwn(data, "thinkingLevel")) {
163
- if (!THINKING_LEVELS.includes(data.thinkingLevel as AgentType["thinkingLevel"] & string))
164
- throw new Error(`thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`);
212
+ if (
213
+ !THINKING_LEVELS.includes(
214
+ data.thinkingLevel as AgentType["thinkingLevel"] & string,
215
+ )
216
+ )
217
+ throw new Error(
218
+ `thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`,
219
+ );
165
220
  result.thinkingLevel = data.thinkingLevel as AgentType["thinkingLevel"];
166
221
  }
167
222
  if (Object.hasOwn(data, "color")) {
168
223
  if (!AGENT_COLORS.includes(data.color as (typeof AGENT_COLORS)[number]))
169
- throw new Error(`color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`);
224
+ throw new Error(
225
+ `color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`,
226
+ );
170
227
  result.color = data.color as string;
171
228
  }
172
229
  if (Object.hasOwn(data, "tools")) result.tools = toolPolicy(data.tools);
@@ -180,25 +237,34 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
180
237
  }
181
238
 
182
239
  export function serializeAgentType(type: AgentType): string {
183
- if (typeof type.systemPrompt !== "string") throw new Error("systemPrompt must be a string");
240
+ if (typeof type.systemPrompt !== "string")
241
+ throw new Error("systemPrompt must be a string");
184
242
  const data: Record<string, unknown> = {
185
243
  name: type.name,
186
244
  description: type.description,
187
245
  };
188
- for (const key of ["model", "thinkingLevel", "color", "tools"] as const)
246
+ const models = getModelPreferences(type);
247
+ if (models !== undefined) data.models = models;
248
+ if (type.modelSuggestions !== undefined)
249
+ data.modelSuggestions = modelSuggestionNames(type.modelSuggestions);
250
+ for (const key of ["thinkingLevel", "color", "tools"] as const)
189
251
  if (type[key] !== undefined) data[key] = type[key];
190
252
  const content = `---\n${stringify(data)}---\n${type.systemPrompt}`;
191
253
  parseAgentType(content);
192
254
  return content;
193
255
  }
194
256
 
195
- export function selectTools(policy: AgentType["tools"], available: string[]): string[] {
257
+ export function selectTools(
258
+ policy: AgentType["tools"],
259
+ available: string[],
260
+ ): string[] {
196
261
  const validated = policy === undefined ? {} : toolPolicy(policy);
197
262
  const names = new Set(available);
198
263
  for (const name of [...(validated.allow ?? []), ...(validated.block ?? [])]) {
199
264
  if (!names.has(name)) throw new Error(`Unavailable tool name: ${name}`);
200
265
  }
201
- const allow = validated.allow === undefined ? names : new Set(validated.allow);
266
+ const allow =
267
+ validated.allow === undefined ? names : new Set(validated.allow);
202
268
  const block = new Set(validated.block ?? []);
203
269
  return [...names].filter((name) => allow.has(name) && !block.has(name));
204
270
  }
@@ -224,11 +290,27 @@ export class ConfigStore {
224
290
  this.types.clear();
225
291
  this.diagnostics = [];
226
292
  const layers: [string, NonNullable<AgentType["source"]>][] = [
227
- [this.options.bundledDir ?? fileURLToPath(new URL("../agents/", import.meta.url)), "bundled"],
228
- [join(this.options.agentDir, "agents"), "user"],
293
+ [
294
+ this.options.bundledDir ??
295
+ fileURLToPath(new URL("../agents/", import.meta.url)),
296
+ "bundled",
297
+ ],
298
+ ...this.scopeDirectories("user").map(
299
+ (directory): [string, NonNullable<AgentType["source"]>] => [
300
+ directory,
301
+ "user",
302
+ ],
303
+ ),
229
304
  ];
230
305
  if (this.options.includeProject)
231
- layers.push([join(this.options.cwd, ".pi", "agents"), "project"]);
306
+ layers.push(
307
+ ...this.scopeDirectories("project").map(
308
+ (directory): [string, NonNullable<AgentType["source"]>] => [
309
+ directory,
310
+ "project",
311
+ ],
312
+ ),
313
+ );
232
314
  for (const [directory, source] of layers) {
233
315
  let files: string[];
234
316
  try {
@@ -252,7 +334,9 @@ export class ConfigStore {
252
334
  let content = "";
253
335
  try {
254
336
  if (!lstatSync(filePath).isFile())
255
- throw new Error("Agent definition must be a regular file, not a symlink");
337
+ throw new Error(
338
+ "Agent definition must be a regular file, not a symlink",
339
+ );
256
340
  content = readFileSync(filePath, "utf8");
257
341
  const type = parseAgentType(content, filePath);
258
342
  if (seenNames.has(type.name)) {
@@ -290,7 +374,9 @@ export class ConfigStore {
290
374
  }
291
375
 
292
376
  list(): AgentType[] {
293
- return structuredClone([...this.types.values()].sort((a, b) => a.name.localeCompare(b.name)));
377
+ return structuredClone(
378
+ [...this.types.values()].sort((a, b) => a.name.localeCompare(b.name)),
379
+ );
294
380
  }
295
381
 
296
382
  get(name: string): AgentType {
@@ -303,27 +389,64 @@ export class ConfigStore {
303
389
  return this.options.includeProject;
304
390
  }
305
391
 
306
- private scopeDirectory(scope: AgentScope): string {
307
- if (scope !== "user" && scope !== "project") throw new Error("Invalid agent scope");
392
+ private preferredScopeDirectory(scope: AgentScope): string {
393
+ if (scope !== "user" && scope !== "project")
394
+ throw new Error("Invalid agent scope");
308
395
  if (scope === "project" && !this.options.includeProject)
309
396
  throw new Error("Project agents are not enabled/trusted");
310
397
  return scope === "user"
311
- ? resolve(this.options.agentDir, "agents")
312
- : resolve(this.options.cwd, ".pi", "agents");
398
+ ? resolve(this.options.agentDir, SUBAGENT_MANAGER_DIR, AGENTS_DIR)
399
+ : resolve(
400
+ this.options.cwd,
401
+ ".pi",
402
+ "agent",
403
+ SUBAGENT_MANAGER_DIR,
404
+ AGENTS_DIR,
405
+ );
406
+ }
407
+
408
+ // Manager-owned storage only. Do not scan legacy Pi agent packages.
409
+ private scopeDirectories(scope: AgentScope): string[] {
410
+ return [this.preferredScopeDirectory(scope)];
313
411
  }
314
412
 
315
413
  private destinationBasePaths(scope: AgentScope, directory: string): string[] {
316
- const base = resolve(scope === "user" ? this.options.agentDir : this.options.cwd);
317
- return scope === "user" ? [base, directory] : [base, join(base, ".pi"), directory];
414
+ if (scope === "user") {
415
+ const base = resolve(this.options.agentDir);
416
+ return [base, join(base, SUBAGENT_MANAGER_DIR), directory];
417
+ }
418
+ const base = resolve(this.options.cwd);
419
+ const projectPi = join(base, ".pi");
420
+ const projectAgent = join(projectPi, "agent");
421
+ return [
422
+ base,
423
+ projectPi,
424
+ projectAgent,
425
+ join(projectAgent, SUBAGENT_MANAGER_DIR),
426
+ directory,
427
+ ];
428
+ }
429
+
430
+ private canPreserveDestination(
431
+ name: string,
432
+ scope: AgentScope,
433
+ original?: SaveOrigin,
434
+ ): boolean {
435
+ return (
436
+ original?.name === name &&
437
+ original.source === scope &&
438
+ typeof original.filePath === "string" &&
439
+ dirname(resolve(original.filePath)) ===
440
+ this.preferredScopeDirectory(scope)
441
+ );
318
442
  }
319
443
 
320
444
  destination(name: string, scope: AgentScope, original?: SaveOrigin): string {
321
445
  if (!NAME.test(name)) throw new Error("Unsafe agent name");
322
- const directory = this.scopeDirectory(scope);
446
+ const directory = this.preferredScopeDirectory(scope);
323
447
  if (
324
- original?.name === name &&
325
- original.source === scope &&
326
- typeof original.filePath === "string"
448
+ this.canPreserveDestination(name, scope, original) &&
449
+ typeof original?.filePath === "string"
327
450
  ) {
328
451
  return validatePreservedDestination(original.filePath, directory);
329
452
  }
@@ -336,13 +459,19 @@ export class ConfigStore {
336
459
  const filePath = this.destination(validated.name, scope, original);
337
460
  const directory = dirname(filePath);
338
461
  // Reject redirected destination directories and files before writing.
339
- for (const path of [...this.destinationBasePaths(scope, directory), filePath]) {
462
+ for (const path of [
463
+ ...this.destinationBasePaths(scope, directory),
464
+ filePath,
465
+ ]) {
340
466
  const stat = assertNotSymlinkPath(path);
341
467
  if (path === filePath && stat && !stat.isFile())
342
468
  throw new Error(`Unsafe agent destination: ${filePath}`);
343
469
  }
344
470
  mkdirSync(directory, { recursive: true });
345
- const temporary = join(dirname(filePath), `.${validated.name}.${randomUUID()}.tmp`);
471
+ const temporary = join(
472
+ dirname(filePath),
473
+ `.${validated.name}.${randomUUID()}.tmp`,
474
+ );
346
475
  try {
347
476
  writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
348
477
  renameSync(temporary, filePath);