@narumitw/pi-btw 0.58.1 → 0.60.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/src/menu.ts CHANGED
@@ -1,509 +1,700 @@
1
- import type {
2
- ExtensionCommandContext,
3
- KeybindingsManager,
4
- Theme,
1
+ import { type Api, getSupportedThinkingLevels, type Model } from "@earendil-works/pi-ai";
2
+ import {
3
+ BorderedLoader,
4
+ type ExtensionCommandContext,
5
+ type KeybindingsManager,
6
+ type Theme,
5
7
  } from "@earendil-works/pi-coding-agent";
6
8
  import type { Component, TUI } from "@earendil-works/pi-tui";
7
9
  import type { MenuContext, RunMenuResult } from "@narumitw/pi-tui-kit";
8
10
  import {
9
- BTW_SHORTCUT_ACTIONS,
10
- type BtwShortcutAction,
11
- normalizeBtwKey,
12
- resolveBtwShortcuts,
13
- validateBtwShortcutEdit,
11
+ BTW_SHORTCUT_ACTIONS,
12
+ type BtwShortcutAction,
13
+ normalizeBtwKey,
14
+ resolveBtwShortcuts,
15
+ validateBtwShortcutEdit,
14
16
  } from "./keybindings.js";
15
17
  import {
16
- type BtwSettings,
17
- type BtwSettingsPatch,
18
- btwSettingsPath,
19
- effectiveFullscreenCopyOnSelect,
20
- effectiveRememberThinkingLevelChanges,
21
- readBtwSettings,
22
- type UpdateBtwSettingsOptions,
23
- updateBtwSettings,
18
+ type BtwSettings,
19
+ type BtwSettingsPatch,
20
+ btwSettingsPath,
21
+ effectiveFullscreenCopyOnSelect,
22
+ effectiveRememberThinkingLevelChanges,
23
+ parseBtwModelReference,
24
+ readBtwSettings,
25
+ type UpdateBtwSettingsOptions,
26
+ updateBtwSettings,
24
27
  } from "./settings.js";
25
28
  import { BTW_THINKING_LEVELS, type BtwThinkingLevel } from "./side-thread.js";
26
29
  import { formatKeyLabel, sanitizeSingleLine } from "./text.js";
27
30
 
28
31
  interface BtwMenuState {
29
- kind: "valid" | "invalid";
30
- settings: BtwSettings;
31
- reason?: string;
32
+ kind: "valid" | "invalid";
33
+ settings: BtwSettings;
34
+ reason?: string;
32
35
  }
33
36
 
34
37
  export interface BtwResumeThreadSummary {
35
- id: string;
36
- title: string;
37
- questionCount: number;
38
+ id: string;
39
+ title: string;
40
+ questionCount: number;
38
41
  }
39
42
 
40
43
  export interface ShowBtwCommandMenuOptions {
41
- currentThinkingLevel: BtwThinkingLevel;
42
- availableThinkingLevels: readonly BtwThinkingLevel[];
43
- resumeThreads?: readonly BtwResumeThreadSummary[];
44
- settingsPath?: string;
45
- readSettings?: typeof readBtwSettings;
46
- updateSettings?: (
47
- patch: BtwSettingsPatch,
48
- options: UpdateBtwSettingsOptions,
49
- ) => Promise<BtwSettings>;
44
+ currentThinkingLevel: BtwThinkingLevel;
45
+ /** Deterministic test override; production derives levels from each selected model. */
46
+ availableThinkingLevels?: readonly BtwThinkingLevel[];
47
+ availableModels?: readonly Model<Api>[];
48
+ currentModel?: Model<Api>;
49
+ scopedModels?: ExtensionCommandContext["scopedModels"];
50
+ resumeThreads?: readonly BtwResumeThreadSummary[];
51
+ settingsPath?: string;
52
+ readSettings?: typeof readBtwSettings;
53
+ updateSettings?: (patch: BtwSettingsPatch, options: UpdateBtwSettingsOptions) => Promise<BtwSettings>;
50
54
  }
51
55
 
52
- export type BtwCommandMenuResult =
53
- | "start"
54
- | "tree"
55
- | "closed"
56
- | { kind: "resume"; threadId: string };
56
+ export type BtwCommandMenuResult = "start" | "tree" | "closed" | { kind: "resume"; threadId: string };
57
57
 
58
- type BtwMenuScreen = "main" | "resume" | "settings" | "invalid" | "shortcut" | "shortcut-input";
58
+ type BtwMenuScreen = "main" | "resume" | "settings" | "model" | "invalid" | "shortcut" | "shortcut-input";
59
59
  type BtwMenuAction =
60
- | "start"
61
- | "start-tree"
62
- | "resume"
63
- | "set-thinking"
64
- | "set-remember"
65
- | "set-fullscreen-copy"
66
- | "edit-shortcut"
67
- | "save-shortcut"
68
- | "reset-shortcut";
60
+ | "start"
61
+ | "start-tree"
62
+ | "resume"
63
+ | "open-model"
64
+ | "set-model"
65
+ | "set-thinking"
66
+ | "set-remember"
67
+ | "set-fullscreen-copy"
68
+ | "edit-shortcut"
69
+ | "save-shortcut"
70
+ | "reset-shortcut";
69
71
  const SAME_AS_MAIN_THREAD = "Same as main thread";
70
72
  type BtwCustomOptions = Parameters<ExtensionCommandContext["ui"]["custom"]>[1];
71
73
 
72
74
  type BtwCustomFactory<T> = (
73
- tui: TUI,
74
- theme: Theme,
75
- keybindings: KeybindingsManager,
76
- done: (result: T) => void,
75
+ tui: TUI,
76
+ theme: Theme,
77
+ keybindings: KeybindingsManager,
78
+ done: (result: T) => void,
77
79
  ) => Component;
78
80
 
79
81
  export async function showBtwCommandMenu(
80
- ctx: ExtensionCommandContext,
81
- options: ShowBtwCommandMenuOptions,
82
+ ctx: ExtensionCommandContext,
83
+ options: ShowBtwCommandMenuOptions,
82
84
  ): Promise<BtwCommandMenuResult> {
83
- if (ctx.mode !== "tui") return "closed";
84
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
85
- if (ctx.signal?.aborted) return "closed";
86
- const settingsPath = options.settingsPath ?? btwSettingsPath();
87
- const readSettings = options.readSettings ?? readBtwSettings;
88
- const updateSettings = options.updateSettings ?? updateBtwSettings;
89
- const levels =
90
- options.availableThinkingLevels.length > 0
91
- ? [...options.availableThinkingLevels]
92
- : (["off"] satisfies BtwThinkingLevel[]);
93
- const displaySettingsPath = sanitizeSingleLine(settingsPath);
94
- const resumeThreads = options.resumeThreads ?? [];
95
- let startSelected = false;
96
- let treeSelected = false;
97
- let resumedThreadId: string | undefined;
98
- let keybindings: KeybindingsManager | undefined;
99
- let shortcut: BtwShortcutAction = "exit";
100
- const shortcutLabels: Record<BtwShortcutAction, string> = {
101
- exit: "Exit shortcut",
102
- cycleThinkingLevel: "Cycle thinking level shortcut",
103
- bringToMain: "Bring to main shortcut",
104
- };
105
- const shortcutValue = (settings: BtwSettings, action: BtwShortcutAction): string => {
106
- if (!keybindings) return "Default";
107
- const effective = resolveBtwShortcuts(
108
- settings.keybindings,
109
- keybindings,
110
- effectiveFullscreenCopyOnSelect(settings),
111
- );
112
- const configured = settings.keybindings?.[action];
113
- if (configured !== undefined && !effective.keys[action].includes(configured)) {
114
- return `Fallback (${effective.label(action)}; saved ${formatKeyLabel(configured)})`;
115
- }
116
- const source =
117
- configured === undefined
118
- ? action === "cycleThinkingLevel"
119
- ? "Inherit Pi"
120
- : "Default"
121
- : "Custom";
122
- return `${source} (${effective.label(action)})`;
123
- };
124
- const saveShortcut = async (
125
- state: BtwMenuState,
126
- value: string | undefined,
127
- signal: AbortSignal,
128
- ) => {
129
- if (!keybindings || state.kind !== "valid" || signal.aborted)
130
- return { kind: "rejected" } as const;
131
- const action = shortcut;
132
- const manager = keybindings;
133
- const validate = (settings: BtwSettings) =>
134
- validateBtwShortcutEdit(
135
- action,
136
- value,
137
- settings.keybindings ?? {},
138
- manager,
139
- effectiveFullscreenCopyOnSelect(settings),
140
- );
141
- const error = validate(state.settings);
142
- if (error) {
143
- notifySafely(ctx, error, "error");
144
- return { kind: "rejected" } as const;
145
- }
146
- try {
147
- await updateSettings(
148
- { keybindings: { [action]: value === undefined ? undefined : normalizeBtwKey(value) } },
149
- {
150
- settingsPath,
151
- signal,
152
- validateCurrent: (settings) => {
153
- const conflict = validate(settings);
154
- if (conflict) throw new Error(conflict);
155
- },
156
- },
157
- );
158
- if (signal.aborted) return { kind: "rejected" } as const;
159
- notifySafely(ctx, "Pi BTW shortcut saved; applies when opening or resuming BTW.", "info");
160
- return { kind: "back" } as const;
161
- } catch (error) {
162
- if (!signal.aborted) notifySaveFailure(ctx, error);
163
- return { kind: "rejected" } as const;
164
- }
165
- };
85
+ if (ctx.mode !== "tui") return "closed";
86
+ const { defineMenu, runMenu, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
87
+ if (ctx.signal?.aborted) return "closed";
88
+ const settingsPath = options.settingsPath ?? btwSettingsPath();
89
+ const readSettings = options.readSettings ?? readBtwSettings;
90
+ const updateSettings = options.updateSettings ?? updateBtwSettings;
91
+ const getAvailable = ctx.modelRegistry.getAvailable;
92
+ const allAvailableModels = deduplicateModels(
93
+ options.availableModels ??
94
+ (typeof getAvailable === "function" ? getAvailable.call(ctx.modelRegistry) : ctx.modelRegistry.getAll()),
95
+ );
96
+ const currentModel = options.currentModel ?? ctx.model;
97
+ const scopedModels = options.scopedModels ?? ctx.scopedModels ?? [];
98
+ const selectableModels = availableModelsInScope(allAvailableModels, scopedModels);
99
+ const modelItemIds = new Map(selectableModels.map((model, index) => [model, `btw-settings-model:${index}`]));
100
+ const modelsByItemId = new Map(selectableModels.map((model) => [modelItemIds.get(model) as string, model]));
101
+ const safeModelMetadata = (value: string, fallback: string): string => {
102
+ const safe = sanitizeTerminalText(value).trim() || fallback;
103
+ return [...safe].slice(0, 512).join("");
104
+ };
105
+ const displayModelReference = (model: Pick<Model<Api>, "provider" | "id">): string =>
106
+ `${safeModelMetadata(model.id, "unknown model")} [${safeModelMetadata(model.provider, "unknown provider")}]`;
107
+ const rawModelReference = (model: Pick<Model<Api>, "provider" | "id">): string | undefined => {
108
+ const reference = `${model.provider}/${model.id}`;
109
+ const parsed = parseBtwModelReference(reference);
110
+ return parsed?.provider === model.provider && parsed.modelId === model.id ? reference : undefined;
111
+ };
112
+ const displaySettingsPath = sanitizeSingleLine(settingsPath);
113
+ const resumeThreads = options.resumeThreads ?? [];
114
+ let startSelected = false;
115
+ let treeSelected = false;
116
+ let resumedThreadId: string | undefined;
117
+ let keybindings: KeybindingsManager | undefined;
118
+ let shortcut: BtwShortcutAction = "exit";
119
+ const shortcutLabels: Record<BtwShortcutAction, string> = {
120
+ exit: "Exit shortcut",
121
+ cycleThinkingLevel: "Cycle thinking level shortcut",
122
+ bringToMain: "Bring to main shortcut",
123
+ };
124
+ const shortcutValue = (settings: BtwSettings, action: BtwShortcutAction): string => {
125
+ if (!keybindings) return "Default";
126
+ const effective = resolveBtwShortcuts(settings.keybindings, keybindings, effectiveFullscreenCopyOnSelect(settings));
127
+ const configured = settings.keybindings?.[action];
128
+ if (configured !== undefined && !effective.keys[action].includes(configured)) {
129
+ return `Fallback (${effective.label(action)}; saved ${formatKeyLabel(configured)})`;
130
+ }
131
+ const source = configured === undefined ? (action === "cycleThinkingLevel" ? "Inherit Pi" : "Default") : "Custom";
132
+ return `${source} (${effective.label(action)})`;
133
+ };
134
+ const saveShortcut = async (state: BtwMenuState, value: string | undefined, signal: AbortSignal) => {
135
+ if (!keybindings || state.kind !== "valid" || signal.aborted) return { kind: "rejected" } as const;
136
+ const action = shortcut;
137
+ const manager = keybindings;
138
+ const validate = (settings: BtwSettings) =>
139
+ validateBtwShortcutEdit(
140
+ action,
141
+ value,
142
+ settings.keybindings ?? {},
143
+ manager,
144
+ effectiveFullscreenCopyOnSelect(settings),
145
+ );
146
+ const error = validate(state.settings);
147
+ if (error) {
148
+ notifySafely(ctx, error, "error");
149
+ return { kind: "rejected" } as const;
150
+ }
151
+ try {
152
+ await updateSettings(
153
+ { keybindings: { [action]: value === undefined ? undefined : normalizeBtwKey(value) } },
154
+ {
155
+ settingsPath,
156
+ signal,
157
+ validateCurrent: (settings) => {
158
+ const conflict = validate(settings);
159
+ if (conflict) throw new Error(conflict);
160
+ },
161
+ },
162
+ );
163
+ if (signal.aborted) return { kind: "rejected" } as const;
164
+ notifySafely(ctx, "Pi BTW shortcut saved; applies when opening or resuming BTW.", "info");
165
+ return { kind: "back" } as const;
166
+ } catch (error) {
167
+ if (!signal.aborted) notifySaveFailure(ctx, error);
168
+ return { kind: "rejected" } as const;
169
+ }
170
+ };
171
+
172
+ const saveModel = async (
173
+ model: Model<Api> | undefined,
174
+ signal: AbortSignal,
175
+ ): Promise<{ kind: "saved" } | { kind: "cancelled" } | { kind: "failed"; error: unknown }> => {
176
+ const modelReference = model ? rawModelReference(model) : undefined;
177
+ if (model && !modelReference) return { kind: "cancelled" };
178
+ const result = await ctx.ui.custom<{ kind: "saved" } | { kind: "cancelled" } | { kind: "failed"; error: unknown }>(
179
+ (tui, theme, _keybindings, done) => {
180
+ const loader = new BorderedLoader(tui, theme, "Saving Pi BTW model...");
181
+ const ownerController = new AbortController();
182
+ const saveSignal = AbortSignal.any([signal, loader.signal, ownerController.signal]);
183
+ let settled = false;
184
+ const finish = (value: { kind: "saved" } | { kind: "cancelled" } | { kind: "failed"; error: unknown }) => {
185
+ if (settled) return;
186
+ settled = true;
187
+ done(value);
188
+ };
189
+ const cancel = () => finish({ kind: "cancelled" });
190
+ loader.onAbort = cancel;
191
+ saveSignal.addEventListener("abort", cancel, { once: true });
192
+ queueMicrotask(() => {
193
+ void (async () => {
194
+ // Let the host mount the loader before a synchronous test double or cached write can settle it.
195
+ await Promise.resolve();
196
+ if (saveSignal.aborted) return;
197
+ try {
198
+ await updateSettings({ model: modelReference }, { settingsPath, signal: saveSignal });
199
+ finish({ kind: "saved" });
200
+ } catch (error) {
201
+ finish(saveSignal.aborted ? { kind: "cancelled" } : { kind: "failed", error });
202
+ }
203
+ })();
204
+ });
205
+ return {
206
+ render: (width: number) => loader.render(width),
207
+ invalidate: () => loader.invalidate(),
208
+ handleInput: (data: string) => loader.handleInput(data),
209
+ dispose() {
210
+ ownerController.abort(new DOMException("Pi BTW model save disposed", "AbortError"));
211
+ loader.dispose();
212
+ },
213
+ };
214
+ },
215
+ );
216
+ return result ?? { kind: "cancelled" };
217
+ };
166
218
 
167
- const loadState = async (): Promise<BtwMenuState> => {
168
- const loaded = await readSettings(settingsPath);
169
- if (loaded.kind === "invalid") {
170
- return { kind: "invalid", settings: {}, reason: loaded.reason };
171
- }
172
- return { kind: "valid", settings: loaded.kind === "loaded" ? loaded.settings : {} };
173
- };
174
- const currentMainThinkingLevel = clampToAvailableThinkingLevel(
175
- options.currentThinkingLevel,
176
- levels,
177
- );
178
- const displayThinkingLevel = (settings: BtwSettings): string =>
179
- settings.thinkingLevel === undefined
180
- ? SAME_AS_MAIN_THREAD
181
- : clampToAvailableThinkingLevel(settings.thinkingLevel, levels);
182
- const displayThinkingSummary = (settings: BtwSettings): string =>
183
- settings.thinkingLevel === undefined
184
- ? `${SAME_AS_MAIN_THREAD} (currently ${currentMainThinkingLevel})`
185
- : displayThinkingLevel(settings);
186
- const displayRememberSummary = (settings: BtwSettings): string => {
187
- const value = effectiveRememberThinkingLevelChanges(settings) ? "On" : "Off";
188
- return settings.thinkingLevel === undefined ? `${value} (fixed levels only)` : value;
189
- };
219
+ const loadState = async (): Promise<BtwMenuState> => {
220
+ const loaded = await readSettings(settingsPath);
221
+ if (loaded.kind === "invalid") {
222
+ return { kind: "invalid", settings: {}, reason: loaded.reason };
223
+ }
224
+ return { kind: "valid", settings: loaded.kind === "loaded" ? loaded.settings : {} };
225
+ };
226
+ const configuredModel = (settings: BtwSettings): Model<Api> | undefined => {
227
+ if (!settings.model) return undefined;
228
+ const reference = parseBtwModelReference(settings.model);
229
+ return reference
230
+ ? allAvailableModels.find((model) => model.provider === reference.provider && model.id === reference.modelId)
231
+ : undefined;
232
+ };
233
+ const selectableConfiguredModel = (settings: BtwSettings): Model<Api> | undefined => {
234
+ const configured = configuredModel(settings);
235
+ return configured ? selectableModels.find((model) => sameModel(model, configured)) : undefined;
236
+ };
237
+ const thinkingLevels = (settings: BtwSettings): BtwThinkingLevel[] => {
238
+ const overridden = options.availableThinkingLevels;
239
+ const effectiveModel = configuredModel(settings) ?? currentModel;
240
+ const available =
241
+ overridden && overridden.length > 0
242
+ ? overridden
243
+ : effectiveModel
244
+ ? getSupportedThinkingLevels(effectiveModel)
245
+ : BTW_THINKING_LEVELS;
246
+ return available.length > 0 ? [...available] : ["off"];
247
+ };
248
+ const currentMainThinkingLevel = (settings: BtwSettings): BtwThinkingLevel =>
249
+ clampToAvailableThinkingLevel(options.currentThinkingLevel, thinkingLevels(settings));
250
+ const displayThinkingLevel = (settings: BtwSettings): string =>
251
+ settings.thinkingLevel === undefined
252
+ ? SAME_AS_MAIN_THREAD
253
+ : clampToAvailableThinkingLevel(settings.thinkingLevel, thinkingLevels(settings));
254
+ const displayThinkingSummary = (settings: BtwSettings): string =>
255
+ settings.thinkingLevel === undefined
256
+ ? `${SAME_AS_MAIN_THREAD} (currently ${currentMainThinkingLevel(settings)})`
257
+ : displayThinkingLevel(settings);
258
+ const displayRememberSummary = (settings: BtwSettings): string => {
259
+ const value = effectiveRememberThinkingLevelChanges(settings) ? "On" : "Off";
260
+ return settings.thinkingLevel === undefined ? `${value} (fixed levels only)` : value;
261
+ };
262
+ const displayModelValue = (settings: BtwSettings): string => {
263
+ if (!settings.model) {
264
+ return currentModel ? `${SAME_AS_MAIN_THREAD} (${displayModelReference(currentModel)})` : SAME_AS_MAIN_THREAD;
265
+ }
266
+ const available = configuredModel(settings);
267
+ if (!available) return `${SAME_AS_MAIN_THREAD} · ${safeModelMetadata(settings.model, "unknown model")} unavailable`;
268
+ const reference = displayModelReference(available);
269
+ return selectableConfiguredModel(settings) ? reference : `${reference} · outside current scope`;
270
+ };
271
+ const modelItems = (settings: BtwSettings) => {
272
+ const configured = configuredModel(settings);
273
+ const selectable = selectableConfiguredModel(settings);
274
+ const retained = settings.model && !selectable;
275
+ return [
276
+ {
277
+ id: "same-as-main",
278
+ label: SAME_AS_MAIN_THREAD,
279
+ description: currentModel
280
+ ? `Currently ${displayModelReference(currentModel)}`
281
+ : "Use the main thread model when /btw starts.",
282
+ },
283
+ ...selectableModels.map((model) => {
284
+ const reference = displayModelReference(model);
285
+ const name = safeModelMetadata(model.name ?? "", "");
286
+ const validReference = rawModelReference(model);
287
+ return {
288
+ id: modelItemIds.get(model) as string,
289
+ label: reference,
290
+ ...(name ? { details: [`Model Name: ${name}`] } : {}),
291
+ searchText: [reference, name].filter(Boolean).join(" "),
292
+ ...(!validReference
293
+ ? {
294
+ disabled: true,
295
+ disabledReason: "This model identity cannot be stored in pi-btw.json.",
296
+ }
297
+ : {}),
298
+ };
299
+ }),
300
+ ...(retained
301
+ ? [
302
+ {
303
+ id: "configured-model",
304
+ label: configured
305
+ ? displayModelReference(configured)
306
+ : safeModelMetadata(settings.model as string, "unknown model"),
307
+ ...(configured
308
+ ? { description: "Configured outside the current model scope; retained until changed." }
309
+ : {
310
+ disabled: true,
311
+ disabledReason: "Configured model is unavailable; /btw falls back to the main model.",
312
+ }),
313
+ },
314
+ ]
315
+ : []),
316
+ ];
317
+ };
318
+ const selectedModelItemId = (settings: BtwSettings): string => {
319
+ const selected = selectableConfiguredModel(settings);
320
+ return selected ? (modelItemIds.get(selected) as string) : settings.model ? "configured-model" : "same-as-main";
321
+ };
322
+ const currentModelItemId = (settings: BtwSettings): string =>
323
+ settings.model && configuredModel(settings) ? selectedModelItemId(settings) : "same-as-main";
190
324
 
191
- const menu = defineMenu<BtwMenuState, BtwMenuScreen, BtwMenuAction, MenuContext>({
192
- start: "main",
193
- screens: {
194
- main: ({ state }) => ({
195
- kind: "actions",
196
- title: "Pi BTW",
197
- lines: [
198
- `Thinking: ${displayThinkingSummary(state.settings)} · Remember changes: ${displayRememberSummary(state.settings)}`,
199
- `Copy on select: ${effectiveFullscreenCopyOnSelect(state.settings) ? "On" : "Off"}`,
200
- ],
201
- items: [
202
- {
203
- id: "start",
204
- label: "Start side thread",
205
- description: "Open an empty side thread",
206
- action: "start",
207
- },
208
- {
209
- id: "start-tree",
210
- label: "Start from main thread tree",
211
- description: "Choose context without switching the main branch",
212
- action: "start-tree",
213
- },
214
- ...(resumeThreads.length > 0
215
- ? [
216
- {
217
- id: "resume" as const,
218
- label: "Resume side thread",
219
- description: "Continue an in-memory side thread",
220
- to: "resume" as const,
221
- },
222
- ]
223
- : []),
224
- {
225
- id: "settings",
226
- label: "Settings",
227
- description: "Choose thinking, keybindings, and selection copying",
228
- to: state.kind === "invalid" ? "invalid" : "settings",
229
- },
230
- ],
231
- hint: "close",
232
- }),
233
- resume: () => ({
234
- kind: "choice",
235
- title: "Resume BTW side thread",
236
- enableSearch: true,
237
- items: resumeThreads.map((thread) => ({
238
- id: thread.id,
239
- label: thread.title,
240
- description: `${thread.questionCount} ${thread.questionCount === 1 ? "question" : "questions"}`,
241
- })),
242
- action: "resume",
243
- viewportSize: 10,
244
- hint: "back",
245
- }),
246
- settings: ({ state }) => ({
247
- kind: "settings",
248
- title: "Pi BTW Settings",
249
- lines: [`User settings · ${displaySettingsPath}`],
250
- items: [
251
- {
252
- id: "thinkingLevel",
253
- label: "Thinking level",
254
- description: `Set the starting level for future pi-btw side threads. Currently ${currentMainThinkingLevel}.`,
255
- currentValue: displayThinkingLevel(state.settings),
256
- values: [SAME_AS_MAIN_THREAD, ...levels],
257
- action: "set-thinking",
258
- },
259
- {
260
- id: "rememberThinkingLevelChanges",
261
- label: "Remember thinking level changes",
262
- description: "Save shortcut changes for fixed thinking levels to pi-btw.json.",
263
- currentValue: effectiveRememberThinkingLevelChanges(state.settings) ? "On" : "Off",
264
- values: ["On", "Off"],
265
- action: "set-remember",
266
- },
267
- {
268
- id: "fullscreenCopyOnSelect",
269
- label: "Copy selection automatically",
270
- description:
271
- "Copy mouse selections immediately instead of with the configured copy key.",
272
- currentValue: effectiveFullscreenCopyOnSelect(state.settings) ? "On" : "Off",
273
- values: ["On", "Off"],
274
- action: "set-fullscreen-copy",
275
- },
276
- ...BTW_SHORTCUT_ACTIONS.map((action) => ({
277
- id: action,
278
- label: shortcutLabels[action],
279
- description:
280
- "Edit a BTW-only key combination or restore its default. Ctrl+C always hard-cancels.",
281
- currentValue: shortcutValue(state.settings, action),
282
- action: "edit-shortcut" as const,
283
- })),
284
- ],
285
- }),
286
- shortcut: ({ state }) => ({
287
- kind: "actions",
288
- title: shortcutLabels[shortcut],
289
- lines: [shortcutValue(state.settings, shortcut), "Ctrl+C always hard-cancels BTW."],
290
- items: [
291
- { id: "edit", label: "Edit key combination…", to: "shortcut-input" },
292
- { id: "reset", label: "Restore default", action: "reset-shortcut" },
293
- ],
294
- hint: "back",
295
- }),
296
- "shortcut-input": () => ({
297
- kind: "input",
298
- title: shortcutLabels[shortcut],
299
- lines: ["Type a key name, not the shortcut itself. For example: ctrl+q or f6."],
300
- placeholder: "Key combination",
301
- action: "save-shortcut",
302
- hint: "back",
303
- }),
304
- invalid: ({ state }) => ({
305
- kind: "detail",
306
- title: "Pi BTW Settings · Read only",
307
- lines: [
308
- `Invalid settings file. Fix ${displaySettingsPath} before saving.`,
309
- sanitizeSingleLine(state.reason ?? "The settings file is invalid."),
310
- ],
311
- hint: "back",
312
- }),
313
- },
314
- actions: {
315
- "edit-shortcut": ({ itemId }) => {
316
- if (!BTW_SHORTCUT_ACTIONS.includes(itemId as BtwShortcutAction))
317
- return { kind: "rejected" };
318
- shortcut = itemId as BtwShortcutAction;
319
- return { kind: "to", screen: "shortcut" };
320
- },
321
- "save-shortcut": ({ state, value, signal }) =>
322
- saveShortcut(state, value?.trim() ?? "", signal),
323
- "reset-shortcut": ({ state, signal }) => saveShortcut(state, undefined, signal),
324
- start: async () => {
325
- startSelected = true;
326
- return { kind: "close" };
327
- },
328
- "start-tree": async () => {
329
- treeSelected = true;
330
- return { kind: "close" };
331
- },
332
- resume: async ({ itemId }: { itemId: string }) => {
333
- if (!resumeThreads.some((thread) => thread.id === itemId)) {
334
- return { kind: "rejected" } as const;
335
- }
336
- resumedThreadId = itemId;
337
- return { kind: "close" } as const;
338
- },
339
- "set-thinking": async ({ value, signal }) => {
340
- if (!value) return { kind: "rejected" };
341
- const patch =
342
- value === SAME_AS_MAIN_THREAD
343
- ? ({ thinkingLevel: undefined } satisfies BtwSettingsPatch)
344
- : levels.includes(value as BtwThinkingLevel)
345
- ? ({ thinkingLevel: value as BtwThinkingLevel } satisfies BtwSettingsPatch)
346
- : undefined;
347
- if (!patch) return { kind: "rejected" };
348
- try {
349
- await updateSettings(patch, { settingsPath, signal });
350
- if (signal.aborted) return { kind: "rejected" };
351
- notifySafely(ctx, `Pi BTW thinking level: ${value}.`, "info");
352
- return { kind: "stay" };
353
- } catch (error) {
354
- if (!signal.aborted) notifySaveFailure(ctx, error);
355
- return { kind: "rejected" };
356
- }
357
- },
358
- "set-remember": async ({ value, signal }) => {
359
- if (value !== "On" && value !== "Off") return { kind: "rejected" };
360
- try {
361
- await updateSettings(
362
- { rememberThinkingLevelChanges: value === "On" },
363
- { settingsPath, signal },
364
- );
365
- if (signal.aborted) return { kind: "rejected" };
366
- notifySafely(ctx, `Remember thinking level changes: ${value}.`, "info");
367
- return { kind: "stay" };
368
- } catch (error) {
369
- if (!signal.aborted) notifySaveFailure(ctx, error);
370
- return { kind: "rejected" };
371
- }
372
- },
373
- "set-fullscreen-copy": async ({ value, signal }) => {
374
- if (value !== "On" && value !== "Off") return { kind: "rejected" };
375
- try {
376
- await updateSettings(
377
- { fullscreenCopyOnSelect: value === "On" },
378
- { settingsPath, signal },
379
- );
380
- if (signal.aborted) return { kind: "rejected" };
381
- notifySafely(ctx, `Copy selection automatically: ${value}.`, "info");
382
- return { kind: "stay" };
383
- } catch (error) {
384
- if (!signal.aborted) notifySaveFailure(ctx, error);
385
- return { kind: "rejected" };
386
- }
387
- },
388
- },
389
- });
325
+ const menu = defineMenu<BtwMenuState, BtwMenuScreen, BtwMenuAction, MenuContext>({
326
+ start: "main",
327
+ screens: {
328
+ main: ({ state }) => ({
329
+ kind: "actions",
330
+ title: "Pi BTW",
331
+ lines: [
332
+ `Model: ${displayModelValue(state.settings)}`,
333
+ `Thinking: ${displayThinkingSummary(state.settings)} · Remember changes: ${displayRememberSummary(state.settings)}`,
334
+ `Copy on select: ${effectiveFullscreenCopyOnSelect(state.settings) ? "On" : "Off"}`,
335
+ ],
336
+ items: [
337
+ {
338
+ id: "start",
339
+ label: "Start side thread",
340
+ description: "Open an empty side thread",
341
+ action: "start",
342
+ },
343
+ {
344
+ id: "start-tree",
345
+ label: "Start from main thread tree…",
346
+ description: "Choose context without switching the main branch",
347
+ action: "start-tree",
348
+ },
349
+ ...(resumeThreads.length > 0
350
+ ? [
351
+ {
352
+ id: "resume" as const,
353
+ label: "Resume side thread",
354
+ description: "Continue an in-memory side thread",
355
+ to: "resume" as const,
356
+ },
357
+ ]
358
+ : []),
359
+ {
360
+ id: "settings",
361
+ label: "Settings",
362
+ description: "Choose model, thinking, keybindings, and selection copying",
363
+ to: state.kind === "invalid" ? "invalid" : "settings",
364
+ },
365
+ ],
366
+ hint: "close",
367
+ }),
368
+ resume: () => ({
369
+ kind: "choice",
370
+ title: "Resume BTW side thread",
371
+ enableSearch: true,
372
+ items: resumeThreads.map((thread) => ({
373
+ id: thread.id,
374
+ label: thread.title,
375
+ description: `${thread.questionCount} ${thread.questionCount === 1 ? "question" : "questions"}`,
376
+ })),
377
+ action: "resume",
378
+ viewportSize: 10,
379
+ hint: "back",
380
+ }),
381
+ settings: ({ state }) => ({
382
+ kind: "settings",
383
+ title: "Pi BTW Settings",
384
+ lines: [`User settings · ${displaySettingsPath}`],
385
+ items: [
386
+ {
387
+ id: "model",
388
+ label: "Model",
389
+ description: "Choose the model for future pi-btw side threads without changing the main session.",
390
+ currentValue: displayModelValue(state.settings),
391
+ action: "open-model",
392
+ },
393
+ {
394
+ id: "thinkingLevel",
395
+ label: "Thinking level",
396
+ description: `Set the starting level for future pi-btw side threads. Currently ${currentMainThinkingLevel(state.settings)}.`,
397
+ currentValue: displayThinkingLevel(state.settings),
398
+ values: [SAME_AS_MAIN_THREAD, ...thinkingLevels(state.settings)],
399
+ action: "set-thinking",
400
+ },
401
+ {
402
+ id: "rememberThinkingLevelChanges",
403
+ label: "Remember thinking level changes",
404
+ description: "Save shortcut changes for fixed thinking levels to pi-btw.json.",
405
+ currentValue: effectiveRememberThinkingLevelChanges(state.settings) ? "On" : "Off",
406
+ values: ["On", "Off"],
407
+ action: "set-remember",
408
+ },
409
+ {
410
+ id: "fullscreenCopyOnSelect",
411
+ label: "Copy selection automatically",
412
+ description: "Copy mouse selections immediately instead of with the configured copy key.",
413
+ currentValue: effectiveFullscreenCopyOnSelect(state.settings) ? "On" : "Off",
414
+ values: ["On", "Off"],
415
+ action: "set-fullscreen-copy",
416
+ },
417
+ ...BTW_SHORTCUT_ACTIONS.map((action) => ({
418
+ id: action,
419
+ label: shortcutLabels[action],
420
+ description: "Edit a BTW-only key combination or restore its default. Ctrl+C always hard-cancels.",
421
+ currentValue: shortcutValue(state.settings, action),
422
+ action: "edit-shortcut" as const,
423
+ })),
424
+ ],
425
+ }),
426
+ model: ({ state }) => ({
427
+ kind: "choice",
428
+ title: "Pi BTW Model",
429
+ lines: [
430
+ "Same as main thread is the default and fallback when a configured model is unavailable.",
431
+ ...(state.settings.model && !selectableConfiguredModel(state.settings)
432
+ ? [`Configured: ${displayModelValue(state.settings)}`]
433
+ : []),
434
+ ],
435
+ items: modelItems(state.settings),
436
+ action: "set-model",
437
+ currentItemId: currentModelItemId(state.settings),
438
+ initialItemId: selectedModelItemId(state.settings),
439
+ enableSearch: true,
440
+ viewportSize: 10,
441
+ hint: "back",
442
+ }),
443
+ shortcut: ({ state }) => ({
444
+ kind: "actions",
445
+ title: shortcutLabels[shortcut],
446
+ lines: [shortcutValue(state.settings, shortcut), "Ctrl+C always hard-cancels BTW."],
447
+ items: [
448
+ { id: "edit", label: "Edit key combination…", to: "shortcut-input" },
449
+ { id: "reset", label: "Restore default", action: "reset-shortcut" },
450
+ ],
451
+ hint: "back",
452
+ }),
453
+ "shortcut-input": () => ({
454
+ kind: "input",
455
+ title: shortcutLabels[shortcut],
456
+ lines: ["Type a key name, not the shortcut itself. For example: ctrl+q or f6."],
457
+ placeholder: "Key combination",
458
+ action: "save-shortcut",
459
+ hint: "back",
460
+ }),
461
+ invalid: ({ state }) => ({
462
+ kind: "detail",
463
+ title: "Pi BTW Settings · Read only",
464
+ lines: [
465
+ `Invalid settings file. Fix ${displaySettingsPath} before saving.`,
466
+ sanitizeSingleLine(state.reason ?? "The settings file is invalid."),
467
+ ],
468
+ hint: "back",
469
+ }),
470
+ },
471
+ actions: {
472
+ "edit-shortcut": ({ itemId }) => {
473
+ if (!BTW_SHORTCUT_ACTIONS.includes(itemId as BtwShortcutAction)) return { kind: "rejected" };
474
+ shortcut = itemId as BtwShortcutAction;
475
+ return { kind: "to", screen: "shortcut" };
476
+ },
477
+ "save-shortcut": ({ state, value, signal }) => saveShortcut(state, value?.trim() ?? "", signal),
478
+ "reset-shortcut": ({ state, signal }) => saveShortcut(state, undefined, signal),
479
+ "open-model": async () => ({ kind: "to", screen: "model" }),
480
+ "set-model": async ({ state, itemId, signal }) => {
481
+ if (itemId === "configured-model" && configuredModel(state.settings)) {
482
+ return { kind: "back" };
483
+ }
484
+ const model = itemId ? modelsByItemId.get(itemId) : undefined;
485
+ if (itemId !== "same-as-main" && (!model || !rawModelReference(model))) return { kind: "rejected" };
486
+ const result = await saveModel(model, signal);
487
+ if (result.kind === "failed") {
488
+ notifySaveFailure(ctx, result.error);
489
+ return { kind: "rejected" };
490
+ }
491
+ if (result.kind === "cancelled" || signal.aborted) return { kind: "close" };
492
+ notifySafely(
493
+ ctx,
494
+ model ? `Pi BTW model: ${displayModelReference(model)}.` : `Pi BTW model: ${SAME_AS_MAIN_THREAD}.`,
495
+ "info",
496
+ );
497
+ return { kind: "back" };
498
+ },
499
+ start: async () => {
500
+ startSelected = true;
501
+ return { kind: "close" };
502
+ },
503
+ "start-tree": async () => {
504
+ treeSelected = true;
505
+ return { kind: "close" };
506
+ },
507
+ resume: async ({ itemId }: { itemId: string }) => {
508
+ if (!resumeThreads.some((thread) => thread.id === itemId)) {
509
+ return { kind: "rejected" } as const;
510
+ }
511
+ resumedThreadId = itemId;
512
+ return { kind: "close" } as const;
513
+ },
514
+ "set-thinking": async ({ state, value, signal }) => {
515
+ if (!value) return { kind: "rejected" };
516
+ const levels = thinkingLevels(state.settings);
517
+ const patch =
518
+ value === SAME_AS_MAIN_THREAD
519
+ ? ({ thinkingLevel: undefined } satisfies BtwSettingsPatch)
520
+ : levels.includes(value as BtwThinkingLevel)
521
+ ? ({ thinkingLevel: value as BtwThinkingLevel } satisfies BtwSettingsPatch)
522
+ : undefined;
523
+ if (!patch) return { kind: "rejected" };
524
+ try {
525
+ await updateSettings(patch, { settingsPath, signal });
526
+ if (signal.aborted) return { kind: "rejected" };
527
+ notifySafely(ctx, `Pi BTW thinking level: ${value}.`, "info");
528
+ return { kind: "stay" };
529
+ } catch (error) {
530
+ if (!signal.aborted) notifySaveFailure(ctx, error);
531
+ return { kind: "rejected" };
532
+ }
533
+ },
534
+ "set-remember": async ({ value, signal }) => {
535
+ if (value !== "On" && value !== "Off") return { kind: "rejected" };
536
+ try {
537
+ await updateSettings({ rememberThinkingLevelChanges: value === "On" }, { settingsPath, signal });
538
+ if (signal.aborted) return { kind: "rejected" };
539
+ notifySafely(ctx, `Remember thinking level changes: ${value}.`, "info");
540
+ return { kind: "stay" };
541
+ } catch (error) {
542
+ if (!signal.aborted) notifySaveFailure(ctx, error);
543
+ return { kind: "rejected" };
544
+ }
545
+ },
546
+ "set-fullscreen-copy": async ({ value, signal }) => {
547
+ if (value !== "On" && value !== "Off") return { kind: "rejected" };
548
+ try {
549
+ await updateSettings({ fullscreenCopyOnSelect: value === "On" }, { settingsPath, signal });
550
+ if (signal.aborted) return { kind: "rejected" };
551
+ notifySafely(ctx, `Copy selection automatically: ${value}.`, "info");
552
+ return { kind: "stay" };
553
+ } catch (error) {
554
+ if (!signal.aborted) notifySaveFailure(ctx, error);
555
+ return { kind: "rejected" };
556
+ }
557
+ },
558
+ },
559
+ });
390
560
 
391
- const result = await runBtwMenuPreservingEditor(
392
- ctx,
393
- (menuContext) => runMenu(menuContext, menu, { getState: loadState }),
394
- (manager) => {
395
- keybindings = manager;
396
- },
397
- );
398
- if (result.kind !== "closed" || result.reason !== "close") return "closed";
399
- if (resumedThreadId) return { kind: "resume", threadId: resumedThreadId };
400
- if (treeSelected) return "tree";
401
- return startSelected ? "start" : "closed";
561
+ const result = await runBtwMenuPreservingEditor(
562
+ ctx,
563
+ (menuContext) => runMenu(menuContext, menu, { getState: loadState }),
564
+ (manager) => {
565
+ keybindings = manager;
566
+ },
567
+ );
568
+ if (result.kind !== "closed" || result.reason !== "close") return "closed";
569
+ if (resumedThreadId) return { kind: "resume", threadId: resumedThreadId };
570
+ if (treeSelected) return "tree";
571
+ return startSelected ? "start" : "closed";
402
572
  }
403
573
 
404
574
  export async function showBtwCustomPreservingEditor<T>(
405
- ctx: ExtensionCommandContext,
406
- factory: BtwCustomFactory<T>,
575
+ ctx: ExtensionCommandContext,
576
+ factory: BtwCustomFactory<T>,
407
577
  ): Promise<T | undefined> {
408
- let liveEditorText = ctx.ui.getEditorText();
409
- let completed = false;
410
- const result = await ctx.ui.custom<T>((tui, theme, keybindings, done) =>
411
- factory(tui, theme, keybindings, (value) => {
412
- try {
413
- liveEditorText = ctx.ui.getEditorText();
414
- } catch {
415
- // Keep completion finite if session replacement invalidates the editor context.
416
- }
417
- completed = true;
418
- done(value);
419
- }),
420
- );
421
- if (completed) {
422
- try {
423
- if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
424
- } catch {
425
- // A replaced context owns a different editor and must not receive stale restoration.
426
- }
427
- }
428
- return result;
578
+ let liveEditorText = ctx.ui.getEditorText();
579
+ let completed = false;
580
+ const result = await ctx.ui.custom<T>((tui, theme, keybindings, done) =>
581
+ factory(tui, theme, keybindings, (value) => {
582
+ try {
583
+ liveEditorText = ctx.ui.getEditorText();
584
+ } catch {
585
+ // Keep completion finite if session replacement invalidates the editor context.
586
+ }
587
+ completed = true;
588
+ done(value);
589
+ }),
590
+ );
591
+ if (completed) {
592
+ try {
593
+ if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
594
+ } catch {
595
+ // A replaced context owns a different editor and must not receive stale restoration.
596
+ }
597
+ }
598
+ return result;
429
599
  }
430
600
 
431
601
  export async function runBtwMenuPreservingEditor(
432
- ctx: ExtensionCommandContext,
433
- run: (menuContext: MenuContext) => Promise<RunMenuResult>,
434
- onKeybindings?: (keybindings: KeybindingsManager) => void,
602
+ ctx: ExtensionCommandContext,
603
+ run: (menuContext: MenuContext) => Promise<RunMenuResult>,
604
+ onKeybindings?: (keybindings: KeybindingsManager) => void,
435
605
  ): Promise<RunMenuResult> {
436
- let liveEditorText = ctx.ui.getEditorText();
437
- let completed = false;
438
- const ui = new Proxy(ctx.ui, {
439
- get(target, property) {
440
- if (property === "custom") {
441
- return <Value>(factory: BtwCustomFactory<Value>, customOptions?: BtwCustomOptions) =>
442
- target.custom<Value>((tui, theme, keybindings, done) => {
443
- onKeybindings?.(keybindings);
444
- return factory(tui, theme, keybindings, (value) => {
445
- try {
446
- liveEditorText = target.getEditorText();
447
- } catch {
448
- // Keep completion finite if session replacement invalidates the editor context.
449
- }
450
- completed = true;
451
- done(value);
452
- });
453
- }, customOptions);
454
- }
455
- const value = Reflect.get(target, property, target) as unknown;
456
- return typeof value === "function" ? value.bind(target) : value;
457
- },
458
- });
459
- const result = await run({ mode: ctx.mode, hasUI: ctx.hasUI, ui });
460
- if (result.kind !== "stale" && completed) {
461
- try {
462
- if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
463
- } catch {
464
- // A replaced context owns a different editor and must not receive stale restoration.
465
- }
466
- }
467
- return result;
606
+ let liveEditorText = ctx.ui.getEditorText();
607
+ let completed = false;
608
+ const ui = new Proxy(ctx.ui, {
609
+ get(target, property) {
610
+ if (property === "custom") {
611
+ return <Value>(factory: BtwCustomFactory<Value>, customOptions?: BtwCustomOptions) =>
612
+ target.custom<Value>((tui, theme, keybindings, done) => {
613
+ onKeybindings?.(keybindings);
614
+ return factory(tui, theme, keybindings, (value) => {
615
+ try {
616
+ liveEditorText = target.getEditorText();
617
+ } catch {
618
+ // Keep completion finite if session replacement invalidates the editor context.
619
+ }
620
+ completed = true;
621
+ done(value);
622
+ });
623
+ }, customOptions);
624
+ }
625
+ const value = Reflect.get(target, property, target) as unknown;
626
+ return typeof value === "function" ? value.bind(target) : value;
627
+ },
628
+ });
629
+ const result = await run({ mode: ctx.mode, hasUI: ctx.hasUI, ui });
630
+ if (result.kind !== "stale" && completed) {
631
+ try {
632
+ if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
633
+ } catch {
634
+ // A replaced context owns a different editor and must not receive stale restoration.
635
+ }
636
+ }
637
+ return result;
638
+ }
639
+
640
+ function deduplicateModels(models: readonly Model<Api>[]): Model<Api>[] {
641
+ return models.filter((model, index) => models.findIndex((candidate) => sameModel(candidate, model)) === index);
642
+ }
643
+
644
+ function availableModelsInScope(
645
+ availableModels: readonly Model<Api>[],
646
+ scopedModels: ExtensionCommandContext["scopedModels"],
647
+ ): Model<Api>[] {
648
+ if (scopedModels.length === 0) return [...availableModels];
649
+ return deduplicateModels(
650
+ scopedModels.flatMap((entry) => {
651
+ const available = availableModels.find((model) => sameModel(model, entry.model));
652
+ return available ? [available] : [];
653
+ }),
654
+ );
655
+ }
656
+
657
+ function sameModel(left: Pick<Model<Api>, "provider" | "id">, right: Pick<Model<Api>, "provider" | "id">): boolean {
658
+ return left.provider === right.provider && left.id === right.id;
468
659
  }
469
660
 
470
661
  function clampToAvailableThinkingLevel(
471
- requested: BtwThinkingLevel,
472
- available: readonly BtwThinkingLevel[],
662
+ requested: BtwThinkingLevel,
663
+ available: readonly BtwThinkingLevel[],
473
664
  ): BtwThinkingLevel {
474
- if (available.includes(requested)) return requested;
475
- const requestedIndex = BTW_THINKING_LEVELS.indexOf(requested);
476
- for (let index = requestedIndex; index < BTW_THINKING_LEVELS.length; index += 1) {
477
- const candidate = BTW_THINKING_LEVELS[index];
478
- if (candidate && available.includes(candidate)) return candidate;
479
- }
480
- for (let index = requestedIndex - 1; index >= 0; index -= 1) {
481
- const candidate = BTW_THINKING_LEVELS[index];
482
- if (candidate && available.includes(candidate)) return candidate;
483
- }
484
- return available[0] ?? "off";
665
+ if (available.includes(requested)) return requested;
666
+ const requestedIndex = BTW_THINKING_LEVELS.indexOf(requested);
667
+ for (let index = requestedIndex; index < BTW_THINKING_LEVELS.length; index += 1) {
668
+ const candidate = BTW_THINKING_LEVELS[index];
669
+ if (candidate && available.includes(candidate)) return candidate;
670
+ }
671
+ for (let index = requestedIndex - 1; index >= 0; index -= 1) {
672
+ const candidate = BTW_THINKING_LEVELS[index];
673
+ if (candidate && available.includes(candidate)) return candidate;
674
+ }
675
+ return available[0] ?? "off";
485
676
  }
486
677
 
487
678
  function notifySaveFailure(ctx: ExtensionCommandContext, error: unknown): void {
488
- notifySafely(
489
- ctx,
490
- `Pi BTW settings were not saved; the previous value remains active: ${formatError(error)}`,
491
- "error",
492
- );
679
+ notifySafely(
680
+ ctx,
681
+ `Pi BTW settings were not saved; the previous value remains active: ${formatError(error)}`,
682
+ "error",
683
+ );
493
684
  }
494
685
 
495
686
  function notifySafely(
496
- ctx: ExtensionCommandContext,
497
- message: string,
498
- level: Parameters<ExtensionCommandContext["ui"]["notify"]>[1],
687
+ ctx: ExtensionCommandContext,
688
+ message: string,
689
+ level: Parameters<ExtensionCommandContext["ui"]["notify"]>[1],
499
690
  ): void {
500
- try {
501
- ctx.ui.notify(sanitizeSingleLine(message), level);
502
- } catch {
503
- // A completed save remains valid if its command context was replaced before notification.
504
- }
691
+ try {
692
+ ctx.ui.notify(sanitizeSingleLine(message), level);
693
+ } catch {
694
+ // A completed save remains valid if its command context was replaced before notification.
695
+ }
505
696
  }
506
697
 
507
698
  function formatError(error: unknown): string {
508
- return error instanceof Error ? error.message : String(error);
699
+ return error instanceof Error ? error.message : String(error);
509
700
  }