pi-subagent-manager 1.2.0 → 1.2.1

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.
@@ -93,9 +93,7 @@ function errorCode(error: unknown): string | undefined {
93
93
  : undefined;
94
94
  }
95
95
 
96
- function lstatIfPresent(
97
- path: string,
98
- ): ReturnType<typeof lstatSync> | undefined {
96
+ function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined {
99
97
  try {
100
98
  return lstatSync(path);
101
99
  } catch (error) {
@@ -104,9 +102,7 @@ function lstatIfPresent(
104
102
  }
105
103
  }
106
104
 
107
- function assertNotSymlinkPath(
108
- path: string,
109
- ): ReturnType<typeof lstatSync> | undefined {
105
+ function assertNotSymlinkPath(path: string): ReturnType<typeof lstatSync> | undefined {
110
106
  const stat = lstatIfPresent(path);
111
107
  if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
112
108
  return stat;
@@ -129,9 +125,7 @@ function validatePreservedDestination(
129
125
  }
130
126
 
131
127
  function frontmatter(content: string): { yaml: string; body: string } {
132
- const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(
133
- content,
134
- );
128
+ const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m.exec(content);
135
129
  if (!match || match.index !== 0)
136
130
  throw new Error("Expected YAML frontmatter enclosed by --- lines");
137
131
  return { yaml: match[1], body: content.slice(match[0].length) };
@@ -160,13 +154,8 @@ function modelSuggestionNames(value: unknown): string[] {
160
154
  }
161
155
 
162
156
  function toolNames(value: unknown, label: string): string[] {
163
- if (
164
- !Array.isArray(value) ||
165
- value.some((name) => typeof name !== "string" || !TOOL.test(name))
166
- ) {
167
- throw new Error(
168
- `${label} must be an array of exact tool names (no wildcards or patterns)`,
169
- );
157
+ if (!Array.isArray(value) || value.some((name) => typeof name !== "string" || !TOOL.test(name))) {
158
+ throw new Error(`${label} must be an array of exact tool names (no wildcards or patterns)`);
170
159
  }
171
160
  if (new Set(value).size !== value.length)
172
161
  throw new Error(`${label} contains duplicate tool names`);
@@ -176,13 +165,10 @@ function toolNames(value: unknown, label: string): string[] {
176
165
  function toolPolicy(value: unknown): NonNullable<AgentType["tools"]> {
177
166
  const mapping = record(value, "tools");
178
167
  for (const key of Object.keys(mapping))
179
- if (key !== "allow" && key !== "block")
180
- throw new Error(`Unknown tools field: ${key}`);
168
+ if (key !== "allow" && key !== "block") throw new Error(`Unknown tools field: ${key}`);
181
169
  const result: NonNullable<AgentType["tools"]> = {};
182
- if (Object.hasOwn(mapping, "allow"))
183
- result.allow = toolNames(mapping.allow, "tools.allow");
184
- if (Object.hasOwn(mapping, "block"))
185
- result.block = toolNames(mapping.block, "tools.block");
170
+ if (Object.hasOwn(mapping, "allow")) result.allow = toolNames(mapping.allow, "tools.allow");
171
+ if (Object.hasOwn(mapping, "block")) result.block = toolNames(mapping.block, "tools.block");
186
172
  return result;
187
173
  }
188
174
 
@@ -200,12 +186,10 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
200
186
  try {
201
187
  const { yaml, body } = frontmatter(content);
202
188
  const doc = parseDocument(yaml, { uniqueKeys: true });
203
- if (doc.errors.length)
204
- throw new Error(doc.errors.map((error) => error.message).join("; "));
189
+ if (doc.errors.length) throw new Error(doc.errors.map((error) => error.message).join("; "));
205
190
  const data = record(doc.toJS({ maxAliasCount: 0 }), "Frontmatter");
206
191
  for (const key of Object.keys(data))
207
- if (!FIELDS.has(key))
208
- throw new Error(`Unknown frontmatter field: ${key}`);
192
+ if (!FIELDS.has(key)) throw new Error(`Unknown frontmatter field: ${key}`);
209
193
  if (typeof data.name !== "string" || !NAME.test(data.name))
210
194
  throw new Error(
211
195
  "name must be a safe identifier using letters, numbers, underscores or hyphens",
@@ -225,26 +209,20 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
225
209
  if (Object.hasOwn(data, "modelSuggestions"))
226
210
  result.modelSuggestions = modelSuggestionNames(data.modelSuggestions);
227
211
  if (Object.hasOwn(data, "thinkingLevel")) {
228
- if (
229
- !THINKING_LEVELS.includes(
230
- data.thinkingLevel as AgentType["thinkingLevel"] & string,
231
- )
232
- )
233
- throw new Error(
234
- `thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`,
235
- );
212
+ if (!THINKING_LEVELS.includes(data.thinkingLevel as AgentType["thinkingLevel"] & string))
213
+ throw new Error(`thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`);
236
214
  result.thinkingLevel = data.thinkingLevel as AgentType["thinkingLevel"];
237
215
  }
238
216
  if (Object.hasOwn(data, "color")) {
239
217
  if (!AGENT_COLORS.includes(data.color as (typeof AGENT_COLORS)[number]))
240
- throw new Error(
241
- `color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`,
242
- );
218
+ throw new Error(`color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`);
243
219
  result.color = data.color as string;
244
220
  }
245
221
  if (Object.hasOwn(data, "icon")) {
246
222
  if (typeof data.icon !== "string" || !/^\p{Co}$/u.test(data.icon))
247
- throw new Error("icon must be a single literal Nerd Font glyph (Unicode private-use character)");
223
+ throw new Error(
224
+ "icon must be a single literal Nerd Font glyph (Unicode private-use character)",
225
+ );
248
226
  result.icon = data.icon;
249
227
  }
250
228
  if (Object.hasOwn(data, "tools")) result.tools = toolPolicy(data.tools);
@@ -258,8 +236,7 @@ export function parseAgentType(content: string, filePath?: string): AgentType {
258
236
  }
259
237
 
260
238
  export function serializeAgentType(type: AgentType): string {
261
- if (typeof type.systemPrompt !== "string")
262
- throw new Error("systemPrompt must be a string");
239
+ if (typeof type.systemPrompt !== "string") throw new Error("systemPrompt must be a string");
263
240
  const data: Record<string, unknown> = {
264
241
  name: type.name,
265
242
  description: type.description,
@@ -326,12 +303,9 @@ export function parseAgentSettings(
326
303
  const label = filePath ?? "Agent settings override";
327
304
  try {
328
305
  if (/^\uFEFF?---[ \t]*\r?\n/m.test(content) || content.includes("\n---"))
329
- throw new Error(
330
- "Settings overrides are plain YAML with no frontmatter and no Markdown body",
331
- );
306
+ throw new Error("Settings overrides are plain YAML with no frontmatter and no Markdown body");
332
307
  const doc = parseDocument(content, { uniqueKeys: true });
333
- if (doc.errors.length)
334
- throw new Error(doc.errors.map((error) => error.message).join("; "));
308
+ if (doc.errors.length) throw new Error(doc.errors.map((error) => error.message).join("; "));
335
309
  const data = record(doc.toJS({ maxAliasCount: 0 }) ?? {}, "Settings override");
336
310
  for (const key of Object.keys(data)) {
337
311
  if (key === "systemPrompt" || key === "prompt" || key === "body")
@@ -359,16 +333,14 @@ export function parseAgentSettings(
359
333
  }
360
334
  const hasModels = Object.hasOwn(data, "models");
361
335
  const hasModel = Object.hasOwn(data, "model");
362
- if (hasModels && hasModel)
363
- throw new Error("Specify either models or model, not both");
336
+ if (hasModels && hasModel) throw new Error("Specify either models or model, not both");
364
337
  if (hasModels)
365
338
  result.models = nullableField(data.models, (value) =>
366
339
  getModelPreferences({ models: value }),
367
340
  ) as string[] | null | undefined;
368
341
  if (hasModel) {
369
342
  if (data.model === null) result.model = null;
370
- else
371
- result.models = getModelPreferences({ model: data.model }) as string[];
343
+ else result.models = getModelPreferences({ model: data.model }) as string[];
372
344
  }
373
345
  if (Object.hasOwn(data, "modelSuggestions"))
374
346
  result.modelSuggestions = nullableField(data.modelSuggestions, (value) =>
@@ -377,17 +349,13 @@ export function parseAgentSettings(
377
349
  if (Object.hasOwn(data, "thinkingLevel"))
378
350
  result.thinkingLevel = nullableField(data.thinkingLevel, (value) => {
379
351
  if (!THINKING_LEVELS.includes(value as AgentType["thinkingLevel"] & string))
380
- throw new Error(
381
- `thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`,
382
- );
352
+ throw new Error(`thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`);
383
353
  return value as AgentType["thinkingLevel"];
384
354
  });
385
355
  if (Object.hasOwn(data, "color"))
386
356
  result.color = nullableField(data.color, (value) => {
387
357
  if (!AGENT_COLORS.includes(value as (typeof AGENT_COLORS)[number]))
388
- throw new Error(
389
- `color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`,
390
- );
358
+ throw new Error(`color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`);
391
359
  return value as string;
392
360
  });
393
361
  if (Object.hasOwn(data, "icon"))
@@ -402,9 +370,7 @@ export function parseAgentSettings(
402
370
  result.tools = data.tools === null ? null : overrideToolPolicy(data.tools);
403
371
  return result;
404
372
  } catch (error) {
405
- throw new Error(
406
- `${label}: ${error instanceof Error ? error.message : String(error)}`,
407
- );
373
+ throw new Error(`${label}: ${error instanceof Error ? error.message : String(error)}`);
408
374
  }
409
375
  }
410
376
 
@@ -420,9 +386,7 @@ export function serializeAgentSettings(override: AgentSettingsOverride): string
420
386
  else if (models !== undefined) data.models = models;
421
387
  if (override.modelSuggestions !== undefined)
422
388
  data.modelSuggestions =
423
- override.modelSuggestions === null
424
- ? null
425
- : modelSuggestionNames(override.modelSuggestions);
389
+ override.modelSuggestions === null ? null : modelSuggestionNames(override.modelSuggestions);
426
390
  for (const key of ["thinkingLevel", "color", "icon", "tools"] as const)
427
391
  if (override[key] !== undefined) data[key] = override[key];
428
392
  const content = `${stringify(data)}`;
@@ -435,10 +399,7 @@ export function serializeAgentSettings(override: AgentSettingsOverride): string
435
399
  * follow the base; explicit null clears the field. The prompt body always
436
400
  * comes from the base.
437
401
  */
438
- export function mergeAgentSettings(
439
- base: AgentType,
440
- override: AgentSettingsOverride,
441
- ): AgentType {
402
+ export function mergeAgentSettings(base: AgentType, override: AgentSettingsOverride): AgentType {
442
403
  const merged: AgentType = structuredClone(base);
443
404
  if (override.description !== undefined) merged.description = override.description;
444
405
  const models = getModelPreferences({
@@ -452,12 +413,7 @@ export function mergeAgentSettings(
452
413
  merged.models = [...models];
453
414
  delete merged.model;
454
415
  }
455
- for (const key of [
456
- "modelSuggestions",
457
- "thinkingLevel",
458
- "color",
459
- "icon",
460
- ] as const) {
416
+ for (const key of ["modelSuggestions", "thinkingLevel", "color", "icon"] as const) {
461
417
  const value = override[key];
462
418
  if (value === undefined) continue;
463
419
  if (value === null) delete merged[key];
@@ -497,12 +453,7 @@ export function diffAgentSettings(base: AgentType, draft: AgentType): AgentSetti
497
453
  if (draftModels === undefined) override.models = null;
498
454
  else override.models = [...draftModels];
499
455
  }
500
- for (const key of [
501
- "modelSuggestions",
502
- "thinkingLevel",
503
- "color",
504
- "icon",
505
- ] as const) {
456
+ for (const key of ["modelSuggestions", "thinkingLevel", "color", "icon"] as const) {
506
457
  const before = base[key];
507
458
  const after = draft[key];
508
459
  if (sameSetting(before, after)) continue;
@@ -611,24 +562,17 @@ export class ConfigStore {
611
562
  this.diagnostics = [];
612
563
  const layers: [string, NonNullable<AgentType["source"]>][] = [
613
564
  [
614
- this.options.bundledDir ??
615
- fileURLToPath(new URL("../../agents/", import.meta.url)),
565
+ this.options.bundledDir ?? fileURLToPath(new URL("../../agents/", import.meta.url)),
616
566
  "bundled",
617
567
  ],
618
568
  ...this.scopeDirectories("user").map(
619
- (directory): [string, NonNullable<AgentType["source"]>] => [
620
- directory,
621
- "user",
622
- ],
569
+ (directory): [string, NonNullable<AgentType["source"]>] => [directory, "user"],
623
570
  ),
624
571
  ];
625
572
  if (this.options.includeProject)
626
573
  layers.push(
627
574
  ...this.scopeDirectories("project").map(
628
- (directory): [string, NonNullable<AgentType["source"]>] => [
629
- directory,
630
- "project",
631
- ],
575
+ (directory): [string, NonNullable<AgentType["source"]>] => [directory, "project"],
632
576
  ),
633
577
  );
634
578
  for (const [directory, source] of layers) {
@@ -643,9 +587,7 @@ export class ConfigStore {
643
587
  if (!stat.isDirectory())
644
588
  throw new Error(`Agent directory must be a directory: ${directory}`);
645
589
  files = readdirSync(directory)
646
- .filter(
647
- (file) => file.endsWith(".md") || isAgentOverrideFile(file),
648
- )
590
+ .filter((file) => file.endsWith(".md") || isAgentOverrideFile(file))
649
591
  .sort();
650
592
  } catch (error) {
651
593
  this.diagnostics.push(`${directory}: ${String(error)}`);
@@ -678,16 +620,12 @@ export class ConfigStore {
678
620
  let content = "";
679
621
  try {
680
622
  if (!lstatSync(filePath).isFile())
681
- throw new Error(
682
- "Agent definition must be a regular file, not a symlink",
683
- );
623
+ throw new Error("Agent definition must be a regular file, not a symlink");
684
624
  content = readFileSync(filePath, "utf8");
685
625
  const type = parseAgentType(content, filePath);
686
626
  if (seenNames.has(type.name)) {
687
627
  blocked.add(type.name);
688
- this.diagnostics.push(
689
- `${filePath}: Duplicate agent name in bundled layer: ${type.name}`,
690
- );
628
+ this.diagnostics.push(`${filePath}: Duplicate agent name in bundled layer: ${type.name}`);
691
629
  continue;
692
630
  }
693
631
  seenNames.add(type.name);
@@ -725,17 +663,10 @@ export class ConfigStore {
725
663
  * Having both for one name, duplicate declarations, malformed files, or an
726
664
  * override without a base fails closed for that agent name.
727
665
  */
728
- private applyScopeLayer(
729
- directory: string,
730
- scope: AgentSettingsScope,
731
- files: string[],
732
- ): void {
666
+ private applyScopeLayer(directory: string, scope: AgentSettingsScope, files: string[]): void {
733
667
  const blocked = new Set<string>();
734
668
  const forks = new Map<string, { type: AgentType; file: string }>();
735
- const overrides = new Map<
736
- string,
737
- { override: AgentSettingsOverride; file: string }
738
- >();
669
+ const overrides = new Map<string, { override: AgentSettingsOverride; file: string }>();
739
670
  const forkNames = new Set<string>();
740
671
  const declareBlocked = (name: string) => {
741
672
  blocked.add(name);
@@ -752,9 +683,7 @@ export class ConfigStore {
752
683
  let content = "";
753
684
  try {
754
685
  if (!lstatSync(filePath).isFile())
755
- throw new Error(
756
- "Agent settings override must be a regular file, not a symlink",
757
- );
686
+ throw new Error("Agent settings override must be a regular file, not a symlink");
758
687
  content = readFileSync(filePath, "utf8");
759
688
  const override = parseAgentSettings(content, filePath, overrideName);
760
689
  const key = override.name ?? overrideName;
@@ -797,9 +726,7 @@ export class ConfigStore {
797
726
  let content = "";
798
727
  try {
799
728
  if (!lstatSync(filePath).isFile())
800
- throw new Error(
801
- "Agent definition must be a regular file, not a symlink",
802
- );
729
+ throw new Error("Agent definition must be a regular file, not a symlink");
803
730
  content = readFileSync(filePath, "utf8");
804
731
  const type = parseAgentType(content, filePath);
805
732
  if (overrides.has(type.name)) {
@@ -897,9 +824,7 @@ export class ConfigStore {
897
824
  }
898
825
 
899
826
  list(): AgentType[] {
900
- return structuredClone(
901
- [...this.types.values()].sort((a, b) => a.name.localeCompare(b.name)),
902
- );
827
+ return structuredClone([...this.types.values()].sort((a, b) => a.name.localeCompare(b.name)));
903
828
  }
904
829
 
905
830
  get(name: string): AgentType {
@@ -913,19 +838,12 @@ export class ConfigStore {
913
838
  }
914
839
 
915
840
  private preferredScopeDirectory(scope: AgentScope): string {
916
- if (scope !== "user" && scope !== "project")
917
- throw new Error("Invalid agent scope");
841
+ if (scope !== "user" && scope !== "project") throw new Error("Invalid agent scope");
918
842
  if (scope === "project" && !this.options.includeProject)
919
843
  throw new Error("Project agents are not enabled/trusted");
920
844
  return scope === "user"
921
845
  ? resolve(this.options.agentDir, SUBAGENT_MANAGER_DIR, AGENTS_DIR)
922
- : resolve(
923
- this.options.cwd,
924
- ".pi",
925
- "agent",
926
- SUBAGENT_MANAGER_DIR,
927
- AGENTS_DIR,
928
- );
846
+ : resolve(this.options.cwd, ".pi", "agent", SUBAGENT_MANAGER_DIR, AGENTS_DIR);
929
847
  }
930
848
 
931
849
  // Manager-owned storage only. Do not scan legacy Pi agent packages.
@@ -941,13 +859,7 @@ export class ConfigStore {
941
859
  const base = resolve(this.options.cwd);
942
860
  const projectPi = join(base, ".pi");
943
861
  const projectAgent = join(projectPi, "agent");
944
- return [
945
- base,
946
- projectPi,
947
- projectAgent,
948
- join(projectAgent, SUBAGENT_MANAGER_DIR),
949
- directory,
950
- ];
862
+ return [base, projectPi, projectAgent, join(projectAgent, SUBAGENT_MANAGER_DIR), directory];
951
863
  }
952
864
 
953
865
  /** Base definition under the top customization, for diffing and read-only display. */
@@ -994,15 +906,12 @@ export class ConfigStore {
994
906
  original?.name !== name ||
995
907
  original.source !== scope ||
996
908
  typeof original.filePath !== "string" ||
997
- dirname(resolve(original.filePath)) !==
998
- this.preferredScopeDirectory(scope)
909
+ dirname(resolve(original.filePath)) !== this.preferredScopeDirectory(scope)
999
910
  )
1000
911
  return false;
1001
912
  const preserved = resolve(original.filePath);
1002
913
  if (kind === "fork") return preserved.endsWith(".md");
1003
- return AGENT_OVERRIDE_EXTENSIONS.some((extension) =>
1004
- preserved.endsWith(extension),
1005
- );
914
+ return AGENT_OVERRIDE_EXTENSIONS.some((extension) => preserved.endsWith(extension));
1006
915
  }
1007
916
 
1008
917
  destination(
@@ -1029,10 +938,7 @@ export class ConfigStore {
1029
938
  private writeContent(filePath: string, name: string, content: string): void {
1030
939
  const directory = dirname(filePath);
1031
940
  mkdirSync(directory, { recursive: true });
1032
- const temporary = join(
1033
- dirname(filePath),
1034
- `.${name}.${randomUUID()}.tmp`,
1035
- );
941
+ const temporary = join(dirname(filePath), `.${name}.${randomUUID()}.tmp`);
1036
942
  try {
1037
943
  writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
1038
944
  renameSync(temporary, filePath);
@@ -1044,10 +950,7 @@ export class ConfigStore {
1044
950
  private assertWritableDestination(filePath: string, scope: AgentScope): void {
1045
951
  const directory = dirname(filePath);
1046
952
  // Reject redirected destination directories and files before writing.
1047
- for (const path of [
1048
- ...this.destinationBasePaths(scope, directory),
1049
- filePath,
1050
- ]) {
953
+ for (const path of [...this.destinationBasePaths(scope, directory), filePath]) {
1051
954
  const stat = assertNotSymlinkPath(path);
1052
955
  if (path === filePath && stat && !stat.isFile())
1053
956
  throw new Error(`Unsafe agent destination: ${filePath}`);
@@ -1072,12 +975,7 @@ export class ConfigStore {
1072
975
  * are retained; `original` is the pre-edit snapshot (also used to avoid
1073
976
  * copying inherited settings into another scope or from a stale draft).
1074
977
  */
1075
- saveOverride(
1076
- name: string,
1077
- draft: AgentType,
1078
- scope: AgentScope,
1079
- original?: AgentType,
1080
- ): AgentType {
978
+ saveOverride(name: string, draft: AgentType, scope: AgentScope, original?: AgentType): AgentType {
1081
979
  if (!NAME.test(name)) throw new Error("Unsafe agent name");
1082
980
  if (draft.name !== name)
1083
981
  throw new Error("Settings overrides cannot rename the agent; fork it instead");
@@ -12,15 +12,12 @@ export function getModelPreferences(type: {
12
12
  }): string[] | undefined {
13
13
  const hasModels = type.models !== undefined;
14
14
  const hasModel = type.model !== undefined;
15
- if (hasModels && hasModel)
16
- throw new Error("Specify either models or model, not both");
15
+ if (hasModels && hasModel) throw new Error("Specify either models or model, not both");
17
16
  if (hasModels) {
18
17
  if (!Array.isArray(type.models))
19
18
  throw new Error("models must be an array of provider/model-id strings");
20
19
  if (type.models.length === 0)
21
- throw new Error(
22
- "models must not be empty; omit models to inherit the parent/default model",
23
- );
20
+ throw new Error("models must not be empty; omit models to inherit the parent/default model");
24
21
  const models = type.models.map((value, index) =>
25
22
  validateModelPreference(value, `models[${index}]`),
26
23
  );