@narumitw/pi-btw 0.58.1 → 0.59.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/README.md +2 -0
- package/dist/index.ts +284 -365
- package/dist/index.ts.map +3 -3
- package/package.json +52 -53
- package/src/bring-to-main.ts +494 -547
- package/src/btw.ts +814 -856
- package/src/fullscreen-ui.ts +673 -674
- package/src/keybindings.ts +228 -270
- package/src/main-tree-picker.ts +309 -318
- package/src/menu.ts +416 -454
- package/src/settings.ts +203 -219
- package/src/side-thread.ts +173 -201
- package/src/text.ts +21 -23
- package/src/transcript-markdown.ts +65 -0
- package/src/transcript-pager.ts +611 -662
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/btw.ts", "../src/bring-to-main.ts", "../src/fullscreen-ui.ts", "../src/keybindings.ts", "../src/text.ts", "../src/main-tree-picker.ts", "../src/settings.ts", "../src/side-thread.ts", "../src/menu.ts", "../src/transcript-pager.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n\ttype Api,\n\tclampThinkingLevel,\n\tgetSupportedThinkingLevels,\n\ttype Model,\n\ttype ProviderHeaders,\n} from \"@earendil-works/pi-ai\";\nimport {\n\tBorderedLoader,\n\ttype ExtensionAPI,\n\ttype ExtensionCommandContext,\n} from \"@earendil-works/pi-coding-agent\";\nimport type { MenuContext, RunMenuResult } from \"@narumitw/pi-tui-kit\";\nimport {\n\ttype BtwBringToMainSegment,\n\ttype BtwBringToMainSummary,\n\tBtwTextRangeSelector,\n\ttype BtwTextRangeSelectorState,\n\tbuildQuickBringToMainSegments,\n\testimateBringToMainTokens,\n\tformatBtwBringToMain,\n\tgetAnsweredTurns,\n\tsummarizeBringToMain,\n} from \"./bring-to-main.js\";\nimport { type RunBtwFullscreen, runBtwFullscreen } from \"./fullscreen-ui.js\";\nimport { pickMainEntry } from \"./main-tree-picker.js\";\nimport {\n\ttype BtwCommandMenuResult,\n\ttype BtwResumeThreadSummary,\n\trunBtwMenuPreservingEditor,\n\tshowBtwCommandMenu,\n\tshowBtwCustomPreservingEditor,\n} from \"./menu.js\";\nimport {\n\ttype BtwSettings,\n\teffectiveFullscreenCopyOnSelect,\n\teffectiveRememberThinkingLevelChanges,\n\tparseBtwModelReference,\n\treadBtwSettings,\n\tupdateBtwSettings,\n} from \"./settings.js\";\nimport {\n\tBTW_THINKING_LEVELS,\n\ttype BtwThinkingLevel,\n\ttype CompleteSimpleFunction,\n\tcompleteSideThreadTurn,\n\tcreateSideThread,\n\ttype SideQuestionAuth,\n\ttype SideThread,\n} from \"./side-thread.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\nimport {\n\tBtwAnsweringView,\n\ttype BtwThinkingControl,\n\tBtwTranscriptPager,\n\ttype TranscriptPagerAction,\n} from \"./transcript-pager.js\";\n\nexport {\n\tBTW_SETTINGS_FILE,\n\ttype BtwSettings,\n\ttype BtwSettingsLoadResult,\n\tnormalizeBtwSettings,\n\tparseBtwModelReference,\n\treadBtwSettings,\n} from \"./settings.js\";\nexport {\n\tBTW_THINKING_LEVELS,\n\ttype BtwThinkingLevel,\n\tbuildUserPrompt,\n\tcompleteSideQuestion,\n} from \"./side-thread.js\";\nexport { sanitizeSingleLine } from \"./text.js\";\n\nconst MAX_CONTEXT_CHARS = 40_000;\n\ninterface LoadBtwThinkingLevelOptions {\n\tsettingsPath?: string;\n\twarn?: (message: string) => void;\n}\n\ntype BtwModelRegistry = Pick<\n\tExtensionCommandContext[\"modelRegistry\"],\n\t\"find\" | \"getApiKeyAndHeaders\"\n>;\n\ntype BtwProviderRegistry = Pick<ExtensionCommandContext[\"modelRegistry\"], \"getProvider\">;\n\nexport function createModelRegistryCompleteSimple(\n\tmodelRegistry: BtwProviderRegistry,\n): CompleteSimpleFunction {\n\treturn async (model, context, options) => {\n\t\tconst provider = modelRegistry.getProvider(model.provider);\n\t\tif (!provider) throw new Error(`No provider registered for model provider: ${model.provider}`);\n\t\treturn provider.streamSimple(model, context, options).result();\n\t};\n}\n\ninterface ResolveBtwModelOptions {\n\tsettings: BtwSettings;\n\tcurrentModel: Model<Api> | undefined;\n\tmodelRegistry: BtwModelRegistry;\n\twarn?: (message: string) => void;\n}\n\nexport interface ResolvedBtwModel {\n\tmodel: Model<Api>;\n\tauth: SideQuestionAuth;\n}\n\nexport interface BtwThreadState {\n\tid: string;\n\ttitle?: string;\n\tthread: SideThread;\n\tthinkingLevel: BtwThinkingLevel;\n\tcreatedAt: number;\n\tupdatedAt: number;\n}\n\nexport async function resolveBtwModel({\n\tsettings,\n\tcurrentModel,\n\tmodelRegistry,\n\twarn,\n}: ResolveBtwModelOptions): Promise<ResolvedBtwModel | undefined> {\n\tconst reportWarning = (message: string) => warn?.(sanitizeSingleLine(message));\n\tif (settings.model) {\n\t\tconst fallback = currentModel\n\t\t\t? `${currentModel.provider}/${currentModel.id}`\n\t\t\t: \"the current model\";\n\t\tconst reference = parseBtwModelReference(settings.model);\n\t\tif (!reference) {\n\t\t\treportWarning(`pi-btw model ${settings.model} is invalid; falling back to ${fallback}.`);\n\t\t\treturn resolveBtwModel({ settings: {}, currentModel, modelRegistry, warn: reportWarning });\n\t\t}\n\t\tconst configuredModel = modelRegistry.find(reference.provider, reference.modelId);\n\t\tif (!configuredModel) {\n\t\t\treportWarning(`pi-btw model ${settings.model} was not found; falling back to ${fallback}.`);\n\t\t} else {\n\t\t\tconst sameAsCurrent =\n\t\t\t\tconfiguredModel === currentModel ||\n\t\t\t\t(configuredModel.provider === currentModel?.provider &&\n\t\t\t\t\tconfiguredModel.id === currentModel.id);\n\t\t\tconst fallbackAction = sameAsCurrent\n\t\t\t\t? \"no distinct current model is available\"\n\t\t\t\t: `falling back to ${fallback}`;\n\t\t\ttry {\n\t\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(configuredModel);\n\t\t\t\tif (auth.ok && hasRequestAuth(auth)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmodel: auth.baseUrl ? { ...configuredModel, baseUrl: auth.baseUrl } : configuredModel,\n\t\t\t\t\t\tauth,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst reason = auth.ok ? \"has no request credentials\" : auth.error;\n\t\t\t\treportWarning(\n\t\t\t\t\t`pi-btw model ${settings.model} is unavailable (${reason}); ${fallbackAction}.`,\n\t\t\t\t);\n\t\t\t} catch (error: unknown) {\n\t\t\t\treportWarning(\n\t\t\t\t\t`pi-btw model ${settings.model} credentials failed (${formatError(error)}); ${fallbackAction}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (sameAsCurrent) return undefined;\n\t\t}\n\t}\n\n\tif (!currentModel) return undefined;\n\ttry {\n\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(currentModel);\n\t\tif (auth.ok && hasRequestAuth(auth)) {\n\t\t\t// Direct provider streams bypass Pi's request preparation, including OAuth routing.\n\t\t\treturn {\n\t\t\t\tmodel: auth.baseUrl ? { ...currentModel, baseUrl: auth.baseUrl } : currentModel,\n\t\t\t\tauth,\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// The caller reports the final lack of an available model.\n\t}\n\treturn undefined;\n}\n\nfunction hasRequestAuth(auth: SideQuestionAuth): boolean {\n\treturn Boolean(\n\t\tauth.apiKey ||\n\t\t\tproviderHeadersHaveValue(auth.headers) ||\n\t\t\t(auth.env && Object.keys(auth.env).length > 0),\n\t);\n}\n\nfunction providerHeadersHaveValue(headers: ProviderHeaders | undefined): boolean {\n\treturn headers !== undefined && Object.values(headers).some((value) => value !== null);\n}\n\nexport async function loadBtwThinkingLevel(\n\tcurrentThinkingLevel: BtwThinkingLevel,\n\toptions: LoadBtwThinkingLevelOptions = {},\n): Promise<BtwThinkingLevel> {\n\tconst settings = await readBtwSettings(options.settingsPath);\n\tif (settings.kind === \"missing\") return currentThinkingLevel;\n\tif (settings.kind === \"loaded\") {\n\t\treturn settings.settings.thinkingLevel ?? currentThinkingLevel;\n\t}\n\n\toptions.warn?.(\n\t\tsanitizeSingleLine(\n\t\t\t`pi-btw settings ignored: ${settings.reason}; expected optional model \"provider/model-id\", omitted thinkingLevel for Same as main thread or thinkingLevel \"${BTW_THINKING_LEVELS.join('\" | \"')}\", boolean rememberThinkingLevelChanges, and boolean fullscreenCopyOnSelect. Using current Pi thinking level.`,\n\t\t),\n\t);\n\treturn currentThinkingLevel;\n}\n\nfunction formatError(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction readBtwSessionId(ctx: ExtensionCommandContext): string | undefined {\n\tconst getSessionId = ctx.sessionManager.getSessionId;\n\tif (typeof getSessionId !== \"function\") return undefined;\n\tconst sessionId = getSessionId.call(ctx.sessionManager);\n\treturn sessionId.length > 0 ? sessionId : undefined;\n}\n\nfunction notifySafely(\n\tctx: ExtensionCommandContext,\n\tmessage: string,\n\tlevel: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n\ttry {\n\t\tctx.ui.notify(sanitizeSingleLine(message), level);\n\t} catch {\n\t\t// Async command continuations may finish after their ExtensionContext is replaced.\n\t}\n}\n\n// Keep this slightly-over-1,000-line command coordinator intact: its injectable menu,\n// request, resume, and delivery flows share the same thread-state and test seams;\n// settings, keybinding policy, terminal ownership, and rendering live in separate modules.\nexport interface BtwExtensionDependencies {\n\tshowCommandMenu?: (\n\t\tpi: ExtensionAPI,\n\t\tctx: ExtensionCommandContext,\n\t\tresumeThreads: readonly BtwResumeThreadSummary[],\n\t) => Promise<BtwCommandMenuResult>;\n\tpickMainEntry?: typeof pickMainEntry;\n\tloadSettings?: typeof loadSettingsForCommand;\n\tresolveModel?: typeof resolveBtwModelWithLoader;\n\trunThread?: typeof runBtwThread;\n\trunFullscreen?: RunBtwFullscreen;\n}\n\nexport default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependencies = {}) {\n\tconst showCommandMenu = dependencies.showCommandMenu ?? showCommandMenuForBtw;\n\tconst pickEntry = dependencies.pickMainEntry ?? pickMainEntry;\n\tconst loadSettings = dependencies.loadSettings ?? loadSettingsForCommand;\n\tconst resolveModel = dependencies.resolveModel ?? resolveBtwModelWithLoader;\n\tconst runThread = dependencies.runThread ?? runBtwThread;\n\tconst runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;\n\t// Pi creates a fresh extension instance after session replacement or reload.\n\tconst resumableThreads = new Map<string, BtwThreadState>();\n\tlet nextThreadNumber = 1;\n\tconst listResumeThreads = (): BtwResumeThreadSummary[] =>\n\t\t[...resumableThreads.values()]\n\t\t\t.reverse()\n\t\t\t.filter((state) => state.thread.turns.length > 0 && state.title)\n\t\t\t.sort(\n\t\t\t\t(first, second) => second.updatedAt - first.updatedAt || second.createdAt - first.createdAt,\n\t\t\t)\n\t\t\t.map((state) => ({\n\t\t\t\tid: state.id,\n\t\t\t\ttitle: state.title ?? \"Untitled side thread\",\n\t\t\t\tquestionCount: state.thread.turns.length,\n\t\t\t}));\n\tpi.registerCommand(\"btw\", {\n\t\tdescription: \"Ask a quick side question without adding it to the main conversation\",\n\t\thandler: async (args, ctx) => {\n\t\t\tconst question = args.trim();\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/btw requires interactive TUI mode\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet menuResult: BtwCommandMenuResult = \"start\";\n\t\t\tlet selectedConversationContext: string | undefined;\n\t\t\tif (!question) {\n\t\t\t\twhile (true) {\n\t\t\t\t\tmenuResult = await showCommandMenu(pi, ctx, listResumeThreads());\n\t\t\t\t\tif (menuResult === \"closed\") return;\n\t\t\t\t\tif (menuResult !== \"tree\") break;\n\n\t\t\t\t\tconst treeResult = await pickEntry(pi, ctx);\n\t\t\t\t\tif (treeResult.kind === \"closed\") return;\n\t\t\t\t\tif (treeResult.kind === \"back\") continue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (!ctx.sessionManager.getEntry(treeResult.entryId)) {\n\t\t\t\t\t\t\tnotifySafely(ctx, \"The selected main-thread entry is no longer available\", \"warning\");\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst branch = ctx.sessionManager.getBranch(treeResult.entryId);\n\t\t\t\t\t\tif (branch.at(-1)?.id !== treeResult.entryId) {\n\t\t\t\t\t\t\tnotifySafely(\n\t\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\t\"The selected main-thread branch is no longer available\",\n\t\t\t\t\t\t\t\t\"warning\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselectedConversationContext = buildConversationContext(branch);\n\t\t\t\t\t\tmenuResult = \"start\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst settings = await loadSettings(ctx);\n\t\t\tconst sameAsMainThinkingLevel = settings.thinkingLevel === undefined;\n\t\t\tconst resolution = await resolveModel(settings, ctx);\n\t\t\tif (resolution.kind === \"cancelled\") {\n\t\t\t\tnotifySafely(ctx, \"Cancelled\", \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (resolution.kind === \"unavailable\") {\n\t\t\t\tnotifySafely(ctx, \"No available model for /btw\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet state =\n\t\t\t\ttypeof menuResult === \"object\" ? resumableThreads.get(menuResult.threadId) : undefined;\n\t\t\tif (typeof menuResult === \"object\" && !state) {\n\t\t\t\tnotifySafely(ctx, \"The selected /btw side thread is no longer available\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst startingTurnCount = state?.thread.turns.length ?? 0;\n\n\t\t\ttry {\n\t\t\t\tawait runFullscreen(\n\t\t\t\t\tctx,\n\t\t\t\t\t(fullscreenCtx) => {\n\t\t\t\t\t\tif (!state) {\n\t\t\t\t\t\t\tconst createdAt = Date.now();\n\t\t\t\t\t\t\tstate = {\n\t\t\t\t\t\t\t\tid: `btw-${nextThreadNumber}`,\n\t\t\t\t\t\t\t\tthread: createSideThread(\n\t\t\t\t\t\t\t\t\tselectedConversationContext ??\n\t\t\t\t\t\t\t\t\t\tbuildConversationContext(fullscreenCtx.sessionManager.getBranch()),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tthinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),\n\t\t\t\t\t\t\t\tcreatedAt,\n\t\t\t\t\t\t\t\tupdatedAt: createdAt,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tnextThreadNumber += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn runThread({\n\t\t\t\t\t\t\tinitialQuestion: question || undefined,\n\t\t\t\t\t\t\tselected: resolution.selected,\n\t\t\t\t\t\t\tthinkingLevel: state.thinkingLevel,\n\t\t\t\t\t\t\trememberThinkingLevelChanges:\n\t\t\t\t\t\t\t\t!sameAsMainThinkingLevel && effectiveRememberThinkingLevelChanges(settings),\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tctx: fullscreenCtx,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcopyOnSelect: effectiveFullscreenCopyOnSelect(settings),\n\t\t\t\t\t\t...(settings.keybindings ? { keybindings: settings.keybindings } : {}),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tif (state?.title && state.thread.turns.length > 0) {\n\t\t\t\t\tif (state.thread.turns.length > startingTurnCount) {\n\t\t\t\t\t\tresumableThreads.delete(state.id);\n\t\t\t\t\t}\n\t\t\t\t\tresumableThreads.set(state.id, state);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n}\n\nasync function showCommandMenuForBtw(\n\tpi: ExtensionAPI,\n\tctx: ExtensionCommandContext,\n\tresumeThreads: readonly BtwResumeThreadSummary[],\n): Promise<BtwCommandMenuResult> {\n\tconst currentModel = ctx.model;\n\tconst availableModels = ctx.modelRegistry.getAll();\n\tconst currentThinkingLevel = pi.getThinkingLevel();\n\tconst loaded = await readBtwSettings();\n\tconst settings = loaded.kind === \"loaded\" ? loaded.settings : {};\n\tconst configured = settings.model ? parseBtwModelReference(settings.model) : undefined;\n\tconst configuredModel = configured\n\t\t? availableModels.find(\n\t\t\t\t(model) => model.provider === configured.provider && model.id === configured.modelId,\n\t\t\t)\n\t\t: undefined;\n\tconst model = configuredModel ?? currentModel;\n\treturn showBtwCommandMenu(ctx, {\n\t\tcurrentThinkingLevel,\n\t\tavailableThinkingLevels: model ? getSupportedThinkingLevels(model) : BTW_THINKING_LEVELS,\n\t\tresumeThreads,\n\t});\n}\n\nasync function loadSettingsForCommand(ctx: ExtensionCommandContext): Promise<BtwSettings> {\n\tconst settingsResult = await readBtwSettings();\n\tif (settingsResult.kind === \"loaded\") return settingsResult.settings;\n\tif (settingsResult.kind === \"invalid\") {\n\t\tnotifySafely(ctx, `pi-btw settings ignored: ${settingsResult.reason}`, \"warning\");\n\t}\n\treturn {};\n}\n\ntype ModelResolutionOutcome =\n\t| { kind: \"cancelled\" }\n\t| { kind: \"unavailable\" }\n\t| { kind: \"selected\"; selected: ResolvedBtwModel };\n\nasync function resolveBtwModelWithLoader(\n\tsettings: BtwSettings,\n\tctx: ExtensionCommandContext,\n): Promise<ModelResolutionOutcome> {\n\treturn ctx.ui.custom<ModelResolutionOutcome>((tui, theme, _keybindings, done) => {\n\t\tconst loader = new BorderedLoader(tui, theme, \"Resolving /btw model credentials...\");\n\t\tlet settled = false;\n\t\tloader.onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tdone({ kind: \"cancelled\" });\n\t\t};\n\n\t\tresolveBtwModel({\n\t\t\tsettings,\n\t\t\tcurrentModel: ctx.model,\n\t\t\tmodelRegistry: ctx.modelRegistry,\n\t\t\twarn: (message) => {\n\t\t\t\tif (!settled) notifySafely(ctx, message, \"warning\");\n\t\t\t},\n\t\t})\n\t\t\t.then((selected) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tdone(selected ? { kind: \"selected\", selected } : { kind: \"unavailable\" });\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tdone({ kind: \"unavailable\" });\n\t\t\t});\n\n\t\treturn loader;\n\t});\n}\n\ninterface RunBtwThreadDependencies {\n\task?: typeof askThreadQuestion;\n\tinteract?: typeof showThreadComposer;\n\tchooseBringToMain?: typeof chooseBringToMain;\n\tdeliverBringToMain?: typeof loadBringToMainDraft;\n\tpersistThinkingLevel?: (level: BtwThinkingLevel) => Promise<unknown>;\n\tnow?: () => number;\n}\n\nexport type BtwThreadResult = { kind: \"closed\" };\n\ntype BtwThreadThinkingControl = Omit<BtwThinkingControl, \"keybindings\">;\n\ninterface BtwThreadSteeringControl {\n\tquestions: readonly string[];\n\tsubmit: (question: string) => void;\n\tthinking: BtwThreadThinkingControl;\n}\n\ntype BtwBringToMainChoice =\n\t| BtwThreadResult\n\t| {\n\t\t\tkind: \"bringToMain\";\n\t\t\tdraft: string;\n\t\t\tsummary: BtwBringToMainSummary;\n\t\t\tselectionState?: BtwTextRangeSelectorState;\n\t }\n\t| { kind: \"back\" };\n\ntype BtwBringToMainDelivery = \"loaded\" | \"back\" | \"closed\";\n\ninterface RunBtwThreadOptions {\n\tinitialQuestion?: string;\n\tselected: ResolvedBtwModel;\n\tthinkingLevel: BtwThinkingLevel;\n\trememberThinkingLevelChanges?: boolean;\n\tsettingsPath?: string;\n\tstate?: BtwThreadState;\n\tctx: ExtensionCommandContext;\n\tdependencies?: RunBtwThreadDependencies;\n}\n\nexport async function runBtwThread({\n\tinitialQuestion,\n\tselected,\n\tthinkingLevel,\n\trememberThinkingLevelChanges = false,\n\tsettingsPath,\n\tstate,\n\tctx,\n\tdependencies = {},\n}: RunBtwThreadOptions): Promise<BtwThreadResult> {\n\tconst ask = dependencies.ask ?? askThreadQuestion;\n\tconst interact = dependencies.interact ?? showThreadComposer;\n\tconst chooseBringToMainAction = dependencies.chooseBringToMain ?? chooseBringToMain;\n\tconst deliverBringToMainDraft = dependencies.deliverBringToMain ?? loadBringToMainDraft;\n\tconst persistThinkingLevel =\n\t\tdependencies.persistThinkingLevel ??\n\t\t((level: BtwThinkingLevel) => updateBtwSettings({ thinkingLevel: level }, { settingsPath }));\n\tconst now = dependencies.now ?? Date.now;\n\tconst thread =\n\t\tstate?.thread ?? createSideThread(buildConversationContext(ctx.sessionManager.getBranch()));\n\tconst thinkingLevels = getSupportedThinkingLevels(selected.model);\n\tconst pendingWrites = new Set<Promise<void>>();\n\tconst steeringQuestions: string[] = [];\n\tlet activeThinkingLevel = clampThinkingLevel(\n\t\tselected.model,\n\t\tstate?.thinkingLevel ?? thinkingLevel,\n\t);\n\tif (state) state.thinkingLevel = activeThinkingLevel;\n\tlet pendingQuestion = initialQuestion;\n\tlet composerDraft: string | undefined;\n\tconst createThinkingControl = (): BtwThreadThinkingControl => ({\n\t\tlevel: activeThinkingLevel,\n\t\tlevels: thinkingLevels,\n\t\tonChange: (level) => {\n\t\t\tif (!thinkingLevels.includes(level)) return;\n\t\t\tactiveThinkingLevel = level;\n\t\t\tif (state) state.thinkingLevel = level;\n\t\t\tif (!rememberThinkingLevelChanges) return;\n\t\t\tlet write!: Promise<void>;\n\t\t\twrite = Promise.resolve()\n\t\t\t\t.then(() => persistThinkingLevel(level))\n\t\t\t\t.then(() => undefined)\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tnotifySafely(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\t`Thinking level changed to ${level}, but could not be remembered in pi-btw.json: ${formatError(error)}`,\n\t\t\t\t\t\t\"warning\",\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t\t.finally(() => pendingWrites.delete(write));\n\t\t\tpendingWrites.add(write);\n\t\t},\n\t});\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (!pendingQuestion) {\n\t\t\t\tconst action = await interact(\n\t\t\t\t\tthread,\n\t\t\t\t\tthread.turns.length > 0,\n\t\t\t\t\tctx,\n\t\t\t\t\tcomposerDraft,\n\t\t\t\t\tcreateThinkingControl(),\n\t\t\t\t);\n\t\t\t\tif (action.kind === \"close\") return { kind: \"closed\" };\n\t\t\t\tif (action.kind === \"bringToMain\") {\n\t\t\t\t\tconst choice = await chooseBringToMainAction(thread, ctx);\n\t\t\t\t\tif (choice.kind === \"closed\") return choice;\n\t\t\t\t\tif (choice.kind === \"back\") {\n\t\t\t\t\t\tcomposerDraft = action.questionDraft;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst delivery = await deliverBringToMainDraft(choice.draft, ctx, choice.summary);\n\t\t\t\t\tif (delivery === \"loaded\" || delivery === \"closed\") return { kind: \"closed\" };\n\t\t\t\t\tcomposerDraft = action.questionDraft;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcomposerDraft = undefined;\n\t\t\t\tpendingQuestion = action.question;\n\t\t\t}\n\n\t\t\tconst result = await ask(thread, pendingQuestion, selected, activeThinkingLevel, ctx, {\n\t\t\t\tquestions: steeringQuestions,\n\t\t\t\tsubmit: (question) => steeringQuestions.push(question),\n\t\t\t\tthinking: createThinkingControl(),\n\t\t\t});\n\t\t\tif (result.kind === \"aborted\") {\n\t\t\t\tnotifySafely(ctx, \"Cancelled\", \"info\");\n\t\t\t\treturn { kind: \"closed\" };\n\t\t\t}\n\t\t\tif (result.kind === \"error\") {\n\t\t\t\tthread.turns.push({\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\tquestion: pendingQuestion,\n\t\t\t\t\tanswer: result.message,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (state) {\n\t\t\t\tstate.title ||= sanitizeSingleLine(pendingQuestion) || \"Untitled side thread\";\n\t\t\t\tstate.updatedAt = now();\n\t\t\t}\n\n\t\t\tpendingQuestion = steeringQuestions.shift();\n\t\t}\n\t} finally {\n\t\tawait Promise.allSettled([...pendingWrites]);\n\t}\n}\n\ninterface ChooseBringToMainDependencies {\n\tshowMenu?: typeof showBtwMenu;\n\tshowPreview?: typeof showBringToMainPreview;\n}\n\nexport async function chooseBringToMain(\n\tthread: SideThread,\n\tctx: ExtensionCommandContext,\n\tdependencies: ChooseBringToMainDependencies = {},\n): Promise<BtwBringToMainChoice> {\n\tconst answered = getAnsweredTurns(thread.turns);\n\tif (answered.length === 0) return { kind: \"back\" };\n\tconst showMenu = dependencies.showMenu ?? showBtwMenu;\n\tconst showPreview = dependencies.showPreview ?? showBringToMainPreview;\n\tconst makeChoice = (segments: readonly BtwBringToMainSegment[]) => ({\n\t\tkind: \"bringToMain\" as const,\n\t\tdraft: formatBtwBringToMain(segments),\n\t\tsummary: summarizeBringToMain(segments),\n\t});\n\n\tconst latestSegments = buildQuickBringToMainSegments(thread.turns, { kind: \"latest\" });\n\tconst entireSegments = buildQuickBringToMainSegments(thread.turns, { kind: \"entire\" });\n\tconst latestOption = `Latest question and answer 1 Q&A \u00B7 ~${estimateBringToMainTokens(latestSegments)} tokens`;\n\tconst fromOption = \"From a question onward\u2026 Choose a starting question\";\n\tconst exactOption = \"Select exact text\u2026 Lines or characters\";\n\tconst entireOption = `Entire side thread ${answered.length} Q&A \u00B7 ~${estimateBringToMainTokens(entireSegments)} tokens`;\n\tconst cancelOption = \"Cancel Return to the side thread\";\n\tlet selectedScope: string | undefined;\n\n\twhile (true) {\n\t\tconst scopeResult = await showMenu(\n\t\t\tctx,\n\t\t\t\"Bring what back to the main thread?\",\n\t\t\t[latestOption, fromOption, exactOption, entireOption, cancelOption],\n\t\t\tselectedScope,\n\t\t);\n\t\tif (scopeResult.kind === \"close\") return { kind: \"closed\" };\n\t\tif (scopeResult.kind === \"back\" || scopeResult.value === cancelOption) return { kind: \"back\" };\n\t\tconst scope = scopeResult.value;\n\t\tselectedScope = scope;\n\t\tif (scope === latestOption) return makeChoice(latestSegments);\n\t\tif (scope === entireOption) {\n\t\t\tconst choice = makeChoice(entireSegments);\n\t\t\tconst preview = await showPreview(ctx, choice.draft, choice.summary);\n\t\t\tif (preview.kind === \"close\") return { kind: \"closed\" };\n\t\t\tif (preview.kind === \"back\") continue;\n\t\t\treturn choice;\n\t\t}\n\t\tif (scope === fromOption) {\n\t\t\tconst questions = answered.map(\n\t\t\t\t(turn, index) => `${index + 1}. ${truncatePreview(sanitizeSingleLine(turn.question))}`,\n\t\t\t);\n\t\t\tlet selectedQuestion: string | undefined;\n\t\t\twhile (true) {\n\t\t\t\tconst questionResult = await showMenu(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"Start from which question?\",\n\t\t\t\t\tquestions,\n\t\t\t\t\tselectedQuestion,\n\t\t\t\t);\n\t\t\t\tif (questionResult.kind === \"close\") return { kind: \"closed\" };\n\t\t\t\tif (questionResult.kind === \"back\") break;\n\t\t\t\tconst answeredTurnIndex = questions.indexOf(questionResult.value);\n\t\t\t\tif (answeredTurnIndex < 0) continue;\n\t\t\t\tselectedQuestion = questionResult.value;\n\t\t\t\tconst choice = makeChoice(\n\t\t\t\t\tbuildQuickBringToMainSegments(thread.turns, { kind: \"from\", answeredTurnIndex }),\n\t\t\t\t);\n\t\t\t\tconst preview = await showPreview(ctx, choice.draft, choice.summary);\n\t\t\t\tif (preview.kind === \"close\") return { kind: \"closed\" };\n\t\t\t\tif (preview.kind === \"back\") continue;\n\t\t\t\treturn choice;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (scope !== exactOption) continue;\n\t\tlet selectionState: BtwTextRangeSelectorState | undefined;\n\t\twhile (true) {\n\t\t\tconst selectedRange = await showBtwCustomPreservingEditor<BtwBringToMainChoice>(\n\t\t\t\tctx,\n\t\t\t\t(tui, theme, keybindings, done) => {\n\t\t\t\t\tlet selector: BtwTextRangeSelector;\n\t\t\t\t\tselector = new BtwTextRangeSelector(\n\t\t\t\t\t\ttui,\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tkeybindings,\n\t\t\t\t\t\tthread.turns,\n\t\t\t\t\t\t(action) => {\n\t\t\t\t\t\t\tif (action.kind === \"back\") done({ kind: \"back\" });\n\t\t\t\t\t\t\telse if (action.kind === \"close\") done({ kind: \"closed\" });\n\t\t\t\t\t\t\telse done({ ...makeChoice(action.segments), selectionState: selector.getState() });\n\t\t\t\t\t\t},\n\t\t\t\t\t\tselectionState,\n\t\t\t\t\t);\n\t\t\t\t\treturn selector;\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (!selectedRange) return { kind: \"closed\" };\n\t\t\tif (selectedRange.kind === \"closed\") return selectedRange;\n\t\t\tif (selectedRange.kind === \"back\") break;\n\t\t\tconst preview = await showPreview(ctx, selectedRange.draft, selectedRange.summary);\n\t\t\tif (preview.kind === \"close\") return { kind: \"closed\" };\n\t\t\tif (preview.kind === \"back\") {\n\t\t\t\tselectionState = selectedRange.selectionState;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"bringToMain\",\n\t\t\t\tdraft: selectedRange.draft,\n\t\t\t\tsummary: selectedRange.summary,\n\t\t\t};\n\t\t}\n\t}\n}\n\ntype BtwMenuSelectorAction =\n\t| { kind: \"select\"; value: string }\n\t| { kind: \"back\" }\n\t| { kind: \"close\" };\n\ntype BtwBringToMainPreviewAction = { kind: \"bring\" } | { kind: \"back\" } | { kind: \"close\" };\n\nasync function showBringToMainPreview(\n\tctx: ExtensionCommandContext,\n\tdraft: string,\n\tsummary: BtwBringToMainSummary,\n): Promise<BtwBringToMainPreviewAction> {\n\tconst { defineMenu, runMenu } = await import(\"@narumitw/pi-tui-kit\");\n\tif (ctx.signal?.aborted) return { kind: \"close\" };\n\tlet confirmed = false;\n\tconst count = summary.messages === 1 ? \"1 message\" : `${summary.messages} messages`;\n\tconst lineCount = summary.lines === 1 ? \"1 line\" : `${summary.lines} lines`;\n\tconst menu = defineMenu<void, \"preview\", \"bring\", MenuContext>({\n\t\tstart: \"preview\",\n\t\tscreens: {\n\t\t\tpreview: () => ({\n\t\t\t\tkind: \"review\",\n\t\t\t\ttitle: `Preview \u00B7 ${count} \u00B7 ${lineCount} \u00B7 ~${summary.tokens} tokens`,\n\t\t\t\tcontent: draft,\n\t\t\t\tviewportSize: \"adaptive\",\n\t\t\t\thint: \"back\",\n\t\t\t\tconfirm: { id: \"bring\", label: \"Bring\", action: \"bring\" },\n\t\t\t}),\n\t\t},\n\t\tactions: {\n\t\t\tbring: async () => {\n\t\t\t\tconfirmed = true;\n\t\t\t\treturn { kind: \"close\" } as const;\n\t\t\t},\n\t\t},\n\t});\n\tconst result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>\n\t\trunMenu(menuContext, menu, { getState: () => undefined }),\n\t);\n\tif (confirmed && result.kind === \"closed\" && result.reason === \"close\") {\n\t\treturn { kind: \"bring\" };\n\t}\n\treturn terminalBtwMenuAction(result);\n}\n\nasync function showBtwMenu(\n\tctx: ExtensionCommandContext,\n\ttitle: string,\n\toptions: readonly string[],\n\tinitialValue?: string,\n): Promise<BtwMenuSelectorAction> {\n\tconst { defineMenu, runMenu } = await import(\"@narumitw/pi-tui-kit\");\n\tif (ctx.signal?.aborted) return { kind: \"close\" };\n\tconst items = options.map((label, index) => ({ id: `option-${index}`, label }));\n\tconst initialIndex = initialValue === undefined ? -1 : options.indexOf(initialValue);\n\tlet selectedValue: string | undefined;\n\tconst menu = defineMenu<void, \"choices\", \"select\", MenuContext>({\n\t\tstart: \"choices\",\n\t\tscreens: {\n\t\t\tchoices: () => ({\n\t\t\t\tkind: \"choice\",\n\t\t\t\ttitle,\n\t\t\t\titems,\n\t\t\t\taction: \"select\",\n\t\t\t\tinitialItemId: initialIndex >= 0 ? `option-${initialIndex}` : undefined,\n\t\t\t\thint: \"back\",\n\t\t\t}),\n\t\t},\n\t\tactions: {\n\t\t\tselect: async ({ itemId }: { itemId: string }) => {\n\t\t\t\tconst index = Number.parseInt(itemId.slice(\"option-\".length), 10);\n\t\t\t\tselectedValue = options[index];\n\t\t\t\treturn selectedValue === undefined\n\t\t\t\t\t? ({ kind: \"stay\" } as const)\n\t\t\t\t\t: ({ kind: \"close\" } as const);\n\t\t\t},\n\t\t},\n\t});\n\tconst result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>\n\t\trunMenu(menuContext, menu, { getState: () => undefined }),\n\t);\n\treturn selectedValue !== undefined && result.kind === \"closed\" && result.reason === \"close\"\n\t\t? { kind: \"select\", value: selectedValue }\n\t\t: terminalBtwMenuAction(result);\n}\n\nfunction terminalBtwMenuAction(result: RunMenuResult): { kind: \"back\" } | { kind: \"close\" } {\n\tif (result.kind === \"closed\") return { kind: result.reason };\n\tif (result.kind === \"error\") throw result.error;\n\treturn { kind: \"close\" };\n}\n\nexport async function loadBringToMainDraft(\n\tdraft: string,\n\tctx: ExtensionCommandContext,\n\tsummary: BtwBringToMainSummary,\n): Promise<BtwBringToMainDelivery> {\n\tconst describeContent = () =>\n\t\t`${summary.messages} ${summary.messages === 1 ? \"message\" : \"messages\"} (~${summary.tokens} ${summary.tokens === 1 ? \"token\" : \"tokens\"})`;\n\tconst existing = ctx.ui.getEditorText();\n\tif (!existing.trim()) {\n\t\tctx.ui.setEditorText(draft);\n\t\tctx.ui.notify(\n\t\t\t`Brought ${describeContent()} to the main editor. Review and submit when ready.`,\n\t\t\t\"info\",\n\t\t);\n\t\treturn \"loaded\";\n\t}\n\n\tconst appendOption = \"Append after current draft Recommended\";\n\tconst replaceOption = \"\u26A0 Replace current draft Discards current editor text\";\n\tconst cancelOption = \"Cancel Return to the side thread\";\n\twhile (true) {\n\t\tconst action = await showBtwMenu(ctx, \"The main editor already has a draft\", [\n\t\t\tappendOption,\n\t\t\treplaceOption,\n\t\t\tcancelOption,\n\t\t]);\n\t\tif (action.kind === \"close\") return \"closed\";\n\t\tif (action.kind === \"back\" || action.value === cancelOption) return \"back\";\n\t\tif (action.value === appendOption) {\n\t\t\tctx.ui.setEditorText(`${ctx.ui.getEditorText()}\\n\\n${draft}`);\n\t\t\tctx.ui.notify(\n\t\t\t\t`Appended ${describeContent()} to the existing main-editor draft. Review and submit when ready.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t\treturn \"loaded\";\n\t\t}\n\t\tif (action.value !== replaceOption) continue;\n\n\t\tconst current = ctx.ui.getEditorText();\n\t\tconst characters = [...current].length;\n\t\tconst confirmed = await showBtwMenu(\n\t\t\tctx,\n\t\t\t`Replace the current ${characters}-character editor draft?`,\n\t\t\t[\"Back Keep current editor text\", \"\u26A0 Replace current draft Cannot be undone\"],\n\t\t);\n\t\tif (confirmed.kind === \"close\") return \"closed\";\n\t\tif (confirmed.kind === \"back\" || confirmed.value === \"Back Keep current editor text\") continue;\n\t\tif (confirmed.value !== \"\u26A0 Replace current draft Cannot be undone\") continue;\n\t\tif (ctx.ui.getEditorText() !== current) {\n\t\t\tctx.ui.notify(\n\t\t\t\t\"The main editor changed during confirmation. Review the updated draft and choose again.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tctx.ui.setEditorText(draft);\n\t\tctx.ui.notify(\n\t\t\t`Replaced the main-editor draft with ${describeContent()}. Review and submit when ready.`,\n\t\t\t\"info\",\n\t\t);\n\t\treturn \"loaded\";\n\t}\n}\n\nfunction truncatePreview(text: string): string {\n\treturn text.length <= 72 ? text : `${text.slice(0, 69)}\u2026`;\n}\n\nasync function askThreadQuestion(\n\tthread: SideThread,\n\tquestion: string,\n\tselected: ResolvedBtwModel,\n\tthinkingLevel: BtwThinkingLevel,\n\tctx: ExtensionCommandContext,\n\tsteering: BtwThreadSteeringControl,\n) {\n\treturn ctx.ui.custom<Awaited<ReturnType<typeof completeSideThreadTurn>>>(\n\t\t(tui, theme, keybindings, done) => {\n\t\t\tlet settled = false;\n\t\t\tconst view = new BtwAnsweringView(\n\t\t\t\ttui,\n\t\t\t\ttheme,\n\t\t\t\tthread.turns,\n\t\t\t\tquestion,\n\t\t\t\t() => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tdone({ kind: \"aborted\" });\n\t\t\t\t},\n\t\t\t\tthinkingLevel,\n\t\t\t\t{\n\t\t\t\t\tsteering: {\n\t\t\t\t\t\tquestions: steering.questions,\n\t\t\t\t\t\tonSubmit: steering.submit,\n\t\t\t\t\t\tthinking: { ...steering.thinking, keybindings },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tcompleteSideThreadTurn({\n\t\t\t\tthread,\n\t\t\t\tquestion,\n\t\t\t\tmodel: selected.model,\n\t\t\t\tthinkingLevel,\n\t\t\t\tauth: selected.auth,\n\t\t\t\tsignal: view.signal,\n\t\t\t\tcompleteSimple: createModelRegistryCompleteSimple(ctx.modelRegistry),\n\t\t\t\tsessionId: readBtwSessionId(ctx),\n\t\t\t}).then((result) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tview.finish();\n\t\t\t\tdone(result);\n\t\t\t});\n\t\t\treturn view;\n\t\t},\n\t);\n}\n\nasync function showThreadComposer(\n\tthread: SideThread,\n\tstartAtBottom: boolean,\n\tctx: ExtensionCommandContext,\n\tinitialQuestion: string | undefined,\n\tthinking: BtwThreadThinkingControl,\n): Promise<TranscriptPagerAction> {\n\treturn ctx.ui.custom<TranscriptPagerAction>(\n\t\t(tui, theme, keybindings, done) =>\n\t\t\tnew BtwTranscriptPager(tui, theme, thread.turns, done, {\n\t\t\t\tstartAtBottom,\n\t\t\t\tinitialQuestion,\n\t\t\t\tthinking: { ...thinking, keybindings },\n\t\t\t}),\n\t);\n}\n\ntype MessageContentBlock = {\n\ttype?: string;\n\ttext?: string;\n\tname?: string;\n\targuments?: unknown;\n\tresult?: unknown;\n};\n\ntype SessionMessage = {\n\trole?: string;\n\tcontent?: unknown;\n\tstopReason?: string;\n};\n\ntype SessionEntry = {\n\ttype: string;\n\tmessage?: SessionMessage;\n};\n\nexport function buildConversationContext(entries: readonly SessionEntry[]) {\n\tconst sections: string[] = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\" || !entry.message?.role) continue;\n\n\t\tconst role = entry.message.role;\n\t\tif (role !== \"user\" && role !== \"assistant\") continue;\n\n\t\tconst contentLines = extractContentLines(entry.message.content);\n\t\tif (contentLines.length === 0) continue;\n\n\t\tconst label = role === \"user\" ? \"User\" : \"Assistant\";\n\t\tconst status =\n\t\t\tentry.message.stopReason && entry.message.stopReason !== \"stop\"\n\t\t\t\t? ` (${entry.message.stopReason})`\n\t\t\t\t: \"\";\n\t\tsections.push(`${label}${status}: ${contentLines.join(\"\\n\")}`);\n\t}\n\n\treturn truncateFromStart(sections.join(\"\\n\\n\"), MAX_CONTEXT_CHARS);\n}\n\nfunction extractContentLines(content: unknown): string[] {\n\tif (typeof content === \"string\") return [content.trim()].filter(Boolean);\n\tif (!Array.isArray(content)) return [];\n\n\tconst lines: string[] = [];\n\tfor (const part of content) {\n\t\tif (!part || typeof part !== \"object\") continue;\n\t\tconst block = part as MessageContentBlock;\n\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\tlines.push(block.text.trim());\n\t\t} else if (block.type === \"toolCall\" && typeof block.name === \"string\") {\n\t\t\tlines.push(`Tool call: ${block.name}(${formatJson(block.arguments)})`);\n\t\t} else if (block.type === \"toolResult\" && typeof block.name === \"string\") {\n\t\t\tlines.push(`Tool result from ${block.name}: ${formatJson(block.result)}`);\n\t\t}\n\t}\n\treturn lines.filter(Boolean);\n}\n\nfunction formatJson(value: unknown) {\n\tif (value === undefined) return \"\";\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction truncateFromStart(text: string, maxChars: number) {\n\tif (text.length <= maxChars) return text;\n\treturn `[Earlier context omitted; showing the last ${maxChars} characters.]\\n${text.slice(-maxChars)}`;\n}\n", "import type { KeybindingsManager, Theme } from \"@earendil-works/pi-coding-agent\";\nimport {\n\ttype Component,\n\tKey,\n\tmatchesKey,\n\ttype TUI,\n\ttruncateToWidth,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport type { SideThreadTurn } from \"./side-thread.js\";\n\nconst RESERVED_APP_ROWS = 3;\nconst GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nexport interface BtwBringToMainSegment {\n\trole: \"user\" | \"assistant\";\n\ttext: string;\n}\n\nexport interface BtwBringToMainSummary {\n\tlines: number;\n\tmessages: number;\n\ttokens: number;\n}\n\nexport interface BtwSelectionLine {\n\trole: BtwBringToMainSegment[\"role\"];\n\ttext: string;\n}\n\nexport interface BtwTextPosition {\n\tline: number;\n\tcolumn: number;\n}\n\nexport interface BtwTextRangeSelectorState {\n\tcursor: BtwTextPosition;\n\tanchor?: BtwTextPosition;\n\tlineAnchor?: number;\n\tpreferredColumn: number;\n\tscrollOffset: number;\n\thorizontalOffset: number;\n}\n\nexport type BtwQuickBringToMainScope =\n\t| { kind: \"latest\" }\n\t| { kind: \"from\"; answeredTurnIndex: number }\n\t| { kind: \"entire\" };\n\nexport type BtwTextRangeSelectorAction =\n\t| { kind: \"confirm\"; segments: BtwBringToMainSegment[] }\n\t| { kind: \"back\" }\n\t| { kind: \"close\" };\n\nexport function getAnsweredTurns(\n\tturns: readonly SideThreadTurn[],\n): Array<Extract<SideThreadTurn, { kind: \"answered\" }>> {\n\treturn turns.filter(\n\t\t(turn): turn is Extract<SideThreadTurn, { kind: \"answered\" }> => turn.kind === \"answered\",\n\t);\n}\n\nexport function buildQuickBringToMainSegments(\n\tturns: readonly SideThreadTurn[],\n\tscope: BtwQuickBringToMainScope,\n): BtwBringToMainSegment[] {\n\tconst answered = getAnsweredTurns(turns);\n\tconst selected =\n\t\tscope.kind === \"latest\"\n\t\t\t? answered.slice(-1)\n\t\t\t: scope.kind === \"from\"\n\t\t\t\t? answered.slice(Math.max(0, scope.answeredTurnIndex))\n\t\t\t\t: answered;\n\treturn selected.flatMap((turn) => [\n\t\t{ role: \"user\" as const, text: turn.question },\n\t\t{ role: \"assistant\" as const, text: turn.answer },\n\t]);\n}\n\nexport function buildBtwSelectionLines(turns: readonly SideThreadTurn[]): BtwSelectionLine[] {\n\treturn buildQuickBringToMainSegments(turns, { kind: \"entire\" }).flatMap((segment) =>\n\t\tsegment.text.split(\"\\n\").map((text) => ({ role: segment.role, text })),\n\t);\n}\n\nexport function segmentsFromLineRange(\n\tlines: readonly BtwSelectionLine[],\n\tanchor: number,\n\tcursor: number,\n): BtwBringToMainSegment[] {\n\tif (lines.length === 0) return [];\n\tconst start = Math.max(0, Math.min(anchor, cursor, lines.length - 1));\n\tconst end = Math.max(0, Math.min(Math.max(anchor, cursor), lines.length - 1));\n\tconst segments: BtwBringToMainSegment[] = [];\n\tfor (const line of lines.slice(start, end + 1)) {\n\t\tconst previous = segments.at(-1);\n\t\tif (previous?.role === line.role) {\n\t\t\tprevious.text += `\\n${line.text}`;\n\t\t} else {\n\t\t\tsegments.push({ role: line.role, text: line.text });\n\t\t}\n\t}\n\treturn segments;\n}\n\nexport function segmentsFromTextRange(\n\tlines: readonly BtwSelectionLine[],\n\tanchor: BtwTextPosition,\n\tcursor: BtwTextPosition,\n): BtwBringToMainSegment[] {\n\tif (lines.length === 0) return [];\n\tconst first = clampTextPosition(lines, anchor);\n\tconst second = clampTextPosition(lines, cursor);\n\tconst [start, end] = compareTextPositions(first, second) <= 0 ? [first, second] : [second, first];\n\tif (compareTextPositions(start, end) === 0) return [];\n\n\tconst segments: BtwBringToMainSegment[] = [];\n\tfor (let lineIndex = start.line; lineIndex <= end.line; lineIndex += 1) {\n\t\tconst line = lines[lineIndex];\n\t\tif (!line) continue;\n\t\tconst characters = splitGraphemes(line.text);\n\t\tconst from = lineIndex === start.line ? start.column : 0;\n\t\tconst to = lineIndex === end.line ? end.column : characters.length;\n\t\tconst text = characters.slice(from, to).join(\"\");\n\t\tif (text) {\n\t\t\tconst previous = segments.at(-1);\n\t\t\tif (previous?.role === line.role) previous.text += text;\n\t\t\telse segments.push({ role: line.role, text });\n\t\t}\n\t\tconst crossesSameRoleLine = lineIndex < end.line && lines[lineIndex + 1]?.role === line.role;\n\t\tif (crossesSameRoleLine) {\n\t\t\tconst current = segments.at(-1);\n\t\t\tif (current?.role === line.role) current.text += \"\\n\";\n\t\t\telse segments.push({ role: line.role, text: \"\\n\" });\n\t\t}\n\t}\n\treturn segments;\n}\n\nexport function estimateBringToMainTokens(segments: readonly BtwBringToMainSegment[]): number {\n\treturn Math.ceil(\n\t\tBuffer.byteLength(segments.map((segment) => segment.text).join(\"\\n\"), \"utf8\") / 4,\n\t);\n}\n\nexport function summarizeBringToMain(\n\tsegments: readonly BtwBringToMainSegment[],\n): BtwBringToMainSummary {\n\treturn {\n\t\tlines: segments.reduce((count, segment) => count + segment.text.split(\"\\n\").length, 0),\n\t\tmessages: segments.length,\n\t\ttokens: estimateBringToMainTokens(segments),\n\t};\n}\n\nexport function formatBtwBringToMain(segments: readonly BtwBringToMainSegment[]): string {\n\tconst body = segments\n\t\t.map(\n\t\t\t(segment) =>\n\t\t\t\t`${segment.role === \"user\" ? \"User\" : \"Assistant\"}:\\n${escapeBringToMainText(segment.text)}`,\n\t\t)\n\t\t.join(\"\\n\\n\");\n\treturn [\n\t\t\"The following context was brought back from a /btw side discussion.\",\n\t\t\"Treat it as discussion context, not as work already completed.\",\n\t\t\"\",\n\t\t\"<btw_context>\",\n\t\tbody,\n\t\t\"</btw_context>\",\n\t].join(\"\\n\");\n}\n\nexport class BtwTextRangeSelector implements Component {\n\tprivate readonly lines: BtwSelectionLine[];\n\tprivate cursor: BtwTextPosition = { line: 0, column: 0 };\n\tprivate anchor: BtwTextPosition | undefined;\n\tprivate lineAnchor: number | undefined;\n\tprivate preferredColumn = 0;\n\tprivate scrollOffset = 0;\n\tprivate horizontalOffset = 0;\n\tprivate warning: string | undefined;\n\tprivate finished = false;\n\n\tconstructor(\n\t\tprivate readonly tui: TUI,\n\t\tprivate readonly theme: Theme,\n\t\tprivate readonly keybindings: KeybindingsManager,\n\t\tturns: readonly SideThreadTurn[],\n\t\tprivate readonly onAction: (action: BtwTextRangeSelectorAction) => void,\n\t\tinitialState?: BtwTextRangeSelectorState,\n\t) {\n\t\tthis.lines = buildBtwSelectionLines(turns);\n\t\tif (initialState) {\n\t\t\tthis.cursor = clampTextPosition(this.lines, initialState.cursor);\n\t\t\tthis.anchor = initialState.anchor\n\t\t\t\t? clampTextPosition(this.lines, initialState.anchor)\n\t\t\t\t: undefined;\n\t\t\tthis.lineAnchor =\n\t\t\t\tinitialState.lineAnchor === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Math.max(0, Math.min(this.lines.length - 1, initialState.lineAnchor));\n\t\t\tthis.preferredColumn = Math.max(0, initialState.preferredColumn);\n\t\t\tthis.scrollOffset = Math.max(0, initialState.scrollOffset);\n\t\t\tthis.horizontalOffset = Math.max(0, initialState.horizontalOffset);\n\t\t}\n\t}\n\n\tgetState(): BtwTextRangeSelectorState {\n\t\treturn {\n\t\t\tcursor: { ...this.cursor },\n\t\t\tanchor: this.anchor ? { ...this.anchor } : undefined,\n\t\t\tlineAnchor: this.lineAnchor,\n\t\t\tpreferredColumn: this.preferredColumn,\n\t\t\tscrollOffset: this.scrollOffset,\n\t\t\thorizontalOffset: this.horizontalOffset,\n\t\t};\n\t}\n\n\trender(width: number): string[] {\n\t\tconst safeWidth = Math.max(1, width);\n\t\tconst availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_ROWS);\n\t\tconst showStatus = availableRows >= 4;\n\t\tconst showFooter = availableRows >= 3;\n\t\tconst viewportHeight = Math.max(\n\t\t\t1,\n\t\t\tavailableRows - 1 - (showStatus ? 1 : 0) - (showFooter ? 1 : 0),\n\t\t);\n\t\tthis.keepCursorVisible(viewportHeight);\n\t\tconst textWidth = Math.max(1, safeWidth - visibleWidth(\"\u25CF> Assistant \u2502 \"));\n\t\tthis.keepCursorHorizontallyVisible(textWidth);\n\t\tconst range = this.getSelectionRange();\n\t\tconst lineRange = this.getLineSelectionRange();\n\t\tconst visible = this.lines.slice(this.scrollOffset, this.scrollOffset + viewportHeight);\n\t\tconst rows = visible.map((line, visibleIndex) => {\n\t\t\tconst lineIndex = this.scrollOffset + visibleIndex;\n\t\t\tconst role = line.role === \"user\" ? \"User\" : \"Assistant\";\n\t\t\tconst lineSelected = lineRange\n\t\t\t\t? lineIndex >= lineRange.start && lineIndex <= lineRange.end\n\t\t\t\t: false;\n\t\t\tconst prefix = `${lineSelected ? \"\u25CF\" : \" \"}${lineIndex === this.cursor.line ? \">\" : \" \"} ${role.padEnd(9)} \u2502 `;\n\t\t\tconst text = this.renderTextLine(line, lineIndex, range, lineSelected);\n\t\t\treturn truncateToWidth(\n\t\t\t\tlineIndex === this.cursor.line ? this.theme.fg(\"accent\", prefix) + text : prefix + text,\n\t\t\t\tsafeWidth,\n\t\t\t\t\"\",\n\t\t\t);\n\t\t});\n\t\tconst selected = this.getSelectedSegments();\n\t\tconst summary = summarizeBringToMain(selected);\n\t\tconst status =\n\t\t\tselected.length === 0\n\t\t\t\t? \"Selected: none\"\n\t\t\t\t: `Selected: ${summary.lines} ${summary.lines === 1 ? \"line\" : \"lines\"} \u00B7 ${summary.messages} ${summary.messages === 1 ? \"message\" : \"messages\"} \u00B7 ~${summary.tokens} ${summary.tokens === 1 ? \"token\" : \"tokens\"}`;\n\t\tconst confirm = confirmKeyLabel(this.keybindings);\n\t\tconst back = keybindingLabel(this.keybindings, \"tui.select.cancel\", [\"ctrl+c\"]);\n\t\tconst vertical = `${keybindingLabel(this.keybindings, \"tui.select.up\")}/${keybindingLabel(this.keybindings, \"tui.select.down\")}`;\n\t\tconst confirmUsesSpace = this.keybindings.matches(\" \", \"tui.select.confirm\");\n\t\tconst detailedFooter = this.warning\n\t\t\t? `${this.warning} \u2022 ${confirmUsesSpace ? \"Shift+Arrows select\" : \"Space lines \u2022 Shift+Arrows text\"} \u2022 ${back} back \u2022 Ctrl+C close`\n\t\t\t: this.lineAnchor !== undefined\n\t\t\t\t? `${confirmUsesSpace ? `${vertical} extend lines` : `Space clear \u2022 ${vertical} extend lines`} \u2022 Shift+Arrows text \u2022 ${confirm} bring \u2022 ${back} back \u2022 Ctrl+C close`\n\t\t\t\t: `Shift+Arrows select \u2022 Arrows move${confirmUsesSpace ? \"\" : \" \u2022 Space lines\"} \u2022 ${confirm} bring \u2022 ${back} back \u2022 Ctrl+C close`;\n\t\tconst criticalFooter = `${confirm} bring \u2022 ${back} back \u2022 Ctrl+C close`;\n\t\tconst footer = visibleWidth(detailedFooter) <= safeWidth ? detailedFooter : criticalFooter;\n\t\treturn fitRows(\n\t\t\t[\n\t\t\t\ttruncateToWidth(\n\t\t\t\t\tthis.theme.fg(\"accent\", this.theme.bold(\"Select text to bring to main\")),\n\t\t\t\t\tsafeWidth,\n\t\t\t\t\t\"\",\n\t\t\t\t),\n\t\t\t\t...(showStatus ? [truncateToWidth(this.theme.fg(\"muted\", status), safeWidth, \"\")] : []),\n\t\t\t\t...rows,\n\t\t\t\t...(showFooter\n\t\t\t\t\t? [\n\t\t\t\t\t\t\ttruncateToWidth(\n\t\t\t\t\t\t\t\tthis.theme.fg(this.warning ? \"warning\" : \"muted\", footer),\n\t\t\t\t\t\t\t\tsafeWidth,\n\t\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t]\n\t\t\t\t\t: []),\n\t\t\t],\n\t\t\tavailableRows,\n\t\t);\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.finished) return;\n\t\tif (matchesKey(data, Key.ctrl(\"c\"))) {\n\t\t\tthis.finish({ kind: \"close\" });\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.finish({ kind: \"back\" });\n\t\t\treturn;\n\t\t}\n\t\tif (matchesConfirm(data, this.keybindings)) {\n\t\t\tif (this.lines.length > 0) {\n\t\t\t\tconst segments = this.getSelectedSegments();\n\t\t\t\tif (segments.length === 0) {\n\t\t\t\t\tthis.warning = \"Select text first\";\n\t\t\t\t\tthis.tui.requestRender();\n\t\t\t\t} else {\n\t\t\t\t\tthis.finish({ kind: \"confirm\", segments });\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.space)) {\n\t\t\tthis.anchor = undefined;\n\t\t\tthis.lineAnchor = this.lineAnchor === undefined ? this.cursor.line : undefined;\n\t\t\tthis.afterMove();\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.shift(\"left\"))) {\n\t\t\tthis.moveHorizontal(-1, true);\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.shift(\"right\"))) {\n\t\t\tthis.moveHorizontal(1, true);\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.shift(\"up\"))) {\n\t\t\tthis.moveVertical(-1, true);\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.shift(\"down\"))) {\n\t\t\tthis.moveVertical(1, true);\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.left)) {\n\t\t\tthis.moveHorizontal(-1, false);\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.right)) {\n\t\t\tthis.moveHorizontal(1, false);\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.up\")) {\n\t\t\tthis.moveVertical(-1, false);\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.down\")) {\n\t\t\tthis.moveVertical(1, false);\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.pageUp\")) {\n\t\t\tthis.moveVertical(-10, false);\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.pageDown\")) {\n\t\t\tthis.moveVertical(10, false);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tinvalidate(): void {}\n\n\tprivate renderTextLine(\n\t\tline: BtwSelectionLine,\n\t\tlineIndex: number,\n\t\trange: { start: BtwTextPosition; end: BtwTextPosition } | undefined,\n\t\tlineSelected: boolean,\n\t): string {\n\t\tconst characters = splitGraphemes(line.text);\n\t\tlet rendered = this.horizontalOffset > 0 ? this.theme.fg(\"muted\", \"\u2026\") : \"\";\n\t\tlet buffer = \"\";\n\t\tlet bufferSelected = false;\n\t\tconst flush = () => {\n\t\t\tif (!buffer) return;\n\t\t\trendered += bufferSelected\n\t\t\t\t? this.theme.bg(\"selectedBg\", this.theme.fg(\"text\", buffer))\n\t\t\t\t: buffer;\n\t\t\tbuffer = \"\";\n\t\t};\n\t\tfor (let column = this.horizontalOffset; column <= characters.length; column += 1) {\n\t\t\tif (range && lineIndex === range.start.line && column === range.start.column) {\n\t\t\t\tflush();\n\t\t\t\trendered += this.theme.fg(\"accent\", \"[\");\n\t\t\t}\n\t\t\tif (lineIndex === this.cursor.line && column === this.cursor.column) {\n\t\t\t\tflush();\n\t\t\t\trendered += this.theme.fg(\"accent\", \"\u2502\");\n\t\t\t}\n\t\t\tif (range && lineIndex === range.end.line && column === range.end.column) {\n\t\t\t\tflush();\n\t\t\t\trendered += this.theme.fg(\"accent\", \"]\");\n\t\t\t}\n\t\t\tconst character = characters[column];\n\t\t\tif (character === undefined) continue;\n\t\t\tconst selected =\n\t\t\t\tlineSelected || (range ? positionFallsInside(lineIndex, column, range) : false);\n\t\t\tif (buffer && selected !== bufferSelected) flush();\n\t\t\tbufferSelected = selected;\n\t\t\tbuffer += escapeTerminalControls(character);\n\t\t}\n\t\tflush();\n\t\treturn rendered;\n\t}\n\n\tprivate getSelectionRange(): { start: BtwTextPosition; end: BtwTextPosition } | undefined {\n\t\tif (!this.anchor || compareTextPositions(this.anchor, this.cursor) === 0) return undefined;\n\t\treturn compareTextPositions(this.anchor, this.cursor) < 0\n\t\t\t? { start: this.anchor, end: this.cursor }\n\t\t\t: { start: this.cursor, end: this.anchor };\n\t}\n\n\tprivate getLineSelectionRange(): { start: number; end: number } | undefined {\n\t\treturn this.lineAnchor === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\tstart: Math.min(this.lineAnchor, this.cursor.line),\n\t\t\t\t\tend: Math.max(this.lineAnchor, this.cursor.line),\n\t\t\t\t};\n\t}\n\n\tprivate getSelectedSegments(): BtwBringToMainSegment[] {\n\t\tif (this.lineAnchor !== undefined) {\n\t\t\treturn segmentsFromLineRange(this.lines, this.lineAnchor, this.cursor.line);\n\t\t}\n\t\treturn this.anchor ? segmentsFromTextRange(this.lines, this.anchor, this.cursor) : [];\n\t}\n\n\tprivate moveHorizontal(delta: -1 | 1, extend: boolean): void {\n\t\tif (this.lines.length === 0) return;\n\t\tif (!extend) this.lineAnchor = undefined;\n\t\tif (!extend && this.anchor) {\n\t\t\tconst range = this.getSelectionRange();\n\t\t\tif (range) this.cursor = delta < 0 ? range.start : range.end;\n\t\t\tthis.anchor = undefined;\n\t\t\tthis.preferredColumn = this.cursor.column;\n\t\t\tthis.afterMove();\n\t\t\treturn;\n\t\t}\n\t\tthis.beginOrClearSelection(extend);\n\t\tconst line = this.lines[this.cursor.line];\n\t\tconst length = line ? splitGraphemes(line.text).length : 0;\n\t\tif (delta < 0) {\n\t\t\tif (this.cursor.column > 0) this.cursor = { ...this.cursor, column: this.cursor.column - 1 };\n\t\t\telse if (this.cursor.line > 0) {\n\t\t\t\tconst previousLine = this.lines[this.cursor.line - 1];\n\t\t\t\tthis.cursor = {\n\t\t\t\t\tline: this.cursor.line - 1,\n\t\t\t\t\tcolumn: previousLine ? splitGraphemes(previousLine.text).length : 0,\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (this.cursor.column < length) {\n\t\t\tthis.cursor = { ...this.cursor, column: this.cursor.column + 1 };\n\t\t} else if (this.cursor.line < this.lines.length - 1) {\n\t\t\tthis.cursor = { line: this.cursor.line + 1, column: 0 };\n\t\t}\n\t\tthis.preferredColumn = this.cursor.column;\n\t\tthis.afterMove();\n\t}\n\n\tprivate moveVertical(delta: number, extend: boolean): void {\n\t\tif (this.lines.length === 0) return;\n\t\tif (extend || this.lineAnchor === undefined) this.beginOrClearSelection(extend);\n\t\tconst line = Math.max(0, Math.min(this.lines.length - 1, this.cursor.line + delta));\n\t\tconst target = this.lines[line];\n\t\tthis.cursor = {\n\t\t\tline,\n\t\t\tcolumn: Math.min(this.preferredColumn, target ? splitGraphemes(target.text).length : 0),\n\t\t};\n\t\tthis.afterMove();\n\t}\n\n\tprivate beginOrClearSelection(extend: boolean): void {\n\t\tif (extend) this.lineAnchor = undefined;\n\t\tif (extend && !this.anchor) this.anchor = { ...this.cursor };\n\t\tif (!extend) this.anchor = undefined;\n\t}\n\n\tprivate afterMove(): void {\n\t\tthis.warning = undefined;\n\t\tthis.tui.requestRender();\n\t}\n\n\tprivate keepCursorVisible(height: number): void {\n\t\tif (height <= 0) return;\n\t\tif (this.cursor.line < this.scrollOffset) this.scrollOffset = this.cursor.line;\n\t\tif (this.cursor.line >= this.scrollOffset + height) {\n\t\t\tthis.scrollOffset = this.cursor.line - height + 1;\n\t\t}\n\t}\n\n\tprivate keepCursorHorizontallyVisible(width: number): void {\n\t\tconst characters = splitGraphemes(this.lines[this.cursor.line]?.text ?? \"\");\n\t\tconst displayWidths = characters.map((character) =>\n\t\t\tvisibleWidth(escapeTerminalControls(character)),\n\t\t);\n\t\tconst currentWidth = displayWidths[this.cursor.column] ?? 0;\n\t\tlet usedWidth = 1 + Math.min(currentWidth, Math.max(0, width - 1));\n\t\tlet offset = this.cursor.column;\n\t\tfor (let index = this.cursor.column - 1; index >= 0; index -= 1) {\n\t\t\tconst nextWidth = usedWidth + (displayWidths[index] ?? 0) + (index > 0 ? 1 : 0);\n\t\t\tif (nextWidth > width) break;\n\t\t\tusedWidth += displayWidths[index] ?? 0;\n\t\t\toffset = index;\n\t\t}\n\t\tthis.horizontalOffset = offset;\n\t}\n\n\tprivate finish(action: BtwTextRangeSelectorAction): void {\n\t\tif (this.finished) return;\n\t\tthis.finished = true;\n\t\tthis.onAction(action);\n\t}\n}\n\nfunction clampTextPosition(\n\tlines: readonly BtwSelectionLine[],\n\tposition: BtwTextPosition,\n): BtwTextPosition {\n\tconst line = Math.max(0, Math.min(lines.length - 1, position.line));\n\tconst text = lines[line]?.text ?? \"\";\n\treturn {\n\t\tline,\n\t\tcolumn: Math.max(0, Math.min(splitGraphemes(text).length, position.column)),\n\t};\n}\n\nfunction confirmKeyLabel(keybindings: KeybindingsManager): string {\n\treturn keybindingLabel(keybindings, \"tui.select.confirm\", [\"ctrl+c\"], \"enter\");\n}\n\nfunction matchesConfirm(data: string, keybindings: KeybindingsManager): boolean {\n\tif (matchesKey(data, Key.ctrl(\"c\"))) return false;\n\tconst hasUsableBinding = keybindings\n\t\t.getKeys(\"tui.select.confirm\")\n\t\t.map(String)\n\t\t.some((key) => key.toLowerCase() !== \"ctrl+c\");\n\treturn (\n\t\tkeybindings.matches(data, \"tui.select.confirm\") ||\n\t\t(!hasUsableBinding && matchesKey(data, Key.enter))\n\t);\n}\n\nfunction keybindingLabel(\n\tkeybindings: KeybindingsManager,\n\tkeybinding:\n\t\t| \"tui.select.confirm\"\n\t\t| \"tui.select.cancel\"\n\t\t| \"tui.select.up\"\n\t\t| \"tui.select.down\"\n\t\t| \"tui.select.pageUp\"\n\t\t| \"tui.select.pageDown\",\n\texcluded: readonly string[] = [],\n\tfallback?: string,\n): string {\n\tconst key = keybindings\n\t\t.getKeys(keybinding)\n\t\t.map(String)\n\t\t.find((candidate) => !excluded.includes(candidate.toLowerCase()));\n\treturn formatKeyLabel(key ?? fallback ?? keybinding);\n}\n\nfunction formatKeyLabel(key: string): string {\n\treturn key\n\t\t.split(\"+\")\n\t\t.map((part) => {\n\t\t\tconst lower = part.toLowerCase();\n\t\t\tif (lower === \"ctrl\") return \"Ctrl\";\n\t\t\tif (lower === \"alt\") return \"Alt\";\n\t\t\tif (lower === \"shift\") return \"Shift\";\n\t\t\tif (lower === \"escape\" || lower === \"esc\") return \"Esc\";\n\t\t\tif (lower === \"enter\" || lower === \"return\") return \"Enter\";\n\t\t\tif (lower === \"pageup\") return \"PgUp\";\n\t\t\tif (lower === \"pagedown\") return \"PgDn\";\n\t\t\treturn part.length === 1\n\t\t\t\t? part.toUpperCase()\n\t\t\t\t: `${part[0]?.toUpperCase() ?? \"\"}${part.slice(1)}`;\n\t\t})\n\t\t.join(\"+\");\n}\n\nfunction splitGraphemes(text: string): string[] {\n\treturn [...GRAPHEME_SEGMENTER.segment(text)].map(({ segment }) => segment);\n}\n\nfunction compareTextPositions(first: BtwTextPosition, second: BtwTextPosition): number {\n\treturn first.line === second.line ? first.column - second.column : first.line - second.line;\n}\n\nfunction positionFallsInside(\n\tline: number,\n\tcolumn: number,\n\trange: { start: BtwTextPosition; end: BtwTextPosition },\n): boolean {\n\tconst position = { line, column };\n\treturn (\n\t\tcompareTextPositions(position, range.start) >= 0 &&\n\t\tcompareTextPositions(position, range.end) < 0\n\t);\n}\n\nfunction fitRows(rows: string[], availableRows: number): string[] {\n\tif (rows.length <= availableRows) return rows;\n\tif (availableRows <= 1) return rows.slice(0, 1);\n\treturn [rows[0] ?? \"\", ...rows.slice(rows.length - availableRows + 1)];\n}\n\nfunction escapeBringToMainText(text: string): string {\n\treturn [...text]\n\t\t.map((character) => {\n\t\t\tif (character === \"\\n\") return character;\n\t\t\tif (character === \"\\t\") return \" \";\n\t\t\tconst code = character.charCodeAt(0);\n\t\t\tif (code <= 31 || (code >= 127 && code <= 159)) {\n\t\t\t\treturn `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n\t\t\t}\n\t\t\treturn character;\n\t\t})\n\t\t.join(\"\")\n\t\t.replace(/<btw_context(?=[ \\t\\r\\n>])/g, \"<btw_context\")\n\t\t.replace(/<\\/btw_context[ \\t\\r\\n]*>/g, (terminator) =>\n\t\t\tterminator.replaceAll(\"<\", \"<\").replaceAll(\">\", \">\"),\n\t\t);\n}\n\nfunction escapeTerminalControls(text: string): string {\n\treturn [...text]\n\t\t.map((character) => {\n\t\t\tconst code = character.charCodeAt(0);\n\t\t\tif (code <= 31 || (code >= 127 && code <= 159)) {\n\t\t\t\treturn `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n\t\t\t}\n\t\t\treturn character;\n\t\t})\n\t\t.join(\"\");\n}\n", "import { spawn } from \"node:child_process\";\nimport {\n\tcopyToClipboard as copyToHostClipboard,\n\ttype ExtensionCommandContext,\n\ttype KeybindingsManager,\n\ttype Theme,\n} from \"@earendil-works/pi-coding-agent\";\nimport {\n\ttype Component,\n\tisKeyRelease,\n\tisKittyProtocolActive,\n\tKey,\n\ttype OverlayHandle,\n\tparseKey,\n\ttype TUI,\n\tTuiAltScreen,\n\ttype TuiInputListener,\n\ttype TuiInputListenerResult,\n\ttruncateToWidth,\n} from \"@earendil-works/pi-tui\";\nimport {\n\ttype BtwKeybindingOverrides,\n\tBtwPasteGuard,\n\tresolveBtwShortcuts,\n\tsetBtwShortcuts,\n} from \"./keybindings.js\";\nimport { formatKeyLabel, sanitizeSingleLine } from \"./text.js\";\n\ntype BtwCustomOptions = Parameters<ExtensionCommandContext[\"ui\"][\"custom\"]>[1];\ntype BtwCustomFactory<T> = (\n\ttui: TUI,\n\ttheme: Theme,\n\tkeybindings: KeybindingsManager,\n\tdone: (result: T) => void,\n) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>;\n\ntype BtwFullscreenTui = TUI & {\n\tflash?: (message: string, durationMs?: number) => void;\n\tsetLayoutRoot(component: Component | undefined): void;\n\taddInputListenerBeforeAll?(listener: TuiInputListener): () => void;\n\taddInputListenerBeforeViewport?(listener: TuiInputListener): () => void;\n};\n\nexport interface BtwFullscreenLayoutComponent extends Component {\n\tgetFullscreenLayout(): Component;\n}\n\nexport interface BtwFullscreenOptions {\n\tkeybindings?: BtwKeybindingOverrides;\n\tcopyOnSelect?: boolean;\n}\n\nexport type BtwFullscreenTuiFactory = (\n\tparent: TUI,\n\ttheme: Theme,\n\tkeybindings: KeybindingsManager,\n\toptions: BtwFullscreenOptions,\n) => BtwFullscreenTui;\n\nexport interface BtwFullscreenDependencies {\n\tcreateTui?: BtwFullscreenTuiFactory;\n\topenUrl?: (url: string) => void;\n\tcopyToClipboard?: (text: string) => Promise<void>;\n\tmanualSelectionCopySupported?: boolean;\n}\n\nexport type RunBtwFullscreen = <T>(\n\tctx: ExtensionCommandContext,\n\trun: (ctx: ExtensionCommandContext) => Promise<T>,\n\toptions?: BtwFullscreenOptions,\n) => Promise<T>;\n\ntype FullscreenOutcome<T> = { kind: \"completed\"; value: T } | { kind: \"failed\"; error: unknown };\n\nclass FullscreenUiDisposedError extends Error {\n\tconstructor() {\n\t\tsuper(\"The dedicated pi-btw UI was disposed.\");\n\t\tthis.name = \"FullscreenUiDisposedError\";\n\t}\n}\n\nexport async function runBtwFullscreen<T>(\n\tctx: ExtensionCommandContext,\n\trun: (ctx: ExtensionCommandContext) => Promise<T>,\n\toptions: BtwFullscreenOptions = {},\n\tdependencies: BtwFullscreenDependencies = {},\n): Promise<T> {\n\tconst createTui =\n\t\tdependencies.createTui ??\n\t\t((\n\t\t\tparent: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tfullscreenOptions: BtwFullscreenOptions,\n\t\t) =>\n\t\t\tcreateBtwFullscreenTui(\n\t\t\t\tparent,\n\t\t\t\ttheme,\n\t\t\t\tkeybindings,\n\t\t\t\tfullscreenOptions.copyOnSelect ?? true,\n\t\t\t\tdependencies.manualSelectionCopySupported ?? hasManualSelectionCopyApi(),\n\t\t\t\tdependencies.openUrl ?? openUrlInBrowser,\n\t\t\t\tdependencies.copyToClipboard ?? copyToHostClipboard,\n\t\t\t));\n\tlet liveEditorText = ctx.ui.getEditorText();\n\tlet restoreEditor = false;\n\tlet host: BtwFullscreenHost<T> | undefined;\n\tconst outcome = await ctx.ui.custom<FullscreenOutcome<T>>(\n\t\t(parent, theme, keybindings, done) => {\n\t\t\thost = new BtwFullscreenHost(\n\t\t\t\tparent,\n\t\t\t\ttheme,\n\t\t\t\tkeybindings,\n\t\t\t\tctx,\n\t\t\t\trun,\n\t\t\t\t(value) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tliveEditorText = ctx.ui.getEditorText();\n\t\t\t\t\t\trestoreEditor = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A replaced session owns a different editor and must not receive stale text.\n\t\t\t\t\t}\n\t\t\t\t\tdone(value);\n\t\t\t\t},\n\t\t\t\tcreateTui,\n\t\t\t\toptions,\n\t\t\t);\n\t\t\treturn host;\n\t\t},\n\t\t{\n\t\t\toverlay: true,\n\t\t\tonHandle: (handle) => host?.setParentOverlay(handle),\n\t\t},\n\t);\n\tif (restoreEditor) {\n\t\ttry {\n\t\t\tif (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);\n\t\t} catch {\n\t\t\t// A replaced session owns a different editor and must not receive stale restoration.\n\t\t}\n\t}\n\tif (outcome.kind === \"failed\") throw outcome.error;\n\treturn outcome.value;\n}\n\ntype BtwInputListeners = {\n\tbeforeAll: Set<TuiInputListener>;\n\tbeforeViewport: Set<TuiInputListener>;\n\tregular: Set<TuiInputListener>;\n};\n\nconst btwInputListeners = new WeakMap<BtwTuiAltScreen, BtwInputListeners>();\n\nfunction dispatchBtwInput(listeners: BtwInputListeners, data: string): TuiInputListenerResult {\n\tlet current = data;\n\tfor (const group of [listeners.beforeAll, listeners.beforeViewport, listeners.regular]) {\n\t\tfor (const listener of group) {\n\t\t\tconst result = listener(current);\n\t\t\tif (result?.consume) return result;\n\t\t\tif (result?.data !== undefined) current = result.data;\n\t\t}\n\t}\n\treturn current === data ? undefined : { data: current };\n}\n\nclass BtwTuiAltScreen extends TuiAltScreen {\n\thasFocusedOverlay(): boolean {\n\t\treturn this.isOverlayFocused();\n\t}\n\n\toverride addInputListener(listener: TuiInputListener): () => void {\n\t\tlet listeners = btwInputListeners.get(this);\n\t\tif (!listeners) {\n\t\t\tconst registeredListeners: BtwInputListeners = {\n\t\t\t\tbeforeAll: new Set(),\n\t\t\t\tbeforeViewport: new Set(),\n\t\t\t\tregular: new Set(),\n\t\t\t};\n\t\t\tbtwInputListeners.set(this, registeredListeners);\n\t\t\tsuper.addInputListener((data) => dispatchBtwInput(registeredListeners, data));\n\t\t\tlisteners = registeredListeners;\n\t\t}\n\t\tlisteners.regular.add(listener);\n\t\treturn () => listeners.regular.delete(listener);\n\t}\n\n\taddInputListenerBeforeAll(listener: TuiInputListener): () => void {\n\t\tconst listeners = btwInputListeners.get(this);\n\t\tif (!listeners) return super.addInputListener(listener);\n\t\tlisteners.beforeAll.add(listener);\n\t\treturn () => listeners.beforeAll.delete(listener);\n\t}\n\n\taddInputListenerBeforeViewport(listener: TuiInputListener): () => void {\n\t\tconst listeners = btwInputListeners.get(this);\n\t\tif (!listeners) return super.addInputListener(listener);\n\t\tlisteners.beforeViewport.add(listener);\n\t\treturn () => listeners.beforeViewport.delete(listener);\n\t}\n\n\toverride removeInputListener(listener: TuiInputListener): void {\n\t\tconst listeners = btwInputListeners.get(this);\n\t\tif (!listeners) {\n\t\t\tsuper.removeInputListener(listener);\n\t\t\treturn;\n\t\t}\n\t\tlisteners.beforeAll.delete(listener);\n\t\tlisteners.beforeViewport.delete(listener);\n\t\tlisteners.regular.delete(listener);\n\t}\n}\n\nconst BRACKETED_PASTE_START = \"\\u001b[200~\";\nconst BRACKETED_PASTE_END = \"\\u001b[201~\";\n\n// TuiAltScreen evaluates these actions before bottom, so shared keys cannot jump to latest.\nconst ALT_SCREEN_ACTIONS_BEFORE_BOTTOM = [\n\t\"tui.altScreen.search\",\n\t\"tui.altScreen.searchNext\",\n\t\"tui.altScreen.searchPrevious\",\n\t\"tui.altScreen.searchClose\",\n\t\"tui.altScreen.pageUp\",\n\t\"tui.altScreen.pageDown\",\n\t\"tui.altScreen.halfPageUp\",\n\t\"tui.altScreen.halfPageDown\",\n\t\"tui.altScreen.lineUp\",\n\t\"tui.altScreen.lineDown\",\n\t\"tui.altScreen.previousPrompt\",\n\t\"tui.altScreen.nextPrompt\",\n\t\"tui.altScreen.top\",\n] as const;\nconst KEY_MODIFIER_ORDER = [\"shift\", \"ctrl\", \"alt\", \"super\"] as const;\nconst MATCHABLE_SPECIAL_KEYS = new Set([\n\t\"space\",\n\t\"tab\",\n\t\"enter\",\n\t\"backspace\",\n\t\"delete\",\n\t\"insert\",\n\t\"home\",\n\t\"end\",\n\t\"pageup\",\n\t\"pagedown\",\n\t\"up\",\n\t\"down\",\n\t\"left\",\n\t\"right\",\n]);\nconst MATCHABLE_SYMBOL_KEYS = new Set(\"`-=[]\\\\;',./!@#$%^&*()_+|~{}:<>?\");\n\nfunction normalizedKeyId(key: string): string {\n\tconst parts = key.toLowerCase().split(\"+\");\n\tconst base = parts.at(-1);\n\tif (!base) return \"\";\n\tconst normalizedBase = base === \"esc\" ? \"escape\" : base === \"return\" ? \"enter\" : base;\n\tconst modifiers = KEY_MODIFIER_ORDER.filter((modifier) => parts.includes(modifier));\n\treturn [...modifiers, normalizedBase].join(\"+\");\n}\n\nfunction formatEffectiveKeyLabel(key: string): string {\n\tconst parts = key.split(\"+\");\n\tconst base = parts.at(-1);\n\tif (base === \"pageup\") parts[parts.length - 1] = \"pageUp\";\n\tif (base === \"pagedown\") parts[parts.length - 1] = \"pageDown\";\n\treturn formatKeyLabel(parts.join(\"+\"));\n}\n\nfunction canMatchKeyInput(key: string): boolean {\n\tconst parts = key.split(\"+\");\n\tconst base = parts.at(-1) ?? \"\";\n\tconst modifiers = parts.slice(0, -1);\n\tif (base === \"escape\") return modifiers.length === 0;\n\tif (base === \"clear\") {\n\t\treturn (\n\t\t\tmodifiers.length === 0 ||\n\t\t\t(modifiers.length === 1 && (modifiers[0] === \"shift\" || modifiers[0] === \"ctrl\"))\n\t\t);\n\t}\n\tif (/^f(?:[1-9]|1[0-2])$/u.test(base)) return modifiers.length === 0;\n\treturn (\n\t\tMATCHABLE_SPECIAL_KEYS.has(base) ||\n\t\t(base.length === 1 && (/^[a-z0-9]$/u.test(base) || MATCHABLE_SYMBOL_KEYS.has(base)))\n\t);\n}\n\nfunction rawCtrlInput(base: string): string | undefined {\n\tif (base.length !== 1) return undefined;\n\tconst rawBase = base === \"-\" ? \"_\" : base;\n\tif (!\"abcdefghijklmnopqrstuvwxyz[\\\\]_\".includes(rawBase)) return undefined;\n\treturn String.fromCharCode(rawBase.charCodeAt(0) & 0x1f);\n}\n\nfunction legacyRawInput(key: string): string | undefined {\n\tconst parts = key.split(\"+\");\n\tconst base = parts.at(-1) ?? \"\";\n\tif (parts.length === 2 && parts[0] === \"ctrl\") return rawCtrlInput(base);\n\tif (isKittyProtocolActive()) return undefined;\n\tif (parts.length === 2 && parts[0] === \"alt\" && base.length === 1) return `\\u001b${base}`;\n\tif (parts.length === 3 && parts[0] === \"ctrl\" && parts[1] === \"alt\") {\n\t\tconst input = rawCtrlInput(base);\n\t\treturn input ? `\\u001b${input}` : undefined;\n\t}\n\treturn undefined;\n}\n\n// Mirror matchesKey(), using parseKey() to canonicalize IDs that share legacy raw input.\nfunction keyInputIdentity(key: string): string {\n\tconst identity = normalizedKeyId(key);\n\tconst input = legacyRawInput(identity);\n\treturn input ? normalizedKeyId(parseKey(input) ?? identity) : identity;\n}\n\nfunction hasManualSelectionCopyApi(): boolean {\n\treturn (\n\t\ttypeof TuiAltScreen.prototype.hasActiveSelection === \"function\" &&\n\t\ttypeof TuiAltScreen.prototype.copyActiveSelectionToClipboard === \"function\"\n\t);\n}\n\nfunction createBtwFullscreenTui(\n\tparent: TUI,\n\ttheme: Theme,\n\tkeybindings: KeybindingsManager,\n\tcopyOnSelect: boolean,\n\tmanualSelectionCopySupported: boolean,\n\topenUrl: (url: string) => void,\n\tcopyToClipboard: (text: string) => Promise<void>,\n): BtwFullscreenTui {\n\tif (!copyOnSelect && !manualSelectionCopySupported) {\n\t\tthrow new Error(\n\t\t\t\"Manual fullscreen selection copying is unavailable in this Pi version; update Pi or enable automatic selection copying.\",\n\t\t);\n\t}\n\tconst styleSearchMatch = (text: string) =>\n\t\ttheme.bg(\"searchMatchBg\", theme.fg(\"searchMatchText\", text));\n\tconst fullscreen = new BtwTuiAltScreen(\n\t\tparent.terminal,\n\t\tparent.getShowHardwareCursor(),\n\t\tundefined,\n\t\t{\n\t\t\tmouse: true,\n\t\t\tcopyOnSelect,\n\t\t\tsearchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),\n\t\t\tscrollToEndIndicator: () => {\n\t\t\t\tconst unavailableKeyIdentities = new Set<string>([keyInputIdentity(Key.ctrl(\"c\"))]);\n\t\t\t\tfor (const action of ALT_SCREEN_ACTIONS_BEFORE_BOTTOM) {\n\t\t\t\t\tfor (const actionKey of keybindings.getKeys(action)) {\n\t\t\t\t\t\tunavailableKeyIdentities.add(keyInputIdentity(String(actionKey)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!copyOnSelect) {\n\t\t\t\t\tfor (const copyKey of keybindings.getKeys(\"app.message.copy\")) {\n\t\t\t\t\t\tunavailableKeyIdentities.add(keyInputIdentity(String(copyKey)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst key = keybindings\n\t\t\t\t\t.getKeys(\"tui.altScreen.bottom\")\n\t\t\t\t\t.map((candidate) => keyInputIdentity(String(candidate)))\n\t\t\t\t\t.find(\n\t\t\t\t\t\t(identity) =>\n\t\t\t\t\t\t\tidentity &&\n\t\t\t\t\t\t\tcanMatchKeyInput(identity) &&\n\t\t\t\t\t\t\t!unavailableKeyIdentities.has(identity) &&\n\t\t\t\t\t\t\tformatEffectiveKeyLabel(identity),\n\t\t\t\t\t);\n\t\t\t\tconst label = theme.fg(\"text\", \" \u2193 Jump to latest message\");\n\t\t\t\tconst shortcut = key ? theme.fg(\"muted\", ` \u00B7 ${formatEffectiveKeyLabel(key)}`) : \"\";\n\t\t\t\treturn theme.bg(\"selectedBg\", `${label}${shortcut} `);\n\t\t\t},\n\t\t\tsearchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),\n\t\t\topenUrl,\n\t\t\tcopySelection: async (text) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait copyToClipboard(text);\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t);\n\tif (!copyOnSelect) {\n\t\tlet isInBracketedPaste = false;\n\t\tfullscreen.addInputListenerBeforeViewport((data) => {\n\t\t\tconst wasInBracketedPaste = isInBracketedPaste;\n\t\t\tconst startsBracketedPaste = data.includes(BRACKETED_PASTE_START);\n\t\t\tif (startsBracketedPaste) isInBracketedPaste = true;\n\t\t\tif (isInBracketedPaste && data.includes(BRACKETED_PASTE_END)) {\n\t\t\t\tisInBracketedPaste = false;\n\t\t\t}\n\t\t\tif (\n\t\t\t\twasInBracketedPaste ||\n\t\t\t\tstartsBracketedPaste ||\n\t\t\t\tfullscreen.hasFocusedOverlay() ||\n\t\t\t\tisKeyRelease(data) ||\n\t\t\t\t!keybindings.matches(data, \"app.message.copy\")\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (!fullscreen.hasActiveSelection()) {\n\t\t\t\tfullscreen.flash(\"No selection to copy\");\n\t\t\t\treturn { consume: true };\n\t\t\t}\n\t\t\tvoid fullscreen.copyActiveSelectionToClipboard().catch(() => fullscreen.flash(\"Copy failed\"));\n\t\t\treturn { consume: true };\n\t\t});\n\t}\n\treturn fullscreen;\n}\n\n// Pi does not export its browser opener, so mirror its shell-free launcher for this isolated TUI.\nfunction openUrlInBrowser(target: string): void {\n\tconst [command, args] =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"open\", [target]]\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? [\"rundll32\", [\"url.dll,FileProtocolHandler\", target]]\n\t\t\t\t: [\"xdg-open\", [target]];\n\tspawn(command, args, { stdio: \"ignore\", detached: true })\n\t\t.on(\"error\", () => {})\n\t\t.unref();\n}\n\nclass BtwFullscreenHost<T> implements Component {\n\tprivate fullscreen: BtwFullscreenTui | undefined;\n\tprivate parentOverlay: OverlayHandle | undefined;\n\tprivate cancelActiveCustom: (() => void) | undefined;\n\tprivate hardCancelActiveCustom: (() => void) | undefined;\n\tprivate removeHardCancelListener: (() => void) | undefined;\n\tprivate started = false;\n\tprivate disposed = false;\n\tprivate finished = false;\n\tprivate parentStopped = false;\n\tprivate parentRestoreAttempted = false;\n\tprivate fullscreenCreated = false;\n\tprivate fullscreenStopped = false;\n\tprivate parentRestoreQueued = false;\n\tprivate parentRestorePromise: Promise<void> | undefined;\n\tprivate cleanupError: unknown;\n\n\tconstructor(\n\t\tprivate readonly parent: TUI,\n\t\tprivate readonly theme: Theme,\n\t\tprivate readonly keybindings: KeybindingsManager,\n\t\tprivate readonly ctx: ExtensionCommandContext,\n\t\tprivate readonly run: (ctx: ExtensionCommandContext) => Promise<T>,\n\t\tprivate readonly done: (outcome: FullscreenOutcome<T>) => void,\n\t\tprivate readonly createTui: BtwFullscreenTuiFactory,\n\t\tprivate readonly options: BtwFullscreenOptions,\n\t) {\n\t\tqueueMicrotask(() => void this.start());\n\t}\n\n\tsetParentOverlay(overlay: OverlayHandle): void {\n\t\tthis.parentOverlay = overlay;\n\t}\n\n\trender(width: number): string[] {\n\t\treturn [truncateToWidth(this.theme.fg(\"muted\", \"Opening btw side thread\u2026\"), width)];\n\t}\n\n\tinvalidate(): void {}\n\n\tdispose(): void {\n\t\tif (this.disposed || this.finished) return;\n\t\tthis.disposed = true;\n\t\tthis.cancelActiveCustom?.();\n\t}\n\n\tprivate async start(): Promise<void> {\n\t\tif (this.started || this.finished) return;\n\t\tthis.started = true;\n\t\tlet outcome: FullscreenOutcome<T>;\n\t\ttry {\n\t\t\tif (this.disposed) throw new FullscreenUiDisposedError();\n\t\t\tthis.parent.stop({ preserveScreen: true });\n\t\t\tthis.parentStopped = true;\n\t\t\tif (this.disposed) throw new FullscreenUiDisposedError();\n\t\t\tthis.fullscreen = this.createTui(this.parent, this.theme, this.keybindings, this.options);\n\t\t\tthis.fullscreenCreated = true;\n\t\t\tthis.fullscreen.start();\n\t\t\tconst shortcuts = resolveBtwShortcuts(\n\t\t\t\tthis.options.keybindings,\n\t\t\t\tthis.keybindings,\n\t\t\t\tthis.options.copyOnSelect ?? true,\n\t\t\t);\n\t\t\tsetBtwShortcuts(this.fullscreen, shortcuts);\n\t\t\t// Negotiate before warning when possible: the first dispatched user input uses\n\t\t\t// the current mode. Recheck each input, including later mode transitions.\n\t\t\tlet previousWarnings: readonly string[] = [];\n\t\t\tconst reportWarnings = () => {\n\t\t\t\tconst warnings = shortcuts.warnings;\n\t\t\t\tfor (const warning of warnings) {\n\t\t\t\t\tif (previousWarnings.includes(warning)) continue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.ctx.ui.notify(`Pi BTW: ${warning}`, \"warning\");\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* A replaced context must not prevent terminal cleanup. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpreviousWarnings = warnings;\n\t\t\t};\n\t\t\tconst pasteGuard = new BtwPasteGuard();\n\t\t\t// Waiting for the custom promise would leave follow-up keys bound to the side TUI.\n\t\t\tconst addHardCancelListener =\n\t\t\t\tthis.fullscreen.addInputListenerBeforeAll?.bind(this.fullscreen) ??\n\t\t\t\tthis.fullscreen.addInputListenerBeforeViewport?.bind(this.fullscreen) ??\n\t\t\t\tthis.fullscreen.addInputListener.bind(this.fullscreen);\n\t\t\tthis.removeHardCancelListener = addHardCancelListener((data) => {\n\t\t\t\treportWarnings();\n\t\t\t\tif (pasteGuard.consume(data) || !shortcuts.matches(data, \"exit\")) return undefined;\n\t\t\t\tthis.disposed = true;\n\t\t\t\ttry {\n\t\t\t\t\tthis.hardCancelActiveCustom?.();\n\t\t\t\t} finally {\n\t\t\t\t\t// ProcessTerminal.stop() destroys its active input buffer. Keep cancellation\n\t\t\t\t\t// synchronous, then drain input before the physical Windows terminal handoff.\n\t\t\t\t\t// Pi has no public input injection, so do not replay bytes already coalesced\n\t\t\t\t\t// behind the hard-cancel key.\n\t\t\t\t\tthis.queueParentRestore();\n\t\t\t\t}\n\t\t\t\treturn { consume: true };\n\t\t\t});\n\t\t\toutcome = { kind: \"completed\", value: await this.run(this.createContext()) };\n\t\t} catch (error) {\n\t\t\toutcome = { kind: \"failed\", error };\n\t\t}\n\n\t\ttry {\n\t\t\tthis.cancelActiveCustom?.();\n\t\t} catch (error) {\n\t\t\tthis.cleanupError ??= error;\n\t\t}\n\t\tif (this.parentRestorePromise) await this.parentRestorePromise;\n\t\telse this.restoreParent();\n\t\tif (this.cleanupError !== undefined) outcome = { kind: \"failed\", error: this.cleanupError };\n\t\tthis.finished = true;\n\t\tthis.done(outcome);\n\t}\n\n\tprivate queueParentRestore(): void {\n\t\tif (this.parentRestoreQueued || this.parentRestoreAttempted) return;\n\t\tthis.parentRestoreQueued = true;\n\t\tthis.parentRestorePromise = Promise.resolve().then(async () => {\n\t\t\ttry {\n\t\t\t\tawait this.fullscreen?.terminal.drainInput?.();\n\t\t\t} catch (error) {\n\t\t\t\tthis.cleanupError ??= error;\n\t\t\t}\n\t\t\tthis.parentRestoreQueued = false;\n\t\t\tthis.restoreParent();\n\t\t});\n\t}\n\n\tprivate restoreParent(): void {\n\t\tconst removeHardCancelListener = this.removeHardCancelListener;\n\t\tthis.removeHardCancelListener = undefined;\n\t\ttry {\n\t\t\tremoveHardCancelListener?.();\n\t\t} catch (error) {\n\t\t\tthis.cleanupError ??= error;\n\t\t}\n\t\tif (this.fullscreenCreated && !this.fullscreenStopped) {\n\t\t\tthis.fullscreenStopped = true;\n\t\t\ttry {\n\t\t\t\tthis.fullscreen?.stop({ preserveScreen: true });\n\t\t\t} catch (error) {\n\t\t\t\tthis.cleanupError ??= error;\n\t\t\t}\n\t\t}\n\t\tif (!this.parentStopped || this.parentRestoreAttempted) return;\n\t\tconst parentOverlay = this.parentOverlay;\n\t\tthis.parentOverlay = undefined;\n\t\ttry {\n\t\t\tparentOverlay?.setHidden(true);\n\t\t} catch (error) {\n\t\t\tthis.cleanupError ??= error;\n\t\t}\n\t\ttry {\n\t\t\tthis.parentRestoreAttempted = true;\n\t\t\tthis.parent.start();\n\t\t\tthis.parent.renderNow(false);\n\t\t} catch (error) {\n\t\t\tthis.cleanupError ??= error;\n\t\t}\n\t}\n\n\tprivate createContext(): ExtensionCommandContext {\n\t\tconst ui = new Proxy(this.ctx.ui, {\n\t\t\tget: (target, property) => {\n\t\t\t\tif (property === \"custom\") {\n\t\t\t\t\treturn <Value>(factory: BtwCustomFactory<Value>, options?: BtwCustomOptions) =>\n\t\t\t\t\t\tthis.showCustom(factory, options);\n\t\t\t\t}\n\t\t\t\tif (property === \"notify\") {\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmessage: string,\n\t\t\t\t\t\tlevel?: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n\t\t\t\t\t) => {\n\t\t\t\t\t\ttarget.notify(message, level);\n\t\t\t\t\t\tconst display = sanitizeSingleLine(message);\n\t\t\t\t\t\tif (display) this.fullscreen?.flash?.(display);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst value = Reflect.get(target, property, target) as unknown;\n\t\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t\t},\n\t\t});\n\t\treturn new Proxy(this.ctx, {\n\t\t\tget: (target, property) => (property === \"ui\" ? ui : Reflect.get(target, property, target)),\n\t\t});\n\t}\n\n\tprivate showCustom<Value>(\n\t\tfactory: BtwCustomFactory<Value>,\n\t\toptions?: BtwCustomOptions,\n\t): Promise<Value> {\n\t\tconst fullscreen = this.fullscreen;\n\t\tif (!fullscreen || this.disposed || this.finished) {\n\t\t\treturn Promise.reject(new FullscreenUiDisposedError());\n\t\t}\n\t\tif (this.cancelActiveCustom) {\n\t\t\treturn Promise.reject(new Error(\"pi-btw attempted to open overlapping custom UI.\"));\n\t\t}\n\n\t\treturn new Promise<Value>((resolve, reject) => {\n\t\t\tlet component: (Component & { dispose?(): void }) | undefined;\n\t\t\tlet overlay: OverlayHandle | undefined;\n\t\t\tlet mounted = false;\n\t\t\tlet layoutMounted = false;\n\t\t\tlet factorySettled = false;\n\t\t\tlet closed = false;\n\t\t\tlet promiseSettled = false;\n\t\t\tlet componentDisposed = false;\n\t\t\tlet pendingValue: Value | undefined;\n\t\t\tlet hasPendingValue = false;\n\n\t\t\tconst disposeComponent = () => {\n\t\t\t\tif (!component || componentDisposed) return;\n\t\t\t\tcomponentDisposed = true;\n\t\t\t\ttry {\n\t\t\t\t\tcomponent.dispose?.();\n\t\t\t\t} catch {\n\t\t\t\t\t// Cleanup must continue so terminal ownership is restored.\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst unmount = () => {\n\t\t\t\tlet cleanupError: unknown;\n\t\t\t\ttry {\n\t\t\t\t\tif (overlay) overlay.hide();\n\t\t\t\t\telse if (mounted && layoutMounted) fullscreen.setLayoutRoot(undefined);\n\t\t\t\t\telse if (mounted && component) fullscreen.removeChild(component);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcleanupError = error;\n\t\t\t\t}\n\t\t\t\tif (overlay || mounted) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfullscreen.setFocus(null);\n\t\t\t\t\t\tfullscreen.requestRender();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcleanupError ??= error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdisposeComponent();\n\t\t\t\tif (cleanupError !== undefined) throw cleanupError;\n\t\t\t};\n\t\t\tconst complete = () => {\n\t\t\t\tif (promiseSettled || !hasPendingValue) return;\n\t\t\t\tpromiseSettled = true;\n\t\t\t\tthis.cancelActiveCustom = undefined;\n\t\t\t\tthis.hardCancelActiveCustom = undefined;\n\t\t\t\tif (!factorySettled) {\n\t\t\t\t\tresolve(pendingValue as Value);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tunmount();\n\t\t\t\t\tresolve(pendingValue as Value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst close = (value: Value) => {\n\t\t\t\tif (closed || promiseSettled) return;\n\t\t\t\tclosed = true;\n\t\t\t\tpendingValue = value;\n\t\t\t\thasPendingValue = true;\n\t\t\t\tcomplete();\n\t\t\t};\n\t\t\tconst fail = (error: unknown) => {\n\t\t\t\tif (promiseSettled) return;\n\t\t\t\tclosed = true;\n\t\t\t\tpromiseSettled = true;\n\t\t\t\tthis.cancelActiveCustom = undefined;\n\t\t\t\tthis.hardCancelActiveCustom = undefined;\n\t\t\t\ttry {\n\t\t\t\t\tunmount();\n\t\t\t\t\treject(error);\n\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\treject(cleanupError);\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.cancelActiveCustom = () => {\n\t\t\t\tif (promiseSettled) return;\n\t\t\t\tdisposeComponent();\n\t\t\t\tif (!promiseSettled) fail(new FullscreenUiDisposedError());\n\t\t\t};\n\t\t\tthis.hardCancelActiveCustom = () => {\n\t\t\t\tif (promiseSettled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcomponent?.handleInput?.(\"\\u0003\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfail(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.cancelActiveCustom?.();\n\t\t\t};\n\n\t\t\tlet created: ReturnType<BtwCustomFactory<Value>>;\n\t\t\ttry {\n\t\t\t\tcreated = factory(fullscreen, this.theme, this.keybindings, close);\n\t\t\t} catch (error) {\n\t\t\t\tfactorySettled = true;\n\t\t\t\tfail(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tPromise.resolve(created)\n\t\t\t\t.then((value) => {\n\t\t\t\t\tcomponent = value;\n\t\t\t\t\tfactorySettled = true;\n\t\t\t\t\tif (promiseSettled) {\n\t\t\t\t\t\tdisposeComponent();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (closed) {\n\t\t\t\t\t\tcomplete();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (options?.overlay) {\n\t\t\t\t\t\tconst overlayOptions =\n\t\t\t\t\t\t\ttypeof options.overlayOptions === \"function\"\n\t\t\t\t\t\t\t\t? options.overlayOptions()\n\t\t\t\t\t\t\t\t: options.overlayOptions;\n\t\t\t\t\t\toverlay = fullscreen.showOverlay(component, overlayOptions);\n\t\t\t\t\t\toptions.onHandle?.(overlay);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfullscreen.clear();\n\t\t\t\t\t\tmounted = true;\n\t\t\t\t\t\tif (isFullscreenLayoutComponent(component)) {\n\t\t\t\t\t\t\tlayoutMounted = true;\n\t\t\t\t\t\t\tfullscreen.setLayoutRoot(component.getFullscreenLayout());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfullscreen.addChild(component);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfullscreen.setFocus(component);\n\t\t\t\t\t\tfullscreen.requestRender();\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch(fail);\n\t\t});\n\t}\n}\n\nfunction isFullscreenLayoutComponent(\n\tcomponent: Component,\n): component is BtwFullscreenLayoutComponent {\n\treturn \"getFullscreenLayout\" in component && typeof component.getFullscreenLayout === \"function\";\n}\n", "import {\n\tisKeyRelease,\n\tisKittyProtocolActive,\n\tKeybindingsManager,\n\ttype KeyId,\n\tmatchesKey,\n\ttype TUI,\n\tTUI_KEYBINDINGS,\n} from \"@earendil-works/pi-tui\";\nimport { formatKeyLabel } from \"./text.js\";\n\nexport const BTW_SHORTCUT_ACTIONS = [\"exit\", \"cycleThinkingLevel\", \"bringToMain\"] as const;\nexport type BtwShortcutAction = (typeof BTW_SHORTCUT_ACTIONS)[number];\nexport type BtwKeybindingOverrides = Partial<Record<BtwShortcutAction, string>>;\n\nconst MODIFIERS = [\"shift\", \"alt\", \"ctrl\", \"super\"] as const;\nconst SYMBOLS = \"`-=[]\\\\;',./!@#$%^&*()_|~{}:<>?\";\nconst SPECIAL: Record<string, number> = {\n\tescape: 27,\n\ttab: 9,\n\tenter: 13,\n\tspace: 32,\n\tbackspace: 127,\n\tinsert: 57425,\n\tdelete: 57426,\n\thome: 57423,\n\tend: 57424,\n\tpageup: 57421,\n\tpagedown: 57422,\n\tleft: 57417,\n\tright: 57418,\n\tup: 57419,\n\tdown: 57420,\n};\nconst FUNCTION_INPUTS = [\n\t\"OP\",\n\t\"OQ\",\n\t\"OR\",\n\t\"OS\",\n\t\"[15~\",\n\t\"[17~\",\n\t\"[18~\",\n\t\"[19~\",\n\t\"[20~\",\n\t\"[21~\",\n\t\"[23~\",\n\t\"[24~\",\n];\n// All cross-identity legacy collisions in Pi's matchesKey(): raw Ctrl bytes,\n// ESC-prefixed bytes (including Alt+arrows), BS/DEL, Enter and Shift+Tab.\n// CSI-u, keypad, lock bits, shifted letters and modifyOtherKeys normalize to\n// the same key+modifiers; probe that identity instead of duplicating the parser.\nconst LEGACY_INPUTS = [\n\t...Array.from({ length: 128 }, (_, code) => String.fromCharCode(code)),\n\t...Array.from({ length: 128 }, (_, code) => `\\u001b${String.fromCharCode(code)}`),\n\t\"\\u001b[Z\",\n\t\"\\u001bOM\",\n\t\"\\u001b[E\",\n\t\"\\u001b[e\",\n\t\"\\u001bOe\",\n\t...FUNCTION_INPUTS.map((suffix) => `\\u001b${suffix}`),\n];\n\n/** Strict settings syntax; Pi itself ignores unknown/duplicate modifier tokens. */\nexport function normalizeBtwKey(value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || value.length > 80 || /[\\s\\p{Cc}]/u.test(value)) return undefined;\n\tconst parts = value.toLowerCase().split(\"+\");\n\tlet base = parts.pop();\n\tif (!base) return undefined;\n\tif (base === \"esc\") base = \"escape\";\n\tif (base === \"return\") base = \"enter\";\n\tif (\n\t\tnew Set(parts).size !== parts.length ||\n\t\tparts.some((part) => !MODIFIERS.includes(part as never))\n\t)\n\t\treturn undefined;\n\tif (\n\t\t!Object.hasOwn(SPECIAL, base) &&\n\t\tbase !== \"clear\" &&\n\t\t!/^f(?:[1-9]|1[0-2])$/u.test(base) &&\n\t\t!(base.length === 1 && (/^[a-z0-9]$/u.test(base) || SYMBOLS.includes(base)))\n\t)\n\t\treturn undefined;\n\tif ((base === \"escape\" || (base.startsWith(\"f\") && base.length > 1)) && parts.length)\n\t\treturn undefined;\n\tif (\n\t\tbase === \"clear\" &&\n\t\t(parts.length > 1 || (parts.length === 1 && ![\"ctrl\", \"shift\"].includes(parts[0] ?? \"\")))\n\t)\n\t\treturn undefined;\n\treturn [...MODIFIERS.filter((part) => parts.includes(part)), base].join(\"+\");\n}\n\n/** Representative inputs are checked by Pi, including its live terminal-mode branches. */\nfunction inputsFor(key: string): string[] {\n\tconst parts = key.split(\"+\");\n\tconst base = parts.pop() ?? \"\";\n\tconst modifier = MODIFIERS.reduce(\n\t\t(mask, part, bit) => mask | (parts.includes(part) ? 1 << bit : 0),\n\t\t0,\n\t);\n\tconst code = SPECIAL[base] ?? (base.length === 1 ? base.charCodeAt(0) : undefined);\n\tconst inputs =\n\t\tcode === undefined ? LEGACY_INPUTS : [...LEGACY_INPUTS, `\\u001b[${code};${modifier + 1}u`];\n\treturn inputs.filter((input) => matchesKey(input, key as KeyId));\n}\n\nexport function btwKeysOverlap(first: string, second: string): boolean {\n\tconst normalized = normalizeBtwKey(first);\n\treturn (\n\t\tnormalized !== undefined &&\n\t\tinputsFor(normalized).some((input) => matchesKey(input, second as KeyId))\n\t);\n}\n\nexport interface BtwShortcuts {\n\tkeys: Record<BtwShortcutAction, readonly string[]>;\n\twarnings: readonly string[];\n\tmatches(data: string, action: BtwShortcutAction): boolean;\n\tlabel(action: BtwShortcutAction): string;\n}\n\nfunction reservedKeys(keybindings: KeybindingsManager, copyOnSelect: boolean): string[] {\n\t// Editor has no autocomplete provider here. Select bindings are still reserved\n\t// because exit also applies to BTW-owned nested review/menu components.\n\treturn [\n\t\t\"ctrl+c\",\n\t\t\"shift+backspace\",\n\t\t\"shift+delete\",\n\t\t\"shift+space\",\n\t\t// Exact-range review uses these fixed selection actions even if Editor is remapped.\n\t\t\"shift+left\",\n\t\t\"shift+right\",\n\t\t\"shift+up\",\n\t\t\"shift+down\",\n\t\t\"left\",\n\t\t\"right\",\n\t\t\"enter\",\n\t\t\"alt+enter\",\n\t\t\"ctrl+j\",\n\t\t\"pageUp\",\n\t\t\"pageDown\",\n\t\t...Object.keys(TUI_KEYBINDINGS).flatMap((id) =>\n\t\t\tkeybindings.getKeys(id as keyof typeof TUI_KEYBINDINGS),\n\t\t),\n\t\t...(!copyOnSelect ? keybindings.getKeys(\"app.message.copy\") : []),\n\t];\n}\n\nfunction isTextKey(key: string): boolean {\n\tconst parts = key.split(\"+\");\n\tconst base = parts.at(-1) ?? \"\";\n\treturn (\n\t\t(base.length === 1 || base === \"space\") &&\n\t\t!parts.some((part) => [\"ctrl\", \"alt\", \"super\"].includes(part))\n\t);\n}\n\nexport function resolveBtwShortcuts(\n\toverrides: BtwKeybindingOverrides = {},\n\tkeybindings: KeybindingsManager,\n\tcopyOnSelect = true,\n): BtwShortcuts {\n\tlet mode = isKittyProtocolActive();\n\tlet snapshot = resolveShortcutSnapshot(overrides, keybindings, copyOnSelect);\n\tconst current = () => {\n\t\tif (mode !== isKittyProtocolActive()) {\n\t\t\tmode = isKittyProtocolActive();\n\t\t\tsnapshot = resolveShortcutSnapshot(overrides, keybindings, copyOnSelect);\n\t\t}\n\t\treturn snapshot;\n\t};\n\t// ProcessTerminal negotiates Kitty asynchronously after the dedicated TUI starts.\n\t// Hints and matching must use the same policy after that mode transition.\n\treturn {\n\t\tget keys() {\n\t\t\treturn current().keys;\n\t\t},\n\t\tget warnings() {\n\t\t\treturn current().warnings;\n\t\t},\n\t\tmatches: (data, action) => current().matches(data, action),\n\t\tlabel: (action) => current().label(action),\n\t};\n}\n\nfunction resolveShortcutSnapshot(\n\toverrides: BtwKeybindingOverrides = {},\n\tkeybindings: KeybindingsManager,\n\tcopyOnSelect = true,\n): BtwShortcuts {\n\tconst reserved = reservedKeys(keybindings, copyOnSelect);\n\tconst keys: BtwShortcuts[\"keys\"] = { exit: [\"ctrl+c\"], cycleThinkingLevel: [], bringToMain: [] };\n\tconst warnings: string[] = [];\n\tconst defaults: Record<BtwShortcutAction, readonly string[]> = {\n\t\texit: [\"ctrl+c\"],\n\t\tcycleThinkingLevel: keybindings.getKeys(\"app.thinking.cycle\"),\n\t\tbringToMain: [\"ctrl+r\"],\n\t};\n\tconst usable = (\n\t\taction: BtwShortcutAction,\n\t\tcandidate: string,\n\t\tinherited = false,\n\t): string | undefined => {\n\t\tconst key = normalizeBtwKey(candidate);\n\t\tif (!key || (!inherited && isTextKey(key))) return undefined;\n\t\tconst inputs = inputsFor(key);\n\t\tif (!inputs.length) return undefined;\n\t\tif (action === \"exit\" && key === \"ctrl+c\") return key;\n\t\tif (\n\t\t\treserved.some(\n\t\t\t\t(other) =>\n\t\t\t\t\ttypeof other === \"string\" && inputs.some((input) => matchesKey(input, other as KeyId)),\n\t\t\t)\n\t\t)\n\t\t\treturn undefined;\n\t\treturn key;\n\t};\n\tconst candidates: BtwKeybindingOverrides = {};\n\tconst availableDefaults = { ...defaults };\n\tfor (const action of BTW_SHORTCUT_ACTIONS) {\n\t\tavailableDefaults[action] = defaults[action]\n\t\t\t.map((key) => usable(action, key, action === \"cycleThinkingLevel\"))\n\t\t\t.filter((key): key is string => key !== undefined);\n\t\tconst override = overrides[action];\n\t\tif (override !== undefined) candidates[action] = usable(action, override);\n\t}\n\t// Compare the complete proposal, not only actions visited earlier. Reject conflicts\n\t// together, then repeat because a rejected override restores its default bindings.\n\tfor (;;) {\n\t\tconst rejected = BTW_SHORTCUT_ACTIONS.filter((action) => {\n\t\t\tconst candidate = candidates[action];\n\t\t\treturn (\n\t\t\t\tcandidate !== undefined &&\n\t\t\t\tBTW_SHORTCUT_ACTIONS.some(\n\t\t\t\t\t(other) =>\n\t\t\t\t\t\tother !== action &&\n\t\t\t\t\t\t(candidates[other] ? [candidates[other]] : availableDefaults[other]).some((key) =>\n\t\t\t\t\t\t\tbtwKeysOverlap(candidate, key),\n\t\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\t\tif (!rejected.length) break;\n\t\tfor (const action of rejected) delete candidates[action];\n\t}\n\tfor (const action of BTW_SHORTCUT_ACTIONS) {\n\t\tconst override = overrides[action];\n\t\tconst selected = candidates[action];\n\t\tif (override !== undefined && !selected)\n\t\t\twarnings.push(\n\t\t\t\t`${action}: configured shortcut is invalid or conflicts with a reserved action; using an available default.`,\n\t\t\t);\n\t\tconst effective = selected\n\t\t\t? [selected]\n\t\t\t: availableDefaults[action].filter(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\t!BTW_SHORTCUT_ACTIONS.some(\n\t\t\t\t\t\t\t(other) => other !== action && keys[other].some((used) => btwKeysOverlap(key, used)),\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\tkeys[action] = action === \"exit\" ? [...new Set([...effective, \"ctrl+c\"])] : effective;\n\t\tif (!keys[action].length && (override !== undefined || defaults[action].length > 0))\n\t\t\twarnings.push(`${action}: no usable shortcut; change Pi BTW Settings or Pi keybindings.`);\n\t}\n\treturn {\n\t\tkeys,\n\t\twarnings,\n\t\tmatches: (data, action) =>\n\t\t\t!isKeyRelease(data) && keys[action].some((key) => matchesKey(data, key as KeyId)),\n\t\tlabel: (action) =>\n\t\t\tkeys[action].length ? formatKeyLabel(keys[action][0] ?? \"\") : \"Unavailable\",\n\t};\n}\n\nexport function validateBtwShortcutEdit(\n\taction: BtwShortcutAction,\n\tvalue: string | undefined,\n\toverrides: BtwKeybindingOverrides,\n\tkeybindings: KeybindingsManager,\n\tcopyOnSelect: boolean,\n): string | undefined {\n\t// Reset must remain available even when several existing overrides conflict.\n\tif (value === undefined) return undefined;\n\tif (!normalizeBtwKey(value))\n\t\treturn \"Invalid key combination. Use a Pi key name such as ctrl+q or f6.\";\n\tconst next = { ...overrides, [action]: value };\n\tconst resolved = resolveBtwShortcuts(next, keybindings, copyOnSelect);\n\tconst previous = resolveBtwShortcuts(overrides, keybindings, copyOnSelect);\n\t// Reject edits that disable another binding as well as the edited binding.\n\tfor (const item of BTW_SHORTCUT_ACTIONS) {\n\t\tif (\n\t\t\t(item === action && !resolved.keys[item].includes(normalizeBtwKey(value) ?? \"\")) ||\n\t\t\t(item !== action && previous.keys[item].some((key) => !resolved.keys[item].includes(key)))\n\t\t) {\n\t\t\treturn `${item} conflicts with another BTW shortcut, editing, selection, search, scrolling, or copying. Choose a different key.`;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nconst bindingsByTui = new WeakMap<TUI, BtwShortcuts>();\nexport function setBtwShortcuts(tui: TUI, shortcuts: BtwShortcuts): void {\n\tbindingsByTui.set(tui, shortcuts);\n}\nexport function getBtwShortcuts(tui: TUI, keybindings?: KeybindingsManager): BtwShortcuts {\n\treturn (\n\t\tbindingsByTui.get(tui) ??\n\t\tresolveBtwShortcuts(\n\t\t\t{},\n\t\t\tkeybindings ??\n\t\t\t\tnew KeybindingsManager({\n\t\t\t\t\t...TUI_KEYBINDINGS,\n\t\t\t\t\t\"app.thinking.cycle\": { defaultKeys: \"shift+tab\" },\n\t\t\t\t}),\n\t\t)\n\t);\n}\n\n/** Keep split bracketed-paste payloads away from screen-level shortcuts. */\nexport class BtwPasteGuard {\n\tprivate active = false;\n\tconsume(data: string): boolean {\n\t\tconst wasActive = this.active;\n\t\tconst starts = data.includes(\"\\u001b[200~\");\n\t\tif (starts) this.active = true;\n\t\tif (this.active && data.includes(\"\\u001b[201~\")) this.active = false;\n\t\treturn wasActive || starts;\n\t}\n}\n", "export function sanitizeSingleLine(text: string): string {\n\treturn [...text.replace(/[\\r\\n\\t]/gu, \" \")]\n\t\t.filter((character) => {\n\t\t\tconst code = character.charCodeAt(0);\n\t\t\treturn code > 31 && (code < 127 || code > 159);\n\t\t})\n\t\t.join(\"\")\n\t\t.replace(/ +/gu, \" \")\n\t\t.trim();\n}\n\nexport function formatKeyLabel(key: string): string {\n\tconst sanitized = sanitizeSingleLine(key);\n\tif (!sanitized) return \"\";\n\treturn sanitized\n\t\t.split(\"+\")\n\t\t.map((part) => {\n\t\t\tconst lower = part.toLowerCase();\n\t\t\tif (lower === \"shift\") return \"Shift\";\n\t\t\tif (lower === \"ctrl\") return \"Ctrl\";\n\t\t\tif (lower === \"alt\") return \"Alt\";\n\t\t\tif (lower === \"super\") return \"Super\";\n\t\t\treturn part.length === 1\n\t\t\t\t? part.toUpperCase()\n\t\t\t\t: `${part[0]?.toUpperCase() ?? \"\"}${part.slice(1)}`;\n\t\t})\n\t\t.join(\"+\");\n}\n", "import {\n\tcopyToClipboard,\n\ttype ExtensionAPI,\n\ttype ExtensionCommandContext,\n\ttype SessionEntry,\n\ttype SessionTreeNode,\n\tTreeSelectorComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport { type Component, type Focusable, Key, matchesKey } from \"@earendil-works/pi-tui\";\nimport { showBtwCustomPreservingEditor } from \"./menu.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\n\nexport type MainEntryPickResult =\n\t| { kind: \"selected\"; entryId: string }\n\t| { kind: \"back\" }\n\t| { kind: \"closed\" };\n\nexport interface MainThreadTreeSelector extends Component, Focusable {\n\tonCopy?: (text: string | undefined) => void;\n\tsetViewLabel?(entryId: string, label: string | undefined, labelTimestamp?: string): void;\n\tdispose?(): void;\n}\n\nexport interface MainThreadTreeSelectorOptions {\n\ttree: SessionTreeNode[];\n\tcurrentLeafId: string | null;\n\tterminalRows: number;\n\tonSelect: (entryId: string) => void;\n\tonCancel: () => void;\n\tonCopy: (entryId: string | undefined, displayText: string | undefined) => void;\n\tonLabelChange: (entryId: string, label: string | undefined) => void;\n}\n\nexport interface MainThreadTreePickerDependencies {\n\tcreateSelector?: (options: MainThreadTreeSelectorOptions) => MainThreadTreeSelector;\n\tcopyToClipboard?: (text: string, signal: AbortSignal) => Promise<void>;\n}\n\nclass MainThreadTreePickerComponent implements Component, Focusable {\n\tconstructor(\n\t\tprivate readonly selector: MainThreadTreeSelector,\n\t\tprivate readonly onClose: () => void,\n\t) {}\n\n\tget focused(): boolean {\n\t\treturn this.selector.focused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis.selector.focused = value;\n\t}\n\n\tget wantsKeyRelease(): boolean | undefined {\n\t\treturn this.selector.wantsKeyRelease;\n\t}\n\n\trender(width: number): string[] {\n\t\treturn this.selector.render(width);\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (matchesKey(data, Key.ctrl(\"c\"))) {\n\t\t\tthis.onClose();\n\t\t\treturn;\n\t\t}\n\t\tthis.selector.handleInput?.(data);\n\t}\n\n\tinvalidate(): void {\n\t\tthis.selector.invalidate();\n\t}\n\n\tdispose(): void {\n\t\tthis.selector.dispose?.();\n\t\tthis.onClose();\n\t}\n}\n\nexport async function pickMainEntry(\n\tpi: ExtensionAPI,\n\tctx: ExtensionCommandContext,\n\tdependencies: MainThreadTreePickerDependencies = {},\n): Promise<MainEntryPickResult> {\n\tlet rawTree: SessionTreeNode[];\n\tlet currentLeafId: string | null;\n\ttry {\n\t\trawTree = ctx.sessionManager.getTree();\n\t\tcurrentLeafId = ctx.sessionManager.getLeafId();\n\t} catch {\n\t\treturn { kind: \"closed\" };\n\t}\n\n\tif (rawTree.length === 0) {\n\t\tnotifySafely(ctx, \"No main-thread entries are available\", \"warning\");\n\t\treturn { kind: \"back\" };\n\t}\n\n\tconst tree = sanitizeTreeForDisplay(rawTree);\n\tconst rawCopyText = collectRawCopyText(rawTree);\n\tconst savedLabels = collectSavedLabels(rawTree);\n\tconst createSelector = dependencies.createSelector ?? createNativeTreeSelector;\n\tconst copy = dependencies.copyToClipboard ?? copyText;\n\tconst copyControllers = new Set<AbortController>();\n\tconst copyTasks = new Set<Promise<void>>();\n\tconst abortCopies = () => {\n\t\tfor (const controller of copyControllers) {\n\t\t\tcontroller.abort(new Error(\"The main-thread tree picker closed\"));\n\t\t}\n\t};\n\tconst result = await showBtwCustomPreservingEditor<MainEntryPickResult>(\n\t\tctx,\n\t\t(tui, _theme, _keybindings, done) => {\n\t\t\tlet settled = false;\n\t\t\tlet selector: MainThreadTreeSelector | undefined;\n\t\t\tconst finish = (value: MainEntryPickResult) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tabortCopies();\n\t\t\t\tdone(value);\n\t\t\t};\n\t\t\tconst onCopy = (entryId: string | undefined, displayText: string | undefined) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tconst text = entryId ? rawCopyText.get(entryId) : displayText;\n\t\t\t\tif (!text) {\n\t\t\t\t\tnotifySafely(ctx, \"Selected entry has no text to copy\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tcopyControllers.add(controller);\n\t\t\t\tlet operation: Promise<void>;\n\t\t\t\ttry {\n\t\t\t\t\toperation = copy(text, controller.signal);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\toperation = Promise.reject(error);\n\t\t\t\t}\n\t\t\t\tlet task!: Promise<void>;\n\t\t\t\ttask = operation\n\t\t\t\t\t.then(() => {\n\t\t\t\t\t\tif (!settled) notifySafely(ctx, \"Copied selected message\", \"info\");\n\t\t\t\t\t})\n\t\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\t\tif (!settled && !controller.signal.aborted) {\n\t\t\t\t\t\t\tnotifySafely(ctx, `Could not copy selected message: ${formatError(error)}`, \"error\");\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.finally(() => {\n\t\t\t\t\t\tcopyControllers.delete(controller);\n\t\t\t\t\t\tcopyTasks.delete(task);\n\t\t\t\t\t});\n\t\t\t\tcopyTasks.add(task);\n\t\t\t};\n\t\t\tconst restoreLabel = (entryId: string) => {\n\t\t\t\tconst previous = savedLabels.get(entryId);\n\t\t\t\tselector?.setViewLabel?.(entryId, previous?.label, previous?.labelTimestamp);\n\t\t\t\ttui.requestRender();\n\t\t\t};\n\t\t\tconst onLabelChange = (entryId: string, label: string | undefined) => {\n\t\t\t\tif (settled) return;\n\t\t\t\ttry {\n\t\t\t\t\tif (!ctx.sessionManager.getEntry(entryId)) {\n\t\t\t\t\t\trestoreLabel(entryId);\n\t\t\t\t\t\tnotifySafely(ctx, \"The selected main-thread entry is no longer available\", \"warning\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst persistedLabel = label === undefined ? undefined : sanitizeSingleLine(label);\n\t\t\t\t\tpi.setLabel(entryId, persistedLabel);\n\t\t\t\t\tsavedLabels.set(entryId, { label: persistedLabel });\n\t\t\t\t\tselector?.setViewLabel?.(entryId, persistedLabel);\n\t\t\t\t\ttui.requestRender();\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\trestoreLabel(entryId);\n\t\t\t\t\tnotifySafely(ctx, `Could not update tree label: ${formatError(error)}`, \"error\");\n\t\t\t\t}\n\t\t\t};\n\t\t\tselector = createSelector({\n\t\t\t\ttree,\n\t\t\t\tcurrentLeafId,\n\t\t\t\tterminalRows: tui.terminal.rows,\n\t\t\t\tonSelect: (entryId) => finish({ kind: \"selected\", entryId }),\n\t\t\t\tonCancel: () => finish({ kind: \"back\" }),\n\t\t\t\tonCopy,\n\t\t\t\tonLabelChange,\n\t\t\t});\n\t\t\treturn new MainThreadTreePickerComponent(selector, () => finish({ kind: \"closed\" }));\n\t\t},\n\t);\n\tabortCopies();\n\tawait Promise.allSettled([...copyTasks]);\n\n\treturn result ?? { kind: \"closed\" };\n}\n\nfunction createNativeTreeSelector(options: MainThreadTreeSelectorOptions): MainThreadTreeSelector {\n\tconst selector = new TreeSelectorComponent(\n\t\toptions.tree,\n\t\toptions.currentLeafId,\n\t\toptions.terminalRows,\n\t\toptions.onSelect,\n\t\toptions.onCancel,\n\t\toptions.onLabelChange,\n\t);\n\tselector.onCopy = (displayText) =>\n\t\toptions.onCopy(selector.getTreeList().getSelectedNode()?.entry.id, displayText);\n\tconst result = selector as MainThreadTreeSelector;\n\tresult.setViewLabel = (entryId, label, labelTimestamp) =>\n\t\tselector.getTreeList().updateNodeLabel(entryId, label, labelTimestamp);\n\treturn result;\n}\n\nfunction sanitizeTreeForDisplay(tree: readonly SessionTreeNode[]): SessionTreeNode[] {\n\treturn tree.map((node) => {\n\t\tconst result: SessionTreeNode = {\n\t\t\tentry: sanitizeEntryForDisplay(node.entry),\n\t\t\tchildren: sanitizeTreeForDisplay(node.children),\n\t\t};\n\t\tif (node.label !== undefined) result.label = sanitizeSingleLine(node.label);\n\t\tif (node.labelTimestamp !== undefined) {\n\t\t\tresult.labelTimestamp = sanitizeSingleLine(node.labelTimestamp);\n\t\t}\n\t\treturn result;\n\t});\n}\n\nfunction sanitizeEntryForDisplay(entry: SessionEntry): SessionEntry {\n\tswitch (entry.type) {\n\t\tcase \"message\": {\n\t\t\tconst message = { ...entry.message } as Record<string, unknown>;\n\t\t\tif (\"content\" in entry.message)\n\t\t\t\tmessage.content = sanitizeDisplayContent(entry.message.content);\n\t\t\tfor (const key of [\"role\", \"errorMessage\", \"command\", \"toolName\"] as const) {\n\t\t\t\tconst value = message[key];\n\t\t\t\tif (typeof value === \"string\") message[key] = sanitizeSingleLine(value);\n\t\t\t}\n\t\t\treturn { ...entry, message } as unknown as SessionEntry;\n\t\t}\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\t...entry,\n\t\t\t\tcustomType: sanitizeSingleLine(entry.customType),\n\t\t\t\tcontent: sanitizeDisplayContent(entry.content) as typeof entry.content,\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn { ...entry, summary: sanitizeSingleLine(entry.summary) };\n\t\tcase \"branch_summary\":\n\t\t\treturn { ...entry, summary: sanitizeSingleLine(entry.summary) };\n\t\tcase \"model_change\":\n\t\t\treturn {\n\t\t\t\t...entry,\n\t\t\t\tprovider: sanitizeSingleLine(entry.provider),\n\t\t\t\tmodelId: sanitizeSingleLine(entry.modelId),\n\t\t\t};\n\t\tcase \"thinking_level_change\":\n\t\t\treturn { ...entry, thinkingLevel: sanitizeSingleLine(entry.thinkingLevel) };\n\t\tcase \"custom\":\n\t\t\treturn { ...entry, customType: sanitizeSingleLine(entry.customType) };\n\t\tcase \"label\":\n\t\t\treturn {\n\t\t\t\t...entry,\n\t\t\t\tlabel: entry.label === undefined ? undefined : sanitizeSingleLine(entry.label),\n\t\t\t};\n\t\tcase \"session_info\":\n\t\t\treturn {\n\t\t\t\t...entry,\n\t\t\t\tname: entry.name === undefined ? undefined : sanitizeSingleLine(entry.name),\n\t\t\t};\n\t}\n}\n\nfunction sanitizeDisplayContent(content: unknown): unknown {\n\tif (typeof content === \"string\") return sanitizeSingleLine(content);\n\tif (!Array.isArray(content)) return content;\n\treturn content.map((block) => {\n\t\tif (block === null || typeof block !== \"object\" || !(\"type\" in block)) return block;\n\t\tif (block.type === \"text\" && \"text\" in block && typeof block.text === \"string\") {\n\t\t\treturn { ...block, text: sanitizeSingleLine(block.text) };\n\t\t}\n\t\tif (block.type === \"toolCall\") {\n\t\t\tconst copy = { ...block } as Record<string, unknown>;\n\t\t\tif (typeof copy.name === \"string\") copy.name = sanitizeSingleLine(copy.name);\n\t\t\tcopy.arguments = sanitizeToolArguments(copy.arguments, new WeakMap());\n\t\t\treturn copy;\n\t\t}\n\t\treturn block;\n\t});\n}\n\nfunction sanitizeToolArguments(value: unknown, seen: WeakMap<object, unknown>): unknown {\n\tif (typeof value === \"string\") return sanitizeSingleLine(value);\n\tif (value === null || typeof value !== \"object\") return value;\n\tconst existing = seen.get(value);\n\tif (existing !== undefined) return existing;\n\tif (Array.isArray(value)) {\n\t\tconst result: unknown[] = [];\n\t\tseen.set(value, result);\n\t\tfor (const item of value) result.push(sanitizeToolArguments(item, seen));\n\t\treturn result;\n\t}\n\tconst result: Record<string, unknown> = {};\n\tseen.set(value, result);\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tresult[key] = sanitizeToolArguments(item, seen);\n\t}\n\treturn result;\n}\n\nfunction collectRawCopyText(tree: readonly SessionTreeNode[]): Map<string, string> {\n\tconst result = new Map<string, string>();\n\tconst visit = (nodes: readonly SessionTreeNode[]) => {\n\t\tfor (const node of nodes) {\n\t\t\tconst text = getRawCopyText(node.entry);\n\t\t\tif (text !== undefined) result.set(node.entry.id, text);\n\t\t\tvisit(node.children);\n\t\t}\n\t};\n\tvisit(tree);\n\treturn result;\n}\n\nfunction getRawCopyText(entry: SessionEntry): string | undefined {\n\tlet text: string | undefined;\n\tif (entry.type === \"message\") {\n\t\tif (entry.message.role === \"bashExecution\") text = entry.message.command;\n\t\telse if (\"content\" in entry.message) {\n\t\t\ttext = extractRawText(entry.message.content);\n\t\t\tif (!text && entry.message.role === \"assistant\") text = entry.message.errorMessage;\n\t\t}\n\t} else if (entry.type === \"custom_message\") text = extractRawText(entry.content);\n\telse if (entry.type === \"compaction\" || entry.type === \"branch_summary\") text = entry.summary;\n\treturn text?.trim() ? text : undefined;\n}\n\nfunction extractRawText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.filter(\n\t\t\t(block): block is { type: \"text\"; text: string } =>\n\t\t\t\tblock !== null &&\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\",\n\t\t)\n\t\t.map((block) => block.text)\n\t\t.join(\"\");\n}\n\ninterface SavedLabel {\n\tlabel: string | undefined;\n\tlabelTimestamp?: string;\n}\n\nfunction collectSavedLabels(tree: readonly SessionTreeNode[]): Map<string, SavedLabel> {\n\tconst result = new Map<string, SavedLabel>();\n\tconst visit = (nodes: readonly SessionTreeNode[]) => {\n\t\tfor (const node of nodes) {\n\t\t\tresult.set(node.entry.id, {\n\t\t\t\tlabel: node.label === undefined ? undefined : sanitizeSingleLine(node.label),\n\t\t\t\tlabelTimestamp:\n\t\t\t\t\tnode.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp),\n\t\t\t});\n\t\t\tvisit(node.children);\n\t\t}\n\t};\n\tvisit(tree);\n\treturn result;\n}\n\nasync function copyText(text: string, signal: AbortSignal): Promise<void> {\n\tsignal.throwIfAborted();\n\tawait copyToClipboard(text);\n\tsignal.throwIfAborted();\n}\n\nfunction notifySafely(\n\tctx: ExtensionCommandContext,\n\tmessage: string,\n\tlevel: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n\ttry {\n\t\tctx.ui.notify(sanitizeSingleLine(message), level);\n\t} catch {\n\t\t// The command context may have been replaced while the selector was open.\n\t}\n}\n\nfunction formatError(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { mkdir, open, rename, rm, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport {\n\tBTW_SHORTCUT_ACTIONS,\n\ttype BtwKeybindingOverrides,\n\tnormalizeBtwKey,\n} from \"./keybindings.js\";\nimport { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\n\nexport const BTW_SETTINGS_FILE = \"pi-btw.json\";\nexport const DEFAULT_FULLSCREEN_COPY_ON_SELECT = true;\nexport const DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES = true;\nconst MAX_SETTINGS_BYTES = 64 * 1024;\n\nexport interface BtwSettings {\n\tkeybindings?: BtwKeybindingOverrides;\n\tmodel?: string;\n\tthinkingLevel?: BtwThinkingLevel;\n\trememberThinkingLevelChanges?: boolean;\n\tfullscreenCopyOnSelect?: boolean;\n}\n\nexport type BtwSettingsLoadResult =\n\t| { kind: \"missing\" }\n\t| { kind: \"invalid\"; reason: string }\n\t| { kind: \"loaded\"; settings: BtwSettings };\n\nexport interface BtwSettingsPatch {\n\tkeybindings?: BtwKeybindingOverrides;\n\tthinkingLevel?: BtwThinkingLevel;\n\trememberThinkingLevelChanges?: boolean;\n\tfullscreenCopyOnSelect?: boolean;\n}\n\nexport interface UpdateBtwSettingsOptions {\n\t/** Validate against the latest document inside the mutation queue, before applying the patch. */\n\tvalidateCurrent?: (settings: BtwSettings) => void;\n\tsettingsPath?: string;\n\tsignal?: AbortSignal;\n\tbeforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;\n}\n\ntype SettingsDocument = Record<string, unknown>;\n\nconst mutationQueues = new Map<string, Promise<void>>();\n\nexport function btwSettingsPath(): string {\n\treturn join(getAgentDir(), BTW_SETTINGS_FILE);\n}\n\nexport function normalizeBtwSettings(value: unknown): BtwSettings | undefined {\n\tif (!isSettingsDocument(value)) return undefined;\n\n\tconst settings: BtwSettings = {};\n\tif (Object.hasOwn(value, \"keybindings\")) {\n\t\tconst keys = value.keybindings;\n\t\tif (!isSettingsDocument(keys)) return undefined;\n\t\tsettings.keybindings = {};\n\t\tfor (const action of BTW_SHORTCUT_ACTIONS) {\n\t\t\tif (!Object.hasOwn(keys, action)) continue;\n\t\t\tconst key = normalizeBtwKey(keys[action]);\n\t\t\tif (!key) return undefined;\n\t\t\tsettings.keybindings[action] = key;\n\t\t}\n\t}\n\tif (Object.hasOwn(value, \"model\")) {\n\t\tconst model = Reflect.get(value, \"model\");\n\t\tif (typeof model !== \"string\" || !parseBtwModelReference(model)) return undefined;\n\t\tsettings.model = model;\n\t}\n\tif (Object.hasOwn(value, \"thinkingLevel\")) {\n\t\tconst thinkingLevel = Reflect.get(value, \"thinkingLevel\");\n\t\tif (!isBtwThinkingLevel(thinkingLevel)) return undefined;\n\t\tsettings.thinkingLevel = thinkingLevel;\n\t}\n\tif (Object.hasOwn(value, \"rememberThinkingLevelChanges\")) {\n\t\tconst remember = Reflect.get(value, \"rememberThinkingLevelChanges\");\n\t\tif (typeof remember !== \"boolean\") return undefined;\n\t\tsettings.rememberThinkingLevelChanges = remember;\n\t}\n\tif (Object.hasOwn(value, \"fullscreenCopyOnSelect\")) {\n\t\tconst copyOnSelect = Reflect.get(value, \"fullscreenCopyOnSelect\");\n\t\tif (typeof copyOnSelect !== \"boolean\") return undefined;\n\t\tsettings.fullscreenCopyOnSelect = copyOnSelect;\n\t}\n\treturn settings;\n}\n\nexport function parseBtwModelReference(\n\treference: string,\n): { provider: string; modelId: string } | undefined {\n\tif (/[\\s\\p{Cc}]/u.test(reference)) return undefined;\n\tconst separator = reference.indexOf(\"/\");\n\tif (separator <= 0 || separator === reference.length - 1) return undefined;\n\treturn { provider: reference.slice(0, separator), modelId: reference.slice(separator + 1) };\n}\n\nexport function effectiveFullscreenCopyOnSelect(settings: BtwSettings): boolean {\n\treturn settings.fullscreenCopyOnSelect ?? DEFAULT_FULLSCREEN_COPY_ON_SELECT;\n}\n\nexport function effectiveRememberThinkingLevelChanges(settings: BtwSettings): boolean {\n\treturn settings.rememberThinkingLevelChanges ?? DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES;\n}\n\nexport async function readBtwSettings(\n\tsettingsPath = btwSettingsPath(),\n): Promise<BtwSettingsLoadResult> {\n\tawait awaitBtwSettingsWrites(settingsPath);\n\treturn readBtwSettingsUncoordinated(settingsPath);\n}\n\nexport function updateBtwSettings(\n\tpatch: BtwSettingsPatch,\n\toptions: UpdateBtwSettingsOptions = {},\n): Promise<BtwSettings> {\n\tconst settingsPath = options.settingsPath ?? btwSettingsPath();\n\treturn enqueueMutation(settingsPath, async () => {\n\t\toptions.signal?.throwIfAborted();\n\t\tconst current = await readSettingsDocumentForUpdate(settingsPath);\n\t\toptions.signal?.throwIfAborted();\n\t\toptions.validateCurrent?.(normalizeBtwSettings(current) ?? {});\n\t\tconst updated = applyBtwSettingsPatch(current, patch);\n\t\tconst settings = normalizeBtwSettings(updated);\n\t\tif (!settings) throw invalidSettingsError(settingsPath, \"invalid settings shape\");\n\t\tawait publishSettings(settingsPath, updated, options.signal, options.beforeRename);\n\t\treturn settings;\n\t});\n}\n\nexport async function awaitBtwSettingsWrites(settingsPath = btwSettingsPath()): Promise<void> {\n\tawait mutationQueues.get(settingsPath);\n}\n\nfunction enqueueMutation<T>(settingsPath: string, mutation: () => Promise<T>): Promise<T> {\n\tconst previous = mutationQueues.get(settingsPath) ?? Promise.resolve();\n\tconst result = previous.then(mutation, mutation);\n\tconst settled = result.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\tmutationQueues.set(settingsPath, settled);\n\tvoid settled.finally(() => {\n\t\tif (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);\n\t});\n\treturn result;\n}\n\nasync function readBtwSettingsUncoordinated(settingsPath: string): Promise<BtwSettingsLoadResult> {\n\tlet contents: string;\n\ttry {\n\t\tcontents = await readSettingsContents(settingsPath);\n\t} catch (error: unknown) {\n\t\tif (isNodeError(error) && error.code === \"ENOENT\") return { kind: \"missing\" };\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n\t}\n\n\ttry {\n\t\tconst settings = normalizeBtwSettings(JSON.parse(contents) as unknown);\n\t\treturn settings\n\t\t\t? { kind: \"loaded\", settings }\n\t\t\t: { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n\t} catch {\n\t\treturn { kind: \"invalid\", reason: `${settingsPath}: invalid JSON` };\n\t}\n}\n\nasync function readSettingsDocumentForUpdate(settingsPath: string): Promise<SettingsDocument> {\n\tlet contents: string;\n\ttry {\n\t\tcontents = await readSettingsContents(settingsPath);\n\t} catch (error: unknown) {\n\t\tif (isNodeError(error) && error.code === \"ENOENT\") return {};\n\t\tthrow invalidSettingsError(settingsPath, formatError(error));\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(contents) as unknown;\n\t} catch {\n\t\tthrow invalidSettingsError(settingsPath, \"invalid JSON\");\n\t}\n\tif (!isSettingsDocument(parsed) || !normalizeBtwSettings(parsed)) {\n\t\tthrow invalidSettingsError(settingsPath, \"invalid settings shape\");\n\t}\n\treturn parsed;\n}\n\nasync function readSettingsContents(settingsPath: string): Promise<string> {\n\tconst flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);\n\tconst handle = await open(settingsPath, flags);\n\ttry {\n\t\tconst descriptorStats = await handle.stat();\n\t\tif (!descriptorStats.isFile()) throw new Error(\"settings path is not a regular file\");\n\t\tif (descriptorStats.size > MAX_SETTINGS_BYTES) {\n\t\t\tthrow new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n\t\t}\n\n\t\tconst buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);\n\t\tlet offset = 0;\n\t\twhile (offset < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);\n\t\t\tif (bytesRead === 0) break;\n\t\t\toffset += bytesRead;\n\t\t}\n\t\tif (offset > MAX_SETTINGS_BYTES) {\n\t\t\tthrow new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n\t\t}\n\t\ttry {\n\t\t\treturn new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n\t\t\t\tbuffer.subarray(0, offset),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow new Error(\"settings file is not valid UTF-8\");\n\t\t}\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\nasync function publishSettings(\n\tsettingsPath: string,\n\tdocument: SettingsDocument,\n\tsignal?: AbortSignal,\n\tbeforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>,\n): Promise<void> {\n\tsignal?.throwIfAborted();\n\tconst contents = `${JSON.stringify(document, null, 2)}\\n`;\n\tif (Buffer.byteLength(contents, \"utf8\") > MAX_SETTINGS_BYTES) {\n\t\tthrow new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);\n\t}\n\tconst directory = dirname(settingsPath);\n\tawait mkdir(directory, { recursive: true });\n\tsignal?.throwIfAborted();\n\tconst temporaryPath = join(\n\t\tdirectory,\n\t\t`.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tawait writeFile(temporaryPath, contents, {\n\t\t\tencoding: \"utf8\",\n\t\t\tflag: \"wx\",\n\t\t\tmode: 0o600,\n\t\t\tsignal,\n\t\t});\n\t\tawait beforeRename?.(temporaryPath, settingsPath);\n\t\tsignal?.throwIfAborted();\n\t\tawait rename(temporaryPath, settingsPath);\n\t} catch (error) {\n\t\tawait rm(temporaryPath, { force: true }).catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\nfunction applyBtwSettingsPatch(\n\tcurrent: SettingsDocument,\n\tpatch: BtwSettingsPatch,\n): SettingsDocument {\n\tconst updated: SettingsDocument = { ...current };\n\tif (patch.keybindings) {\n\t\tconst keys = isSettingsDocument(current.keybindings) ? { ...current.keybindings } : {};\n\t\tfor (const action of BTW_SHORTCUT_ACTIONS) {\n\t\t\tif (!Object.hasOwn(patch.keybindings, action)) continue;\n\t\t\tif (patch.keybindings[action] === undefined) delete keys[action];\n\t\t\telse keys[action] = patch.keybindings[action];\n\t\t}\n\t\tif (Object.keys(keys).length) updated.keybindings = keys;\n\t\telse delete updated.keybindings;\n\t}\n\tif (Object.hasOwn(patch, \"thinkingLevel\")) {\n\t\tif (patch.thinkingLevel === undefined) delete updated.thinkingLevel;\n\t\telse updated.thinkingLevel = patch.thinkingLevel;\n\t}\n\tif (Object.hasOwn(patch, \"rememberThinkingLevelChanges\")) {\n\t\tupdated.rememberThinkingLevelChanges = patch.rememberThinkingLevelChanges;\n\t}\n\tif (Object.hasOwn(patch, \"fullscreenCopyOnSelect\")) {\n\t\tif (patch.fullscreenCopyOnSelect === undefined) delete updated.fullscreenCopyOnSelect;\n\t\telse updated.fullscreenCopyOnSelect = patch.fullscreenCopyOnSelect;\n\t}\n\treturn updated;\n}\n\nfunction isSettingsDocument(value: unknown): value is SettingsDocument {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBtwThinkingLevel(value: unknown): value is BtwThinkingLevel {\n\treturn BTW_THINKING_LEVELS.includes(value as BtwThinkingLevel);\n}\n\nfunction invalidSettingsError(settingsPath: string, reason: string): Error {\n\treturn new Error(`pi-btw settings at ${settingsPath} are invalid: ${reason}`);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n", "import type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tMessage,\n\tModel,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tUserMessage,\n} from \"@earendil-works/pi-ai\";\n\nexport const BTW_THINKING_LEVELS = [\n\t\"off\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n\t\"max\",\n] as const;\n\nexport type BtwThinkingLevel = (typeof BTW_THINKING_LEVELS)[number];\n\nexport interface SideQuestionAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tenv?: Record<string, string>;\n}\n\nexport type CompleteSimpleFunction = <TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => Promise<AssistantMessage>;\n\nexport type SideThreadTurn =\n\t| {\n\t\t\tkind: \"answered\";\n\t\t\tquestion: string;\n\t\t\tanswer: string;\n\t\t\tresponse: AssistantMessage;\n\t }\n\t| {\n\t\t\tkind: \"error\";\n\t\t\tquestion: string;\n\t\t\tanswer: string;\n\t };\n\nexport interface SideThread {\n\tconversationContext: string;\n\tturns: SideThreadTurn[];\n}\n\nexport function createSideThread(conversationContext: string): SideThread {\n\treturn { conversationContext, turns: [] };\n}\n\nexport function buildSideThreadMessages(thread: SideThread, question: string): Message[] {\n\tconst answeredTurns = thread.turns.filter(\n\t\t(turn): turn is Extract<SideThreadTurn, { kind: \"answered\" }> => turn.kind === \"answered\",\n\t);\n\tconst messages: Message[] = [];\n\n\tif (answeredTurns.length === 0) {\n\t\tmessages.push(createUserMessage(buildUserPrompt(question, thread.conversationContext)));\n\t\treturn messages;\n\t}\n\n\tconst [first, ...rest] = answeredTurns;\n\tmessages.push(\n\t\tcreateUserMessage(buildUserPrompt(first.question, thread.conversationContext)),\n\t\tfirst.response,\n\t);\n\tfor (const turn of rest) {\n\t\tmessages.push(createUserMessage(buildFollowUpPrompt(turn.question)), turn.response);\n\t}\n\tmessages.push(createUserMessage(buildFollowUpPrompt(question)));\n\treturn messages;\n}\n\nexport interface CompleteSideThreadTurnOptions {\n\tthread: SideThread;\n\tmodel: Model<Api>;\n\tquestion: string;\n\tthinkingLevel: BtwThinkingLevel;\n\tauth: SideQuestionAuth;\n\tsignal?: AbortSignal;\n\tcompleteSimple: CompleteSimpleFunction;\n\tsessionId?: string;\n}\n\nexport type CompleteSideThreadTurnResult =\n\t| { kind: \"answered\"; response: AssistantMessage; answer: string }\n\t| { kind: \"aborted\" }\n\t| { kind: \"error\"; message: string };\n\nexport async function completeSideThreadTurn({\n\tthread,\n\tmodel,\n\tquestion,\n\tthinkingLevel,\n\tauth,\n\tsignal,\n\tcompleteSimple,\n\tsessionId,\n}: CompleteSideThreadTurnOptions): Promise<CompleteSideThreadTurnResult> {\n\tif (signal?.aborted) return { kind: \"aborted\" };\n\ttry {\n\t\tconst response = await completeSimple(\n\t\t\tmodel,\n\t\t\t{ systemPrompt: SYSTEM_PROMPT, messages: buildSideThreadMessages(thread, question) },\n\t\t\tbuildStreamOptions(auth, { thinkingLevel, signal, model, sessionId }),\n\t\t);\n\t\tif (signal?.aborted || response?.stopReason === \"aborted\") return { kind: \"aborted\" };\n\t\tif (!isAssistantMessage(response)) {\n\t\t\treturn { kind: \"error\", message: \"The side model returned a malformed response.\" };\n\t\t}\n\t\tif (response.stopReason === \"error\") {\n\t\t\treturn {\n\t\t\t\tkind: \"error\",\n\t\t\t\tmessage: response.errorMessage ?? \"The side model returned an error.\",\n\t\t\t};\n\t\t}\n\n\t\tconst answer = extractAssistantText(response) || \"No response received.\";\n\t\tthread.turns.push({ kind: \"answered\", question, answer, response });\n\t\treturn { kind: \"answered\", response, answer };\n\t} catch (error: unknown) {\n\t\tif (signal?.aborted) return { kind: \"aborted\" };\n\t\treturn { kind: \"error\", message: formatError(error) };\n\t}\n}\n\nexport interface CompleteSideQuestionOptions {\n\tmodel: Model<Api>;\n\tquestion: string;\n\tconversationContext: string;\n\tthinkingLevel: BtwThinkingLevel;\n\tauth: SideQuestionAuth;\n\tsignal?: AbortSignal;\n\tcompleteSimple: CompleteSimpleFunction;\n\tsessionId?: string;\n}\n\nexport async function completeSideQuestion({\n\tmodel,\n\tquestion,\n\tconversationContext,\n\tthinkingLevel,\n\tauth,\n\tsignal,\n\tcompleteSimple,\n\tsessionId,\n}: CompleteSideQuestionOptions): Promise<AssistantMessage> {\n\treturn completeSimple(\n\t\tmodel,\n\t\t{\n\t\t\tsystemPrompt: SYSTEM_PROMPT,\n\t\t\tmessages: [createUserMessage(buildUserPrompt(question, conversationContext))],\n\t\t},\n\t\tbuildStreamOptions(auth, { thinkingLevel, signal, model, sessionId }),\n\t);\n}\n\nexport function extractAssistantText(response: AssistantMessage): string {\n\treturn response.content\n\t\t.filter(\n\t\t\t(content): content is { type: \"text\"; text: string } =>\n\t\t\t\tcontent !== null &&\n\t\t\t\ttypeof content === \"object\" &&\n\t\t\t\tcontent.type === \"text\" &&\n\t\t\t\ttypeof content.text === \"string\",\n\t\t)\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n}\n\nfunction isAssistantMessage(value: unknown): value is AssistantMessage {\n\tif (value === null || typeof value !== \"object\") return false;\n\tconst candidate = value as Partial<AssistantMessage>;\n\treturn (\n\t\tcandidate.role === \"assistant\" &&\n\t\tArray.isArray(candidate.content) &&\n\t\ttypeof candidate.stopReason === \"string\"\n\t);\n}\n\nexport function buildUserPrompt(question: string, conversationContext: string): string {\n\treturn [\n\t\t\"Answer this side question without modifying the main conversation.\",\n\t\t\"\",\n\t\t\"<side_question>\",\n\t\tquestion,\n\t\t\"</side_question>\",\n\t\t\"\",\n\t\t\"<conversation_context>\",\n\t\tconversationContext || \"No prior conversation context was available.\",\n\t\t\"</conversation_context>\",\n\t].join(\"\\n\");\n}\n\nexport function buildFollowUpPrompt(question: string): string {\n\treturn [\n\t\t\"Continue the same side conversation.\",\n\t\t\"\",\n\t\t\"<side_question>\",\n\t\tquestion,\n\t\t\"</side_question>\",\n\t].join(\"\\n\");\n}\n\nfunction createUserMessage(text: string): UserMessage {\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [{ type: \"text\", text }],\n\t\ttimestamp: Date.now(),\n\t};\n}\n\n// Minimal session-headers fork of Pi core provider-attribution\n// (pinned to @earendil-works/pi-coding-agent@0.85.0 src/core/provider-attribution.ts:getSessionHeaders).\n// Core does not export this helper and extensions have no SettingsManager, so only session\n// headers are mirrored here. Default attribution headers are intentionally out of scope.\n// Keep semantics bug-compatible with core: case-sensitive Object.assign, explicit auth\n// headers win on exact-case match.\nconst OPENCODE_HOST = \"opencode.ai\";\n\nfunction matchesOpencodeHost(baseUrl: string | undefined): boolean {\n\tif (!baseUrl) return false;\n\ttry {\n\t\treturn new URL(baseUrl).hostname === OPENCODE_HOST;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction getOpencodeSessionHeaders(\n\tmodel: Pick<Model<Api>, \"provider\" | \"baseUrl\">,\n\tsessionId?: string,\n): ProviderHeaders | undefined {\n\tif (!sessionId) return undefined;\n\tif (\n\t\tmodel.provider !== \"opencode\" &&\n\t\tmodel.provider !== \"opencode-go\" &&\n\t\t!matchesOpencodeHost(model.baseUrl)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n}\n\nfunction mergeSessionHeaders(\n\tauthHeaders: ProviderHeaders | undefined,\n\tsessionHeaders: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!sessionHeaders && !authHeaders) return undefined;\n\t// Bug-compatible with core mergeProviderAttributionHeaders: case-sensitive assign.\n\treturn { ...sessionHeaders, ...authHeaders };\n}\n\ninterface BuildSideThreadStreamOptions {\n\tthinkingLevel: BtwThinkingLevel;\n\tsignal?: AbortSignal;\n\tmodel?: Pick<Model<Api>, \"provider\" | \"baseUrl\">;\n\tsessionId?: string;\n}\n\nfunction buildStreamOptions(\n\tauth: SideQuestionAuth,\n\t{ thinkingLevel, signal, model, sessionId }: BuildSideThreadStreamOptions,\n): SimpleStreamOptions {\n\tconst sessionHeaders = model ? getOpencodeSessionHeaders(model, sessionId) : undefined;\n\tconst options: SimpleStreamOptions = {\n\t\tapiKey: auth.apiKey,\n\t\theaders: mergeSessionHeaders(auth.headers, sessionHeaders),\n\t\tenv: auth.env,\n\t\tsignal,\n\t};\n\tif (thinkingLevel !== \"off\") options.reasoning = thinkingLevel;\n\treturn options;\n}\n\nfunction formatError(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nconst SYSTEM_PROMPT = `You answer quick side questions for a coding-agent user.\n\nUse the provided conversation context only as background. Answer the user's side question directly and concisely. Do not claim to have changed files, run tools, or affected the main task. If the context is insufficient, say what is unknown and give the best next step.`;\n", "import type {\n\tExtensionCommandContext,\n\tKeybindingsManager,\n\tTheme,\n} from \"@earendil-works/pi-coding-agent\";\nimport type { Component, TUI } from \"@earendil-works/pi-tui\";\nimport type { MenuContext, RunMenuResult } from \"@narumitw/pi-tui-kit\";\nimport {\n\tBTW_SHORTCUT_ACTIONS,\n\ttype BtwShortcutAction,\n\tnormalizeBtwKey,\n\tresolveBtwShortcuts,\n\tvalidateBtwShortcutEdit,\n} from \"./keybindings.js\";\nimport {\n\ttype BtwSettings,\n\ttype BtwSettingsPatch,\n\tbtwSettingsPath,\n\teffectiveFullscreenCopyOnSelect,\n\teffectiveRememberThinkingLevelChanges,\n\treadBtwSettings,\n\ttype UpdateBtwSettingsOptions,\n\tupdateBtwSettings,\n} from \"./settings.js\";\nimport { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\nimport { formatKeyLabel, sanitizeSingleLine } from \"./text.js\";\n\ninterface BtwMenuState {\n\tkind: \"valid\" | \"invalid\";\n\tsettings: BtwSettings;\n\treason?: string;\n}\n\nexport interface BtwResumeThreadSummary {\n\tid: string;\n\ttitle: string;\n\tquestionCount: number;\n}\n\nexport interface ShowBtwCommandMenuOptions {\n\tcurrentThinkingLevel: BtwThinkingLevel;\n\tavailableThinkingLevels: readonly BtwThinkingLevel[];\n\tresumeThreads?: readonly BtwResumeThreadSummary[];\n\tsettingsPath?: string;\n\treadSettings?: typeof readBtwSettings;\n\tupdateSettings?: (\n\t\tpatch: BtwSettingsPatch,\n\t\toptions: UpdateBtwSettingsOptions,\n\t) => Promise<BtwSettings>;\n}\n\nexport type BtwCommandMenuResult =\n\t| \"start\"\n\t| \"tree\"\n\t| \"closed\"\n\t| { kind: \"resume\"; threadId: string };\n\ntype BtwMenuScreen = \"main\" | \"resume\" | \"settings\" | \"invalid\" | \"shortcut\" | \"shortcut-input\";\ntype BtwMenuAction =\n\t| \"start\"\n\t| \"start-tree\"\n\t| \"resume\"\n\t| \"set-thinking\"\n\t| \"set-remember\"\n\t| \"set-fullscreen-copy\"\n\t| \"edit-shortcut\"\n\t| \"save-shortcut\"\n\t| \"reset-shortcut\";\nconst SAME_AS_MAIN_THREAD = \"Same as main thread\";\ntype BtwCustomOptions = Parameters<ExtensionCommandContext[\"ui\"][\"custom\"]>[1];\n\ntype BtwCustomFactory<T> = (\n\ttui: TUI,\n\ttheme: Theme,\n\tkeybindings: KeybindingsManager,\n\tdone: (result: T) => void,\n) => Component;\n\nexport async function showBtwCommandMenu(\n\tctx: ExtensionCommandContext,\n\toptions: ShowBtwCommandMenuOptions,\n): Promise<BtwCommandMenuResult> {\n\tif (ctx.mode !== \"tui\") return \"closed\";\n\tconst { defineMenu, runMenu } = await import(\"@narumitw/pi-tui-kit\");\n\tif (ctx.signal?.aborted) return \"closed\";\n\tconst settingsPath = options.settingsPath ?? btwSettingsPath();\n\tconst readSettings = options.readSettings ?? readBtwSettings;\n\tconst updateSettings = options.updateSettings ?? updateBtwSettings;\n\tconst levels =\n\t\toptions.availableThinkingLevels.length > 0\n\t\t\t? [...options.availableThinkingLevels]\n\t\t\t: ([\"off\"] satisfies BtwThinkingLevel[]);\n\tconst displaySettingsPath = sanitizeSingleLine(settingsPath);\n\tconst resumeThreads = options.resumeThreads ?? [];\n\tlet startSelected = false;\n\tlet treeSelected = false;\n\tlet resumedThreadId: string | undefined;\n\tlet keybindings: KeybindingsManager | undefined;\n\tlet shortcut: BtwShortcutAction = \"exit\";\n\tconst shortcutLabels: Record<BtwShortcutAction, string> = {\n\t\texit: \"Exit shortcut\",\n\t\tcycleThinkingLevel: \"Cycle thinking level shortcut\",\n\t\tbringToMain: \"Bring to main shortcut\",\n\t};\n\tconst shortcutValue = (settings: BtwSettings, action: BtwShortcutAction): string => {\n\t\tif (!keybindings) return \"Default\";\n\t\tconst effective = resolveBtwShortcuts(\n\t\t\tsettings.keybindings,\n\t\t\tkeybindings,\n\t\t\teffectiveFullscreenCopyOnSelect(settings),\n\t\t);\n\t\tconst configured = settings.keybindings?.[action];\n\t\tif (configured !== undefined && !effective.keys[action].includes(configured)) {\n\t\t\treturn `Fallback (${effective.label(action)}; saved ${formatKeyLabel(configured)})`;\n\t\t}\n\t\tconst source =\n\t\t\tconfigured === undefined\n\t\t\t\t? action === \"cycleThinkingLevel\"\n\t\t\t\t\t? \"Inherit Pi\"\n\t\t\t\t\t: \"Default\"\n\t\t\t\t: \"Custom\";\n\t\treturn `${source} (${effective.label(action)})`;\n\t};\n\tconst saveShortcut = async (\n\t\tstate: BtwMenuState,\n\t\tvalue: string | undefined,\n\t\tsignal: AbortSignal,\n\t) => {\n\t\tif (!keybindings || state.kind !== \"valid\" || signal.aborted)\n\t\t\treturn { kind: \"rejected\" } as const;\n\t\tconst action = shortcut;\n\t\tconst manager = keybindings;\n\t\tconst validate = (settings: BtwSettings) =>\n\t\t\tvalidateBtwShortcutEdit(\n\t\t\t\taction,\n\t\t\t\tvalue,\n\t\t\t\tsettings.keybindings ?? {},\n\t\t\t\tmanager,\n\t\t\t\teffectiveFullscreenCopyOnSelect(settings),\n\t\t\t);\n\t\tconst error = validate(state.settings);\n\t\tif (error) {\n\t\t\tnotifySafely(ctx, error, \"error\");\n\t\t\treturn { kind: \"rejected\" } as const;\n\t\t}\n\t\ttry {\n\t\t\tawait updateSettings(\n\t\t\t\t{ keybindings: { [action]: value === undefined ? undefined : normalizeBtwKey(value) } },\n\t\t\t\t{\n\t\t\t\t\tsettingsPath,\n\t\t\t\t\tsignal,\n\t\t\t\t\tvalidateCurrent: (settings) => {\n\t\t\t\t\t\tconst conflict = validate(settings);\n\t\t\t\t\t\tif (conflict) throw new Error(conflict);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (signal.aborted) return { kind: \"rejected\" } as const;\n\t\t\tnotifySafely(ctx, \"Pi BTW shortcut saved; applies when opening or resuming BTW.\", \"info\");\n\t\t\treturn { kind: \"back\" } as const;\n\t\t} catch (error) {\n\t\t\tif (!signal.aborted) notifySaveFailure(ctx, error);\n\t\t\treturn { kind: \"rejected\" } as const;\n\t\t}\n\t};\n\n\tconst loadState = async (): Promise<BtwMenuState> => {\n\t\tconst loaded = await readSettings(settingsPath);\n\t\tif (loaded.kind === \"invalid\") {\n\t\t\treturn { kind: \"invalid\", settings: {}, reason: loaded.reason };\n\t\t}\n\t\treturn { kind: \"valid\", settings: loaded.kind === \"loaded\" ? loaded.settings : {} };\n\t};\n\tconst currentMainThinkingLevel = clampToAvailableThinkingLevel(\n\t\toptions.currentThinkingLevel,\n\t\tlevels,\n\t);\n\tconst displayThinkingLevel = (settings: BtwSettings): string =>\n\t\tsettings.thinkingLevel === undefined\n\t\t\t? SAME_AS_MAIN_THREAD\n\t\t\t: clampToAvailableThinkingLevel(settings.thinkingLevel, levels);\n\tconst displayThinkingSummary = (settings: BtwSettings): string =>\n\t\tsettings.thinkingLevel === undefined\n\t\t\t? `${SAME_AS_MAIN_THREAD} (currently ${currentMainThinkingLevel})`\n\t\t\t: displayThinkingLevel(settings);\n\tconst displayRememberSummary = (settings: BtwSettings): string => {\n\t\tconst value = effectiveRememberThinkingLevelChanges(settings) ? \"On\" : \"Off\";\n\t\treturn settings.thinkingLevel === undefined ? `${value} (fixed levels only)` : value;\n\t};\n\n\tconst menu = defineMenu<BtwMenuState, BtwMenuScreen, BtwMenuAction, MenuContext>({\n\t\tstart: \"main\",\n\t\tscreens: {\n\t\t\tmain: ({ state }) => ({\n\t\t\t\tkind: \"actions\",\n\t\t\t\ttitle: \"Pi BTW\",\n\t\t\t\tlines: [\n\t\t\t\t\t`Thinking: ${displayThinkingSummary(state.settings)} \u00B7 Remember changes: ${displayRememberSummary(state.settings)}`,\n\t\t\t\t\t`Copy on select: ${effectiveFullscreenCopyOnSelect(state.settings) ? \"On\" : \"Off\"}`,\n\t\t\t\t],\n\t\t\t\titems: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"start\",\n\t\t\t\t\t\tlabel: \"Start side thread\",\n\t\t\t\t\t\tdescription: \"Open an empty side thread\",\n\t\t\t\t\t\taction: \"start\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"start-tree\",\n\t\t\t\t\t\tlabel: \"Start from main thread tree\u2026\",\n\t\t\t\t\t\tdescription: \"Choose context without switching the main branch\",\n\t\t\t\t\t\taction: \"start-tree\",\n\t\t\t\t\t},\n\t\t\t\t\t...(resumeThreads.length > 0\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tid: \"resume\" as const,\n\t\t\t\t\t\t\t\t\tlabel: \"Resume side thread\",\n\t\t\t\t\t\t\t\t\tdescription: \"Continue an in-memory side thread\",\n\t\t\t\t\t\t\t\t\tto: \"resume\" as const,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: []),\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"settings\",\n\t\t\t\t\t\tlabel: \"Settings\",\n\t\t\t\t\t\tdescription: \"Choose thinking, keybindings, and selection copying\",\n\t\t\t\t\t\tto: state.kind === \"invalid\" ? \"invalid\" : \"settings\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\thint: \"close\",\n\t\t\t}),\n\t\t\tresume: () => ({\n\t\t\t\tkind: \"choice\",\n\t\t\t\ttitle: \"Resume BTW side thread\",\n\t\t\t\tenableSearch: true,\n\t\t\t\titems: resumeThreads.map((thread) => ({\n\t\t\t\t\tid: thread.id,\n\t\t\t\t\tlabel: thread.title,\n\t\t\t\t\tdescription: `${thread.questionCount} ${thread.questionCount === 1 ? \"question\" : \"questions\"}`,\n\t\t\t\t})),\n\t\t\t\taction: \"resume\",\n\t\t\t\tviewportSize: 10,\n\t\t\t\thint: \"back\",\n\t\t\t}),\n\t\t\tsettings: ({ state }) => ({\n\t\t\t\tkind: \"settings\",\n\t\t\t\ttitle: \"Pi BTW Settings\",\n\t\t\t\tlines: [`User settings \u00B7 ${displaySettingsPath}`],\n\t\t\t\titems: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"thinkingLevel\",\n\t\t\t\t\t\tlabel: \"Thinking level\",\n\t\t\t\t\t\tdescription: `Set the starting level for future pi-btw side threads. Currently ${currentMainThinkingLevel}.`,\n\t\t\t\t\t\tcurrentValue: displayThinkingLevel(state.settings),\n\t\t\t\t\t\tvalues: [SAME_AS_MAIN_THREAD, ...levels],\n\t\t\t\t\t\taction: \"set-thinking\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"rememberThinkingLevelChanges\",\n\t\t\t\t\t\tlabel: \"Remember thinking level changes\",\n\t\t\t\t\t\tdescription: \"Save shortcut changes for fixed thinking levels to pi-btw.json.\",\n\t\t\t\t\t\tcurrentValue: effectiveRememberThinkingLevelChanges(state.settings) ? \"On\" : \"Off\",\n\t\t\t\t\t\tvalues: [\"On\", \"Off\"],\n\t\t\t\t\t\taction: \"set-remember\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"fullscreenCopyOnSelect\",\n\t\t\t\t\t\tlabel: \"Copy selection automatically\",\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Copy mouse selections immediately instead of with the configured copy key.\",\n\t\t\t\t\t\tcurrentValue: effectiveFullscreenCopyOnSelect(state.settings) ? \"On\" : \"Off\",\n\t\t\t\t\t\tvalues: [\"On\", \"Off\"],\n\t\t\t\t\t\taction: \"set-fullscreen-copy\",\n\t\t\t\t\t},\n\t\t\t\t\t...BTW_SHORTCUT_ACTIONS.map((action) => ({\n\t\t\t\t\t\tid: action,\n\t\t\t\t\t\tlabel: shortcutLabels[action],\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Edit a BTW-only key combination or restore its default. Ctrl+C always hard-cancels.\",\n\t\t\t\t\t\tcurrentValue: shortcutValue(state.settings, action),\n\t\t\t\t\t\taction: \"edit-shortcut\" as const,\n\t\t\t\t\t})),\n\t\t\t\t],\n\t\t\t}),\n\t\t\tshortcut: ({ state }) => ({\n\t\t\t\tkind: \"actions\",\n\t\t\t\ttitle: shortcutLabels[shortcut],\n\t\t\t\tlines: [shortcutValue(state.settings, shortcut), \"Ctrl+C always hard-cancels BTW.\"],\n\t\t\t\titems: [\n\t\t\t\t\t{ id: \"edit\", label: \"Edit key combination\u2026\", to: \"shortcut-input\" },\n\t\t\t\t\t{ id: \"reset\", label: \"Restore default\", action: \"reset-shortcut\" },\n\t\t\t\t],\n\t\t\t\thint: \"back\",\n\t\t\t}),\n\t\t\t\"shortcut-input\": () => ({\n\t\t\t\tkind: \"input\",\n\t\t\t\ttitle: shortcutLabels[shortcut],\n\t\t\t\tlines: [\"Type a key name, not the shortcut itself. For example: ctrl+q or f6.\"],\n\t\t\t\tplaceholder: \"Key combination\",\n\t\t\t\taction: \"save-shortcut\",\n\t\t\t\thint: \"back\",\n\t\t\t}),\n\t\t\tinvalid: ({ state }) => ({\n\t\t\t\tkind: \"detail\",\n\t\t\t\ttitle: \"Pi BTW Settings \u00B7 Read only\",\n\t\t\t\tlines: [\n\t\t\t\t\t`Invalid settings file. Fix ${displaySettingsPath} before saving.`,\n\t\t\t\t\tsanitizeSingleLine(state.reason ?? \"The settings file is invalid.\"),\n\t\t\t\t],\n\t\t\t\thint: \"back\",\n\t\t\t}),\n\t\t},\n\t\tactions: {\n\t\t\t\"edit-shortcut\": ({ itemId }) => {\n\t\t\t\tif (!BTW_SHORTCUT_ACTIONS.includes(itemId as BtwShortcutAction))\n\t\t\t\t\treturn { kind: \"rejected\" };\n\t\t\t\tshortcut = itemId as BtwShortcutAction;\n\t\t\t\treturn { kind: \"to\", screen: \"shortcut\" };\n\t\t\t},\n\t\t\t\"save-shortcut\": ({ state, value, signal }) =>\n\t\t\t\tsaveShortcut(state, value?.trim() ?? \"\", signal),\n\t\t\t\"reset-shortcut\": ({ state, signal }) => saveShortcut(state, undefined, signal),\n\t\t\tstart: async () => {\n\t\t\t\tstartSelected = true;\n\t\t\t\treturn { kind: \"close\" };\n\t\t\t},\n\t\t\t\"start-tree\": async () => {\n\t\t\t\ttreeSelected = true;\n\t\t\t\treturn { kind: \"close\" };\n\t\t\t},\n\t\t\tresume: async ({ itemId }: { itemId: string }) => {\n\t\t\t\tif (!resumeThreads.some((thread) => thread.id === itemId)) {\n\t\t\t\t\treturn { kind: \"rejected\" } as const;\n\t\t\t\t}\n\t\t\t\tresumedThreadId = itemId;\n\t\t\t\treturn { kind: \"close\" } as const;\n\t\t\t},\n\t\t\t\"set-thinking\": async ({ value, signal }) => {\n\t\t\t\tif (!value) return { kind: \"rejected\" };\n\t\t\t\tconst patch =\n\t\t\t\t\tvalue === SAME_AS_MAIN_THREAD\n\t\t\t\t\t\t? ({ thinkingLevel: undefined } satisfies BtwSettingsPatch)\n\t\t\t\t\t\t: levels.includes(value as BtwThinkingLevel)\n\t\t\t\t\t\t\t? ({ thinkingLevel: value as BtwThinkingLevel } satisfies BtwSettingsPatch)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\tif (!patch) return { kind: \"rejected\" };\n\t\t\t\ttry {\n\t\t\t\t\tawait updateSettings(patch, { settingsPath, signal });\n\t\t\t\t\tif (signal.aborted) return { kind: \"rejected\" };\n\t\t\t\t\tnotifySafely(ctx, `Pi BTW thinking level: ${value}.`, \"info\");\n\t\t\t\t\treturn { kind: \"stay\" };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!signal.aborted) notifySaveFailure(ctx, error);\n\t\t\t\t\treturn { kind: \"rejected\" };\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"set-remember\": async ({ value, signal }) => {\n\t\t\t\tif (value !== \"On\" && value !== \"Off\") return { kind: \"rejected\" };\n\t\t\t\ttry {\n\t\t\t\t\tawait updateSettings(\n\t\t\t\t\t\t{ rememberThinkingLevelChanges: value === \"On\" },\n\t\t\t\t\t\t{ settingsPath, signal },\n\t\t\t\t\t);\n\t\t\t\t\tif (signal.aborted) return { kind: \"rejected\" };\n\t\t\t\t\tnotifySafely(ctx, `Remember thinking level changes: ${value}.`, \"info\");\n\t\t\t\t\treturn { kind: \"stay\" };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!signal.aborted) notifySaveFailure(ctx, error);\n\t\t\t\t\treturn { kind: \"rejected\" };\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"set-fullscreen-copy\": async ({ value, signal }) => {\n\t\t\t\tif (value !== \"On\" && value !== \"Off\") return { kind: \"rejected\" };\n\t\t\t\ttry {\n\t\t\t\t\tawait updateSettings(\n\t\t\t\t\t\t{ fullscreenCopyOnSelect: value === \"On\" },\n\t\t\t\t\t\t{ settingsPath, signal },\n\t\t\t\t\t);\n\t\t\t\t\tif (signal.aborted) return { kind: \"rejected\" };\n\t\t\t\t\tnotifySafely(ctx, `Copy selection automatically: ${value}.`, \"info\");\n\t\t\t\t\treturn { kind: \"stay\" };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!signal.aborted) notifySaveFailure(ctx, error);\n\t\t\t\t\treturn { kind: \"rejected\" };\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\n\tconst result = await runBtwMenuPreservingEditor(\n\t\tctx,\n\t\t(menuContext) => runMenu(menuContext, menu, { getState: loadState }),\n\t\t(manager) => {\n\t\t\tkeybindings = manager;\n\t\t},\n\t);\n\tif (result.kind !== \"closed\" || result.reason !== \"close\") return \"closed\";\n\tif (resumedThreadId) return { kind: \"resume\", threadId: resumedThreadId };\n\tif (treeSelected) return \"tree\";\n\treturn startSelected ? \"start\" : \"closed\";\n}\n\nexport async function showBtwCustomPreservingEditor<T>(\n\tctx: ExtensionCommandContext,\n\tfactory: BtwCustomFactory<T>,\n): Promise<T | undefined> {\n\tlet liveEditorText = ctx.ui.getEditorText();\n\tlet completed = false;\n\tconst result = await ctx.ui.custom<T>((tui, theme, keybindings, done) =>\n\t\tfactory(tui, theme, keybindings, (value) => {\n\t\t\ttry {\n\t\t\t\tliveEditorText = ctx.ui.getEditorText();\n\t\t\t} catch {\n\t\t\t\t// Keep completion finite if session replacement invalidates the editor context.\n\t\t\t}\n\t\t\tcompleted = true;\n\t\t\tdone(value);\n\t\t}),\n\t);\n\tif (completed) {\n\t\ttry {\n\t\t\tif (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);\n\t\t} catch {\n\t\t\t// A replaced context owns a different editor and must not receive stale restoration.\n\t\t}\n\t}\n\treturn result;\n}\n\nexport async function runBtwMenuPreservingEditor(\n\tctx: ExtensionCommandContext,\n\trun: (menuContext: MenuContext) => Promise<RunMenuResult>,\n\tonKeybindings?: (keybindings: KeybindingsManager) => void,\n): Promise<RunMenuResult> {\n\tlet liveEditorText = ctx.ui.getEditorText();\n\tlet completed = false;\n\tconst ui = new Proxy(ctx.ui, {\n\t\tget(target, property) {\n\t\t\tif (property === \"custom\") {\n\t\t\t\treturn <Value>(factory: BtwCustomFactory<Value>, customOptions?: BtwCustomOptions) =>\n\t\t\t\t\ttarget.custom<Value>((tui, theme, keybindings, done) => {\n\t\t\t\t\t\tonKeybindings?.(keybindings);\n\t\t\t\t\t\treturn factory(tui, theme, keybindings, (value) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tliveEditorText = target.getEditorText();\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Keep completion finite if session replacement invalidates the editor context.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcompleted = true;\n\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t});\n\t\t\t\t\t}, customOptions);\n\t\t\t}\n\t\t\tconst value = Reflect.get(target, property, target) as unknown;\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t});\n\tconst result = await run({ mode: ctx.mode, hasUI: ctx.hasUI, ui });\n\tif (result.kind !== \"stale\" && completed) {\n\t\ttry {\n\t\t\tif (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);\n\t\t} catch {\n\t\t\t// A replaced context owns a different editor and must not receive stale restoration.\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction clampToAvailableThinkingLevel(\n\trequested: BtwThinkingLevel,\n\tavailable: readonly BtwThinkingLevel[],\n): BtwThinkingLevel {\n\tif (available.includes(requested)) return requested;\n\tconst requestedIndex = BTW_THINKING_LEVELS.indexOf(requested);\n\tfor (let index = requestedIndex; index < BTW_THINKING_LEVELS.length; index += 1) {\n\t\tconst candidate = BTW_THINKING_LEVELS[index];\n\t\tif (candidate && available.includes(candidate)) return candidate;\n\t}\n\tfor (let index = requestedIndex - 1; index >= 0; index -= 1) {\n\t\tconst candidate = BTW_THINKING_LEVELS[index];\n\t\tif (candidate && available.includes(candidate)) return candidate;\n\t}\n\treturn available[0] ?? \"off\";\n}\n\nfunction notifySaveFailure(ctx: ExtensionCommandContext, error: unknown): void {\n\tnotifySafely(\n\t\tctx,\n\t\t`Pi BTW settings were not saved; the previous value remains active: ${formatError(error)}`,\n\t\t\"error\",\n\t);\n}\n\nfunction notifySafely(\n\tctx: ExtensionCommandContext,\n\tmessage: string,\n\tlevel: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n\ttry {\n\t\tctx.ui.notify(sanitizeSingleLine(message), level);\n\t} catch {\n\t\t// A completed save remains valid if its command context was replaced before notification.\n\t}\n}\n\nfunction formatError(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n", "import type { AssistantMessage } from \"@earendil-works/pi-ai\";\nimport {\n\tAssistantMessageComponent,\n\tgetMarkdownTheme,\n\ttype KeybindingsManager,\n\ttype Theme,\n\tUserMessageComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport {\n\ttype Component,\n\tCURSOR_MARKER,\n\tEditor,\n\ttype EditorTheme,\n\ttype Focusable,\n\tKey,\n\tLoader,\n\tMarkdown,\n\tmatchesKey,\n\tScrollView,\n\ttype TUI,\n\ttruncateToWidth,\n\tVStack,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport type { BtwFullscreenLayoutComponent } from \"./fullscreen-ui.js\";\nimport { BtwPasteGuard, type BtwShortcuts, getBtwShortcuts } from \"./keybindings.js\";\nimport type { BtwThinkingLevel, SideThreadTurn } from \"./side-thread.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\n\nconst TRANSCRIPT_CHROME_LINES = 2;\nconst MAX_STEERING_DISPLAY_LINES = 3;\nconst OSC133_MARKERS = [\"\\u001b]133;A\\u0007\", \"\\u001b]133;B\\u0007\", \"\\u001b]133;C\\u0007\"];\n// Pi renders a spacer above the custom component and a two-line built-in footer below it.\nconst RESERVED_APP_LINES = 3;\n\n// A temporary fit after manual scrolling must not silently resume following new output.\nclass PreservingScrollView extends ScrollView {\n\toverride updateLayout(\n\t\tcontentHeight: number,\n\t\tviewportHeight: number,\n\t\trequestRender: () => void,\n\t): void {\n\t\tconst preserveManualPosition = !this.isFollowingEnd;\n\t\tsuper.updateLayout(contentHeight, viewportHeight, requestRender);\n\t\tif (preserveManualPosition && this.isFollowingEnd) {\n\t\t\tthis.scrollTo(this.scrollTop, { disableFollow: true });\n\t\t}\n\t}\n}\n\nexport type TranscriptPagerAction =\n\t| { kind: \"submit\"; question: string }\n\t| { kind: \"bringToMain\"; questionDraft: string }\n\t| { kind: \"close\" };\n\nexport interface BtwThinkingControl {\n\tlevel: BtwThinkingLevel;\n\tlevels: readonly BtwThinkingLevel[];\n\tkeybindings: KeybindingsManager;\n\tonChange: (level: BtwThinkingLevel) => void;\n}\n\nexport interface BtwAnsweringViewOptions {\n\tsteering?: {\n\t\tquestions: readonly string[];\n\t\tonSubmit: (question: string) => void;\n\t\tthinking?: BtwThinkingControl;\n\t};\n}\n\nexport class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusable {\n\tprivate readonly shortcuts: BtwShortcuts;\n\tprivate readonly pasteGuard = new BtwPasteGuard();\n\tprivate readonly transcriptComponents: Component[];\n\tprivate readonly editor: Editor;\n\tprivate readonly canBringToMain: boolean;\n\tprivate readonly scrollView: ScrollView;\n\tprivate readonly layoutRoot: VStack;\n\tprivate lastContentLineCount = 0;\n\tprivate warning: string | undefined;\n\tprivate finished = false;\n\tprivate isFocused = false;\n\tprivate thinkingLevel: BtwThinkingLevel | undefined;\n\n\tconstructor(\n\t\tprivate readonly tui: TUI,\n\t\tprivate readonly theme: Theme,\n\t\tturns: readonly SideThreadTurn[],\n\t\tprivate readonly onAction: (action: TranscriptPagerAction) => void,\n\t\tprivate readonly options: {\n\t\t\tstartAtBottom?: boolean;\n\t\t\tinitialQuestion?: string;\n\t\t\tthinking?: BtwThinkingControl;\n\t\t} = {},\n\t) {\n\t\tthis.shortcuts = getBtwShortcuts(tui, options.thinking?.keybindings);\n\t\tthis.transcriptComponents = buildTranscriptComponents(turns, this.theme);\n\t\tthis.canBringToMain = turns.some((turn) => turn.kind === \"answered\");\n\t\tthis.thinkingLevel = options.thinking?.level;\n\t\tconst editorTheme: EditorTheme = {\n\t\t\tborderColor: (text) => this.theme.fg(\"accent\", text),\n\t\t\tselectList: {\n\t\t\t\tselectedPrefix: (text) => this.theme.fg(\"accent\", text),\n\t\t\t\tselectedText: (text) => this.theme.fg(\"accent\", text),\n\t\t\t\tdescription: (text) => this.theme.fg(\"muted\", text),\n\t\t\t\tscrollInfo: (text) => this.theme.fg(\"dim\", text),\n\t\t\t\tnoMatch: (text) => this.theme.fg(\"warning\", text),\n\t\t\t},\n\t\t};\n\t\tthis.editor = new Editor(this.tui, editorTheme);\n\t\tif (options.initialQuestion) this.editor.setText(options.initialQuestion);\n\t\tthis.editor.onChange = () => {\n\t\t\tthis.warning = undefined;\n\t\t};\n\t\tthis.editor.onSubmit = (text) => {\n\t\t\tconst question = text.trim();\n\t\t\tif (!question) {\n\t\t\t\tthis.warning = \"Question cannot be empty\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.finished = true;\n\t\t\tthis.onAction({ kind: \"submit\", question });\n\t\t};\n\t\tconst transcript = this.createTranscriptComponent();\n\t\tthis.scrollView = new PreservingScrollView(transcript, {\n\t\t\tfollow: options.startAtBottom ? \"end\" : \"none\",\n\t\t\tprimary: true,\n\t\t});\n\t\tthis.layoutRoot = new VStack([\n\t\t\t{ component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },\n\t\t\t{ component: this.scrollView, basis: 0, grow: 1, minSize: 0 },\n\t\t\t{ component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },\n\t\t\t{ component: this.editor, basis: \"auto\", shrink: 1, minSize: 0 },\n\t\t]);\n\t}\n\n\tget focused(): boolean {\n\t\treturn this.isFocused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis.isFocused = value;\n\t\tthis.editor.focused = value;\n\t}\n\n\tgetFullscreenLayout(): Component {\n\t\treturn this.layoutRoot;\n\t}\n\n\trender(width: number): string[] {\n\t\tif (width <= 0) return [];\n\t\tconst safeWidth = Math.max(1, width);\n\t\tconst editorLines = this.editor.render(safeWidth);\n\t\tconst availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);\n\t\tconst viewportHeight = Math.max(\n\t\t\t0,\n\t\t\tavailableRows - editorLines.length - TRANSCRIPT_CHROME_LINES,\n\t\t);\n\t\tconst contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);\n\t\tthis.lastContentLineCount = contentLines.length;\n\t\tthis.scrollView.updateLayout(contentLines.length, viewportHeight, () =>\n\t\t\tthis.tui.requestRender(),\n\t\t);\n\n\t\treturn fitComposerLayout(\n\t\t\trenderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),\n\t\t\tcontentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),\n\t\t\tthis.renderFooter(safeWidth),\n\t\t\teditorLines,\n\t\t\tavailableRows,\n\t\t).map((line) => truncateToWidth(line, safeWidth));\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.finished) return;\n\t\tif (this.pasteGuard.consume(data)) {\n\t\t\tthis.editor.handleInput(data);\n\t\t\tthis.tui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (this.shortcuts.matches(data, \"exit\")) {\n\t\t\tthis.finished = true;\n\t\t\tthis.onAction({ kind: \"close\" });\n\t\t\treturn;\n\t\t}\n\t\tif (this.canBringToMain && this.shortcuts.matches(data, \"bringToMain\")) {\n\t\t\tthis.finished = true;\n\t\t\tthis.onAction({ kind: \"bringToMain\", questionDraft: this.editor.getExpandedText() });\n\t\t\treturn;\n\t\t}\n\t\tconst thinking = this.options.thinking;\n\t\tif (\n\t\t\tthinking &&\n\t\t\tthinking.levels.length > 1 &&\n\t\t\tthis.shortcuts.matches(data, \"cycleThinkingLevel\")\n\t\t) {\n\t\t\tconst currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);\n\t\t\tconst nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];\n\t\t\tif (nextLevel) {\n\t\t\t\tthis.thinkingLevel = nextLevel;\n\t\t\t\tthinking.onChange(nextLevel);\n\t\t\t\tthis.warning = undefined;\n\t\t\t\tthis.tui.requestRender();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.pageUp)) {\n\t\t\tthis.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));\n\t\t\tthis.tui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.pageDown)) {\n\t\t\tthis.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));\n\t\t\tthis.tui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tthis.editor.handleInput(data);\n\t\tif (!this.finished) this.tui.requestRender();\n\t}\n\n\tinvalidate(): void {\n\t\tthis.layoutRoot.invalidate();\n\t}\n\n\tdispose(): void {\n\t\tif (this.finished) return;\n\t\tthis.finished = true;\n\t\tthis.onAction({ kind: \"close\" });\n\t}\n\n\tprivate renderFooter(width: number): string {\n\t\tconst exit = this.shortcuts.label(\"exit\");\n\t\tconst bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;\n\t\tconst bringKey = this.shortcuts.label(\"bringToMain\");\n\t\tif (this.warning) {\n\t\t\tconst warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} exit`;\n\t\t\treturn truncateToWidth(this.theme.fg(\"warning\", warning), width);\n\t\t}\n\t\tconst scrollable = this.getMaxScrollOffset() > 0;\n\t\tconst thinking = this.options.thinking;\n\t\tconst cycleHint =\n\t\t\tthinking &&\n\t\t\tthinking.levels.length > 1 &&\n\t\t\tthis.thinkingLevel &&\n\t\t\tthis.shortcuts.keys.cycleThinkingLevel.length\n\t\t\t\t? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label(\"cycleThinkingLevel\")} cycle`\n\t\t\t\t: \"\";\n\t\tconst base = bring\n\t\t\t? `btw \u2022 Enter send \u2022 ${bringKey} bring to main \u2022 ${exit} exit`\n\t\t\t: `btw \u2022 Enter send \u2022 ${exit} exit`;\n\t\tconst fullBase = `${base}${cycleHint}`;\n\t\tconst fallbackBase = `btw \u2022 Enter \u2022 ${exit}`;\n\t\tconst compactBase = bring ? `btw \u2022 Enter \u2022 ${bringKey} \u2022 ${exit}` : fallbackBase;\n\t\tconst compactWithThinking = `${compactBase}${cycleHint}`;\n\t\tlet hints =\n\t\t\tvisibleWidth(fullBase) <= width\n\t\t\t\t? fullBase\n\t\t\t\t: visibleWidth(compactWithThinking) <= width\n\t\t\t\t\t? compactWithThinking\n\t\t\t\t\t: visibleWidth(compactBase) <= width\n\t\t\t\t\t\t? compactBase\n\t\t\t\t\t\t: fallbackBase;\n\t\tif (scrollable) {\n\t\t\tconst history = ` \u2022 ${this.scrollView.scrollTop > 0 ? \"\u2191 older\" : \"\u2193 newer\"} \u2022 PgUp/PgDn history`;\n\t\t\tconst compactHistory = \" \u2022 PgUp/PgDn\";\n\t\t\tconst compactScrollable = bring\n\t\t\t\t? `Enter \u2022 ${bringKey} \u2022 ${exit} \u2022 PgUp/PgDn`\n\t\t\t\t: `${fallbackBase}${compactHistory}`;\n\t\t\tif (visibleWidth(`${hints}${history}`) <= width) {\n\t\t\t\thints += history;\n\t\t\t} else if (visibleWidth(`${compactBase}${history}`) <= width) {\n\t\t\t\thints = `${compactBase}${history}`;\n\t\t\t} else if (visibleWidth(`${hints}${compactHistory}`) <= width) {\n\t\t\t\thints += compactHistory;\n\t\t\t} else if (visibleWidth(`${compactBase}${compactHistory}`) <= width) {\n\t\t\t\thints = `${compactBase}${compactHistory}`;\n\t\t\t} else if (visibleWidth(compactScrollable) <= width) {\n\t\t\t\thints = compactScrollable;\n\t\t\t}\n\t\t}\n\t\treturn truncateToWidth(this.theme.fg(\"muted\", hints), width);\n\t}\n\n\tprivate createHeaderComponent(): Component {\n\t\treturn {\n\t\t\trender: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],\n\t\t\tinvalidate() {},\n\t\t};\n\t}\n\n\tprivate createTranscriptComponent(): Component {\n\t\treturn {\n\t\t\trender: (width) => {\n\t\t\t\tconst lines = renderTranscriptLines(this.transcriptComponents, width);\n\t\t\t\tthis.lastContentLineCount = lines.length;\n\t\t\t\treturn lines;\n\t\t\t},\n\t\t\tinvalidate: () => {\n\t\t\t\tfor (const component of this.transcriptComponents) component.invalidate();\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate createFooterComponent(): Component {\n\t\treturn {\n\t\t\trender: (width) => [this.renderFooter(width)],\n\t\t\tinvalidate() {},\n\t\t};\n\t}\n\n\tprivate getMaxScrollOffset(): number {\n\t\treturn Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);\n\t}\n}\n\nexport class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable {\n\tprivate readonly shortcuts: BtwShortcuts;\n\tprivate readonly pasteGuard = new BtwPasteGuard();\n\tprivate readonly transcriptComponents: Component[];\n\tprivate readonly loader: Loader;\n\tprivate readonly editor: Editor | undefined;\n\tprivate readonly controller = new AbortController();\n\tprivate readonly scrollView: ScrollView;\n\tprivate readonly layoutRoot: VStack;\n\tprivate lastContentLineCount = 0;\n\tprivate warning: string | undefined;\n\tprivate finished = false;\n\tprivate isFocused = false;\n\tprivate thinkingLevel: BtwThinkingLevel | undefined;\n\n\tconstructor(\n\t\tprivate readonly tui: TUI,\n\t\tprivate readonly theme: Theme,\n\t\tturns: readonly SideThreadTurn[],\n\t\tpendingQuestion: string,\n\t\tprivate readonly onCancel: () => void,\n\t\tthinkingLevel?: BtwThinkingLevel,\n\t\tprivate readonly options: BtwAnsweringViewOptions = {},\n\t) {\n\t\tthis.shortcuts = getBtwShortcuts(tui, options.steering?.thinking?.keybindings);\n\t\tthis.transcriptComponents = buildTranscriptComponents(turns, this.theme, pendingQuestion);\n\t\tthis.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;\n\t\tthis.loader = new Loader(\n\t\t\tthis.tui,\n\t\t\t(text) => this.theme.fg(\"accent\", text),\n\t\t\t(text) => this.theme.fg(\"muted\", text),\n\t\t\t\"Answering\u2026\",\n\t\t);\n\t\tif (options.steering) {\n\t\t\tconst editorTheme: EditorTheme = {\n\t\t\t\tborderColor: (text) => this.theme.fg(\"accent\", text),\n\t\t\t\tselectList: {\n\t\t\t\t\tselectedPrefix: (text) => this.theme.fg(\"accent\", text),\n\t\t\t\t\tselectedText: (text) => this.theme.fg(\"accent\", text),\n\t\t\t\t\tdescription: (text) => this.theme.fg(\"muted\", text),\n\t\t\t\t\tscrollInfo: (text) => this.theme.fg(\"dim\", text),\n\t\t\t\t\tnoMatch: (text) => this.theme.fg(\"warning\", text),\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.editor = new Editor(this.tui, editorTheme);\n\t\t\tthis.editor.onChange = () => {\n\t\t\t\tthis.warning = undefined;\n\t\t\t};\n\t\t\tthis.editor.onSubmit = (text) => {\n\t\t\t\tconst question = text.trim();\n\t\t\t\tif (!question) {\n\t\t\t\t\tthis.warning = \"Question cannot be empty\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\toptions.steering?.onSubmit(question);\n\t\t\t\tthis.warning = undefined;\n\t\t\t};\n\t\t}\n\t\tconst transcript = this.createTranscriptComponent();\n\t\tthis.scrollView = new PreservingScrollView(transcript, { follow: \"end\", primary: true });\n\t\tthis.layoutRoot = new VStack([\n\t\t\t{ component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },\n\t\t\t{ component: this.scrollView, basis: 0, grow: 1, minSize: 0 },\n\t\t\t{\n\t\t\t\tcomponent: this.createSteeringComponent(),\n\t\t\t\tbasis: \"auto\",\n\t\t\t\tshrink: 1,\n\t\t\t\tminSize: 0,\n\t\t\t\tmaxSize: MAX_STEERING_DISPLAY_LINES,\n\t\t\t},\n\t\t\t{ component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },\n\t\t\t...(this.editor\n\t\t\t\t? [{ component: this.editor, basis: \"auto\" as const, shrink: 1, minSize: 0 }]\n\t\t\t\t: []),\n\t\t]);\n\t}\n\n\tget focused(): boolean {\n\t\treturn this.isFocused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis.isFocused = value;\n\t\tif (this.editor) this.editor.focused = value;\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.controller.signal;\n\t}\n\n\tgetFullscreenLayout(): Component {\n\t\treturn this.layoutRoot;\n\t}\n\n\trender(width: number): string[] {\n\t\tif (width <= 0) return [];\n\t\tconst safeWidth = Math.max(1, width);\n\t\tconst availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);\n\t\tconst editorLines = this.editor?.render(safeWidth) ?? [];\n\t\tconst steeringCapacity = Math.max(\n\t\t\t0,\n\t\t\tavailableRows - editorLines.length - TRANSCRIPT_CHROME_LINES,\n\t\t);\n\t\tconst steeringLines = renderSteeringLines(\n\t\t\tthis.options.steering?.questions ?? [],\n\t\t\tsafeWidth,\n\t\t\tthis.theme,\n\t\t\tMath.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity),\n\t\t);\n\t\tconst viewportHeight = Math.max(\n\t\t\t0,\n\t\t\tavailableRows - editorLines.length - TRANSCRIPT_CHROME_LINES - steeringLines.length,\n\t\t);\n\t\tconst contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);\n\t\tthis.lastContentLineCount = contentLines.length;\n\t\tthis.scrollView.updateLayout(contentLines.length, viewportHeight, () =>\n\t\t\tthis.tui.requestRender(),\n\t\t);\n\n\t\treturn fitComposerLayout(\n\t\t\trenderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),\n\t\t\tcontentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),\n\t\t\tthis.renderFooter(safeWidth),\n\t\t\teditorLines,\n\t\t\tavailableRows,\n\t\t\tsteeringLines,\n\t\t).map((line) => truncateToWidth(line, safeWidth));\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.finished) return;\n\t\tif (this.pasteGuard.consume(data)) {\n\t\t\tthis.editor?.handleInput(data);\n\t\t\tthis.tui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (this.shortcuts.matches(data, \"exit\")) {\n\t\t\tthis.finished = true;\n\t\t\tthis.loader.stop();\n\t\t\tthis.controller.abort();\n\t\t\tthis.onCancel();\n\t\t\treturn;\n\t\t}\n\t\tconst thinking = this.options.steering?.thinking;\n\t\tif (\n\t\t\tthinking &&\n\t\t\tthinking.levels.length > 1 &&\n\t\t\tthis.shortcuts.matches(data, \"cycleThinkingLevel\")\n\t\t) {\n\t\t\tconst currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);\n\t\t\tconst nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];\n\t\t\tif (nextLevel) {\n\t\t\t\tthis.thinkingLevel = nextLevel;\n\t\t\t\tthinking.onChange(nextLevel);\n\t\t\t\tthis.warning = undefined;\n\t\t\t\tthis.tui.requestRender();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.pageUp)) {\n\t\t\tthis.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));\n\t\t\tthis.tui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, Key.pageDown)) {\n\t\t\tthis.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));\n\t\t\tthis.tui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tthis.editor?.handleInput(data);\n\t\tthis.tui.requestRender();\n\t}\n\n\tinvalidate(): void {\n\t\tthis.layoutRoot.invalidate();\n\t}\n\n\tfinish(): void {\n\t\tthis.finished = true;\n\t\tthis.loader.stop();\n\t}\n\n\tdispose(): void {\n\t\tif (this.finished) {\n\t\t\tthis.loader.stop();\n\t\t\tthis.controller.abort();\n\t\t\treturn;\n\t\t}\n\t\tthis.finished = true;\n\t\tthis.loader.stop();\n\t\tthis.controller.abort();\n\t\tthis.onCancel();\n\t}\n\n\tprivate renderFooter(width: number): string {\n\t\tconst exit = this.shortcuts.label(\"exit\");\n\t\tif (this.warning) {\n\t\t\tconst warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} cancel`;\n\t\t\treturn truncateToWidth(this.theme.fg(\"warning\", warning), width);\n\t\t}\n\t\tconst baseHint = this.editor ? `Enter steer \u2022 ${exit} cancel` : `${exit} cancel`;\n\t\tconst thinking = this.options.steering?.thinking;\n\t\tconst cycleHint =\n\t\t\tthinking &&\n\t\t\tthinking.levels.length > 1 &&\n\t\t\tthis.thinkingLevel &&\n\t\t\tthis.shortcuts.keys.cycleThinkingLevel.length\n\t\t\t\t? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label(\"cycleThinkingLevel\")} cycle`\n\t\t\t\t: \"\";\n\t\tconst scrollHint = this.getMaxScrollOffset() > 0 ? \" \u2022 PgUp/PgDn history\" : \"\";\n\t\tconst hints = `${baseHint}${cycleHint}${scrollHint}`;\n\t\tconst compactHints = this.editor ? `Enter \u2022 ${exit}` : exit;\n\t\tconst selectedHints = visibleWidth(hints) <= width ? hints : compactHints;\n\t\tconst loaderWidth = Math.max(1, width - visibleWidth(selectedHints) - 3);\n\t\tconst loaderLine = this.loader.render(loaderWidth).at(-1) ?? \"Answering\u2026\";\n\t\treturn truncateToWidth(`${loaderLine} \u2022 ${this.theme.fg(\"muted\", selectedHints)}`, width);\n\t}\n\n\tprivate createHeaderComponent(): Component {\n\t\treturn {\n\t\t\trender: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],\n\t\t\tinvalidate() {},\n\t\t};\n\t}\n\n\tprivate createTranscriptComponent(): Component {\n\t\treturn {\n\t\t\trender: (width) => {\n\t\t\t\tconst lines = renderTranscriptLines(this.transcriptComponents, width);\n\t\t\t\tthis.lastContentLineCount = lines.length;\n\t\t\t\treturn lines;\n\t\t\t},\n\t\t\tinvalidate: () => {\n\t\t\t\tfor (const component of this.transcriptComponents) component.invalidate();\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate createSteeringComponent(): Component {\n\t\treturn {\n\t\t\trender: (width) =>\n\t\t\t\trenderSteeringLines(\n\t\t\t\t\tthis.options.steering?.questions ?? [],\n\t\t\t\t\twidth,\n\t\t\t\t\tthis.theme,\n\t\t\t\t\tMAX_STEERING_DISPLAY_LINES,\n\t\t\t\t),\n\t\t\tinvalidate() {},\n\t\t};\n\t}\n\n\tprivate createFooterComponent(): Component {\n\t\treturn {\n\t\t\trender: (width) => [this.renderFooter(width)],\n\t\t\tinvalidate: () => this.loader.invalidate(),\n\t\t};\n\t}\n\n\tprivate getMaxScrollOffset(): number {\n\t\treturn Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);\n\t}\n}\n\nexport function formatSideTranscript(turns: readonly SideThreadTurn[]): string {\n\treturn turns\n\t\t.map((turn) => {\n\t\t\tconst question = escapeTerminalControls(turn.question);\n\t\t\tconst rawAnswer = escapeTerminalControls(turn.answer);\n\t\t\tconst answer = turn.kind === \"error\" ? `Error: ${rawAnswer}` : rawAnswer;\n\t\t\treturn `${question}\\n\\n${answer}`;\n\t\t})\n\t\t.join(\"\\n\\n\");\n}\n\nfunction buildTranscriptComponents(\n\tturns: readonly SideThreadTurn[],\n\ttheme: Theme,\n\tpendingQuestion?: string,\n): Component[] {\n\tconst components = turns.flatMap((turn): Component[] => {\n\t\tconst question = new UserMessageComponent(\n\t\t\tescapeTerminalControls(turn.question),\n\t\t\tgetMarkdownTheme(),\n\t\t\t1,\n\t\t);\n\t\tif (turn.kind === \"error\") {\n\t\t\tconst error = new Markdown(\n\t\t\t\t`Error: ${escapeTerminalControls(turn.answer)}`,\n\t\t\t\t1,\n\t\t\t\t1,\n\t\t\t\tgetMarkdownTheme(),\n\t\t\t\t{ color: (text) => theme.fg(\"error\", text) },\n\t\t\t);\n\t\t\treturn [question, error];\n\t\t}\n\t\tconst response: AssistantMessage = {\n\t\t\t...turn.response,\n\t\t\tcontent: [{ type: \"text\", text: escapeTerminalControls(turn.answer) }],\n\t\t\tstopReason: \"stop\",\n\t\t\terrorMessage: undefined,\n\t\t};\n\t\treturn [question, new AssistantMessageComponent(response, true, getMarkdownTheme(), \"\", 1)];\n\t});\n\tif (pendingQuestion) {\n\t\tcomponents.push(\n\t\t\tnew UserMessageComponent(escapeTerminalControls(pendingQuestion), getMarkdownTheme(), 1),\n\t\t);\n\t}\n\treturn components;\n}\n\nfunction renderTranscriptLines(components: readonly Component[], width: number): string[] {\n\treturn components\n\t\t.flatMap((component) => component.render(width))\n\t\t.map(stripShellIntegrationMarkers);\n}\n\nfunction renderSideThreadHeader(\n\twidth: number,\n\ttheme: Theme,\n\tthinkingLevel?: BtwThinkingLevel,\n): string {\n\tconst thinking = thinkingLevel ? ` \u00B7 thinking ${thinkingLevel}` : \"\";\n\tconst title = truncateToWidth(`\u2500 btw \u00B7 side thread${thinking} `, width);\n\tconst ruleWidth = Math.max(0, width - visibleWidth(title));\n\treturn theme.fg(\"muted\", `${title}${\"\u2500\".repeat(ruleWidth)}`);\n}\n\nfunction fitComposerLayout(\n\theader: string,\n\tcontentLines: string[],\n\tfooter: string,\n\teditorLines: string[],\n\tavailableRows: number,\n\tstatusLines: string[] = [],\n): string[] {\n\tconst lines = [header, ...contentLines, ...statusLines, footer, ...editorLines];\n\tif (lines.length <= availableRows) return lines;\n\tif (availableRows <= 1) return [header];\n\tconst editorBudget = Math.max(0, availableRows - 2);\n\treturn [header, footer, ...fitEditorLines(editorLines, editorBudget)];\n}\n\nfunction fitEditorLines(editorLines: string[], budget: number): string[] {\n\tif (budget <= 0) return [];\n\tif (editorLines.length <= budget) return editorLines;\n\tconst cursorIndex = editorLines.findIndex((line) => line.includes(CURSOR_MARKER));\n\tif (cursorIndex < 0) return editorLines.slice(-budget);\n\tconst start = Math.min(cursorIndex, editorLines.length - budget);\n\treturn editorLines.slice(start, start + budget);\n}\n\nfunction renderSteeringLines(\n\tquestions: readonly string[],\n\twidth: number,\n\ttheme: Theme,\n\tmaxLines: number,\n): string[] {\n\tif (questions.length === 0 || maxLines <= 0) return [];\n\tconst formatQuestion = (question: string) =>\n\t\tsanitizeSingleLine(question) || \"(non-printing message)\";\n\tif (maxLines === 1 && questions.length > 1) {\n\t\treturn [\n\t\t\ttruncateToWidth(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"dim\",\n\t\t\t\t\t`Steering (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? \"\")}`,\n\t\t\t\t),\n\t\t\t\twidth,\n\t\t\t),\n\t\t];\n\t}\n\tconst hasOverflow = questions.length > maxLines;\n\tconst questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;\n\tconst lines = questions\n\t\t.slice(0, questionLimit)\n\t\t.map((question) =>\n\t\t\ttruncateToWidth(theme.fg(\"dim\", `Steering: ${formatQuestion(question)}`), width),\n\t\t);\n\tif (hasOverflow) {\n\t\tlines.push(\n\t\t\ttruncateToWidth(\n\t\t\t\ttheme.fg(\"dim\", `Steering: \u2026 +${questions.length - questionLimit} more`),\n\t\t\t\twidth,\n\t\t\t),\n\t\t);\n\t}\n\treturn lines;\n}\n\nfunction stripShellIntegrationMarkers(line: string): string {\n\treturn OSC133_MARKERS.reduce((result, marker) => result.replaceAll(marker, \"\"), line);\n}\n\nfunction escapeTerminalControls(text: string): string {\n\treturn [...text]\n\t\t.map((character) => {\n\t\t\tif (character === \"\\n\") return character;\n\t\t\tif (character === \"\\t\") return \" \";\n\t\t\tconst code = character.charCodeAt(0);\n\t\t\tif (code <= 31 || (code >= 127 && code <= 159)) {\n\t\t\t\treturn `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n\t\t\t}\n\t\t\treturn character;\n\t\t})\n\t\t.join(\"\");\n}\n"],
|
|
5
|
-
"mappings": ";;;;AAAA;AAAA,EAEC;AAAA,EACA;AAAA,OAGM;AACP;AAAA,EACC;AAAA,OAGM;;;ACVP;AAAA,EAEC;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OACM;AAGP,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB,IAAI,KAAK,UAAU,QAAW,EAAE,aAAa,WAAW,CAAC;AA0C7E,SAAS,iBACf,OACuD;AACvD,SAAO,MAAM;AAAA,IACZ,CAAC,SAAgE,KAAK,SAAS;AAAA,EAChF;AACD;AAEO,SAAS,8BACf,OACA,OAC0B;AAC1B,QAAM,WAAW,iBAAiB,KAAK;AACvC,QA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M,SAAS,CAAC,GAAG;AAAA,IACtE,WAAW,MAAM,SAAS,gBAAgB,OAAO,MAAM,SAAS,UAAU;AACzE,YAAM,KAAK,oBAAoB,MAAM,IAAI,KAAK,WAAW,MAAM,MAAM,CAAC,EAAE;AAAA,IACzE;AAAA,EACD;AACA,SAAO,MAAM,OAAO,OAAO;AAC5B;AAEA,SAAS,WAAW,OAAgB;AACnC,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI;AACH,WAAO,KAAK,UAAU,KAAK;AAAA,EAC5B,QAAQ;AACP,WAAO,OAAO,KAAK;AAAA,EACpB;AACD;AAEA,SAAS,kBAAkB,MAAc,UAAkB;AAC1D,MAAI,KAAK,UAAU,SAAU,QAAO;AACpC,SAAO,8CAA8C,QAAQ;AAAA,EAAkB,KAAK,MAAM,CAAC,QAAQ,CAAC;AACrG;",
|
|
3
|
+
"sources": ["../src/btw.ts", "../src/bring-to-main.ts", "../src/fullscreen-ui.ts", "../src/keybindings.ts", "../src/text.ts", "../src/main-tree-picker.ts", "../src/settings.ts", "../src/side-thread.ts", "../src/menu.ts", "../src/transcript-markdown.ts", "../src/transcript-pager.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n type Api,\n clampThinkingLevel,\n getSupportedThinkingLevels,\n type Model,\n type ProviderHeaders,\n} from \"@earendil-works/pi-ai\";\nimport { BorderedLoader, type ExtensionAPI, type ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport type { MenuContext, RunMenuResult } from \"@narumitw/pi-tui-kit\";\nimport {\n type BtwBringToMainSegment,\n type BtwBringToMainSummary,\n BtwTextRangeSelector,\n type BtwTextRangeSelectorState,\n buildQuickBringToMainSegments,\n estimateBringToMainTokens,\n formatBtwBringToMain,\n getAnsweredTurns,\n summarizeBringToMain,\n} from \"./bring-to-main.js\";\nimport { type RunBtwFullscreen, runBtwFullscreen } from \"./fullscreen-ui.js\";\nimport { pickMainEntry } from \"./main-tree-picker.js\";\nimport {\n type BtwCommandMenuResult,\n type BtwResumeThreadSummary,\n runBtwMenuPreservingEditor,\n showBtwCommandMenu,\n showBtwCustomPreservingEditor,\n} from \"./menu.js\";\nimport {\n type BtwSettings,\n effectiveFullscreenCopyOnSelect,\n effectiveRememberThinkingLevelChanges,\n parseBtwModelReference,\n readBtwSettings,\n updateBtwSettings,\n} from \"./settings.js\";\nimport {\n BTW_THINKING_LEVELS,\n type BtwThinkingLevel,\n type CompleteSimpleFunction,\n completeSideThreadTurn,\n createSideThread,\n type SideQuestionAuth,\n type SideThread,\n} from \"./side-thread.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\nimport { type BtwMarkdownTransformers, prepareBtwTranscriptMarkdown } from \"./transcript-markdown.js\";\nimport {\n BtwAnsweringView,\n type BtwThinkingControl,\n BtwTranscriptPager,\n type TranscriptPagerAction,\n} from \"./transcript-pager.js\";\n\nexport {\n BTW_SETTINGS_FILE,\n type BtwSettings,\n type BtwSettingsLoadResult,\n normalizeBtwSettings,\n parseBtwModelReference,\n readBtwSettings,\n} from \"./settings.js\";\nexport {\n BTW_THINKING_LEVELS,\n type BtwThinkingLevel,\n buildUserPrompt,\n completeSideQuestion,\n} from \"./side-thread.js\";\nexport { sanitizeSingleLine } from \"./text.js\";\n\nconst MAX_CONTEXT_CHARS = 40_000;\n\ninterface LoadBtwThinkingLevelOptions {\n settingsPath?: string;\n warn?: (message: string) => void;\n}\n\ntype BtwModelRegistry = Pick<ExtensionCommandContext[\"modelRegistry\"], \"find\" | \"getApiKeyAndHeaders\">;\n\ntype BtwProviderRegistry = Pick<ExtensionCommandContext[\"modelRegistry\"], \"getProvider\">;\n\nexport function createModelRegistryCompleteSimple(modelRegistry: BtwProviderRegistry): CompleteSimpleFunction {\n return async (model, context, options) => {\n const provider = modelRegistry.getProvider(model.provider);\n if (!provider) throw new Error(`No provider registered for model provider: ${model.provider}`);\n return provider.streamSimple(model, context, options).result();\n };\n}\n\ninterface ResolveBtwModelOptions {\n settings: BtwSettings;\n currentModel: Model<Api> | undefined;\n modelRegistry: BtwModelRegistry;\n warn?: (message: string) => void;\n}\n\nexport interface ResolvedBtwModel {\n model: Model<Api>;\n auth: SideQuestionAuth;\n}\n\nexport interface BtwThreadState {\n id: string;\n title?: string;\n thread: SideThread;\n thinkingLevel: BtwThinkingLevel;\n createdAt: number;\n updatedAt: number;\n}\n\nexport async function resolveBtwModel({\n settings,\n currentModel,\n modelRegistry,\n warn,\n}: ResolveBtwModelOptions): Promise<ResolvedBtwModel | undefined> {\n const reportWarning = (message: string) => warn?.(sanitizeSingleLine(message));\n if (settings.model) {\n const fallback = currentModel ? `${currentModel.provider}/${currentModel.id}` : \"the current model\";\n const reference = parseBtwModelReference(settings.model);\n if (!reference) {\n reportWarning(`pi-btw model ${settings.model} is invalid; falling back to ${fallback}.`);\n return resolveBtwModel({ settings: {}, currentModel, modelRegistry, warn: reportWarning });\n }\n const configuredModel = modelRegistry.find(reference.provider, reference.modelId);\n if (!configuredModel) {\n reportWarning(`pi-btw model ${settings.model} was not found; falling back to ${fallback}.`);\n } else {\n const sameAsCurrent =\n configuredModel === currentModel ||\n (configuredModel.provider === currentModel?.provider && configuredModel.id === currentModel.id);\n const fallbackAction = sameAsCurrent ? \"no distinct current model is available\" : `falling back to ${fallback}`;\n try {\n const auth = await modelRegistry.getApiKeyAndHeaders(configuredModel);\n if (auth.ok && hasRequestAuth(auth)) {\n return {\n model: auth.baseUrl ? { ...configuredModel, baseUrl: auth.baseUrl } : configuredModel,\n auth,\n };\n }\n const reason = auth.ok ? \"has no request credentials\" : auth.error;\n reportWarning(`pi-btw model ${settings.model} is unavailable (${reason}); ${fallbackAction}.`);\n } catch (error: unknown) {\n reportWarning(`pi-btw model ${settings.model} credentials failed (${formatError(error)}); ${fallbackAction}.`);\n }\n if (sameAsCurrent) return undefined;\n }\n }\n\n if (!currentModel) return undefined;\n try {\n const auth = await modelRegistry.getApiKeyAndHeaders(currentModel);\n if (auth.ok && hasRequestAuth(auth)) {\n // Direct provider streams bypass Pi's request preparation, including OAuth routing.\n return {\n model: auth.baseUrl ? { ...currentModel, baseUrl: auth.baseUrl } : currentModel,\n auth,\n };\n }\n } catch {\n // The caller reports the final lack of an available model.\n }\n return undefined;\n}\n\nfunction hasRequestAuth(auth: SideQuestionAuth): boolean {\n return Boolean(\n auth.apiKey || providerHeadersHaveValue(auth.headers) || (auth.env && Object.keys(auth.env).length > 0),\n );\n}\n\nfunction providerHeadersHaveValue(headers: ProviderHeaders | undefined): boolean {\n return headers !== undefined && Object.values(headers).some((value) => value !== null);\n}\n\nexport async function loadBtwThinkingLevel(\n currentThinkingLevel: BtwThinkingLevel,\n options: LoadBtwThinkingLevelOptions = {},\n): Promise<BtwThinkingLevel> {\n const settings = await readBtwSettings(options.settingsPath);\n if (settings.kind === \"missing\") return currentThinkingLevel;\n if (settings.kind === \"loaded\") {\n return settings.settings.thinkingLevel ?? currentThinkingLevel;\n }\n\n options.warn?.(\n sanitizeSingleLine(\n `pi-btw settings ignored: ${settings.reason}; expected optional model \"provider/model-id\", omitted thinkingLevel for Same as main thread or thinkingLevel \"${BTW_THINKING_LEVELS.join('\" | \"')}\", boolean rememberThinkingLevelChanges, and boolean fullscreenCopyOnSelect. Using current Pi thinking level.`,\n ),\n );\n return currentThinkingLevel;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction readBtwSessionId(ctx: ExtensionCommandContext): string | undefined {\n const getSessionId = ctx.sessionManager.getSessionId;\n if (typeof getSessionId !== \"function\") return undefined;\n const sessionId = getSessionId.call(ctx.sessionManager);\n return sessionId.length > 0 ? sessionId : undefined;\n}\n\nfunction notifySafely(\n ctx: ExtensionCommandContext,\n message: string,\n level: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n try {\n ctx.ui.notify(sanitizeSingleLine(message), level);\n } catch {\n // Async command continuations may finish after their ExtensionContext is replaced.\n }\n}\n\n// Keep this slightly-over-1,000-line command coordinator intact: its injectable menu,\n// request, resume, and delivery flows share the same thread-state and test seams;\n// settings, keybinding policy, terminal ownership, and rendering live in separate modules.\nexport interface BtwExtensionDependencies {\n showCommandMenu?: (\n pi: ExtensionAPI,\n ctx: ExtensionCommandContext,\n resumeThreads: readonly BtwResumeThreadSummary[],\n ) => Promise<BtwCommandMenuResult>;\n pickMainEntry?: typeof pickMainEntry;\n loadSettings?: typeof loadSettingsForCommand;\n resolveModel?: typeof resolveBtwModelWithLoader;\n runThread?: typeof runBtwThread;\n runFullscreen?: RunBtwFullscreen;\n}\n\nexport default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependencies = {}) {\n const showCommandMenu = dependencies.showCommandMenu ?? showCommandMenuForBtw;\n const pickEntry = dependencies.pickMainEntry ?? pickMainEntry;\n const loadSettings = dependencies.loadSettings ?? loadSettingsForCommand;\n const resolveModel = dependencies.resolveModel ?? resolveBtwModelWithLoader;\n const runThread = dependencies.runThread ?? runBtwThread;\n const runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;\n // Pi creates a fresh extension instance after session replacement or reload.\n const resumableThreads = new Map<string, BtwThreadState>();\n let nextThreadNumber = 1;\n const listResumeThreads = (): BtwResumeThreadSummary[] =>\n [...resumableThreads.values()]\n .reverse()\n .filter((state) => state.thread.turns.length > 0 && state.title)\n .sort((first, second) => second.updatedAt - first.updatedAt || second.createdAt - first.createdAt)\n .map((state) => ({\n id: state.id,\n title: state.title ?? \"Untitled side thread\",\n questionCount: state.thread.turns.length,\n }));\n pi.registerCommand(\"btw\", {\n description: \"Ask a quick side question without adding it to the main conversation\",\n handler: async (args, ctx) => {\n const question = args.trim();\n if (ctx.mode !== \"tui\") {\n ctx.ui.notify(\"/btw requires interactive TUI mode\", \"error\");\n return;\n }\n\n let menuResult: BtwCommandMenuResult = \"start\";\n let selectedConversationContext: string | undefined;\n if (!question) {\n while (true) {\n menuResult = await showCommandMenu(pi, ctx, listResumeThreads());\n if (menuResult === \"closed\") return;\n if (menuResult !== \"tree\") break;\n\n const treeResult = await pickEntry(pi, ctx);\n if (treeResult.kind === \"closed\") return;\n if (treeResult.kind === \"back\") continue;\n try {\n if (!ctx.sessionManager.getEntry(treeResult.entryId)) {\n notifySafely(ctx, \"The selected main-thread entry is no longer available\", \"warning\");\n continue;\n }\n const branch = ctx.sessionManager.getBranch(treeResult.entryId);\n if (branch.at(-1)?.id !== treeResult.entryId) {\n notifySafely(ctx, \"The selected main-thread branch is no longer available\", \"warning\");\n continue;\n }\n selectedConversationContext = buildConversationContext(branch);\n menuResult = \"start\";\n break;\n } catch {\n return;\n }\n }\n }\n\n const settings = await loadSettings(ctx);\n const sameAsMainThinkingLevel = settings.thinkingLevel === undefined;\n const resolution = await resolveModel(settings, ctx);\n if (resolution.kind === \"cancelled\") {\n notifySafely(ctx, \"Cancelled\", \"info\");\n return;\n }\n if (resolution.kind === \"unavailable\") {\n notifySafely(ctx, \"No available model for /btw\", \"error\");\n return;\n }\n\n let state = typeof menuResult === \"object\" ? resumableThreads.get(menuResult.threadId) : undefined;\n if (typeof menuResult === \"object\" && !state) {\n notifySafely(ctx, \"The selected /btw side thread is no longer available\", \"warning\");\n return;\n }\n const startingTurnCount = state?.thread.turns.length ?? 0;\n\n try {\n await runFullscreen(\n ctx,\n (fullscreenCtx) => {\n if (!state) {\n const createdAt = Date.now();\n state = {\n id: `btw-${nextThreadNumber}`,\n thread: createSideThread(\n selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch()),\n ),\n thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),\n createdAt,\n updatedAt: createdAt,\n };\n nextThreadNumber += 1;\n }\n return runThread({\n initialQuestion: question || undefined,\n selected: resolution.selected,\n thinkingLevel: state.thinkingLevel,\n rememberThinkingLevelChanges: !sameAsMainThinkingLevel && effectiveRememberThinkingLevelChanges(settings),\n state,\n ctx: fullscreenCtx,\n });\n },\n {\n copyOnSelect: effectiveFullscreenCopyOnSelect(settings),\n ...(settings.keybindings ? { keybindings: settings.keybindings } : {}),\n },\n );\n } finally {\n if (state?.title && state.thread.turns.length > 0) {\n if (state.thread.turns.length > startingTurnCount) {\n resumableThreads.delete(state.id);\n }\n resumableThreads.set(state.id, state);\n }\n }\n },\n });\n}\n\nasync function showCommandMenuForBtw(\n pi: ExtensionAPI,\n ctx: ExtensionCommandContext,\n resumeThreads: readonly BtwResumeThreadSummary[],\n): Promise<BtwCommandMenuResult> {\n const currentModel = ctx.model;\n const availableModels = ctx.modelRegistry.getAll();\n const currentThinkingLevel = pi.getThinkingLevel();\n const loaded = await readBtwSettings();\n const settings = loaded.kind === \"loaded\" ? loaded.settings : {};\n const configured = settings.model ? parseBtwModelReference(settings.model) : undefined;\n const configuredModel = configured\n ? availableModels.find((model) => model.provider === configured.provider && model.id === configured.modelId)\n : undefined;\n const model = configuredModel ?? currentModel;\n return showBtwCommandMenu(ctx, {\n currentThinkingLevel,\n availableThinkingLevels: model ? getSupportedThinkingLevels(model) : BTW_THINKING_LEVELS,\n resumeThreads,\n });\n}\n\nasync function loadSettingsForCommand(ctx: ExtensionCommandContext): Promise<BtwSettings> {\n const settingsResult = await readBtwSettings();\n if (settingsResult.kind === \"loaded\") return settingsResult.settings;\n if (settingsResult.kind === \"invalid\") {\n notifySafely(ctx, `pi-btw settings ignored: ${settingsResult.reason}`, \"warning\");\n }\n return {};\n}\n\ntype ModelResolutionOutcome =\n | { kind: \"cancelled\" }\n | { kind: \"unavailable\" }\n | { kind: \"selected\"; selected: ResolvedBtwModel };\n\nasync function resolveBtwModelWithLoader(\n settings: BtwSettings,\n ctx: ExtensionCommandContext,\n): Promise<ModelResolutionOutcome> {\n return ctx.ui.custom<ModelResolutionOutcome>((tui, theme, _keybindings, done) => {\n const loader = new BorderedLoader(tui, theme, \"Resolving /btw model credentials...\");\n let settled = false;\n loader.onAbort = () => {\n if (settled) return;\n settled = true;\n done({ kind: \"cancelled\" });\n };\n\n resolveBtwModel({\n settings,\n currentModel: ctx.model,\n modelRegistry: ctx.modelRegistry,\n warn: (message) => {\n if (!settled) notifySafely(ctx, message, \"warning\");\n },\n })\n .then((selected) => {\n if (settled) return;\n settled = true;\n done(selected ? { kind: \"selected\", selected } : { kind: \"unavailable\" });\n })\n .catch(() => {\n if (settled) return;\n settled = true;\n done({ kind: \"unavailable\" });\n });\n\n return loader;\n });\n}\n\ninterface RunBtwThreadDependencies {\n ask?: typeof askThreadQuestion;\n interact?: typeof showThreadComposer;\n chooseBringToMain?: typeof chooseBringToMain;\n deliverBringToMain?: typeof loadBringToMainDraft;\n persistThinkingLevel?: (level: BtwThinkingLevel) => Promise<unknown>;\n now?: () => number;\n}\n\nexport type BtwThreadResult = { kind: \"closed\" };\n\ntype BtwThreadThinkingControl = Omit<BtwThinkingControl, \"keybindings\">;\n\ninterface BtwThreadSteeringControl {\n questions: readonly string[];\n submit: (question: string) => void;\n thinking: BtwThreadThinkingControl;\n}\n\ntype BtwBringToMainChoice =\n | BtwThreadResult\n | {\n kind: \"bringToMain\";\n draft: string;\n summary: BtwBringToMainSummary;\n selectionState?: BtwTextRangeSelectorState;\n }\n | { kind: \"back\" };\n\ntype BtwBringToMainDelivery = \"loaded\" | \"back\" | \"closed\";\n\ninterface RunBtwThreadOptions {\n initialQuestion?: string;\n selected: ResolvedBtwModel;\n thinkingLevel: BtwThinkingLevel;\n rememberThinkingLevelChanges?: boolean;\n settingsPath?: string;\n state?: BtwThreadState;\n ctx: ExtensionCommandContext;\n dependencies?: RunBtwThreadDependencies;\n}\n\nexport async function runBtwThread({\n initialQuestion,\n selected,\n thinkingLevel,\n rememberThinkingLevelChanges = false,\n settingsPath,\n state,\n ctx,\n dependencies = {},\n}: RunBtwThreadOptions): Promise<BtwThreadResult> {\n const ask = dependencies.ask ?? askThreadQuestion;\n const interact = dependencies.interact ?? showThreadComposer;\n const chooseBringToMainAction = dependencies.chooseBringToMain ?? chooseBringToMain;\n const deliverBringToMainDraft = dependencies.deliverBringToMain ?? loadBringToMainDraft;\n const persistThinkingLevel =\n dependencies.persistThinkingLevel ??\n ((level: BtwThinkingLevel) => updateBtwSettings({ thinkingLevel: level }, { settingsPath }));\n const now = dependencies.now ?? Date.now;\n const thread = state?.thread ?? createSideThread(buildConversationContext(ctx.sessionManager.getBranch()));\n const thinkingLevels = getSupportedThinkingLevels(selected.model);\n const pendingWrites = new Set<Promise<void>>();\n const steeringQuestions: string[] = [];\n let activeThinkingLevel = clampThinkingLevel(selected.model, state?.thinkingLevel ?? thinkingLevel);\n if (state) state.thinkingLevel = activeThinkingLevel;\n let pendingQuestion = initialQuestion;\n let composerDraft: string | undefined;\n const createThinkingControl = (): BtwThreadThinkingControl => ({\n level: activeThinkingLevel,\n levels: thinkingLevels,\n onChange: (level) => {\n if (!thinkingLevels.includes(level)) return;\n activeThinkingLevel = level;\n if (state) state.thinkingLevel = level;\n if (!rememberThinkingLevelChanges) return;\n let write!: Promise<void>;\n write = Promise.resolve()\n .then(() => persistThinkingLevel(level))\n .then(() => undefined)\n .catch((error: unknown) => {\n notifySafely(\n ctx,\n `Thinking level changed to ${level}, but could not be remembered in pi-btw.json: ${formatError(error)}`,\n \"warning\",\n );\n })\n .finally(() => pendingWrites.delete(write));\n pendingWrites.add(write);\n },\n });\n\n try {\n while (true) {\n if (!pendingQuestion) {\n const action = await interact(thread, thread.turns.length > 0, ctx, composerDraft, createThinkingControl());\n if (action.kind === \"close\") return { kind: \"closed\" };\n if (action.kind === \"bringToMain\") {\n const choice = await chooseBringToMainAction(thread, ctx);\n if (choice.kind === \"closed\") return choice;\n if (choice.kind === \"back\") {\n composerDraft = action.questionDraft;\n continue;\n }\n const delivery = await deliverBringToMainDraft(choice.draft, ctx, choice.summary);\n if (delivery === \"loaded\" || delivery === \"closed\") return { kind: \"closed\" };\n composerDraft = action.questionDraft;\n continue;\n }\n composerDraft = undefined;\n pendingQuestion = action.question;\n }\n\n const result = await ask(thread, pendingQuestion, selected, activeThinkingLevel, ctx, {\n questions: steeringQuestions,\n submit: (question) => steeringQuestions.push(question),\n thinking: createThinkingControl(),\n });\n if (result.kind === \"aborted\") {\n notifySafely(ctx, \"Cancelled\", \"info\");\n return { kind: \"closed\" };\n }\n if (result.kind === \"error\") {\n thread.turns.push({\n kind: \"error\",\n question: pendingQuestion,\n answer: result.message,\n });\n }\n if (state) {\n state.title ||= sanitizeSingleLine(pendingQuestion) || \"Untitled side thread\";\n state.updatedAt = now();\n }\n\n pendingQuestion = steeringQuestions.shift();\n }\n } finally {\n await Promise.allSettled([...pendingWrites]);\n }\n}\n\ninterface ChooseBringToMainDependencies {\n showMenu?: typeof showBtwMenu;\n showPreview?: typeof showBringToMainPreview;\n}\n\nexport async function chooseBringToMain(\n thread: SideThread,\n ctx: ExtensionCommandContext,\n dependencies: ChooseBringToMainDependencies = {},\n): Promise<BtwBringToMainChoice> {\n const answered = getAnsweredTurns(thread.turns);\n if (answered.length === 0) return { kind: \"back\" };\n const showMenu = dependencies.showMenu ?? showBtwMenu;\n const showPreview = dependencies.showPreview ?? showBringToMainPreview;\n const makeChoice = (segments: readonly BtwBringToMainSegment[]) => ({\n kind: \"bringToMain\" as const,\n draft: formatBtwBringToMain(segments),\n summary: summarizeBringToMain(segments),\n });\n\n const latestSegments = buildQuickBringToMainSegments(thread.turns, { kind: \"latest\" });\n const entireSegments = buildQuickBringToMainSegments(thread.turns, { kind: \"entire\" });\n const latestOption = `Latest question and answer 1 Q&A \u00B7 ~${estimateBringToMainTokens(latestSegments)} tokens`;\n const fromOption = \"From a question onward\u2026 Choose a starting question\";\n const exactOption = \"Select exact text\u2026 Lines or characters\";\n const entireOption = `Entire side thread ${answered.length} Q&A \u00B7 ~${estimateBringToMainTokens(entireSegments)} tokens`;\n const cancelOption = \"Cancel Return to the side thread\";\n let selectedScope: string | undefined;\n\n while (true) {\n const scopeResult = await showMenu(\n ctx,\n \"Bring what back to the main thread?\",\n [latestOption, fromOption, exactOption, entireOption, cancelOption],\n selectedScope,\n );\n if (scopeResult.kind === \"close\") return { kind: \"closed\" };\n if (scopeResult.kind === \"back\" || scopeResult.value === cancelOption) return { kind: \"back\" };\n const scope = scopeResult.value;\n selectedScope = scope;\n if (scope === latestOption) return makeChoice(latestSegments);\n if (scope === entireOption) {\n const choice = makeChoice(entireSegments);\n const preview = await showPreview(ctx, choice.draft, choice.summary);\n if (preview.kind === \"close\") return { kind: \"closed\" };\n if (preview.kind === \"back\") continue;\n return choice;\n }\n if (scope === fromOption) {\n const questions = answered.map(\n (turn, index) => `${index + 1}. ${truncatePreview(sanitizeSingleLine(turn.question))}`,\n );\n let selectedQuestion: string | undefined;\n while (true) {\n const questionResult = await showMenu(ctx, \"Start from which question?\", questions, selectedQuestion);\n if (questionResult.kind === \"close\") return { kind: \"closed\" };\n if (questionResult.kind === \"back\") break;\n const answeredTurnIndex = questions.indexOf(questionResult.value);\n if (answeredTurnIndex < 0) continue;\n selectedQuestion = questionResult.value;\n const choice = makeChoice(buildQuickBringToMainSegments(thread.turns, { kind: \"from\", answeredTurnIndex }));\n const preview = await showPreview(ctx, choice.draft, choice.summary);\n if (preview.kind === \"close\") return { kind: \"closed\" };\n if (preview.kind === \"back\") continue;\n return choice;\n }\n continue;\n }\n\n if (scope !== exactOption) continue;\n let selectionState: BtwTextRangeSelectorState | undefined;\n while (true) {\n const selectedRange = await showBtwCustomPreservingEditor<BtwBringToMainChoice>(\n ctx,\n (tui, theme, keybindings, done) => {\n let selector: BtwTextRangeSelector;\n selector = new BtwTextRangeSelector(\n tui,\n theme,\n keybindings,\n thread.turns,\n (action) => {\n if (action.kind === \"back\") done({ kind: \"back\" });\n else if (action.kind === \"close\") done({ kind: \"closed\" });\n else done({ ...makeChoice(action.segments), selectionState: selector.getState() });\n },\n selectionState,\n );\n return selector;\n },\n );\n if (!selectedRange) return { kind: \"closed\" };\n if (selectedRange.kind === \"closed\") return selectedRange;\n if (selectedRange.kind === \"back\") break;\n const preview = await showPreview(ctx, selectedRange.draft, selectedRange.summary);\n if (preview.kind === \"close\") return { kind: \"closed\" };\n if (preview.kind === \"back\") {\n selectionState = selectedRange.selectionState;\n continue;\n }\n return {\n kind: \"bringToMain\",\n draft: selectedRange.draft,\n summary: selectedRange.summary,\n };\n }\n }\n}\n\ntype BtwMenuSelectorAction = { kind: \"select\"; value: string } | { kind: \"back\" } | { kind: \"close\" };\n\ntype BtwBringToMainPreviewAction = { kind: \"bring\" } | { kind: \"back\" } | { kind: \"close\" };\n\nasync function showBringToMainPreview(\n ctx: ExtensionCommandContext,\n draft: string,\n summary: BtwBringToMainSummary,\n): Promise<BtwBringToMainPreviewAction> {\n const { defineMenu, runMenu } = await import(\"@narumitw/pi-tui-kit\");\n if (ctx.signal?.aborted) return { kind: \"close\" };\n let confirmed = false;\n const count = summary.messages === 1 ? \"1 message\" : `${summary.messages} messages`;\n const lineCount = summary.lines === 1 ? \"1 line\" : `${summary.lines} lines`;\n const menu = defineMenu<void, \"preview\", \"bring\", MenuContext>({\n start: \"preview\",\n screens: {\n preview: () => ({\n kind: \"review\",\n title: `Preview \u00B7 ${count} \u00B7 ${lineCount} \u00B7 ~${summary.tokens} tokens`,\n content: draft,\n viewportSize: \"adaptive\",\n hint: \"back\",\n confirm: { id: \"bring\", label: \"Bring\", action: \"bring\" },\n }),\n },\n actions: {\n bring: async () => {\n confirmed = true;\n return { kind: \"close\" } as const;\n },\n },\n });\n const result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>\n runMenu(menuContext, menu, { getState: () => undefined }),\n );\n if (confirmed && result.kind === \"closed\" && result.reason === \"close\") {\n return { kind: \"bring\" };\n }\n return terminalBtwMenuAction(result);\n}\n\nasync function showBtwMenu(\n ctx: ExtensionCommandContext,\n title: string,\n options: readonly string[],\n initialValue?: string,\n): Promise<BtwMenuSelectorAction> {\n const { defineMenu, runMenu } = await import(\"@narumitw/pi-tui-kit\");\n if (ctx.signal?.aborted) return { kind: \"close\" };\n const items = options.map((label, index) => ({ id: `option-${index}`, label }));\n const initialIndex = initialValue === undefined ? -1 : options.indexOf(initialValue);\n let selectedValue: string | undefined;\n const menu = defineMenu<void, \"choices\", \"select\", MenuContext>({\n start: \"choices\",\n screens: {\n choices: () => ({\n kind: \"choice\",\n title,\n items,\n action: \"select\",\n initialItemId: initialIndex >= 0 ? `option-${initialIndex}` : undefined,\n hint: \"back\",\n }),\n },\n actions: {\n select: async ({ itemId }: { itemId: string }) => {\n const index = Number.parseInt(itemId.slice(\"option-\".length), 10);\n selectedValue = options[index];\n return selectedValue === undefined ? ({ kind: \"stay\" } as const) : ({ kind: \"close\" } as const);\n },\n },\n });\n const result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>\n runMenu(menuContext, menu, { getState: () => undefined }),\n );\n return selectedValue !== undefined && result.kind === \"closed\" && result.reason === \"close\"\n ? { kind: \"select\", value: selectedValue }\n : terminalBtwMenuAction(result);\n}\n\nfunction terminalBtwMenuAction(result: RunMenuResult): { kind: \"back\" } | { kind: \"close\" } {\n if (result.kind === \"closed\") return { kind: result.reason };\n if (result.kind === \"error\") throw result.error;\n return { kind: \"close\" };\n}\n\nexport async function loadBringToMainDraft(\n draft: string,\n ctx: ExtensionCommandContext,\n summary: BtwBringToMainSummary,\n): Promise<BtwBringToMainDelivery> {\n const describeContent = () =>\n `${summary.messages} ${summary.messages === 1 ? \"message\" : \"messages\"} (~${summary.tokens} ${summary.tokens === 1 ? \"token\" : \"tokens\"})`;\n const existing = ctx.ui.getEditorText();\n if (!existing.trim()) {\n ctx.ui.setEditorText(draft);\n ctx.ui.notify(`Brought ${describeContent()} to the main editor. Review and submit when ready.`, \"info\");\n return \"loaded\";\n }\n\n const appendOption = \"Append after current draft Recommended\";\n const replaceOption = \"\u26A0 Replace current draft Discards current editor text\";\n const cancelOption = \"Cancel Return to the side thread\";\n while (true) {\n const action = await showBtwMenu(ctx, \"The main editor already has a draft\", [\n appendOption,\n replaceOption,\n cancelOption,\n ]);\n if (action.kind === \"close\") return \"closed\";\n if (action.kind === \"back\" || action.value === cancelOption) return \"back\";\n if (action.value === appendOption) {\n ctx.ui.setEditorText(`${ctx.ui.getEditorText()}\\n\\n${draft}`);\n ctx.ui.notify(\n `Appended ${describeContent()} to the existing main-editor draft. Review and submit when ready.`,\n \"info\",\n );\n return \"loaded\";\n }\n if (action.value !== replaceOption) continue;\n\n const current = ctx.ui.getEditorText();\n const characters = [...current].length;\n const confirmed = await showBtwMenu(ctx, `Replace the current ${characters}-character editor draft?`, [\n \"Back Keep current editor text\",\n \"\u26A0 Replace current draft Cannot be undone\",\n ]);\n if (confirmed.kind === \"close\") return \"closed\";\n if (confirmed.kind === \"back\" || confirmed.value === \"Back Keep current editor text\") continue;\n if (confirmed.value !== \"\u26A0 Replace current draft Cannot be undone\") continue;\n if (ctx.ui.getEditorText() !== current) {\n ctx.ui.notify(\n \"The main editor changed during confirmation. Review the updated draft and choose again.\",\n \"warning\",\n );\n continue;\n }\n ctx.ui.setEditorText(draft);\n ctx.ui.notify(`Replaced the main-editor draft with ${describeContent()}. Review and submit when ready.`, \"info\");\n return \"loaded\";\n }\n}\n\nfunction truncatePreview(text: string): string {\n return text.length <= 72 ? text : `${text.slice(0, 69)}\u2026`;\n}\n\nasync function prepareCurrentTranscriptMarkdown(\n thread: SideThread,\n pendingQuestion: string | undefined,\n ctx: ExtensionCommandContext,\n): Promise<BtwMarkdownTransformers | undefined> {\n while (true) {\n const turnCount = thread.turns.length;\n const createMarkdownTransformers = ctx.signal\n ? await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion, ctx.signal)\n : await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion);\n if (!createMarkdownTransformers || ctx.signal?.aborted) return undefined;\n if (thread.turns.length === turnCount) return createMarkdownTransformers;\n }\n}\n\nasync function askThreadQuestion(\n thread: SideThread,\n question: string,\n selected: ResolvedBtwModel,\n thinkingLevel: BtwThinkingLevel,\n ctx: ExtensionCommandContext,\n steering: BtwThreadSteeringControl,\n) {\n const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, question, ctx);\n if (!createMarkdownTransformers) return { kind: \"aborted\" as const };\n return ctx.ui.custom<Awaited<ReturnType<typeof completeSideThreadTurn>>>((tui, theme, keybindings, done) => {\n let settled = false;\n const view = new BtwAnsweringView(\n tui,\n theme,\n thread.turns,\n question,\n () => {\n if (settled) return;\n settled = true;\n done({ kind: \"aborted\" });\n },\n thinkingLevel,\n {\n markdownTransformers: createMarkdownTransformers(theme),\n steering: {\n questions: steering.questions,\n onSubmit: steering.submit,\n thinking: { ...steering.thinking, keybindings },\n },\n },\n );\n completeSideThreadTurn({\n thread,\n question,\n model: selected.model,\n thinkingLevel,\n auth: selected.auth,\n signal: view.signal,\n completeSimple: createModelRegistryCompleteSimple(ctx.modelRegistry),\n sessionId: readBtwSessionId(ctx),\n }).then((result) => {\n if (settled) return;\n settled = true;\n view.finish();\n done(result);\n });\n return view;\n });\n}\n\nasync function showThreadComposer(\n thread: SideThread,\n startAtBottom: boolean,\n ctx: ExtensionCommandContext,\n initialQuestion: string | undefined,\n thinking: BtwThreadThinkingControl,\n): Promise<TranscriptPagerAction> {\n const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, initialQuestion, ctx);\n if (!createMarkdownTransformers) return { kind: \"close\" };\n return ctx.ui.custom<TranscriptPagerAction>(\n (tui, theme, keybindings, done) =>\n new BtwTranscriptPager(tui, theme, thread.turns, done, {\n startAtBottom,\n initialQuestion,\n markdownTransformers: createMarkdownTransformers(theme),\n thinking: { ...thinking, keybindings },\n }),\n );\n}\n\ntype MessageContentBlock = {\n type?: string;\n text?: string;\n name?: string;\n arguments?: unknown;\n result?: unknown;\n};\n\ntype SessionMessage = {\n role?: string;\n content?: unknown;\n stopReason?: string;\n};\n\ntype SessionEntry = {\n type: string;\n message?: SessionMessage;\n};\n\nexport function buildConversationContext(entries: readonly SessionEntry[]) {\n const sections: string[] = [];\n\n for (const entry of entries) {\n if (entry.type !== \"message\" || !entry.message?.role) continue;\n\n const role = entry.message.role;\n if (role !== \"user\" && role !== \"assistant\") continue;\n\n const contentLines = extractContentLines(entry.message.content);\n if (contentLines.length === 0) continue;\n\n const label = role === \"user\" ? \"User\" : \"Assistant\";\n const status =\n entry.message.stopReason && entry.message.stopReason !== \"stop\" ? ` (${entry.message.stopReason})` : \"\";\n sections.push(`${label}${status}: ${contentLines.join(\"\\n\")}`);\n }\n\n return truncateFromStart(sections.join(\"\\n\\n\"), MAX_CONTEXT_CHARS);\n}\n\nfunction extractContentLines(content: unknown): string[] {\n if (typeof content === \"string\") return [content.trim()].filter(Boolean);\n if (!Array.isArray(content)) return [];\n\n const lines: string[] = [];\n for (const part of content) {\n if (!part || typeof part !== \"object\") continue;\n const block = part as MessageContentBlock;\n if (block.type === \"text\" && typeof block.text === \"string\") {\n lines.push(block.text.trim());\n } else if (block.type === \"toolCall\" && typeof block.name === \"string\") {\n lines.push(`Tool call: ${block.name}(${formatJson(block.arguments)})`);\n } else if (block.type === \"toolResult\" && typeof block.name === \"string\") {\n lines.push(`Tool result from ${block.name}: ${formatJson(block.result)}`);\n }\n }\n return lines.filter(Boolean);\n}\n\nfunction formatJson(value: unknown) {\n if (value === undefined) return \"\";\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction truncateFromStart(text: string, maxChars: number) {\n if (text.length <= maxChars) return text;\n return `[Earlier context omitted; showing the last ${maxChars} characters.]\\n${text.slice(-maxChars)}`;\n}\n", "import type { KeybindingsManager, Theme } from \"@earendil-works/pi-coding-agent\";\nimport { type Component, Key, matchesKey, type TUI, truncateToWidth, visibleWidth } from \"@earendil-works/pi-tui\";\nimport type { SideThreadTurn } from \"./side-thread.js\";\n\nconst RESERVED_APP_ROWS = 3;\nconst GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nexport interface BtwBringToMainSegment {\n role: \"user\" | \"assistant\";\n text: string;\n}\n\nexport interface BtwBringToMainSummary {\n lines: number;\n messages: number;\n tokens: number;\n}\n\nexport interface BtwSelectionLine {\n role: BtwBringToMainSegment[\"role\"];\n text: string;\n}\n\nexport interface BtwTextPosition {\n line: number;\n column: number;\n}\n\nexport interface BtwTextRangeSelectorState {\n cursor: BtwTextPosition;\n anchor?: BtwTextPosition;\n lineAnchor?: number;\n preferredColumn: number;\n scrollOffset: number;\n horizontalOffset: number;\n}\n\nexport type BtwQuickBringToMainScope =\n | { kind: \"latest\" }\n | { kind: \"from\"; answeredTurnIndex: number }\n | { kind: \"entire\" };\n\nexport type BtwTextRangeSelectorAction =\n | { kind: \"confirm\"; segments: BtwBringToMainSegment[] }\n | { kind: \"back\" }\n | { kind: \"close\" };\n\nexport function getAnsweredTurns(turns: readonly SideThreadTurn[]): Extract<SideThreadTurn, { kind: \"answered\" }>[] {\n return turns.filter((turn): turn is Extract<SideThreadTurn, { kind: \"answered\" }> => turn.kind === \"answered\");\n}\n\nexport function buildQuickBringToMainSegments(\n turns: readonly SideThreadTurn[],\n scope: BtwQuickBringToMainScope,\n): BtwBringToMainSegment[] {\n const answered = getAnsweredTurns(turns);\n const selected =\n scope.kind === \"latest\"\n ? answered.slice(-1)\n : scope.kind === \"from\"\n ? answered.slice(Math.max(0, scope.answeredTurnIndex))\n : answered;\n return selected.flatMap((turn) => [\n { role: \"user\" as const, text: turn.question },\n { role: \"assistant\" as const, text: turn.answer },\n ]);\n}\n\nexport function buildBtwSelectionLines(turns: readonly SideThreadTurn[]): BtwSelectionLine[] {\n return buildQuickBringToMainSegments(turns, { kind: \"entire\" }).flatMap((segment) =>\n segment.text.split(\"\\n\").map((text) => ({ role: segment.role, text })),\n );\n}\n\nexport function segmentsFromLineRange(\n lines: readonly BtwSelectionLine[],\n anchor: number,\n cursor: number,\n): BtwBringToMainSegment[] {\n if (lines.length === 0) return [];\n const start = Math.max(0, Math.min(anchor, cursor, lines.length - 1));\n const end = Math.max(0, Math.min(Math.max(anchor, cursor), lines.length - 1));\n const segments: BtwBringToMainSegment[] = [];\n for (const line of lines.slice(start, end + 1)) {\n const previous = segments.at(-1);\n if (previous?.role === line.role) {\n previous.text += `\\n${line.text}`;\n } else {\n segments.push({ role: line.role, text: line.text });\n }\n }\n return segments;\n}\n\nexport function segmentsFromTextRange(\n lines: readonly BtwSelectionLine[],\n anchor: BtwTextPosition,\n cursor: BtwTextPosition,\n): BtwBringToMainSegment[] {\n if (lines.length === 0) return [];\n const first = clampTextPosition(lines, anchor);\n const second = clampTextPosition(lines, cursor);\n const [start, end] = compareTextPositions(first, second) <= 0 ? [first, second] : [second, first];\n if (compareTextPositions(start, end) === 0) return [];\n\n const segments: BtwBringToMainSegment[] = [];\n for (let lineIndex = start.line; lineIndex <= end.line; lineIndex += 1) {\n const line = lines[lineIndex];\n if (!line) continue;\n const characters = splitGraphemes(line.text);\n const from = lineIndex === start.line ? start.column : 0;\n const to = lineIndex === end.line ? end.column : characters.length;\n const text = characters.slice(from, to).join(\"\");\n if (text) {\n const previous = segments.at(-1);\n if (previous?.role === line.role) previous.text += text;\n else segments.push({ role: line.role, text });\n }\n const crossesSameRoleLine = lineIndex < end.line && lines[lineIndex + 1]?.role === line.role;\n if (crossesSameRoleLine) {\n const current = segments.at(-1);\n if (current?.role === line.role) current.text += \"\\n\";\n else segments.push({ role: line.role, text: \"\\n\" });\n }\n }\n return segments;\n}\n\nexport function estimateBringToMainTokens(segments: readonly BtwBringToMainSegment[]): number {\n return Math.ceil(Buffer.byteLength(segments.map((segment) => segment.text).join(\"\\n\"), \"utf8\") / 4);\n}\n\nexport function summarizeBringToMain(segments: readonly BtwBringToMainSegment[]): BtwBringToMainSummary {\n return {\n lines: segments.reduce((count, segment) => count + segment.text.split(\"\\n\").length, 0),\n messages: segments.length,\n tokens: estimateBringToMainTokens(segments),\n };\n}\n\nexport function formatBtwBringToMain(segments: readonly BtwBringToMainSegment[]): string {\n const body = segments\n .map((segment) => `${segment.role === \"user\" ? \"User\" : \"Assistant\"}:\\n${escapeBringToMainText(segment.text)}`)\n .join(\"\\n\\n\");\n return [\n \"The following context was brought back from a /btw side discussion.\",\n \"Treat it as discussion context, not as work already completed.\",\n \"\",\n \"<btw_context>\",\n body,\n \"</btw_context>\",\n ].join(\"\\n\");\n}\n\nexport class BtwTextRangeSelector implements Component {\n private readonly lines: BtwSelectionLine[];\n private cursor: BtwTextPosition = { line: 0, column: 0 };\n private anchor: BtwTextPosition | undefined;\n private lineAnchor: number | undefined;\n private preferredColumn = 0;\n private scrollOffset = 0;\n private horizontalOffset = 0;\n private warning: string | undefined;\n private finished = false;\n\n constructor(\n private readonly tui: TUI,\n private readonly theme: Theme,\n private readonly keybindings: KeybindingsManager,\n turns: readonly SideThreadTurn[],\n private readonly onAction: (action: BtwTextRangeSelectorAction) => void,\n initialState?: BtwTextRangeSelectorState,\n ) {\n this.lines = buildBtwSelectionLines(turns);\n if (initialState) {\n this.cursor = clampTextPosition(this.lines, initialState.cursor);\n this.anchor = initialState.anchor ? clampTextPosition(this.lines, initialState.anchor) : undefined;\n this.lineAnchor =\n initialState.lineAnchor === undefined\n ? undefined\n : Math.max(0, Math.min(this.lines.length - 1, initialState.lineAnchor));\n this.preferredColumn = Math.max(0, initialState.preferredColumn);\n this.scrollOffset = Math.max(0, initialState.scrollOffset);\n this.horizontalOffset = Math.max(0, initialState.horizontalOffset);\n }\n }\n\n getState(): BtwTextRangeSelectorState {\n return {\n cursor: { ...this.cursor },\n anchor: this.anchor ? { ...this.anchor } : undefined,\n lineAnchor: this.lineAnchor,\n preferredColumn: this.preferredColumn,\n scrollOffset: this.scrollOffset,\n horizontalOffset: this.horizontalOffset,\n };\n }\n\n render(width: number): string[] {\n const safeWidth = Math.max(1, width);\n const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_ROWS);\n const showStatus = availableRows >= 4;\n const showFooter = availableRows >= 3;\n const viewportHeight = Math.max(1, availableRows - 1 - (showStatus ? 1 : 0) - (showFooter ? 1 : 0));\n this.keepCursorVisible(viewportHeight);\n const textWidth = Math.max(1, safeWidth - visibleWidth(\"\u25CF> Assistant \u2502 \"));\n this.keepCursorHorizontallyVisible(textWidth);\n const range = this.getSelectionRange();\n const lineRange = this.getLineSelectionRange();\n const visible = this.lines.slice(this.scrollOffset, this.scrollOffset + viewportHeight);\n const rows = visible.map((line, visibleIndex) => {\n const lineIndex = this.scrollOffset + visibleIndex;\n const role = line.role === \"user\" ? \"User\" : \"Assistant\";\n const lineSelected = lineRange ? lineIndex >= lineRange.start && lineIndex <= lineRange.end : false;\n const prefix = `${lineSelected ? \"\u25CF\" : \" \"}${lineIndex === this.cursor.line ? \">\" : \" \"} ${role.padEnd(9)} \u2502 `;\n const text = this.renderTextLine(line, lineIndex, range, lineSelected);\n return truncateToWidth(\n lineIndex === this.cursor.line ? this.theme.fg(\"accent\", prefix) + text : prefix + text,\n safeWidth,\n \"\",\n );\n });\n const selected = this.getSelectedSegments();\n const summary = summarizeBringToMain(selected);\n const status =\n selected.length === 0\n ? \"Selected: none\"\n : `Selected: ${summary.lines} ${summary.lines === 1 ? \"line\" : \"lines\"} \u00B7 ${summary.messages} ${summary.messages === 1 ? \"message\" : \"messages\"} \u00B7 ~${summary.tokens} ${summary.tokens === 1 ? \"token\" : \"tokens\"}`;\n const confirm = confirmKeyLabel(this.keybindings);\n const back = keybindingLabel(this.keybindings, \"tui.select.cancel\", [\"ctrl+c\"]);\n const vertical = `${keybindingLabel(this.keybindings, \"tui.select.up\")}/${keybindingLabel(this.keybindings, \"tui.select.down\")}`;\n const confirmUsesSpace = this.keybindings.matches(\" \", \"tui.select.confirm\");\n const detailedFooter = this.warning\n ? `${this.warning} \u2022 ${confirmUsesSpace ? \"Shift+Arrows select\" : \"Space lines \u2022 Shift+Arrows text\"} \u2022 ${back} back \u2022 Ctrl+C close`\n : this.lineAnchor !== undefined\n ? `${confirmUsesSpace ? `${vertical} extend lines` : `Space clear \u2022 ${vertical} extend lines`} \u2022 Shift+Arrows text \u2022 ${confirm} bring \u2022 ${back} back \u2022 Ctrl+C close`\n : `Shift+Arrows select \u2022 Arrows move${confirmUsesSpace ? \"\" : \" \u2022 Space lines\"} \u2022 ${confirm} bring \u2022 ${back} back \u2022 Ctrl+C close`;\n const criticalFooter = `${confirm} bring \u2022 ${back} back \u2022 Ctrl+C close`;\n const footer = visibleWidth(detailedFooter) <= safeWidth ? detailedFooter : criticalFooter;\n return fitRows(\n [\n truncateToWidth(this.theme.fg(\"accent\", this.theme.bold(\"Select text to bring to main\")), safeWidth, \"\"),\n ...(showStatus ? [truncateToWidth(this.theme.fg(\"muted\", status), safeWidth, \"\")] : []),\n ...rows,\n ...(showFooter\n ? [truncateToWidth(this.theme.fg(this.warning ? \"warning\" : \"muted\", footer), safeWidth, \"\")]\n : []),\n ],\n availableRows,\n );\n }\n\n handleInput(data: string): void {\n if (this.finished) return;\n if (matchesKey(data, Key.ctrl(\"c\"))) {\n this.finish({ kind: \"close\" });\n return;\n }\n if (this.keybindings.matches(data, \"tui.select.cancel\")) {\n this.finish({ kind: \"back\" });\n return;\n }\n if (matchesConfirm(data, this.keybindings)) {\n if (this.lines.length > 0) {\n const segments = this.getSelectedSegments();\n if (segments.length === 0) {\n this.warning = \"Select text first\";\n this.tui.requestRender();\n } else {\n this.finish({ kind: \"confirm\", segments });\n }\n }\n return;\n }\n if (matchesKey(data, Key.space)) {\n this.anchor = undefined;\n this.lineAnchor = this.lineAnchor === undefined ? this.cursor.line : undefined;\n this.afterMove();\n return;\n }\n if (matchesKey(data, Key.shift(\"left\"))) {\n this.moveHorizontal(-1, true);\n return;\n }\n if (matchesKey(data, Key.shift(\"right\"))) {\n this.moveHorizontal(1, true);\n return;\n }\n if (matchesKey(data, Key.shift(\"up\"))) {\n this.moveVertical(-1, true);\n return;\n }\n if (matchesKey(data, Key.shift(\"down\"))) {\n this.moveVertical(1, true);\n return;\n }\n if (matchesKey(data, Key.left)) {\n this.moveHorizontal(-1, false);\n return;\n }\n if (matchesKey(data, Key.right)) {\n this.moveHorizontal(1, false);\n return;\n }\n if (this.keybindings.matches(data, \"tui.select.up\")) {\n this.moveVertical(-1, false);\n return;\n }\n if (this.keybindings.matches(data, \"tui.select.down\")) {\n this.moveVertical(1, false);\n return;\n }\n if (this.keybindings.matches(data, \"tui.select.pageUp\")) {\n this.moveVertical(-10, false);\n return;\n }\n if (this.keybindings.matches(data, \"tui.select.pageDown\")) {\n this.moveVertical(10, false);\n return;\n }\n }\n\n invalidate(): void {}\n\n private renderTextLine(\n line: BtwSelectionLine,\n lineIndex: number,\n range: { start: BtwTextPosition; end: BtwTextPosition } | undefined,\n lineSelected: boolean,\n ): string {\n const characters = splitGraphemes(line.text);\n let rendered = this.horizontalOffset > 0 ? this.theme.fg(\"muted\", \"\u2026\") : \"\";\n let buffer = \"\";\n let bufferSelected = false;\n const flush = () => {\n if (!buffer) return;\n rendered += bufferSelected ? this.theme.bg(\"selectedBg\", this.theme.fg(\"text\", buffer)) : buffer;\n buffer = \"\";\n };\n for (let column = this.horizontalOffset; column <= characters.length; column += 1) {\n if (range && lineIndex === range.start.line && column === range.start.column) {\n flush();\n rendered += this.theme.fg(\"accent\", \"[\");\n }\n if (lineIndex === this.cursor.line && column === this.cursor.column) {\n flush();\n rendered += this.theme.fg(\"accent\", \"\u2502\");\n }\n if (range && lineIndex === range.end.line && column === range.end.column) {\n flush();\n rendered += this.theme.fg(\"accent\", \"]\");\n }\n const character = characters[column];\n if (character === undefined) continue;\n const selected = lineSelected || (range ? positionFallsInside(lineIndex, column, range) : false);\n if (buffer && selected !== bufferSelected) flush();\n bufferSelected = selected;\n buffer += escapeTerminalControls(character);\n }\n flush();\n return rendered;\n }\n\n private getSelectionRange(): { start: BtwTextPosition; end: BtwTextPosition } | undefined {\n if (!this.anchor || compareTextPositions(this.anchor, this.cursor) === 0) return undefined;\n return compareTextPositions(this.anchor, this.cursor) < 0\n ? { start: this.anchor, end: this.cursor }\n : { start: this.cursor, end: this.anchor };\n }\n\n private getLineSelectionRange(): { start: number; end: number } | undefined {\n return this.lineAnchor === undefined\n ? undefined\n : {\n start: Math.min(this.lineAnchor, this.cursor.line),\n end: Math.max(this.lineAnchor, this.cursor.line),\n };\n }\n\n private getSelectedSegments(): BtwBringToMainSegment[] {\n if (this.lineAnchor !== undefined) {\n return segmentsFromLineRange(this.lines, this.lineAnchor, this.cursor.line);\n }\n return this.anchor ? segmentsFromTextRange(this.lines, this.anchor, this.cursor) : [];\n }\n\n private moveHorizontal(delta: -1 | 1, extend: boolean): void {\n if (this.lines.length === 0) return;\n if (!extend) this.lineAnchor = undefined;\n if (!extend && this.anchor) {\n const range = this.getSelectionRange();\n if (range) this.cursor = delta < 0 ? range.start : range.end;\n this.anchor = undefined;\n this.preferredColumn = this.cursor.column;\n this.afterMove();\n return;\n }\n this.beginOrClearSelection(extend);\n const line = this.lines[this.cursor.line];\n const length = line ? splitGraphemes(line.text).length : 0;\n if (delta < 0) {\n if (this.cursor.column > 0) this.cursor = { ...this.cursor, column: this.cursor.column - 1 };\n else if (this.cursor.line > 0) {\n const previousLine = this.lines[this.cursor.line - 1];\n this.cursor = {\n line: this.cursor.line - 1,\n column: previousLine ? splitGraphemes(previousLine.text).length : 0,\n };\n }\n } else if (this.cursor.column < length) {\n this.cursor = { ...this.cursor, column: this.cursor.column + 1 };\n } else if (this.cursor.line < this.lines.length - 1) {\n this.cursor = { line: this.cursor.line + 1, column: 0 };\n }\n this.preferredColumn = this.cursor.column;\n this.afterMove();\n }\n\n private moveVertical(delta: number, extend: boolean): void {\n if (this.lines.length === 0) return;\n if (extend || this.lineAnchor === undefined) this.beginOrClearSelection(extend);\n const line = Math.max(0, Math.min(this.lines.length - 1, this.cursor.line + delta));\n const target = this.lines[line];\n this.cursor = {\n line,\n column: Math.min(this.preferredColumn, target ? splitGraphemes(target.text).length : 0),\n };\n this.afterMove();\n }\n\n private beginOrClearSelection(extend: boolean): void {\n if (extend) this.lineAnchor = undefined;\n if (extend && !this.anchor) this.anchor = { ...this.cursor };\n if (!extend) this.anchor = undefined;\n }\n\n private afterMove(): void {\n this.warning = undefined;\n this.tui.requestRender();\n }\n\n private keepCursorVisible(height: number): void {\n if (height <= 0) return;\n if (this.cursor.line < this.scrollOffset) this.scrollOffset = this.cursor.line;\n if (this.cursor.line >= this.scrollOffset + height) {\n this.scrollOffset = this.cursor.line - height + 1;\n }\n }\n\n private keepCursorHorizontallyVisible(width: number): void {\n const characters = splitGraphemes(this.lines[this.cursor.line]?.text ?? \"\");\n const displayWidths = characters.map((character) => visibleWidth(escapeTerminalControls(character)));\n const currentWidth = displayWidths[this.cursor.column] ?? 0;\n let usedWidth = 1 + Math.min(currentWidth, Math.max(0, width - 1));\n let offset = this.cursor.column;\n for (let index = this.cursor.column - 1; index >= 0; index -= 1) {\n const nextWidth = usedWidth + (displayWidths[index] ?? 0) + (index > 0 ? 1 : 0);\n if (nextWidth > width) break;\n usedWidth += displayWidths[index] ?? 0;\n offset = index;\n }\n this.horizontalOffset = offset;\n }\n\n private finish(action: BtwTextRangeSelectorAction): void {\n if (this.finished) return;\n this.finished = true;\n this.onAction(action);\n }\n}\n\nfunction clampTextPosition(lines: readonly BtwSelectionLine[], position: BtwTextPosition): BtwTextPosition {\n const line = Math.max(0, Math.min(lines.length - 1, position.line));\n const text = lines[line]?.text ?? \"\";\n return {\n line,\n column: Math.max(0, Math.min(splitGraphemes(text).length, position.column)),\n };\n}\n\nfunction confirmKeyLabel(keybindings: KeybindingsManager): string {\n return keybindingLabel(keybindings, \"tui.select.confirm\", [\"ctrl+c\"], \"enter\");\n}\n\nfunction matchesConfirm(data: string, keybindings: KeybindingsManager): boolean {\n if (matchesKey(data, Key.ctrl(\"c\"))) return false;\n const hasUsableBinding = keybindings\n .getKeys(\"tui.select.confirm\")\n .map(String)\n .some((key) => key.toLowerCase() !== \"ctrl+c\");\n return keybindings.matches(data, \"tui.select.confirm\") || (!hasUsableBinding && matchesKey(data, Key.enter));\n}\n\nfunction keybindingLabel(\n keybindings: KeybindingsManager,\n keybinding:\n | \"tui.select.confirm\"\n | \"tui.select.cancel\"\n | \"tui.select.up\"\n | \"tui.select.down\"\n | \"tui.select.pageUp\"\n | \"tui.select.pageDown\",\n excluded: readonly string[] = [],\n fallback?: string,\n): string {\n const key = keybindings\n .getKeys(keybinding)\n .map(String)\n .find((candidate) => !excluded.includes(candidate.toLowerCase()));\n return formatKeyLabel(key ?? fallback ?? keybinding);\n}\n\nfunction formatKeyLabel(key: string): string {\n return key\n .split(\"+\")\n .map((part) => {\n const lower = part.toLowerCase();\n if (lower === \"ctrl\") return \"Ctrl\";\n if (lower === \"alt\") return \"Alt\";\n if (lower === \"shift\") return \"Shift\";\n if (lower === \"escape\" || lower === \"esc\") return \"Esc\";\n if (lower === \"enter\" || lower === \"return\") return \"Enter\";\n if (lower === \"pageup\") return \"PgUp\";\n if (lower === \"pagedown\") return \"PgDn\";\n return part.length === 1 ? part.toUpperCase() : `${part[0]?.toUpperCase() ?? \"\"}${part.slice(1)}`;\n })\n .join(\"+\");\n}\n\nfunction splitGraphemes(text: string): string[] {\n return [...GRAPHEME_SEGMENTER.segment(text)].map(({ segment }) => segment);\n}\n\nfunction compareTextPositions(first: BtwTextPosition, second: BtwTextPosition): number {\n return first.line === second.line ? first.column - second.column : first.line - second.line;\n}\n\nfunction positionFallsInside(\n line: number,\n column: number,\n range: { start: BtwTextPosition; end: BtwTextPosition },\n): boolean {\n const position = { line, column };\n return compareTextPositions(position, range.start) >= 0 && compareTextPositions(position, range.end) < 0;\n}\n\nfunction fitRows(rows: string[], availableRows: number): string[] {\n if (rows.length <= availableRows) return rows;\n if (availableRows <= 1) return rows.slice(0, 1);\n return [rows[0] ?? \"\", ...rows.slice(rows.length - availableRows + 1)];\n}\n\nfunction escapeBringToMainText(text: string): string {\n return [...text]\n .map((character) => {\n if (character === \"\\n\") return character;\n if (character === \"\\t\") return \" \";\n const code = character.charCodeAt(0);\n if (code <= 31 || (code >= 127 && code <= 159)) {\n return `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n }\n return character;\n })\n .join(\"\")\n .replace(/<btw_context(?=[ \\t\\r\\n>])/g, \"<btw_context\")\n .replace(/<\\/btw_context[ \\t\\r\\n]*>/g, (terminator) => terminator.replaceAll(\"<\", \"<\").replaceAll(\">\", \">\"));\n}\n\nfunction escapeTerminalControls(text: string): string {\n return [...text]\n .map((character) => {\n const code = character.charCodeAt(0);\n if (code <= 31 || (code >= 127 && code <= 159)) {\n return `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n }\n return character;\n })\n .join(\"\");\n}\n", "import { spawn } from \"node:child_process\";\nimport {\n copyToClipboard as copyToHostClipboard,\n type ExtensionCommandContext,\n type KeybindingsManager,\n type Theme,\n} from \"@earendil-works/pi-coding-agent\";\nimport {\n type Component,\n isKeyRelease,\n isKittyProtocolActive,\n Key,\n type OverlayHandle,\n parseKey,\n type TUI,\n TuiAltScreen,\n type TuiInputListener,\n type TuiInputListenerResult,\n truncateToWidth,\n} from \"@earendil-works/pi-tui\";\nimport { type BtwKeybindingOverrides, BtwPasteGuard, resolveBtwShortcuts, setBtwShortcuts } from \"./keybindings.js\";\nimport { formatKeyLabel, sanitizeSingleLine } from \"./text.js\";\n\ntype BtwCustomOptions = Parameters<ExtensionCommandContext[\"ui\"][\"custom\"]>[1];\ntype BtwCustomFactory<T> = (\n tui: TUI,\n theme: Theme,\n keybindings: KeybindingsManager,\n done: (result: T) => void,\n) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>;\n\ntype BtwFullscreenTui = TUI & {\n flash?: (message: string, durationMs?: number) => void;\n setLayoutRoot(component: Component | undefined): void;\n addInputListenerBeforeAll?(listener: TuiInputListener): () => void;\n addInputListenerBeforeViewport?(listener: TuiInputListener): () => void;\n};\n\nexport interface BtwFullscreenLayoutComponent extends Component {\n getFullscreenLayout(): Component;\n}\n\nexport interface BtwFullscreenOptions {\n keybindings?: BtwKeybindingOverrides;\n copyOnSelect?: boolean;\n}\n\nexport type BtwFullscreenTuiFactory = (\n parent: TUI,\n theme: Theme,\n keybindings: KeybindingsManager,\n options: BtwFullscreenOptions,\n) => BtwFullscreenTui;\n\nexport interface BtwFullscreenDependencies {\n createTui?: BtwFullscreenTuiFactory;\n openUrl?: (url: string) => void;\n copyToClipboard?: (text: string) => Promise<void>;\n manualSelectionCopySupported?: boolean;\n}\n\nexport type RunBtwFullscreen = <T>(\n ctx: ExtensionCommandContext,\n run: (ctx: ExtensionCommandContext) => Promise<T>,\n options?: BtwFullscreenOptions,\n) => Promise<T>;\n\ntype FullscreenOutcome<T> = { kind: \"completed\"; value: T } | { kind: \"failed\"; error: unknown };\n\nclass FullscreenUiDisposedError extends Error {\n constructor() {\n super(\"The dedicated pi-btw UI was disposed.\");\n this.name = \"FullscreenUiDisposedError\";\n }\n}\n\nexport async function runBtwFullscreen<T>(\n ctx: ExtensionCommandContext,\n run: (ctx: ExtensionCommandContext) => Promise<T>,\n options: BtwFullscreenOptions = {},\n dependencies: BtwFullscreenDependencies = {},\n): Promise<T> {\n const createTui =\n dependencies.createTui ??\n ((parent: TUI, theme: Theme, keybindings: KeybindingsManager, fullscreenOptions: BtwFullscreenOptions) =>\n createBtwFullscreenTui(\n parent,\n theme,\n keybindings,\n fullscreenOptions.copyOnSelect ?? true,\n dependencies.manualSelectionCopySupported ?? hasManualSelectionCopyApi(),\n dependencies.openUrl ?? openUrlInBrowser,\n dependencies.copyToClipboard ?? copyToHostClipboard,\n ));\n let liveEditorText = ctx.ui.getEditorText();\n let restoreEditor = false;\n let host: BtwFullscreenHost<T> | undefined;\n const outcome = await ctx.ui.custom<FullscreenOutcome<T>>(\n (parent, theme, keybindings, done) => {\n host = new BtwFullscreenHost(\n parent,\n theme,\n keybindings,\n ctx,\n run,\n (value) => {\n try {\n liveEditorText = ctx.ui.getEditorText();\n restoreEditor = true;\n } catch {\n // A replaced session owns a different editor and must not receive stale text.\n }\n done(value);\n },\n createTui,\n options,\n );\n return host;\n },\n {\n overlay: true,\n onHandle: (handle) => host?.setParentOverlay(handle),\n },\n );\n if (restoreEditor) {\n try {\n if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);\n } catch {\n // A replaced session owns a different editor and must not receive stale restoration.\n }\n }\n if (outcome.kind === \"failed\") throw outcome.error;\n return outcome.value;\n}\n\ntype BtwInputListeners = {\n beforeAll: Set<TuiInputListener>;\n beforeViewport: Set<TuiInputListener>;\n regular: Set<TuiInputListener>;\n};\n\nconst btwInputListeners = new WeakMap<BtwTuiAltScreen, BtwInputListeners>();\n\nfunction dispatchBtwInput(listeners: BtwInputListeners, data: string): TuiInputListenerResult {\n let current = data;\n for (const group of [listeners.beforeAll, listeners.beforeViewport, listeners.regular]) {\n for (const listener of group) {\n const result = listener(current);\n if (result?.consume) return result;\n if (result?.data !== undefined) current = result.data;\n }\n }\n return current === data ? undefined : { data: current };\n}\n\nclass BtwTuiAltScreen extends TuiAltScreen {\n hasFocusedOverlay(): boolean {\n return this.isOverlayFocused();\n }\n\n override addInputListener(listener: TuiInputListener): () => void {\n let listeners = btwInputListeners.get(this);\n if (!listeners) {\n const registeredListeners: BtwInputListeners = {\n beforeAll: new Set(),\n beforeViewport: new Set(),\n regular: new Set(),\n };\n btwInputListeners.set(this, registeredListeners);\n super.addInputListener((data) => dispatchBtwInput(registeredListeners, data));\n listeners = registeredListeners;\n }\n listeners.regular.add(listener);\n return () => listeners.regular.delete(listener);\n }\n\n addInputListenerBeforeAll(listener: TuiInputListener): () => void {\n const listeners = btwInputListeners.get(this);\n if (!listeners) return super.addInputListener(listener);\n listeners.beforeAll.add(listener);\n return () => listeners.beforeAll.delete(listener);\n }\n\n addInputListenerBeforeViewport(listener: TuiInputListener): () => void {\n const listeners = btwInputListeners.get(this);\n if (!listeners) return super.addInputListener(listener);\n listeners.beforeViewport.add(listener);\n return () => listeners.beforeViewport.delete(listener);\n }\n\n override removeInputListener(listener: TuiInputListener): void {\n const listeners = btwInputListeners.get(this);\n if (!listeners) {\n super.removeInputListener(listener);\n return;\n }\n listeners.beforeAll.delete(listener);\n listeners.beforeViewport.delete(listener);\n listeners.regular.delete(listener);\n }\n}\n\nconst BRACKETED_PASTE_START = \"\\u001b[200~\";\nconst BRACKETED_PASTE_END = \"\\u001b[201~\";\n\n// TuiAltScreen evaluates these actions before bottom, so shared keys cannot jump to latest.\nconst ALT_SCREEN_ACTIONS_BEFORE_BOTTOM = [\n \"tui.altScreen.search\",\n \"tui.altScreen.searchNext\",\n \"tui.altScreen.searchPrevious\",\n \"tui.altScreen.searchClose\",\n \"tui.altScreen.pageUp\",\n \"tui.altScreen.pageDown\",\n \"tui.altScreen.halfPageUp\",\n \"tui.altScreen.halfPageDown\",\n \"tui.altScreen.lineUp\",\n \"tui.altScreen.lineDown\",\n \"tui.altScreen.previousPrompt\",\n \"tui.altScreen.nextPrompt\",\n \"tui.altScreen.top\",\n] as const;\nconst KEY_MODIFIER_ORDER = [\"shift\", \"ctrl\", \"alt\", \"super\"] as const;\nconst MATCHABLE_SPECIAL_KEYS = new Set([\n \"space\",\n \"tab\",\n \"enter\",\n \"backspace\",\n \"delete\",\n \"insert\",\n \"home\",\n \"end\",\n \"pageup\",\n \"pagedown\",\n \"up\",\n \"down\",\n \"left\",\n \"right\",\n]);\nconst MATCHABLE_SYMBOL_KEYS = new Set(\"`-=[]\\\\;',./!@#$%^&*()_+|~{}:<>?\");\n\nfunction normalizedKeyId(key: string): string {\n const parts = key.toLowerCase().split(\"+\");\n const base = parts.at(-1);\n if (!base) return \"\";\n const normalizedBase = base === \"esc\" ? \"escape\" : base === \"return\" ? \"enter\" : base;\n const modifiers = KEY_MODIFIER_ORDER.filter((modifier) => parts.includes(modifier));\n return [...modifiers, normalizedBase].join(\"+\");\n}\n\nfunction formatEffectiveKeyLabel(key: string): string {\n const parts = key.split(\"+\");\n const base = parts.at(-1);\n if (base === \"pageup\") parts[parts.length - 1] = \"pageUp\";\n if (base === \"pagedown\") parts[parts.length - 1] = \"pageDown\";\n return formatKeyLabel(parts.join(\"+\"));\n}\n\nfunction canMatchKeyInput(key: string): boolean {\n const parts = key.split(\"+\");\n const base = parts.at(-1) ?? \"\";\n const modifiers = parts.slice(0, -1);\n if (base === \"escape\") return modifiers.length === 0;\n if (base === \"clear\") {\n return modifiers.length === 0 || (modifiers.length === 1 && (modifiers[0] === \"shift\" || modifiers[0] === \"ctrl\"));\n }\n if (/^f(?:[1-9]|1[0-2])$/u.test(base)) return modifiers.length === 0;\n return (\n MATCHABLE_SPECIAL_KEYS.has(base) ||\n (base.length === 1 && (/^[a-z0-9]$/u.test(base) || MATCHABLE_SYMBOL_KEYS.has(base)))\n );\n}\n\nfunction rawCtrlInput(base: string): string | undefined {\n if (base.length !== 1) return undefined;\n const rawBase = base === \"-\" ? \"_\" : base;\n if (!\"abcdefghijklmnopqrstuvwxyz[\\\\]_\".includes(rawBase)) return undefined;\n return String.fromCharCode(rawBase.charCodeAt(0) & 0x1f);\n}\n\nfunction legacyRawInput(key: string): string | undefined {\n const parts = key.split(\"+\");\n const base = parts.at(-1) ?? \"\";\n if (parts.length === 2 && parts[0] === \"ctrl\") return rawCtrlInput(base);\n if (isKittyProtocolActive()) return undefined;\n if (parts.length === 2 && parts[0] === \"alt\" && base.length === 1) return `\\u001b${base}`;\n if (parts.length === 3 && parts[0] === \"ctrl\" && parts[1] === \"alt\") {\n const input = rawCtrlInput(base);\n return input ? `\\u001b${input}` : undefined;\n }\n return undefined;\n}\n\n// Mirror matchesKey(), using parseKey() to canonicalize IDs that share legacy raw input.\nfunction keyInputIdentity(key: string): string {\n const identity = normalizedKeyId(key);\n const input = legacyRawInput(identity);\n return input ? normalizedKeyId(parseKey(input) ?? identity) : identity;\n}\n\nfunction hasManualSelectionCopyApi(): boolean {\n return (\n typeof TuiAltScreen.prototype.hasActiveSelection === \"function\" &&\n typeof TuiAltScreen.prototype.copyActiveSelectionToClipboard === \"function\"\n );\n}\n\nfunction createBtwFullscreenTui(\n parent: TUI,\n theme: Theme,\n keybindings: KeybindingsManager,\n copyOnSelect: boolean,\n manualSelectionCopySupported: boolean,\n openUrl: (url: string) => void,\n copyToClipboard: (text: string) => Promise<void>,\n): BtwFullscreenTui {\n if (!copyOnSelect && !manualSelectionCopySupported) {\n throw new Error(\n \"Manual fullscreen selection copying is unavailable in this Pi version; update Pi or enable automatic selection copying.\",\n );\n }\n const styleSearchMatch = (text: string) => theme.bg(\"searchMatchBg\", theme.fg(\"searchMatchText\", text));\n const fullscreen = new BtwTuiAltScreen(parent.terminal, parent.getShowHardwareCursor(), undefined, {\n mouse: true,\n copyOnSelect,\n searchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),\n scrollToEndIndicator: () => {\n const unavailableKeyIdentities = new Set<string>([keyInputIdentity(Key.ctrl(\"c\"))]);\n for (const action of ALT_SCREEN_ACTIONS_BEFORE_BOTTOM) {\n for (const actionKey of keybindings.getKeys(action)) {\n unavailableKeyIdentities.add(keyInputIdentity(String(actionKey)));\n }\n }\n if (!copyOnSelect) {\n for (const copyKey of keybindings.getKeys(\"app.message.copy\")) {\n unavailableKeyIdentities.add(keyInputIdentity(String(copyKey)));\n }\n }\n const key = keybindings\n .getKeys(\"tui.altScreen.bottom\")\n .map((candidate) => keyInputIdentity(String(candidate)))\n .find(\n (identity) =>\n identity &&\n canMatchKeyInput(identity) &&\n !unavailableKeyIdentities.has(identity) &&\n formatEffectiveKeyLabel(identity),\n );\n const label = theme.fg(\"text\", \" \u2193 Jump to latest message\");\n const shortcut = key ? theme.fg(\"muted\", ` \u00B7 ${formatEffectiveKeyLabel(key)}`) : \"\";\n return theme.bg(\"selectedBg\", `${label}${shortcut} `);\n },\n searchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),\n openUrl,\n copySelection: async (text) => {\n try {\n await copyToClipboard(text);\n return true;\n } catch {\n return false;\n }\n },\n });\n if (!copyOnSelect) {\n let isInBracketedPaste = false;\n fullscreen.addInputListenerBeforeViewport((data) => {\n const wasInBracketedPaste = isInBracketedPaste;\n const startsBracketedPaste = data.includes(BRACKETED_PASTE_START);\n if (startsBracketedPaste) isInBracketedPaste = true;\n if (isInBracketedPaste && data.includes(BRACKETED_PASTE_END)) {\n isInBracketedPaste = false;\n }\n if (\n wasInBracketedPaste ||\n startsBracketedPaste ||\n fullscreen.hasFocusedOverlay() ||\n isKeyRelease(data) ||\n !keybindings.matches(data, \"app.message.copy\")\n ) {\n return undefined;\n }\n if (!fullscreen.hasActiveSelection()) {\n fullscreen.flash(\"No selection to copy\");\n return { consume: true };\n }\n void fullscreen.copyActiveSelectionToClipboard().catch(() => fullscreen.flash(\"Copy failed\"));\n return { consume: true };\n });\n }\n return fullscreen;\n}\n\n// Pi does not export its browser opener, so mirror its shell-free launcher for this isolated TUI.\nfunction openUrlInBrowser(target: string): void {\n const [command, args] =\n process.platform === \"darwin\"\n ? [\"open\", [target]]\n : process.platform === \"win32\"\n ? [\"rundll32\", [\"url.dll,FileProtocolHandler\", target]]\n : [\"xdg-open\", [target]];\n spawn(command, args, { stdio: \"ignore\", detached: true })\n .on(\"error\", () => {})\n .unref();\n}\n\nclass BtwFullscreenHost<T> implements Component {\n private fullscreen: BtwFullscreenTui | undefined;\n private parentOverlay: OverlayHandle | undefined;\n private cancelActiveCustom: (() => void) | undefined;\n private hardCancelActiveCustom: (() => void) | undefined;\n private removeHardCancelListener: (() => void) | undefined;\n private removeUpstreamAbortListener: (() => void) | undefined;\n private started = false;\n private disposed = false;\n private finished = false;\n private parentStopped = false;\n private parentRestoreAttempted = false;\n private fullscreenCreated = false;\n private fullscreenStopped = false;\n private parentRestoreQueued = false;\n private parentRestorePromise: Promise<void> | undefined;\n private cleanupError: unknown;\n private readonly lifetimeController = new AbortController();\n\n constructor(\n private readonly parent: TUI,\n private readonly theme: Theme,\n private readonly keybindings: KeybindingsManager,\n private readonly ctx: ExtensionCommandContext,\n private readonly run: (ctx: ExtensionCommandContext) => Promise<T>,\n private readonly done: (outcome: FullscreenOutcome<T>) => void,\n private readonly createTui: BtwFullscreenTuiFactory,\n private readonly options: BtwFullscreenOptions,\n ) {\n queueMicrotask(() => void this.start());\n }\n\n setParentOverlay(overlay: OverlayHandle): void {\n this.parentOverlay = overlay;\n }\n\n render(width: number): string[] {\n return [truncateToWidth(this.theme.fg(\"muted\", \"Opening btw side thread\u2026\"), width)];\n }\n\n invalidate(): void {}\n\n dispose(): void {\n if (this.disposed || this.finished) return;\n this.disposed = true;\n this.lifetimeController.abort();\n this.cancelActiveCustom?.();\n }\n\n private async start(): Promise<void> {\n if (this.started || this.finished) return;\n this.started = true;\n this.watchUpstreamCancellation();\n let outcome: FullscreenOutcome<T>;\n try {\n if (this.disposed) throw new FullscreenUiDisposedError();\n this.parent.stop({ preserveScreen: true });\n this.parentStopped = true;\n if (this.disposed) throw new FullscreenUiDisposedError();\n this.fullscreen = this.createTui(this.parent, this.theme, this.keybindings, this.options);\n this.fullscreenCreated = true;\n this.fullscreen.start();\n const shortcuts = resolveBtwShortcuts(\n this.options.keybindings,\n this.keybindings,\n this.options.copyOnSelect ?? true,\n );\n setBtwShortcuts(this.fullscreen, shortcuts);\n // Negotiate before warning when possible: the first dispatched user input uses\n // the current mode. Recheck each input, including later mode transitions.\n let previousWarnings: readonly string[] = [];\n const reportWarnings = () => {\n const warnings = shortcuts.warnings;\n for (const warning of warnings) {\n if (previousWarnings.includes(warning)) continue;\n try {\n this.ctx.ui.notify(`Pi BTW: ${warning}`, \"warning\");\n } catch {\n /* A replaced context must not prevent terminal cleanup. */\n }\n }\n previousWarnings = warnings;\n };\n const pasteGuard = new BtwPasteGuard();\n // Waiting for the custom promise would leave follow-up keys bound to the side TUI.\n const addHardCancelListener =\n this.fullscreen.addInputListenerBeforeAll?.bind(this.fullscreen) ??\n this.fullscreen.addInputListenerBeforeViewport?.bind(this.fullscreen) ??\n this.fullscreen.addInputListener.bind(this.fullscreen);\n this.removeHardCancelListener = addHardCancelListener((data) => {\n reportWarnings();\n if (pasteGuard.consume(data) || !shortcuts.matches(data, \"exit\")) return undefined;\n this.disposed = true;\n this.lifetimeController.abort();\n try {\n this.hardCancelActiveCustom?.();\n } finally {\n // ProcessTerminal.stop() destroys its active input buffer. Keep cancellation\n // synchronous, then drain input before the physical Windows terminal handoff.\n // Pi has no public input injection, so do not replay bytes already coalesced\n // behind the hard-cancel key.\n this.queueParentRestore();\n }\n return { consume: true };\n });\n outcome = { kind: \"completed\", value: await this.run(this.createContext()) };\n } catch (error) {\n outcome = { kind: \"failed\", error };\n }\n\n try {\n this.cancelActiveCustom?.();\n } catch (error) {\n this.cleanupError ??= error;\n }\n if (this.parentRestorePromise) await this.parentRestorePromise;\n else this.restoreParent();\n if (this.cleanupError !== undefined) outcome = { kind: \"failed\", error: this.cleanupError };\n this.finished = true;\n this.done(outcome);\n }\n\n private watchUpstreamCancellation(): void {\n const signal = this.ctx.signal;\n if (!signal) return;\n const onAbort = () => this.dispose();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n this.removeUpstreamAbortListener = () => signal.removeEventListener(\"abort\", onAbort);\n if (signal.aborted) onAbort();\n }\n\n private queueParentRestore(): void {\n if (this.parentRestoreQueued || this.parentRestoreAttempted) return;\n this.parentRestoreQueued = true;\n this.parentRestorePromise = Promise.resolve().then(async () => {\n try {\n await this.fullscreen?.terminal.drainInput?.();\n } catch (error) {\n this.cleanupError ??= error;\n }\n this.parentRestoreQueued = false;\n this.restoreParent();\n });\n }\n\n private restoreParent(): void {\n const removeUpstreamAbortListener = this.removeUpstreamAbortListener;\n this.removeUpstreamAbortListener = undefined;\n try {\n removeUpstreamAbortListener?.();\n } catch (error) {\n this.cleanupError ??= error;\n }\n const removeHardCancelListener = this.removeHardCancelListener;\n this.removeHardCancelListener = undefined;\n try {\n removeHardCancelListener?.();\n } catch (error) {\n this.cleanupError ??= error;\n }\n if (this.fullscreenCreated && !this.fullscreenStopped) {\n this.fullscreenStopped = true;\n try {\n this.fullscreen?.stop({ preserveScreen: true });\n } catch (error) {\n this.cleanupError ??= error;\n }\n }\n if (!this.parentStopped || this.parentRestoreAttempted) return;\n const parentOverlay = this.parentOverlay;\n this.parentOverlay = undefined;\n try {\n parentOverlay?.setHidden(true);\n } catch (error) {\n this.cleanupError ??= error;\n }\n try {\n this.parentRestoreAttempted = true;\n this.parent.start();\n this.parent.renderNow(false);\n } catch (error) {\n this.cleanupError ??= error;\n }\n }\n\n private createContext(): ExtensionCommandContext {\n const ui = new Proxy(this.ctx.ui, {\n get: (target, property) => {\n if (property === \"custom\") {\n return <Value>(factory: BtwCustomFactory<Value>, options?: BtwCustomOptions) =>\n this.showCustom(factory, options);\n }\n if (property === \"notify\") {\n return (message: string, level?: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1]) => {\n target.notify(message, level);\n const display = sanitizeSingleLine(message);\n if (display) this.fullscreen?.flash?.(display);\n };\n }\n const value = Reflect.get(target, property, target) as unknown;\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n const signal = this.ctx.signal\n ? AbortSignal.any([this.ctx.signal, this.lifetimeController.signal])\n : this.lifetimeController.signal;\n return new Proxy(this.ctx, {\n get: (target, property) => {\n if (property === \"ui\") return ui;\n if (property === \"signal\") return signal;\n return Reflect.get(target, property, target);\n },\n });\n }\n\n private showCustom<Value>(factory: BtwCustomFactory<Value>, options?: BtwCustomOptions): Promise<Value> {\n const fullscreen = this.fullscreen;\n if (!fullscreen || this.disposed || this.finished) {\n return Promise.reject(new FullscreenUiDisposedError());\n }\n if (this.cancelActiveCustom) {\n return Promise.reject(new Error(\"pi-btw attempted to open overlapping custom UI.\"));\n }\n\n return new Promise<Value>((resolve, reject) => {\n let component: (Component & { dispose?(): void }) | undefined;\n let overlay: OverlayHandle | undefined;\n let mounted = false;\n let layoutMounted = false;\n let factorySettled = false;\n let closed = false;\n let promiseSettled = false;\n let componentDisposed = false;\n let pendingValue: Value | undefined;\n let hasPendingValue = false;\n\n const disposeComponent = () => {\n if (!component || componentDisposed) return;\n componentDisposed = true;\n try {\n component.dispose?.();\n } catch {\n // Cleanup must continue so terminal ownership is restored.\n }\n };\n const unmount = () => {\n let cleanupError: unknown;\n try {\n if (overlay) overlay.hide();\n else if (mounted && layoutMounted) fullscreen.setLayoutRoot(undefined);\n else if (mounted && component) fullscreen.removeChild(component);\n } catch (error) {\n cleanupError = error;\n }\n if (overlay || mounted) {\n try {\n fullscreen.setFocus(null);\n fullscreen.requestRender();\n } catch (error) {\n cleanupError ??= error;\n }\n }\n disposeComponent();\n if (cleanupError !== undefined) throw cleanupError;\n };\n const complete = () => {\n if (promiseSettled || !hasPendingValue) return;\n promiseSettled = true;\n this.cancelActiveCustom = undefined;\n this.hardCancelActiveCustom = undefined;\n if (!factorySettled) {\n resolve(pendingValue as Value);\n return;\n }\n try {\n unmount();\n resolve(pendingValue as Value);\n } catch (error) {\n reject(error);\n }\n };\n const close = (value: Value) => {\n if (closed || promiseSettled) return;\n closed = true;\n pendingValue = value;\n hasPendingValue = true;\n complete();\n };\n const fail = (error: unknown) => {\n if (promiseSettled) return;\n closed = true;\n promiseSettled = true;\n this.cancelActiveCustom = undefined;\n this.hardCancelActiveCustom = undefined;\n try {\n unmount();\n reject(error);\n } catch (cleanupError) {\n reject(cleanupError);\n }\n };\n this.cancelActiveCustom = () => {\n if (promiseSettled) return;\n disposeComponent();\n if (!promiseSettled) fail(new FullscreenUiDisposedError());\n };\n this.hardCancelActiveCustom = () => {\n if (promiseSettled) return;\n try {\n component?.handleInput?.(\"\\u0003\");\n } catch (error) {\n fail(error);\n return;\n }\n this.cancelActiveCustom?.();\n };\n\n let created: ReturnType<BtwCustomFactory<Value>>;\n try {\n created = factory(fullscreen, this.theme, this.keybindings, close);\n } catch (error) {\n factorySettled = true;\n fail(error);\n return;\n }\n Promise.resolve(created)\n .then((value) => {\n component = value;\n factorySettled = true;\n if (promiseSettled) {\n disposeComponent();\n return;\n }\n if (closed) {\n complete();\n return;\n }\n if (options?.overlay) {\n const overlayOptions =\n typeof options.overlayOptions === \"function\" ? options.overlayOptions() : options.overlayOptions;\n overlay = fullscreen.showOverlay(component, overlayOptions);\n options.onHandle?.(overlay);\n } else {\n fullscreen.clear();\n mounted = true;\n if (isFullscreenLayoutComponent(component)) {\n layoutMounted = true;\n fullscreen.setLayoutRoot(component.getFullscreenLayout());\n } else {\n fullscreen.addChild(component);\n }\n fullscreen.setFocus(component);\n fullscreen.requestRender();\n }\n })\n .catch(fail);\n });\n }\n}\n\nfunction isFullscreenLayoutComponent(component: Component): component is BtwFullscreenLayoutComponent {\n return \"getFullscreenLayout\" in component && typeof component.getFullscreenLayout === \"function\";\n}\n", "import {\n isKeyRelease,\n isKittyProtocolActive,\n KeybindingsManager,\n type KeyId,\n matchesKey,\n type TUI,\n TUI_KEYBINDINGS,\n} from \"@earendil-works/pi-tui\";\nimport { formatKeyLabel } from \"./text.js\";\n\nexport const BTW_SHORTCUT_ACTIONS = [\"exit\", \"cycleThinkingLevel\", \"bringToMain\"] as const;\nexport type BtwShortcutAction = (typeof BTW_SHORTCUT_ACTIONS)[number];\nexport type BtwKeybindingOverrides = Partial<Record<BtwShortcutAction, string>>;\n\nconst MODIFIERS = [\"shift\", \"alt\", \"ctrl\", \"super\"] as const;\nconst SYMBOLS = \"`-=[]\\\\;',./!@#$%^&*()_|~{}:<>?\";\nconst SPECIAL: Record<string, number> = {\n escape: 27,\n tab: 9,\n enter: 13,\n space: 32,\n backspace: 127,\n insert: 57425,\n delete: 57426,\n home: 57423,\n end: 57424,\n pageup: 57421,\n pagedown: 57422,\n left: 57417,\n right: 57418,\n up: 57419,\n down: 57420,\n};\nconst FUNCTION_INPUTS = [\"OP\", \"OQ\", \"OR\", \"OS\", \"[15~\", \"[17~\", \"[18~\", \"[19~\", \"[20~\", \"[21~\", \"[23~\", \"[24~\"];\n// All cross-identity legacy collisions in Pi's matchesKey(): raw Ctrl bytes,\n// ESC-prefixed bytes (including Alt+arrows), BS/DEL, Enter and Shift+Tab.\n// CSI-u, keypad, lock bits, shifted letters and modifyOtherKeys normalize to\n// the same key+modifiers; probe that identity instead of duplicating the parser.\nconst LEGACY_INPUTS = [\n ...Array.from({ length: 128 }, (_, code) => String.fromCharCode(code)),\n ...Array.from({ length: 128 }, (_, code) => `\\u001b${String.fromCharCode(code)}`),\n \"\\u001b[Z\",\n \"\\u001bOM\",\n \"\\u001b[E\",\n \"\\u001b[e\",\n \"\\u001bOe\",\n ...FUNCTION_INPUTS.map((suffix) => `\\u001b${suffix}`),\n];\n\n/** Strict settings syntax; Pi itself ignores unknown/duplicate modifier tokens. */\nexport function normalizeBtwKey(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length > 80 || /[\\s\\p{Cc}]/u.test(value)) return undefined;\n const parts = value.toLowerCase().split(\"+\");\n let base = parts.pop();\n if (!base) return undefined;\n if (base === \"esc\") base = \"escape\";\n if (base === \"return\") base = \"enter\";\n if (new Set(parts).size !== parts.length || parts.some((part) => !MODIFIERS.includes(part as never)))\n return undefined;\n if (\n !Object.hasOwn(SPECIAL, base) &&\n base !== \"clear\" &&\n !/^f(?:[1-9]|1[0-2])$/u.test(base) &&\n !(base.length === 1 && (/^[a-z0-9]$/u.test(base) || SYMBOLS.includes(base)))\n )\n return undefined;\n if ((base === \"escape\" || (base.startsWith(\"f\") && base.length > 1)) && parts.length) return undefined;\n if (base === \"clear\" && (parts.length > 1 || (parts.length === 1 && ![\"ctrl\", \"shift\"].includes(parts[0] ?? \"\"))))\n return undefined;\n return [...MODIFIERS.filter((part) => parts.includes(part)), base].join(\"+\");\n}\n\n/** Representative inputs are checked by Pi, including its live terminal-mode branches. */\nfunction inputsFor(key: string): string[] {\n const parts = key.split(\"+\");\n const base = parts.pop() ?? \"\";\n const modifier = MODIFIERS.reduce((mask, part, bit) => mask | (parts.includes(part) ? 1 << bit : 0), 0);\n const code = SPECIAL[base] ?? (base.length === 1 ? base.charCodeAt(0) : undefined);\n const inputs = code === undefined ? LEGACY_INPUTS : [...LEGACY_INPUTS, `\\u001b[${code};${modifier + 1}u`];\n return inputs.filter((input) => matchesKey(input, key as KeyId));\n}\n\nexport function btwKeysOverlap(first: string, second: string): boolean {\n const normalized = normalizeBtwKey(first);\n return normalized !== undefined && inputsFor(normalized).some((input) => matchesKey(input, second as KeyId));\n}\n\nexport interface BtwShortcuts {\n keys: Record<BtwShortcutAction, readonly string[]>;\n warnings: readonly string[];\n matches(data: string, action: BtwShortcutAction): boolean;\n label(action: BtwShortcutAction): string;\n}\n\nfunction reservedKeys(keybindings: KeybindingsManager, copyOnSelect: boolean): string[] {\n // Editor has no autocomplete provider here. Select bindings are still reserved\n // because exit also applies to BTW-owned nested review/menu components.\n return [\n \"ctrl+c\",\n \"shift+backspace\",\n \"shift+delete\",\n \"shift+space\",\n // Exact-range review uses these fixed selection actions even if Editor is remapped.\n \"shift+left\",\n \"shift+right\",\n \"shift+up\",\n \"shift+down\",\n \"left\",\n \"right\",\n \"enter\",\n \"alt+enter\",\n \"ctrl+j\",\n \"pageUp\",\n \"pageDown\",\n ...Object.keys(TUI_KEYBINDINGS).flatMap((id) => keybindings.getKeys(id as keyof typeof TUI_KEYBINDINGS)),\n ...(!copyOnSelect ? keybindings.getKeys(\"app.message.copy\") : []),\n ];\n}\n\nfunction isTextKey(key: string): boolean {\n const parts = key.split(\"+\");\n const base = parts.at(-1) ?? \"\";\n return (base.length === 1 || base === \"space\") && !parts.some((part) => [\"ctrl\", \"alt\", \"super\"].includes(part));\n}\n\nexport function resolveBtwShortcuts(\n overrides: BtwKeybindingOverrides = {},\n keybindings: KeybindingsManager,\n copyOnSelect = true,\n): BtwShortcuts {\n let mode = isKittyProtocolActive();\n let snapshot = resolveShortcutSnapshot(overrides, keybindings, copyOnSelect);\n const current = () => {\n if (mode !== isKittyProtocolActive()) {\n mode = isKittyProtocolActive();\n snapshot = resolveShortcutSnapshot(overrides, keybindings, copyOnSelect);\n }\n return snapshot;\n };\n // ProcessTerminal negotiates Kitty asynchronously after the dedicated TUI starts.\n // Hints and matching must use the same policy after that mode transition.\n return {\n get keys() {\n return current().keys;\n },\n get warnings() {\n return current().warnings;\n },\n matches: (data, action) => current().matches(data, action),\n label: (action) => current().label(action),\n };\n}\n\nfunction resolveShortcutSnapshot(\n overrides: BtwKeybindingOverrides = {},\n keybindings: KeybindingsManager,\n copyOnSelect = true,\n): BtwShortcuts {\n const reserved = reservedKeys(keybindings, copyOnSelect);\n const keys: BtwShortcuts[\"keys\"] = { exit: [\"ctrl+c\"], cycleThinkingLevel: [], bringToMain: [] };\n const warnings: string[] = [];\n const defaults: Record<BtwShortcutAction, readonly string[]> = {\n exit: [\"ctrl+c\"],\n cycleThinkingLevel: keybindings.getKeys(\"app.thinking.cycle\"),\n bringToMain: [\"ctrl+r\"],\n };\n const usable = (action: BtwShortcutAction, candidate: string, inherited = false): string | undefined => {\n const key = normalizeBtwKey(candidate);\n if (!key || (!inherited && isTextKey(key))) return undefined;\n const inputs = inputsFor(key);\n if (!inputs.length) return undefined;\n if (action === \"exit\" && key === \"ctrl+c\") return key;\n if (\n reserved.some((other) => typeof other === \"string\" && inputs.some((input) => matchesKey(input, other as KeyId)))\n )\n return undefined;\n return key;\n };\n const candidates: BtwKeybindingOverrides = {};\n const availableDefaults = { ...defaults };\n for (const action of BTW_SHORTCUT_ACTIONS) {\n availableDefaults[action] = defaults[action]\n .map((key) => usable(action, key, action === \"cycleThinkingLevel\"))\n .filter((key): key is string => key !== undefined);\n const override = overrides[action];\n if (override !== undefined) candidates[action] = usable(action, override);\n }\n // Compare the complete proposal, not only actions visited earlier. Reject conflicts\n // together, then repeat because a rejected override restores its default bindings.\n for (;;) {\n const rejected = BTW_SHORTCUT_ACTIONS.filter((action) => {\n const candidate = candidates[action];\n return (\n candidate !== undefined &&\n BTW_SHORTCUT_ACTIONS.some(\n (other) =>\n other !== action &&\n (candidates[other] ? [candidates[other]] : availableDefaults[other]).some((key) =>\n btwKeysOverlap(candidate, key),\n ),\n )\n );\n });\n if (!rejected.length) break;\n for (const action of rejected) delete candidates[action];\n }\n for (const action of BTW_SHORTCUT_ACTIONS) {\n const override = overrides[action];\n const selected = candidates[action];\n if (override !== undefined && !selected)\n warnings.push(\n `${action}: configured shortcut is invalid or conflicts with a reserved action; using an available default.`,\n );\n const effective = selected\n ? [selected]\n : availableDefaults[action].filter(\n (key) =>\n !BTW_SHORTCUT_ACTIONS.some(\n (other) => other !== action && keys[other].some((used) => btwKeysOverlap(key, used)),\n ),\n );\n keys[action] = action === \"exit\" ? [...new Set([...effective, \"ctrl+c\"])] : effective;\n if (!keys[action].length && (override !== undefined || defaults[action].length > 0))\n warnings.push(`${action}: no usable shortcut; change Pi BTW Settings or Pi keybindings.`);\n }\n return {\n keys,\n warnings,\n matches: (data, action) => !isKeyRelease(data) && keys[action].some((key) => matchesKey(data, key as KeyId)),\n label: (action) => (keys[action].length ? formatKeyLabel(keys[action][0] ?? \"\") : \"Unavailable\"),\n };\n}\n\nexport function validateBtwShortcutEdit(\n action: BtwShortcutAction,\n value: string | undefined,\n overrides: BtwKeybindingOverrides,\n keybindings: KeybindingsManager,\n copyOnSelect: boolean,\n): string | undefined {\n // Reset must remain available even when several existing overrides conflict.\n if (value === undefined) return undefined;\n if (!normalizeBtwKey(value)) return \"Invalid key combination. Use a Pi key name such as ctrl+q or f6.\";\n const next = { ...overrides, [action]: value };\n const resolved = resolveBtwShortcuts(next, keybindings, copyOnSelect);\n const previous = resolveBtwShortcuts(overrides, keybindings, copyOnSelect);\n // Reject edits that disable another binding as well as the edited binding.\n for (const item of BTW_SHORTCUT_ACTIONS) {\n if (\n (item === action && !resolved.keys[item].includes(normalizeBtwKey(value) ?? \"\")) ||\n (item !== action && previous.keys[item].some((key) => !resolved.keys[item].includes(key)))\n ) {\n return `${item} conflicts with another BTW shortcut, editing, selection, search, scrolling, or copying. Choose a different key.`;\n }\n }\n return undefined;\n}\n\nconst bindingsByTui = new WeakMap<TUI, BtwShortcuts>();\nexport function setBtwShortcuts(tui: TUI, shortcuts: BtwShortcuts): void {\n bindingsByTui.set(tui, shortcuts);\n}\nexport function getBtwShortcuts(tui: TUI, keybindings?: KeybindingsManager): BtwShortcuts {\n return (\n bindingsByTui.get(tui) ??\n resolveBtwShortcuts(\n {},\n keybindings ??\n new KeybindingsManager({\n ...TUI_KEYBINDINGS,\n \"app.thinking.cycle\": { defaultKeys: \"shift+tab\" },\n }),\n )\n );\n}\n\n/** Keep split bracketed-paste payloads away from screen-level shortcuts. */\nexport class BtwPasteGuard {\n private active = false;\n consume(data: string): boolean {\n const wasActive = this.active;\n const starts = data.includes(\"\\u001b[200~\");\n if (starts) this.active = true;\n if (this.active && data.includes(\"\\u001b[201~\")) this.active = false;\n return wasActive || starts;\n }\n}\n", "export function sanitizeSingleLine(text: string): string {\n return [...text.replace(/[\\r\\n\\t]/gu, \" \")]\n .filter((character) => {\n const code = character.charCodeAt(0);\n return code > 31 && (code < 127 || code > 159);\n })\n .join(\"\")\n .replace(/ +/gu, \" \")\n .trim();\n}\n\nexport function formatKeyLabel(key: string): string {\n const sanitized = sanitizeSingleLine(key);\n if (!sanitized) return \"\";\n return sanitized\n .split(\"+\")\n .map((part) => {\n const lower = part.toLowerCase();\n if (lower === \"shift\") return \"Shift\";\n if (lower === \"ctrl\") return \"Ctrl\";\n if (lower === \"alt\") return \"Alt\";\n if (lower === \"super\") return \"Super\";\n return part.length === 1 ? part.toUpperCase() : `${part[0]?.toUpperCase() ?? \"\"}${part.slice(1)}`;\n })\n .join(\"+\");\n}\n", "import {\n copyToClipboard,\n type ExtensionAPI,\n type ExtensionCommandContext,\n type SessionEntry,\n type SessionTreeNode,\n TreeSelectorComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport { type Component, type Focusable, Key, matchesKey } from \"@earendil-works/pi-tui\";\nimport { showBtwCustomPreservingEditor } from \"./menu.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\n\nexport type MainEntryPickResult = { kind: \"selected\"; entryId: string } | { kind: \"back\" } | { kind: \"closed\" };\n\nexport interface MainThreadTreeSelector extends Component, Focusable {\n onCopy?: (text: string | undefined) => void;\n setViewLabel?(entryId: string, label: string | undefined, labelTimestamp?: string): void;\n dispose?(): void;\n}\n\nexport interface MainThreadTreeSelectorOptions {\n tree: SessionTreeNode[];\n currentLeafId: string | null;\n terminalRows: number;\n onSelect: (entryId: string) => void;\n onCancel: () => void;\n onCopy: (entryId: string | undefined, displayText: string | undefined) => void;\n onLabelChange: (entryId: string, label: string | undefined) => void;\n}\n\nexport interface MainThreadTreePickerDependencies {\n createSelector?: (options: MainThreadTreeSelectorOptions) => MainThreadTreeSelector;\n copyToClipboard?: (text: string, signal: AbortSignal) => Promise<void>;\n}\n\nclass MainThreadTreePickerComponent implements Component, Focusable {\n constructor(\n private readonly selector: MainThreadTreeSelector,\n private readonly onClose: () => void,\n ) {}\n\n get focused(): boolean {\n return this.selector.focused;\n }\n\n set focused(value: boolean) {\n this.selector.focused = value;\n }\n\n get wantsKeyRelease(): boolean | undefined {\n return this.selector.wantsKeyRelease;\n }\n\n render(width: number): string[] {\n return this.selector.render(width);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, Key.ctrl(\"c\"))) {\n this.onClose();\n return;\n }\n this.selector.handleInput?.(data);\n }\n\n invalidate(): void {\n this.selector.invalidate();\n }\n\n dispose(): void {\n this.selector.dispose?.();\n this.onClose();\n }\n}\n\nexport async function pickMainEntry(\n pi: ExtensionAPI,\n ctx: ExtensionCommandContext,\n dependencies: MainThreadTreePickerDependencies = {},\n): Promise<MainEntryPickResult> {\n let rawTree: SessionTreeNode[];\n let currentLeafId: string | null;\n try {\n rawTree = ctx.sessionManager.getTree();\n currentLeafId = ctx.sessionManager.getLeafId();\n } catch {\n return { kind: \"closed\" };\n }\n\n if (rawTree.length === 0) {\n notifySafely(ctx, \"No main-thread entries are available\", \"warning\");\n return { kind: \"back\" };\n }\n\n const tree = sanitizeTreeForDisplay(rawTree);\n const rawCopyText = collectRawCopyText(rawTree);\n const savedLabels = collectSavedLabels(rawTree);\n const createSelector = dependencies.createSelector ?? createNativeTreeSelector;\n const copy = dependencies.copyToClipboard ?? copyText;\n const copyControllers = new Set<AbortController>();\n const copyTasks = new Set<Promise<void>>();\n const abortCopies = () => {\n for (const controller of copyControllers) {\n controller.abort(new Error(\"The main-thread tree picker closed\"));\n }\n };\n const result = await showBtwCustomPreservingEditor<MainEntryPickResult>(ctx, (tui, _theme, _keybindings, done) => {\n let settled = false;\n let selector: MainThreadTreeSelector | undefined;\n const finish = (value: MainEntryPickResult) => {\n if (settled) return;\n settled = true;\n abortCopies();\n done(value);\n };\n const onCopy = (entryId: string | undefined, displayText: string | undefined) => {\n if (settled) return;\n const text = entryId ? rawCopyText.get(entryId) : displayText;\n if (!text) {\n notifySafely(ctx, \"Selected entry has no text to copy\", \"warning\");\n return;\n }\n const controller = new AbortController();\n copyControllers.add(controller);\n let operation: Promise<void>;\n try {\n operation = copy(text, controller.signal);\n } catch (error: unknown) {\n operation = Promise.reject(error);\n }\n let task!: Promise<void>;\n task = operation\n .then(() => {\n if (!settled) notifySafely(ctx, \"Copied selected message\", \"info\");\n })\n .catch((error: unknown) => {\n if (!settled && !controller.signal.aborted) {\n notifySafely(ctx, `Could not copy selected message: ${formatError(error)}`, \"error\");\n }\n })\n .finally(() => {\n copyControllers.delete(controller);\n copyTasks.delete(task);\n });\n copyTasks.add(task);\n };\n const restoreLabel = (entryId: string) => {\n const previous = savedLabels.get(entryId);\n selector?.setViewLabel?.(entryId, previous?.label, previous?.labelTimestamp);\n tui.requestRender();\n };\n const onLabelChange = (entryId: string, label: string | undefined) => {\n if (settled) return;\n try {\n if (!ctx.sessionManager.getEntry(entryId)) {\n restoreLabel(entryId);\n notifySafely(ctx, \"The selected main-thread entry is no longer available\", \"warning\");\n return;\n }\n const persistedLabel = label === undefined ? undefined : sanitizeSingleLine(label);\n pi.setLabel(entryId, persistedLabel);\n savedLabels.set(entryId, { label: persistedLabel });\n selector?.setViewLabel?.(entryId, persistedLabel);\n tui.requestRender();\n } catch (error: unknown) {\n restoreLabel(entryId);\n notifySafely(ctx, `Could not update tree label: ${formatError(error)}`, \"error\");\n }\n };\n selector = createSelector({\n tree,\n currentLeafId,\n terminalRows: tui.terminal.rows,\n onSelect: (entryId) => finish({ kind: \"selected\", entryId }),\n onCancel: () => finish({ kind: \"back\" }),\n onCopy,\n onLabelChange,\n });\n return new MainThreadTreePickerComponent(selector, () => finish({ kind: \"closed\" }));\n });\n abortCopies();\n await Promise.allSettled([...copyTasks]);\n\n return result ?? { kind: \"closed\" };\n}\n\nfunction createNativeTreeSelector(options: MainThreadTreeSelectorOptions): MainThreadTreeSelector {\n const selector = new TreeSelectorComponent(\n options.tree,\n options.currentLeafId,\n options.terminalRows,\n options.onSelect,\n options.onCancel,\n options.onLabelChange,\n );\n selector.onCopy = (displayText) => options.onCopy(selector.getTreeList().getSelectedNode()?.entry.id, displayText);\n const result = selector as MainThreadTreeSelector;\n result.setViewLabel = (entryId, label, labelTimestamp) =>\n selector.getTreeList().updateNodeLabel(entryId, label, labelTimestamp);\n return result;\n}\n\nfunction sanitizeTreeForDisplay(tree: readonly SessionTreeNode[]): SessionTreeNode[] {\n return tree.map((node) => {\n const result: SessionTreeNode = {\n entry: sanitizeEntryForDisplay(node.entry),\n children: sanitizeTreeForDisplay(node.children),\n };\n if (node.label !== undefined) result.label = sanitizeSingleLine(node.label);\n if (node.labelTimestamp !== undefined) {\n result.labelTimestamp = sanitizeSingleLine(node.labelTimestamp);\n }\n return result;\n });\n}\n\nfunction sanitizeEntryForDisplay(entry: SessionEntry): SessionEntry {\n switch (entry.type) {\n case \"message\": {\n const message = { ...entry.message } as Record<string, unknown>;\n if (\"content\" in entry.message) message.content = sanitizeDisplayContent(entry.message.content);\n for (const key of [\"role\", \"errorMessage\", \"command\", \"toolName\"] as const) {\n const value = message[key];\n if (typeof value === \"string\") message[key] = sanitizeSingleLine(value);\n }\n return { ...entry, message } as unknown as SessionEntry;\n }\n case \"custom_message\":\n return {\n ...entry,\n customType: sanitizeSingleLine(entry.customType),\n content: sanitizeDisplayContent(entry.content) as typeof entry.content,\n };\n case \"compaction\":\n return { ...entry, summary: sanitizeSingleLine(entry.summary) };\n case \"branch_summary\":\n return { ...entry, summary: sanitizeSingleLine(entry.summary) };\n case \"model_change\":\n return {\n ...entry,\n provider: sanitizeSingleLine(entry.provider),\n modelId: sanitizeSingleLine(entry.modelId),\n };\n case \"thinking_level_change\":\n return { ...entry, thinkingLevel: sanitizeSingleLine(entry.thinkingLevel) };\n case \"custom\":\n return { ...entry, customType: sanitizeSingleLine(entry.customType) };\n case \"label\":\n return {\n ...entry,\n label: entry.label === undefined ? undefined : sanitizeSingleLine(entry.label),\n };\n case \"session_info\":\n return {\n ...entry,\n name: entry.name === undefined ? undefined : sanitizeSingleLine(entry.name),\n };\n }\n}\n\nfunction sanitizeDisplayContent(content: unknown): unknown {\n if (typeof content === \"string\") return sanitizeSingleLine(content);\n if (!Array.isArray(content)) return content;\n return content.map((block) => {\n if (block === null || typeof block !== \"object\" || !(\"type\" in block)) return block;\n if (block.type === \"text\" && \"text\" in block && typeof block.text === \"string\") {\n return { ...block, text: sanitizeSingleLine(block.text) };\n }\n if (block.type === \"toolCall\") {\n const copy = { ...block } as Record<string, unknown>;\n if (typeof copy.name === \"string\") copy.name = sanitizeSingleLine(copy.name);\n copy.arguments = sanitizeToolArguments(copy.arguments, new WeakMap());\n return copy;\n }\n return block;\n });\n}\n\nfunction sanitizeToolArguments(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (typeof value === \"string\") return sanitizeSingleLine(value);\n if (value === null || typeof value !== \"object\") return value;\n const existing = seen.get(value);\n if (existing !== undefined) return existing;\n if (Array.isArray(value)) {\n const result: unknown[] = [];\n seen.set(value, result);\n for (const item of value) result.push(sanitizeToolArguments(item, seen));\n return result;\n }\n const result: Record<string, unknown> = {};\n seen.set(value, result);\n for (const [key, item] of Object.entries(value)) {\n result[key] = sanitizeToolArguments(item, seen);\n }\n return result;\n}\n\nfunction collectRawCopyText(tree: readonly SessionTreeNode[]): Map<string, string> {\n const result = new Map<string, string>();\n const visit = (nodes: readonly SessionTreeNode[]) => {\n for (const node of nodes) {\n const text = getRawCopyText(node.entry);\n if (text !== undefined) result.set(node.entry.id, text);\n visit(node.children);\n }\n };\n visit(tree);\n return result;\n}\n\nfunction getRawCopyText(entry: SessionEntry): string | undefined {\n let text: string | undefined;\n if (entry.type === \"message\") {\n if (entry.message.role === \"bashExecution\") text = entry.message.command;\n else if (\"content\" in entry.message) {\n text = extractRawText(entry.message.content);\n if (!text && entry.message.role === \"assistant\") text = entry.message.errorMessage;\n }\n } else if (entry.type === \"custom_message\") text = extractRawText(entry.content);\n else if (entry.type === \"compaction\" || entry.type === \"branch_summary\") text = entry.summary;\n return text?.trim() ? text : undefined;\n}\n\nfunction extractRawText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .filter(\n (block): block is { type: \"text\"; text: string } =>\n block !== null &&\n typeof block === \"object\" &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\",\n )\n .map((block) => block.text)\n .join(\"\");\n}\n\ninterface SavedLabel {\n label: string | undefined;\n labelTimestamp?: string;\n}\n\nfunction collectSavedLabels(tree: readonly SessionTreeNode[]): Map<string, SavedLabel> {\n const result = new Map<string, SavedLabel>();\n const visit = (nodes: readonly SessionTreeNode[]) => {\n for (const node of nodes) {\n result.set(node.entry.id, {\n label: node.label === undefined ? undefined : sanitizeSingleLine(node.label),\n labelTimestamp: node.labelTimestamp === undefined ? undefined : sanitizeSingleLine(node.labelTimestamp),\n });\n visit(node.children);\n }\n };\n visit(tree);\n return result;\n}\n\nasync function copyText(text: string, signal: AbortSignal): Promise<void> {\n signal.throwIfAborted();\n await copyToClipboard(text);\n signal.throwIfAborted();\n}\n\nfunction notifySafely(\n ctx: ExtensionCommandContext,\n message: string,\n level: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n try {\n ctx.ui.notify(sanitizeSingleLine(message), level);\n } catch {\n // The command context may have been replaced while the selector was open.\n }\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { mkdir, open, rename, rm, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport { BTW_SHORTCUT_ACTIONS, type BtwKeybindingOverrides, normalizeBtwKey } from \"./keybindings.js\";\nimport { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\n\nexport const BTW_SETTINGS_FILE = \"pi-btw.json\";\nexport const DEFAULT_FULLSCREEN_COPY_ON_SELECT = true;\nexport const DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES = true;\nconst MAX_SETTINGS_BYTES = 64 * 1024;\n\nexport interface BtwSettings {\n keybindings?: BtwKeybindingOverrides;\n model?: string;\n thinkingLevel?: BtwThinkingLevel;\n rememberThinkingLevelChanges?: boolean;\n fullscreenCopyOnSelect?: boolean;\n}\n\nexport type BtwSettingsLoadResult =\n | { kind: \"missing\" }\n | { kind: \"invalid\"; reason: string }\n | { kind: \"loaded\"; settings: BtwSettings };\n\nexport interface BtwSettingsPatch {\n keybindings?: BtwKeybindingOverrides;\n thinkingLevel?: BtwThinkingLevel;\n rememberThinkingLevelChanges?: boolean;\n fullscreenCopyOnSelect?: boolean;\n}\n\nexport interface UpdateBtwSettingsOptions {\n /** Validate against the latest document inside the mutation queue, before applying the patch. */\n validateCurrent?: (settings: BtwSettings) => void;\n settingsPath?: string;\n signal?: AbortSignal;\n beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;\n}\n\ntype SettingsDocument = Record<string, unknown>;\n\nconst mutationQueues = new Map<string, Promise<void>>();\n\nexport function btwSettingsPath(): string {\n return join(getAgentDir(), BTW_SETTINGS_FILE);\n}\n\nexport function normalizeBtwSettings(value: unknown): BtwSettings | undefined {\n if (!isSettingsDocument(value)) return undefined;\n\n const settings: BtwSettings = {};\n if (Object.hasOwn(value, \"keybindings\")) {\n const keys = value.keybindings;\n if (!isSettingsDocument(keys)) return undefined;\n settings.keybindings = {};\n for (const action of BTW_SHORTCUT_ACTIONS) {\n if (!Object.hasOwn(keys, action)) continue;\n const key = normalizeBtwKey(keys[action]);\n if (!key) return undefined;\n settings.keybindings[action] = key;\n }\n }\n if (Object.hasOwn(value, \"model\")) {\n const model = Reflect.get(value, \"model\");\n if (typeof model !== \"string\" || !parseBtwModelReference(model)) return undefined;\n settings.model = model;\n }\n if (Object.hasOwn(value, \"thinkingLevel\")) {\n const thinkingLevel = Reflect.get(value, \"thinkingLevel\");\n if (!isBtwThinkingLevel(thinkingLevel)) return undefined;\n settings.thinkingLevel = thinkingLevel;\n }\n if (Object.hasOwn(value, \"rememberThinkingLevelChanges\")) {\n const remember = Reflect.get(value, \"rememberThinkingLevelChanges\");\n if (typeof remember !== \"boolean\") return undefined;\n settings.rememberThinkingLevelChanges = remember;\n }\n if (Object.hasOwn(value, \"fullscreenCopyOnSelect\")) {\n const copyOnSelect = Reflect.get(value, \"fullscreenCopyOnSelect\");\n if (typeof copyOnSelect !== \"boolean\") return undefined;\n settings.fullscreenCopyOnSelect = copyOnSelect;\n }\n return settings;\n}\n\nexport function parseBtwModelReference(reference: string): { provider: string; modelId: string } | undefined {\n if (/[\\s\\p{Cc}]/u.test(reference)) return undefined;\n const separator = reference.indexOf(\"/\");\n if (separator <= 0 || separator === reference.length - 1) return undefined;\n return { provider: reference.slice(0, separator), modelId: reference.slice(separator + 1) };\n}\n\nexport function effectiveFullscreenCopyOnSelect(settings: BtwSettings): boolean {\n return settings.fullscreenCopyOnSelect ?? DEFAULT_FULLSCREEN_COPY_ON_SELECT;\n}\n\nexport function effectiveRememberThinkingLevelChanges(settings: BtwSettings): boolean {\n return settings.rememberThinkingLevelChanges ?? DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES;\n}\n\nexport async function readBtwSettings(settingsPath = btwSettingsPath()): Promise<BtwSettingsLoadResult> {\n await awaitBtwSettingsWrites(settingsPath);\n return readBtwSettingsUncoordinated(settingsPath);\n}\n\nexport function updateBtwSettings(\n patch: BtwSettingsPatch,\n options: UpdateBtwSettingsOptions = {},\n): Promise<BtwSettings> {\n const settingsPath = options.settingsPath ?? btwSettingsPath();\n return enqueueMutation(settingsPath, async () => {\n options.signal?.throwIfAborted();\n const current = await readSettingsDocumentForUpdate(settingsPath);\n options.signal?.throwIfAborted();\n options.validateCurrent?.(normalizeBtwSettings(current) ?? {});\n const updated = applyBtwSettingsPatch(current, patch);\n const settings = normalizeBtwSettings(updated);\n if (!settings) throw invalidSettingsError(settingsPath, \"invalid settings shape\");\n await publishSettings(settingsPath, updated, options.signal, options.beforeRename);\n return settings;\n });\n}\n\nexport async function awaitBtwSettingsWrites(settingsPath = btwSettingsPath()): Promise<void> {\n await mutationQueues.get(settingsPath);\n}\n\nfunction enqueueMutation<T>(settingsPath: string, mutation: () => Promise<T>): Promise<T> {\n const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();\n const result = previous.then(mutation, mutation);\n const settled = result.then(\n () => undefined,\n () => undefined,\n );\n mutationQueues.set(settingsPath, settled);\n void settled.finally(() => {\n if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);\n });\n return result;\n}\n\nasync function readBtwSettingsUncoordinated(settingsPath: string): Promise<BtwSettingsLoadResult> {\n let contents: string;\n try {\n contents = await readSettingsContents(settingsPath);\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"ENOENT\") return { kind: \"missing\" };\n return { kind: \"invalid\", reason: `${settingsPath}: ${formatError(error)}` };\n }\n\n try {\n const settings = normalizeBtwSettings(JSON.parse(contents) as unknown);\n return settings\n ? { kind: \"loaded\", settings }\n : { kind: \"invalid\", reason: `${settingsPath}: invalid settings shape` };\n } catch {\n return { kind: \"invalid\", reason: `${settingsPath}: invalid JSON` };\n }\n}\n\nasync function readSettingsDocumentForUpdate(settingsPath: string): Promise<SettingsDocument> {\n let contents: string;\n try {\n contents = await readSettingsContents(settingsPath);\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"ENOENT\") return {};\n throw invalidSettingsError(settingsPath, formatError(error));\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(contents) as unknown;\n } catch {\n throw invalidSettingsError(settingsPath, \"invalid JSON\");\n }\n if (!isSettingsDocument(parsed) || !normalizeBtwSettings(parsed)) {\n throw invalidSettingsError(settingsPath, \"invalid settings shape\");\n }\n return parsed;\n}\n\nasync function readSettingsContents(settingsPath: string): Promise<string> {\n const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);\n const handle = await open(settingsPath, flags);\n try {\n const descriptorStats = await handle.stat();\n if (!descriptorStats.isFile()) throw new Error(\"settings path is not a regular file\");\n if (descriptorStats.size > MAX_SETTINGS_BYTES) {\n throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n\n const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);\n let offset = 0;\n while (offset < buffer.byteLength) {\n const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n if (offset > MAX_SETTINGS_BYTES) {\n throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));\n } catch {\n throw new Error(\"settings file is not valid UTF-8\");\n }\n } finally {\n await handle.close();\n }\n}\n\nasync function publishSettings(\n settingsPath: string,\n document: SettingsDocument,\n signal?: AbortSignal,\n beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>,\n): Promise<void> {\n signal?.throwIfAborted();\n const contents = `${JSON.stringify(document, null, 2)}\\n`;\n if (Buffer.byteLength(contents, \"utf8\") > MAX_SETTINGS_BYTES) {\n throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n const directory = dirname(settingsPath);\n await mkdir(directory, { recursive: true });\n signal?.throwIfAborted();\n const temporaryPath = join(directory, `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`);\n try {\n await writeFile(temporaryPath, contents, {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n signal,\n });\n await beforeRename?.(temporaryPath, settingsPath);\n signal?.throwIfAborted();\n await rename(temporaryPath, settingsPath);\n } catch (error) {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\nfunction applyBtwSettingsPatch(current: SettingsDocument, patch: BtwSettingsPatch): SettingsDocument {\n const updated: SettingsDocument = { ...current };\n if (patch.keybindings) {\n const keys = isSettingsDocument(current.keybindings) ? { ...current.keybindings } : {};\n for (const action of BTW_SHORTCUT_ACTIONS) {\n if (!Object.hasOwn(patch.keybindings, action)) continue;\n if (patch.keybindings[action] === undefined) delete keys[action];\n else keys[action] = patch.keybindings[action];\n }\n if (Object.keys(keys).length) updated.keybindings = keys;\n else delete updated.keybindings;\n }\n if (Object.hasOwn(patch, \"thinkingLevel\")) {\n if (patch.thinkingLevel === undefined) delete updated.thinkingLevel;\n else updated.thinkingLevel = patch.thinkingLevel;\n }\n if (Object.hasOwn(patch, \"rememberThinkingLevelChanges\")) {\n updated.rememberThinkingLevelChanges = patch.rememberThinkingLevelChanges;\n }\n if (Object.hasOwn(patch, \"fullscreenCopyOnSelect\")) {\n if (patch.fullscreenCopyOnSelect === undefined) delete updated.fullscreenCopyOnSelect;\n else updated.fullscreenCopyOnSelect = patch.fullscreenCopyOnSelect;\n }\n return updated;\n}\n\nfunction isSettingsDocument(value: unknown): value is SettingsDocument {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBtwThinkingLevel(value: unknown): value is BtwThinkingLevel {\n return BTW_THINKING_LEVELS.includes(value as BtwThinkingLevel);\n}\n\nfunction invalidSettingsError(settingsPath: string, reason: string): Error {\n return new Error(`pi-btw settings at ${settingsPath} are invalid: ${reason}`);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n", "import type {\n Api,\n AssistantMessage,\n Context,\n Message,\n Model,\n ProviderHeaders,\n SimpleStreamOptions,\n UserMessage,\n} from \"@earendil-works/pi-ai\";\n\nexport const BTW_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport type BtwThinkingLevel = (typeof BTW_THINKING_LEVELS)[number];\n\nexport interface SideQuestionAuth {\n apiKey?: string;\n headers?: ProviderHeaders;\n env?: Record<string, string>;\n}\n\nexport type CompleteSimpleFunction = <TApi extends Api>(\n model: Model<TApi>,\n context: Context,\n options?: SimpleStreamOptions,\n) => Promise<AssistantMessage>;\n\nexport type SideThreadTurn =\n | {\n kind: \"answered\";\n question: string;\n answer: string;\n response: AssistantMessage;\n }\n | {\n kind: \"error\";\n question: string;\n answer: string;\n };\n\nexport interface SideThread {\n conversationContext: string;\n turns: SideThreadTurn[];\n}\n\nexport function createSideThread(conversationContext: string): SideThread {\n return { conversationContext, turns: [] };\n}\n\nexport function buildSideThreadMessages(thread: SideThread, question: string): Message[] {\n const answeredTurns = thread.turns.filter(\n (turn): turn is Extract<SideThreadTurn, { kind: \"answered\" }> => turn.kind === \"answered\",\n );\n const messages: Message[] = [];\n\n if (answeredTurns.length === 0) {\n messages.push(createUserMessage(buildUserPrompt(question, thread.conversationContext)));\n return messages;\n }\n\n const [first, ...rest] = answeredTurns;\n messages.push(createUserMessage(buildUserPrompt(first.question, thread.conversationContext)), first.response);\n for (const turn of rest) {\n messages.push(createUserMessage(buildFollowUpPrompt(turn.question)), turn.response);\n }\n messages.push(createUserMessage(buildFollowUpPrompt(question)));\n return messages;\n}\n\nexport interface CompleteSideThreadTurnOptions {\n thread: SideThread;\n model: Model<Api>;\n question: string;\n thinkingLevel: BtwThinkingLevel;\n auth: SideQuestionAuth;\n signal?: AbortSignal;\n completeSimple: CompleteSimpleFunction;\n sessionId?: string;\n}\n\nexport type CompleteSideThreadTurnResult =\n | { kind: \"answered\"; response: AssistantMessage; answer: string }\n | { kind: \"aborted\" }\n | { kind: \"error\"; message: string };\n\nexport async function completeSideThreadTurn({\n thread,\n model,\n question,\n thinkingLevel,\n auth,\n signal,\n completeSimple,\n sessionId,\n}: CompleteSideThreadTurnOptions): Promise<CompleteSideThreadTurnResult> {\n if (signal?.aborted) return { kind: \"aborted\" };\n try {\n const response = await completeSimple(\n model,\n { systemPrompt: SYSTEM_PROMPT, messages: buildSideThreadMessages(thread, question) },\n buildStreamOptions(auth, { thinkingLevel, signal, model, sessionId }),\n );\n if (signal?.aborted || response?.stopReason === \"aborted\") return { kind: \"aborted\" };\n if (!isAssistantMessage(response)) {\n return { kind: \"error\", message: \"The side model returned a malformed response.\" };\n }\n if (response.stopReason === \"error\") {\n return {\n kind: \"error\",\n message: response.errorMessage ?? \"The side model returned an error.\",\n };\n }\n\n const answer = extractAssistantText(response) || \"No response received.\";\n thread.turns.push({ kind: \"answered\", question, answer, response });\n return { kind: \"answered\", response, answer };\n } catch (error: unknown) {\n if (signal?.aborted) return { kind: \"aborted\" };\n return { kind: \"error\", message: formatError(error) };\n }\n}\n\nexport interface CompleteSideQuestionOptions {\n model: Model<Api>;\n question: string;\n conversationContext: string;\n thinkingLevel: BtwThinkingLevel;\n auth: SideQuestionAuth;\n signal?: AbortSignal;\n completeSimple: CompleteSimpleFunction;\n sessionId?: string;\n}\n\nexport async function completeSideQuestion({\n model,\n question,\n conversationContext,\n thinkingLevel,\n auth,\n signal,\n completeSimple,\n sessionId,\n}: CompleteSideQuestionOptions): Promise<AssistantMessage> {\n return completeSimple(\n model,\n {\n systemPrompt: SYSTEM_PROMPT,\n messages: [createUserMessage(buildUserPrompt(question, conversationContext))],\n },\n buildStreamOptions(auth, { thinkingLevel, signal, model, sessionId }),\n );\n}\n\nexport function extractAssistantText(response: AssistantMessage): string {\n return response.content\n .filter(\n (content): content is { type: \"text\"; text: string } =>\n content !== null && typeof content === \"object\" && content.type === \"text\" && typeof content.text === \"string\",\n )\n .map((content) => content.text)\n .join(\"\\n\")\n .trim();\n}\n\nfunction isAssistantMessage(value: unknown): value is AssistantMessage {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<AssistantMessage>;\n return candidate.role === \"assistant\" && Array.isArray(candidate.content) && typeof candidate.stopReason === \"string\";\n}\n\nexport function buildUserPrompt(question: string, conversationContext: string): string {\n return [\n \"Answer this side question without modifying the main conversation.\",\n \"\",\n \"<side_question>\",\n question,\n \"</side_question>\",\n \"\",\n \"<conversation_context>\",\n conversationContext || \"No prior conversation context was available.\",\n \"</conversation_context>\",\n ].join(\"\\n\");\n}\n\nexport function buildFollowUpPrompt(question: string): string {\n return [\"Continue the same side conversation.\", \"\", \"<side_question>\", question, \"</side_question>\"].join(\"\\n\");\n}\n\nfunction createUserMessage(text: string): UserMessage {\n return {\n role: \"user\",\n content: [{ type: \"text\", text }],\n timestamp: Date.now(),\n };\n}\n\n// Minimal session-headers fork of Pi core provider-attribution\n// (pinned to @earendil-works/pi-coding-agent@0.85.0 src/core/provider-attribution.ts:getSessionHeaders).\n// Core does not export this helper and extensions have no SettingsManager, so only session\n// headers are mirrored here. Default attribution headers are intentionally out of scope.\n// Keep semantics bug-compatible with core: case-sensitive Object.assign, explicit auth\n// headers win on exact-case match.\nconst OPENCODE_HOST = \"opencode.ai\";\n\nfunction matchesOpencodeHost(baseUrl: string | undefined): boolean {\n if (!baseUrl) return false;\n try {\n return new URL(baseUrl).hostname === OPENCODE_HOST;\n } catch {\n return false;\n }\n}\n\nfunction getOpencodeSessionHeaders(\n model: Pick<Model<Api>, \"provider\" | \"baseUrl\">,\n sessionId?: string,\n): ProviderHeaders | undefined {\n if (!sessionId) return undefined;\n if (model.provider !== \"opencode\" && model.provider !== \"opencode-go\" && !matchesOpencodeHost(model.baseUrl)) {\n return undefined;\n }\n return { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n}\n\nfunction mergeSessionHeaders(\n authHeaders: ProviderHeaders | undefined,\n sessionHeaders: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n if (!sessionHeaders && !authHeaders) return undefined;\n // Bug-compatible with core mergeProviderAttributionHeaders: case-sensitive assign.\n return { ...sessionHeaders, ...authHeaders };\n}\n\ninterface BuildSideThreadStreamOptions {\n thinkingLevel: BtwThinkingLevel;\n signal?: AbortSignal;\n model?: Pick<Model<Api>, \"provider\" | \"baseUrl\">;\n sessionId?: string;\n}\n\nfunction buildStreamOptions(\n auth: SideQuestionAuth,\n { thinkingLevel, signal, model, sessionId }: BuildSideThreadStreamOptions,\n): SimpleStreamOptions {\n const sessionHeaders = model ? getOpencodeSessionHeaders(model, sessionId) : undefined;\n const options: SimpleStreamOptions = {\n apiKey: auth.apiKey,\n headers: mergeSessionHeaders(auth.headers, sessionHeaders),\n env: auth.env,\n signal,\n };\n if (thinkingLevel !== \"off\") options.reasoning = thinkingLevel;\n return options;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst SYSTEM_PROMPT = `You answer quick side questions for a coding-agent user.\n\nUse the provided conversation context only as background. Answer the user's side question directly and concisely. Do not claim to have changed files, run tools, or affected the main task. If the context is insufficient, say what is unknown and give the best next step.`;\n", "import type { ExtensionCommandContext, KeybindingsManager, Theme } from \"@earendil-works/pi-coding-agent\";\nimport type { Component, TUI } from \"@earendil-works/pi-tui\";\nimport type { MenuContext, RunMenuResult } from \"@narumitw/pi-tui-kit\";\nimport {\n BTW_SHORTCUT_ACTIONS,\n type BtwShortcutAction,\n normalizeBtwKey,\n resolveBtwShortcuts,\n validateBtwShortcutEdit,\n} from \"./keybindings.js\";\nimport {\n type BtwSettings,\n type BtwSettingsPatch,\n btwSettingsPath,\n effectiveFullscreenCopyOnSelect,\n effectiveRememberThinkingLevelChanges,\n readBtwSettings,\n type UpdateBtwSettingsOptions,\n updateBtwSettings,\n} from \"./settings.js\";\nimport { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\nimport { formatKeyLabel, sanitizeSingleLine } from \"./text.js\";\n\ninterface BtwMenuState {\n kind: \"valid\" | \"invalid\";\n settings: BtwSettings;\n reason?: string;\n}\n\nexport interface BtwResumeThreadSummary {\n id: string;\n title: string;\n questionCount: number;\n}\n\nexport interface ShowBtwCommandMenuOptions {\n currentThinkingLevel: BtwThinkingLevel;\n availableThinkingLevels: readonly BtwThinkingLevel[];\n resumeThreads?: readonly BtwResumeThreadSummary[];\n settingsPath?: string;\n readSettings?: typeof readBtwSettings;\n updateSettings?: (patch: BtwSettingsPatch, options: UpdateBtwSettingsOptions) => Promise<BtwSettings>;\n}\n\nexport type BtwCommandMenuResult = \"start\" | \"tree\" | \"closed\" | { kind: \"resume\"; threadId: string };\n\ntype BtwMenuScreen = \"main\" | \"resume\" | \"settings\" | \"invalid\" | \"shortcut\" | \"shortcut-input\";\ntype BtwMenuAction =\n | \"start\"\n | \"start-tree\"\n | \"resume\"\n | \"set-thinking\"\n | \"set-remember\"\n | \"set-fullscreen-copy\"\n | \"edit-shortcut\"\n | \"save-shortcut\"\n | \"reset-shortcut\";\nconst SAME_AS_MAIN_THREAD = \"Same as main thread\";\ntype BtwCustomOptions = Parameters<ExtensionCommandContext[\"ui\"][\"custom\"]>[1];\n\ntype BtwCustomFactory<T> = (\n tui: TUI,\n theme: Theme,\n keybindings: KeybindingsManager,\n done: (result: T) => void,\n) => Component;\n\nexport async function showBtwCommandMenu(\n ctx: ExtensionCommandContext,\n options: ShowBtwCommandMenuOptions,\n): Promise<BtwCommandMenuResult> {\n if (ctx.mode !== \"tui\") return \"closed\";\n const { defineMenu, runMenu } = await import(\"@narumitw/pi-tui-kit\");\n if (ctx.signal?.aborted) return \"closed\";\n const settingsPath = options.settingsPath ?? btwSettingsPath();\n const readSettings = options.readSettings ?? readBtwSettings;\n const updateSettings = options.updateSettings ?? updateBtwSettings;\n const levels =\n options.availableThinkingLevels.length > 0\n ? [...options.availableThinkingLevels]\n : ([\"off\"] satisfies BtwThinkingLevel[]);\n const displaySettingsPath = sanitizeSingleLine(settingsPath);\n const resumeThreads = options.resumeThreads ?? [];\n let startSelected = false;\n let treeSelected = false;\n let resumedThreadId: string | undefined;\n let keybindings: KeybindingsManager | undefined;\n let shortcut: BtwShortcutAction = \"exit\";\n const shortcutLabels: Record<BtwShortcutAction, string> = {\n exit: \"Exit shortcut\",\n cycleThinkingLevel: \"Cycle thinking level shortcut\",\n bringToMain: \"Bring to main shortcut\",\n };\n const shortcutValue = (settings: BtwSettings, action: BtwShortcutAction): string => {\n if (!keybindings) return \"Default\";\n const effective = resolveBtwShortcuts(settings.keybindings, keybindings, effectiveFullscreenCopyOnSelect(settings));\n const configured = settings.keybindings?.[action];\n if (configured !== undefined && !effective.keys[action].includes(configured)) {\n return `Fallback (${effective.label(action)}; saved ${formatKeyLabel(configured)})`;\n }\n const source = configured === undefined ? (action === \"cycleThinkingLevel\" ? \"Inherit Pi\" : \"Default\") : \"Custom\";\n return `${source} (${effective.label(action)})`;\n };\n const saveShortcut = async (state: BtwMenuState, value: string | undefined, signal: AbortSignal) => {\n if (!keybindings || state.kind !== \"valid\" || signal.aborted) return { kind: \"rejected\" } as const;\n const action = shortcut;\n const manager = keybindings;\n const validate = (settings: BtwSettings) =>\n validateBtwShortcutEdit(\n action,\n value,\n settings.keybindings ?? {},\n manager,\n effectiveFullscreenCopyOnSelect(settings),\n );\n const error = validate(state.settings);\n if (error) {\n notifySafely(ctx, error, \"error\");\n return { kind: \"rejected\" } as const;\n }\n try {\n await updateSettings(\n { keybindings: { [action]: value === undefined ? undefined : normalizeBtwKey(value) } },\n {\n settingsPath,\n signal,\n validateCurrent: (settings) => {\n const conflict = validate(settings);\n if (conflict) throw new Error(conflict);\n },\n },\n );\n if (signal.aborted) return { kind: \"rejected\" } as const;\n notifySafely(ctx, \"Pi BTW shortcut saved; applies when opening or resuming BTW.\", \"info\");\n return { kind: \"back\" } as const;\n } catch (error) {\n if (!signal.aborted) notifySaveFailure(ctx, error);\n return { kind: \"rejected\" } as const;\n }\n };\n\n const loadState = async (): Promise<BtwMenuState> => {\n const loaded = await readSettings(settingsPath);\n if (loaded.kind === \"invalid\") {\n return { kind: \"invalid\", settings: {}, reason: loaded.reason };\n }\n return { kind: \"valid\", settings: loaded.kind === \"loaded\" ? loaded.settings : {} };\n };\n const currentMainThinkingLevel = clampToAvailableThinkingLevel(options.currentThinkingLevel, levels);\n const displayThinkingLevel = (settings: BtwSettings): string =>\n settings.thinkingLevel === undefined\n ? SAME_AS_MAIN_THREAD\n : clampToAvailableThinkingLevel(settings.thinkingLevel, levels);\n const displayThinkingSummary = (settings: BtwSettings): string =>\n settings.thinkingLevel === undefined\n ? `${SAME_AS_MAIN_THREAD} (currently ${currentMainThinkingLevel})`\n : displayThinkingLevel(settings);\n const displayRememberSummary = (settings: BtwSettings): string => {\n const value = effectiveRememberThinkingLevelChanges(settings) ? \"On\" : \"Off\";\n return settings.thinkingLevel === undefined ? `${value} (fixed levels only)` : value;\n };\n\n const menu = defineMenu<BtwMenuState, BtwMenuScreen, BtwMenuAction, MenuContext>({\n start: \"main\",\n screens: {\n main: ({ state }) => ({\n kind: \"actions\",\n title: \"Pi BTW\",\n lines: [\n `Thinking: ${displayThinkingSummary(state.settings)} \u00B7 Remember changes: ${displayRememberSummary(state.settings)}`,\n `Copy on select: ${effectiveFullscreenCopyOnSelect(state.settings) ? \"On\" : \"Off\"}`,\n ],\n items: [\n {\n id: \"start\",\n label: \"Start side thread\",\n description: \"Open an empty side thread\",\n action: \"start\",\n },\n {\n id: \"start-tree\",\n label: \"Start from main thread tree\u2026\",\n description: \"Choose context without switching the main branch\",\n action: \"start-tree\",\n },\n ...(resumeThreads.length > 0\n ? [\n {\n id: \"resume\" as const,\n label: \"Resume side thread\",\n description: \"Continue an in-memory side thread\",\n to: \"resume\" as const,\n },\n ]\n : []),\n {\n id: \"settings\",\n label: \"Settings\",\n description: \"Choose thinking, keybindings, and selection copying\",\n to: state.kind === \"invalid\" ? \"invalid\" : \"settings\",\n },\n ],\n hint: \"close\",\n }),\n resume: () => ({\n kind: \"choice\",\n title: \"Resume BTW side thread\",\n enableSearch: true,\n items: resumeThreads.map((thread) => ({\n id: thread.id,\n label: thread.title,\n description: `${thread.questionCount} ${thread.questionCount === 1 ? \"question\" : \"questions\"}`,\n })),\n action: \"resume\",\n viewportSize: 10,\n hint: \"back\",\n }),\n settings: ({ state }) => ({\n kind: \"settings\",\n title: \"Pi BTW Settings\",\n lines: [`User settings \u00B7 ${displaySettingsPath}`],\n items: [\n {\n id: \"thinkingLevel\",\n label: \"Thinking level\",\n description: `Set the starting level for future pi-btw side threads. Currently ${currentMainThinkingLevel}.`,\n currentValue: displayThinkingLevel(state.settings),\n values: [SAME_AS_MAIN_THREAD, ...levels],\n action: \"set-thinking\",\n },\n {\n id: \"rememberThinkingLevelChanges\",\n label: \"Remember thinking level changes\",\n description: \"Save shortcut changes for fixed thinking levels to pi-btw.json.\",\n currentValue: effectiveRememberThinkingLevelChanges(state.settings) ? \"On\" : \"Off\",\n values: [\"On\", \"Off\"],\n action: \"set-remember\",\n },\n {\n id: \"fullscreenCopyOnSelect\",\n label: \"Copy selection automatically\",\n description: \"Copy mouse selections immediately instead of with the configured copy key.\",\n currentValue: effectiveFullscreenCopyOnSelect(state.settings) ? \"On\" : \"Off\",\n values: [\"On\", \"Off\"],\n action: \"set-fullscreen-copy\",\n },\n ...BTW_SHORTCUT_ACTIONS.map((action) => ({\n id: action,\n label: shortcutLabels[action],\n description: \"Edit a BTW-only key combination or restore its default. Ctrl+C always hard-cancels.\",\n currentValue: shortcutValue(state.settings, action),\n action: \"edit-shortcut\" as const,\n })),\n ],\n }),\n shortcut: ({ state }) => ({\n kind: \"actions\",\n title: shortcutLabels[shortcut],\n lines: [shortcutValue(state.settings, shortcut), \"Ctrl+C always hard-cancels BTW.\"],\n items: [\n { id: \"edit\", label: \"Edit key combination\u2026\", to: \"shortcut-input\" },\n { id: \"reset\", label: \"Restore default\", action: \"reset-shortcut\" },\n ],\n hint: \"back\",\n }),\n \"shortcut-input\": () => ({\n kind: \"input\",\n title: shortcutLabels[shortcut],\n lines: [\"Type a key name, not the shortcut itself. For example: ctrl+q or f6.\"],\n placeholder: \"Key combination\",\n action: \"save-shortcut\",\n hint: \"back\",\n }),\n invalid: ({ state }) => ({\n kind: \"detail\",\n title: \"Pi BTW Settings \u00B7 Read only\",\n lines: [\n `Invalid settings file. Fix ${displaySettingsPath} before saving.`,\n sanitizeSingleLine(state.reason ?? \"The settings file is invalid.\"),\n ],\n hint: \"back\",\n }),\n },\n actions: {\n \"edit-shortcut\": ({ itemId }) => {\n if (!BTW_SHORTCUT_ACTIONS.includes(itemId as BtwShortcutAction)) return { kind: \"rejected\" };\n shortcut = itemId as BtwShortcutAction;\n return { kind: \"to\", screen: \"shortcut\" };\n },\n \"save-shortcut\": ({ state, value, signal }) => saveShortcut(state, value?.trim() ?? \"\", signal),\n \"reset-shortcut\": ({ state, signal }) => saveShortcut(state, undefined, signal),\n start: async () => {\n startSelected = true;\n return { kind: \"close\" };\n },\n \"start-tree\": async () => {\n treeSelected = true;\n return { kind: \"close\" };\n },\n resume: async ({ itemId }: { itemId: string }) => {\n if (!resumeThreads.some((thread) => thread.id === itemId)) {\n return { kind: \"rejected\" } as const;\n }\n resumedThreadId = itemId;\n return { kind: \"close\" } as const;\n },\n \"set-thinking\": async ({ value, signal }) => {\n if (!value) return { kind: \"rejected\" };\n const patch =\n value === SAME_AS_MAIN_THREAD\n ? ({ thinkingLevel: undefined } satisfies BtwSettingsPatch)\n : levels.includes(value as BtwThinkingLevel)\n ? ({ thinkingLevel: value as BtwThinkingLevel } satisfies BtwSettingsPatch)\n : undefined;\n if (!patch) return { kind: \"rejected\" };\n try {\n await updateSettings(patch, { settingsPath, signal });\n if (signal.aborted) return { kind: \"rejected\" };\n notifySafely(ctx, `Pi BTW thinking level: ${value}.`, \"info\");\n return { kind: \"stay\" };\n } catch (error) {\n if (!signal.aborted) notifySaveFailure(ctx, error);\n return { kind: \"rejected\" };\n }\n },\n \"set-remember\": async ({ value, signal }) => {\n if (value !== \"On\" && value !== \"Off\") return { kind: \"rejected\" };\n try {\n await updateSettings({ rememberThinkingLevelChanges: value === \"On\" }, { settingsPath, signal });\n if (signal.aborted) return { kind: \"rejected\" };\n notifySafely(ctx, `Remember thinking level changes: ${value}.`, \"info\");\n return { kind: \"stay\" };\n } catch (error) {\n if (!signal.aborted) notifySaveFailure(ctx, error);\n return { kind: \"rejected\" };\n }\n },\n \"set-fullscreen-copy\": async ({ value, signal }) => {\n if (value !== \"On\" && value !== \"Off\") return { kind: \"rejected\" };\n try {\n await updateSettings({ fullscreenCopyOnSelect: value === \"On\" }, { settingsPath, signal });\n if (signal.aborted) return { kind: \"rejected\" };\n notifySafely(ctx, `Copy selection automatically: ${value}.`, \"info\");\n return { kind: \"stay\" };\n } catch (error) {\n if (!signal.aborted) notifySaveFailure(ctx, error);\n return { kind: \"rejected\" };\n }\n },\n },\n });\n\n const result = await runBtwMenuPreservingEditor(\n ctx,\n (menuContext) => runMenu(menuContext, menu, { getState: loadState }),\n (manager) => {\n keybindings = manager;\n },\n );\n if (result.kind !== \"closed\" || result.reason !== \"close\") return \"closed\";\n if (resumedThreadId) return { kind: \"resume\", threadId: resumedThreadId };\n if (treeSelected) return \"tree\";\n return startSelected ? \"start\" : \"closed\";\n}\n\nexport async function showBtwCustomPreservingEditor<T>(\n ctx: ExtensionCommandContext,\n factory: BtwCustomFactory<T>,\n): Promise<T | undefined> {\n let liveEditorText = ctx.ui.getEditorText();\n let completed = false;\n const result = await ctx.ui.custom<T>((tui, theme, keybindings, done) =>\n factory(tui, theme, keybindings, (value) => {\n try {\n liveEditorText = ctx.ui.getEditorText();\n } catch {\n // Keep completion finite if session replacement invalidates the editor context.\n }\n completed = true;\n done(value);\n }),\n );\n if (completed) {\n try {\n if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);\n } catch {\n // A replaced context owns a different editor and must not receive stale restoration.\n }\n }\n return result;\n}\n\nexport async function runBtwMenuPreservingEditor(\n ctx: ExtensionCommandContext,\n run: (menuContext: MenuContext) => Promise<RunMenuResult>,\n onKeybindings?: (keybindings: KeybindingsManager) => void,\n): Promise<RunMenuResult> {\n let liveEditorText = ctx.ui.getEditorText();\n let completed = false;\n const ui = new Proxy(ctx.ui, {\n get(target, property) {\n if (property === \"custom\") {\n return <Value>(factory: BtwCustomFactory<Value>, customOptions?: BtwCustomOptions) =>\n target.custom<Value>((tui, theme, keybindings, done) => {\n onKeybindings?.(keybindings);\n return factory(tui, theme, keybindings, (value) => {\n try {\n liveEditorText = target.getEditorText();\n } catch {\n // Keep completion finite if session replacement invalidates the editor context.\n }\n completed = true;\n done(value);\n });\n }, customOptions);\n }\n const value = Reflect.get(target, property, target) as unknown;\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n const result = await run({ mode: ctx.mode, hasUI: ctx.hasUI, ui });\n if (result.kind !== \"stale\" && completed) {\n try {\n if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);\n } catch {\n // A replaced context owns a different editor and must not receive stale restoration.\n }\n }\n return result;\n}\n\nfunction clampToAvailableThinkingLevel(\n requested: BtwThinkingLevel,\n available: readonly BtwThinkingLevel[],\n): BtwThinkingLevel {\n if (available.includes(requested)) return requested;\n const requestedIndex = BTW_THINKING_LEVELS.indexOf(requested);\n for (let index = requestedIndex; index < BTW_THINKING_LEVELS.length; index += 1) {\n const candidate = BTW_THINKING_LEVELS[index];\n if (candidate && available.includes(candidate)) return candidate;\n }\n for (let index = requestedIndex - 1; index >= 0; index -= 1) {\n const candidate = BTW_THINKING_LEVELS[index];\n if (candidate && available.includes(candidate)) return candidate;\n }\n return available[0] ?? \"off\";\n}\n\nfunction notifySaveFailure(ctx: ExtensionCommandContext, error: unknown): void {\n notifySafely(\n ctx,\n `Pi BTW settings were not saved; the previous value remains active: ${formatError(error)}`,\n \"error\",\n );\n}\n\nfunction notifySafely(\n ctx: ExtensionCommandContext,\n message: string,\n level: Parameters<ExtensionCommandContext[\"ui\"][\"notify\"]>[1],\n): void {\n try {\n ctx.ui.notify(sanitizeSingleLine(message), level);\n } catch {\n // A completed save remains valid if its command context was replaced before notification.\n }\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n", "import type { MarkdownTransformer, Theme } from \"@earendil-works/pi-coding-agent\";\nimport type { SideThreadTurn } from \"./side-thread.js\";\n\nexport type BtwMarkdownTransformers = (theme: Theme) => readonly MarkdownTransformer[];\n\ntype MermaidMarkdownModule = typeof import(\"@narumitw/pi-tui-kit/markdown\");\n\nconst MERMAID_MARKDOWN_MODULE = \"@narumitw/pi-tui-kit/markdown\";\nconst noMarkdownTransformers: BtwMarkdownTransformers = () => [];\n\nexport function prepareBtwTranscriptMarkdown(\n turns: readonly SideThreadTurn[],\n pendingQuestion?: string,\n): Promise<BtwMarkdownTransformers>;\nexport function prepareBtwTranscriptMarkdown(\n turns: readonly SideThreadTurn[],\n pendingQuestion: string | undefined,\n signal: AbortSignal,\n): Promise<BtwMarkdownTransformers | undefined>;\nexport async function prepareBtwTranscriptMarkdown(\n turns: readonly SideThreadTurn[],\n pendingQuestion?: string,\n signal?: AbortSignal,\n): Promise<BtwMarkdownTransformers | undefined> {\n const documents = turns.flatMap((turn) =>\n turn.kind === \"answered\" ? [turn.question, turn.answer] : [turn.question],\n );\n if (pendingQuestion) documents.push(pendingQuestion);\n if (!documents.some((document) => /mermaid/iu.test(document))) return noMarkdownTransformers;\n if (signal?.aborted) return undefined;\n\n const markdownModule = await settleUnlessAborted(\n import(MERMAID_MARKDOWN_MODULE) as Promise<MermaidMarkdownModule>,\n signal,\n );\n if (!markdownModule || signal?.aborted) return undefined;\n const { createMermaidMarkdownTransformer, prepareMermaidMarkdownRenderer } = markdownModule;\n const preparations = new Set<Promise<void>>();\n for (const document of documents) {\n const preparation = prepareMermaidMarkdownRenderer(document);\n if (preparation) preparations.add(preparation);\n }\n if (preparations.size > 0 && !(await settleUnlessAborted(Promise.all(preparations), signal))) return undefined;\n if (signal?.aborted) return undefined;\n\n return (theme) => {\n const transformer = createMermaidMarkdownTransformer(theme);\n return transformer ? [transformer] : [];\n };\n}\n\nasync function settleUnlessAborted<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T | undefined> {\n if (!signal) return operation;\n let onAbort: (() => void) | undefined;\n const aborted = new Promise<undefined>((resolve) => {\n onAbort = () => resolve(undefined);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n if (signal.aborted) onAbort();\n });\n try {\n return await Promise.race([operation, aborted]);\n } finally {\n if (onAbort) signal.removeEventListener(\"abort\", onAbort);\n }\n}\n", "import type { AssistantMessage } from \"@earendil-works/pi-ai\";\nimport {\n AssistantMessageComponent,\n getMarkdownTheme,\n type KeybindingsManager,\n type MarkdownTransformer,\n type Theme,\n UserMessageComponent,\n} from \"@earendil-works/pi-coding-agent\";\nimport {\n type Component,\n CURSOR_MARKER,\n Editor,\n type EditorTheme,\n type Focusable,\n Key,\n Loader,\n Markdown,\n matchesKey,\n ScrollView,\n type TUI,\n truncateToWidth,\n VStack,\n visibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport type { BtwFullscreenLayoutComponent } from \"./fullscreen-ui.js\";\nimport { BtwPasteGuard, type BtwShortcuts, getBtwShortcuts } from \"./keybindings.js\";\nimport type { BtwThinkingLevel, SideThreadTurn } from \"./side-thread.js\";\nimport { sanitizeSingleLine } from \"./text.js\";\n\nconst TRANSCRIPT_CHROME_LINES = 2;\nconst MAX_STEERING_DISPLAY_LINES = 3;\nconst OSC133_MARKERS = [\"\\u001b]133;A\\u0007\", \"\\u001b]133;B\\u0007\", \"\\u001b]133;C\\u0007\"];\n// Pi renders a spacer above the custom component and a two-line built-in footer below it.\nconst RESERVED_APP_LINES = 3;\n\n// A temporary fit after manual scrolling must not silently resume following new output.\nclass PreservingScrollView extends ScrollView {\n override updateLayout(contentHeight: number, viewportHeight: number, requestRender: () => void): void {\n const preserveManualPosition = !this.isFollowingEnd;\n super.updateLayout(contentHeight, viewportHeight, requestRender);\n if (preserveManualPosition && this.isFollowingEnd) {\n this.scrollTo(this.scrollTop, { disableFollow: true });\n }\n }\n}\n\nexport type TranscriptPagerAction =\n | { kind: \"submit\"; question: string }\n | { kind: \"bringToMain\"; questionDraft: string }\n | { kind: \"close\" };\n\nexport interface BtwThinkingControl {\n level: BtwThinkingLevel;\n levels: readonly BtwThinkingLevel[];\n keybindings: KeybindingsManager;\n onChange: (level: BtwThinkingLevel) => void;\n}\n\nexport interface BtwAnsweringViewOptions {\n markdownTransformers?: readonly MarkdownTransformer[];\n steering?: {\n questions: readonly string[];\n onSubmit: (question: string) => void;\n thinking?: BtwThinkingControl;\n };\n}\n\nexport class BtwTranscriptPager implements BtwFullscreenLayoutComponent, Focusable {\n private readonly shortcuts: BtwShortcuts;\n private readonly pasteGuard = new BtwPasteGuard();\n private readonly transcriptComponents: Component[];\n private readonly editor: Editor;\n private readonly canBringToMain: boolean;\n private readonly scrollView: ScrollView;\n private readonly layoutRoot: VStack;\n private lastContentLineCount = 0;\n private warning: string | undefined;\n private finished = false;\n private isFocused = false;\n private thinkingLevel: BtwThinkingLevel | undefined;\n\n constructor(\n private readonly tui: TUI,\n private readonly theme: Theme,\n turns: readonly SideThreadTurn[],\n private readonly onAction: (action: TranscriptPagerAction) => void,\n private readonly options: {\n startAtBottom?: boolean;\n initialQuestion?: string;\n markdownTransformers?: readonly MarkdownTransformer[];\n thinking?: BtwThinkingControl;\n } = {},\n ) {\n this.shortcuts = getBtwShortcuts(tui, options.thinking?.keybindings);\n this.transcriptComponents = buildTranscriptComponents(turns, this.theme, undefined, options.markdownTransformers);\n this.canBringToMain = turns.some((turn) => turn.kind === \"answered\");\n this.thinkingLevel = options.thinking?.level;\n const editorTheme: EditorTheme = {\n borderColor: (text) => this.theme.fg(\"accent\", text),\n selectList: {\n selectedPrefix: (text) => this.theme.fg(\"accent\", text),\n selectedText: (text) => this.theme.fg(\"accent\", text),\n description: (text) => this.theme.fg(\"muted\", text),\n scrollInfo: (text) => this.theme.fg(\"dim\", text),\n noMatch: (text) => this.theme.fg(\"warning\", text),\n },\n };\n this.editor = new Editor(this.tui, editorTheme);\n if (options.initialQuestion) this.editor.setText(options.initialQuestion);\n this.editor.onChange = () => {\n this.warning = undefined;\n };\n this.editor.onSubmit = (text) => {\n const question = text.trim();\n if (!question) {\n this.warning = \"Question cannot be empty\";\n return;\n }\n this.finished = true;\n this.onAction({ kind: \"submit\", question });\n };\n const transcript = this.createTranscriptComponent();\n this.scrollView = new PreservingScrollView(transcript, {\n follow: options.startAtBottom ? \"end\" : \"none\",\n primary: true,\n });\n this.layoutRoot = new VStack([\n { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },\n { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },\n { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },\n { component: this.editor, basis: \"auto\", shrink: 1, minSize: 0 },\n ]);\n }\n\n get focused(): boolean {\n return this.isFocused;\n }\n\n set focused(value: boolean) {\n this.isFocused = value;\n this.editor.focused = value;\n }\n\n getFullscreenLayout(): Component {\n return this.layoutRoot;\n }\n\n render(width: number): string[] {\n if (width <= 0) return [];\n const safeWidth = Math.max(1, width);\n const editorLines = this.editor.render(safeWidth);\n const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);\n const viewportHeight = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);\n const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);\n this.lastContentLineCount = contentLines.length;\n this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());\n\n return fitComposerLayout(\n renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),\n contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),\n this.renderFooter(safeWidth),\n editorLines,\n availableRows,\n ).map((line) => truncateToWidth(line, safeWidth));\n }\n\n handleInput(data: string): void {\n if (this.finished) return;\n if (this.pasteGuard.consume(data)) {\n this.editor.handleInput(data);\n this.tui.requestRender();\n return;\n }\n if (this.shortcuts.matches(data, \"exit\")) {\n this.finished = true;\n this.onAction({ kind: \"close\" });\n return;\n }\n if (this.canBringToMain && this.shortcuts.matches(data, \"bringToMain\")) {\n this.finished = true;\n this.onAction({ kind: \"bringToMain\", questionDraft: this.editor.getExpandedText() });\n return;\n }\n const thinking = this.options.thinking;\n if (thinking && thinking.levels.length > 1 && this.shortcuts.matches(data, \"cycleThinkingLevel\")) {\n const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);\n const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];\n if (nextLevel) {\n this.thinkingLevel = nextLevel;\n thinking.onChange(nextLevel);\n this.warning = undefined;\n this.tui.requestRender();\n }\n return;\n }\n if (matchesKey(data, Key.pageUp)) {\n this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));\n this.tui.requestRender();\n return;\n }\n if (matchesKey(data, Key.pageDown)) {\n this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));\n this.tui.requestRender();\n return;\n }\n this.editor.handleInput(data);\n if (!this.finished) this.tui.requestRender();\n }\n\n invalidate(): void {\n this.layoutRoot.invalidate();\n }\n\n dispose(): void {\n if (this.finished) return;\n this.finished = true;\n this.onAction({ kind: \"close\" });\n }\n\n private renderFooter(width: number): string {\n const exit = this.shortcuts.label(\"exit\");\n const bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;\n const bringKey = this.shortcuts.label(\"bringToMain\");\n if (this.warning) {\n const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} exit`;\n return truncateToWidth(this.theme.fg(\"warning\", warning), width);\n }\n const scrollable = this.getMaxScrollOffset() > 0;\n const thinking = this.options.thinking;\n const cycleHint =\n thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length\n ? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label(\"cycleThinkingLevel\")} cycle`\n : \"\";\n const base = bring\n ? `btw \u2022 Enter send \u2022 ${bringKey} bring to main \u2022 ${exit} exit`\n : `btw \u2022 Enter send \u2022 ${exit} exit`;\n const fullBase = `${base}${cycleHint}`;\n const fallbackBase = `btw \u2022 Enter \u2022 ${exit}`;\n const compactBase = bring ? `btw \u2022 Enter \u2022 ${bringKey} \u2022 ${exit}` : fallbackBase;\n const compactWithThinking = `${compactBase}${cycleHint}`;\n let hints =\n visibleWidth(fullBase) <= width\n ? fullBase\n : visibleWidth(compactWithThinking) <= width\n ? compactWithThinking\n : visibleWidth(compactBase) <= width\n ? compactBase\n : fallbackBase;\n if (scrollable) {\n const history = ` \u2022 ${this.scrollView.scrollTop > 0 ? \"\u2191 older\" : \"\u2193 newer\"} \u2022 PgUp/PgDn history`;\n const compactHistory = \" \u2022 PgUp/PgDn\";\n const compactScrollable = bring\n ? `Enter \u2022 ${bringKey} \u2022 ${exit} \u2022 PgUp/PgDn`\n : `${fallbackBase}${compactHistory}`;\n if (visibleWidth(`${hints}${history}`) <= width) {\n hints += history;\n } else if (visibleWidth(`${compactBase}${history}`) <= width) {\n hints = `${compactBase}${history}`;\n } else if (visibleWidth(`${hints}${compactHistory}`) <= width) {\n hints += compactHistory;\n } else if (visibleWidth(`${compactBase}${compactHistory}`) <= width) {\n hints = `${compactBase}${compactHistory}`;\n } else if (visibleWidth(compactScrollable) <= width) {\n hints = compactScrollable;\n }\n }\n return truncateToWidth(this.theme.fg(\"muted\", hints), width);\n }\n\n private createHeaderComponent(): Component {\n return {\n render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],\n invalidate() {},\n };\n }\n\n private createTranscriptComponent(): Component {\n return {\n render: (width) => {\n const lines = renderTranscriptLines(this.transcriptComponents, width);\n this.lastContentLineCount = lines.length;\n return lines;\n },\n invalidate: () => {\n for (const component of this.transcriptComponents) component.invalidate();\n },\n };\n }\n\n private createFooterComponent(): Component {\n return {\n render: (width) => [this.renderFooter(width)],\n invalidate() {},\n };\n }\n\n private getMaxScrollOffset(): number {\n return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);\n }\n}\n\nexport class BtwAnsweringView implements BtwFullscreenLayoutComponent, Focusable {\n private readonly shortcuts: BtwShortcuts;\n private readonly pasteGuard = new BtwPasteGuard();\n private readonly transcriptComponents: Component[];\n private readonly loader: Loader;\n private readonly editor: Editor | undefined;\n private readonly controller = new AbortController();\n private readonly scrollView: ScrollView;\n private readonly layoutRoot: VStack;\n private lastContentLineCount = 0;\n private warning: string | undefined;\n private finished = false;\n private isFocused = false;\n private thinkingLevel: BtwThinkingLevel | undefined;\n\n constructor(\n private readonly tui: TUI,\n private readonly theme: Theme,\n turns: readonly SideThreadTurn[],\n pendingQuestion: string,\n private readonly onCancel: () => void,\n thinkingLevel?: BtwThinkingLevel,\n private readonly options: BtwAnsweringViewOptions = {},\n ) {\n this.shortcuts = getBtwShortcuts(tui, options.steering?.thinking?.keybindings);\n this.transcriptComponents = buildTranscriptComponents(\n turns,\n this.theme,\n pendingQuestion,\n options.markdownTransformers,\n );\n this.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;\n this.loader = new Loader(\n this.tui,\n (text) => this.theme.fg(\"accent\", text),\n (text) => this.theme.fg(\"muted\", text),\n \"Answering\u2026\",\n );\n if (options.steering) {\n const editorTheme: EditorTheme = {\n borderColor: (text) => this.theme.fg(\"accent\", text),\n selectList: {\n selectedPrefix: (text) => this.theme.fg(\"accent\", text),\n selectedText: (text) => this.theme.fg(\"accent\", text),\n description: (text) => this.theme.fg(\"muted\", text),\n scrollInfo: (text) => this.theme.fg(\"dim\", text),\n noMatch: (text) => this.theme.fg(\"warning\", text),\n },\n };\n this.editor = new Editor(this.tui, editorTheme);\n this.editor.onChange = () => {\n this.warning = undefined;\n };\n this.editor.onSubmit = (text) => {\n const question = text.trim();\n if (!question) {\n this.warning = \"Question cannot be empty\";\n return;\n }\n options.steering?.onSubmit(question);\n this.warning = undefined;\n };\n }\n const transcript = this.createTranscriptComponent();\n this.scrollView = new PreservingScrollView(transcript, { follow: \"end\", primary: true });\n this.layoutRoot = new VStack([\n { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },\n { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },\n {\n component: this.createSteeringComponent(),\n basis: \"auto\",\n shrink: 1,\n minSize: 0,\n maxSize: MAX_STEERING_DISPLAY_LINES,\n },\n { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },\n ...(this.editor ? [{ component: this.editor, basis: \"auto\" as const, shrink: 1, minSize: 0 }] : []),\n ]);\n }\n\n get focused(): boolean {\n return this.isFocused;\n }\n\n set focused(value: boolean) {\n this.isFocused = value;\n if (this.editor) this.editor.focused = value;\n }\n\n get signal(): AbortSignal {\n return this.controller.signal;\n }\n\n getFullscreenLayout(): Component {\n return this.layoutRoot;\n }\n\n render(width: number): string[] {\n if (width <= 0) return [];\n const safeWidth = Math.max(1, width);\n const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);\n const editorLines = this.editor?.render(safeWidth) ?? [];\n const steeringCapacity = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);\n const steeringLines = renderSteeringLines(\n this.options.steering?.questions ?? [],\n safeWidth,\n this.theme,\n Math.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity),\n );\n const viewportHeight = Math.max(\n 0,\n availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES - steeringLines.length,\n );\n const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);\n this.lastContentLineCount = contentLines.length;\n this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());\n\n return fitComposerLayout(\n renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),\n contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),\n this.renderFooter(safeWidth),\n editorLines,\n availableRows,\n steeringLines,\n ).map((line) => truncateToWidth(line, safeWidth));\n }\n\n handleInput(data: string): void {\n if (this.finished) return;\n if (this.pasteGuard.consume(data)) {\n this.editor?.handleInput(data);\n this.tui.requestRender();\n return;\n }\n if (this.shortcuts.matches(data, \"exit\")) {\n this.finished = true;\n this.loader.stop();\n this.controller.abort();\n this.onCancel();\n return;\n }\n const thinking = this.options.steering?.thinking;\n if (thinking && thinking.levels.length > 1 && this.shortcuts.matches(data, \"cycleThinkingLevel\")) {\n const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);\n const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];\n if (nextLevel) {\n this.thinkingLevel = nextLevel;\n thinking.onChange(nextLevel);\n this.warning = undefined;\n this.tui.requestRender();\n }\n return;\n }\n if (matchesKey(data, Key.pageUp)) {\n this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));\n this.tui.requestRender();\n return;\n }\n if (matchesKey(data, Key.pageDown)) {\n this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));\n this.tui.requestRender();\n return;\n }\n this.editor?.handleInput(data);\n this.tui.requestRender();\n }\n\n invalidate(): void {\n this.layoutRoot.invalidate();\n }\n\n finish(): void {\n this.finished = true;\n this.loader.stop();\n }\n\n dispose(): void {\n if (this.finished) {\n this.loader.stop();\n this.controller.abort();\n return;\n }\n this.finished = true;\n this.loader.stop();\n this.controller.abort();\n this.onCancel();\n }\n\n private renderFooter(width: number): string {\n const exit = this.shortcuts.label(\"exit\");\n if (this.warning) {\n const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} cancel`;\n return truncateToWidth(this.theme.fg(\"warning\", warning), width);\n }\n const baseHint = this.editor ? `Enter steer \u2022 ${exit} cancel` : `${exit} cancel`;\n const thinking = this.options.steering?.thinking;\n const cycleHint =\n thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length\n ? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label(\"cycleThinkingLevel\")} cycle`\n : \"\";\n const scrollHint = this.getMaxScrollOffset() > 0 ? \" \u2022 PgUp/PgDn history\" : \"\";\n const hints = `${baseHint}${cycleHint}${scrollHint}`;\n const compactHints = this.editor ? `Enter \u2022 ${exit}` : exit;\n const selectedHints = visibleWidth(hints) <= width ? hints : compactHints;\n const loaderWidth = Math.max(1, width - visibleWidth(selectedHints) - 3);\n const loaderLine = this.loader.render(loaderWidth).at(-1) ?? \"Answering\u2026\";\n return truncateToWidth(`${loaderLine} \u2022 ${this.theme.fg(\"muted\", selectedHints)}`, width);\n }\n\n private createHeaderComponent(): Component {\n return {\n render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],\n invalidate() {},\n };\n }\n\n private createTranscriptComponent(): Component {\n return {\n render: (width) => {\n const lines = renderTranscriptLines(this.transcriptComponents, width);\n this.lastContentLineCount = lines.length;\n return lines;\n },\n invalidate: () => {\n for (const component of this.transcriptComponents) component.invalidate();\n },\n };\n }\n\n private createSteeringComponent(): Component {\n return {\n render: (width) =>\n renderSteeringLines(this.options.steering?.questions ?? [], width, this.theme, MAX_STEERING_DISPLAY_LINES),\n invalidate() {},\n };\n }\n\n private createFooterComponent(): Component {\n return {\n render: (width) => [this.renderFooter(width)],\n invalidate: () => this.loader.invalidate(),\n };\n }\n\n private getMaxScrollOffset(): number {\n return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);\n }\n}\n\nexport function formatSideTranscript(turns: readonly SideThreadTurn[]): string {\n return turns\n .map((turn) => {\n const question = escapeTerminalControls(turn.question);\n const rawAnswer = escapeTerminalControls(turn.answer);\n const answer = turn.kind === \"error\" ? `Error: ${rawAnswer}` : rawAnswer;\n return `${question}\\n\\n${answer}`;\n })\n .join(\"\\n\\n\");\n}\n\nfunction buildTranscriptComponents(\n turns: readonly SideThreadTurn[],\n theme: Theme,\n pendingQuestion?: string,\n markdownTransformers: readonly MarkdownTransformer[] = [],\n): Component[] {\n const components = turns.flatMap((turn): Component[] => {\n const question = new UserMessageComponent(\n escapeTerminalControls(turn.question),\n getMarkdownTheme(),\n 1,\n markdownTransformers,\n );\n if (turn.kind === \"error\") {\n const error = new Markdown(`Error: ${escapeTerminalControls(turn.answer)}`, 1, 1, getMarkdownTheme(), {\n color: (text) => theme.fg(\"error\", text),\n });\n return [question, error];\n }\n const response: AssistantMessage = {\n ...turn.response,\n content: [{ type: \"text\", text: escapeTerminalControls(turn.answer) }],\n stopReason: \"stop\",\n errorMessage: undefined,\n };\n return [question, new AssistantMessageComponent(response, true, getMarkdownTheme(), \"\", 1, markdownTransformers)];\n });\n if (pendingQuestion) {\n components.push(\n new UserMessageComponent(escapeTerminalControls(pendingQuestion), getMarkdownTheme(), 1, markdownTransformers),\n );\n }\n return components;\n}\n\nfunction renderTranscriptLines(components: readonly Component[], width: number): string[] {\n return components.flatMap((component) => component.render(width)).map(stripShellIntegrationMarkers);\n}\n\nfunction renderSideThreadHeader(width: number, theme: Theme, thinkingLevel?: BtwThinkingLevel): string {\n const thinking = thinkingLevel ? ` \u00B7 thinking ${thinkingLevel}` : \"\";\n const title = truncateToWidth(`\u2500 btw \u00B7 side thread${thinking} `, width);\n const ruleWidth = Math.max(0, width - visibleWidth(title));\n return theme.fg(\"muted\", `${title}${\"\u2500\".repeat(ruleWidth)}`);\n}\n\nfunction fitComposerLayout(\n header: string,\n contentLines: string[],\n footer: string,\n editorLines: string[],\n availableRows: number,\n statusLines: string[] = [],\n): string[] {\n const lines = [header, ...contentLines, ...statusLines, footer, ...editorLines];\n if (lines.length <= availableRows) return lines;\n if (availableRows <= 1) return [header];\n const editorBudget = Math.max(0, availableRows - 2);\n return [header, footer, ...fitEditorLines(editorLines, editorBudget)];\n}\n\nfunction fitEditorLines(editorLines: string[], budget: number): string[] {\n if (budget <= 0) return [];\n if (editorLines.length <= budget) return editorLines;\n const cursorIndex = editorLines.findIndex((line) => line.includes(CURSOR_MARKER));\n if (cursorIndex < 0) return editorLines.slice(-budget);\n const start = Math.min(cursorIndex, editorLines.length - budget);\n return editorLines.slice(start, start + budget);\n}\n\nfunction renderSteeringLines(questions: readonly string[], width: number, theme: Theme, maxLines: number): string[] {\n if (questions.length === 0 || maxLines <= 0) return [];\n const formatQuestion = (question: string) => sanitizeSingleLine(question) || \"(non-printing message)\";\n if (maxLines === 1 && questions.length > 1) {\n return [\n truncateToWidth(\n theme.fg(\"dim\", `Steering (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? \"\")}`),\n width,\n ),\n ];\n }\n const hasOverflow = questions.length > maxLines;\n const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;\n const lines = questions\n .slice(0, questionLimit)\n .map((question) => truncateToWidth(theme.fg(\"dim\", `Steering: ${formatQuestion(question)}`), width));\n if (hasOverflow) {\n lines.push(truncateToWidth(theme.fg(\"dim\", `Steering: \u2026 +${questions.length - questionLimit} more`), width));\n }\n return lines;\n}\n\nfunction stripShellIntegrationMarkers(line: string): string {\n return OSC133_MARKERS.reduce((result, marker) => result.replaceAll(marker, \"\"), line);\n}\n\nfunction escapeTerminalControls(text: string): string {\n return [...text]\n .map((character) => {\n if (character === \"\\n\") return character;\n if (character === \"\\t\") return \" \";\n const code = character.charCodeAt(0);\n if (code <= 31 || (code >= 127 && code <= 159)) {\n return `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n }\n return character;\n })\n .join(\"\");\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAAA;AAAA,EAEE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,sBAAuE;;;ACNhF,SAAyB,KAAK,YAAsB,iBAAiB,oBAAoB;AAGzF,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB,IAAI,KAAK,UAAU,QAAW,EAAE,aAAa,WAAW,CAAC;AA0C7E,SAAS,iBAAiB,OAAmF;AAClH,SAAO,MAAM,OAAO,CAAC,SAAgE,KAAK,SAAS,UAAU;AAC/G;AAEO,SAAS,8BACd,OACA,OACyB;AACzB,QAAM,WAAW,iBAAiB,KAAK;AACvC,QAAM,WACJ,MAAM,SAAS,WACX,SAAS,MAAM,EAAE,IACjB,MAAM,SAAS,SACb,SAAS,MAAM,KAAK,IAAI,GAAG,MAAM,iBAAiB,CAAC,IACnD;AACR,SAAO,SAAS,QAAQ,CAAC,SAAS;AAAA,IAChC,EAAE,MAAM,QAAiB,MAAM,KAAK,SAAS;AAAA,IAC7C,EAAE,MAAM,aAAsB,MAAM,KAAK,OAAO;AAAA,E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
|
|
6
6
|
"names": ["isKeyRelease", "isKittyProtocolActive", "Key", "truncateToWidth", "matchesKey", "formatKeyLabel", "matchesKey", "formatKeyLabel", "formatKeyLabel", "isKittyProtocolActive", "copyToClipboard", "Key", "isKeyRelease", "truncateToWidth", "Key", "matchesKey", "formatError", "formatKeyLabel", "error", "value", "formatError", "matchesKey", "Key", "notifySafely", "formatError", "result", "Key", "matchesKey", "truncateToWidth", "visibleWidth", "truncateToWidth", "matchesKey", "Key", "visibleWidth", "escapeTerminalControls", "truncateToWidth", "visibleWidth", "formatError", "formatError", "notifySafely", "model"]
|
|
7
7
|
}
|