@narumitw/pi-btw 0.63.3 → 0.63.5

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