pi-subagent-manager 0.12.0 → 0.13.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.
@@ -115,9 +115,13 @@ function assertNotSymlinkPath(
115
115
  function validatePreservedDestination(
116
116
  filePath: string,
117
117
  directory: string,
118
+ extensions: readonly string[] = [".md"],
118
119
  ): string {
119
120
  const resolved = resolve(filePath);
120
- if (dirname(resolved) !== directory || !resolved.endsWith(".md"))
121
+ if (
122
+ dirname(resolved) !== directory ||
123
+ !extensions.some((extension) => resolved.endsWith(extension))
124
+ )
121
125
  throw new Error(`Unsafe agent destination: ${resolved}`);
122
126
  const stat = lstatIfPresent(resolved);
123
127
  if (!stat?.isFile()) throw new Error(`Unsafe agent destination: ${resolved}`);
@@ -261,6 +265,246 @@ export function serializeAgentType(type: AgentType): string {
261
265
  return content;
262
266
  }
263
267
 
268
+ export type AgentSettingsScope = "user" | "project";
269
+ export type AgentCustomizationKind = "fork" | "override";
270
+
271
+ /**
272
+ * Sparse settings parsed from a `<name>.yml` override file. Plain YAML mapping,
273
+ * no frontmatter, no Markdown body. Omitted fields follow the base definition;
274
+ * explicit `null` on an optional field resets it to the base/inherit state.
275
+ */
276
+ export interface AgentSettingsOverride {
277
+ name?: string;
278
+ description?: string;
279
+ models?: string[] | null;
280
+ /** @deprecated Single-model alias; normalized to models. */
281
+ model?: string | null;
282
+ modelSuggestions?: string[] | null;
283
+ thinkingLevel?: AgentType["thinkingLevel"] | null;
284
+ color?: string | null;
285
+ icon?: string | null;
286
+ tools?: NonNullable<AgentType["tools"]> | null;
287
+ }
288
+
289
+ export const AGENT_OVERRIDE_EXTENSIONS = [".yml", ".yaml"] as const;
290
+
291
+ function overrideBaseName(file: string): string | undefined {
292
+ for (const extension of AGENT_OVERRIDE_EXTENSIONS)
293
+ if (file.endsWith(extension)) return file.slice(0, -extension.length);
294
+ return undefined;
295
+ }
296
+
297
+ export function isAgentOverrideFile(file: string): boolean {
298
+ return overrideBaseName(file) !== undefined;
299
+ }
300
+
301
+ function nullableField<T>(value: unknown, validate: (value: unknown) => T): T | null {
302
+ if (value === null) return null;
303
+ return validate(value);
304
+ }
305
+
306
+ /**
307
+ * Parse a settings-only `<name>.yml` override. Rejects prompt bodies and
308
+ * unknown fields; validates shared fields with the same rules as full
309
+ * definitions. `expectedName` (the file basename) must match `name` when set.
310
+ */
311
+ export function parseAgentSettings(
312
+ content: string,
313
+ filePath?: string,
314
+ expectedName?: string,
315
+ ): AgentSettingsOverride {
316
+ const label = filePath ?? "Agent settings override";
317
+ try {
318
+ if (/^\uFEFF?---[ \t]*\r?\n/m.test(content) || content.includes("\n---"))
319
+ throw new Error(
320
+ "Settings overrides are plain YAML with no frontmatter and no Markdown body",
321
+ );
322
+ const doc = parseDocument(content, { uniqueKeys: true });
323
+ if (doc.errors.length)
324
+ throw new Error(doc.errors.map((error) => error.message).join("; "));
325
+ const data = record(doc.toJS({ maxAliasCount: 0 }) ?? {}, "Settings override");
326
+ for (const key of Object.keys(data)) {
327
+ if (key === "systemPrompt" || key === "prompt" || key === "body")
328
+ throw new Error(
329
+ `Settings overrides carry no prompt body; "${key}" belongs in a <name>.md fork`,
330
+ );
331
+ if (!FIELDS.has(key)) throw new Error(`Unknown settings field: ${key}`);
332
+ }
333
+ const result: AgentSettingsOverride = {};
334
+ if (Object.hasOwn(data, "name")) {
335
+ if (typeof data.name !== "string" || !NAME.test(data.name))
336
+ throw new Error(
337
+ "name must be a safe identifier using letters, numbers, underscores or hyphens",
338
+ );
339
+ if (expectedName !== undefined && data.name !== expectedName)
340
+ throw new Error(
341
+ `name ${JSON.stringify(data.name)} does not match override file ${JSON.stringify(expectedName)}`,
342
+ );
343
+ result.name = data.name;
344
+ }
345
+ if (Object.hasOwn(data, "description")) {
346
+ if (typeof data.description !== "string" || !data.description.trim())
347
+ throw new Error("description must be a nonempty string");
348
+ result.description = data.description;
349
+ }
350
+ const hasModels = Object.hasOwn(data, "models");
351
+ const hasModel = Object.hasOwn(data, "model");
352
+ if (hasModels && hasModel)
353
+ throw new Error("Specify either models or model, not both");
354
+ if (hasModels)
355
+ result.models = nullableField(data.models, (value) =>
356
+ getModelPreferences({ models: value }),
357
+ ) as string[] | null | undefined;
358
+ if (hasModel) {
359
+ if (data.model === null) result.model = null;
360
+ else
361
+ result.models = getModelPreferences({ model: data.model }) as string[];
362
+ }
363
+ if (Object.hasOwn(data, "modelSuggestions"))
364
+ result.modelSuggestions = nullableField(data.modelSuggestions, (value) =>
365
+ modelSuggestionNames(value),
366
+ );
367
+ if (Object.hasOwn(data, "thinkingLevel"))
368
+ result.thinkingLevel = nullableField(data.thinkingLevel, (value) => {
369
+ if (!THINKING_LEVELS.includes(value as AgentType["thinkingLevel"] & string))
370
+ throw new Error(
371
+ `thinkingLevel must be one of: ${THINKING_LEVELS.join(", ")}`,
372
+ );
373
+ return value as AgentType["thinkingLevel"];
374
+ });
375
+ if (Object.hasOwn(data, "color"))
376
+ result.color = nullableField(data.color, (value) => {
377
+ if (!AGENT_COLORS.includes(value as (typeof AGENT_COLORS)[number]))
378
+ throw new Error(
379
+ `color must be a Pi foreground token: ${AGENT_COLORS.join(", ")}`,
380
+ );
381
+ return value as string;
382
+ });
383
+ if (Object.hasOwn(data, "icon"))
384
+ result.icon = nullableField(data.icon, (value) => {
385
+ if (typeof value !== "string" || !/^\p{Co}$/u.test(value))
386
+ throw new Error(
387
+ "icon must be a single literal Nerd Font glyph (Unicode private-use character)",
388
+ );
389
+ return value;
390
+ });
391
+ if (Object.hasOwn(data, "tools"))
392
+ result.tools = data.tools === null ? null : toolPolicy(data.tools);
393
+ return result;
394
+ } catch (error) {
395
+ throw new Error(
396
+ `${label}: ${error instanceof Error ? error.message : String(error)}`,
397
+ );
398
+ }
399
+ }
400
+
401
+ export function serializeAgentSettings(override: AgentSettingsOverride): string {
402
+ const data: Record<string, unknown> = {};
403
+ if (override.name !== undefined) data.name = override.name;
404
+ if (override.description !== undefined) data.description = override.description;
405
+ const models = getModelPreferences({
406
+ models: override.models ?? undefined,
407
+ model: override.model ?? undefined,
408
+ } as { models?: unknown; model?: unknown });
409
+ if (override.models === null || override.model === null) data.models = null;
410
+ else if (models !== undefined) data.models = models;
411
+ if (override.modelSuggestions !== undefined)
412
+ data.modelSuggestions =
413
+ override.modelSuggestions === null
414
+ ? null
415
+ : modelSuggestionNames(override.modelSuggestions);
416
+ for (const key of ["thinkingLevel", "color", "icon", "tools"] as const)
417
+ if (override[key] !== undefined) data[key] = override[key];
418
+ const content = `${stringify(data)}`;
419
+ parseAgentSettings(content);
420
+ return content;
421
+ }
422
+
423
+ /** Fields an override may clear back to the base/inherit state with null. */
424
+ const CLEARABLE_OVERRIDE_FIELDS = new Set([
425
+ "models",
426
+ "modelSuggestions",
427
+ "thinkingLevel",
428
+ "color",
429
+ "icon",
430
+ "tools",
431
+ ]);
432
+
433
+ /**
434
+ * Merge a sparse settings override on top of a base definition. Unset fields
435
+ * follow the base; explicit null clears the field. The prompt body always
436
+ * comes from the base.
437
+ */
438
+ export function mergeAgentSettings(
439
+ base: AgentType,
440
+ override: AgentSettingsOverride,
441
+ ): AgentType {
442
+ const merged: AgentType = structuredClone(base);
443
+ if (override.description !== undefined) merged.description = override.description;
444
+ const models = getModelPreferences({
445
+ models: override.models ?? undefined,
446
+ model: override.model ?? undefined,
447
+ } as { models?: unknown; model?: unknown });
448
+ if (override.models === null || override.model === null) {
449
+ delete merged.models;
450
+ delete merged.model;
451
+ } else if (models !== undefined) {
452
+ merged.models = [...models];
453
+ delete merged.model;
454
+ }
455
+ for (const key of [
456
+ "modelSuggestions",
457
+ "thinkingLevel",
458
+ "color",
459
+ "icon",
460
+ "tools",
461
+ ] as const) {
462
+ const value = override[key];
463
+ if (value === undefined) continue;
464
+ if (value === null) delete merged[key];
465
+ else (merged[key] as unknown) = structuredClone(value);
466
+ }
467
+ merged.systemPrompt = base.systemPrompt;
468
+ return merged;
469
+ }
470
+
471
+ /**
472
+ * Diff a draft against its base: only changed settings land in the override
473
+ * file, so untouched fields keep tracking bundled updates. Always includes
474
+ * the agent name for readability.
475
+ */
476
+ export function diffAgentSettings(base: AgentType, draft: AgentType): AgentSettingsOverride {
477
+ const override: AgentSettingsOverride = { name: draft.name };
478
+ if (draft.description !== base.description) override.description = draft.description;
479
+ const baseModels = getModelPreferences(base);
480
+ const draftModels = getModelPreferences(draft);
481
+ const sameModels =
482
+ (baseModels === undefined && draftModels === undefined) ||
483
+ (baseModels !== undefined &&
484
+ draftModels !== undefined &&
485
+ baseModels.length === draftModels.length &&
486
+ baseModels.every((model, index) => model === draftModels[index]));
487
+ if (!sameModels) {
488
+ if (draftModels === undefined) override.models = null;
489
+ else override.models = [...draftModels];
490
+ }
491
+ for (const key of [
492
+ "modelSuggestions",
493
+ "thinkingLevel",
494
+ "color",
495
+ "icon",
496
+ "tools",
497
+ ] as const) {
498
+ const before = base[key];
499
+ const after = draft[key];
500
+ if (JSON.stringify(before ?? null) === JSON.stringify(after ?? null)) continue;
501
+ if (after === undefined) override[key] = null as never;
502
+ else (override[key] as unknown) = structuredClone(after);
503
+ }
504
+ void CLEARABLE_OVERRIDE_FIELDS;
505
+ return override;
506
+ }
507
+
264
508
  export function selectTools(
265
509
  policy: AgentType["tools"],
266
510
  available: string[],
@@ -294,6 +538,7 @@ export interface ConfigStoreOptions {
294
538
  export class ConfigStore {
295
539
  diagnostics: string[] = [];
296
540
  private types = new Map<string, AgentType>();
541
+ private bases = new Map<string, AgentType>();
297
542
  private readonly options: ConfigStoreOptions;
298
543
 
299
544
  constructor(options: ConfigStoreOptions) {
@@ -303,6 +548,7 @@ export class ConfigStore {
303
548
 
304
549
  reload(): void {
305
550
  this.types.clear();
551
+ this.bases.clear();
306
552
  this.diagnostics = [];
307
553
  const layers: [string, NonNullable<AgentType["source"]>][] = [
308
554
  [
@@ -334,40 +580,140 @@ export class ConfigStore {
334
580
  if (!stat.isDirectory())
335
581
  throw new Error(`Agent directory must be a directory: ${directory}`);
336
582
  files = readdirSync(directory)
337
- .filter((file) => file.endsWith(".md"))
583
+ .filter(
584
+ (file) => file.endsWith(".md") || isAgentOverrideFile(file),
585
+ )
338
586
  .sort();
339
587
  } catch (error) {
340
588
  this.diagnostics.push(`${directory}: ${String(error)}`);
341
589
  // An unreadable override layer cannot safely expose lower-precedence policies.
342
590
  this.types.clear();
591
+ this.bases.clear();
343
592
  continue;
344
593
  }
345
- const blocked = new Set<string>();
346
- const seenNames = new Set<string>();
347
- for (const file of files) {
348
- const filePath = join(directory, file);
594
+ if (source === "bundled") {
595
+ this.loadBundledLayer(directory, files);
596
+ continue;
597
+ }
598
+ this.applyScopeLayer(directory, source, files);
599
+ }
600
+ }
601
+
602
+ /** Bundled layer: full `<name>.md` definitions only; overrides are rejected. */
603
+ private loadBundledLayer(directory: string, files: string[]): void {
604
+ const blocked = new Set<string>();
605
+ const seenNames = new Set<string>();
606
+ for (const file of files) {
607
+ const filePath = join(directory, file);
608
+ if (isAgentOverrideFile(file)) {
609
+ blocked.add(overrideBaseName(file)!);
610
+ this.diagnostics.push(
611
+ `${filePath}: Settings overrides (<name>.yml) are not allowed in the bundled layer`,
612
+ );
613
+ continue;
614
+ }
615
+ let content = "";
616
+ try {
617
+ if (!lstatSync(filePath).isFile())
618
+ throw new Error(
619
+ "Agent definition must be a regular file, not a symlink",
620
+ );
621
+ content = readFileSync(filePath, "utf8");
622
+ const type = parseAgentType(content, filePath);
623
+ if (seenNames.has(type.name)) {
624
+ blocked.add(type.name);
625
+ this.diagnostics.push(
626
+ `${filePath}: Duplicate agent name in bundled layer: ${type.name}`,
627
+ );
628
+ continue;
629
+ }
630
+ seenNames.add(type.name);
631
+ this.types.set(type.name, { ...type, source: "bundled" });
632
+ } catch (error) {
633
+ blocked.add(file.slice(0, -3));
634
+ // Extract declared names even if another field or duplicate key is malformed.
635
+ try {
636
+ const doc = parseDocument(frontmatter(content).yaml);
637
+ if (isMap(doc.contents))
638
+ for (const pair of doc.contents.items) {
639
+ if (
640
+ isScalar(pair.key) &&
641
+ pair.key.value === "name" &&
642
+ isScalar(pair.value) &&
643
+ typeof pair.value.value === "string"
644
+ )
645
+ blocked.add(pair.value.value);
646
+ }
647
+ } catch {
648
+ /* Filename still provides a fail-closed tombstone. */
649
+ }
650
+ this.diagnostics.push(`${filePath}: ${String(error)}`);
651
+ }
652
+ }
653
+ for (const name of blocked) {
654
+ this.types.delete(name);
655
+ this.bases.delete(name);
656
+ }
657
+ }
658
+
659
+ /**
660
+ * User/project layer: `<name>.md` is a full fork (replaces the base),
661
+ * `<name>.yml` is a settings-only override merged on top of the base.
662
+ * Having both for one name, duplicate declarations, malformed files, or an
663
+ * override without a base fails closed for that agent name.
664
+ */
665
+ private applyScopeLayer(
666
+ directory: string,
667
+ scope: AgentSettingsScope,
668
+ files: string[],
669
+ ): void {
670
+ const blocked = new Set<string>();
671
+ const forks = new Map<string, { type: AgentType; file: string }>();
672
+ const overrides = new Map<
673
+ string,
674
+ { override: AgentSettingsOverride; file: string }
675
+ >();
676
+ const forkNames = new Set<string>();
677
+ const declareBlocked = (name: string) => {
678
+ blocked.add(name);
679
+ };
680
+ for (const file of files) {
681
+ const filePath = join(directory, file);
682
+ const overrideName = overrideBaseName(file);
683
+ if (overrideName !== undefined) {
684
+ if (!NAME.test(overrideName)) {
685
+ declareBlocked(overrideName);
686
+ this.diagnostics.push(`${filePath}: Invalid agent name in override filename`);
687
+ continue;
688
+ }
349
689
  let content = "";
350
690
  try {
351
691
  if (!lstatSync(filePath).isFile())
352
692
  throw new Error(
353
- "Agent definition must be a regular file, not a symlink",
693
+ "Agent settings override must be a regular file, not a symlink",
354
694
  );
355
695
  content = readFileSync(filePath, "utf8");
356
- const type = parseAgentType(content, filePath);
357
- if (seenNames.has(type.name)) {
358
- blocked.add(type.name);
696
+ const override = parseAgentSettings(content, filePath, overrideName);
697
+ const key = override.name ?? overrideName;
698
+ if (forkNames.has(key)) {
699
+ declareBlocked(key);
700
+ this.diagnostics.push(
701
+ `${filePath}: Use either ${key}.md (full fork) or ${key}.yml (settings override), not both`,
702
+ );
703
+ continue;
704
+ }
705
+ if (overrides.has(key)) {
706
+ declareBlocked(key);
359
707
  this.diagnostics.push(
360
- `${filePath}: Duplicate agent name in ${source} layer: ${type.name}`,
708
+ `${filePath}: Duplicate agent override in ${scope} layer: ${key}`,
361
709
  );
362
710
  continue;
363
711
  }
364
- seenNames.add(type.name);
365
- this.types.set(type.name, { ...type, source });
712
+ overrides.set(key, { override, file });
366
713
  } catch (error) {
367
- blocked.add(file.slice(0, -3));
368
- // Extract declared names even if another field or duplicate key is malformed.
714
+ declareBlocked(overrideName);
369
715
  try {
370
- const doc = parseDocument(frontmatter(content).yaml);
716
+ const doc = parseDocument(content);
371
717
  if (isMap(doc.contents))
372
718
  for (const pair of doc.contents.items) {
373
719
  if (
@@ -376,15 +722,113 @@ export class ConfigStore {
376
722
  isScalar(pair.value) &&
377
723
  typeof pair.value.value === "string"
378
724
  )
379
- blocked.add(pair.value.value);
725
+ declareBlocked(pair.value.value);
380
726
  }
381
727
  } catch {
382
728
  /* Filename still provides a fail-closed tombstone. */
383
729
  }
384
730
  this.diagnostics.push(`${filePath}: ${String(error)}`);
385
731
  }
732
+ continue;
386
733
  }
387
- for (const name of blocked) this.types.delete(name);
734
+ let content = "";
735
+ try {
736
+ if (!lstatSync(filePath).isFile())
737
+ throw new Error(
738
+ "Agent definition must be a regular file, not a symlink",
739
+ );
740
+ content = readFileSync(filePath, "utf8");
741
+ const type = parseAgentType(content, filePath);
742
+ if (overrides.has(type.name)) {
743
+ declareBlocked(type.name);
744
+ this.diagnostics.push(
745
+ `${filePath}: Use either ${type.name}.md (full fork) or ${type.name}.yml (settings override), not both`,
746
+ );
747
+ continue;
748
+ }
749
+ if (forkNames.has(type.name)) {
750
+ declareBlocked(type.name);
751
+ this.diagnostics.push(
752
+ `${filePath}: Duplicate agent name in ${scope} layer: ${type.name}`,
753
+ );
754
+ continue;
755
+ }
756
+ forkNames.add(type.name);
757
+ forks.set(type.name, { type, file });
758
+ } catch (error) {
759
+ declareBlocked(file.slice(0, -3));
760
+ try {
761
+ const doc = parseDocument(frontmatter(content).yaml);
762
+ if (isMap(doc.contents))
763
+ for (const pair of doc.contents.items) {
764
+ if (
765
+ isScalar(pair.key) &&
766
+ pair.key.value === "name" &&
767
+ isScalar(pair.value) &&
768
+ typeof pair.value.value === "string"
769
+ )
770
+ declareBlocked(pair.value.value);
771
+ }
772
+ } catch {
773
+ /* Filename still provides a fail-closed tombstone. */
774
+ }
775
+ this.diagnostics.push(`${filePath}: ${String(error)}`);
776
+ }
777
+ }
778
+ for (const name of [...forks.keys()].filter((name) => overrides.has(name))) {
779
+ declareBlocked(name);
780
+ this.diagnostics.push(
781
+ `${join(directory, forks.get(name)!.file)} and ${join(directory, overrides.get(name)!.file)}: ` +
782
+ `Use either ${name}.md (full fork) or ${name}.yml (settings override), not both`,
783
+ );
784
+ }
785
+ for (const [name, { type, file }] of forks) {
786
+ if (blocked.has(name)) continue;
787
+ const filePath = join(directory, file);
788
+ const base = this.types.get(name);
789
+ const fork: AgentType = {
790
+ ...type,
791
+ source: scope,
792
+ filePath,
793
+ customization: { kind: "fork", scope, filePath },
794
+ baseSource: base?.source,
795
+ baseFilePath: base?.filePath,
796
+ };
797
+ this.bases.set(name, base ? structuredClone(base) : structuredClone(fork));
798
+ this.types.set(name, fork);
799
+ }
800
+ for (const [name, { override, file }] of overrides) {
801
+ if (blocked.has(name)) continue;
802
+ const filePath = join(directory, file);
803
+ const base = this.types.get(name);
804
+ if (!base) {
805
+ declareBlocked(name);
806
+ this.diagnostics.push(
807
+ `${filePath}: Settings override has no base agent named ${JSON.stringify(name)}; ` +
808
+ `create ${name}.md first or remove the override`,
809
+ );
810
+ continue;
811
+ }
812
+ try {
813
+ const merged = mergeAgentSettings(base, { ...override, name });
814
+ this.bases.set(name, structuredClone(base));
815
+ this.types.set(name, {
816
+ ...merged,
817
+ name,
818
+ source: scope,
819
+ filePath,
820
+ customization: { kind: "override", scope, filePath },
821
+ baseSource: base.source,
822
+ baseFilePath: base.filePath,
823
+ });
824
+ } catch (error) {
825
+ declareBlocked(name);
826
+ this.diagnostics.push(`${filePath}: ${String(error)}`);
827
+ }
828
+ }
829
+ for (const name of blocked) {
830
+ this.types.delete(name);
831
+ this.bases.delete(name);
388
832
  }
389
833
  }
390
834
 
@@ -442,50 +886,60 @@ export class ConfigStore {
442
886
  ];
443
887
  }
444
888
 
889
+ /** Base definition under the top customization, for diffing and read-only display. */
890
+ getBase(name: string): AgentType | undefined {
891
+ const base = this.bases.get(name);
892
+ return base ? structuredClone(base) : undefined;
893
+ }
894
+
445
895
  private canPreserveDestination(
446
896
  name: string,
447
897
  scope: AgentScope,
448
- original?: SaveOrigin,
898
+ original: SaveOrigin | undefined,
899
+ kind: AgentCustomizationKind,
449
900
  ): boolean {
450
- return (
451
- original?.name === name &&
452
- original.source === scope &&
453
- typeof original.filePath === "string" &&
454
- dirname(resolve(original.filePath)) ===
901
+ if (
902
+ original?.name !== name ||
903
+ original.source !== scope ||
904
+ typeof original.filePath !== "string" ||
905
+ dirname(resolve(original.filePath)) !==
455
906
  this.preferredScopeDirectory(scope)
907
+ )
908
+ return false;
909
+ const preserved = resolve(original.filePath);
910
+ if (kind === "fork") return preserved.endsWith(".md");
911
+ return AGENT_OVERRIDE_EXTENSIONS.some((extension) =>
912
+ preserved.endsWith(extension),
456
913
  );
457
914
  }
458
915
 
459
- destination(name: string, scope: AgentScope, original?: SaveOrigin): string {
916
+ destination(
917
+ name: string,
918
+ scope: AgentScope,
919
+ original?: SaveOrigin,
920
+ kind: AgentCustomizationKind = "fork",
921
+ ): string {
460
922
  if (!NAME.test(name)) throw new Error("Unsafe agent name");
461
923
  const directory = this.preferredScopeDirectory(scope);
462
924
  if (
463
- this.canPreserveDestination(name, scope, original) &&
925
+ this.canPreserveDestination(name, scope, original, kind) &&
464
926
  typeof original?.filePath === "string"
465
927
  ) {
466
- return validatePreservedDestination(original.filePath, directory);
928
+ return validatePreservedDestination(
929
+ original.filePath,
930
+ directory,
931
+ kind === "fork" ? [".md"] : [...AGENT_OVERRIDE_EXTENSIONS],
932
+ );
467
933
  }
468
- return resolve(directory, `${name}.md`);
934
+ return resolve(directory, `${name}${kind === "fork" ? ".md" : ".yml"}`);
469
935
  }
470
936
 
471
- save(type: AgentType, scope: AgentScope, original?: SaveOrigin): AgentType {
472
- const content = serializeAgentType(type);
473
- const validated = parseAgentType(content);
474
- const filePath = this.destination(validated.name, scope, original);
937
+ private writeContent(filePath: string, name: string, content: string): void {
475
938
  const directory = dirname(filePath);
476
- // Reject redirected destination directories and files before writing.
477
- for (const path of [
478
- ...this.destinationBasePaths(scope, directory),
479
- filePath,
480
- ]) {
481
- const stat = assertNotSymlinkPath(path);
482
- if (path === filePath && stat && !stat.isFile())
483
- throw new Error(`Unsafe agent destination: ${filePath}`);
484
- }
485
939
  mkdirSync(directory, { recursive: true });
486
940
  const temporary = join(
487
941
  dirname(filePath),
488
- `.${validated.name}.${randomUUID()}.tmp`,
942
+ `.${name}.${randomUUID()}.tmp`,
489
943
  );
490
944
  try {
491
945
  writeFileSync(temporary, content, { flag: "wx", mode: 0o600 });
@@ -493,7 +947,82 @@ export class ConfigStore {
493
947
  } finally {
494
948
  if (lstatIfPresent(temporary)) unlinkSync(temporary);
495
949
  }
950
+ }
951
+
952
+ private assertWritableDestination(filePath: string, scope: AgentScope): void {
953
+ const directory = dirname(filePath);
954
+ // Reject redirected destination directories and files before writing.
955
+ for (const path of [
956
+ ...this.destinationBasePaths(scope, directory),
957
+ filePath,
958
+ ]) {
959
+ const stat = assertNotSymlinkPath(path);
960
+ if (path === filePath && stat && !stat.isFile())
961
+ throw new Error(`Unsafe agent destination: ${filePath}`);
962
+ }
963
+ }
964
+
965
+ /** Save a full `<name>.md` fork. Replaces the base definition entirely. */
966
+ save(type: AgentType, scope: AgentScope, original?: SaveOrigin): AgentType {
967
+ const content = serializeAgentType(type);
968
+ const validated = parseAgentType(content);
969
+ const filePath = this.destination(validated.name, scope, original, "fork");
970
+ this.assertWritableDestination(filePath, scope);
971
+ this.writeContent(filePath, validated.name, content);
972
+ this.reload();
973
+ return this.get(validated.name);
974
+ }
975
+
976
+ /**
977
+ * Save a settings-only `<name>.yml` override merged on top of the base.
978
+ * The prompt body always comes from the base; only changed settings are
979
+ * written so untouched fields keep tracking bundled updates.
980
+ */
981
+ saveOverride(
982
+ name: string,
983
+ draft: AgentType,
984
+ scope: AgentScope,
985
+ original?: SaveOrigin,
986
+ ): AgentType {
987
+ if (!NAME.test(name)) throw new Error("Unsafe agent name");
988
+ if (draft.name !== name)
989
+ throw new Error("Settings overrides cannot rename the agent; fork it instead");
990
+ const base = this.getBase(name) ?? (() => {
991
+ try {
992
+ return this.get(name);
993
+ } catch {
994
+ return undefined;
995
+ }
996
+ })();
997
+ if (!base) throw new Error(`Settings override has no base agent named ${JSON.stringify(name)}`);
998
+ if (base.name !== name)
999
+ throw new Error(`Settings override has no base agent named ${JSON.stringify(name)}`);
1000
+ const override = diffAgentSettings(base, { ...draft, name });
1001
+ const content = serializeAgentSettings(override);
1002
+ parseAgentSettings(content, undefined, name);
1003
+ const filePath = this.destination(name, scope, original, "override");
1004
+ this.assertWritableDestination(filePath, scope);
1005
+ this.writeContent(filePath, name, content);
1006
+ this.reload();
1007
+ return this.get(name);
1008
+ }
1009
+
1010
+ /** Remove a user/project customization so the base definition shows through. */
1011
+ removeCustomization(name: string, scope: AgentScope): void {
1012
+ const current = this.types.get(name);
1013
+ const customization = current?.customization;
1014
+ if (!customization || customization.scope !== scope)
1015
+ throw new Error(`No ${scope} customization found for ${JSON.stringify(name)}`);
1016
+ const resolved = resolve(customization.filePath);
1017
+ if (
1018
+ dirname(resolved) !== this.preferredScopeDirectory(scope) ||
1019
+ (!resolved.endsWith(".md") &&
1020
+ !AGENT_OVERRIDE_EXTENSIONS.some((extension) => resolved.endsWith(extension)))
1021
+ )
1022
+ throw new Error(`Unsafe agent destination: ${resolved}`);
1023
+ const stat = lstatIfPresent(resolved);
1024
+ if (!stat?.isFile()) throw new Error(`Unsafe agent destination: ${resolved}`);
1025
+ unlinkSync(resolved);
496
1026
  this.reload();
497
- return { ...validated, filePath, source: scope };
498
1027
  }
499
1028
  }