@narumitw/pi-btw 0.63.4 → 0.63.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-btw",
3
- "version": "0.63.4",
3
+ "version": "0.63.6",
4
4
  "description": "Pi extension that adds a /btw side-question command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -45,7 +45,7 @@
45
45
  "directory": "packages/pi-btw"
46
46
  },
47
47
  "dependencies": {
48
- "@narumitw/pi-tui-kit": "^0.69.0"
48
+ "@narumitw/pi-tui-kit": "^0.69.1"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@earendil-works/pi-ai": "*",
package/src/btw.ts CHANGED
@@ -1,30 +1,19 @@
1
1
  import { type Api, clampThinkingLevel, getSupportedThinkingLevels, type Model } from "@earendil-works/pi-ai";
2
2
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { MenuContext, RunMenuResult } from "@narumitw/pi-tui-kit";
4
- import {
5
- type BtwBringToMainSegment,
6
- type BtwBringToMainSummary,
4
+ import type {
5
+ BtwBringToMainSegment,
6
+ BtwBringToMainSummary,
7
7
  BtwTextRangeSelector,
8
- type BtwTextRangeSelectorState,
9
- buildQuickBringToMainSegments,
10
- estimateBringToMainTokens,
11
- formatBtwBringToMain,
12
- getAnsweredTurns,
13
- summarizeBringToMain,
8
+ BtwTextRangeSelectorState,
14
9
  } from "./bring-to-main.js";
15
10
  import type { BtwDisplayModel } from "./conversation-chrome.js";
16
- import { type RunBtwFullscreen, runBtwFullscreen } from "./fullscreen-ui.js";
17
- import { importMainUpdates } from "./import-main-updates.js";
11
+ import type { RunBtwFullscreen } from "./fullscreen-ui.js";
12
+ import type { importMainUpdates } from "./import-main-updates.js";
18
13
  import { buildMainContextSnapshot, captureMainContextSource } from "./main-context-snapshot.js";
19
14
  import { registerBtwMainThreadUpdates } from "./main-thread-updates.js";
20
- import { pickMainEntry } from "./main-tree-picker.js";
21
- import {
22
- type BtwCommandMenuResult,
23
- type BtwResumeThreadSummary,
24
- runBtwMenuPreservingEditor,
25
- showBtwCommandMenu,
26
- showBtwCustomPreservingEditor,
27
- } from "./menu.js";
15
+ import type { pickMainEntry } from "./main-tree-picker.js";
16
+ import type { BtwCommandMenuResult, BtwResumeThreadSummary } from "./menu.js";
28
17
  import { type BtwSessionLifetime, registerBtwSessionLifetimes } from "./session-lifetime.js";
29
18
  import {
30
19
  type BtwSettings,
@@ -48,12 +37,7 @@ import {
48
37
  } from "./side-thread.js";
49
38
  import { sanitizeSingleLine } from "./text.js";
50
39
  import { type BtwMarkdownTransformers, prepareBtwTranscriptMarkdown } from "./transcript-markdown.js";
51
- import {
52
- BtwAnsweringView,
53
- type BtwThinkingControl,
54
- BtwTranscriptPager,
55
- type TranscriptPagerAction,
56
- } from "./transcript-pager.js";
40
+ import type { BtwThinkingControl, TranscriptPagerAction } from "./transcript-pager.js";
57
41
 
58
42
  export { buildConversationContext } from "./conversation-context.js";
59
43
  export {
@@ -206,13 +190,27 @@ export interface BtwExtensionDependencies {
206
190
  runFullscreen?: RunBtwFullscreen;
207
191
  }
208
192
 
193
+ const runFullscreenOnFirstUse: RunBtwFullscreen = async (ctx, run, options) => {
194
+ const { runBtwFullscreen } = await import("./fullscreen-ui.js");
195
+ if (ctx.signal?.aborted || options?.signal?.aborted || options?.canRestoreParent?.() === false) {
196
+ throw new DOMException("Pi BTW session ended", "AbortError");
197
+ }
198
+ return runBtwFullscreen(ctx, run, options);
199
+ };
200
+
201
+ const pickEntryOnFirstUse: typeof pickMainEntry = async (pi, ctx) => {
202
+ const { pickMainEntry } = await import("./main-tree-picker.js");
203
+ if (ctx.signal?.aborted) return { kind: "closed" };
204
+ return pickMainEntry(pi, ctx);
205
+ };
206
+
209
207
  export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependencies = {}) {
210
208
  const showCommandMenu = dependencies.showCommandMenu ?? showCommandMenuForBtw;
211
- const pickEntry = dependencies.pickMainEntry ?? pickMainEntry;
209
+ const pickEntry = dependencies.pickMainEntry ?? pickEntryOnFirstUse;
212
210
  const loadSettings = dependencies.loadSettings ?? loadSettingsForCommand;
213
211
  const resolveModel = dependencies.resolveModel ?? resolveBtwModelForCommand;
214
212
  const runThread = dependencies.runThread ?? runBtwThread;
215
- const runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;
213
+ const runFullscreen = dependencies.runFullscreen ?? runFullscreenOnFirstUse;
216
214
  const subscribeMainThreadUpdates = registerBtwMainThreadUpdates(pi);
217
215
  const getLifetime = registerBtwSessionLifetimes(pi);
218
216
  const sessionThreads = new WeakMap<BtwSessionLifetime, Map<string, BtwThreadState>>();
@@ -391,6 +389,8 @@ async function showCommandMenuForBtw(
391
389
  ctx: ExtensionCommandContext,
392
390
  resumeThreads: readonly BtwResumeThreadSummary[],
393
391
  ): Promise<BtwCommandMenuResult> {
392
+ const { showBtwCommandMenu } = await import("./menu.js");
393
+ if (ctx.signal?.aborted) return "closed";
394
394
  return showBtwCommandMenu(ctx, {
395
395
  currentThinkingLevel: pi.getThinkingLevel(),
396
396
  resumeThreads,
@@ -530,7 +530,10 @@ export async function runBtwThread({
530
530
  if (ctx.signal?.aborted || action.kind === "close") return { kind: "closed" };
531
531
  if (action.kind === "importMainUpdates") {
532
532
  composerDraft = action.questionDraft;
533
- const result = await (dependencies.importUpdates ?? importMainUpdates)(thread, ctx);
533
+ const importUpdates =
534
+ dependencies.importUpdates ?? (await import("./import-main-updates.js")).importMainUpdates;
535
+ if (ctx.signal?.aborted) return { kind: "closed" };
536
+ const result = await importUpdates(thread, ctx);
534
537
  if (ctx.signal?.aborted || result === "close") return { kind: "closed" };
535
538
  continue;
536
539
  }
@@ -592,6 +595,18 @@ export async function chooseBringToMain(
592
595
  ctx: ExtensionCommandContext,
593
596
  dependencies: ChooseBringToMainDependencies = {},
594
597
  ): Promise<BtwBringToMainChoice> {
598
+ if (ctx.signal?.aborted) return { kind: "closed" };
599
+ const [
600
+ {
601
+ getAnsweredTurns,
602
+ buildQuickBringToMainSegments,
603
+ estimateBringToMainTokens,
604
+ formatBtwBringToMain,
605
+ summarizeBringToMain,
606
+ BtwTextRangeSelector,
607
+ },
608
+ { showBtwCustomPreservingEditor },
609
+ ] = await Promise.all([import("./bring-to-main.js"), import("./menu.js")]);
595
610
  if (ctx.signal?.aborted) return { kind: "closed" };
596
611
  const answered = getAnsweredTurns(thread.turns);
597
612
  if (answered.length === 0) return { kind: "back" };
@@ -701,7 +716,10 @@ async function showBringToMainPreview(
701
716
  draft: string,
702
717
  summary: BtwBringToMainSummary,
703
718
  ): Promise<BtwBringToMainPreviewAction> {
704
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
719
+ const [{ defineMenu, runMenu }, { runBtwMenuPreservingEditor }] = await Promise.all([
720
+ import("@narumitw/pi-tui-kit"),
721
+ import("./menu.js"),
722
+ ]);
705
723
  if (ctx.signal?.aborted) return { kind: "close" };
706
724
  let confirmed = false;
707
725
  const count = summary.messages === 1 ? "1 message" : `${summary.messages} messages`;
@@ -741,7 +759,10 @@ async function showBtwMenu(
741
759
  options: readonly string[],
742
760
  initialValue?: string,
743
761
  ): Promise<BtwMenuSelectorAction> {
744
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
762
+ const [{ defineMenu, runMenu }, { runBtwMenuPreservingEditor }] = await Promise.all([
763
+ import("@narumitw/pi-tui-kit"),
764
+ import("./menu.js"),
765
+ ]);
745
766
  if (ctx.signal?.aborted) return { kind: "close" };
746
767
  const items = options.map((label, index) => ({ id: `option-${index}`, label }));
747
768
  const initialIndex = initialValue === undefined ? -1 : options.indexOf(initialValue);
@@ -867,6 +888,8 @@ async function askThreadQuestion(
867
888
  ctx: ExtensionCommandContext,
868
889
  steering: BtwThreadSteeringControl,
869
890
  ) {
891
+ const { BtwAnsweringView } = await import("./transcript-pager.js");
892
+ if (ctx.signal?.aborted) return { kind: "aborted" as const };
870
893
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, question, ctx);
871
894
  if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "aborted" as const };
872
895
  return ctx.ui.custom<Awaited<ReturnType<typeof completeSideThreadTurn>>>((tui, theme, keybindings, done) => {
@@ -918,6 +941,8 @@ async function showThreadComposer(
918
941
  thinking: BtwThreadThinkingControl,
919
942
  model?: BtwDisplayModel,
920
943
  ): Promise<TranscriptPagerAction> {
944
+ const { BtwTranscriptPager } = await import("./transcript-pager.js");
945
+ if (ctx.signal?.aborted) return { kind: "close" };
921
946
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, initialQuestion, ctx);
922
947
  if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "close" };
923
948
  let statusLeaf: string | null | undefined;
@@ -92,9 +92,7 @@ export async function pickMainEntry(
92
92
  return { kind: "back" };
93
93
  }
94
94
 
95
- const tree = sanitizeTreeForDisplay(rawTree);
96
- const rawCopyText = collectRawCopyText(rawTree);
97
- const savedLabels = collectSavedLabels(rawTree);
95
+ const { tree, rawCopyText, savedLabels } = prepareTreeSnapshot(rawTree);
98
96
  const createSelector = dependencies.createSelector ?? createNativeTreeSelector;
99
97
  const copy = dependencies.copyToClipboard ?? copyText;
100
98
  const copyControllers = new Set<AbortController>();
@@ -200,18 +198,40 @@ function createNativeTreeSelector(options: MainThreadTreeSelectorOptions): MainT
200
198
  return result;
201
199
  }
202
200
 
203
- function sanitizeTreeForDisplay(tree: readonly SessionTreeNode[]): SessionTreeNode[] {
204
- return tree.map((node) => {
205
- const result: SessionTreeNode = {
201
+ function prepareTreeSnapshot(rawTree: readonly SessionTreeNode[]): {
202
+ tree: SessionTreeNode[];
203
+ rawCopyText: Map<string, string>;
204
+ savedLabels: Map<string, SavedLabel>;
205
+ } {
206
+ const tree: SessionTreeNode[] = [];
207
+ const rawCopyText = new Map<string, string>();
208
+ const savedLabels = new Map<string, SavedLabel>();
209
+ // Keep traversal state on the heap: valid session histories can be arbitrarily deep.
210
+ const stack = [{ source: rawTree, target: tree, index: 0 }];
211
+ while (stack.length > 0) {
212
+ const frame = stack[stack.length - 1];
213
+ if (frame.index === frame.source.length) {
214
+ stack.pop();
215
+ continue;
216
+ }
217
+ const node = frame.source[frame.index++];
218
+ const label = node.label === undefined ? undefined : sanitizeSingleLine(node.label);
219
+ const labelTimestamp = node.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp);
220
+ const displayNode: SessionTreeNode = {
206
221
  entry: sanitizeEntryForDisplay(node.entry),
207
- children: sanitizeTreeForDisplay(node.children),
222
+ children: [],
208
223
  };
209
- if (node.label !== undefined) result.label = sanitizeSingleLine(node.label);
210
- if (node.labelTimestamp !== undefined) {
211
- result.labelTimestamp = sanitizeSingleLine(node.labelTimestamp);
224
+ if (label !== undefined) displayNode.label = label;
225
+ if (labelTimestamp !== undefined) displayNode.labelTimestamp = labelTimestamp;
226
+ frame.target.push(displayNode);
227
+ const text = getRawCopyText(node.entry);
228
+ if (text !== undefined) rawCopyText.set(node.entry.id, text);
229
+ savedLabels.set(node.entry.id, { label, labelTimestamp });
230
+ if (node.children.length > 0) {
231
+ stack.push({ source: node.children, target: displayNode.children, index: 0 });
212
232
  }
213
- return result;
214
- });
233
+ }
234
+ return { tree, rawCopyText, savedLabels };
215
235
  }
216
236
 
217
237
  function sanitizeEntryForDisplay(entry: SessionEntry): SessionEntry {
@@ -305,19 +325,6 @@ function sanitizeToolArguments(value: unknown, seen: WeakMap<object, unknown>):
305
325
  return result;
306
326
  }
307
327
 
308
- function collectRawCopyText(tree: readonly SessionTreeNode[]): Map<string, string> {
309
- const result = new Map<string, string>();
310
- const visit = (nodes: readonly SessionTreeNode[]) => {
311
- for (const node of nodes) {
312
- const text = getRawCopyText(node.entry);
313
- if (text !== undefined) result.set(node.entry.id, text);
314
- visit(node.children);
315
- }
316
- };
317
- visit(tree);
318
- return result;
319
- }
320
-
321
328
  function getRawCopyText(entry: SessionEntry): string | undefined {
322
329
  let text: string | undefined;
323
330
  if (entry.type === "message") {
@@ -353,21 +360,6 @@ interface SavedLabel {
353
360
  labelTimestamp?: string;
354
361
  }
355
362
 
356
- function collectSavedLabels(tree: readonly SessionTreeNode[]): Map<string, SavedLabel> {
357
- const result = new Map<string, SavedLabel>();
358
- const visit = (nodes: readonly SessionTreeNode[]) => {
359
- for (const node of nodes) {
360
- result.set(node.entry.id, {
361
- label: node.label === undefined ? undefined : sanitizeSingleLine(node.label),
362
- labelTimestamp: node.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp),
363
- });
364
- visit(node.children);
365
- }
366
- };
367
- visit(tree);
368
- return result;
369
- }
370
-
371
363
  async function copyText(text: string, signal: AbortSignal): Promise<void> {
372
364
  signal.throwIfAborted();
373
365
  await copyToClipboard(text);