@narumitw/pi-btw 0.61.1 → 0.62.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.
@@ -9,7 +9,7 @@ import {
9
9
  } from "@earendil-works/pi-tui";
10
10
  import { formatKeyLabel } from "./text.js";
11
11
 
12
- export const BTW_SHORTCUT_ACTIONS = ["exit", "cycleThinkingLevel", "bringToMain"] as const;
12
+ export const BTW_SHORTCUT_ACTIONS = ["exit", "cycleThinkingLevel", "bringToMain", "switchPane"] as const;
13
13
  export type BtwShortcutAction = (typeof BTW_SHORTCUT_ACTIONS)[number];
14
14
  export type BtwKeybindingOverrides = Partial<Record<BtwShortcutAction, string>>;
15
15
 
@@ -35,8 +35,8 @@ const SPECIAL: Record<string, number> = {
35
35
  const FUNCTION_INPUTS = ["OP", "OQ", "OR", "OS", "[15~", "[17~", "[18~", "[19~", "[20~", "[21~", "[23~", "[24~"];
36
36
  // All cross-identity legacy collisions in Pi's matchesKey(): raw Ctrl bytes,
37
37
  // ESC-prefixed bytes (including Alt+arrows), BS/DEL, Enter and Shift+Tab.
38
- // CSI-u, keypad, lock bits, shifted letters and modifyOtherKeys normalize to
39
- // the same key+modifiers; probe that identity instead of duplicating the parser.
38
+ // Keypad, lock bits and shifted letters preserve identities; enhanced
39
+ // physical/logical symbols and printable layout alternatives are probed below.
40
40
  const LEGACY_INPUTS = [
41
41
  ...Array.from({ length: 128 }, (_, code) => String.fromCharCode(code)),
42
42
  ...Array.from({ length: 128 }, (_, code) => `\u001b${String.fromCharCode(code)}`),
@@ -48,7 +48,7 @@ const LEGACY_INPUTS = [
48
48
  ...FUNCTION_INPUTS.map((suffix) => `\u001b${suffix}`),
49
49
  ];
50
50
 
51
- /** Strict settings syntax; Pi itself ignores unknown/duplicate modifier tokens. */
51
+ /** Strict settings syntax; reject unknown and duplicate modifier tokens. */
52
52
  export function normalizeBtwKey(value: unknown): string | undefined {
53
53
  if (typeof value !== "string" || value.length > 80 || /[\s\p{Cc}]/u.test(value)) return undefined;
54
54
  const parts = value.toLowerCase().split("+");
@@ -81,9 +81,55 @@ function inputsFor(key: string): string[] {
81
81
  return inputs.filter((input) => matchesKey(input, key as KeyId));
82
82
  }
83
83
 
84
+ export function btwKeyHasReachableInput(candidate: string, blockers: readonly string[]): boolean {
85
+ const key = normalizeBtwKey(candidate);
86
+ return (
87
+ key !== undefined &&
88
+ inputsFor(key).some(
89
+ (input) => !blockers.some((other) => typeof other === "string" && matchesKey(input, other as KeyId)),
90
+ )
91
+ );
92
+ }
93
+
94
+ function protocolIdentity(value: string): { codepoint: number; modifier: number } | undefined {
95
+ let base = value.toLowerCase();
96
+ const seen = new Set<string>();
97
+ for (;;) {
98
+ const part = MODIFIERS.find((modifier) => base.startsWith(`${modifier}+`));
99
+ if (!part) break;
100
+ if (seen.has(part)) return undefined;
101
+ seen.add(part);
102
+ base = base.slice(part.length + 1);
103
+ }
104
+ if (!base || (base.includes("+") && base !== "+")) return undefined;
105
+ if (base === "esc") base = "escape";
106
+ if (base === "return") base = "enter";
107
+ const codepoint = SPECIAL[base] ?? (base.length === 1 ? base.charCodeAt(0) : undefined);
108
+ if (codepoint === undefined) return undefined;
109
+ return { codepoint, modifier: MODIFIERS.reduce((mask, part, bit) => mask | (seen.has(part) ? 1 << bit : 0), 0) };
110
+ }
111
+
112
+ function protocolInputs(first: string, second: string): string[] {
113
+ const identity = protocolIdentity(first);
114
+ const alternate = protocolIdentity(second)?.codepoint;
115
+ if (!identity || alternate === undefined) return [];
116
+ const { codepoint, modifier } = identity;
117
+ return [
118
+ // Alternate layout fields describe printable keys, not invented functional
119
+ // key mappings such as Ctrl+Up with a Latin base-layout key.
120
+ ...(codepoint >= 33 && codepoint <= 126 && alternate >= 33 && alternate <= 126
121
+ ? [`\u001b[${codepoint}:${alternate};${modifier + 1}u`, `\u001b[${codepoint}::${alternate};${modifier + 1}u`]
122
+ : []),
123
+ `\u001b[27;${modifier + 1};${codepoint}~`,
124
+ ];
125
+ }
126
+
84
127
  export function btwKeysOverlap(first: string, second: string): boolean {
85
128
  const normalized = normalizeBtwKey(first);
86
- return normalized !== undefined && inputsFor(normalized).some((input) => matchesKey(input, second as KeyId));
129
+ if (normalized === undefined) return false;
130
+ return [...inputsFor(normalized), ...protocolInputs(normalized, second), ...protocolInputs(second, normalized)].some(
131
+ (input) => matchesKey(input, normalized as KeyId) && matchesKey(input, second as KeyId),
132
+ );
87
133
  }
88
134
 
89
135
  export interface BtwShortcuts {
@@ -158,12 +204,13 @@ function resolveShortcutSnapshot(
158
204
  copyOnSelect = true,
159
205
  ): BtwShortcuts {
160
206
  const reserved = reservedKeys(keybindings, copyOnSelect);
161
- const keys: BtwShortcuts["keys"] = { exit: ["ctrl+c"], cycleThinkingLevel: [], bringToMain: [] };
207
+ const keys: BtwShortcuts["keys"] = { exit: ["ctrl+c"], cycleThinkingLevel: [], bringToMain: [], switchPane: [] };
162
208
  const warnings: string[] = [];
163
209
  const defaults: Record<BtwShortcutAction, readonly string[]> = {
164
210
  exit: ["ctrl+c"],
165
211
  cycleThinkingLevel: keybindings.getKeys("app.thinking.cycle"),
166
212
  bringToMain: ["ctrl+r"],
213
+ switchPane: ["f6", "f7", "f8"],
167
214
  };
168
215
  const usable = (action: BtwShortcutAction, candidate: string, inherited = false): string | undefined => {
169
216
  const key = normalizeBtwKey(candidate);
@@ -171,10 +218,7 @@ function resolveShortcutSnapshot(
171
218
  const inputs = inputsFor(key);
172
219
  if (!inputs.length) return undefined;
173
220
  if (action === "exit" && key === "ctrl+c") return key;
174
- if (
175
- reserved.some((other) => typeof other === "string" && inputs.some((input) => matchesKey(input, other as KeyId)))
176
- )
177
- return undefined;
221
+ if (reserved.some((other) => typeof other === "string" && btwKeysOverlap(key, other))) return undefined;
178
222
  return key;
179
223
  };
180
224
  const candidates: BtwKeybindingOverrides = {};
@@ -186,6 +230,20 @@ function resolveShortcutSnapshot(
186
230
  const override = overrides[action];
187
231
  if (override !== undefined) candidates[action] = usable(action, override);
188
232
  }
233
+ // Pane transfer is additive: never displace an existing override or inherited
234
+ // thinking action merely because it uses one of the pane action's fallbacks.
235
+ availableDefaults.switchPane = availableDefaults.switchPane
236
+ .filter(
237
+ (key) =>
238
+ BTW_SHORTCUT_ACTIONS.some(
239
+ (action) =>
240
+ action !== "switchPane" &&
241
+ (candidates[action] ? [candidates[action]] : availableDefaults[action]).some((other) =>
242
+ btwKeysOverlap(key, other),
243
+ ),
244
+ ) === false,
245
+ )
246
+ .slice(0, 1);
189
247
  // Compare the complete proposal, not only actions visited earlier. Reject conflicts
190
248
  // together, then repeat because a rejected override restores its default bindings.
191
249
  for (;;) {
@@ -220,7 +278,12 @@ function resolveShortcutSnapshot(
220
278
  (other) => other !== action && keys[other].some((used) => btwKeysOverlap(key, used)),
221
279
  ),
222
280
  );
223
- keys[action] = action === "exit" ? [...new Set([...effective, "ctrl+c"])] : effective;
281
+ keys[action] =
282
+ action === "exit"
283
+ ? [...new Set([...effective, "ctrl+c"])]
284
+ : action === "switchPane"
285
+ ? effective.slice(0, 1)
286
+ : effective;
224
287
  if (!keys[action].length && (override !== undefined || defaults[action].length > 0))
225
288
  warnings.push(`${action}: no usable shortcut; change Pi BTW Settings or Pi keybindings.`);
226
289
  }
@@ -249,7 +312,9 @@ export function validateBtwShortcutEdit(
249
312
  for (const item of BTW_SHORTCUT_ACTIONS) {
250
313
  if (
251
314
  (item === action && !resolved.keys[item].includes(normalizeBtwKey(value) ?? "")) ||
252
- (item !== action && previous.keys[item].some((key) => !resolved.keys[item].includes(key)))
315
+ (item !== action &&
316
+ !(item === "switchPane" && overrides.switchPane === undefined) &&
317
+ previous.keys[item].some((key) => !resolved.keys[item].includes(key)))
253
318
  ) {
254
319
  return `${item} conflicts with another BTW shortcut, editing, selection, search, scrolling, or copying. Choose a different key.`;
255
320
  }
@@ -257,22 +322,35 @@ export function validateBtwShortcutEdit(
257
322
  return undefined;
258
323
  }
259
324
 
325
+ const hostInputBlockersByTui = new WeakMap<TUI, readonly string[]>();
326
+ export function setBtwHostInputBlockers(tui: TUI, keys: readonly string[]): void {
327
+ hostInputBlockersByTui.set(tui, keys);
328
+ }
329
+ export function getBtwHostInputBlockers(tui: TUI): readonly string[] {
330
+ return hostInputBlockersByTui.get(tui) ?? [];
331
+ }
332
+
333
+ const keybindingsByTui = new WeakMap<TUI, KeybindingsManager>();
334
+ export function setBtwKeybindings(tui: TUI, keybindings: KeybindingsManager): void {
335
+ keybindingsByTui.set(tui, keybindings);
336
+ }
337
+ export function getBtwKeybindings(tui: TUI, keybindings?: KeybindingsManager): KeybindingsManager {
338
+ return (
339
+ keybindingsByTui.get(tui) ??
340
+ keybindings ??
341
+ new KeybindingsManager({
342
+ ...TUI_KEYBINDINGS,
343
+ "app.thinking.cycle": { defaultKeys: "shift+tab" },
344
+ })
345
+ );
346
+ }
347
+
260
348
  const bindingsByTui = new WeakMap<TUI, BtwShortcuts>();
261
349
  export function setBtwShortcuts(tui: TUI, shortcuts: BtwShortcuts): void {
262
350
  bindingsByTui.set(tui, shortcuts);
263
351
  }
264
352
  export function getBtwShortcuts(tui: TUI, keybindings?: KeybindingsManager): BtwShortcuts {
265
- return (
266
- bindingsByTui.get(tui) ??
267
- resolveBtwShortcuts(
268
- {},
269
- keybindings ??
270
- new KeybindingsManager({
271
- ...TUI_KEYBINDINGS,
272
- "app.thinking.cycle": { defaultKeys: "shift+tab" },
273
- }),
274
- )
275
- );
353
+ return bindingsByTui.get(tui) ?? resolveBtwShortcuts({}, getBtwKeybindings(tui, keybindings));
276
354
  }
277
355
 
278
356
  /** Keep split bracketed-paste payloads away from screen-level shortcuts. */
package/src/menu.ts CHANGED
@@ -129,6 +129,7 @@ export async function showBtwCommandMenu(
129
129
  exit: "Exit shortcut",
130
130
  cycleThinkingLevel: "Cycle thinking level shortcut",
131
131
  bringToMain: "Bring to main shortcut",
132
+ switchPane: "Switch pane shortcut",
132
133
  };
133
134
  const shortcutValue = (settings: BtwSettings, action: BtwShortcutAction): string => {
134
135
  if (!keybindings) return "Default";
@@ -592,7 +593,7 @@ export async function showBtwCommandMenu(
592
593
 
593
594
  const result = await runBtwMenuPreservingEditor(
594
595
  ctx,
595
- (menuContext) => runMenu(menuContext, menu, { getState: loadState }),
596
+ (menuContext) => runMenu(menuContext, menu, { getState: loadState, signal: ctx.signal }),
596
597
  (manager) => {
597
598
  keybindings = manager;
598
599
  },
@@ -607,27 +608,33 @@ export async function showBtwCustomPreservingEditor<T>(
607
608
  ctx: ExtensionCommandContext,
608
609
  factory: BtwCustomFactory<T>,
609
610
  ): Promise<T | undefined> {
611
+ const { runCustomInteraction } = await import("@narumitw/pi-tui-kit");
612
+ if (ctx.signal?.aborted) return undefined;
610
613
  let liveEditorText = ctx.ui.getEditorText();
611
614
  let completed = false;
612
- const result = await ctx.ui.custom<T>((tui, theme, keybindings, done) =>
613
- factory(tui, theme, keybindings, (value) => {
614
- try {
615
- liveEditorText = ctx.ui.getEditorText();
616
- } catch {
617
- // Keep completion finite if session replacement invalidates the editor context.
618
- }
619
- completed = true;
620
- done(value);
621
- }),
622
- );
623
- if (completed) {
615
+ const result = await runCustomInteraction<T>(ctx, {
616
+ signal: ctx.signal,
617
+ create: ({ tui, theme, keybindings, complete }) =>
618
+ factory(tui, theme, keybindings, (value) => {
619
+ if (ctx.signal?.aborted) return;
620
+ try {
621
+ liveEditorText = ctx.ui.getEditorText();
622
+ } catch {
623
+ // Keep completion finite if session replacement invalidates the editor context.
624
+ }
625
+ completed = true;
626
+ complete(value);
627
+ }),
628
+ });
629
+ if (result.kind === "error") throw result.error;
630
+ if (!ctx.signal?.aborted && completed) {
624
631
  try {
625
632
  if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
626
633
  } catch {
627
634
  // A replaced context owns a different editor and must not receive stale restoration.
628
635
  }
629
636
  }
630
- return result;
637
+ return result.kind === "completed" ? result.value : undefined;
631
638
  }
632
639
 
633
640
  export async function runBtwMenuPreservingEditor(
@@ -635,31 +642,38 @@ export async function runBtwMenuPreservingEditor(
635
642
  run: (menuContext: MenuContext) => Promise<RunMenuResult>,
636
643
  onKeybindings?: (keybindings: KeybindingsManager) => void,
637
644
  ): Promise<RunMenuResult> {
645
+ if (ctx.signal?.aborted) return { kind: "stale" };
638
646
  let liveEditorText = ctx.ui.getEditorText();
639
647
  let completed = false;
640
648
  const ui = new Proxy(ctx.ui, {
641
649
  get(target, property) {
642
650
  if (property === "custom") {
643
651
  return <Value>(factory: BtwCustomFactory<Value>, customOptions?: BtwCustomOptions) =>
644
- target.custom<Value>((tui, theme, keybindings, done) => {
645
- onKeybindings?.(keybindings);
646
- return factory(tui, theme, keybindings, (value) => {
647
- try {
648
- liveEditorText = target.getEditorText();
649
- } catch {
650
- // Keep completion finite if session replacement invalidates the editor context.
651
- }
652
- completed = true;
653
- done(value);
654
- });
655
- }, customOptions);
652
+ ctx.signal?.aborted
653
+ ? Promise.resolve(undefined as Value)
654
+ : target.custom<Value>((tui, theme, keybindings, done) => {
655
+ onKeybindings?.(keybindings);
656
+ return factory(tui, theme, keybindings, (value) => {
657
+ try {
658
+ if (ctx.signal?.aborted) {
659
+ done(value);
660
+ return;
661
+ }
662
+ liveEditorText = target.getEditorText();
663
+ } catch {
664
+ // Keep completion finite if session replacement invalidates the editor context.
665
+ }
666
+ completed = true;
667
+ done(value);
668
+ });
669
+ }, customOptions);
656
670
  }
657
671
  const value = Reflect.get(target, property, target) as unknown;
658
672
  return typeof value === "function" ? value.bind(target) : value;
659
673
  },
660
674
  });
661
675
  const result = await run({ mode: ctx.mode, hasUI: ctx.hasUI, ui });
662
- if (result.kind !== "stale" && completed) {
676
+ if (!ctx.signal?.aborted && result.kind !== "stale" && completed) {
663
677
  try {
664
678
  if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
665
679
  } catch {
@@ -720,6 +734,7 @@ function notifySafely(
720
734
  message: string,
721
735
  level: Parameters<ExtensionCommandContext["ui"]["notify"]>[1],
722
736
  ): void {
737
+ if (ctx.signal?.aborted) return;
723
738
  try {
724
739
  ctx.ui.notify(sanitizeSingleLine(message), level);
725
740
  } catch {
@@ -0,0 +1,66 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { awaitBtwSettingsWrites } from "./settings.js";
3
+
4
+ /** ctx.signal belongs to an agent run, not to the session or an idle command. */
5
+ export class BtwSessionLifetime {
6
+ readonly controller = new AbortController();
7
+ private readonly tasks = new Set<Promise<unknown>>();
8
+ private restoreParent = true;
9
+ private shutdown: Promise<void> | undefined;
10
+
11
+ get signal(): AbortSignal {
12
+ return this.controller.signal;
13
+ }
14
+
15
+ readonly canRestoreParent = (): boolean => this.restoreParent;
16
+
17
+ track<T>(task: Promise<T>): Promise<T> {
18
+ this.tasks.add(task);
19
+ void task.then(
20
+ () => this.tasks.delete(task),
21
+ () => this.tasks.delete(task),
22
+ );
23
+ return task;
24
+ }
25
+
26
+ stop(quit: boolean): Promise<void> {
27
+ // Quit can stop the renderer before it emits session_shutdown.
28
+ if (quit) this.restoreParent = false;
29
+ if (this.shutdown) return this.shutdown;
30
+ this.controller.abort(new DOMException("Pi BTW session ended", "AbortError"));
31
+ this.shutdown = (async () => {
32
+ try {
33
+ await Promise.allSettled([...this.tasks]);
34
+ await awaitBtwSettingsWrites();
35
+ } finally {
36
+ // Non-quit teardown drains handlers before Pi resets UI and invalidates ctx.
37
+ this.restoreParent = false;
38
+ }
39
+ })();
40
+ return this.shutdown;
41
+ }
42
+ }
43
+
44
+ export function registerBtwSessionLifetimes(pi: ExtensionAPI): (ctx: ExtensionContext) => BtwSessionLifetime {
45
+ const sessions = new WeakMap<ExtensionContext["sessionManager"], BtwSessionLifetime>();
46
+ let previous: BtwSessionLifetime | undefined;
47
+ pi.on("session_start", async (_event, ctx) => {
48
+ const replaced = previous;
49
+ const lifetime = new BtwSessionLifetime();
50
+ sessions.set(ctx.sessionManager, lifetime);
51
+ previous = lifetime;
52
+ await replaced?.stop(false);
53
+ });
54
+ pi.on("session_shutdown", async (event, ctx) => {
55
+ await sessions.get(ctx.sessionManager)?.stop(event.reason === "quit");
56
+ });
57
+ return (ctx) => {
58
+ let lifetime = sessions.get(ctx.sessionManager);
59
+ if (!lifetime) {
60
+ lifetime = new BtwSessionLifetime();
61
+ sessions.set(ctx.sessionManager, lifetime);
62
+ previous = lifetime;
63
+ }
64
+ return lifetime;
65
+ };
66
+ }