pi-better-subagents 0.23.3 → 0.25.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/README.md CHANGED
@@ -12,6 +12,7 @@ Use `pi-better-subagents` when you want Pi to launch independent agent work with
12
12
 
13
13
  ## Core Features
14
14
  - Non-blocking subagent launches, with an optional role and named-agent catalog (`docs/agent-catalog.md`, `docs/agent-catalog-lifecycle.md`).
15
+ - Completed-subagent continuation: `subagent_resume` continues a saved single or batch conversation under a new attempt id. Retention is optional cleanup protection: `retain_session` pins artifacts, and `subagent_release` removes that protection without invalidating history that still exists. See [continuing a completed subagent](docs/usage.md#continuing-a-completed-subagent).
15
16
  - Typed foreground `subagent_spawn_batch` launch receipts for native Pi codemode (Pi 0.99.1+), preserving direct tool calls, per-run callbacks, and batch capacity/catalog guarantees. See [codemode batch launches](docs/usage.md#codemode-batch-launches).
16
17
  - Opt-in OS task sandboxing on macOS and Linux.
17
18
  - Explicit tool allowlists for child sessions.
package/agent-commands.ts CHANGED
@@ -31,6 +31,8 @@ import {
31
31
  loadCatalog,
32
32
  projectCatalogPaths,
33
33
  refreshCatalog,
34
+ resetRuntimeToBundled,
35
+ resetUserDefinition,
34
36
  saveDefinition,
35
37
  userCatalogPaths,
36
38
  type CatalogSnapshot,
@@ -758,6 +760,37 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
758
760
  }
759
761
  return { ok: saved.ok, message: saved.ok ? `Defaults saved (${saved.scope}): ${id}.` : saved.diagnostics.map((item) => item.message).join(" ") };
760
762
  },
763
+ resetToBundled(entry) {
764
+ const source = entry.winningSource;
765
+ if (!source) return { ok: false, message: "The definition source is unavailable. Reopen its settings." };
766
+ const reset = resetRuntimeToBundled({ ...location(host, deps), id: entry.id, expectedPath: source.path, expectedDigest: source.contentDigest });
767
+ if (reset.ok) {
768
+ commandResult.wrote = true;
769
+ commandResult.path = reset.path;
770
+ commandResult.scope = "user";
771
+ try { deps.sessionSettings!.reset(entry.id); }
772
+ catch (error) {
773
+ return { ok: false, message: `Saved defaults reset for ${entry.id}, but current-session overrides remain active: ${error instanceof Error ? error.message : String(error)}. Retry Reset to bundled to clear them.` };
774
+ }
775
+ }
776
+ return { ok: reset.ok, message: reset.ok
777
+ ? `Bundled model/effort restored: ${entry.id}. Role instructions unchanged.`
778
+ : reset.diagnostics.map(item => item.message).join(" ") };
779
+ },
780
+ resetDefinition(entry) {
781
+ if (entry.identity.scope === "bundled") return { ok: true, message: `Already using bundled instructions: ${entry.id}. Model/effort unchanged.` };
782
+ const source = entry.winningSource;
783
+ if (!source) return { ok: false, message: "The definition source is unavailable. Reopen its settings." };
784
+ const reset = resetUserDefinition({ ...location(host, deps), id: entry.id, expectedPath: source.path, expectedDigest: source.contentDigest });
785
+ if (reset.ok) {
786
+ commandResult.wrote = true;
787
+ commandResult.path = reset.path;
788
+ commandResult.scope = "user";
789
+ }
790
+ return { ok: reset.ok, message: reset.ok
791
+ ? `Bundled instructions restored: ${entry.id}. Model/effort kept. Backup: ${reset.backupPath}.`
792
+ : reset.diagnostics.map(item => item.message).join(" ") };
793
+ },
761
794
  } : undefined, () => viewportHeight), {
762
795
  overlay: true,
763
796
  overlayOptions: {
@@ -130,6 +130,7 @@ export interface OperationView {
130
130
  winningSource?: { scope: string; path: string; contentDigest: string; id: string };
131
131
  shadowed: { scope: string; path: string; contentDigest: string; reason: string }[];
132
132
  instructionMode?: string;
133
+ preferenceSources?: Partial<Record<"model" | "effort", { scope: "user" | "project"; path: string; bundled?: boolean }>>;
133
134
  instructions?: string;
134
135
  fields?: { model: OperationField; effort: OperationField; tier: OperationField };
135
136
  /** The definition's own default model and effort (role default, or the agent's override or inherited value). Null when neither is set. */
@@ -332,6 +333,11 @@ export function presentCatalogEntry(snapshot: CatalogSnapshot, id: string, enric
332
333
  winningSource: inspection.winningSource,
333
334
  shadowed: inspection.shadowed.map((item) => ({ ...item })),
334
335
  instructionMode: inspection.instructionMode,
336
+ preferenceSources: Object.fromEntries((["model", "effort"] as const).flatMap(key => {
337
+ const owner = inspection.kind === "agent" && fields?.[key].inherited ? inspection.roleId : id;
338
+ const source = owner ? snapshot.preferenceSources?.[owner]?.[key] : undefined;
339
+ return source ? [[key, source]] : [];
340
+ })),
335
341
  instructions: inspection.instructions,
336
342
  fields,
337
343
  defaults: definitionDefaults(fields),
@@ -1,6 +1,9 @@
1
1
  /** Branch-local catalog preferences. Null removes a definition's own value. */
2
+ import { mkdirSync } from "node:fs";
3
+ import { dirname } from "node:path";
2
4
  import { EFFORT_LEVELS, type CatalogDefinition, type PortablePreferences, type ThinkingLevel } from "./catalog-schema.ts";
3
- import { contentDigest, saveDefinition, type CatalogSnapshot, type LoadCatalogInput, type SaveResult } from "./catalog-store.ts";
5
+ import { contentDigest, projectCatalogPaths, userCatalogPaths, type CatalogSnapshot, type LoadCatalogInput, type SaveResult } from "./catalog-store.ts";
6
+ import { writeCatalogPreferences } from "./catalog-preferences.ts";
4
7
 
5
8
  export const AGENT_SESSION_SETTINGS_ENTRY = "pi-better-subagents-agent-settings";
6
9
  export type AgentSettingKey = "model" | "effort";
@@ -12,11 +15,16 @@ export interface AgentSessionSettings {
12
15
  restore(ctx: AgentSessionContext): void;
13
16
  snapshot(): AgentSessionOverrides;
14
17
  change(id: string, key: AgentSettingKey, value: string | null): void;
18
+ reset(id: string): void;
15
19
  clear(): void;
16
20
  }
17
21
 
22
+ function validId(id: unknown): id is string {
23
+ return typeof id === "string" && /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id);
24
+ }
25
+
18
26
  function valid(id: unknown, key: unknown, value: unknown): boolean {
19
- return typeof id === "string" && /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(id) &&
27
+ return validId(id) &&
20
28
  (key === "model" || key === "effort") && (value === null || typeof value === "string" &&
21
29
  (key === "model" ? /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(value)
22
30
  : (EFFORT_LEVELS as readonly string[]).includes(value)));
@@ -28,6 +36,11 @@ export function createAgentSessionSettings(pi: { appendEntry(customType: string,
28
36
  const apply = (id: string, key: AgentSettingKey, value: string | null) => {
29
37
  overrides = Object.freeze({ ...overrides, [id]: Object.freeze({ ...overrides[id], [key]: value }) });
30
38
  };
39
+ const reset = (id: string) => {
40
+ const next = { ...overrides };
41
+ delete next[id];
42
+ overrides = Object.freeze(next);
43
+ };
31
44
  return {
32
45
  snapshot: () => overrides,
33
46
  clear() { overrides = Object.freeze({}); },
@@ -38,8 +51,12 @@ export function createAgentSessionSettings(pi: { appendEntry(customType: string,
38
51
  for (const entry of branch) {
39
52
  if (!entry || entry.type !== "custom" || entry.customType !== AGENT_SESSION_SETTINGS_ENTRY) continue;
40
53
  const data = entry.data;
41
- if (data?.version !== 1 || !valid(data.id, data.key, data.value)) continue;
42
- apply(data.id, data.key, data.value);
54
+ if (data?.version !== 1) continue;
55
+ if (data.kind === "reset") {
56
+ if (validId(data.id)) reset(data.id);
57
+ } else if (valid(data.id, data.key, data.value)) {
58
+ apply(data.id, data.key, data.value);
59
+ }
43
60
  }
44
61
  },
45
62
  change(id, key, value) {
@@ -48,13 +65,19 @@ export function createAgentSessionSettings(pi: { appendEntry(customType: string,
48
65
  pi.appendEntry(AGENT_SESSION_SETTINGS_ENTRY, { version: 1, id, key, value });
49
66
  apply(id, key, value);
50
67
  },
68
+ reset(id) {
69
+ if (!validId(id)) throw new Error("Choose a valid catalog id. Nothing changed.");
70
+ // Append first, just like changes: failed persistence leaves the session intact.
71
+ pi.appendEntry(AGENT_SESSION_SETTINGS_ENTRY, { version: 1, kind: "reset", id });
72
+ reset(id);
73
+ },
51
74
  };
52
75
  }
53
76
 
54
77
  /** Copy only preferences; never repair or bypass a catalog validation failure. */
55
- export function sessionPreferences(definition: CatalogDefinition, settings: AgentSessionOverrides = {}): PortablePreferences {
78
+ export function sessionPreferences(definition: CatalogDefinition, settings: AgentSessionOverrides = {}, saved: AgentSessionOverrides = {}): PortablePreferences {
56
79
  const own = { ...(definition.kind === "role" ? definition.defaults : definition.overrides) };
57
- const patch = settings[definition.id];
80
+ const patch = { ...saved[definition.id], ...settings[definition.id] };
58
81
  for (const key of ["model", "effort"] as const) {
59
82
  if (!patch || !Object.hasOwn(patch, key)) continue;
60
83
  if (patch[key] === null) delete own[key];
@@ -74,16 +97,22 @@ export function withAgentSessionSettings(snapshot: CatalogSnapshot, settings?: A
74
97
  return Object.freeze({ ...snapshot, digest, revision: digest, sessionSettings: Object.freeze(ordered) });
75
98
  }
76
99
 
77
- /** Save selected own preferences only. Never flatten inherited role settings. */
100
+ /** Save selected preference edits without copying or rewriting Markdown definitions. */
78
101
  export function saveAgentSessionDefaults(snapshot: CatalogSnapshot, id: string, settings: AgentSessionOverrides, location: LoadCatalogInput): SaveResult {
79
102
  const entry = snapshot.roles.get(id) ?? snapshot.agents.get(id);
80
103
  if (!entry?.definition || !entry.structurallyValid || entry.duplicate) {
81
104
  return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: `Cannot save ${id}: repair the catalog definition first. Session edits are unchanged.`, blocking: true, structural: false }] };
82
105
  }
83
- const definition = structuredClone(entry.definition);
84
- const preferences = sessionPreferences(definition, settings);
85
- if (definition.kind === "role") definition.defaults = preferences;
86
- else definition.overrides = preferences;
87
- // The store validates and writes atomically, including trust and symlink checks.
88
- return saveDefinition({ ...location, definition, scope: entry.scope === "project" ? "project" : "user", replace: entry.scope !== "bundled" });
106
+ const scope = entry.scope === "project" || Object.values(snapshot.preferenceSources?.[id] ?? {}).some(source => source.scope === "project") ? "project" : "user";
107
+ if (scope === "project" && !location.projectTrusted) {
108
+ return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: "Project catalog preferences require a trusted project. Nothing changed.", blocking: true, structural: false }] };
109
+ }
110
+ const root = scope === "project" ? projectCatalogPaths(location.cwd, location.projectConfigDirName).root : userCatalogPaths(location.userRoot).root;
111
+ try {
112
+ mkdirSync(dirname(root), { recursive: true, mode: 0o700 });
113
+ const saved = writeCatalogPreferences(root, id, current => ({ ...current, ...settings[id] }));
114
+ return { ok: true, path: saved.path, scope, diagnostics: [] };
115
+ } catch (error) {
116
+ return { ok: false, diagnostics: [{ severity: "error", code: "agents-save", message: error instanceof Error ? error.message : String(error), blocking: true, structural: false }] };
117
+ }
89
118
  }
@@ -0,0 +1,139 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { join, resolve } from "node:path";
5
+ import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
6
+
7
+ export type CatalogPreference = Readonly<{ bundled?: true; model?: string | null; effort?: ThinkingLevel | null }>;
8
+ export type CatalogPreferences = Readonly<Record<string, CatalogPreference>>;
9
+ const ID = /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
10
+ const MODEL = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/;
11
+
12
+ function object(value: unknown, label: string): Record<string, unknown> {
13
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be a JSON object.`);
14
+ return value as Record<string, unknown>;
15
+ }
16
+
17
+ function preferences(id: string, value: unknown): CatalogPreference {
18
+ if (typeof id !== "string" || !ID.test(id)) throw new Error(`Invalid catalog id ${JSON.stringify(id)}.`);
19
+ const record = object(value, `Preferences for ${id}`);
20
+ for (const [key, item] of Object.entries(record)) {
21
+ if (key !== "bundled" && key !== "model" && key !== "effort") throw new Error(`Unknown preference ${key} for ${id}.`);
22
+ if (key === "bundled" ? item !== true : item !== null && (typeof item !== "string" || (key === "model" ? !MODEL.test(item)
23
+ : !(THINKING_LEVELS as readonly string[]).includes(item)))) {
24
+ throw new Error(`Invalid ${key} preference for ${id}: ${JSON.stringify(item)}.`);
25
+ }
26
+ }
27
+ return Object.freeze({
28
+ ...(Object.hasOwn(record, "bundled") ? { bundled: true as const } : {}),
29
+ ...(Object.hasOwn(record, "model") ? { model: record.model as string | null } : {}),
30
+ ...(Object.hasOwn(record, "effort") ? { effort: record.effort as ThinkingLevel | null } : {}),
31
+ });
32
+ }
33
+
34
+ function snapshot(values: CatalogPreferences): { settings: CatalogPreferences; digest: string } {
35
+ const settings = Object.freeze(Object.fromEntries(Object.keys(values).sort().map(id => [id, values[id]])));
36
+ return { settings, digest: createHash("sha256").update(JSON.stringify(settings)).digest("hex") };
37
+ }
38
+
39
+ function stat(path: string) {
40
+ try { return lstatSync(path); }
41
+ catch (error) {
42
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
43
+ throw error;
44
+ }
45
+ }
46
+
47
+ function checkRoot(root: string): boolean {
48
+ const info = stat(root);
49
+ if (!info) return false;
50
+ if (info.isSymbolicLink()) throw new Error(`Refusing symlink catalog directory ${root}.`);
51
+ if (!info.isDirectory()) throw new Error(`Catalog root ${root} must be a directory.`);
52
+ return true;
53
+ }
54
+
55
+ function checkFile(path: string): boolean {
56
+ const info = stat(path);
57
+ if (!info) return false;
58
+ if (info.isSymbolicLink()) throw new Error(`Refusing symlink catalog settings file ${path}.`);
59
+ if (!info.isFile()) throw new Error(`Catalog settings ${path} must be a regular file.`);
60
+ return true;
61
+ }
62
+
63
+ export function readCatalogPreferences(root: string): { settings: CatalogPreferences; digest: string } {
64
+ root = resolve(root);
65
+ const path = join(root, "settings.json");
66
+ try {
67
+ if (!checkRoot(root) || !checkFile(path)) return snapshot({});
68
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
69
+ let data: Record<string, unknown>;
70
+ try {
71
+ if (!fstatSync(fd).isFile()) throw new Error("Settings must be a regular file.");
72
+ data = object(JSON.parse(readFileSync(fd, "utf8")), "Catalog settings");
73
+ } finally { closeSync(fd); }
74
+ if (data.version !== 1 || !Object.hasOwn(data, "defaults") ||
75
+ Object.keys(data).some(key => key !== "version" && key !== "defaults")) {
76
+ throw new Error("Expected only version: 1 and defaults in catalog settings.");
77
+ }
78
+ const settings = Object.fromEntries(Object.entries(object(data.defaults, "Catalog defaults"))
79
+ .map(([id, value]) => [id, preferences(id, value)]));
80
+ return snapshot(settings);
81
+ } catch (error) {
82
+ throw new Error(`Cannot read catalog preferences at ${path}: ${(error as Error).message}`, { cause: error });
83
+ }
84
+ }
85
+
86
+ function acquire(path: string): () => void {
87
+ // Read-only catalog consumers (including the portable CLI) need no lock adapter.
88
+ const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
89
+ lockSync(path: string, options: { realpath: boolean }): () => void;
90
+ };
91
+ for (let attempt = 0; attempt < 100; attempt++) {
92
+ try { return lockfile.lockSync(path, { realpath: false }); }
93
+ catch (error) {
94
+ if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === 99) throw error;
95
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
96
+ }
97
+ }
98
+ throw new Error(`Cannot lock catalog settings at ${path}.`);
99
+ }
100
+
101
+ /** Replace only this id's own preferences; null explicitly clears a definition value. */
102
+ export function writeCatalogPreferences(root: string, id: string, value: CatalogPreference | ((current: CatalogPreference) => CatalogPreference)): { path: string; settings: CatalogPreferences; digest: string } {
103
+ // Validate literal input before touching disk; updater callbacks run under the lock.
104
+ const selected = typeof value === "function" ? (preferences(id, {}), undefined) : preferences(id, value);
105
+ root = resolve(root);
106
+ const path = join(root, "settings.json");
107
+ let release: (() => void) | undefined;
108
+ let pending: string | undefined;
109
+ try {
110
+ if (!checkRoot(root)) {
111
+ // Do not create the caller's user/project configuration directories.
112
+ try { mkdirSync(root, { mode: 0o700 }); }
113
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
114
+ checkRoot(root);
115
+ }
116
+ checkFile(path);
117
+ release = acquire(path);
118
+ const settings = { ...readCatalogPreferences(root).settings };
119
+ const next = selected ?? preferences(id, (value as (current: CatalogPreference) => CatalogPreference)(settings[id] ?? Object.freeze({})));
120
+ if (Object.keys(next).length) settings[id] = next;
121
+ else delete settings[id];
122
+ const result = snapshot(settings);
123
+ pending = join(root, `.settings.json.${randomUUID()}.tmp`);
124
+ const fd = openSync(pending, "wx", 0o600);
125
+ try {
126
+ writeFileSync(fd, `${JSON.stringify({ version: 1, defaults: result.settings }, null, 2)}\n`);
127
+ fsyncSync(fd);
128
+ } finally { closeSync(fd); }
129
+ checkRoot(root);
130
+ checkFile(path);
131
+ renameSync(pending, path);
132
+ return { path, ...result };
133
+ } catch (error) {
134
+ throw new Error(`Cannot save catalog preferences at ${path}: ${(error as Error).message}`, { cause: error });
135
+ } finally {
136
+ try { if (pending) rmSync(pending, { force: true }); }
137
+ finally { release?.(); }
138
+ }
139
+ }
@@ -224,7 +224,7 @@ function resolveRole(snapshot: CatalogSnapshot, roleId: string): Resolution {
224
224
  return blockedEntry(snapshot, entry, entry.diagnostics);
225
225
  }
226
226
  const definition = entry.definition;
227
- const preferences = sessionPreferences(definition, snapshot.sessionSettings);
227
+ const preferences = sessionPreferences(definition, snapshot.sessionSettings, snapshot.savedSettings);
228
228
  const launchable = entry.schemaLaunchable;
229
229
  const diagnostics = launchable
230
230
  ? [...entry.diagnostics]
@@ -334,8 +334,8 @@ function baseEffective(
334
334
  } | undefined,
335
335
  ): EffectiveDefinition {
336
336
  const mode = agent.instructionMode;
337
- const overrides = sessionPreferences(agent, snapshot.sessionSettings);
338
- const defaults = inheritance ? sessionPreferences(inheritance.role, snapshot.sessionSettings) : {};
337
+ const overrides = sessionPreferences(agent, snapshot.sessionSettings, snapshot.savedSettings);
338
+ const defaults = inheritance ? sessionPreferences(inheritance.role, snapshot.sessionSettings, snapshot.savedSettings) : {};
339
339
  const instructions = inheritance
340
340
  ? combineInstructions(inheritance.role.body, agent.body, mode)
341
341
  : agent.body;
package/catalog-store.ts CHANGED
@@ -29,6 +29,7 @@ import { homedir } from "node:os";
29
29
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
30
30
  import { fileURLToPath } from "node:url";
31
31
  import type { AgentSessionOverrides } from "./agent-session-settings.ts";
32
+ import { readCatalogPreferences, writeCatalogPreferences } from "./catalog-preferences.ts";
32
33
  import {
33
34
  CATALOG_SCHEMA_VERSION,
34
35
  DiagnosticCodes,
@@ -40,6 +41,7 @@ import {
40
41
  type CatalogScope,
41
42
  type Diagnostic,
42
43
  type ParseResult,
44
+ type ThinkingLevel,
43
45
  } from "./catalog-schema.ts";
44
46
 
45
47
  export type { CatalogScope, CatalogKind, CatalogDefinition, Diagnostic, ParseResult };
@@ -111,6 +113,8 @@ export interface CatalogSnapshot {
111
113
  diagnostics: readonly Diagnostic[];
112
114
  /** Immutable, branch-local preferences; never written by loadCatalog. */
113
115
  sessionSettings?: AgentSessionOverrides;
116
+ savedSettings?: AgentSessionOverrides;
117
+ preferenceSources?: Readonly<Record<string, Readonly<Partial<Record<"model" | "effort", { scope: "user" | "project"; path: string; bundled?: boolean }>>>>>;
114
118
  }
115
119
 
116
120
  export interface SaveResult {
@@ -226,7 +230,65 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
226
230
  }
227
231
 
228
232
  const { entries, blocked } = selectIdentities(groups, diagnostics);
229
- return finishSnapshot(entries, blocked, diagnostics, loadedAt);
233
+ const savedSettings: Record<string, { model?: string | null; effort?: ThinkingLevel | null }> = {};
234
+ const preferenceSources: Record<string, Partial<Record<"model" | "effort", { scope: "user" | "project"; path: string; bundled?: boolean }>>> = {};
235
+ const preferenceDigests: string[] = [];
236
+ const scopes = [
237
+ { scope: "user" as const, root: user.root },
238
+ ...(input.projectTrusted ? [{ scope: "project" as const, root: projectCatalogPaths(input.cwd, configDirName).root }] : []),
239
+ ];
240
+ for (const { scope, root } of scopes) {
241
+ try {
242
+ const preferences = readCatalogPreferences(root);
243
+ preferenceDigests.push(preferences.digest);
244
+ for (const entry of entries) {
245
+ if (scope === "user" && entry.scope === "project") continue;
246
+ const own = preferences.settings[entry.id];
247
+ if (!own) continue;
248
+ const resolved: { model?: string | null; effort?: ThinkingLevel | null } = {};
249
+ if (own.bundled) {
250
+ const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
251
+ const fallback = fallbacks.length === 1 ? fallbacks[0] : undefined;
252
+ const raw = fallback ? readFileSync(fallback.path, "utf8") : undefined;
253
+ const parsed = raw === undefined ? undefined : parseDefinition(raw, fallback!.path);
254
+ if (!fallback || !parsed?.ok || parsed.definition?.id !== entry.id || parsed.diagnostics.some(item => item.blocking)
255
+ || contentDigest(raw!) !== fallback.contentDigest) {
256
+ const failure = diagnostic("catalog-preferences", `Cannot inherit bundled runtime defaults for ${entry.id}: a single valid bundled definition is required.`, {
257
+ scope, path: join(root, "settings.json"), id: entry.id, blocking: true, structural: false,
258
+ });
259
+ entry.diagnostics = [...entry.diagnostics, failure];
260
+ entry.schemaLaunchable = false;
261
+ diagnostics.push(failure);
262
+ continue;
263
+ }
264
+ const bundled = parsed.definition.kind === "role" ? parsed.definition.defaults : parsed.definition.overrides;
265
+ resolved.model = bundled.model ?? null;
266
+ resolved.effort = bundled.effort ?? null;
267
+ }
268
+ for (const key of ["model", "effort"] as const) {
269
+ if (Object.hasOwn(own, key)) Object.assign(resolved, { [key]: own[key] });
270
+ }
271
+ savedSettings[entry.id] = { ...savedSettings[entry.id], ...resolved };
272
+ const sources = preferenceSources[entry.id] ??= {};
273
+ for (const key of ["model", "effort"] as const) {
274
+ if (Object.hasOwn(resolved, key)) sources[key] = { scope, path: join(root, "settings.json"), ...(own.bundled && !Object.hasOwn(own, key) ? { bundled: true } : {}) };
275
+ }
276
+ }
277
+ } catch (error) {
278
+ const failure = diagnostic("catalog-preferences", error instanceof Error ? error.message : String(error), {
279
+ scope, path: join(root, "settings.json"), blocking: true, structural: false,
280
+ });
281
+ diagnostics.push(failure);
282
+ for (const entry of entries) {
283
+ if (scope === "user" && entry.scope === "project") continue;
284
+ entry.diagnostics = [...entry.diagnostics, failure];
285
+ entry.schemaLaunchable = false;
286
+ }
287
+ }
288
+ }
289
+ const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt);
290
+ const digest = contentDigest(JSON.stringify([snapshot.digest, preferenceDigests, savedSettings, preferenceSources]));
291
+ return deepFreeze({ ...snapshot, digest, revision: digest, savedSettings, preferenceSources });
230
292
  }
231
293
 
232
294
  export function refreshCatalog(input: LoadCatalogInput): CatalogSnapshot {
@@ -237,6 +299,130 @@ export function createDefinition(input: SaveDefinitionInput): SaveResult {
237
299
  return saveDefinition({ ...input, replace: input.replace ?? false });
238
300
  }
239
301
 
302
+ type ResetDefinitionInput = LoadCatalogInput & {
303
+ id: string;
304
+ expectedPath: string;
305
+ expectedDigest: string;
306
+ };
307
+
308
+ /** Archive one displayed user override, preserving its model and effort preferences. */
309
+ export function resetUserDefinition(input: ResetDefinitionInput): SaveResult & { backupPath?: string } {
310
+ return resetDefinition(input, false);
311
+ }
312
+
313
+ /** Restore bundled defaults, archiving a user definition and clearing only this id's user preferences. */
314
+ export function resetToBundled(input: ResetDefinitionInput): SaveResult & { backupPath?: string } {
315
+ return resetDefinition(input, true);
316
+ }
317
+
318
+ /** Restore bundled model and effort while keeping every Markdown definition intact. */
319
+ export function resetRuntimeToBundled(input: ResetDefinitionInput): SaveResult {
320
+ return resetDefinition(input, true, true);
321
+ }
322
+
323
+ function assertNoProjectPreferences(snapshot: CatalogSnapshot, id: string): void {
324
+ if (Object.values(snapshot.preferenceSources?.[id] ?? {}).some(source => source.scope === "project")) {
325
+ throw new Error("Project preferences are active for this id. Reset to bundled cannot clear project preferences. Nothing was archived.");
326
+ }
327
+ }
328
+
329
+ function resetDefinition(input: ResetDefinitionInput, clearPreferences: boolean, runtimeOnly = false): SaveResult & { backupPath?: string } {
330
+ try {
331
+ const snapshot = loadCatalog(input);
332
+ const entry = snapshot.roles.get(input.id) ?? snapshot.agents.get(input.id);
333
+ if (!entry || (entry.scope !== "user" && !(clearPreferences && entry.scope === "bundled")) || entry.duplicate || entry.paths.length !== 1) {
334
+ throw new Error(clearPreferences
335
+ ? "Only a single user or bundled definition can be reset. Project definitions are unchanged."
336
+ : "Only a single user override can be reset. Project and bundled definitions are unchanged.");
337
+ }
338
+ if (clearPreferences) assertNoProjectPreferences(snapshot, input.id);
339
+ if (entry.path !== input.expectedPath || entry.contentDigest !== input.expectedDigest) {
340
+ throw new Error("The user definition changed since this screen was opened. Reopen its settings before resetting.");
341
+ }
342
+ const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
343
+ if (fallbacks.length !== 1) throw new Error("Exactly one bundled definition must be available for this id. Nothing was changed.");
344
+ const fallback = fallbacks[0]!;
345
+ const bundledRoot = entry.kind === "role" ? input.bundledRoot ?? bundledRolesRoot() : input.bundledAgentsRoot;
346
+ if (!bundledRoot || lstatSync(bundledRoot).isSymbolicLink()) throw new Error("The bundled catalog is unavailable or symlinked.");
347
+ assertInside(bundledRoot, fallback.path);
348
+ assertNoSymlinkWalk(bundledRoot, fallback.path);
349
+ const bundledRaw = readFileSync(fallback.path, "utf8");
350
+ const bundled = parseDefinition(bundledRaw, fallback.path);
351
+ if (!bundled.ok || bundled.diagnostics.some(item => item.blocking) || bundled.definition?.id !== input.id || contentDigest(bundledRaw) !== fallback.contentDigest) {
352
+ throw new Error("The bundled definition is invalid. Nothing was changed.");
353
+ }
354
+ const root = userCatalogPaths(input.userRoot).root;
355
+ const directory = join(root, entry.kind === "role" ? "roles" : "agents");
356
+ const definitionRoot = entry.scope === "user" ? input.userRoot : bundledRoot;
357
+ if (entry.scope === "user" && resolve(dirname(entry.path)) !== resolve(directory)) throw new Error("The user definition is outside its catalog directory.");
358
+ assertInside(definitionRoot, entry.path);
359
+ assertNoSymlinkWalk(definitionRoot, entry.path);
360
+ const stats = lstatSync(entry.path);
361
+ const raw = readFileSync(entry.path);
362
+ const text = raw.toString("utf8");
363
+ if (!stats.isFile() || stats.isSymbolicLink() || !Buffer.from(text).equals(raw) || contentDigest(text) !== input.expectedDigest) {
364
+ throw new Error("The user definition changed before reset. Nothing was changed.");
365
+ }
366
+ let previous: NonNullable<AgentSessionOverrides[string]> = {};
367
+ const legacy = entry.definition?.kind === "role" ? entry.definition.defaults : entry.definition?.overrides;
368
+ const bundledPreferences = bundled.definition?.kind === "role" ? bundled.definition.defaults : bundled.definition?.overrides;
369
+ const legacyPreferences = {
370
+ ...(legacy?.model !== undefined ? { model: legacy.model } : bundledPreferences?.model !== undefined ? { model: null } : {}),
371
+ ...(legacy?.effort !== undefined ? { effort: legacy.effort } : bundledPreferences?.effort !== undefined ? { effort: null } : {}),
372
+ };
373
+ // Clearing JSON alone would reveal legacy runtime choices in user Markdown.
374
+ const runtimePreferences = entry.scope === "user" ? { bundled: true as const } : {};
375
+ const assertBundledUnchanged = () => {
376
+ if (lstatSync(bundledRoot).isSymbolicLink()) throw new Error("The bundled catalog is unavailable or symlinked.");
377
+ assertInside(bundledRoot, fallback.path);
378
+ assertNoSymlinkWalk(bundledRoot, fallback.path);
379
+ if (readFileSync(fallback.path, "utf8") !== bundledRaw) {
380
+ throw new Error("The bundled fallback changed while saving preferences. Nothing was archived. Reopen its settings.");
381
+ }
382
+ };
383
+ const saved = writeCatalogPreferences(root, input.id, current => {
384
+ if (runtimeOnly) assertBundledUnchanged();
385
+ previous = current;
386
+ return runtimeOnly ? runtimePreferences : clearPreferences ? {} : current.bundled ? current : { ...legacyPreferences, ...current };
387
+ });
388
+ // Discovery skips hidden files. Keep the original bytes for manual recovery.
389
+ const backupPath = entry.scope === "user" && !runtimeOnly
390
+ ? join(directory, `.${basename(entry.path)}.${randomBytes(12).toString("hex")}.backup`)
391
+ : undefined;
392
+ try {
393
+ const refreshed = loadCatalog(input);
394
+ const current = refreshed.roles.get(input.id) ?? refreshed.agents.get(input.id);
395
+ if (clearPreferences) assertNoProjectPreferences(refreshed, input.id);
396
+ const currentFallbacks = current?.scope === "bundled" ? [current] : current?.unused.filter(source => source.scope === "bundled") ?? [];
397
+ if (current?.scope !== entry.scope || current.duplicate || current.path !== entry.path || current.contentDigest !== input.expectedDigest
398
+ || currentFallbacks.length !== 1 || currentFallbacks[0]?.path !== fallback.path || currentFallbacks[0]?.contentDigest !== fallback.contentDigest) {
399
+ throw new Error("The definition or bundled fallback changed while saving preferences. Nothing was archived. Reopen its settings.");
400
+ }
401
+ assertBundledUnchanged();
402
+ assertNoSymlinkWalk(definitionRoot, entry.path);
403
+ const latest = readFileSync(entry.path);
404
+ if (!latest.equals(raw) || !lstatSync(entry.path).isFile()) {
405
+ throw new Error("The user definition changed while saving preferences. Nothing was archived. Reopen its settings.");
406
+ }
407
+ if (backupPath) renameSync(entry.path, backupPath);
408
+ }
409
+ catch (error) {
410
+ // Compare and roll back under the same lock; preserve any later edit.
411
+ try {
412
+ writeCatalogPreferences(root, input.id, current => JSON.stringify(current) === JSON.stringify(saved.settings[input.id] ?? {}) ? previous : current);
413
+ } catch (rollback) {
414
+ throw new Error(`${error instanceof Error ? error.message : String(error)} Preference rollback also failed: ${rollback instanceof Error ? rollback.message : String(rollback)}`);
415
+ }
416
+ throw error;
417
+ }
418
+ return { ok: true, path: backupPath ? entry.path : saved.path, backupPath, scope: "user", diagnostics: [] };
419
+ } catch (error) {
420
+ return { ok: false, diagnostics: [diagnostic("agents-reset", error instanceof Error ? error.message : String(error), {
421
+ scope: "user", id: input.id, blocking: true, structural: false,
422
+ })] };
423
+ }
424
+ }
425
+
240
426
  export function saveDefinition(input: SaveDefinitionInput): SaveResult {
241
427
  const scope = input.scope ?? "user";
242
428
  const diagnostics: Diagnostic[] = [];