pi-subagent-manager 0.22.0 → 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/README.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/pi-subagent-manager.svg)](https://www.npmjs.com/package/pi-subagent-manager)
4
4
  [![npm downloads](https://img.shields.io/npm/dm/pi-subagent-manager.svg)](https://www.npmjs.com/package/pi-subagent-manager)
5
+ [![GitHub stars](https://img.shields.io/github/stars/championswimmer/pi-subagent-manager?style=social)](https://github.com/championswimmer/pi-subagent-manager/stargazers)
5
6
  [![CI](https://github.com/championswimmer/pi-subagent-manager/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/championswimmer/pi-subagent-manager/actions/workflows/tests.yml)
6
7
  [![codecov](https://codecov.io/gh/championswimmer/pi-subagent-manager/branch/main/graph/badge.svg)](https://codecov.io/gh/championswimmer/pi-subagent-manager)
7
8
 
@@ -64,14 +65,16 @@ They inherit your current model until you set preferences. Details: [docs/defaul
64
65
 
65
66
  ## Commands
66
67
 
67
- | Command | Opens |
68
- | ---------------- | ------------------------------------------------------ |
69
- | `/agents` | Settings (mode, limits, model picking, tool filtering) |
70
- | `/agents types` | Agent-type browser and editor |
71
- | `/agents tree` | Fullscreen tree and live viewer with manual steering |
72
- | `/agents import` | Import agents from other subagent extensions |
73
- | `/agents reload` | Reload definitions and settings |
74
- | `/agents reap` | Confirm the eligible count, then forget completed agents and free retained-thread slots (cannot be resumed); preserves active parents and ancestors of retained threads. Session files remain on disk. |
68
+ | Command | Opens |
69
+ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
70
+ | `/agents` | Settings (mode, limits, model picking, tool filtering) |
71
+ | `/agents types` | Agent-type browser and editor |
72
+ | `/agents tree` | Fullscreen tree and live viewer with manual steering |
73
+ | `/agents import` | Import agents from other subagent extensions |
74
+ | `/agents fork:<agent> <task>` | Start a detached agent that inherits your current conversation (autocompletes every available agent) |
75
+ | `/agents fresh:<agent> <task>` | Start a detached agent with no inherited context (autocompletes every available agent) |
76
+ | `/agents reload` | Reload definitions and settings |
77
+ | `/agents reap` | Confirm the eligible count, then forget completed agents and free retained-thread slots (cannot be resumed); preserves active parents and ancestors of retained threads. Session files remain on disk. |
75
78
 
76
79
  A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line. A fresh prompt hides previously settled agents from the widget; they reappear only when resumed, and `/agents tree` always keeps them available. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. Press **Right** at the end of the draft (or in an empty input) to collapse the widget to one line for this session only, without changing saved settings. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
77
80
 
@@ -81,7 +84,7 @@ A live **Agents** widget sits above the input box. Choose **Full** (the existing
81
84
  - **`npm:pi-footer`:** with the default status-key mode, add **Extension Status** through `/footer` and select **`subagent_cost`**. Event mode instead requires a **Pi Event Value** widget with **Widget ID** entered manually and **Raw value only** enabled; event IDs are not listed in the status selector.
82
85
  - Values publish at session start and immediately on subagent startup, including `💵 $0.0000`, then after settlement/settings changes. Total cost includes the main session plus settled subagents. The icon picker offers three Nerd Font choices when the labs toggle is on, otherwise three emoji choices. Status modes leave your footer untouched; event mode retains a fallback showing the selected value/icon when no extension provides `/footer`. See [Cost display settings](docs/settings.md#labs-cost-display-costdisplay) and the [pi-footer setup guide with exact snippets](docs/pi-footer.md).
83
86
 
84
- Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names (off by default; requires a Nerd Font in your terminal). Loaders appear **before**, never instead of, the role icon. Choose Circle, Braille, or Hourglass under **[labs] Loader style**, with previews of every animation frame and each family's completed, paused, failed, and stopped icons. Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
87
+ Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names (off by default; requires a Nerd Font in your terminal). Loaders appear **before**, never instead of, the role icon. Choose Braille, ASCII (`| / - \`), ASCII Star (`+ x *`), or ASCII Pulse (`= * -`) with Nerd Fonts off; enabling Nerd Fonts also unlocks Circle and Hourglass under **[labs] Loader style**, with previews of every animation frame and each family's completed, paused, failed, and stopped icons. Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
85
88
 
86
89
  Enable **[labs] Enable subagent extensions** in `/agents settings` to reload configured user and trusted-project extension hooks in each subagent’s separate session. It is off by default and experimental: hooks that assume main-session state can cause bugs or unintended consequences. This is configured-file discovery, **not exact main-session inheritance**; CLI-only, inline, and built-in extensions are not reloaded. See [subagent extension settings](docs/settings.md#labs-enable-subagent-extensions-subagentextensions) and read the [limitations](docs/subagent-extension-limitations.md) before enabling.
87
90
 
@@ -143,7 +143,7 @@ In `/agents types`, select **[labs] Icon** and paste the glyph, then save the ag
143
143
  | Ctrl+S | Save (or apply a multiline field to the draft) |
144
144
  | Esc | Discard draft |
145
145
 
146
- The model picker lists selected models first, in fallback order. **Enter** toggles a model, **Ctrl+↑/↓** reorders, typing filters. Unselected models are ranked by fuzzy match against `modelSuggestions`, scoped models first.
146
+ The model picker lists selected models first, in fallback order. **Enter** toggles a model; **w/s** moves a selected model up/down in browse mode. **/** or **Tab** enters search, where typing (including w/s) filters; **Tab** returns to browsing while keeping the filter. Other typed letters also start search. Unselected models are ranked by fuzzy match against `modelSuggestions`, scoped models first.
147
147
 
148
148
  **External editor** opens the whole Markdown definition in `$VISUAL`, `$EDITOR`,
149
149
  or `vi` in fork mode. For an overlay, edit its YAML file directly and reload.
package/docs/settings.md CHANGED
@@ -62,17 +62,28 @@ Minimal mode groups starting agents with running agents and excludes the main co
62
62
 
63
63
  ## [labs] Nerd Font icons (`nerdFontIcons`)
64
64
 
65
- Experimental features are tagged **[labs]** in settings. **[labs] Nerd Font icons** is an on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"nerdFontIcons": true` in your settings file. Configure a [Nerd Font](https://www.nerdfonts.com/) in your terminal first; unsupported fonts may show boxes or incorrect glyphs. The extension does not install or detect fonts.
65
+ Experimental features are tagged **[labs]** in the selected setting's help. Row labels omit that prefix to leave room for provenance dots. **[labs] Nerd Font icons** is an on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"nerdFontIcons": true` in your settings file. Configure a [Nerd Font](https://www.nerdfonts.com/) in your terminal first; unsupported fonts may show boxes or incorrect glyphs. The extension does not install or detect fonts.
66
66
 
67
- When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker. Starting/running agents show the selected loader **before the original role icon**, never replacing it. Completed, paused, failed, and stopped agents show that loader family's corresponding static state icon before the role icon. Agents without a configured role icon still show their loader/state indicator. The one-line minimal widget uses the same family's indicators for aggregate status counts. Turning the setting off restores text-only labels without removing configured icons; RPC output keeps state indicators static. Saved settings apply immediately to newly rendered widgets and dialogs.
67
+ When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker. Starting/running agents show the selected loader **before the original role icon**, never replacing it. Completed, paused, failed, and stopped agents show that loader family's corresponding static state icon before the role icon. Agents without a configured role icon still show their loader/state indicator. The one-line minimal widget uses the same family's indicators for aggregate status counts. Turning the setting off hides role icons without removing configured icons; portable loaders remain visible; RPC output keeps state indicators static. Saved settings apply immediately to newly rendered widgets and dialogs.
68
68
 
69
69
  All six bundled agents have [role-specific icons](default-agents.md#nerd-font-icons). Add or change an icon with **[labs] Icon** in `/agents types`, or the optional `icon` frontmatter field in [your own agent](custom-agents.md#icons-labs). Retained threads keep the icon from their saved agent definition.
70
70
 
71
71
  ## [labs] Loader style (`loaderStyle`)
72
72
 
73
- Choose **Circle** (default), **Braille**, or **Hourglass** in `/agents` settings and save with **Ctrl+S**, or set `"loaderStyle": "circle"`, `"braille"`, or `"hourglass"` in your settings file. Loaders are displayed when **[labs] Nerd Font icons** is enabled.
73
+ Choose a loader in `/agents` settings and save with **Ctrl+S**, or set `loaderStyle` in your settings file:
74
74
 
75
- The Labs preview shows every family's running animation frames and completed, paused, failed, and stopped icons, so you can compare all states before choosing. Starting uses the running animation. State indicators always precede the unchanged role icon; the selected family also applies to the minimal widget's counts. In non-animated output, active agents use the family's first frame.
75
+ | Style | Setting | Running frames | Requires Nerd Font |
76
+ | --- | --- | --- | --- |
77
+ | Circle | `circle` (saved default) | Circle slices | Yes |
78
+ | Braille | `braille` | ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏ | No (standard Unicode, not ASCII) |
79
+ | Hourglass | `hourglass` | Hourglass stages | Yes |
80
+ | ASCII | `ascii` | `\| / - \\` | No |
81
+ | ASCII Star | `ascii-star` | `+ x *` | No |
82
+ | ASCII Pulse | `ascii-pulse` | `= * -` | No |
83
+
84
+ With **[labs] Nerd Font icons** off, the picker shows only Braille and ASCII palettes. With it on, all palettes are available. Saved Circle/Hourglass preferences render as ASCII while Nerd Fonts are off, without changing the saved preference. ASCII palettes use `+`, `=`, `!`, and `#` for completed, paused, failed, and stopped states. The compact ASCII animations are inspired by [cli-spinners](https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json) (`line`, `star2`, and `toggle13`).
85
+
86
+ The Labs preview shows every family's running animation frames and completed, paused, failed, and stopped icons, so you can compare all states before choosing. Starting uses the running animation. State indicators precede the role icon when role icons are enabled; the selected family also applies to the minimal widget's counts. In non-animated output, active agents use the family's first frame.
76
87
 
77
88
  ## [labs] Cost display (`costDisplay`)
78
89
 
@@ -173,9 +184,38 @@ Lower it to keep the tree tidy. Raise it for long sessions with many agents. Whe
173
184
 
174
185
  ## Scope
175
186
 
176
- The dialog's scope field picks where to save: **global** or **trusted project**.
177
- Your selection is remembered across dialog reopenings, projects, and Pi restarts,
178
- even if you cancel. It is stored separately from manager settings in
179
- `<agentDir>/subagent-manager/ui-state.json`. Untrusted projects always use Global
180
- without overwriting your remembered choice. Existing project settings still
181
- override global defaults; switching scope does not change the values shown.
187
+ Settings are read in order: **built-in defaults → Global → trusted Current Project**.
188
+ All keys are optional. The dialog saves only values different from the lower layer,
189
+ so unchanged settings continue inheriting future global changes. Restoring defaults
190
+ is a draft edit; in Project scope it can explicitly override non-default global values.
191
+
192
+ Colored dots before each setting describe saved changes: an **accent dot** means
193
+ changed in Global relative to defaults; a **warning dot** means changed in Current
194
+ Project relative to effective global settings. Both dots appear when both layers
195
+ change that setting, even when the project restores the built-in default. Equal
196
+ values are not changes. Unsaved edits do not change the dots. Footer display groups
197
+ the provenance of its three settings; its submenu shows each separately.
198
+
199
+ The save scope is **Global** when no project settings file exists and **Current
200
+ Project** when one exists. It is determined independently for each project; the old
201
+ cross-project `ui-state.json` preference is no longer used by this dialog.
202
+ Untrusted projects always read and save Global only.
203
+
204
+ Changing scope opens a confirmation screen with **Cancel selected by default**:
205
+
206
+ - **Global → Current Project:** Confirm creates the project settings file as an
207
+ empty object (inheriting global). Unsaved edits are kept; Save and apply writes
208
+ them to Project. Future edits in this project use Project scope.
209
+ - **Current Project → Global:** Confirm deletes only this manager's project
210
+ settings file, discards unsaved edits, reloads global/default values immediately,
211
+ and routes future saves to Global. Project values are not copied into Global.
212
+ - **Cancel / Esc:** no files, values, or scope are changed.
213
+
214
+ Confirmed scope changes happen **immediately** and survive cancelling the outer
215
+ settings screen. Ordinary value edits still require **Save and apply**. Running
216
+ agents and retained threads are kept.
217
+
218
+ The dialog warns about invalid settings layers. Project saves are blocked until an
219
+ invalid Global layer is fixed, rather than persisting a default-based snapshot.
220
+ If settings layers change while the dialog is open, Save and scope transitions
221
+ refuse the stale draft: reopen settings to load the new values before editing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -649,8 +649,44 @@ export default function piSubagent(pi: ExtensionAPI): void {
649
649
  context = undefined;
650
650
  });
651
651
  const agentSubcommands = ["tree", "settings", "types", "import", "reload", "reap"] as const;
652
+ const spawnModes = ["fork", "fresh"] as const;
653
+ /** `/agents fork:<type> <task>` inherits the main conversation; `fresh:` starts with no context. */
654
+ const spawnFromCommand = async (
655
+ ctx: ExtensionContext,
656
+ mode: (typeof spawnModes)[number],
657
+ typeName: string,
658
+ task: string,
659
+ ) => {
660
+ if (limits.subagentMode === "off") {
661
+ ctx.ui.notify("Subagent Mode is off. Change it in /agents settings.", "warning");
662
+ return;
663
+ }
664
+ const current = requireManager();
665
+ if (!store.list().some((type) => type.name === typeName)) {
666
+ ctx.ui.notify(`Unknown agent type: ${typeName}`, "error");
667
+ return;
668
+ }
669
+ const base = typeName.replace(/[^A-Za-z0-9_-]/g, "-").replace(/^[^A-Za-z0-9]+/, "") || "agent";
670
+ const taken = new Set(current.list().map((thread) => thread.path));
671
+ const prefix = mode === "fork" ? "/root/" : "/";
672
+ let n = 1;
673
+ while (taken.has(`${prefix}${base}-${n}`)) n++;
674
+ const path = `${prefix}${base}-${n}`;
675
+ try {
676
+ await current.scope("/root").spawn({ path, type: typeName, task, wait: false });
677
+ persist();
678
+ refreshWidget(ctx);
679
+ ctx.ui.notify(
680
+ `Started ${typeName} (${mode === "fork" ? "forked context" : "fresh context"}) at ${path}`,
681
+ "info",
682
+ );
683
+ } catch (error) {
684
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
685
+ }
686
+ };
652
687
  pi.registerCommand("agents", {
653
- description: "Configure agent settings, import/edit definitions, or show the live tree",
688
+ description:
689
+ "Configure agent settings, show the live tree, or run /agents fork:<agent> | fresh:<agent> <task>",
654
690
  getArgumentCompletions: (argumentText) => {
655
691
  const text = argumentText.trimStart();
656
692
  const completed = text.match(/^(\S+)(\s+)([\s\S]*)$/);
@@ -662,9 +698,33 @@ export default function piSubagent(pi: ExtensionAPI): void {
662
698
  .filter((path) => path !== "/root");
663
699
  const matched = fuzzyFilter(paths, completed[3]!.trimStart(), (path) => path);
664
700
  if (matched.length === 0) return null;
665
- return matched.map((path) => ({ value: `tree ${path}`, label: path }));
701
+ return matched.map((path) => ({
702
+ value: `tree ${path}`,
703
+ label: path,
704
+ }));
666
705
  }
667
706
  if ((agentSubcommands as readonly string[]).includes(command)) return null;
707
+ if (/^(fork|fresh):/.test(command)) return null;
708
+ }
709
+ const lower = text.toLowerCase();
710
+ const colon = lower.indexOf(":");
711
+ // "fo", "fork", "fork:", "fork:wo" -> every matching `fork:<agent>` / `fresh:<agent>`.
712
+ if (lower === "f")
713
+ return spawnModes.map((mode) => ({ value: `${mode}:`, label: `${mode}:` }));
714
+ const modes = spawnModes.filter((mode) =>
715
+ colon >= 0 ? lower.slice(0, colon) === mode : lower.length >= 2 && mode.startsWith(lower),
716
+ );
717
+ if (modes.length) {
718
+ const names = store.list().map((type) => type.name);
719
+ const filter = colon >= 0 ? lower.slice(colon + 1) : "";
720
+ const matched = filter ? fuzzyFilter(names, filter, (name) => name) : names;
721
+ const out = modes.flatMap((mode) =>
722
+ matched.map((name) => ({
723
+ value: `${mode}:${name}`,
724
+ label: `${mode}:${name}`,
725
+ })),
726
+ );
727
+ if (out.length) return out;
668
728
  }
669
729
  const matched = fuzzyFilter([...agentSubcommands], text, (name) => name);
670
730
  if (matched.length === 0) return null;
@@ -672,7 +732,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
672
732
  },
673
733
  handler: async (args, ctx) => {
674
734
  const [command, ...rest] = args.trim().split(/\s+/);
675
- if (command === "import") {
735
+ const spawnMatch = args.trim().match(/^(fork|fresh):(\S+)(?:\s+([\s\S]*))?$/);
736
+ if (spawnMatch) {
737
+ const task = spawnMatch[3]?.trim();
738
+ if (!task)
739
+ ctx.ui.notify(`Usage: /agents ${spawnMatch[1]}:${spawnMatch[2]} <task>`, "warning");
740
+ else await spawnFromCommand(ctx, spawnMatch[1] as "fork" | "fresh", spawnMatch[2]!, task);
741
+ } else if (command === "import") {
676
742
  await importAgents(ctx, false);
677
743
  } else if (command === "types") {
678
744
  await editAgentTypes(ctx, store, limits.nerdFontIcons, {
@@ -747,7 +813,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
747
813
  );
748
814
  } else
749
815
  ctx.ui.notify(
750
- "Usage: /agents [tree [path] | settings | types | import | reload | reap]",
816
+ "Usage: /agents [tree [path] | settings | types | import | reload | reap | fork:<agent> <task> | fresh:<agent> <task>]",
751
817
  "warning",
752
818
  );
753
819
  },
@@ -3,6 +3,7 @@ import {
3
3
  closeSync,
4
4
  constants,
5
5
  fchmodSync,
6
+ linkSync,
6
7
  lstatSync,
7
8
  mkdirSync,
8
9
  openSync,
@@ -28,7 +29,7 @@ export type CostValue = (typeof COST_VALUES)[number];
28
29
  export const COST_ICONS = ["money", "coins", "wallet"] as const;
29
30
  export type CostIcon = (typeof COST_ICONS)[number];
30
31
 
31
- export const LOADER_STYLES = ["circle", "braille", "hourglass"] as const;
32
+ export const LOADER_STYLES = ["circle", "braille", "hourglass", "ascii", "ascii-star", "ascii-pulse"] as const;
32
33
  export type LoaderStyle = (typeof LOADER_STYLES)[number];
33
34
 
34
35
  export const TOOL_FILTERING_MODES = ["allowed", "all-except-blocked", "all"] as const;
@@ -120,7 +121,7 @@ function requirement(key: (typeof KEYS)[number]): string {
120
121
  if (key === "costDisplay") return "costDisplay must be pi-footer-event, pi-footer-status or pi-status";
121
122
  if (key === "costValue") return "costValue must be subagents or total";
122
123
  if (key === "costIcon") return "costIcon must be money, coins or wallet";
123
- if (key === "loaderStyle") return "loaderStyle must be circle, braille or hourglass";
124
+ if (key === "loaderStyle") return `loaderStyle must be one of: ${LOADER_STYLES.join(", ")}`;
124
125
  if (key === "toolFiltering") return "toolFiltering must be allowed, all-except-blocked or all";
125
126
  if (key === "modelSelection")
126
127
  return "modelSelection must be pick-first-available, pick-first-scoped or use-current";
@@ -222,82 +223,74 @@ function layer(base: string, segments: string[]): SettingsLayer {
222
223
  return { filePath: join(current, "settings.json"), directories };
223
224
  }
224
225
 
225
- function readLayerContent(entry: SettingsLayer): string | undefined {
226
+ function settingsFileExists(entry: SettingsLayer): boolean {
226
227
  for (const directory of entry.directories) {
227
228
  const stat = assertNotSymlinkPath(directory);
228
- if (!stat) return undefined;
229
+ if (!stat) return false;
229
230
  if (!stat.isDirectory())
230
231
  throw new Error(`Settings directory must be a directory: ${directory}`);
231
232
  }
232
233
  const stat = assertNotSymlinkPath(entry.filePath);
233
- if (!stat) return undefined;
234
+ if (!stat) return false;
234
235
  if (!stat.isFile())
235
236
  throw new Error(`Settings must be a regular file: ${entry.filePath}`);
236
- return readFileSync(entry.filePath, "utf8");
237
- }
238
-
239
- function readLayer(entry: SettingsLayer): Partial<ManagerSettings> | undefined {
240
- const content = readLayerContent(entry);
241
- return content === undefined ? undefined : parseSettings(content);
237
+ return true;
242
238
  }
243
239
 
244
240
  export type ManagerSaveScope = "user" | "project";
245
241
 
246
- function uiStateLayer(agentDir: string): SettingsLayer {
247
- const entry = layer(agentDir, ["subagent-manager"]);
248
- return { ...entry, filePath: join(dirname(entry.filePath), "ui-state.json") };
242
+ function detail(error: unknown): string {
243
+ return error instanceof Error ? error.message : String(error);
249
244
  }
250
245
 
251
- /** UI preference only: never participates in manager-settings precedence. */
252
- export function loadManagerSaveScope(options: {
246
+ export interface ManagerSettingsOptions {
247
+ cwd: string;
253
248
  agentDir: string;
254
249
  includeProject: boolean;
255
- }): ManagerSaveScope {
256
- if (!options.includeProject) return "user";
257
- try {
258
- const content = readLayerContent(uiStateLayer(options.agentDir));
259
- if (content !== undefined) {
260
- const state: unknown = JSON.parse(content);
261
- if (
262
- state && typeof state === "object" && !Array.isArray(state) &&
263
- "saveScope" in state && state.saveScope === "user"
264
- ) return "user";
265
- }
266
- } catch {
267
- // Missing, invalid or unsafe UI state must not prevent opening settings.
268
- }
269
- return "project";
270
- }
271
-
272
- export function saveManagerSaveScope(agentDir: string, scope: ManagerSaveScope): void {
273
- if (scope !== "user" && scope !== "project") throw new Error("Invalid settings scope");
274
- const entry = uiStateLayer(agentDir);
275
- ensureScopeDirectories(entry.directories);
276
- writeAtomically(entry, `${JSON.stringify({ saveScope: scope }, null, 2)}\n`);
277
250
  }
278
251
 
279
- function detail(error: unknown): string {
280
- return error instanceof Error ? error.message : String(error);
252
+ export interface ManagerSettingsLayers {
253
+ settings: ManagerSettings;
254
+ diagnostics: string[];
255
+ global: Partial<ManagerSettings>;
256
+ project: Partial<ManagerSettings>;
257
+ scope: ManagerSaveScope;
281
258
  }
282
259
 
283
- export function loadManagerSettings(options: {
284
- cwd: string;
285
- agentDir: string;
286
- includeProject: boolean;
287
- }): { settings: ManagerSettings; diagnostics: string[] } {
288
- const diagnostics: string[] = [];
289
- const settings: ManagerSettings = { ...DEFAULT_MANAGER_SETTINGS };
290
- const layers = [layer(options.agentDir, ["subagent-manager"])];
260
+ /** Validated layers retain provenance; save scope belongs to the current project. */
261
+ export function loadManagerSettingsLayers(options: ManagerSettingsOptions): ManagerSettingsLayers {
262
+ const result: ManagerSettingsLayers = {
263
+ settings: { ...DEFAULT_MANAGER_SETTINGS },
264
+ diagnostics: [],
265
+ global: {},
266
+ project: {},
267
+ scope: "user",
268
+ };
269
+ const layers: ["global" | "project", SettingsLayer][] = [
270
+ ["global", layer(options.agentDir, ["subagent-manager"])],
271
+ ];
291
272
  if (options.includeProject)
292
- layers.push(layer(options.cwd, [".pi", "agent", "subagent-manager"]));
293
- for (const entry of layers) {
273
+ layers.push(["project", layer(options.cwd, [".pi", "agent", "subagent-manager"])]);
274
+ for (const [scope, entry] of layers) {
294
275
  try {
295
- const parsed = readLayer(entry);
296
- if (parsed !== undefined) Object.assign(settings, parsed);
276
+ if (!settingsFileExists(entry)) continue;
277
+ // Malformed/unreadable regular project files still represent a save destination.
278
+ if (scope === "project") result.scope = "project";
279
+ const parsed = parseSettings(readFileSync(entry.filePath, "utf8"));
280
+ result[scope] = parsed;
281
+ Object.assign(result.settings, parsed);
297
282
  } catch (error) {
298
- diagnostics.push(`${entry.filePath}: ${detail(error)}`);
283
+ result.diagnostics.push(`${entry.filePath}: ${detail(error)}`);
299
284
  }
300
285
  }
286
+ return result;
287
+ }
288
+
289
+ export function loadManagerSettings(options: ManagerSettingsOptions): {
290
+ settings: ManagerSettings;
291
+ diagnostics: string[];
292
+ } {
293
+ const { settings, diagnostics } = loadManagerSettingsLayers(options);
301
294
  return { settings, diagnostics };
302
295
  }
303
296
 
@@ -360,7 +353,7 @@ function exclusiveCreateFlags(): number {
360
353
  return constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0);
361
354
  }
362
355
 
363
- function writeAtomically(entry: SettingsLayer, content: string): void {
356
+ function writeAtomically(entry: SettingsLayer, content: string, overwrite = true): void {
364
357
  const filePath = entry.filePath;
365
358
  const temporary = join(dirname(filePath), `.settings.${randomUUID()}.tmp`);
366
359
  let created = false;
@@ -380,7 +373,17 @@ function writeAtomically(entry: SettingsLayer, content: string): void {
380
373
  const tempStat = assertNotSymlinkPath(temporary);
381
374
  if (!tempStat?.isFile())
382
375
  throw new Error(`Settings must be a regular file: ${temporary}`);
383
- renameSync(temporary, filePath);
376
+ if (overwrite) renameSync(temporary, filePath);
377
+ else {
378
+ try {
379
+ // Linking a completed temporary file creates the destination without clobbering
380
+ // a settings file that appeared after the initial absence check.
381
+ linkSync(temporary, filePath);
382
+ } catch (error) {
383
+ if (errorCode(error) !== "EEXIST") throw error;
384
+ assertRegularFileOrAbsent(filePath);
385
+ }
386
+ }
384
387
  } finally {
385
388
  if (created) {
386
389
  try {
@@ -414,3 +417,72 @@ export function saveManagerSettings(options: {
414
417
  writeAtomically(entry, content);
415
418
  return entry.filePath;
416
419
  }
420
+
421
+ function assertExpectedLayers(current: ManagerSettingsLayers, expected: ManagerSettingsLayers): void {
422
+ if (
423
+ current.scope !== expected.scope ||
424
+ KEYS.some((key) => current.global[key] !== expected.global[key] ||
425
+ current.project[key] !== expected.project[key]) ||
426
+ current.diagnostics.length !== expected.diagnostics.length ||
427
+ current.diagnostics.some((diagnostic, index) => diagnostic !== expected.diagnostics[index])
428
+ ) {
429
+ throw new Error("Settings changed on disk. Reopen settings before saving or switching scope to avoid stale inherited values.");
430
+ }
431
+ }
432
+
433
+ /** Persist only values that change the selected scope's inherited settings. */
434
+ export function saveManagerOverrides(options: ManagerSettingsOptions & {
435
+ scope: ManagerSaveScope;
436
+ settings: ManagerSettings;
437
+ expectedLayers?: ManagerSettingsLayers;
438
+ }): string {
439
+ if (options.scope !== "user" && options.scope !== "project")
440
+ throw new Error("Invalid settings scope");
441
+ if (options.scope === "project" && !options.includeProject)
442
+ throw new Error("Project settings are not enabled/trusted");
443
+ // Validate the complete draft before creating directories or modifying files.
444
+ const parsed = parseSettings(serializedSettings(options.settings));
445
+ const current = loadManagerSettingsLayers(options);
446
+ if (options.expectedLayers) assertExpectedLayers(current, options.expectedLayers);
447
+ if (options.scope === "project") {
448
+ const globalPath = layer(options.agentDir, ["subagent-manager"]).filePath;
449
+ const globalDiagnostics = current.diagnostics.filter((diagnostic) => diagnostic.startsWith(`${globalPath}:`));
450
+ if (globalDiagnostics.length > 0)
451
+ throw new Error(`Cannot save project overrides while global settings are invalid. Fix global settings and reopen settings. ${globalDiagnostics.join("; ")}`);
452
+ }
453
+ const inherited = options.scope === "user"
454
+ ? DEFAULT_MANAGER_SETTINGS
455
+ : { ...DEFAULT_MANAGER_SETTINGS, ...current.global };
456
+ const overrides = Object.fromEntries(
457
+ KEYS.filter((key) => parsed[key] !== inherited[key]).map((key) => [key, parsed[key]]),
458
+ );
459
+ const entry = options.scope === "user"
460
+ ? layer(options.agentDir, ["subagent-manager"])
461
+ : layer(options.cwd, [".pi", "agent", "subagent-manager"]);
462
+ ensureScopeDirectories(entry.directories);
463
+ writeAtomically(entry, `${JSON.stringify(overrides, null, 2)}\n`);
464
+ return entry.filePath;
465
+ }
466
+
467
+ /** Confirmed scope transition: create an empty project layer or remove only its file. */
468
+ export function setManagerProjectSettings(options: ManagerSettingsOptions & {
469
+ enabled: boolean;
470
+ expectedLayers?: ManagerSettingsLayers;
471
+ }): string {
472
+ if (!options.includeProject) throw new Error("Project settings are not enabled/trusted");
473
+ if (typeof options.enabled !== "boolean") throw new Error("Invalid project settings state");
474
+ if (options.expectedLayers)
475
+ assertExpectedLayers(loadManagerSettingsLayers(options), options.expectedLayers);
476
+ const entry = layer(options.cwd, [".pi", "agent", "subagent-manager"]);
477
+ const present = settingsFileExists(entry);
478
+ if (options.enabled) {
479
+ if (!present) {
480
+ ensureScopeDirectories(entry.directories);
481
+ writeAtomically(entry, "{}\n", false);
482
+ }
483
+ } else if (present) {
484
+ // Recheck owned paths immediately before deletion; malformed JSON is removable.
485
+ if (settingsFileExists(entry)) unlinkSync(entry.filePath);
486
+ }
487
+ return entry.filePath;
488
+ }
@@ -1,4 +1,4 @@
1
- import type { LoaderStyle } from "../prefs/settings.ts";
1
+ import { LOADER_STYLES, type LoaderStyle } from "../prefs/settings.ts";
2
2
  import type { ThreadView } from "../types.ts";
3
3
 
4
4
  export const AGENT_PROGRESS_INTERVAL = 180;
@@ -10,12 +10,14 @@ export const AGENT_LOADERS: Record<
10
10
  LoaderStyle,
11
11
  {
12
12
  label: string;
13
+ requiresNerdFont: boolean;
13
14
  frames: readonly string[];
14
15
  states: Record<SettledState, string>;
15
16
  }
16
17
  > = {
17
18
  circle: {
18
19
  label: "Circle",
20
+ requiresNerdFont: true,
19
21
  // Nerd Fonts md-circle-slice-1..8, check-circle, pause-circle, close-circle, stop-circle.
20
22
  frames: Array.from({ length: 8 }, (_, index) => String.fromCodePoint(0xf0a9e + index)),
21
23
  states: {
@@ -27,17 +29,49 @@ export const AGENT_LOADERS: Record<
27
29
  },
28
30
  braille: {
29
31
  label: "Braille",
32
+ requiresNerdFont: false,
30
33
  frames: Array.from("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
31
34
  states: { completed: "✓", paused: "Ⅱ", failed: "×", stopped: "■" },
32
35
  },
33
36
  hourglass: {
34
37
  label: "Hourglass",
38
+ requiresNerdFont: true,
35
39
  // Nerd Fonts fa-hourglass-start/half/end, check-square, pause, times-circle, stop.
36
40
  frames: ["\uf251", "\uf252", "\uf253"],
37
41
  states: { completed: "\uf14a", paused: "\uf04c", failed: "\uf057", stopped: "\uf04d" },
38
42
  },
43
+ // Compact ASCII palettes inspired by cli-spinners line, star2 and toggle13.
44
+ // https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json
45
+ ascii: {
46
+ label: "ASCII",
47
+ requiresNerdFont: false,
48
+ frames: ["|", "/", "-", "\\"],
49
+ states: { completed: "+", paused: "=", failed: "!", stopped: "#" },
50
+ },
51
+ "ascii-star": {
52
+ label: "ASCII Star",
53
+ requiresNerdFont: false,
54
+ frames: ["+", "x", "*"],
55
+ states: { completed: "+", paused: "=", failed: "!", stopped: "#" },
56
+ },
57
+ "ascii-pulse": {
58
+ label: "ASCII Pulse",
59
+ requiresNerdFont: false,
60
+ frames: ["=", "*", "-"],
61
+ states: { completed: "+", paused: "=", failed: "!", stopped: "#" },
62
+ },
39
63
  };
40
64
 
65
+ /** Filter the picker without exposing private-use glyphs to ordinary fonts. */
66
+ export function availableLoaderStyles(nerdFontIcons: boolean): LoaderStyle[] {
67
+ return LOADER_STYLES.filter((style) => nerdFontIcons || !AGENT_LOADERS[style].requiresNerdFont);
68
+ }
69
+
70
+ /** Preserve saved preferences, but render a portable fallback when Nerd Fonts are off. */
71
+ export function effectiveLoaderStyle(style: LoaderStyle, nerdFontIcons: boolean): LoaderStyle {
72
+ return !nerdFontIcons && AGENT_LOADERS[style].requiresNerdFont ? "ascii" : style;
73
+ }
74
+
41
75
  /** RPC/non-animated hosts use the first running frame and all settled indicators. */
42
76
  export function agentProgressIcon(
43
77
  thread: Pick<ThreadView, "state">,
@@ -46,8 +80,7 @@ export function agentProgressIcon(
46
80
  animate = true,
47
81
  loaderStyle: LoaderStyle = "circle",
48
82
  ): string | undefined {
49
- if (!nerdFontIcons) return undefined;
50
- const loader = AGENT_LOADERS[loaderStyle];
83
+ const loader = AGENT_LOADERS[effectiveLoaderStyle(loaderStyle, nerdFontIcons)];
51
84
  if (thread.state === "starting" || thread.state === "running") {
52
85
  const index = animate ? Math.floor(Math.max(0, now) / AGENT_PROGRESS_INTERVAL) : 0;
53
86
  return loader.frames[index % loader.frames.length];
@@ -56,8 +89,10 @@ export function agentProgressIcon(
56
89
  }
57
90
 
58
91
  /** Restrict the separate label prefix to trusted, single built-in loader glyphs. */
59
- export function isAgentLoaderGlyph(glyph: string): boolean {
92
+ export function isAgentLoaderGlyph(glyph: string, nerdFontIcons = true): boolean {
60
93
  return Object.values(AGENT_LOADERS).some(
61
- (loader) => loader.frames.includes(glyph) || Object.values(loader.states).includes(glyph),
94
+ (loader) =>
95
+ (nerdFontIcons || !loader.requiresNerdFont) &&
96
+ (loader.frames.includes(glyph) || Object.values(loader.states).includes(glyph)),
62
97
  );
63
98
  }
@@ -30,13 +30,13 @@ export function footerUsage(entries: readonly SessionEntry[]) {
30
30
  }
31
31
  export const COST_WIDGET_ID = "subagent_cost";
32
32
  export const COST_WIDGET_EVENT = "pi-footer:update-widget";
33
- export const COST_ICON = "\uf0d6";
33
+ export const COST_ICON = "\uf0d6"; // nf-fa-money_bill
34
34
 
35
35
  export function costIconGlyph(icon: CostIcon, nerdFontIcons: boolean): string {
36
36
  const glyphs = {
37
37
  money: { emoji: "💵", nerd: COST_ICON },
38
- coins: { emoji: "🪙", nerd: "\u{f0512}" },
39
- wallet: { emoji: "👛", nerd: "\u{f055d}" },
38
+ coins: { emoji: "🪙", nerd: "\uede8" }, // nf-fa-coins
39
+ wallet: { emoji: "👛", nerd: "\uee1e" }, // nf-fa-wallet
40
40
  };
41
41
  return glyphs[icon][nerdFontIcons ? "nerd" : "emoji"];
42
42
  }
package/src/ui/dialog.ts CHANGED
@@ -191,6 +191,7 @@ export class DialogMenu {
191
191
  selectedId?: string,
192
192
  readonly footer = "↑↓ navigate · Enter select · Esc close",
193
193
  private saveId?: string,
194
+ private renderLegend?: (theme: Theme) => string,
194
195
  ) {
195
196
  const index = rows.findIndex((row) => row.id === selectedId);
196
197
  if (index >= 0) this.selected = index;
@@ -224,11 +225,16 @@ export class DialogMenu {
224
225
  render(width: number): string[] {
225
226
  const height = dialogHeight(this.host);
226
227
  const inner = Math.max(0, width - 4);
228
+ const legend = this.renderLegend
229
+ ? wrapTextWithAnsi(this.renderLegend(this.theme), Math.max(1, inner - 1))
230
+ .slice(0, Math.max(0, height - 8))
231
+ .map((line) => ` ${line}`)
232
+ : [];
227
233
  const help = (this.rows[this.selected]?.help ?? "")
228
234
  .split(/\r\n?|\n/)
229
235
  .flatMap((line) => wrapTextWithAnsi(dialogText(line), Math.max(1, inner - 1)))
230
- .slice(0, Math.max(1, height - 7));
231
- this.viewport = Math.max(1, height - 6 - help.length);
236
+ .slice(0, Math.max(1, height - 7 - legend.length));
237
+ this.viewport = Math.max(1, height - 6 - help.length - legend.length);
232
238
  const start = Math.max(
233
239
  0,
234
240
  Math.min(
@@ -262,6 +268,12 @@ export class DialogMenu {
262
268
  "",
263
269
  ...help.map((line) => this.theme.fg("muted", ` ${line}`)),
264
270
  ];
271
+ if (legend.length) {
272
+ const budget = Math.max(0, height - 4 - legend.length);
273
+ body.length = Math.min(body.length, budget);
274
+ while (body.length < budget) body.push("");
275
+ body.push(...legend);
276
+ }
265
277
  return frameDialog(
266
278
  this.theme,
267
279
  width,
@@ -286,7 +298,7 @@ export async function dialogMenu(
286
298
  ctx: ExtensionContext,
287
299
  title: string,
288
300
  rows: DialogRow[],
289
- options: { selectedId?: string; footer?: string; saveId?: string } = {},
301
+ options: { selectedId?: string; footer?: string; saveId?: string; renderLegend?: (theme: Theme) => string } = {},
290
302
  ): Promise<string | undefined> {
291
303
  return ctx.ui.custom(
292
304
  (host, theme, _keys, done) =>
@@ -299,6 +311,7 @@ export async function dialogMenu(
299
311
  options.selectedId,
300
312
  options.footer,
301
313
  options.saveId,
314
+ options.renderLegend,
302
315
  ),
303
316
  DIALOG_OPTIONS,
304
317
  );
@@ -210,11 +210,7 @@ export class LiveAgentView {
210
210
 
211
211
  private syncProgress(): void {
212
212
  const state = this.snapshot?.thread?.state;
213
- const active =
214
- this.nerdFontIcons &&
215
- !this.disposed &&
216
- !this.error &&
217
- (state === "starting" || state === "running");
213
+ const active = !this.disposed && !this.error && (state === "starting" || state === "running");
218
214
  if (!active) {
219
215
  if (this.progressTimer !== undefined) clearInterval(this.progressTimer);
220
216
  this.progressTimer = undefined;
@@ -102,6 +102,7 @@ export class OrderedModelEditorComponent extends Container {
102
102
  private readonly searchInput = new Input({ placeholder: "Search models" });
103
103
  private draft: string[];
104
104
  private pickerQuery = "";
105
+ private searching = false;
105
106
  private currentItems: ModelSelectItem[] = [];
106
107
  private selectList = new SelectList([], 1, getSelectListTheme(), MODEL_EDITOR_LAYOUT);
107
108
  private _focused = false;
@@ -133,14 +134,12 @@ export class OrderedModelEditorComponent extends Container {
133
134
  "muted",
134
135
  this.withScopeWarning(
135
136
  this.suggestedScores.size
136
- ? "Selected first; suggested matches scoped first, then other models; the rest A–Z. Type to search."
137
- : "Selected first. Search by provider/id or model name; other models A–Z.",
137
+ ? "Selected first; suggested matches scoped first, then other models; the rest A–Z. / to search."
138
+ : "Selected first. / to search by provider/id or model name; other models A–Z.",
138
139
  ),
139
140
  ),
140
141
  );
141
- this.footerText.setText(
142
- this.theme.fg("dim", "↑↓ select · Enter toggle · Ctrl+↑↓ reorder · Ctrl+S done · Esc cancel"),
143
- );
142
+ this.updateFooter();
144
143
  this.addChild(this.searchInput);
145
144
  this.refreshPickerList();
146
145
  }
@@ -151,7 +150,7 @@ export class OrderedModelEditorComponent extends Container {
151
150
 
152
151
  set focused(value: boolean) {
153
152
  this._focused = value;
154
- this.searchInput.focused = value;
153
+ this.searchInput.focused = value && this.searching;
155
154
  }
156
155
 
157
156
  getMode(): "picker" {
@@ -235,8 +234,13 @@ export class OrderedModelEditorComponent extends Container {
235
234
  this.onDone([...this.draft]);
236
235
  return;
237
236
  }
238
- const earlier = matchesKey(keyData, Key.ctrl("up"));
239
- const later = matchesKey(keyData, Key.ctrl("down"));
237
+ if (matchesKey(keyData, Key.tab) || (!this.searching && keyData === "/")) {
238
+ this.setSearching(!this.searching);
239
+ this.tui.requestRender();
240
+ return;
241
+ }
242
+ const earlier = !this.searching && keyData === "w";
243
+ const later = !this.searching && keyData === "s";
240
244
  if (earlier || later) {
241
245
  const selected = this.selectList.getSelectedItem()?.value;
242
246
  const index = selected === undefined ? -1 : this.draft.indexOf(selected);
@@ -261,6 +265,7 @@ export class OrderedModelEditorComponent extends Container {
261
265
  this.searchInput.handleInput(keyData);
262
266
  const nextQuery = this.searchInput.getValue();
263
267
  if (nextQuery !== this.pickerQuery) {
268
+ this.setSearching(true);
264
269
  this.pickerQuery = nextQuery;
265
270
  // Keep selected preferences visible, but focus the first search result
266
271
  // so typing a query and pressing Enter still adds the matching model.
@@ -270,6 +275,23 @@ export class OrderedModelEditorComponent extends Container {
270
275
  this.tui.requestRender();
271
276
  }
272
277
 
278
+ private setSearching(value: boolean): void {
279
+ this.searching = value;
280
+ this.searchInput.focused = this._focused && value;
281
+ this.updateFooter();
282
+ }
283
+
284
+ private updateFooter(): void {
285
+ this.footerText.setText(
286
+ this.theme.fg(
287
+ "dim",
288
+ this.searching
289
+ ? "↑↓ select · Enter toggle · Tab browse · Ctrl+S done · Esc cancel"
290
+ : "↑↓ select · Enter toggle · w/s reorder · / search · Ctrl+S done · Esc cancel",
291
+ ),
292
+ );
293
+ }
294
+
273
295
  private refreshPickerList(selectedValue?: string, focusSearchResult = false): void {
274
296
  const previousIndex = this.currentItems.findIndex(
275
297
  (item) => item.value === this.selectList.getSelectedItem()?.value,
@@ -1,10 +1,11 @@
1
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
2
2
  import type { ConfigStore } from "../prefs/config.ts";
3
3
  import {
4
4
  canOpenDialog,
5
5
  dialogInput,
6
6
  dialogMenu,
7
7
  withDialogSession,
8
+ type DialogRow,
8
9
  } from "./dialog.ts";
9
10
  import {
10
11
  DEFAULT_MANAGER_SETTINGS,
@@ -14,9 +15,9 @@ import {
14
15
  type CostValue,
15
16
  LOADER_STYLES,
16
17
  type LoaderStyle,
17
- loadManagerSaveScope,
18
- saveManagerSaveScope,
19
- saveManagerSettings,
18
+ loadManagerSettingsLayers,
19
+ saveManagerOverrides,
20
+ setManagerProjectSettings,
20
21
  type ManagerSettings,
21
22
  type ModelSelectionMode,
22
23
  type SubagentMode,
@@ -25,7 +26,7 @@ import {
25
26
  } from "../prefs/settings.ts";
26
27
  import { editAgentTypes } from "./ui.ts";
27
28
  import type { ToolEditorOptions } from "./tool-picker.ts";
28
- import { AGENT_LOADERS } from "./agent-loader.ts";
29
+ import { AGENT_LOADERS, availableLoaderStyles, effectiveLoaderStyle } from "./agent-loader.ts";
29
30
  import { costIconGlyph } from "./cost-footer.ts";
30
31
 
31
32
  const LOADER_OPTIONS = LOADER_STYLES.map((id) => {
@@ -34,7 +35,7 @@ const LOADER_OPTIONS = LOADER_STYLES.map((id) => {
34
35
  id,
35
36
  label: loader.label,
36
37
  value: `${loader.frames.join(" ")} · ${Object.values(loader.states).join(" ")}`,
37
- help: `Each row: all starting/running frames · completed, paused, failed, stopped.\nStarting/running: ${loader.frames.join(" ")}\nCompleted: ${loader.states.completed} · Paused: ${loader.states.paused}\nFailed: ${loader.states.failed} · Stopped: ${loader.states.stopped}\nRequires [labs] Nerd Font icons On. The loader appears before the unchanged role icon.`,
38
+ help: `Each row: all starting/running frames · completed, paused, failed, stopped.\nStarting/running: ${loader.frames.join(" ")}\nCompleted: ${loader.states.completed} · Paused: ${loader.states.paused}\nFailed: ${loader.states.failed} · Stopped: ${loader.states.stopped}\n${loader.requiresNerdFont ? "Requires [labs] Nerd Font icons On." : id === "braille" ? "Standard Unicode Braille; no Nerd Font needed." : "ASCII only; no special font needed."} The loader appears before the role icon when enabled.`,
38
39
  };
39
40
  });
40
41
 
@@ -149,11 +150,34 @@ const COST_VALUE_OPTIONS = [
149
150
 
150
151
  const COST_ICON_LABELS = { money: "Money", coins: "Coins", wallet: "Wallet" } as const;
151
152
 
153
+ type SettingsLayers = ReturnType<typeof loadManagerSettingsLayers>;
154
+
155
+ /** Persisted changes, not unsaved draft values; theme styling is computed on render. */
156
+ function withProvenance(row: DialogRow, keys: (keyof ManagerSettings)[], layers: SettingsLayers): DialogRow {
157
+ const globalChanged = keys.some((key) => layers.global[key] !== undefined &&
158
+ layers.global[key] !== DEFAULT_MANAGER_SETTINGS[key]);
159
+ const projectChanged = keys.some((key) => layers.project[key] !== undefined &&
160
+ layers.project[key] !== (layers.global[key] ?? DEFAULT_MANAGER_SETTINGS[key]));
161
+ return {
162
+ ...row,
163
+ renderLabel: (label, theme) =>
164
+ (globalChanged ? theme.fg("accent", "●") + " " : "") +
165
+ (projectChanged ? theme.fg("warning", "●") + " " : "") + label.replace(/^\[labs\] /, ""),
166
+ help: `${row.label}\n${row.help ?? ""}`,
167
+ };
168
+ }
169
+
170
+ function provenanceLegend(theme: Theme): string {
171
+ const global = theme.fg("accent", "●");
172
+ const project = theme.fg("warning", "●");
173
+ return theme.fg("muted", "Saved: ") + `${global} Global · ${project} Current Project · ${global} ${project} Both`;
174
+ }
175
+
152
176
  /** Edits the shared draft; only the outer settings screen saves or applies it. */
153
- async function configureFooterDisplay(ctx: ExtensionCommandContext, draft: ManagerSettings): Promise<void> {
177
+ async function configureFooterDisplay(ctx: ExtensionCommandContext, draft: ManagerSettings, layers: SettingsLayers): Promise<void> {
154
178
  let selectedId: string | undefined;
155
179
  while (true) {
156
- const action = await dialogMenu(ctx, "[labs] Footer display", [
180
+ const action = await dialogMenu(ctx, "[labs] Footer display", ([
157
181
  {
158
182
  id: "location",
159
183
  label: "Location",
@@ -173,7 +197,10 @@ async function configureFooterDisplay(ctx: ExtensionCommandContext, draft: Manag
173
197
  help: `Choose a money-related ${draft.nerdFontIcons ? "Nerd Font" : "emoji"} icon. The family follows [labs] Nerd Font icons.`,
174
198
  },
175
199
  { id: "back", label: "Back", help: "Return to settings. Save and apply there to commit these changes." },
176
- ], { selectedId, footer: "↑↓/Tab navigate · Enter edit · Esc back" });
200
+ ] as DialogRow[]).map((row) => {
201
+ const key = ({ location: "costDisplay", value: "costValue", icon: "costIcon" } as Record<string, keyof ManagerSettings>)[row.id];
202
+ return key ? withProvenance(row, [key], layers) : row;
203
+ }), { selectedId, renderLegend: provenanceLegend, footer: "↑↓/Tab navigate · Enter edit · Esc back" });
177
204
  if (!action || action === "back") return;
178
205
  selectedId = action;
179
206
  if (action === "location") {
@@ -244,18 +271,26 @@ async function configureAgentsDialog(
244
271
  apply(): void;
245
272
  },
246
273
  ): Promise<void> {
247
- let draft = { ...options.settings };
248
- let scope = loadManagerSaveScope({
274
+ const readLayers = () => loadManagerSettingsLayers({
275
+ cwd: ctx.cwd,
249
276
  agentDir: options.agentDir,
250
277
  includeProject: ctx.isProjectTrusted(),
251
278
  });
279
+ let layers = readLayers();
280
+ const reportDiagnostics = () => {
281
+ for (const diagnostic of layers.diagnostics) ctx.ui.notify(diagnostic, "warning");
282
+ };
283
+ reportDiagnostics();
284
+ let baseline = { ...layers.settings };
285
+ let draft = { ...baseline };
286
+ let scope = layers.scope;
252
287
  let selectedId: string | undefined;
253
288
  while (true) {
254
- const dirty = JSON.stringify(draft) !== JSON.stringify(options.settings);
289
+ const dirty = JSON.stringify(draft) !== JSON.stringify(baseline);
255
290
  const action = await dialogMenu(
256
291
  ctx,
257
292
  `Agents settings${dirty ? " · unsaved" : ""}`,
258
- [
293
+ ([
259
294
  {
260
295
  id: "subagentMode",
261
296
  label: "Subagent Mode",
@@ -294,13 +329,13 @@ async function configureAgentsDialog(
294
329
  id: "nerdFontIcons",
295
330
  label: "[labs] Nerd Font icons",
296
331
  value: draft.nerdFontIcons ? "On" : "Off",
297
- help: "Experimental: display each agent type’s optional icon, preceded by its loader/state indicator.\nRequires a Nerd Font configured in your terminal; otherwise glyphs may appear as boxes.\nOff by default. Save and apply to update the widget immediately.",
332
+ help: "Experimental: display each agent type’s optional Nerd Font icon and unlock Nerd Font loader palettes.\nRequires a Nerd Font configured in your terminal; otherwise glyphs may appear as boxes.\nOff by default. Braille and ASCII loaders work with this Off. Save and apply to update immediately.",
298
333
  },
299
334
  {
300
335
  id: "loaderStyle",
301
336
  label: "[labs] Loader style",
302
- value: AGENT_LOADERS[draft.loaderStyle].label,
303
- help: "Choose Circle, Braille or Hourglass. Preview every animation frame and settled state for all families.\nRequires [labs] Nerd Font icons On. Circle is the default.\nSave and apply to update the widget immediately.",
337
+ value: AGENT_LOADERS[effectiveLoaderStyle(draft.loaderStyle, draft.nerdFontIcons)].label,
338
+ help: "Preview every animation frame and settled state.\nNerd Fonts Off: Braille (standard Unicode), ASCII, ASCII Star and ASCII Pulse. On: all palettes, including Circle and Hourglass.\nNerd-only saved styles fall back to ASCII while Nerd Fonts are off. Save and apply to update immediately.",
304
339
  },
305
340
  {
306
341
  id: "subagentExtensions",
@@ -318,7 +353,7 @@ async function configureAgentsDialog(
318
353
  id: "scope",
319
354
  label: "Save scope",
320
355
  value: scope === "user" ? "Global" : "Current Project",
321
- help: "Global: save all values shown as your defaults for every project. Existing project settings still override them, including here.\nCurrent Project: save all values shown for this project only, overriding your global defaults here. Other projects are unchanged. Requires a trusted project.\nSwitching scope only changes where you save, not the values shown. Your choice is remembered across projects and restarts, even if you cancel.",
356
+ help: "Global: save overrides of built-in defaults for all projects.\nCurrent Project: save overrides of global settings for this trusted project.\nSwitching requires confirmation: enabling Project creates its settings file; switching to Global deletes it and discards unsaved edits. Confirmed scope changes happen immediately, even if you later cancel.",
322
357
  },
323
358
  {
324
359
  id: "types",
@@ -336,17 +371,23 @@ async function configureAgentsDialog(
336
371
  label: "Save and apply",
337
372
  value: dirty ? "(changes)" : undefined,
338
373
  valueColor: dirty ? "warning" as const : undefined,
339
- help: "Save all values to the selected scope and reload settings now.\nProject overrides still take precedence.\nRunning agents and retained sessions are kept.",
374
+ help: "Save only overrides to the selected scope and reload settings now.\nUnchanged values inherit from the lower layer.\nRunning agents and retained sessions are kept.",
340
375
  },
341
376
  {
342
377
  id: "cancel",
343
378
  label: "Cancel",
344
379
  help: "Close without saving manager settings.",
345
380
  },
346
- ],
381
+ ] as DialogRow[]).map((row) => {
382
+ const keys = row.id === "costDisplay"
383
+ ? ["costDisplay", "costValue", "costIcon"] as (keyof ManagerSettings)[]
384
+ : row.id in DEFAULT_MANAGER_SETTINGS ? [row.id as keyof ManagerSettings] : [];
385
+ return keys.length ? withProvenance(row, keys, layers) : row;
386
+ }),
347
387
  {
348
388
  selectedId,
349
389
  saveId: "save",
390
+ renderLegend: provenanceLegend,
350
391
  footer: "↑↓/Tab navigate · Enter edit · Ctrl+S save · Esc cancel",
351
392
  },
352
393
  );
@@ -396,14 +437,18 @@ async function configureAgentsDialog(
396
437
  if (WIDGET_MODE_OPTIONS.some((option) => option.id === mode))
397
438
  draft.widgetMode = mode as WidgetMode;
398
439
  } else if (action === "costDisplay") {
399
- await configureFooterDisplay(ctx, draft);
440
+ await configureFooterDisplay(ctx, draft, layers);
400
441
  } else if (action === "nerdFontIcons") {
401
442
  draft.nerdFontIcons = !draft.nerdFontIcons;
402
443
  } else if (action === "loaderStyle") {
403
- const style = await dialogMenu(ctx, "[labs] Loader style", LOADER_OPTIONS, {
404
- selectedId: draft.loaderStyle,
405
- });
406
- if (LOADER_STYLES.includes(style as LoaderStyle)) draft.loaderStyle = style as LoaderStyle;
444
+ const styles = availableLoaderStyles(draft.nerdFontIcons);
445
+ const style = await dialogMenu(
446
+ ctx,
447
+ "[labs] Loader style",
448
+ LOADER_OPTIONS.filter((option) => styles.includes(option.id)),
449
+ { selectedId: effectiveLoaderStyle(draft.loaderStyle, draft.nerdFontIcons) },
450
+ );
451
+ if (styles.includes(style as LoaderStyle)) draft.loaderStyle = style as LoaderStyle;
407
452
  } else if (action === "subagentExtensions") {
408
453
  draft.subagentExtensions = !draft.subagentExtensions;
409
454
  } else if (action === "finalRecap") {
@@ -416,8 +461,33 @@ async function configureAgentsDialog(
416
461
  );
417
462
  else {
418
463
  const nextScope = scope === "user" ? "project" : "user";
419
- saveManagerSaveScope(options.agentDir, nextScope);
464
+ const message = nextScope === "project"
465
+ ? "Create project file now; outer Cancel cannot undo.\nThis will create this project's settings.json. Further changes will be saved there. Unsaved edits are kept until Save and apply."
466
+ : "Delete project file now. Discard edits. No undo.\nUnsaved edits will be discarded. Outer Cancel cannot undo. We reload global settings; further changes are saved globally.";
467
+ const confirmation = await dialogMenu(ctx,
468
+ nextScope === "project" ? "Enable project settings?" : "Clear project settings and use Global?",
469
+ [
470
+ { id: "confirm", label: "Confirm", help: message },
471
+ { id: "cancel", label: "Cancel", help: message + "\nCancel leaves files, scope and unsaved edits unchanged." },
472
+ ],
473
+ { selectedId: "cancel", footer: "↑↓/Tab choose · Enter select · Esc cancel" },
474
+ );
475
+ if (confirmation !== "confirm") continue;
476
+ setManagerProjectSettings({
477
+ cwd: ctx.cwd,
478
+ agentDir: options.agentDir,
479
+ includeProject: ctx.isProjectTrusted(),
480
+ enabled: nextScope === "project",
481
+ expectedLayers: layers,
482
+ });
483
+ layers = readLayers();
484
+ reportDiagnostics();
420
485
  scope = nextScope;
486
+ if (scope === "user") {
487
+ baseline = { ...layers.settings };
488
+ draft = { ...baseline };
489
+ options.apply();
490
+ }
421
491
  }
422
492
  } else if (action === "defaults") draft = { ...DEFAULT_MANAGER_SETTINGS };
423
493
  else if (action === "types") {
@@ -427,16 +497,17 @@ async function configureAgentsDialog(
427
497
  });
428
498
  options.store.reload();
429
499
  } else if (action === "save") {
430
- const file = saveManagerSettings({
500
+ const file = saveManagerOverrides({
431
501
  cwd: ctx.cwd,
432
502
  agentDir: options.agentDir,
433
503
  includeProject: ctx.isProjectTrusted(),
434
504
  scope,
435
505
  settings: draft,
506
+ expectedLayers: layers,
436
507
  });
437
508
  options.apply();
438
509
  ctx.ui.notify(
439
- `Saved ${file}. Settings reloaded; project overrides take precedence.`,
510
+ `Saved ${file}. Settings reloaded; unchanged values inherit from the lower layer.`,
440
511
  "info",
441
512
  );
442
513
  return;
@@ -139,7 +139,6 @@ export class StatusDialog {
139
139
  private syncRefresh(): void {
140
140
  if (!this.refreshing) return;
141
141
  const delay =
142
- this.nerdFontIcons &&
143
142
  this.service
144
143
  .list()
145
144
  .some(
package/src/ui/ui.ts CHANGED
@@ -92,7 +92,7 @@ export function agentTypeLabel(
92
92
  const role =
93
93
  nerdFontIcons && typeof icon === "string" && /^\p{Co}$/u.test(icon) ? `${icon} ` : "";
94
94
  const progress =
95
- nerdFontIcons && loaderIcon && isAgentLoaderGlyph(loaderIcon) ? `${loaderIcon} ` : "";
95
+ loaderIcon && isAgentLoaderGlyph(loaderIcon, nerdFontIcons) ? `${loaderIcon} ` : "";
96
96
  return `${progress}${role}${sanitizeText(type)}`;
97
97
  }
98
98
 
@@ -460,11 +460,8 @@ export function updateWidget(
460
460
  "pi-subagent",
461
461
  (tui) => {
462
462
  let timer: ReturnType<typeof setInterval> | undefined;
463
- if (snapshot.some(isLive) && (mode === "full" || nerdFontIcons)) {
464
- timer = setInterval(
465
- () => tui.requestRender(),
466
- nerdFontIcons ? AGENT_PROGRESS_INTERVAL : 1000,
467
- );
463
+ if (snapshot.some(isLive)) {
464
+ timer = setInterval(() => tui.requestRender(), AGENT_PROGRESS_INTERVAL);
468
465
  timer.unref();
469
466
  }
470
467
  return {