@ferris1225/pi-subagents 6.0.5 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,189 +1,106 @@
1
- /** Role-based settings. Each field saves independently; Esc always goes back. */
1
+ /** Independent model and thinking preferences for each built-in role. */
2
2
 
3
- import { stat } from "node:fs/promises";
4
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
4
  import {
6
- BUILTIN_AGENT_NAMES,
7
- DEFAULT_CONFIG,
8
- agentProfile,
9
- errorMessage,
10
- getConfigPath,
11
- loadConfig,
12
- roleThinkingLevel,
13
- saveConfig,
14
- type SubagentsConfig,
15
- type ThinkingLevel,
5
+ BUILTIN_AGENT_NAMES, DEFAULT_AGENT_SETTINGS, DEFAULT_THINKING_LEVEL, errorMessage, getConfigPath,
6
+ initializeConfig, loadConfig, saveConfig, type ThinkingLevel,
16
7
  } from "./config.ts";
17
8
  import {
18
- CURRENT_MAIN_MODEL,
19
- applyAgentModelChoice,
20
- availableModelsInScope,
21
- buildModelPickerItems,
22
- currentModelRef,
23
- findModelByRef,
24
- resolveThinkingLevel,
25
- supportedThinkingLevels,
9
+ CURRENT_MAIN_MODEL, availableModelsInScope, buildModelPickerItems, currentModelRef,
10
+ findModelByRef, resolveThinkingLevel, supportedThinkingLevels,
26
11
  } from "./models.ts";
27
- import { promptRoleGrid, promptSelectOne, type RoleGridFocus, type RoleGridRow, type SetupItem } from "./ui.ts";
12
+ import { promptSelectOne, promptSettings, type SetupItem, type SettingKey } from "./ui.ts";
28
13
 
29
- const ROLE_DEFAULT = "__role_default__";
30
- const THINKING_LEVEL_HINTS: Record<ThinkingLevel, string> = {
31
- off: "no reasoning tokens",
32
- minimal: "minimal reasoning",
33
- low: "light reasoning",
34
- medium: "balanced reasoning",
35
- high: "deep reasoning",
36
- xhigh: "extra-deep reasoning",
37
- max: "strongest reasoning",
14
+ const THINKING_HINTS: Record<ThinkingLevel, string> = {
15
+ off: "No reasoning tokens", minimal: "Minimal reasoning", low: "Light reasoning",
16
+ medium: "Balanced reasoning", high: "Deep reasoning", xhigh: "Extra-deep reasoning", max: "Strongest reasoning",
38
17
  };
39
18
 
40
- const ROLE_PURPOSE: Record<string, string> = {
41
- scout: "Research with citations",
42
- artisan: "Implement and verify",
43
- sentinel: "Review and challenge claims",
44
- };
45
-
46
- async function configExists(configPath: string): Promise<boolean> {
47
- try {
48
- await stat(configPath);
49
- return true;
50
- } catch {
51
- return false;
52
- }
53
- }
54
-
55
- function roleModel(ctx: ExtensionContext, config: SubagentsConfig, name: string) {
56
- return findModelByRef(availableModelsInScope(ctx), config.agentModels[name]) ?? ctx.model;
57
- }
58
-
59
- /** One row per role: every model and thinking choice stays visible together in the standalone modal panel. */
60
- function roleRows(ctx: ExtensionContext, config: SubagentsConfig): RoleGridRow[] {
61
- const mainRef = currentModelRef(ctx) ?? "Pi default";
62
- const models = availableModelsInScope(ctx);
63
- return BUILTIN_AGENT_NAMES.map((name) => {
64
- const profile = agentProfile(name)!;
65
- const selected = config.agentModels[name];
66
- const model = findModelByRef(models, selected);
67
- const available = !selected || Boolean(model);
68
- const modelLabel = selected
69
- ? (model ? model.name + " · " + model.provider + (model.name !== selected ? " (" + selected + ")" : "") : selected + " (unavailable)")
70
- : "Follow main (dynamic)";
71
- const preferred = config.agentThinkingLevels[name] ?? roleThinkingLevel(name);
72
- const effective = resolveThinkingLevel(model ?? ctx.model, preferred);
73
- const clamped = effective !== preferred ? " (" + preferred + " requested)" : "";
74
- const overridden = Boolean(config.agentThinkingLevels[name]);
75
- return {
76
- role: name,
77
- purpose: ROLE_PURPOSE[name],
78
- thinkingOverridden: overridden,
79
- model: modelLabel,
80
- thinking: effective + clamped,
81
- description: profile.remark + " Model: " + (selected
82
- ? "pinned reference " + selected + (available ? "; falls back to main if it fails." : "; unavailable, using main.")
83
- : "follows main (" + mainRef + ") dynamically.")
84
- + " Thinking: role default " + roleThinkingLevel(name) + ", clamped to the model-supported levels. Reset restores " + name + " to Follow main and that default. * marks an override.",
85
- };
86
- });
87
- }
88
-
89
- async function editSetting(
90
- ctx: ExtensionContext,
91
- config: SubagentsConfig,
92
- name: string,
93
- field: string,
94
- ): Promise<SubagentsConfig | undefined> {
95
- const next: SubagentsConfig = {
96
- agentModels: { ...config.agentModels },
97
- agentThinkingLevels: { ...config.agentThinkingLevels },
98
- };
99
- if (field === "reset") {
100
- delete next.agentModels[name];
101
- delete next.agentThinkingLevels[name];
102
- } else if (field === "model") {
103
- const choice = await promptSelectOne(ctx, name + " · Model",
104
- "Follow main = dynamic · Others = pinned · Esc back without changes",
105
- buildModelPickerItems({ models: availableModelsInScope(ctx), configuredRef: config.agentModels[name], mainRef: currentModelRef(ctx) }),
106
- config.agentModels[name] ?? CURRENT_MAIN_MODEL);
107
- if (choice === undefined) return undefined;
108
- next.agentModels = applyAgentModelChoice(next.agentModels, name, choice);
109
- } else if (field === "thinking") {
110
- const model = roleModel(ctx, config, name);
111
- const preferredDefault = roleThinkingLevel(name);
112
- const effectiveDefault = resolveThinkingLevel(model, preferredDefault);
113
- const supported = supportedThinkingLevels(model);
114
- if (!supported.length) {
115
- ctx.ui.notify("Choose a model before changing thinking; its supported levels are not available yet.", "info");
116
- return undefined;
117
- }
118
- const current = config.agentThinkingLevels[name];
119
- const options: SetupItem[] = [
120
- {
121
- value: ROLE_DEFAULT,
122
- label: "Role default",
123
- description: preferredDefault + (effectiveDefault !== preferredDefault ? " → " + effectiveDefault + " on this model" : ""),
124
- saved: !current,
125
- },
126
- ...supported.map((level) => ({
127
- value: level,
128
- label: level,
129
- description: THINKING_LEVEL_HINTS[level],
130
- saved: current === level,
131
- })),
132
- ];
133
- if (current && !supported.includes(current)) {
134
- options.push({
135
- value: current,
136
- label: current + " (runs as " + resolveThinkingLevel(model, current) + ")",
137
- description: "Saved preference; this model clamps it. Keep it for other models, or choose a supported level.",
138
- saved: true,
139
- });
140
- }
141
- const choice = await promptSelectOne(ctx, name + " · Thinking",
142
- "Reasoning effort · saved preferences survive model changes · Esc back",
143
- options, current ?? ROLE_DEFAULT);
144
- if (choice === undefined) return undefined;
145
- if (choice === ROLE_DEFAULT) delete next.agentThinkingLevels[name];
146
- else next.agentThinkingLevels[name] = choice as ThinkingLevel;
147
- } else {
148
- return undefined;
149
- }
150
- return next;
151
- }
152
-
153
- /** Standalone modal panel for first install and later edits. */
154
19
  export async function runSetup(ctx: ExtensionContext, configPath: string = getConfigPath()): Promise<void> {
155
20
  if (ctx.mode !== "tui") {
156
21
  ctx.ui.notify("/subagents-setup requires Pi's interactive TUI.", "error");
157
22
  return;
158
23
  }
159
24
  try {
160
- let config = await loadConfig(configPath);
161
- let focus: RoleGridFocus = {};
25
+ await ensureDefaultConfig(ctx, configPath);
26
+ let focus: SettingKey = "researcher.model";
162
27
  let status = "Changes save immediately";
163
28
  while (true) {
164
- const choice = await promptRoleGrid(ctx, roleRows(ctx, config), focus, status);
165
- if (choice === undefined) return;
166
- focus = { row: choice.row, column: choice.column };
167
- const next = await editSetting(ctx, config, choice.role, choice.field);
168
- if (!next) continue;
169
- await saveConfig(next, configPath);
170
- config = next;
171
- status = "Saved " + choice.role + (choice.field === "reset" ? " defaults" : " " + choice.field);
29
+ const config = await loadConfig(configPath);
30
+ const models = availableModelsInScope(ctx);
31
+ const choice = await promptSettings(ctx, {
32
+ main: currentModelRef(ctx) ?? "Pi default",
33
+ roles: BUILTIN_AGENT_NAMES.map((role) => {
34
+ const settings = config[role];
35
+ const selected = findModelByRef(models, settings.model);
36
+ const unavailable = !!settings.model && !selected;
37
+ const effective = resolveThinkingLevel(selected ?? ctx.model, settings.thinking);
38
+ return {
39
+ role, model: settings.model ?? "Follow main",
40
+ thinking: unavailable ? settings.thinking : effective + (effective !== settings.thinking ? " (" + settings.thinking + " requested)" : ""),
41
+ unavailable,
42
+ };
43
+ }),
44
+ status, focus,
45
+ });
46
+ if (!choice) return;
47
+ focus = choice;
48
+ const role = BUILTIN_AGENT_NAMES.find((name) => choice.startsWith(name + "."))!;
49
+ const title = role === "researcher" ? "Researcher" : "Worker";
50
+ const settings = config[role];
51
+ const selected = findModelByRef(models, settings.model);
52
+ const model = settings.model ? selected : ctx.model;
53
+ const effective = resolveThinkingLevel(model, settings.thinking);
54
+ if (choice === role + ".model") {
55
+ const picked = await promptSelectOne(ctx, title + " model", "Search available models · Enter save · Esc cancel",
56
+ buildModelPickerItems({ models, configuredRef: settings.model, mainRef: currentModelRef(ctx) }),
57
+ settings.model ?? CURRENT_MAIN_MODEL);
58
+ if (picked === undefined) continue;
59
+ const next = await loadConfig(configPath);
60
+ if (picked === CURRENT_MAIN_MODEL) delete next[role].model;
61
+ else next[role].model = picked;
62
+ await saveConfig(next, configPath);
63
+ status = title + " model saved";
64
+ } else if (choice === role + ".thinking") {
65
+ const levels = supportedThinkingLevels(model);
66
+ if (!levels.length) {
67
+ ctx.ui.notify("Choose a model before changing thinking; its supported levels are not available yet.", "info");
68
+ continue;
69
+ }
70
+ const items: SetupItem[] = levels.map((level) => ({
71
+ value: level, label: level + (level === DEFAULT_THINKING_LEVEL ? " (default)" : ""),
72
+ description: THINKING_HINTS[level], saved: level === settings.thinking,
73
+ }));
74
+ if (!levels.includes(settings.thinking)) items.push({
75
+ value: settings.thinking, label: settings.thinking + " (runs as " + effective + ")",
76
+ description: "Saved preference; the current model clamps it.", saved: true,
77
+ });
78
+ const picked = await promptSelectOne(ctx, title + " thinking", "Reasoning effort for " + role + " · Esc cancel", items, settings.thinking);
79
+ if (picked === undefined) continue;
80
+ const next = await loadConfig(configPath);
81
+ next[role].thinking = picked as ThinkingLevel;
82
+ await saveConfig(next, configPath);
83
+ status = title + " thinking saved";
84
+ } else if (choice === role + ".reset") {
85
+ await saveConfig({ ...await loadConfig(configPath), [role]: { ...DEFAULT_AGENT_SETTINGS } }, configPath);
86
+ status = title + " defaults restored";
87
+ }
172
88
  }
173
89
  } catch (error) {
174
90
  ctx.ui.notify("pi-subagents setup failed: " + errorMessage(error), "error");
175
91
  }
176
92
  }
177
93
 
178
- /** Write shipped defaults once so every role works immediately. */
179
- export async function ensureDefaultConfig(
180
- ctx: ExtensionContext,
181
- configPath: string = getConfigPath(),
182
- ): Promise<void> {
183
- if (await configExists(configPath)) return;
184
- await saveConfig(DEFAULT_CONFIG, configPath);
185
- ctx.ui.notify(
186
- "pi-subagents: wrote " + configPath + " with all roles enabled; each follows the main model. Run /subagents-setup to pick a model and thinking level per role.",
187
- "info",
188
- );
94
+ export async function ensureDefaultConfig(ctx: ExtensionContext, configPath: string = getConfigPath()): Promise<void> {
95
+ try {
96
+ const result = await initializeConfig(configPath);
97
+ if (!result) return;
98
+ ctx.ui.notify(
99
+ "pi-subagents: " + (result === "reset" ? "overwrote the old config with independent role settings at " : "initialized role settings at ")
100
+ + configPath + ". Run /subagents-setup to choose a model and thinking level for Researcher and Worker. Both default to Follow main with medium thinking.",
101
+ "info",
102
+ );
103
+ } catch (error) {
104
+ ctx.ui.notify("pi-subagents could not initialize settings: " + errorMessage(error) + ". Fix the config path and run /subagents-setup.", "warning");
105
+ }
189
106
  }
@@ -1,10 +1,11 @@
1
- /** Standalone modal panels for /subagents-setup role settings and model selection. */
1
+ /** Role settings and searchable model selection in a keyboard-driven overlay. */
2
2
 
3
3
  import {
4
4
  Input, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi,
5
5
  type Component, type Focusable, type Keybinding, type KeybindingsManager, type OverlayOptions, type SelectItem, type TUI,
6
6
  } from "@earendil-works/pi-tui";
7
7
  import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
8
+ import { BUILTIN_AGENT_NAMES, type AgentName } from "./config.ts";
8
9
 
9
10
  type PickerContext = Pick<ExtensionCommandContext, "mode" | "ui">;
10
11
  const PAGE_SIZE = 10;
@@ -19,9 +20,16 @@ export const SETUP_OVERLAY_OPTIONS: OverlayOptions = {
19
20
 
20
21
  /** Modal height budget on the full terminal canvas instead of the input dock. */
21
22
  function setupHeight(tui: TUI): number {
22
- const termRows = tui.terminal?.rows ?? 28;
23
+ const termRows = tui.terminal.rows;
23
24
  const maxRows = Math.floor(termRows * 0.88);
24
- return Math.max(6, Math.min(maxRows, termRows - 2));
25
+ return Math.max(1, Math.min(maxRows, termRows - 2));
26
+ }
27
+
28
+ function keyLabel(keys: KeybindingsManager, action: Keybinding): string {
29
+ const key = keys.getKeys(action)[0];
30
+ if (!key) return "unbound";
31
+ const labels: Record<string, string> = { up: "↑", down: "↓", enter: "Enter", escape: "Esc", pageUp: "PgUp", pageDown: "PgDn", ctrl: "Ctrl", alt: "Alt", shift: "Shift" };
32
+ return key.split("+").map((part) => labels[part] ?? part).join("+");
25
33
  }
26
34
 
27
35
  function padToWidth(text: string, width: number): string {
@@ -115,10 +123,7 @@ class Picker implements Component, Focusable {
115
123
  }
116
124
 
117
125
  private keyLabel(action: Keybinding): string {
118
- const key = this.keybindings.getKeys(action)[0];
119
- if (!key) return "unbound";
120
- const labels: Record<string, string> = { up: "↑", down: "↓", enter: "Enter", escape: "Esc", pageUp: "PgUp", pageDown: "PgDn", ctrl: "Ctrl", alt: "Alt", shift: "Shift" };
121
- return key.split("+").map((part) => labels[part] ?? part).join("+");
126
+ return keyLabel(this.keybindings, action);
122
127
  }
123
128
 
124
129
  private detailLines(width: number): string[] {
@@ -151,7 +156,7 @@ class Picker implements Component, Focusable {
151
156
  theme.bold(this.options.title + (this.details ? " · Details" : "")),
152
157
  ...(this.details ? [] : this.search.render(innerWidth)),
153
158
  item ? theme.fg("accent", "› ") + theme.underline(item.label + (this.isSaved(item) ? " [saved]" : "")) : "No matches. Clear or change the search.",
154
- ].map((line) => truncateToWidth(line, width, "…"));
159
+ ].slice(0, height).map((line) => truncateToWidth(line, width, "…"));
155
160
  }
156
161
 
157
162
  const navigation = move + " move · " + confirm + " select · " + cancel + " back";
@@ -285,205 +290,119 @@ export function promptSelectOne(
285
290
  }
286
291
  return ctx.ui.custom<string | undefined>(
287
292
  (tui, theme, keybindings, done) => new Picker(items, { title, hint, initialValue }, tui, theme, keybindings, done),
288
- { overlay: true, overlayOptions: SETUP_OVERLAY_OPTIONS },
293
+ { overlay: true, overlayOptions: SETUP_OVERLAY_OPTIONS, blocked: { kind: "question", message: title } },
289
294
  );
290
295
  }
291
296
 
292
- export interface RoleGridRow {
293
- role: string;
294
- purpose?: string;
297
+ export interface RoleSettingsView {
298
+ role: AgentName;
295
299
  model: string;
296
- /** Effective level, optionally followed by the requested level when clamped. */
297
300
  thinking: string;
298
- thinkingOverridden?: boolean;
299
- description: string;
301
+ unavailable: boolean;
300
302
  }
301
- export interface RoleGridFocus { row?: number; column?: number; }
302
- const GRID_COLUMNS = ["model", "thinking", "reset"] as const;
303
- export type RoleGridColumn = (typeof GRID_COLUMNS)[number];
304
- export interface RoleGridChoice { row: number; column: number; role: string; field: RoleGridColumn; }
305
-
306
- /** Standalone modal panel with a role register beside the selected role's settings;
307
- * narrow terminals stack the same regions. Full effective values are never squeezed into grid cells. */
308
- class RoleGrid implements Component {
309
- private row: number;
310
- private column: number;
311
- private scrollTop = 0;
312
- private pageRows = 1;
313
- private viewport = "";
314
- private revealField = true;
315
-
316
- private readonly rows: RoleGridRow[];
317
- private readonly status: string;
303
+
304
+ export interface SettingsView {
305
+ main: string;
306
+ roles: RoleSettingsView[];
307
+ status: string;
308
+ focus: SettingKey;
309
+ }
310
+
311
+ const SETTING_FIELDS = ["model", "thinking", "reset"] as const;
312
+ export type SettingKey = `${AgentName}.${(typeof SETTING_FIELDS)[number]}`;
313
+ const SETTING_KEYS = BUILTIN_AGENT_NAMES.flatMap((role) => SETTING_FIELDS.map((field): SettingKey => `${role}.${field}`));
314
+ const ROLE_LABELS: Record<AgentName, string> = { researcher: "Researcher", worker: "Worker" };
315
+ const ROLE_DESCRIPTIONS: Record<AgentName, string> = { researcher: "Read-only research", worker: "Implementation & checks" };
316
+
317
+ class RoleSettings implements Component {
318
+ private cursor: number;
319
+ private detailTop = 0;
320
+ private detailPage = 1;
321
+ private readonly view: SettingsView;
318
322
  private readonly tui: TUI;
319
323
  private readonly theme: Theme;
320
- private readonly keybindings: KeybindingsManager;
321
- private readonly done: (choice: RoleGridChoice | undefined) => void;
322
-
324
+ private readonly keys: KeybindingsManager;
325
+ private readonly done: (value: SettingKey | undefined) => void;
323
326
  constructor(
324
- rows: RoleGridRow[], status: string, focus: RoleGridFocus, tui: TUI, theme: Theme,
325
- keybindings: KeybindingsManager, done: (choice: RoleGridChoice | undefined) => void,
327
+ view: SettingsView, tui: TUI, theme: Theme,
328
+ keys: KeybindingsManager, done: (value: SettingKey | undefined) => void,
326
329
  ) {
327
- this.rows = rows;
328
- this.status = status;
330
+ this.view = view;
329
331
  this.tui = tui;
330
332
  this.theme = theme;
331
- this.keybindings = keybindings;
333
+ this.keys = keys;
332
334
  this.done = done;
333
- this.row = Math.min(Math.max(0, focus.row ?? 0), Math.max(0, rows.length - 1));
334
- this.column = Math.min(Math.max(0, focus.column ?? 0), GRID_COLUMNS.length - 1);
335
- }
336
-
337
- private settings(width: number): { lines: string[]; start: number; end: number } {
338
- const focused = this.rows[this.row];
339
- if (!focused) return { lines: [this.theme.fg("dim", "No roles configured.")], start: 0, end: 1 };
340
- const theme = this.theme;
341
- const dim = (text: string) => theme.fg("dim", text);
342
- const field = GRID_COLUMNS[this.column]!;
343
- const label = field === "thinking" ? "Thinking (reasoning effort)" : field === "reset" ? "Reset" : "Model";
344
- const lines = [theme.bold(focused.role + " · " + label), ""];
345
- const starts: number[] = [];
346
- const setting = (column: number, name: string, hint: string): void => {
347
- starts.push(lines.length);
348
- const active = this.column === column;
349
- lines.push((active ? theme.fg("accent", "› ") : " ") + (active ? theme.underline(theme.bold(name)) : name) + dim(" · " + hint));
350
- };
351
- const value = (text: string): void => {
352
- lines.push(...wrapTextWithAnsi(text, Math.max(1, width - 2)).map((line) => " " + line));
353
- };
354
- setting(0, "Model", "Enter edit");
355
- value(focused.model);
356
- setting(1, "Thinking", "effective");
357
- value(focused.thinking);
358
- lines.push(dim(" Source: " + (focused.thinkingOverridden ? "override *" : "role default")));
359
- setting(2, "Reset", "Enter restore defaults");
360
- const end = lines.length;
361
- lines.push("", ...wrapTextWithAnsi(focused.description, width).map(dim));
362
- return { lines, start: starts[this.column]!, end: starts[this.column + 1] ?? end };
335
+ this.cursor = Math.max(0, SETTING_KEYS.findIndex((key) => key === view.focus));
363
336
  }
364
337
 
365
338
  render(width: number): string[] {
366
339
  if (width <= 0) return [];
367
- const theme = this.theme;
368
- const dim = (text: string) => theme.fg("dim", text);
369
340
  const height = setupHeight(this.tui);
370
- const framed = width >= 20 && height >= 10;
371
- const innerWidth = framed ? Math.max(1, width - 4) : width;
372
- const wide = innerWidth >= 72;
373
- // The two panes close exactly: roleWidth + 3-column gutter + detailWidth = innerWidth.
374
- const roleWidth = wide ? Math.min(28, Math.max(20, Math.floor(innerWidth * 0.28))) : innerWidth;
375
- const roles: string[] = [];
376
- for (const [index, role] of this.rows.entries()) {
377
- const selected = index === this.row;
378
- const title = role.purpose && wide ? role.role + " · " + role.purpose : role.role;
379
- const clippedTitle = truncateToWidth(title, Math.max(1, roleWidth - 2), "…");
380
- const name = selected ? theme.bold(clippedTitle) : clippedTitle;
381
- roles.push((selected ? theme.fg("accent", "› ") : " ") + name);
382
- if (wide) {
383
- const summary = role.model + " · " + role.thinking + (role.thinkingOverridden ? " *" : "");
384
- roles.push(dim(" " + truncateToWidth(summary, roleWidth - 2, "…")));
385
- }
386
- }
387
- const details = this.settings(wide ? innerWidth - roleWidth - 3 : innerWidth);
388
- const detailOffset = wide ? 0 : roles.length + 1;
389
- const body: string[] = [];
390
- const divider = dim(" │ ");
391
- if (wide) {
392
- for (let i = 0; i < Math.max(roles.length, details.lines.length); i++) {
393
- const left = truncateToWidth(roles[i] ?? "", roleWidth, "…");
394
- body.push(left + " ".repeat(Math.max(0, roleWidth - visibleWidth(left))) + divider + (details.lines[i] ?? ""));
395
- }
396
- } else {
397
- body.push(...roles, "", ...details.lines);
398
- }
399
- const footer = innerWidth >= 52
400
- ? [dim("↑/↓ role · ←/→ field · Enter edit · Esc close")]
401
- : [dim("↑/↓ role · ←/→ field"), dim("Enter edit · Esc close")];
402
-
403
- const chromeRows = framed ? 4 + footer.length + 1 : 3 + footer.length + 1;
404
- if (body.length + chromeRows <= height) {
405
- this.scrollTop = 0;
406
- this.revealField = true;
407
- if (!framed) {
408
- return [theme.bold("Subagents · Roles"), dim(this.status), "", ...body, "", ...footer]
409
- .map((line) => truncateToWidth(line, width, "…"));
341
+ const framed = width >= 36 && height >= 20;
342
+ const inner = Math.max(1, width - (framed ? 4 : 0));
343
+ const theme = this.theme;
344
+ const entries = BUILTIN_AGENT_NAMES.flatMap((role) => {
345
+ const view = this.view.roles.find((entry) => entry.role === role)!;
346
+ return SETTING_FIELDS.map((field) => ({ role, field, view }));
347
+ });
348
+ const active = entries[this.cursor]!;
349
+ const label = ROLE_LABELS[active.role];
350
+ const key = (action: Keybinding) => keyLabel(this.keys, action);
351
+ const navigation = key("tui.select.up") + key("tui.select.down") + " move · " + key("tui.select.confirm") + " edit · " + key("tui.select.cancel") + " close";
352
+ const rows: string[] = [];
353
+ for (const [index, { role, field, view }] of entries.entries()) {
354
+ if (framed && field === "model") {
355
+ if (index) rows.push("");
356
+ rows.push(theme.bold(ROLE_LABELS[role]) + theme.fg("muted", " · " + ROLE_DESCRIPTIONS[role]));
410
357
  }
411
- return framePanel(theme, width, "Subagents · Roles", this.status, body, footer);
358
+ const name = field === "model" ? "Model" : field === "thinking" ? "Thinking" : "Reset";
359
+ const value = field === "model" ? view.model : field === "thinking" ? view.thinking : "Follow main · medium";
360
+ const prefix = framed ? name.padEnd(10) : ROLE_LABELS[role] + " " + name + " ";
361
+ const warning = field === "model" && view.unavailable ? " [unavailable]" : "";
362
+ const line = truncateToWidth(prefix + value, Math.max(1, inner - 2 - visibleWidth(warning)), "…") + theme.fg("warning", warning);
363
+ rows.push(index === this.cursor ? theme.fg("accent", "› " + theme.bold(line)) : " " + line);
412
364
  }
413
-
414
- // Pin the selected identity while scrolling the existing pane content.
415
- // The field's complete value and provenance remain reachable by paging.
416
- const compact = height < 10;
417
- const header = [details.lines[0]!];
418
- const controls = innerWidth >= 58
419
- ? [dim("↑/↓ role · ←/→ field · PgUp/Dn scroll · Enter edit · Esc close")]
420
- : compact
421
- ? [dim("PgUp/Dn scroll · Enter edit · Esc")]
422
- : [dim("↑/↓ role · ←/→ field"), dim("PgUp/Dn scroll · Enter edit · Esc")];
423
- const scrollChrome = framed ? 4 + header.length + controls.length + 1 : header.length + controls.length;
424
- this.pageRows = Math.max(1, height - scrollChrome);
425
- const viewport = innerWidth + ":" + this.pageRows;
426
- if (this.revealField || this.viewport !== viewport) {
427
- const start = detailOffset + details.start;
428
- const end = detailOffset + details.end;
429
- // One-line viewports show the value rather than repeating its label.
430
- this.scrollTop = end - start > this.pageRows ? start + Number(this.pageRows === 1 && end > start + 1)
431
- : Math.max(0, end - this.pageRows);
432
- }
433
- this.viewport = viewport;
434
- this.revealField = false;
435
- this.scrollTop = Math.max(0, Math.min(this.scrollTop, body.length - this.pageRows));
436
- const visibleBody = [...header, ...body.slice(this.scrollTop, this.scrollTop + this.pageRows)];
437
- if (!framed) {
438
- return [...visibleBody, ...controls].map((line) => truncateToWidth(line, width, "…"));
365
+ const detail = active.field === "reset"
366
+ ? "Reset only " + label + " to Follow main and medium thinking."
367
+ : label + " " + active.field + ": " + active.view[active.field];
368
+ const details = wrapTextWithAnsi(detail + (active.view.unavailable ? " · Model unavailable; choose an available model to resume this role." : ""), inner);
369
+ const footer = [this.view.status, navigation];
370
+ const header = [theme.fg("muted", truncateToWidth("Main · " + this.view.main, inner, "…"))];
371
+ if (framed) header.push("");
372
+ const chrome = framed ? 4 : 1;
373
+ const rowBudget = Math.max(1, height - chrome - header.length - footer.length);
374
+ const start = framed ? 0 : Math.max(0, Math.min(this.cursor - Math.floor(rowBudget / 2), rows.length - rowBudget));
375
+ const visibleRows = rows.slice(start, start + rowBudget);
376
+ const detailBudget = Math.max(0, height - chrome - header.length - visibleRows.length - footer.length - 1);
377
+ this.detailPage = Math.max(1, detailBudget);
378
+ this.detailTop = Math.max(0, Math.min(this.detailTop, details.length - this.detailPage));
379
+ const body = [...header, ...visibleRows];
380
+ if (detailBudget) {
381
+ body.push("", ...details.slice(this.detailTop, this.detailTop + detailBudget).map((line) => theme.fg(active.view.unavailable ? "warning" : "muted", line)));
382
+ if (details.length > detailBudget) footer[0] = key("tui.select.pageUp") + "/" + key("tui.select.pageDown") + " details · " + this.view.status;
439
383
  }
440
- return framePanel(theme, width, "Subagents · Roles", this.status, visibleBody, controls);
384
+ if (framed) return framePanel(theme, width, "Subagents · Models & thinking", undefined, body, footer);
385
+ if (height < 6) return [theme.bold(label), rows[this.cursor]!, key("tui.select.confirm") + " edit · " + key("tui.select.cancel") + " close"]
386
+ .slice(0, height).map((line) => truncateToWidth(line, width, "…"));
387
+ return [theme.bold("Subagents"), ...body, ...footer].map((line) => truncateToWidth(line, width, "…"));
441
388
  }
442
389
 
443
390
  handleInput(data: string): void {
444
- const kb = this.keybindings;
445
- const rows = this.rows.length;
446
- const previousRow = this.row;
447
- const previousColumn = this.column;
448
- if (kb.matches(data, "tui.select.pageUp")) {
449
- this.scrollTop -= this.pageRows;
450
- } else if (kb.matches(data, "tui.select.pageDown")) {
451
- this.scrollTop += this.pageRows;
452
- } else if (kb.matches(data, "tui.select.up")) {
453
- if (rows) this.row = (this.row - 1 + rows) % rows;
454
- } else if (kb.matches(data, "tui.select.down")) {
455
- if (rows) this.row = (this.row + 1) % rows;
456
- } else if (matchesKey(data, "left") || kb.matches(data, "tui.editor.cursorLeft")) {
457
- this.column = (this.column - 1 + GRID_COLUMNS.length) % GRID_COLUMNS.length;
458
- } else if (matchesKey(data, "right") || kb.matches(data, "tui.editor.cursorRight")) {
459
- this.column = (this.column + 1) % GRID_COLUMNS.length;
460
- } else if (kb.matches(data, "tui.select.confirm")) {
461
- const focused = this.rows[this.row];
462
- if (focused) {
463
- this.done({ row: this.row, column: this.column, role: focused.role, field: GRID_COLUMNS[this.column]! });
464
- return;
465
- }
466
- } else if (kb.matches(data, "tui.select.cancel")) {
467
- this.done(undefined);
468
- return;
469
- } else return;
470
- if (this.row !== previousRow || this.column !== previousColumn) this.revealField = true;
391
+ if (this.keys.matches(data, "tui.select.cancel")) { this.done(undefined); return; }
392
+ if (this.keys.matches(data, "tui.select.confirm")) { this.done(SETTING_KEYS[this.cursor]); return; }
393
+ if (this.keys.matches(data, "tui.select.up")) { this.cursor = (this.cursor + SETTING_KEYS.length - 1) % SETTING_KEYS.length; this.detailTop = 0; }
394
+ else if (this.keys.matches(data, "tui.select.down")) { this.cursor = (this.cursor + 1) % SETTING_KEYS.length; this.detailTop = 0; }
395
+ else if (this.keys.matches(data, "tui.select.pageUp")) this.detailTop -= this.detailPage;
396
+ else if (this.keys.matches(data, "tui.select.pageDown")) this.detailTop += this.detailPage;
471
397
  this.tui.requestRender();
472
398
  }
473
399
 
474
400
  invalidate(): void {}
475
401
  }
476
402
 
477
- /** Role × setting modal panel. Esc closes without a change. */
478
- export function promptRoleGrid(
479
- ctx: PickerContext, rows: RoleGridRow[], focus: RoleGridFocus = {}, status = "Changes save immediately",
480
- ): Promise<RoleGridChoice | undefined> {
481
- if (ctx.mode !== "tui") {
482
- ctx.ui.notify("/subagents-setup requires Pi's interactive TUI.", "error");
483
- return Promise.resolve(undefined);
484
- }
485
- return ctx.ui.custom<RoleGridChoice | undefined>(
486
- (tui, theme, keybindings, done) => new RoleGrid(rows, status, focus, tui, theme, keybindings, done),
487
- { overlay: true, overlayOptions: SETUP_OVERLAY_OPTIONS },
403
+ export function promptSettings(ctx: PickerContext, view: SettingsView): Promise<SettingKey | undefined> {
404
+ return ctx.ui.custom<SettingKey | undefined>(
405
+ (tui, theme, keys, done) => new RoleSettings(view, tui, theme, keys, done),
406
+ { overlay: true, overlayOptions: SETUP_OVERLAY_OPTIONS, blocked: { kind: "question", message: "Configure subagent models and thinking" } },
488
407
  );
489
408
  }