@narumitw/pi-btw 0.63.4 → 0.63.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,824 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+ import {
4
+ BtwPasteGuard,
5
+ btwKeyHasReachableInput,
6
+ formatKeyLabel,
7
+ getBtwHostInputBlockers,
8
+ getBtwKeybindings,
9
+ getBtwShortcuts,
10
+ normalizeBtwKey,
11
+ sanitizeSingleLine
12
+ } from "./chunk-FWW662MW.ts";
13
+
14
+ // src/transcript-pager.ts
15
+ import {
16
+ AssistantMessageComponent,
17
+ getMarkdownTheme,
18
+ UserMessageComponent
19
+ } from "@earendil-works/pi-coding-agent";
20
+ import {
21
+ CURSOR_MARKER,
22
+ Editor,
23
+ isKeyRelease,
24
+ renderFakeCursor,
25
+ ScrollView,
26
+ Spacer,
27
+ Text,
28
+ truncateToWidth as truncateToWidth2,
29
+ VStack,
30
+ visibleWidth as visibleWidth2
31
+ } from "@earendil-works/pi-tui";
32
+
33
+ // src/conversation-chrome.ts
34
+ import { Loader, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
35
+ var BtwWorkingIndicator = class extends Loader {
36
+ renderInBorder(width) {
37
+ const line = super.render(width + 2)[1] ?? "";
38
+ return truncateToWidth(line.startsWith(" ") ? line.slice(1).trimEnd() : line.trimEnd(), width, "");
39
+ }
40
+ renderSpinnerInBorder(width) {
41
+ return truncateToWidth(this.getRenderedIndicator(), width, "");
42
+ }
43
+ };
44
+ function renderWorkingBorder(width, hiddenLineCount, borderColor, status) {
45
+ if (width <= 0) return "";
46
+ let label = status.renderInBorder(Math.max(1, width - 5));
47
+ let labelWidth = visibleWidth(label);
48
+ if (labelWidth === 0) return void 0;
49
+ const overflow = hiddenLineCount > 0 ? ` \u2191 ${hiddenLineCount} more ` : void 0;
50
+ const overflowWidth = overflow ? visibleWidth(overflow) : 0;
51
+ const overflowStart = Math.floor((width - overflowWidth) / 2);
52
+ const fitsOverflow = () => overflow !== void 0 && overflowWidth + 2 <= width && overflowStart - (3 + labelWidth + 1) >= 1;
53
+ if (overflow && !fitsOverflow()) {
54
+ label = status.renderSpinnerInBorder(width);
55
+ labelWidth = visibleWidth(label);
56
+ }
57
+ if (fitsOverflow()) {
58
+ const leftWidth = 3 + labelWidth + 1;
59
+ return borderColor("\u2500\u2500 ") + label + borderColor(
60
+ ` ${"\u2500".repeat(overflowStart - leftWidth)}${overflow}${"\u2500".repeat(width - overflowStart - overflowWidth)}`
61
+ );
62
+ }
63
+ if (width >= labelWidth + 5) {
64
+ return borderColor("\u2500\u2500 ") + label + borderColor(` ${"\u2500".repeat(width - labelWidth - 4)}`);
65
+ }
66
+ label = status.renderSpinnerInBorder(width);
67
+ labelWidth = visibleWidth(label);
68
+ const prefix = Math.min(3, Math.max(0, width - labelWidth));
69
+ return borderColor("\u2500".repeat(prefix)) + label + borderColor("\u2500".repeat(Math.max(0, width - prefix - labelWidth)));
70
+ }
71
+ function renderConversationFooter(width, theme, options) {
72
+ if (width < 3) return [];
73
+ const focus = options.focus ? `${options.focus.pane === "side" ? "BTW" : "Main"} focus` : void 0;
74
+ const left = focus && visibleWidth(`btw \xB7 ${focus}`) <= width ? `btw \xB7 ${focus}` : "btw";
75
+ const model = options.model ? sanitizeSingleLine(`${options.model.provider}/${options.model.id}`) : "";
76
+ const thinking = options.thinkingLevel ? `thinking ${options.thinkingLevel}` : "";
77
+ const right = [[model, thinking].filter(Boolean).join(" \u2022 "), thinking, model].find(
78
+ (value) => value && visibleWidth(left) + 2 + visibleWidth(value) <= width
79
+ );
80
+ const identity = right ? `${left}${" ".repeat(width - visibleWidth(left) - visibleWidth(right))}${right}` : left;
81
+ return [
82
+ theme.fg("dim", identity),
83
+ ...options.hint ? [theme.fg(options.warning ? "warning" : "muted", options.hint)] : []
84
+ ];
85
+ }
86
+
87
+ // src/transcript-pager.ts
88
+ var MAX_STEERING_DISPLAY_LINES = 3;
89
+ var OSC133_MARKERS = ["\x1B]133;A\x07", "\x1B]133;B\x07", "\x1B]133;C\x07"];
90
+ var RESERVED_APP_LINES = 3;
91
+ var BtwComposer = class extends Editor {
92
+ constructor(tui, theme, dispatch, loader) {
93
+ super(tui, theme);
94
+ this.dispatch = dispatch;
95
+ this.loader = loader;
96
+ }
97
+ dispatch;
98
+ loader;
99
+ handleInput(data) {
100
+ this.dispatch(data);
101
+ }
102
+ handleEditorInput(data) {
103
+ super.handleInput(data);
104
+ }
105
+ render(width) {
106
+ if (width <= 0) return [];
107
+ return super.render(Math.max(3, width)).map((line) => {
108
+ if (width <= 2 && line.includes(CURSOR_MARKER))
109
+ return CURSOR_MARKER + renderFakeCursor(" ") + " ".repeat(width - 1);
110
+ return truncateToWidth2(line, width, "");
111
+ });
112
+ }
113
+ renderTopBorder(width, hiddenLineCount) {
114
+ if (!this.loader) return super.renderTopBorder(width, hiddenLineCount);
115
+ return renderWorkingBorder(width, hiddenLineCount, this.borderColor, this.loader) ?? super.renderTopBorder(width, hiddenLineCount);
116
+ }
117
+ };
118
+ var VIEWPORT_ACTIONS = [
119
+ "tui.altScreen.search",
120
+ "tui.altScreen.pageUp",
121
+ "tui.altScreen.pageDown",
122
+ "tui.altScreen.halfPageUp",
123
+ "tui.altScreen.halfPageDown",
124
+ "tui.altScreen.lineUp",
125
+ "tui.altScreen.lineDown",
126
+ "tui.altScreen.previousPrompt",
127
+ "tui.altScreen.nextPrompt",
128
+ "tui.altScreen.top",
129
+ "tui.altScreen.bottom"
130
+ ];
131
+ var BEFORE_SUBMIT = [
132
+ "tui.input.copy",
133
+ "tui.editor.undo",
134
+ "tui.input.tab",
135
+ "tui.editor.deleteToLineEnd",
136
+ "tui.editor.deleteToLineStart",
137
+ "tui.editor.deleteWordBackward",
138
+ "tui.editor.deleteWordForward",
139
+ "tui.editor.deleteCharBackward",
140
+ "tui.editor.deleteCharForward",
141
+ "tui.editor.yank",
142
+ "tui.editor.yankPop",
143
+ "tui.editor.historyPrevious",
144
+ "tui.editor.historyNext",
145
+ "tui.editor.cursorLineStart",
146
+ "tui.editor.cursorLineEnd",
147
+ "tui.editor.cursorWordLeft",
148
+ "tui.editor.cursorWordRight",
149
+ "tui.input.newLine"
150
+ ];
151
+ function usableKeys(keybindings, action, blockers) {
152
+ return keybindings.getKeys(action).flatMap((candidate) => {
153
+ const key = normalizeBtwKey(candidate);
154
+ return key && btwKeyHasReachableInput(key, blockers) ? [key] : [];
155
+ });
156
+ }
157
+ function submitHint(tui, keybindings, verb) {
158
+ const earlier = tui.mode === "fullscreen" ? VIEWPORT_ACTIONS : ["tui.altScreen.pageUp", "tui.altScreen.pageDown"];
159
+ const blockers = [
160
+ ...getBtwHostInputBlockers(tui),
161
+ "ctrl+c",
162
+ "shift+backspace",
163
+ "shift+delete",
164
+ ...[...earlier, ...BEFORE_SUBMIT].flatMap((id) => keybindings.getKeys(id))
165
+ ];
166
+ const key = usableKeys(keybindings, "tui.input.submit", blockers)[0];
167
+ return key ? `${formatKeyLabel(key)} ${verb}` : "";
168
+ }
169
+ function pagingHint(tui, keybindings) {
170
+ const actions = ["tui.altScreen.pageUp", "tui.altScreen.pageDown"];
171
+ const labels = actions.flatMap((action) => {
172
+ const earlier = tui.mode === "fullscreen" ? VIEWPORT_ACTIONS.slice(0, VIEWPORT_ACTIONS.indexOf(action)) : action === "tui.altScreen.pageDown" ? ["tui.altScreen.pageUp"] : [];
173
+ const blockers = [...getBtwHostInputBlockers(tui), "ctrl+c", ...earlier.flatMap((id) => keybindings.getKeys(id))];
174
+ const key = usableKeys(keybindings, action, blockers)[0];
175
+ return key ? [
176
+ formatKeyLabel(key).replace(/Pageup$/u, "PgUp").replace(/Pagedown$/u, "PgDn")
177
+ ] : [];
178
+ });
179
+ return labels.length ? `${labels.join("/")} history` : "";
180
+ }
181
+ function handleFallbackPaging(data, tui, keybindings, scrollView) {
182
+ if (tui.mode === "fullscreen" || isKeyRelease(data)) return false;
183
+ for (const [action, direction] of [
184
+ ["tui.altScreen.pageUp", -1],
185
+ ["tui.altScreen.pageDown", 1]
186
+ ]) {
187
+ if (keybindings.matches(data, action)) {
188
+ scrollView.scrollBy(direction * Math.max(1, scrollView.viewportHeight - 4));
189
+ return true;
190
+ }
191
+ }
192
+ return false;
193
+ }
194
+ function fittingHint(width, variants) {
195
+ return variants.find((hint) => visibleWidth2(hint) <= Math.max(0, width)) ?? "";
196
+ }
197
+ function compactHints(parts) {
198
+ return parts.filter(Boolean).join(" \u2022 ");
199
+ }
200
+ function releaseScrollbar(scrollView) {
201
+ scrollView.setScrollbarActive(false);
202
+ scrollView.setScrollbar("hidden");
203
+ }
204
+ function thinkingBorder(theme, level, text) {
205
+ return level && theme.getThinkingBorderColor ? theme.getThinkingBorderColor(level)(text) : theme.fg("borderMuted", text);
206
+ }
207
+ var PreservingScrollView = class extends ScrollView {
208
+ updateLayout(contentHeight, viewportHeight, requestRender) {
209
+ const preserveManualPosition = !this.isFollowingEnd;
210
+ super.updateLayout(contentHeight, viewportHeight, requestRender);
211
+ if (preserveManualPosition && this.isFollowingEnd) {
212
+ this.scrollTo(this.scrollTop, { disableFollow: true });
213
+ }
214
+ }
215
+ };
216
+ var BtwTranscriptPager = class {
217
+ constructor(tui, theme, turns, onAction, options = {}) {
218
+ this.tui = tui;
219
+ this.theme = theme;
220
+ this.onAction = onAction;
221
+ this.options = options;
222
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
223
+ this.transcriptComponents = buildTranscriptComponents(turns, this.theme, void 0, options.markdownTransformers);
224
+ this.canBringToMain = turns.some((turn) => turn.kind === "answered");
225
+ this.thinkingLevel = options.thinking?.level;
226
+ const editorTheme = {
227
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
228
+ selectList: {
229
+ selectedPrefix: (text) => this.theme.fg("accent", text),
230
+ selectedText: (text) => this.theme.fg("accent", text),
231
+ description: (text) => this.theme.fg("muted", text),
232
+ scrollInfo: (text) => this.theme.fg("dim", text),
233
+ noMatch: (text) => this.theme.fg("warning", text)
234
+ }
235
+ };
236
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data));
237
+ if (options.initialQuestion) this.editor.setText(options.initialQuestion);
238
+ this.editor.onChange = () => {
239
+ this.warning = void 0;
240
+ };
241
+ this.editor.onSubmit = (text) => {
242
+ const question = text.trim();
243
+ if (!question) {
244
+ this.warning = "Question cannot be empty";
245
+ return;
246
+ }
247
+ this.finished = true;
248
+ this.onAction({ kind: "submit", question });
249
+ };
250
+ const transcript = this.createTranscriptComponent();
251
+ this.scrollView = new PreservingScrollView(transcript, {
252
+ follow: "end",
253
+ primary: true,
254
+ scrollbar: "auto",
255
+ scrollbarTrackStyle: (text) => this.theme.fg("scrollbarTrack", text),
256
+ scrollbarThumbStyle: (text) => this.theme.fg("scrollbarThumb", text)
257
+ });
258
+ if (!options.startAtBottom) this.scrollView.scrollTo(0, { disableFollow: true });
259
+ const dock = new VStack([
260
+ { component: this.editor, basis: "auto", shrink: 1, minSize: 1 },
261
+ { component: this.createFooterComponent(), basis: "auto", shrink: 1, minSize: 0 }
262
+ ]);
263
+ this.layoutRoot = new VStack([
264
+ { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
265
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 }
266
+ ]);
267
+ }
268
+ tui;
269
+ theme;
270
+ onAction;
271
+ options;
272
+ workspaceFocus;
273
+ get keybindings() {
274
+ return getBtwKeybindings(this.tui, this.options.keybindings ?? this.options.thinking?.keybindings);
275
+ }
276
+ setWorkspaceFocus(pane, shortcutLabel) {
277
+ this.workspaceFocus = { pane, shortcutLabel: shortcutLabel ? sanitizeSingleLine(shortcutLabel) : void 0 };
278
+ this.tui.requestRender();
279
+ }
280
+ shortcuts;
281
+ pasteGuard = new BtwPasteGuard();
282
+ transcriptComponents;
283
+ editor;
284
+ canBringToMain;
285
+ scrollView;
286
+ layoutRoot;
287
+ lastContentLineCount = 0;
288
+ warning;
289
+ finished = false;
290
+ isFocused = false;
291
+ thinkingLevel;
292
+ get focused() {
293
+ return this.isFocused;
294
+ }
295
+ set focused(value) {
296
+ this.isFocused = value;
297
+ this.editor.focused = value;
298
+ }
299
+ getFullscreenLayout() {
300
+ return this.layoutRoot;
301
+ }
302
+ getPrimaryScrollView() {
303
+ return this.scrollView;
304
+ }
305
+ render(width) {
306
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
307
+ const safeWidth = Math.max(1, width);
308
+ const editorLines = this.editor.render(safeWidth);
309
+ const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
310
+ const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
311
+ this.lastContentLineCount = contentLines.length;
312
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - this.renderFooter(safeWidth).length);
313
+ this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
314
+ return fitComposerLayout(
315
+ contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
316
+ this.renderFooter(safeWidth),
317
+ editorLines,
318
+ availableRows
319
+ ).map((line) => truncateToWidth2(line, safeWidth));
320
+ }
321
+ handleInput(data) {
322
+ if (this.finished) return;
323
+ if (this.pasteGuard.consume(data)) {
324
+ this.editor.handleEditorInput(data);
325
+ this.tui.requestRender();
326
+ return;
327
+ }
328
+ if (this.shortcuts.matches(data, "exit")) {
329
+ this.finished = true;
330
+ this.onAction({ kind: "close" });
331
+ return;
332
+ }
333
+ if (this.options.mainUpdates && this.shortcuts.matches(data, "importMainUpdates")) {
334
+ this.finished = true;
335
+ this.onAction({ kind: "importMainUpdates", questionDraft: this.editor.getExpandedText() });
336
+ return;
337
+ }
338
+ if (this.canBringToMain && this.shortcuts.matches(data, "bringToMain")) {
339
+ this.finished = true;
340
+ this.onAction({ kind: "bringToMain", questionDraft: this.editor.getExpandedText() });
341
+ return;
342
+ }
343
+ const thinking = this.options.thinking;
344
+ if (thinking && thinking.levels.length > 1 && this.shortcuts.matches(data, "cycleThinkingLevel")) {
345
+ const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);
346
+ const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];
347
+ if (nextLevel) {
348
+ this.thinkingLevel = nextLevel;
349
+ thinking.onChange(nextLevel);
350
+ this.warning = void 0;
351
+ this.tui.requestRender();
352
+ }
353
+ return;
354
+ }
355
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
356
+ this.editor.handleEditorInput(data);
357
+ }
358
+ if (!this.finished) this.tui.requestRender();
359
+ }
360
+ invalidate() {
361
+ this.layoutRoot.invalidate();
362
+ }
363
+ dispose() {
364
+ releaseScrollbar(this.scrollView);
365
+ if (this.finished) return;
366
+ this.finished = true;
367
+ this.onAction({ kind: "close" });
368
+ }
369
+ renderFooter(width) {
370
+ return renderConversationFooter(width, this.theme, {
371
+ model: this.options.model,
372
+ thinkingLevel: this.thinkingLevel,
373
+ focus: this.workspaceFocus,
374
+ hint: this.renderHints(width),
375
+ warning: this.warning !== void 0
376
+ });
377
+ }
378
+ renderHints(width) {
379
+ const exit = this.shortcuts.label("exit");
380
+ const bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;
381
+ const bringKey = this.shortcuts.label("bringToMain");
382
+ if (this.warning) return fittingHint(width, [`${this.warning} \u2022 ${exit} exit`, `Empty \u2022 ${exit}`, exit]);
383
+ const thinking = this.options.thinking;
384
+ const cycle = thinking && thinking.levels.length > 1 && this.shortcuts.keys.cycleThinkingLevel.length ? `${this.shortcuts.label("cycleThinkingLevel")} thinking` : "";
385
+ const importKey = this.options.mainUpdates && this.shortcuts.keys.importMainUpdates.length ? this.shortcuts.label("importMainUpdates") : "";
386
+ const newMainUpdates = importKey ? this.options.mainUpdates?.() : false;
387
+ const importHint = importKey ? `${importKey} import main${newMainUpdates ? " (new)" : ""}` : "";
388
+ const compactImportHint = importKey ? `${importKey} import${newMainUpdates ? " (new)" : ""}` : "";
389
+ const submit = submitHint(this.tui, this.keybindings, "send");
390
+ const history = this.getMaxScrollOffset() > 0 ? pagingHint(this.tui, this.keybindings) : "";
391
+ const switchPane = this.workspaceFocus?.shortcutLabel ? `${this.workspaceFocus.shortcutLabel} switch` : "";
392
+ const submitKey = submit.split(" ")[0] ?? "";
393
+ return fittingHint(width, [
394
+ compactHints([
395
+ submit,
396
+ bring ? `${bringKey} bring to main` : "",
397
+ `${exit} exit`,
398
+ cycle,
399
+ history,
400
+ switchPane,
401
+ importHint
402
+ ]),
403
+ ...compactImportHint ? [
404
+ compactHints([submit, bring ? bringKey : "", exit, cycle, history, switchPane, compactImportHint]),
405
+ compactHints([submitKey, exit, compactImportHint])
406
+ ] : [],
407
+ compactHints([submit, bring ? bringKey : "", exit, cycle, history, switchPane]),
408
+ compactHints([submitKey, bring ? bringKey : "", exit, cycle, history.replace(/ history$/u, ""), switchPane]),
409
+ compactHints([submitKey, bring ? bringKey : "", exit, history.replace(/ history$/u, "")]),
410
+ compactHints([submitKey, bring ? bringKey : "", exit]),
411
+ compactHints([submitKey, exit]),
412
+ exit
413
+ ]);
414
+ }
415
+ createTranscriptComponent() {
416
+ return {
417
+ render: (width) => {
418
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
419
+ this.lastContentLineCount = lines.length;
420
+ return lines;
421
+ },
422
+ invalidate: () => {
423
+ for (const component of this.transcriptComponents) component.invalidate();
424
+ }
425
+ };
426
+ }
427
+ createFooterComponent() {
428
+ return {
429
+ render: (width) => this.renderFooter(width),
430
+ invalidate() {
431
+ }
432
+ };
433
+ }
434
+ getMaxScrollOffset() {
435
+ return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);
436
+ }
437
+ };
438
+ var BtwAnsweringView = class {
439
+ constructor(tui, theme, turns, pendingQuestion, onCancel, thinkingLevel, options = {}) {
440
+ this.tui = tui;
441
+ this.theme = theme;
442
+ this.onCancel = onCancel;
443
+ this.options = options;
444
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
445
+ this.transcriptComponents = buildTranscriptComponents(
446
+ turns,
447
+ this.theme,
448
+ pendingQuestion,
449
+ options.markdownTransformers
450
+ );
451
+ this.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;
452
+ this.loader = new BtwWorkingIndicator(
453
+ this.tui,
454
+ (text) => this.theme.fg("accent", text),
455
+ (text) => this.theme.fg("muted", text),
456
+ "Answering\u2026"
457
+ );
458
+ if (options.steering) {
459
+ const editorTheme = {
460
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
461
+ selectList: {
462
+ selectedPrefix: (text) => this.theme.fg("accent", text),
463
+ selectedText: (text) => this.theme.fg("accent", text),
464
+ description: (text) => this.theme.fg("muted", text),
465
+ scrollInfo: (text) => this.theme.fg("dim", text),
466
+ noMatch: (text) => this.theme.fg("warning", text)
467
+ }
468
+ };
469
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data), this.loader);
470
+ this.editor.onChange = () => {
471
+ this.warning = void 0;
472
+ };
473
+ this.editor.onSubmit = (text) => {
474
+ const question = text.trim();
475
+ if (!question) {
476
+ this.warning = "Question cannot be empty";
477
+ return;
478
+ }
479
+ options.steering?.onSubmit(question);
480
+ this.warning = void 0;
481
+ };
482
+ }
483
+ const transcript = this.createTranscriptComponent();
484
+ this.scrollView = new PreservingScrollView(transcript, {
485
+ follow: "end",
486
+ primary: true,
487
+ scrollbar: "auto",
488
+ scrollbarTrackStyle: (text) => this.theme.fg("scrollbarTrack", text),
489
+ scrollbarThumbStyle: (text) => this.theme.fg("scrollbarThumb", text)
490
+ });
491
+ const dock = new VStack([
492
+ {
493
+ component: this.createSteeringComponent(),
494
+ basis: "auto",
495
+ shrink: 1,
496
+ minSize: 0,
497
+ maxSize: MAX_STEERING_DISPLAY_LINES
498
+ },
499
+ { component: this.editor ?? this.createWorkingComponent(), basis: "auto", shrink: 1, minSize: 1 },
500
+ { component: this.createFooterComponent(), basis: "auto", shrink: 1, minSize: 0 }
501
+ ]);
502
+ this.layoutRoot = new VStack([
503
+ { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
504
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 }
505
+ ]);
506
+ }
507
+ tui;
508
+ theme;
509
+ onCancel;
510
+ options;
511
+ workspaceFocus;
512
+ get keybindings() {
513
+ return getBtwKeybindings(this.tui, this.options.keybindings ?? this.options.steering?.thinking?.keybindings);
514
+ }
515
+ setWorkspaceFocus(pane, shortcutLabel) {
516
+ this.workspaceFocus = { pane, shortcutLabel: shortcutLabel ? sanitizeSingleLine(shortcutLabel) : void 0 };
517
+ this.tui.requestRender();
518
+ }
519
+ shortcuts;
520
+ pasteGuard = new BtwPasteGuard();
521
+ transcriptComponents;
522
+ loader;
523
+ editor;
524
+ controller = new AbortController();
525
+ scrollView;
526
+ layoutRoot;
527
+ lastContentLineCount = 0;
528
+ warning;
529
+ finished = false;
530
+ isFocused = false;
531
+ thinkingLevel;
532
+ get focused() {
533
+ return this.isFocused;
534
+ }
535
+ set focused(value) {
536
+ this.isFocused = value;
537
+ if (this.editor) this.editor.focused = value;
538
+ }
539
+ get signal() {
540
+ return this.controller.signal;
541
+ }
542
+ getFullscreenLayout() {
543
+ return this.layoutRoot;
544
+ }
545
+ getPrimaryScrollView() {
546
+ return this.scrollView;
547
+ }
548
+ render(width) {
549
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
550
+ const safeWidth = Math.max(1, width);
551
+ const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
552
+ const editorLines = this.editor?.render(safeWidth) ?? this.renderWorking(safeWidth);
553
+ const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
554
+ this.lastContentLineCount = contentLines.length;
555
+ const footerLines = this.renderFooter(safeWidth);
556
+ const steeringCapacity = Math.max(0, availableRows - editorLines.length - footerLines.length);
557
+ const steeringLines = renderSteeringLines(
558
+ this.options.steering?.questions ?? [],
559
+ safeWidth,
560
+ this.theme,
561
+ Math.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity)
562
+ );
563
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - footerLines.length - steeringLines.length);
564
+ this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
565
+ return fitComposerLayout(
566
+ contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
567
+ this.renderFooter(safeWidth),
568
+ editorLines,
569
+ availableRows,
570
+ steeringLines
571
+ ).map((line) => truncateToWidth2(line, safeWidth));
572
+ }
573
+ handleInput(data) {
574
+ if (this.finished) return;
575
+ if (this.pasteGuard.consume(data)) {
576
+ this.editor?.handleEditorInput(data);
577
+ this.tui.requestRender();
578
+ return;
579
+ }
580
+ if (this.shortcuts.matches(data, "exit")) {
581
+ this.finished = true;
582
+ this.loader.stop();
583
+ this.controller.abort();
584
+ this.onCancel();
585
+ return;
586
+ }
587
+ const thinking = this.options.steering?.thinking;
588
+ if (thinking && thinking.levels.length > 1 && this.shortcuts.matches(data, "cycleThinkingLevel")) {
589
+ const currentIndex = thinking.levels.indexOf(this.thinkingLevel ?? thinking.level);
590
+ const nextLevel = thinking.levels[(currentIndex + 1) % thinking.levels.length];
591
+ if (nextLevel) {
592
+ this.thinkingLevel = nextLevel;
593
+ thinking.onChange(nextLevel);
594
+ this.warning = void 0;
595
+ this.tui.requestRender();
596
+ }
597
+ return;
598
+ }
599
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
600
+ this.editor?.handleEditorInput(data);
601
+ }
602
+ this.tui.requestRender();
603
+ }
604
+ invalidate() {
605
+ this.layoutRoot.invalidate();
606
+ }
607
+ finish() {
608
+ this.finished = true;
609
+ releaseScrollbar(this.scrollView);
610
+ this.loader.stop();
611
+ }
612
+ dispose() {
613
+ releaseScrollbar(this.scrollView);
614
+ if (this.finished) {
615
+ this.loader.stop();
616
+ this.controller.abort();
617
+ return;
618
+ }
619
+ this.finished = true;
620
+ this.loader.stop();
621
+ this.controller.abort();
622
+ this.onCancel();
623
+ }
624
+ renderFooter(width) {
625
+ return renderConversationFooter(width, this.theme, {
626
+ model: this.options.model,
627
+ thinkingLevel: this.thinkingLevel,
628
+ focus: this.workspaceFocus,
629
+ hint: this.renderHints(width),
630
+ warning: this.warning !== void 0
631
+ });
632
+ }
633
+ renderHints(width) {
634
+ const exit = this.shortcuts.label("exit");
635
+ if (this.warning) return fittingHint(width, [`${this.warning} \u2022 ${exit} cancel`, `Empty \u2022 ${exit}`, exit]);
636
+ const submit = this.editor ? submitHint(this.tui, this.keybindings, "queue next") : "";
637
+ const thinking = this.options.steering?.thinking;
638
+ const cycle = thinking && thinking.levels.length > 1 && this.shortcuts.keys.cycleThinkingLevel.length ? `${this.shortcuts.label("cycleThinkingLevel")} thinking` : "";
639
+ const history = this.getMaxScrollOffset() > 0 ? pagingHint(this.tui, this.keybindings) : "";
640
+ const switchPane = this.workspaceFocus?.shortcutLabel ? `${this.workspaceFocus.shortcutLabel} switch` : "";
641
+ const submitKey = submit.split(" ")[0] ?? "";
642
+ return fittingHint(width, [
643
+ compactHints([submit, `${exit} cancel`, cycle, history, switchPane]),
644
+ compactHints([submit, exit, cycle, history, switchPane]),
645
+ compactHints([submitKey, exit, cycle, history.replace(/ history$/u, ""), switchPane]),
646
+ compactHints([submitKey, exit, history.replace(/ history$/u, "")]),
647
+ compactHints([submitKey, exit]),
648
+ exit
649
+ ]);
650
+ }
651
+ renderWorking(width) {
652
+ return [this.loader.renderInBorder(Math.max(0, width))];
653
+ }
654
+ createWorkingComponent() {
655
+ return { render: (width) => this.renderWorking(width), invalidate: () => this.loader.invalidate() };
656
+ }
657
+ createTranscriptComponent() {
658
+ return {
659
+ render: (width) => {
660
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
661
+ this.lastContentLineCount = lines.length;
662
+ return lines;
663
+ },
664
+ invalidate: () => {
665
+ for (const component of this.transcriptComponents) component.invalidate();
666
+ }
667
+ };
668
+ }
669
+ createSteeringComponent() {
670
+ return {
671
+ render: (width) => renderSteeringLines(this.options.steering?.questions ?? [], width, this.theme, MAX_STEERING_DISPLAY_LINES),
672
+ invalidate() {
673
+ }
674
+ };
675
+ }
676
+ createFooterComponent() {
677
+ return {
678
+ render: (width) => this.renderFooter(width),
679
+ invalidate: () => this.loader.invalidate()
680
+ };
681
+ }
682
+ getMaxScrollOffset() {
683
+ return Math.max(0, this.lastContentLineCount - this.scrollView.viewportHeight);
684
+ }
685
+ };
686
+ function formatSideTranscript(turns) {
687
+ return turns.map((turn) => {
688
+ if (turn.kind === "mainContext") return `Main context update
689
+
690
+ ${escapeTerminalControls(turn.snapshot.text)}`;
691
+ const question = escapeTerminalControls(turn.question);
692
+ const rawAnswer = escapeTerminalControls(turn.answer);
693
+ const answer = turn.kind === "error" ? `Error: ${rawAnswer}` : rawAnswer;
694
+ return `${question}
695
+
696
+ ${answer}`;
697
+ }).join("\n\n");
698
+ }
699
+ function buildTranscriptComponents(turns, theme, pendingQuestion, markdownTransformers = []) {
700
+ const components = turns.flatMap((turn, index) => {
701
+ const preceding = index > 0 ? [new Spacer(1)] : [];
702
+ if (turn.kind === "mainContext") {
703
+ const update = {
704
+ render: (width) => new Text(
705
+ theme.fg("muted", `Main context update
706
+
707
+ ${escapeTerminalControls(turn.snapshot.text)}`),
708
+ 1,
709
+ 0
710
+ ).render(width),
711
+ invalidate() {
712
+ }
713
+ };
714
+ return [...preceding, update];
715
+ }
716
+ const question = new UserMessageComponent(
717
+ escapeTerminalControls(turn.question),
718
+ getMarkdownTheme(),
719
+ 1,
720
+ markdownTransformers
721
+ );
722
+ if (turn.kind === "error") {
723
+ const error = {
724
+ render: (width) => new Text(theme.fg("error", `Error: ${escapeTerminalControls(turn.answer)}`), 1, 0).render(width),
725
+ invalidate() {
726
+ }
727
+ };
728
+ return [...preceding, question, new Spacer(1), error];
729
+ }
730
+ const response = {
731
+ ...turn.response,
732
+ content: [{ type: "text", text: escapeTerminalControls(turn.answer) }],
733
+ stopReason: "stop",
734
+ errorMessage: void 0
735
+ };
736
+ return [
737
+ ...preceding,
738
+ question,
739
+ new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers)
740
+ ];
741
+ });
742
+ if (pendingQuestion) {
743
+ if (components.length > 0) components.push(new Spacer(1));
744
+ components.push(
745
+ new UserMessageComponent(escapeTerminalControls(pendingQuestion), getMarkdownTheme(), 1, markdownTransformers)
746
+ );
747
+ }
748
+ return components;
749
+ }
750
+ function renderTranscriptLines(components, width, native = false) {
751
+ return components.flatMap((component) => {
752
+ const lines = component.render(width);
753
+ const trusted = component instanceof UserMessageComponent || component instanceof AssistantMessageComponent;
754
+ return lines.map((line, index) => {
755
+ let prefix = "";
756
+ if (native && trusted) {
757
+ if (index === 0 && line.startsWith(OSC133_MARKERS[0] ?? "")) prefix += OSC133_MARKERS[0];
758
+ const end = `${OSC133_MARKERS[1]}${OSC133_MARKERS[2]}`;
759
+ if (index === lines.length - 1 && line.slice(prefix.length).startsWith(end)) prefix += end;
760
+ }
761
+ return prefix + truncateToWidth2(stripShellIntegrationMarkers(line), Math.max(0, width), "");
762
+ });
763
+ });
764
+ }
765
+ function fitComposerLayout(contentLines, footerLines, editorLines, availableRows, statusLines = []) {
766
+ if (availableRows <= 0) return [];
767
+ const editorBudget = Math.min(editorLines.length, availableRows);
768
+ const footerBudget = Math.min(footerLines.length, availableRows - editorBudget);
769
+ const statusBudget = Math.min(statusLines.length, availableRows - editorBudget - footerBudget);
770
+ const transcriptBudget = availableRows - editorBudget - footerBudget - statusBudget;
771
+ return [
772
+ ...contentLines.slice(0, transcriptBudget),
773
+ ...statusLines.slice(0, statusBudget),
774
+ ...fitEditorLines(editorLines, editorBudget),
775
+ ...footerLines.slice(0, footerBudget)
776
+ ];
777
+ }
778
+ function fitEditorLines(editorLines, budget) {
779
+ if (budget <= 0) return [];
780
+ if (editorLines.length <= budget) return editorLines;
781
+ const cursorIndex = editorLines.findIndex((line) => line.includes(CURSOR_MARKER));
782
+ if (cursorIndex < 0) return editorLines.slice(-budget);
783
+ const start = Math.min(cursorIndex, editorLines.length - budget);
784
+ return editorLines.slice(start, start + budget);
785
+ }
786
+ function renderSteeringLines(questions, width, theme, maxLines) {
787
+ if (questions.length === 0 || maxLines <= 0) return [];
788
+ const formatQuestion = (question) => sanitizeSingleLine(question) || "(non-printing message)";
789
+ if (maxLines === 1 && questions.length > 1) {
790
+ return [
791
+ truncateToWidth2(
792
+ theme.fg("dim", ` Steering next (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`),
793
+ width
794
+ )
795
+ ];
796
+ }
797
+ const hasOverflow = questions.length > maxLines;
798
+ const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;
799
+ const lines = questions.slice(0, questionLimit).map((question) => truncateToWidth2(theme.fg("dim", ` Steering next: ${formatQuestion(question)}`), width));
800
+ if (hasOverflow) {
801
+ lines.push(truncateToWidth2(theme.fg("dim", ` Steering next: \u2026 +${questions.length - questionLimit} more`), width));
802
+ }
803
+ return lines;
804
+ }
805
+ function stripShellIntegrationMarkers(line) {
806
+ return line.replace(/\u001b\]133;[^\u0007\u001b]*(?:\u0007|\u001b\\)/gu, "");
807
+ }
808
+ function escapeTerminalControls(text) {
809
+ return [...text].map((character) => {
810
+ if (character === "\n") return character;
811
+ if (character === " ") return " ";
812
+ const code = character.charCodeAt(0);
813
+ if (code <= 31 || code >= 127 && code <= 159) {
814
+ return `\\x${code.toString(16).padStart(2, "0")}`;
815
+ }
816
+ return character;
817
+ }).join("");
818
+ }
819
+ export {
820
+ BtwAnsweringView,
821
+ BtwTranscriptPager,
822
+ formatSideTranscript
823
+ };
824
+ //# sourceMappingURL=transcript-pager-D7XAJC65.ts.map