@narumitw/pi-btw 0.55.2 → 0.55.3
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/dist/index.ts +143 -46
- package/dist/index.ts.map +3 -3
- package/package.json +2 -2
- package/src/fullscreen-ui.ts +136 -22
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/btw.ts", "../src/bring-to-main.ts", "../src/fullscreen-ui.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\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)) return { model: configuredModel, auth };\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)) return { model: currentModel, auth };\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('\" | \"')}\", and boolean rememberThinkingLevelChanges. 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 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\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(ctx, (fullscreenCtx) => {\n\t\t\t\t\tif (!state) {\n\t\t\t\t\t\tconst createdAt = Date.now();\n\t\t\t\t\t\tstate = {\n\t\t\t\t\t\t\tid: `btw-${nextThreadNumber}`,\n\t\t\t\t\t\t\tthread: createSideThread(\n\t\t\t\t\t\t\t\tselectedConversationContext ??\n\t\t\t\t\t\t\t\t\tbuildConversationContext(fullscreenCtx.sessionManager.getBranch()),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tthinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),\n\t\t\t\t\t\t\tcreatedAt,\n\t\t\t\t\t\t\tupdatedAt: createdAt,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tnextThreadNumber += 1;\n\t\t\t\t\t}\n\t\t\t\t\treturn runThread({\n\t\t\t\t\t\tinitialQuestion: question || undefined,\n\t\t\t\t\t\tselected: resolution.selected,\n\t\t\t\t\t\tthinkingLevel: state.thinkingLevel,\n\t\t\t\t\t\trememberThinkingLevelChanges:\n\t\t\t\t\t\t\t!sameAsMainThinkingLevel && effectiveRememberThinkingLevelChanges(settings),\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tctx: fullscreenCtx,\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}).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\ttype OverlayHandle,\n\ttype TUI,\n\tTuiAltScreen,\n\ttruncateToWidth,\n} from \"@earendil-works/pi-tui\";\nimport { 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};\n\nexport interface BtwFullscreenLayoutComponent extends Component {\n\tgetFullscreenLayout(): Component;\n}\n\nexport type BtwFullscreenTuiFactory = (parent: TUI, theme: Theme) => BtwFullscreenTui;\n\nexport interface BtwFullscreenDependencies {\n\tcreateTui?: BtwFullscreenTuiFactory;\n\topenUrl?: (url: string) => void;\n\tcopyToClipboard?: (text: string) => Promise<void>;\n}\n\nexport type RunBtwFullscreen = <T>(\n\tctx: ExtensionCommandContext,\n\trun: (ctx: ExtensionCommandContext) => Promise<T>,\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\tdependencies: BtwFullscreenDependencies = {},\n): Promise<T> {\n\tconst createTui =\n\t\tdependencies.createTui ??\n\t\t((parent: TUI, theme: Theme) =>\n\t\t\tcreateBtwFullscreenTui(\n\t\t\t\tparent,\n\t\t\t\ttheme,\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\tconst outcome = await ctx.ui.custom<FullscreenOutcome<T>>(\n\t\t(parent, theme, keybindings, done) =>\n\t\t\tnew 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),\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\nfunction createBtwFullscreenTui(\n\tparent: TUI,\n\ttheme: Theme,\n\topenUrl: (url: string) => void,\n\tcopyToClipboard: (text: string) => Promise<void>,\n): BtwFullscreenTui {\n\tconst styleSearchMatch = (text: string) =>\n\t\ttheme.bg(\"searchMatchBg\", theme.fg(\"searchMatchText\", text));\n\treturn new TuiAltScreen(parent.terminal, parent.getShowHardwareCursor(), undefined, {\n\t\tmouse: true,\n\t\tsearchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),\n\t\tsearchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),\n\t\topenUrl,\n\t\tcopySelection: async (text) => {\n\t\t\ttry {\n\t\t\t\tawait copyToClipboard(text);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t});\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 cancelActiveCustom: (() => void) | undefined;\n\tprivate started = false;\n\tprivate disposed = false;\n\tprivate finished = false;\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) {\n\t\tqueueMicrotask(() => void this.start());\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\tlet parentStopped = false;\n\t\tlet fullscreenCreated = false;\n\t\ttry {\n\t\t\tif (this.disposed) throw new FullscreenUiDisposedError();\n\t\t\tthis.parent.stop({ preserveScreen: true });\n\t\t\tparentStopped = true;\n\t\t\tif (this.disposed) throw new FullscreenUiDisposedError();\n\t\t\tthis.fullscreen = this.createTui(this.parent, this.theme);\n\t\t\tfullscreenCreated = true;\n\t\t\tthis.fullscreen.start();\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\tlet cleanupError: unknown;\n\t\ttry {\n\t\t\tthis.cancelActiveCustom?.();\n\t\t} catch (error) {\n\t\t\tcleanupError = error;\n\t\t}\n\t\tif (fullscreenCreated) {\n\t\t\ttry {\n\t\t\t\tthis.fullscreen?.stop({ preserveScreen: true });\n\t\t\t} catch (error) {\n\t\t\t\tcleanupError ??= error;\n\t\t\t}\n\t\t}\n\t\tif (parentStopped) {\n\t\t\ttry {\n\t\t\t\tthis.parent.start();\n\t\t\t\tthis.parent.renderNow(false);\n\t\t\t} catch (error) {\n\t\t\t\tcleanupError ??= error;\n\t\t\t}\n\t\t}\n\t\tif (cleanupError !== undefined) outcome = { kind: \"failed\", error: cleanupError };\n\t\tthis.finished = true;\n\t\tthis.done(outcome);\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\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\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\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", "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", "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 { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\n\nexport const BTW_SETTINGS_FILE = \"pi-btw.json\";\nexport const DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES = true;\nconst MAX_SETTINGS_BYTES = 64 * 1024;\n\nexport interface BtwSettings {\n\tmodel?: string;\n\tthinkingLevel?: BtwThinkingLevel;\n\trememberThinkingLevelChanges?: 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\tthinkingLevel?: BtwThinkingLevel;\n\trememberThinkingLevelChanges?: boolean;\n}\n\nexport interface UpdateBtwSettingsOptions {\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, \"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\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 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\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 (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\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}\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}: 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),\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}\n\nexport async function completeSideQuestion({\n\tmodel,\n\tquestion,\n\tconversationContext,\n\tthinkingLevel,\n\tauth,\n\tsignal,\n\tcompleteSimple,\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),\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\nfunction buildStreamOptions(\n\tauth: SideQuestionAuth,\n\tthinkingLevel: BtwThinkingLevel,\n\tsignal?: AbortSignal,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = {\n\t\tapiKey: auth.apiKey,\n\t\theaders: auth.headers,\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\ttype BtwSettings,\n\ttype BtwSettingsPatch,\n\tbtwSettingsPath,\n\teffectiveRememberThinkingLevelChanges,\n\treadBtwSettings,\n\ttype UpdateBtwSettingsOptions,\n\tupdateBtwSettings,\n} from \"./settings.js\";\nimport { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\nimport { 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\";\ntype BtwMenuAction = \"start\" | \"start-tree\" | \"resume\" | \"set-thinking\" | \"set-remember\";\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\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],\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 pi-btw thinking level and fixed-level shortcut memory\",\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],\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\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},\n\t});\n\n\tconst result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>\n\t\trunMenu(menuContext, menu, { getState: loadState }),\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): 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>(\n\t\t\t\t\t\t(tui, theme, keybindings, done) =>\n\t\t\t\t\t\t\tfactory(tui, theme, keybindings, (value) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tliveEditorText = target.getEditorText();\n\t\t\t\t\t\t\t\t} catch {\n\t\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\t}\n\t\t\t\t\t\t\t\tcompleted = true;\n\t\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\tcustomOptions,\n\t\t\t\t\t);\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 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 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.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\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);\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.finished = true;\n\t\t\tthis.onAction({ kind: \"close\" });\n\t\t\treturn;\n\t\t}\n\t\tif (this.canBringToMain && matchesKey(data, Key.ctrl(\"r\"))) {\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\tthinking.keybindings.matches(data, \"app.thinking.cycle\")\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\tif (this.warning) {\n\t\t\tconst warning = width < 32 ? \"Empty \u2022 Ctrl+C\" : `${this.warning} \u2022 Ctrl+C 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 && thinking.levels.length > 1 && this.thinkingLevel\n\t\t\t\t? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${thinkingKeyLabel(thinking.keybindings)} cycle`\n\t\t\t\t: \"\";\n\t\tconst base = this.canBringToMain\n\t\t\t? \"btw \u2022 Enter send \u2022 Ctrl+R bring to main \u2022 Ctrl+C exit\"\n\t\t\t: \"btw \u2022 Enter send \u2022 Ctrl+C exit\";\n\t\tconst fullBase = `${base}${cycleHint}`;\n\t\tconst fallbackBase = \"btw \u2022 Enter \u2022 Ctrl+C\";\n\t\tconst compactBase = this.canBringToMain ? \"btw \u2022 Enter \u2022 Ctrl+R \u2022 Ctrl+C\" : 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 = this.canBringToMain\n\t\t\t\t? \"Enter \u2022 Ctrl+R \u2022 Ctrl+C \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 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.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\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);\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.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\tthinking.keybindings.matches(data, \"app.thinking.cycle\")\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\tif (this.warning) {\n\t\t\tconst warning = width < 32 ? \"Empty \u2022 Ctrl+C\" : `${this.warning} \u2022 Ctrl+C cancel`;\n\t\t\treturn truncateToWidth(this.theme.fg(\"warning\", warning), width);\n\t\t}\n\t\tconst baseHint = this.editor ? \"Enter steer \u2022 Ctrl+C cancel\" : \"Ctrl+C cancel\";\n\t\tconst thinking = this.options.steering?.thinking;\n\t\tconst cycleHint =\n\t\t\tthinking && thinking.levels.length > 1 && this.thinkingLevel\n\t\t\t\t? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${thinkingKeyLabel(thinking.keybindings)} 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 Ctrl+C\" : \"Ctrl+C\";\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 thinkingKeyLabel(keybindings: KeybindingsManager): string {\n\tconst key =\n\t\tsanitizeSingleLine(String(keybindings.getKeys(\"app.thinking.cycle\")[0] ?? \"shift+tab\")) ||\n\t\t\"Shift+Tab\";\n\treturn key\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\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 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,O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,iBAAiB;AAClE;AAEA,SAAS,oBAAoB,SAA4B;AACxD,MAAI,OAAO,YAAY,SAAU,QAAO,CAAC,QAAQ,KAAK,CAAC,EAAE,OAAO,OAAO;AACvE,MAAI,CAAC,MAAM,QAAQ,OAAO,EAAG,QAAO,CAAC;AAErC,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,SAAS;AAC3B,QAAI,CAAC,QAAQ,OAAO,SAAS,SAAU;AACvC,UAAM,QAAQ;AACd,QAAI,MAAM,SAAS,UAAU,OAAO,MAAM,SAAS,UAAU;AAC5D,YAAM,KAAK,MAAM,KAAK,KAAK,CAAC;AAAA,IAC7B,WAAW,MAAM,SAAS,cAAc,OAAO,MAAM,SAAS,UAAU;AACvE,YAAM,KAAK,cAAc,MAAM,IAAI,IAAI,WAAW,MAAM,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;",
|
|
6
|
-
"names": ["truncateToWidth", "copyToClipboard", "truncateToWidth", "Key", "matchesKey", "formatError", "value", "formatError", "matchesKey", "Key", "notifySafely", "formatError", "result", "Key", "matchesKey", "truncateToWidth", "visibleWidth", "matchesKey", "Key", "truncateToWidth", "visibleWidth", "escapeTerminalControls", "truncateToWidth", "visibleWidth", "formatError", "formatError", "notifySafely", "model"]
|
|
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\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)) return { model: configuredModel, auth };\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)) return { model: currentModel, auth };\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('\" | \"')}\", and boolean rememberThinkingLevelChanges. 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 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\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(ctx, (fullscreenCtx) => {\n\t\t\t\t\tif (!state) {\n\t\t\t\t\t\tconst createdAt = Date.now();\n\t\t\t\t\t\tstate = {\n\t\t\t\t\t\t\tid: `btw-${nextThreadNumber}`,\n\t\t\t\t\t\t\tthread: createSideThread(\n\t\t\t\t\t\t\t\tselectedConversationContext ??\n\t\t\t\t\t\t\t\t\tbuildConversationContext(fullscreenCtx.sessionManager.getBranch()),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tthinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),\n\t\t\t\t\t\t\tcreatedAt,\n\t\t\t\t\t\t\tupdatedAt: createdAt,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tnextThreadNumber += 1;\n\t\t\t\t\t}\n\t\t\t\t\treturn runThread({\n\t\t\t\t\t\tinitialQuestion: question || undefined,\n\t\t\t\t\t\tselected: resolution.selected,\n\t\t\t\t\t\tthinkingLevel: state.thinkingLevel,\n\t\t\t\t\t\trememberThinkingLevelChanges:\n\t\t\t\t\t\t\t!sameAsMainThinkingLevel && effectiveRememberThinkingLevelChanges(settings),\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tctx: fullscreenCtx,\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}).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\tKey,\n\tmatchesKey,\n\ttype OverlayHandle,\n\ttype TUI,\n\tTuiAltScreen,\n\ttype TuiInputListener,\n\ttype TuiInputListenerResult,\n\ttruncateToWidth,\n} from \"@earendil-works/pi-tui\";\nimport { 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\taddInputListenerBeforeViewport?(listener: TuiInputListener): () => void;\n};\n\nexport interface BtwFullscreenLayoutComponent extends Component {\n\tgetFullscreenLayout(): Component;\n}\n\nexport type BtwFullscreenTuiFactory = (parent: TUI, theme: Theme) => BtwFullscreenTui;\n\nexport interface BtwFullscreenDependencies {\n\tcreateTui?: BtwFullscreenTuiFactory;\n\topenUrl?: (url: string) => void;\n\tcopyToClipboard?: (text: string) => Promise<void>;\n}\n\nexport type RunBtwFullscreen = <T>(\n\tctx: ExtensionCommandContext,\n\trun: (ctx: ExtensionCommandContext) => Promise<T>,\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\tdependencies: BtwFullscreenDependencies = {},\n): Promise<T> {\n\tconst createTui =\n\t\tdependencies.createTui ??\n\t\t((parent: TUI, theme: Theme) =>\n\t\t\tcreateBtwFullscreenTui(\n\t\t\t\tparent,\n\t\t\t\ttheme,\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);\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\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.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\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\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\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.beforeViewport.delete(listener);\n\t\tlisteners.regular.delete(listener);\n\t}\n}\n\nfunction createBtwFullscreenTui(\n\tparent: TUI,\n\ttheme: Theme,\n\topenUrl: (url: string) => void,\n\tcopyToClipboard: (text: string) => Promise<void>,\n): BtwFullscreenTui {\n\tconst styleSearchMatch = (text: string) =>\n\t\ttheme.bg(\"searchMatchBg\", theme.fg(\"searchMatchText\", text));\n\treturn new BtwTuiAltScreen(parent.terminal, parent.getShowHardwareCursor(), undefined, {\n\t\tmouse: true,\n\t\tsearchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),\n\t\tsearchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),\n\t\topenUrl,\n\t\tcopySelection: async (text) => {\n\t\t\ttry {\n\t\t\t\tawait copyToClipboard(text);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t});\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 parentRestarted = false;\n\tprivate fullscreenCreated = false;\n\tprivate fullscreenStopped = false;\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) {\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);\n\t\t\tthis.fullscreenCreated = true;\n\t\t\tthis.fullscreen.start();\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.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\tif (isKeyRelease(data) || !matchesKey(data, Key.ctrl(\"c\"))) return undefined;\n\t\t\t\ttry {\n\t\t\t\t\tthis.hardCancelActiveCustom?.();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.restoreParent();\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\tthis.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 restoreParent(): void {\n\t\tthis.removeHardCancelListener?.();\n\t\tthis.removeHardCancelListener = undefined;\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.parentRestarted) 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.parent.start();\n\t\t\tthis.parentRestarted = true;\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", "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", "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 { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\n\nexport const BTW_SETTINGS_FILE = \"pi-btw.json\";\nexport const DEFAULT_REMEMBER_THINKING_LEVEL_CHANGES = true;\nconst MAX_SETTINGS_BYTES = 64 * 1024;\n\nexport interface BtwSettings {\n\tmodel?: string;\n\tthinkingLevel?: BtwThinkingLevel;\n\trememberThinkingLevelChanges?: 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\tthinkingLevel?: BtwThinkingLevel;\n\trememberThinkingLevelChanges?: boolean;\n}\n\nexport interface UpdateBtwSettingsOptions {\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, \"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\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 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\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 (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\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}\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}: 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),\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}\n\nexport async function completeSideQuestion({\n\tmodel,\n\tquestion,\n\tconversationContext,\n\tthinkingLevel,\n\tauth,\n\tsignal,\n\tcompleteSimple,\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),\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\nfunction buildStreamOptions(\n\tauth: SideQuestionAuth,\n\tthinkingLevel: BtwThinkingLevel,\n\tsignal?: AbortSignal,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = {\n\t\tapiKey: auth.apiKey,\n\t\theaders: auth.headers,\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\ttype BtwSettings,\n\ttype BtwSettingsPatch,\n\tbtwSettingsPath,\n\teffectiveRememberThinkingLevelChanges,\n\treadBtwSettings,\n\ttype UpdateBtwSettingsOptions,\n\tupdateBtwSettings,\n} from \"./settings.js\";\nimport { BTW_THINKING_LEVELS, type BtwThinkingLevel } from \"./side-thread.js\";\nimport { 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\";\ntype BtwMenuAction = \"start\" | \"start-tree\" | \"resume\" | \"set-thinking\" | \"set-remember\";\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\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],\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 pi-btw thinking level and fixed-level shortcut memory\",\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],\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\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},\n\t});\n\n\tconst result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>\n\t\trunMenu(menuContext, menu, { getState: loadState }),\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): 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>(\n\t\t\t\t\t\t(tui, theme, keybindings, done) =>\n\t\t\t\t\t\t\tfactory(tui, theme, keybindings, (value) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tliveEditorText = target.getEditorText();\n\t\t\t\t\t\t\t\t} catch {\n\t\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\t}\n\t\t\t\t\t\t\t\tcompleted = true;\n\t\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\tcustomOptions,\n\t\t\t\t\t);\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 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 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.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\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);\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.finished = true;\n\t\t\tthis.onAction({ kind: \"close\" });\n\t\t\treturn;\n\t\t}\n\t\tif (this.canBringToMain && matchesKey(data, Key.ctrl(\"r\"))) {\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\tthinking.keybindings.matches(data, \"app.thinking.cycle\")\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\tif (this.warning) {\n\t\t\tconst warning = width < 32 ? \"Empty \u2022 Ctrl+C\" : `${this.warning} \u2022 Ctrl+C 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 && thinking.levels.length > 1 && this.thinkingLevel\n\t\t\t\t? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${thinkingKeyLabel(thinking.keybindings)} cycle`\n\t\t\t\t: \"\";\n\t\tconst base = this.canBringToMain\n\t\t\t? \"btw \u2022 Enter send \u2022 Ctrl+R bring to main \u2022 Ctrl+C exit\"\n\t\t\t: \"btw \u2022 Enter send \u2022 Ctrl+C exit\";\n\t\tconst fullBase = `${base}${cycleHint}`;\n\t\tconst fallbackBase = \"btw \u2022 Enter \u2022 Ctrl+C\";\n\t\tconst compactBase = this.canBringToMain ? \"btw \u2022 Enter \u2022 Ctrl+R \u2022 Ctrl+C\" : 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 = this.canBringToMain\n\t\t\t\t? \"Enter \u2022 Ctrl+R \u2022 Ctrl+C \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 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.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\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);\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.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\tthinking.keybindings.matches(data, \"app.thinking.cycle\")\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\tif (this.warning) {\n\t\t\tconst warning = width < 32 ? \"Empty \u2022 Ctrl+C\" : `${this.warning} \u2022 Ctrl+C cancel`;\n\t\t\treturn truncateToWidth(this.theme.fg(\"warning\", warning), width);\n\t\t}\n\t\tconst baseHint = this.editor ? \"Enter steer \u2022 Ctrl+C cancel\" : \"Ctrl+C cancel\";\n\t\tconst thinking = this.options.steering?.thinking;\n\t\tconst cycleHint =\n\t\t\tthinking && thinking.levels.length > 1 && this.thinkingLevel\n\t\t\t\t? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${thinkingKeyLabel(thinking.keybindings)} 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 Ctrl+C\" : \"Ctrl+C\";\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 thinkingKeyLabel(keybindings: KeybindingsManager): string {\n\tconst key =\n\t\tsanitizeSingleLine(String(keybindings.getKeys(\"app.thinking.cycle\")[0] ?? \"shift+tab\")) ||\n\t\t\"Shift+Tab\";\n\treturn key\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\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 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;A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ACd,QAAI,MAAM,SAAS,UAAU,OAAO,MAAM,SAAS,UAAU;AAC5D,YAAM,KAAK,MAAM,KAAK,KAAK,CAAC;AAAA,IAC7B,WAAW,MAAM,SAAS,cAAc,OAAO,MAAM,SAAS,UAAU;AACvE,YAAM,KAAK,cAAc,MAAM,IAAI,IAAI,WAAW,MAAM,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;",
|
|
6
|
+
"names": ["Key", "matchesKey", "truncateToWidth", "copyToClipboard", "truncateToWidth", "matchesKey", "Key", "Key", "matchesKey", "formatError", "value", "formatError", "matchesKey", "Key", "notifySafely", "formatError", "result", "Key", "matchesKey", "truncateToWidth", "visibleWidth", "matchesKey", "Key", "truncateToWidth", "visibleWidth", "escapeTerminalControls", "truncateToWidth", "visibleWidth", "formatError", "formatError", "notifySafely", "model"]
|
|
7
7
|
}
|