pi-better-subagents 0.23.3 → 0.24.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/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[] = [];
package/catalog-ui.ts CHANGED
@@ -15,6 +15,8 @@ export interface CatalogEditor {
15
15
  settings(): AgentSessionOverrides;
16
16
  change(id: string, key: AgentSettingKey, value: string | null): void;
17
17
  save(id: string): { ok: boolean; message: string };
18
+ resetToBundled?(entry: OperationView): { ok: boolean; message: string };
19
+ resetDefinition?(entry: OperationView): { ok: boolean; message: string };
18
20
  }
19
21
 
20
22
  function stateLabel(entry: OperationView): string {
@@ -137,11 +139,15 @@ export function createCatalogComponent(
137
139
  getHeight: () => number = () => 30,
138
140
  ) {
139
141
  let selectedId = initialId ?? catalog.entries[0]?.id;
140
- let mode: "list" | "detail" | "prompt" = initialId ? "detail" : "list";
142
+ let mode: "list" | "detail" | "prompt" | "files" = initialId ? "detail" : "list";
141
143
  let query = "";
142
144
  let scroll = 0;
143
145
  let settingRow = 0;
144
146
  let settingPositions: number[] = [];
147
+ let resetPointerRows: number[] = [];
148
+ let resetPointerEntry: OperationView | undefined;
149
+ let pressedReset: OperationView | undefined;
150
+ let pressedResetMode: "detail" | "prompt" | undefined;
145
151
  let revealSetting = false;
146
152
  let picker: SelectList | undefined;
147
153
  let filterPicker: ((filter: string) => void) | undefined;
@@ -162,9 +168,30 @@ export function createCatalogComponent(
162
168
  report(result.message, !result.ok);
163
169
  } catch (cause) { report(String(cause instanceof Error ? cause.message : cause), true); }
164
170
  }
171
+ function canReset(entry: OperationView | undefined): boolean {
172
+ return !!editor?.resetToBundled && !!entry && !Object.values(entry.preferenceSources ?? {}).some(source => source.scope === "project")
173
+ && (entry.identity.scope === "bundled" || entry.identity.scope === "user" && entry.shadowed.some(source => source.scope === "bundled"));
174
+ }
175
+ function canResetDefinition(entry: OperationView | undefined): boolean {
176
+ return !!editor?.resetDefinition && !!entry && (entry.identity.scope === "bundled"
177
+ || entry.identity.scope === "user" && entry.shadowed.some(source => source.scope === "bundled"));
178
+ }
179
+ function reset(entry = selected(), definition = false) {
180
+ if (!entry || !(definition ? canResetDefinition(entry) : canReset(entry))) return;
181
+ try {
182
+ const result = definition ? editor!.resetDefinition!(entry) : editor!.resetToBundled!(entry);
183
+ refresh();
184
+ settingRow = 0;
185
+ scroll = 0;
186
+ resetPointerRows = [];
187
+ resetPointerEntry = undefined;
188
+ report(result.message, !result.ok);
189
+ } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
190
+ }
165
191
  function edit() {
166
192
  const current = selected();
167
193
  if (!current || !editor) return;
194
+ if (settingRow === 2) { reset(current); return; }
168
195
  if (!current.definitionValid) { report("Repair the catalog definition before editing.", true); return; }
169
196
  const key: AgentSettingKey = settingRow === 0 ? "model" : "effort";
170
197
  // Pi treats an empty scope as unrestricted. Scoped choices never include
@@ -211,22 +238,47 @@ export function createCatalogComponent(
211
238
  [entry.id, entry.identity.name, entry.identity.description, entry.role?.id]
212
239
  .some((value) => value?.toLowerCase().includes(query.toLowerCase())));
213
240
  const selected = () => filtered().find((entry) => entry.id === selectedId);
214
- const detailRows = (entry: OperationView, width: number, controls: string[] = []) => (mode === "prompt"
215
- ? [`${entry.identity.name || entry.id} · effective instructions`, "", ...(entry.instructions?.split("\n") ?? ["(none)"])]
216
- : catalogDetailLines(entry, !!editor, width, controls, theme))
217
- .flatMap((text) => text ? wrapLine(text, Math.max(1, width - 2)) : [""]);
241
+ const detailRows = (entry: OperationView, width: number, controls: string[] = []) => {
242
+ let lines: string[];
243
+ if (mode === "prompt") lines = [
244
+ ...(canResetDefinition(entry) ? [theme.fg("accent", "> Reset to bundled"), theme.fg("dim", " Restores the prompt; keeps model/effort choices."), ""] : []),
245
+ theme.fg("muted", `Source: ${entry.identity.scope ?? "unknown"} definition`), "", ...(entry.instructions?.split("\n") ?? ["(No resolved instructions)"]),
246
+ ];
247
+ else if (mode === "files") lines = [
248
+ theme.fg("muted", "Definition"), entry.identity.path ?? "(none)", "",
249
+ theme.fg("muted", "Saved preferences"),
250
+ ...([...new Set(Object.values(entry.preferenceSources ?? {}).map(source => `${source.scope}: ${source.path}`))].length
251
+ ? [...new Set(Object.values(entry.preferenceSources ?? {}).map(source => `${source.scope}: ${source.path}`))] : ["No saved preferences for this definition."]),
252
+ "", theme.fg("muted", "Session edits"), ...JSON.stringify(editor?.settings()[entry.id] ?? {}, null, 2).split("\n"),
253
+ ...(entry.shadowed.length ? ["", theme.fg("muted", "Shadowed definitions"), ...entry.shadowed.map(source => `${source.scope}: ${source.path}`)] : []),
254
+ ];
255
+ else lines = [
256
+ ...(editor ? controls : (["model", "effort"] as const).flatMap(key => settingLines(key === "model" ? "Model" : "Effort", entry.fields?.[key].value ?? "(unset)", entry.fields?.[key].inherited || entry.fields?.[key].source === "role-default" ? "inherited" : "catalog", Math.max(1, width - 4), " ", theme))),
257
+ "", theme.fg("dim", "Model and effort save separately from instructions."), "",
258
+ `ID ${entry.id}`, `Scope ${entry.identity.scope ?? "unknown"}`,
259
+ ...(entry.role?.id && entry.identity.kind === "agent" ? [`Role ${entry.role.id}`] : []),
260
+ `Tier ${entry.fields?.tier.value ?? "(unset)"}`,
261
+ `Actual ${entry.actualModel ?? "not resolved"}${entry.actualEffort ? ` · ${entry.actualEffort}` : ""}`,
262
+ "", theme.fg("muted", "Launch resolution"), entry.launchabilityReason,
263
+ ...(entry.validation.length ? ["", theme.fg("muted", "Diagnostics"), ...entry.validation.map(item => `${item.blocking ? "!" : "·"} ${item.message}`)] : []),
264
+ ...(entry.restrictions.length ? ["", theme.fg("muted", "Execution restrictions"), ...entry.restrictions.map(item => `${item.honored ? "honored" : "not honored"} ${item.name}`)] : []),
265
+ ];
266
+ return lines.flatMap(text => text ? wrapLine(text, Math.max(1, width - 4)).map(row => ` ${row}`) : [""]);
267
+ };
218
268
 
219
269
 
220
270
  return {
221
271
  get focused() { return focused; },
222
272
  set focused(value: boolean) { focused = value; search.focused = value && !!picker && pickerKey === "model"; },
223
273
  render(width: number): string[] {
274
+ resetPointerRows = [];
275
+ resetPointerEntry = undefined;
224
276
  const safeWidth = Math.max(1, width);
225
277
  const height = Math.max(1, Math.floor(getHeight()));
226
- const footerRows = (editor && mode !== "prompt" ? 2 : 0) + (message ? 2 : 0);
278
+ const footerRows = (editor ? 2 : 0) + (message ? 2 : 0);
227
279
  const diagnosticRows = Math.min(catalog.diagnostics.length, 3);
228
280
  const listSize = Math.max(1, height - 5 - footerRows - diagnosticRows - 1);
229
- const detailSize = Math.max(1, height - 5 - footerRows);
281
+ const detailSize = Math.max(1, height - 6 - footerRows);
230
282
  const fit = (lines: string[]) => {
231
283
  const result = lines.slice(0, height).map(line);
232
284
  while (result.length < height) result.push("");
@@ -254,13 +306,18 @@ export function createCatalogComponent(
254
306
  const own = editor?.settings()[current.id];
255
307
  const ownSession = Object.hasOwn(own ?? {}, key);
256
308
  const roleSession = field?.inherited && Object.hasOwn(editor?.settings()[current.role?.id ?? ""] ?? {}, key);
257
- const origin = ownSession && own?.[key] === null ? "inherit / session" : ownSession ? "session" : roleSession ? "inherited / session" : field?.inherited ? "inherited" : "catalog";
309
+ const saved = current.preferenceSources?.[key];
310
+ const inherited = current.identity.kind === "agent" && field?.inherited;
311
+ const origin = ownSession && own?.[key] === null ? "inherit / session" : ownSession ? "session" : roleSession ? "inherited / session"
312
+ : saved?.bundled ? "bundled" : saved ? `${inherited ? "inherited / " : ""}${saved.scope} config`
313
+ : current.identity.scope === "bundled" && !inherited ? "bundled" : field?.inherited ? "inherited" : "catalog";
258
314
  return settingLines(label, field?.value ?? "(unset)", origin, Math.max(1, safeWidth - 4), settingRow === index ? "> " : " ", theme);
259
315
  }),
316
+ ...(canReset(current) ? [theme.fg(settingRow === 2 ? "accent" : "muted", `${settingRow === 2 ? "> " : " "}Reset to bundled`), theme.fg("dim", " Restores model/effort; keeps the role prompt.")] : []),
260
317
  ] : [];
261
318
  const detailLines = current ? detailRows(current, safeWidth, controls) : [];
262
319
  if (editor && mode === "detail") {
263
- settingPositions = ["Model", "Effort"].map((label) => detailLines.findIndex((text) =>
320
+ settingPositions = ["Model", "Effort", ...(canReset(current) ? ["Reset to bundled"] : [])].map((label) => detailLines.findIndex((text) =>
264
321
  new RegExp(`^ [> ] ${label}(?:\\s|$)`).test(text.replace(/\x1b\[[0-9;]*m/g, ""))));
265
322
  if (revealSetting && settingPositions[settingRow] >= 0) {
266
323
  const position = settingPositions[settingRow];
@@ -270,9 +327,21 @@ export function createCatalogComponent(
270
327
  revealSetting = false;
271
328
  }
272
329
  scroll = Math.max(0, Math.min(scroll, detailLines.length - detailSize));
330
+ if (mode === "detail" && current && canReset(current)) {
331
+ const position = settingPositions[2];
332
+ if (position >= scroll && position < scroll + detailSize) {
333
+ resetPointerRows = [4 + position - scroll];
334
+ resetPointerEntry = current;
335
+ }
336
+ }
337
+ if (mode === "prompt" && current && canResetDefinition(current) && scroll === 0) {
338
+ resetPointerRows = [4];
339
+ resetPointerEntry = current;
340
+ }
273
341
  const lines = mode !== "list" && current ? [
274
- theme.fg("accent", mode === "prompt" ? "Agents / prompt" : editor ? `Agents / ${current.identity.name || current.id}` : "Agents / inspect"),
275
- theme.fg("dim", mode === "prompt" ? "← details · ↑↓ scroll · Esc back" : `${editor ? "Enter change · " : ""}p prompt · ← list · ↑↓ ${editor ? "select / scroll" : "scroll"} · Esc back`),
342
+ theme.fg("accent", `Agents / ${current.identity.name || current.id}`),
343
+ ([['detail', 'Settings'], ['prompt', 'Instructions'], ['files', 'Files']] as const).map(([tab, label]) => theme.fg(mode === tab ? "accent" : "dim", mode === tab ? `[${label}]` : label)).join(" "),
344
+ theme.fg("dim", safeWidth < 60 ? "Tab switch · ↑↓ move · Enter · Esc" : `Tab / Shift+Tab switch · ↑↓ ${mode === "detail" && editor ? "select / scroll · Enter change" : mode === "prompt" && canResetDefinition(current) ? "scroll · Enter reset at top" : "scroll"} · Esc list`),
276
345
  "",
277
346
 
278
347
  ...detailLines.slice(scroll, scroll + detailSize).map((text, i) =>
@@ -297,7 +366,7 @@ export function createCatalogComponent(
297
366
  ...catalog.diagnostics.slice(0, 2).map((diagnostic) => theme.fg("warning", `! ${diagnostic.message}`)),
298
367
  ...(catalog.diagnostics.length > 2 ? [theme.fg("warning", `! ${catalog.diagnostics.length - 2} more catalog diagnostics`)] : []),
299
368
  ];
300
- if (editor && mode !== "prompt") lines.push("", theme.fg("dim", "ctrl+s Save selected defaults"));
369
+ if (editor) lines.push("", theme.fg("dim", "Ctrl+S Save defaults"));
301
370
  if (message) lines.push("", theme.fg(error ? "error" : "muted", message));
302
371
  return fit(lines);
303
372
  },
@@ -312,15 +381,25 @@ export function createCatalogComponent(
312
381
  return;
313
382
  }
314
383
  if (editor && matchesKey(data, "ctrl+s")) { save(); return; }
384
+ if (mode !== "list" && (matchesKey(data, "tab") || matchesKey(data, "shift+tab"))) {
385
+ const tabs = ["detail", "prompt", "files"] as const;
386
+ const index = tabs.indexOf(mode);
387
+ mode = tabs[(index + (matchesKey(data, "shift+tab") ? 2 : 1)) % 3];
388
+ scroll = 0;
389
+ revealSetting = mode === "detail";
390
+ pressedReset = undefined;
391
+ requestRender();
392
+ return;
393
+ }
315
394
  if (matchesKey(data, "escape") || matchesKey(data, "left")) {
316
- if (mode === "prompt") { mode = "detail"; scroll = 0; }
395
+ if (mode === "prompt" || mode === "files") { mode = "detail"; scroll = 0; revealSetting = true; }
317
396
  else if (mode === "detail") { mode = "list"; scroll = 0; }
318
397
  else if (query) { query = ""; selectedId = catalog.entries[0]?.id; }
319
398
  else { close(); return; }
320
399
  } else if (matchesKey(data, "up") || matchesKey(data, "down")) {
321
400
  const delta = matchesKey(data, "down") ? 1 : -1;
322
- if (mode === "detail" && editor && scroll <= (settingPositions[1] ?? 0)
323
- && ((delta > 0 && settingRow === 0) || (delta < 0 && settingRow === 1))) {
401
+ if (mode === "detail" && editor && scroll <= (settingPositions.at(-1) ?? 0)
402
+ && ((delta > 0 && settingRow < settingPositions.length - 1) || (delta < 0 && settingRow > 0))) {
324
403
  settingRow += delta;
325
404
  revealSetting = true;
326
405
  }
@@ -339,6 +418,8 @@ export function createCatalogComponent(
339
418
  revealSetting = true;
340
419
  } else if (editor && mode === "detail" && (matchesKey(data, "enter") || data === " ")) {
341
420
  try { edit(); } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
421
+ } else if (editor && mode === "prompt" && scroll === 0 && (matchesKey(data, "enter") || data === " ")) {
422
+ reset(selected(), true);
342
423
  } else if (mode === "list" && matchesKey(data, "backspace")) {
343
424
  query = query.slice(0, -1);
344
425
  selectedId = filtered()[0]?.id;
@@ -348,6 +429,22 @@ export function createCatalogComponent(
348
429
  }
349
430
  requestRender();
350
431
  },
432
+ handleMouse(event: { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean }) {
433
+ const entry = resetPointerEntry;
434
+ const hit = !picker && (mode === "detail" || mode === "prompt") && entry && event.button === "left" && !event.shift && !event.alt && !event.ctrl
435
+ && event.x >= 0 && event.x < event.width && resetPointerRows.includes(event.y);
436
+ if (event.type === "press") {
437
+ pressedReset = hit ? entry : undefined;
438
+ pressedResetMode = hit ? mode as "detail" | "prompt" : undefined;
439
+ return hit ? { handled: true as const, render: false } : undefined;
440
+ }
441
+ if (event.type !== "click") return undefined;
442
+ const pressed = pressedReset;
443
+ pressedReset = undefined;
444
+ if (!hit || !pressed || pressedResetMode !== mode || pressed.id !== entry.id || pressed.winningSource?.contentDigest !== entry.winningSource?.contentDigest) return undefined;
445
+ reset(pressed, mode === "prompt");
446
+ return { handled: true as const, render: true };
447
+ },
351
448
  invalidate() { picker?.invalidate(); search.invalidate(); },
352
449
  };
353
450
  }
@@ -55,11 +55,20 @@ already-admitted jobs. Model choices come from the session's Pi model scope
55
55
  (`ctx.scopedModels`); an empty scope is no restriction, so they fall back to the
56
56
  current Pi model registry's available models.
57
57
 
58
- Ctrl+S saves only the selected definition's own preferences, never flattened
59
- inherited settings. Bundled roles are copied to user scope; existing user and
60
- project definitions are saved in their own scope with the store's trust,
61
- validation, and atomic-write checks. Plain `loadCatalog` remains disk-only so
62
- saving selects the current winning definition rather than a stale overlay.
58
+ Ctrl+S saves only the selected definition's model/effort edits in catalog
59
+ `settings.json`, preserving other saved fields without copying Markdown or
60
+ flattening inherited defaults. `loadCatalog` reads definition files and saved
61
+ preferences from disk; the branch overlay stays separate. User preferences apply
62
+ to user and bundled definitions; trusted project preferences take precedence.
63
+ Project-owned definitions do not consume user preferences.
64
+
65
+ Settings, Instructions, and Files have separate TUI tabs; Ctrl+S is the only
66
+ save control. **Reset to bundled** in Settings restores model/effort preferences
67
+ and clears branch-local edits without changing Markdown. The same action in
68
+ Instructions restores the bundled prompt while preserving model/effort choices;
69
+ a user Markdown override is archived. Session reset entries replay on reload and
70
+ branch navigation. Existing launch snapshots remain unchanged. Project-owned
71
+ definitions are excluded; runtime reset also excludes active project config.
63
72
 
64
73
  Headless callers can inject a session controller or immutable
65
74
  `CatalogHost.sessionSettings`. Hosts without these hooks retain inspection-only
@@ -6,7 +6,7 @@ Commands, the read-only discovery tool, and the Codex importer for `pi-agent/v1`
6
6
 
7
7
  `/agents` is one Pi command. Dialogs use `ctx.ui.select`, `confirm`, `input`, and `editor`. `ctx.hasUI` is false in print and JSON mode. When a choice or confirmation is required there, the command returns `clarification-needed` and writes nothing.
8
8
 
9
- In an interactive TUI, `/agents`, `/agents list`, and `/agents show` open a focused catalog view instead of leaving the listing in a persistent widget. Rows align name, effective model, source, and launch state; narrow terminals retain name and model. The model is the resolved actual model when available, otherwise the requested or inherited preference, or `not resolved`. Type to filter by id, name, description, or base role; use Up/Down and Enter to inspect. The detail view puts launchability and its reason first, then source, inherited/overridden settings, and diagnostics. Press `p` in detail to read the complete effective instructions (role plus agent in add mode, agent text in replace mode); this is not the task-specific launch prompt. Up/Down scrolls detail or prompt; Left or Escape returns to detail, then list, clears the filter, then closes. `/agents show <id>` opens that definition directly. Print/JSON callers still receive the complete text and structured result; bare `/agents` still returns help outside the custom TUI.
9
+ In an interactive TUI, `/agents`, `/agents list`, and `/agents show` open a focused catalog view instead of leaving the listing in a persistent widget. Rows align name, effective model, source, and launch state; narrow terminals retain name and model. The model is the resolved actual model when available, otherwise the requested or inherited preference, or `not resolved`. Type to filter by id, name, description, or base role; use Up/Down and Enter to inspect. The detail view opens **Settings**, with Model, Effort, launch resolution, and diagnostics. **Instructions** contains the complete effective prompt (role plus agent in add mode, agent text in replace mode); this is not the task-specific launch prompt. **Files** shows definition and saved-config sources plus current session edits. Tab and Shift+Tab cycle between these pages; `p` opens Instructions. Up/Down selects settings or scrolls the current page. Left or Escape returns to Settings, then list, clears the filter, then closes. `/agents show <id>` opens that definition directly. Print/JSON callers still receive the complete text and structured result; bare `/agents` still returns help outside the custom TUI.
10
10
 
11
11
  ### Model and effort edits
12
12
 
@@ -16,7 +16,27 @@ The scope affects only the picker. Launch and runtime model resolution keep read
16
16
 
17
17
  A selected value immediately appends a custom entry to the current session branch. It does not write a catalog file. Reloading the extension or session restores the active branch's edits. Branches share their common ancestor settings but subsequent edits do not cross to siblings. Role edits flow into named agents that inherit that field. Choosing `Inherit` removes the selected definition's own value, including a saved agent override, instead of storing an explicit null preference. For a role with no parent, that removes its default. Later role/file edits remain live.
18
18
 
19
- Ctrl+S in list, detail, or settings (or Enter on Save as defaults) explicitly saves the selected definition's own model and effort changes. It never copies inherited role fields into an agent. Existing personal/project definitions stay in their winning scope; a bundled definition becomes a personal whole-definition shadow copy, leaving the package file untouched. Project trust, duplicate/invalid-definition checks, validation, and atomic catalog writes still apply. Both successful and failed saves leave branch edits intact. A failed save reports the error without changing the catalog defaults.
19
+ Ctrl+S saves the selected definition's model and effort edits to `agents/settings.json` in user scope, or the corresponding trusted project catalog. It never copies or rewrites a Markdown definition, so changing a bundled role's model does not freeze its prompt or its untouched defaults. Existing saved preferences for other definitions are preserved. Writes validate the config and use a lock plus atomic replacement; malformed config is not overwritten. Both successful and failed saves leave branch edits intact.
20
+
21
+ The dedicated config has this shape:
22
+
23
+ ```json
24
+ {
25
+ "version": 1,
26
+ "defaults": {
27
+ "role.developer": { "model": "openai/gpt-6.1-sol", "effort": "high" }
28
+ }
29
+ }
30
+ ```
31
+
32
+ Saved fields override definition defaults one field at a time; branch edits override saved fields. A record with `bundled: true` takes model/effort defaults from the current bundled definition before applying any explicit fields in that record. Trusted project config wins over user config. User config does not override a project-owned Markdown definition. The detail view labels saved fields as `user config` or `project config`.
33
+
34
+ Both Settings and Instructions offer **Reset to bundled**, with independent effects:
35
+
36
+ - **Settings:** follows the current bundled model and effort, clears that id's current-session choices, and leaves its Markdown prompt unchanged. A user definition records `{ "bundled": true }` instead of copied default values; the UI shows `bundled`, and later bundle updates apply automatically. An explicit model/effort choice can override one field while the other keeps following the bundle. Project-owned definitions and active project config are excluded.
37
+ - **Instructions:** archives a user Markdown override in a hidden `.backup` file beside the original and reveals the bundled role prompt. Its model/effort choices move to the config where needed, and session choices remain unchanged. An already-bundled prompt needs no change. Project definitions are excluded.
38
+
39
+ Click the action once, or select it in Settings and press Enter. In Instructions, Enter activates the reset when scrolled to the top. The action requires a valid bundled fallback and refuses stale selections, duplicates, and symlink redirects. Other definitions stay unchanged. Saving remains **Ctrl+S** only; there is no Save button or selectable save row. Existing overrides remain intact until explicitly reset.
20
40
 
21
41
  New launches and `agents_catalog` discovery use the same session overlay. Explicit per-run model/effort choices still win, a batch retains one immutable snapshot, and active/completed runs do not change. Role effort remains an inherited default with the existing nearest-supported adjustment; named-agent effort remains explicit and blocks when unsupported. The lifecycle wiring required to enable this surface is in [agent-catalog-lifecycle.md](./agent-catalog-lifecycle.md#session-settings-integration).
22
42
 
@@ -78,7 +78,9 @@ For external consumers, the repo-root `agent-catalog.yaml` publishes the shared
78
78
  definitions through a [Git subscription contract](catalog-subscription.md).
79
79
  This publication mechanism does not change local source precedence below.
80
80
 
81
- Precedence is project, then personal, then bundled. The higher source replaces the whole definition. Omitted agent fields inherit from the effective role, not from the shadowed agent.
81
+ Markdown definition precedence is project, then personal, then bundled. The higher source replaces the whole definition. Omitted agent fields inherit from the effective role, not from the shadowed agent.
82
+
83
+ Model and effort choices saved through `/agents` live separately in the catalog's `settings.json` (`version: 1`, with a `defaults` map keyed by role/agent id). They override only those fields, without shadowing the Markdown prompt. Branch edits win over saved preferences; trusted project preferences win over user preferences. User preferences do not override project-owned definitions. Existing Markdown overrides stay whole definitions until explicitly archived through **Reset to bundled** in Instructions. See [catalog operations](agent-catalog-operations.md#model-and-effort-edits).
82
84
 
83
85
  | Scope | Path |
84
86
  | --- | --- |
@@ -94,7 +96,7 @@ Role references use the same precedence. A missing or unusable role leaves the a
94
96
 
95
97
  ## Snapshots
96
98
 
97
- `loadCatalog` / `refreshCatalog` read the disk every time and return a new frozen snapshot. `digest` / `revision` is a sha256 of the canonical entries, unused sources, and snapshot diagnostics. `loadedAt` is not part of the digest. Callers must reuse one snapshot for every job in a batch. Later file edits do not mutate a snapshot already taken. `/agents reload` is an inspection operation owned by the operations unit; it is not required for the next `loadCatalog` to see edits.
99
+ `loadCatalog` / `refreshCatalog` read the disk every time and return a new frozen snapshot. `digest` / `revision` is a sha256 of the canonical entries, unused sources, saved preferences and their sources, and snapshot diagnostics. `loadedAt` is not part of the digest. Callers must reuse one snapshot for every job in a batch. Later file edits do not mutate a snapshot already taken. `/agents reload` is an inspection operation owned by the operations unit; it is not required for the next `loadCatalog` to see edits.
98
100
 
99
101
  File diagnostics for an id live on that catalog entry. `snapshot.diagnostics` carries directory, trust, duplicate, and no-id failures. `resolveSelection`, `listCatalog`, and `inspectCatalog` are the launchability view; `schemaLaunchable` does not yet know whether an agent's role exists.
100
102
 
package/index.ts CHANGED
@@ -17,6 +17,7 @@ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@e
17
17
  import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
18
18
  import * as PiTui from "@earendil-works/pi-tui";
19
19
  import { CustomEditor } from "@earendil-works/pi-coding-agent";
20
+ import { initializeNavigatorPanels } from "./shared-navigator-panels.ts";
20
21
  import { matchesKey, Key, truncateToWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
21
22
  import { Type } from "@earendil-works/pi-ai";
22
23
  import {
@@ -1465,6 +1466,7 @@ function catalogRoleSchema(purpose: string) {
1465
1466
  }
1466
1467
 
1467
1468
  export default function (pi: ExtensionAPI) {
1469
+ initializeNavigatorPanels(pi);
1468
1470
  const agentSessionSettings = createAgentSessionSettings(pi);
1469
1471
  let catalogModelRegistry: ExtensionContext["modelRegistry"] | undefined;
1470
1472
  let delegationOverride: DelegationMode | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.23.3",
3
+ "version": "0.24.0",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -3,12 +3,14 @@ schema: pi-agent/v1
3
3
  kind: role
4
4
  id: role.developer
5
5
  name: Developer
6
- description: Owns implementation and focused tests; excludes architecture policy and independent review.
6
+ description: Owns implementation and focused tests, including release metadata preparation; excludes delivery, publishing, architecture policy, and independent review.
7
7
  defaults:
8
8
  model: openai/gpt-6.1-sol
9
9
  effort: high
10
10
  tier: balanced
11
11
  ---
12
12
  Implement the requested change in the existing system and own focused tests. Preserve behavior the task did not ask to change, and record what you verified.
13
+ For a release, prepare and test metadata under the coordinator's approved plan: version files, dependency pins, lockfile, changelog, and package checks. Hand back the local changes or commit, verification evidence, and remaining blockers.
14
+ Delivery and publishing belong to the coordinator: remote pushes, PR creation and merge, queue admission, release tags, publisher dispatch, and publication verification. Do not perform those operations or take ownership of external waits. The coordinator uses background watchers for CI, merge queues, publishers, registry propagation, and deployments. If an assignment crosses this boundary, report the mismatch and hand it back before proceeding.
13
15
  When a check fails, report the failing step, the error message and where the evidence is; an exit code alone is not a failure report. Keep the first failure separate from later cleanup errors. Send long command output to a file and read only the tail or the matching lines.
14
16
  Do not define product policy or own broad architecture decisions; route those to Product Manager or Architect. Independent critique belongs to Reviewer, not the implementer.
@@ -0,0 +1,250 @@
1
+ // Generated from packages/navigator/panels.ts. Do not edit directly.
2
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
3
+ import type { Component, TUI } from "@earendil-works/pi-tui";
4
+ import { randomUUID } from "node:crypto";
5
+ import { readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.js";
6
+
7
+ export const NAVIGATOR_PANEL_WIDGET_KEY = "background-work-list";
8
+ export const NAVIGATOR_ENTRY_TYPE = "pi-better-harness-navigator-panels";
9
+ export const NAVIGATOR_STICKY_SETTING_ID = "navigator-sticky";
10
+ type MouseEvent = { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean };
11
+ type PanelComponent = Component & { dispose?(): void; handleMouse?(event: MouseEvent): { handled: true; render: boolean } | undefined };
12
+ export type NavigatorPanelFactory = (tui: TUI, theme: Theme) => PanelComponent;
13
+ type Panel = { factory: NavigatorPanelFactory; component?: PanelComponent | undefined };
14
+ type Preference = { version: 1; sticky: boolean };
15
+ type Owner = { pi: ExtensionAPI; stop?: (() => void) | undefined };
16
+ type State = {
17
+ panels: Map<string, Panel>;
18
+ owners: Map<ExtensionAPI, Owner>;
19
+ ctx?: ExtensionContext | undefined;
20
+ ui?: ExtensionContext["ui"] | undefined;
21
+ pi?: ExtensionAPI | undefined;
22
+ sticky: boolean;
23
+ mounted: boolean;
24
+ tui?: TUI | undefined;
25
+ theme?: Theme | undefined;
26
+ anchor?: string | undefined;
27
+ pendingAnchor: boolean;
28
+ generation: number;
29
+ ranges: Array<{ start: number; end: number; component: PanelComponent }>;
30
+ control?: { id: string; label: string; values: string[]; get(): string; change(value: string, ctx: ExtensionContext): void } | undefined;
31
+ };
32
+ const KEY = Symbol.for("pi-better-harness.navigator-panels.state");
33
+ function state(): State {
34
+ const global = globalThis as typeof globalThis & { [KEY]?: State };
35
+ return global[KEY] ??= { panels: new Map(), owners: new Map(), sticky: true, mounted: false, pendingAnchor: false, generation: 0, ranges: [] };
36
+ }
37
+ function parsePreference(value: unknown): Preference {
38
+ if (value === undefined) return { version: 1, sticky: true };
39
+ const preference = value as Partial<Preference> | null;
40
+ if (!preference || preference.version !== 1 || typeof preference.sticky !== "boolean") {
41
+ throw new Error("Navigator preference must contain version 1 and a boolean sticky value.");
42
+ }
43
+ return { version: 1, sticky: preference.sticky };
44
+ }
45
+ function canScroll(pi: ExtensionAPI | undefined): boolean {
46
+ return typeof pi?.registerEntryRenderer === "function" && typeof pi?.appendEntry === "function";
47
+ }
48
+ function isTui(ctx: ExtensionContext | undefined): ctx is ExtensionContext {
49
+ return ctx?.mode === "tui" && ctx.hasUI && typeof ctx.ui?.setWidget === "function";
50
+ }
51
+ function disposePanels(s: State): void {
52
+ for (const panel of s.panels.values()) {
53
+ try { panel.component?.dispose?.(); } catch { /* stale UI cleanup is best effort */ }
54
+ panel.component = undefined;
55
+ }
56
+ s.ranges = [];
57
+ }
58
+ function orderedPanels(s: State): Panel[] {
59
+ const rank = (key: string) => key === "pi-better-goal" ? 0 : key === "pi-better-plan" ? 1 : 2;
60
+ return [...s.panels.entries()].sort(([a], [b]) => rank(a) - rank(b)).map(([, panel]) => panel);
61
+ }
62
+ function buildPanels(s: State): void {
63
+ if (!s.tui || !s.theme) return;
64
+ for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme);
65
+ }
66
+ function renderPanels(s: State, width: number): string[] {
67
+ buildPanels(s);
68
+ const lines: string[] = [];
69
+ s.ranges = [];
70
+ for (const panel of orderedPanels(s)) {
71
+ if (!panel.component) continue;
72
+ const rendered = panel.component.render(width);
73
+ s.ranges.push({ start: lines.length, end: lines.length + rendered.length, component: panel.component });
74
+ lines.push(...rendered);
75
+ }
76
+ return lines;
77
+ }
78
+ function mouse(s: State, event: MouseEvent) {
79
+ const range = s.ranges.find(range => event.y >= range.start && event.y < range.end);
80
+ return range?.component.handleMouse?.({ ...event, y: event.y - range.start });
81
+ }
82
+ function restoreAnchor(ctx: ExtensionContext): string | undefined {
83
+ let anchor: string | undefined;
84
+ for (const entry of ctx.sessionManager?.getBranch?.() ?? []) {
85
+ if (entry.type !== "custom" || entry.customType !== NAVIGATOR_ENTRY_TYPE) continue;
86
+ const data = entry.data as { version?: unknown; anchor?: unknown } | undefined;
87
+ if (data?.version === 1 && typeof data.anchor === "string") anchor = data.anchor;
88
+ }
89
+ return anchor;
90
+ }
91
+ function appendAnchor(s: State): void {
92
+ if (s.sticky || s.anchor || !canScroll(s.pi)) return;
93
+ const anchor = randomUUID();
94
+ s.anchor = anchor;
95
+ try { s.pi!.appendEntry(NAVIGATOR_ENTRY_TYPE, { version: 1, anchor }); }
96
+ catch (error) { s.anchor = undefined; throw error; }
97
+ }
98
+ function scheduleAnchor(s: State): void {
99
+ if (s.anchor || s.pendingAnchor || s.sticky) return;
100
+ s.pendingAnchor = true;
101
+ const generation = s.generation;
102
+ // Session writes cannot run inside a component render. Empty sessions stay untouched.
103
+ queueMicrotask(() => {
104
+ if (generation !== s.generation) return;
105
+ s.pendingAnchor = false;
106
+ if (!s.sticky && s.panels.size) appendAnchor(s);
107
+ });
108
+ }
109
+ function clearHost(s: State): void {
110
+ s.generation++;
111
+ s.pendingAnchor = false;
112
+ try {
113
+ if (s.mounted && isTui(s.ctx)) s.ctx.ui.setWidget(NAVIGATOR_PANEL_WIDGET_KEY, undefined);
114
+ } catch { /* an old session context may already be detached */ }
115
+ disposePanels(s);
116
+ s.mounted = false;
117
+ s.tui = undefined;
118
+ s.theme = undefined;
119
+ }
120
+ function adoptContext(s: State, ctx: ExtensionContext): void {
121
+ if (s.ui && s.ui !== ctx.ui) {
122
+ clearHost(s);
123
+ s.panels.clear();
124
+ s.anchor = undefined;
125
+ }
126
+ s.ctx = ctx;
127
+ s.ui = ctx.ui;
128
+ }
129
+ function mountHost(s: State): void {
130
+ if (!isTui(s.ctx) || s.mounted || !s.panels.size) return;
131
+ s.mounted = true;
132
+ s.ctx.ui.setWidget(NAVIGATOR_PANEL_WIDGET_KEY, (tui, theme) => {
133
+ if (s.tui !== tui || s.theme !== theme) disposePanels(s);
134
+ s.tui = tui;
135
+ s.theme = theme;
136
+ buildPanels(s);
137
+ return {
138
+ render(width: number) {
139
+ const lines = renderPanels(s, width);
140
+ if (s.sticky) return lines;
141
+ if (lines.length) scheduleAnchor(s);
142
+ return [];
143
+ },
144
+ handleMouse: (event: MouseEvent) => s.sticky ? mouse(s, event) : undefined,
145
+ invalidate() {
146
+ for (const panel of s.panels.values()) panel.component?.invalidate();
147
+ },
148
+ dispose() { disposePanels(s); s.mounted = false; },
149
+ };
150
+ }, { placement: "aboveEditor" });
151
+ }
152
+ function changeSticky(value: string, ctx: ExtensionContext): void {
153
+ if (value !== "On" && value !== "Off") throw new Error("Sticky navigator expects On or Off.");
154
+ const s = state();
155
+ if (value === "Off" && !canScroll(s.pi)) {
156
+ throw new Error("Scrolling navigator requires a Pi version with registerEntryRenderer support.");
157
+ }
158
+ updateHarnessSetting("navigator", current => {
159
+ parsePreference(current);
160
+ return { version: 1, sticky: value === "On" };
161
+ });
162
+ adoptContext(s, ctx);
163
+ if (s.sticky && value === "Off") s.anchor = undefined;
164
+ s.sticky = value === "On";
165
+ refreshNavigatorPanels(ctx);
166
+ }
167
+ export function initializeNavigatorPanels(pi: ExtensionAPI): void {
168
+ const s = state();
169
+ if (s.owners.has(pi)) return;
170
+ s.pi = pi;
171
+ try { s.sticky = parsePreference(readHarnessSetting("navigator")).sticky; }
172
+ catch { s.sticky = true; }
173
+ if (!canScroll(pi)) s.sticky = true;
174
+ if (canScroll(pi)) pi.registerEntryRenderer(NAVIGATOR_ENTRY_TYPE, (entry) => {
175
+ const data = entry.data as { version?: number; anchor?: string } | undefined;
176
+ if (data?.version !== 1 || !data.anchor) return undefined;
177
+ // Pi reconstructs chat before session_start restores the visible branch.
178
+ // Keep the component mounted and resolve its active anchor at render time.
179
+ return {
180
+ render: width => !s.sticky && data.anchor === s.anchor ? renderPanels(s, width) : [],
181
+ handleMouse: event => !s.sticky && data.anchor === s.anchor ? mouse(s, event) : undefined,
182
+ invalidate() { for (const panel of s.panels.values()) panel.component?.invalidate(); },
183
+ } as PanelComponent;
184
+ });
185
+ s.control ??= {
186
+ id: NAVIGATOR_STICKY_SETTING_ID, label: "Sticky navigator", values: ["On", "Off"],
187
+ get: () => state().sticky ? "On" : "Off", change: changeSticky,
188
+ };
189
+ const owner: Owner = { pi };
190
+ s.owners.set(pi, owner);
191
+ // Use one stable contribution callback across vendored copies, but each owner
192
+ // cleans up its own event subscription when its extension is unloaded.
193
+ const register = () => pi.events?.emit?.("harness-settings:register", s.control);
194
+ owner.stop = pi.events?.on?.("harness-settings:request", register);
195
+ register();
196
+ pi.on("session_start", (_event, ctx) => {
197
+ adoptContext(s, ctx);
198
+ s.anchor = restoreAnchor(ctx);
199
+ });
200
+ pi.on("session_tree", (_event, ctx) => {
201
+ adoptContext(s, ctx);
202
+ s.anchor = restoreAnchor(ctx);
203
+ refreshNavigatorPanels(ctx);
204
+ });
205
+ pi.on("session_shutdown", () => {
206
+ owner.stop?.();
207
+ s.owners.delete(pi);
208
+ if (s.owners.size) return;
209
+ clearHost(s);
210
+ s.panels.clear();
211
+ s.anchor = undefined;
212
+ s.ctx = undefined;
213
+ s.ui = undefined;
214
+ s.pi = undefined;
215
+ });
216
+ }
217
+ export function setNavigatorPanel(
218
+ ctx: ExtensionContext, key: string, content: NavigatorPanelFactory | undefined,
219
+ _options?: { placement?: "aboveEditor" | "belowEditor" },
220
+ ): void {
221
+ const s = state();
222
+ if (!isTui(ctx)) return;
223
+ adoptContext(s, ctx);
224
+ s.panels.get(key)?.component?.dispose?.();
225
+ if (content) s.panels.set(key, { factory: content });
226
+ else s.panels.delete(key);
227
+ if (!s.panels.size) { clearHost(s); return; }
228
+ mountHost(s);
229
+ buildPanels(s);
230
+ s.tui?.requestRender?.();
231
+ }
232
+ export function refreshNavigatorPanels(ctx?: ExtensionContext): void {
233
+ const s = state();
234
+ if (ctx) adoptContext(s, ctx);
235
+ mountHost(s);
236
+ s.tui?.requestRender?.(true);
237
+ }
238
+ export function __resetNavigatorPanelsForTests(): void {
239
+ const s = state();
240
+ clearHost(s);
241
+ for (const owner of s.owners.values()) owner.stop?.();
242
+ s.owners.clear();
243
+ s.panels.clear();
244
+ s.pi = undefined;
245
+ s.ctx = undefined;
246
+ s.ui = undefined;
247
+ s.anchor = undefined;
248
+ s.sticky = true;
249
+ s.control = undefined;
250
+ }
@@ -2,6 +2,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { truncateToWidth as piTruncateToWidth, visibleWidth as piVisibleWidth } from "@earendil-works/pi-tui";
3
3
  import type { Component } from "@earendil-works/pi-tui";
4
4
  import { createRenderScheduler, type RenderScheduler } from "./shared-render-scheduler.ts";
5
+ import { setNavigatorPanel } from "./shared-navigator-panels.ts";
5
6
 
6
7
  export default function navigatorExtension(): void {
7
8
  // Internal shared package. Pi may scan its symlink in the extension directory
@@ -195,7 +196,7 @@ export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostD
195
196
  ...deps,
196
197
  createTranscriptComponent: deps.createTranscriptComponent ?? s.deps?.createTranscriptComponent,
197
198
  };
198
- try { (ctx.ui as any).setWidget?.(MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
199
+ try { setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
199
200
  s.mainListWidgetInstalled = false;
200
201
  s.mainListRequestRender = undefined;
201
202
  s.mainListDeadlineScheduler?.dispose();
@@ -215,8 +216,7 @@ export function disposeBackgroundWorkNavigator(ctx?: ExtensionContext): void {
215
216
  const activeCtx = ctx ?? s.uiCtx;
216
217
  s.uiCtx = undefined;
217
218
  if (activeCtx && isNavigatorUiAvailable(activeCtx)) {
218
- const ui = activeCtx.ui;
219
- try { (ui as any).setWidget?.(MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
219
+ try { setNavigatorPanel(activeCtx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
220
220
  }
221
221
  s.lastHint = undefined;
222
222
  s.lastMainListLines = undefined;
@@ -291,7 +291,7 @@ function refreshMainListWidget(): void {
291
291
  })] : undefined;
292
292
  if (!rows.length) {
293
293
  if (!s.mainListWidgetInstalled) return;
294
- try { (ctx.ui as any).setWidget?.(MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
294
+ try { setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
295
295
  s.mainListWidgetInstalled = false;
296
296
  s.mainListRequestRender = undefined;
297
297
  s.lastMainListSignature = undefined;
@@ -299,7 +299,7 @@ function refreshMainListWidget(): void {
299
299
  }
300
300
  if (!s.mainListWidgetInstalled) {
301
301
  try {
302
- (ctx.ui as any).setWidget?.(MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown) => createMainListWidget(tui, theme, deps), { placement: "aboveEditor" });
302
+ setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown) => createMainListWidget(tui, theme, deps), { placement: "aboveEditor" });
303
303
  s.mainListWidgetInstalled = true;
304
304
  } catch { /* ignore */ }
305
305
  }